-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwechat-oauth-service.ts
More file actions
277 lines (235 loc) · 8.22 KB
/
Copy pathwechat-oauth-service.ts
File metadata and controls
277 lines (235 loc) · 8.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import { createHmac, timingSafeEqual } from "node:crypto";
import { AppError } from "../core/errors";
const WECHAT_AUTHORIZE_URL = "https://open.weixin.qq.com/connect/oauth2/authorize";
const WECHAT_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
const WECHAT_USERINFO_URL = "https://api.weixin.qq.com/sns/userinfo";
const STATE_TTL_MS = 10 * 60 * 1_000;
const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1_000;
interface WeChatOAuthServiceOptions {
appId?: string;
appSecret?: string;
publicBaseUrl?: string;
oauthScope?: "snsapi_base" | "snsapi_userinfo";
sessionSecret?: string;
}
interface SignedStatePayload {
shareSlug: string;
issuedAt: number;
}
interface SignedIdentitySessionPayload {
platformUserId: string;
displayName: string;
issuedAt: number;
expiresAt: number;
}
interface WeChatAccessTokenResponse {
access_token?: string;
expires_in?: number;
refresh_token?: string;
openid?: string;
scope?: string;
unionid?: string;
errcode?: number;
errmsg?: string;
}
interface WeChatUserInfoResponse {
openid?: string;
nickname?: string;
unionid?: string;
errcode?: number;
errmsg?: string;
}
export interface WeChatIdentityProfile {
platformUserId: string;
displayName: string;
}
export class WeChatOAuthService {
constructor(private readonly options: WeChatOAuthServiceOptions) {}
isConfigured(): boolean {
return Boolean(
this.options.appId &&
this.options.appSecret &&
this.options.publicBaseUrl,
);
}
buildAuthorizationUrl(shareSlug: string): string {
this.assertConfigured();
const url = new URL(WECHAT_AUTHORIZE_URL);
url.searchParams.set("appid", this.options.appId as string);
url.searchParams.set("redirect_uri", this.getRedirectUri());
url.searchParams.set("response_type", "code");
url.searchParams.set("scope", this.options.oauthScope ?? "snsapi_userinfo");
url.searchParams.set("state", this.signPayload<SignedStatePayload>({
shareSlug,
issuedAt: Date.now(),
}));
return `${url.toString()}#wechat_redirect`;
}
verifyState(state: string): SignedStatePayload {
this.assertConfigured();
const payload = this.verifyPayload<SignedStatePayload>(
state,
"The WeChat sign-in link is invalid or expired.",
);
if (
typeof payload.shareSlug !== "string" ||
typeof payload.issuedAt !== "number" ||
Date.now() - payload.issuedAt > STATE_TTL_MS
) {
throw new AppError("WeChat OAuth state payload was invalid.", {
statusCode: 400,
userMessage: "The WeChat sign-in link is invalid or expired.",
});
}
return payload;
}
async exchangeCodeForIdentity(code: string): Promise<WeChatIdentityProfile> {
this.assertConfigured();
const tokenUrl = new URL(WECHAT_ACCESS_TOKEN_URL);
tokenUrl.searchParams.set("appid", this.options.appId as string);
tokenUrl.searchParams.set("secret", this.options.appSecret as string);
tokenUrl.searchParams.set("code", code);
tokenUrl.searchParams.set("grant_type", "authorization_code");
const tokenResponse = await fetch(tokenUrl.toString());
if (!tokenResponse.ok) {
throw new AppError("WeChat OAuth token exchange failed.", {
statusCode: 502,
userMessage: "WeChat sign-in failed. Try the join link again.",
});
}
const tokenPayload = (await tokenResponse.json()) as WeChatAccessTokenResponse;
if (tokenPayload.errcode || !tokenPayload.openid) {
throw new AppError(`WeChat OAuth token exchange failed: ${tokenPayload.errmsg ?? "unknown error"}.`, {
statusCode: 502,
userMessage: "WeChat sign-in failed. Try the join link again.",
});
}
const platformUserId = tokenPayload.unionid ?? tokenPayload.openid;
const displayName = await this.resolveDisplayName(tokenPayload);
return {
platformUserId,
displayName,
};
}
createIdentitySession(identity: WeChatIdentityProfile): string {
this.assertConfigured();
return this.signPayload<SignedIdentitySessionPayload>({
platformUserId: identity.platformUserId,
displayName: identity.displayName,
issuedAt: Date.now(),
expiresAt: Date.now() + SESSION_TTL_MS,
});
}
verifyIdentitySession(token: string): WeChatIdentityProfile {
this.assertConfigured();
const payload = this.verifyPayload<SignedIdentitySessionPayload>(
token,
"WeChat sign-in has expired. Open the join link again in WeChat.",
);
if (
typeof payload.platformUserId !== "string" ||
typeof payload.displayName !== "string" ||
typeof payload.issuedAt !== "number" ||
typeof payload.expiresAt !== "number" ||
Date.now() > payload.expiresAt
) {
throw new AppError("WeChat identity session payload was invalid.", {
statusCode: 400,
userMessage: "WeChat sign-in has expired. Open the join link again in WeChat.",
});
}
return {
platformUserId: payload.platformUserId,
displayName: payload.displayName,
};
}
private async resolveDisplayName(tokenPayload: WeChatAccessTokenResponse): Promise<string> {
const defaultLabel = `WeChat User ${tokenPayload.openid?.slice(-4) ?? ""}`.trim();
const scope = tokenPayload.scope ?? "";
if (
!scope.includes("snsapi_userinfo") ||
!tokenPayload.access_token ||
!tokenPayload.openid
) {
return defaultLabel;
}
const userInfoUrl = new URL(WECHAT_USERINFO_URL);
userInfoUrl.searchParams.set("access_token", tokenPayload.access_token);
userInfoUrl.searchParams.set("openid", tokenPayload.openid);
userInfoUrl.searchParams.set("lang", "en_US");
const userInfoResponse = await fetch(userInfoUrl.toString());
if (!userInfoResponse.ok) {
return defaultLabel;
}
const userInfo = (await userInfoResponse.json()) as WeChatUserInfoResponse;
if (userInfo.errcode || !userInfo.nickname) {
return defaultLabel;
}
return userInfo.nickname;
}
private signPayload<T extends object>(payload: T): string {
const encodedPayload = Buffer.from(JSON.stringify(payload), "utf8").toString("base64url");
return `${encodedPayload}.${this.createSignature(encodedPayload).toString("base64url")}`;
}
private verifyPayload<T>(value: string, userMessage: string): T {
const [encodedPayload, signature] = value.split(".");
if (!encodedPayload || !signature) {
throw new AppError("Signed payload was malformed.", {
statusCode: 400,
userMessage,
});
}
const expectedSignature = this.createSignature(encodedPayload);
const actualSignature = this.decodeSignature(signature);
if (
expectedSignature.length !== actualSignature.length ||
!timingSafeEqual(expectedSignature, actualSignature)
) {
throw new AppError("Signed payload signature did not match.", {
statusCode: 400,
userMessage,
});
}
try {
return JSON.parse(Buffer.from(encodedPayload, "base64url").toString("utf8")) as T;
} catch {
throw new AppError("Signed payload could not be parsed.", {
statusCode: 400,
userMessage,
});
}
}
private createSignature(encodedPayload: string): Buffer {
return createHmac("sha256", this.getSigningSecret())
.update(encodedPayload)
.digest();
}
private decodeSignature(signature: string): Buffer {
try {
return Buffer.from(signature, "base64url");
} catch {
throw new AppError("WeChat OAuth signature could not be decoded.", {
statusCode: 400,
userMessage: "The WeChat sign-in link is invalid or expired.",
});
}
}
private getRedirectUri(): string {
return new URL("/auth/wechat/callback", ensureTrailingSlash(this.options.publicBaseUrl as string)).toString();
}
private getSigningSecret(): string {
return this.options.sessionSecret ?? (this.options.appSecret as string);
}
private assertConfigured(): void {
if (this.isConfigured()) {
return;
}
throw new AppError("WeChat OAuth service is missing required configuration.", {
statusCode: 500,
userMessage: "WeChat sign-in is not configured on this server yet.",
});
}
}
function ensureTrailingSlash(value: string): string {
return value.endsWith("/") ? value : `${value}/`;
}