-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.ts
428 lines (340 loc) · 10.4 KB
/
index.ts
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/**
* Welcome to Cloudflare Workers! This is your first worker.
*
* - Run `npm run dev` in your terminal to start a development server
* - Open a browser tab at http://localhost:8787/ to see your worker in action
* - Run `npm run deploy` to publish your worker
*
* Bind resources to your worker in `wrangler.toml`. After adding bindings, a type definition for the
* `Env` object can be regenerated with `npm run cf-typegen`.
*
* Learn more at https://developers.cloudflare.com/workers/
*/
import { AutoRouter, cors, error, html, IRequest } from 'itty-router';
import {
DeleteCommentIDParam,
GetCommentBody,
GetCommentRespBody,
JWTPayload,
OAuthState,
PatchCommentBody,
PatchCommentIDBody,
PatchCommentIDParam,
PostCommentBody,
PutCommitHashBody,
ResponseBody,
} from './types';
import { deleteComment, getComment, getUserOfComment, modifyComment, postComment, registerUser } from './db';
import { setCommitHash, compareCommitHash, modifyComments, renameComments, sendCommentUpdateToTelegram } from './administration';
import { matchCommentCache, purgeAllCommentCache, purgeCommentCache, putCommentCache } from './cache';
import { signJWT } from './utils';
import { getAccessToken, getUserInfo, getUserTeamMembership } from './oauth';
import {
isAdmin,
isSameCommenter,
validateAdministratorSecret,
validateAndDecodeAuthorizationToken,
validateAndDecodePath,
validateComment,
validateCommitHash,
validateDiff,
validateOffset,
validatePath,
} from './validation';
const { preflight, corsify } = cors({
origin: [
'https://oi-wiki.org',
'http://oi-wiki.com',
'https://oi-wiki.net',
'https://oi-wiki.wiki',
'https://oi-wiki.win',
'https://oi-wiki.xyz',
'https://oiwiki.moe',
'https://oiwiki.net',
'https://oiwiki.org',
'https://oiwiki.wiki',
'https://oiwiki.win',
'https://oiwiki.com',
'https://oi.wiki',
],
allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
allowHeaders: ['Authorization', 'Content-Type'],
maxAge: 86400,
});
const router = AutoRouter<IRequest, [Env, ExecutionContext]>({
before: [preflight],
finally: [corsify],
});
router.get('/', async () => {
return html`<h1>OI-Wiki feedback sys backend</h1>
See <a href="https://github.com/OI-wiki/feedback-sys">GitHub</a> for more information.`;
});
router.post('/comment/:path', async (req, env, ctx) => {
const params = req.params as GetCommentBody;
if (params === undefined) {
return error(400, 'Invalid request body');
}
const path = validateAndDecodePath(params.path);
if (path === null) {
return error(400, 'Invalid path');
}
params.path = path;
const body = await req.json<PostCommentBody>();
if (
body == undefined ||
body.offset == undefined ||
body.comment == undefined ||
body.offset.start == undefined ||
body.offset.end == undefined ||
body.commit_hash == undefined
) {
return error(400, 'Invalid request body');
}
if (!validateOffset(body.offset)) {
return error(400, 'Invalid offset');
}
if (!validateComment(body.comment)) {
return error(400, 'Invalid comment');
}
if (!(await compareCommitHash(env, body.commit_hash))) {
return error(409, 'Commit hash mismatch, usually due to outdated cache or running CI/CD, please retry after a few minutes');
}
const token = await validateAndDecodeAuthorizationToken(env, req);
if (token === null) {
return error(401, 'Unauthorized');
}
const data = {
path: params.path,
offset: body.offset,
commenter: {
oauth_provider: token.provider,
oauth_user_id: token.id + '',
},
comment: body.comment,
};
const commentId = await postComment(env, data);
ctx.waitUntil(sendCommentUpdateToTelegram(env, data, token.name, commentId));
const cache = caches.default;
ctx.waitUntil(purgeCommentCache(env, cache, new URL(req.url).origin, params.path));
return {
status: 200,
} satisfies ResponseBody;
});
router.delete('/comment/:path/id/:id', async (req, env, ctx) => {
const params = req.params as DeleteCommentIDParam;
if (params == undefined || params.id == undefined) {
return error(400, 'Invalid request body');
}
const path = validateAndDecodePath(params.path);
if (path === null) {
return error(400, 'Invalid path');
}
params.path = path;
const token = await validateAndDecodeAuthorizationToken(env, req);
if (token === null) {
return error(401, 'Unauthorized');
}
const user = await getUserOfComment(env, parseInt(params.id));
if (!isSameCommenter(user, token) && !isAdmin(token)) {
return error(403, 'Forbidden');
}
await deleteComment(env, parseInt(params.id));
const cache = caches.default;
ctx.waitUntil(purgeCommentCache(env, cache, new URL(req.url).origin, params.path));
return {
status: 200,
} satisfies ResponseBody;
});
router.patch('/comment/:path/id/:id', async (req, env, ctx) => {
const params = req.params as PatchCommentIDParam;
if (params == undefined || params.id == undefined) {
return error(400, 'Invalid request body');
}
const path = validateAndDecodePath(params.path);
if (path === null) {
return error(400, 'Invalid path');
}
params.path = path;
const body = await req.json<PatchCommentIDBody>();
if (body == undefined) {
return error(400, 'Invalid request body');
}
if (!validateComment(body.comment)) {
return error(400, 'Invalid comment');
}
const token = await validateAndDecodeAuthorizationToken(env, req);
if (token === null) {
return error(401, 'Unauthorized');
}
const user = await getUserOfComment(env, parseInt(params.id));
if (!isSameCommenter(user, token) && !isAdmin(token)) {
return error(403, 'Forbidden');
}
await modifyComment(env, parseInt(params.id), body.comment);
const cache = caches.default;
ctx.waitUntil(purgeCommentCache(env, cache, new URL(req.url).origin, params.path));
return {
status: 200,
} satisfies ResponseBody;
});
router.get('/comment/:path', async (req, env, ctx) => {
const params = req.params as GetCommentBody;
if (params == undefined) {
return error(400, 'Invalid request body');
}
const path = validateAndDecodePath(params.path);
if (path === null) {
return error(400, 'Invalid path');
}
params.path = path;
const cache = caches.default;
let resp = await matchCommentCache(env, cache, new URL(req.url).origin, params.path);
if (!resp) {
resp = new Response(
JSON.stringify({
status: 200,
data: await getComment(env, params),
} satisfies ResponseBody<GetCommentRespBody>),
{
headers: {
'Content-Type': 'application/json',
},
},
);
ctx.waitUntil(putCommentCache(env, cache, new URL(req.url).origin, params.path, resp.clone()));
}
return resp;
});
router.patch('/comment/:path', async (req, env, ctx) => {
const params = req.params as GetCommentBody;
if (params == undefined) {
return error(400, 'Invalid request body');
}
const path = validateAndDecodePath(params.path);
if (path === null) {
return error(400, 'Invalid path');
}
params.path = path;
const body = await req.json<PatchCommentBody>();
if (body == undefined) {
return error(400, 'Invalid request body');
}
if (body.type != 'renamed' && body.type != 'modified') {
return error(400, 'Invalid request body');
}
if (body.type === 'renamed' && !validatePath(body.to)) {
return error(400, 'Invalid request body');
}
if (body.type === 'modified' && !validateDiff(body.diff)) {
return error(400, 'Invalid request body');
}
if (!validateAdministratorSecret(env, req)) {
return error(401, 'Unauthorized');
}
const cache = caches.default;
ctx.waitUntil(purgeCommentCache(env, cache, new URL(req.url).origin, params.path));
if (body.type === 'renamed') {
await renameComments(env, params.path, body.to);
} else if (body.type === 'modified') {
await modifyComments(env, params.path, body.diff);
}
return {
status: 200,
} satisfies ResponseBody;
});
router.get('/meta/github-app', async (req, env, ctx) => {
return {
status: 200,
data: {
client_id: env.GITHUB_APP_CLIENT_ID,
},
} satisfies ResponseBody;
});
router.get('/oauth/callback', async (req, env, ctx) => {
if (req.query['setup_action'] === 'install') {
return {
status: 200,
} satisfies ResponseBody;
}
const rawState = req.query['state'] as string | undefined;
if (rawState == undefined) {
return error(400, 'Invalid request');
}
const state: OAuthState = JSON.parse(decodeURIComponent(rawState as string));
if (state == undefined || state.redirect == undefined) {
return error(400, 'Invalid request');
}
const err = req.query['error'] as string | undefined;
if (err === 'access_denied') {
return new Response(null, {
status: 302,
headers: {
Location: state.redirect,
},
});
}
if (err != undefined) {
return error(400, `OAuth error (${err}): ${req.query['error_description']}`);
}
const code = req.query['code'] as string | undefined;
if (code == undefined) {
return error(400, 'Invalid request');
}
const token = await getAccessToken(env, code);
const userInfo = await getUserInfo(token);
const [org, team] = env.GITHUB_ORG_ADMINISTRATOR_TEAM.split('/');
const membership = await getUserTeamMembership(token, userInfo.login, org, team);
const jwt = await signJWT(
{
provider: 'github',
id: userInfo.id + '',
name: userInfo.name ?? userInfo.login,
isAdmin: membership?.state === 'active',
} satisfies JWTPayload,
env.OAUTH_JWT_SECRET,
);
await registerUser(
env,
userInfo.name ?? userInfo.login,
'github',
userInfo.id + '',
userInfo.avatar_url,
`https://github.com/${userInfo.login}`,
);
const redirectUrl = new URL(state.redirect);
redirectUrl.searchParams.append('oauth_token', jwt);
return new Response(null, {
status: 302,
headers: {
// 这样设计而不是 Set-Cookie 是因为跨站 Set-Cookie 不好做
Location: redirectUrl.toString(),
},
});
});
router.put('/meta/commithash', async (req, env, ctx) => {
const body = await req.json<PutCommitHashBody>();
if (body == undefined) {
return error(400, 'Invalid request body');
}
if (!validateCommitHash(body.commit_hash)) {
return error(400, 'Invalid commit hash');
}
if (!validateAdministratorSecret(env, req)) {
return error(401, 'Unauthorized');
}
await setCommitHash(env, body.commit_hash);
return {
status: 200,
} satisfies ResponseBody;
});
router.delete('/cache', async (req, env, ctx) => {
if (!validateAdministratorSecret(env, req)) {
return error(401, 'Unauthorized');
}
const cache = caches.default;
await purgeAllCommentCache(env, cache, new URL(req.url).origin);
return {
status: 200,
} satisfies ResponseBody;
});
export default { ...router } satisfies ExportedHandler<Env>;