返回 CodeWhale
route.ts
根目录 / web / app / api / admin / post / route.ts
1 import { revalidatePath } from "next/cache";
2 import { NextResponse } from "next/server";
3 import { BodyReadError, readBoundedBody } from "@/lib/bounded-body";
4 import {
5 approveDigestRecord,
6 claimDraft,
7 clearDraftResolution,
8 clearPostOutcomeUnknown,
9 getPostOutcomeUnknown,
10 markPostOutcomeUnknown,
11 deleteDigestRecord,
12 deleteDraft,
13 getAgentEnv,
14 getDraft,
15 getDraftResolution,
16 markDraftResolved,
17 parseDraftKey,
18 releaseDraftClaim,
19 reviewedBodyHash,
20 validateSession,
21 type CommunityAgentEnv,
22 type DraftClaimResult,
23 } from "@/lib/community-agent";
24
25 export const dynamic = "force-dynamic";
26
27 async function checkAuth(req: Request, env: CommunityAgentEnv): Promise<{ ok: boolean; status?: number; error?: string }> {
28 if (!env.MAINTAINER_TOKEN) {
29 return { ok: false, status: 503, error: "not configured" };
30 }
31
32 const cookieHeader = req.headers.get("cookie") ?? "";
33 let sid: string | undefined;
34 for (const c of cookieHeader.split(";")) {
35 const [name, ...rest] = c.trim().split("=");
36 if (name === "mt_sid") {
37 sid = rest.join("=");
38 break;
39 }
40 }
41
42 if (!sid || !(await validateSession(env.CURATED_KV, sid, env.MAINTAINER_TOKEN))) {
43 return { ok: false, status: 401, error: "unauthorized" };
44 }
45 return { ok: true };
46 }
47
48 const ALLOWED_ORIGINS = new Set(["https://codewhale.net", "https://www.codewhale.net"]);
49 const MAX_BODY_BYTES = 65_536;
50
51 /** Refresh the ISR copy of /digest after its published set changes. */
52 function revalidateDigestPage() {
53 try {
54 revalidatePath("/[locale]/digest", "page");
55 } catch (e) {
56 // The page still refreshes on its hourly revalidate.
57 console.error("digest revalidation failed", e);
58 }
59 }
60
61 /**
62 * A GitHub 4xx other than 408/429 means the post was not created, so the
63 * claim can be released. A 5xx, 408 or 429 can come back after GitHub already
64 * created the comment or issue, so its outcome is unknown.
65 */
66 function githubDefinitelyRejected(status: number): boolean {
67 return status >= 400 && status < 500 && status !== 408 && status !== 429;
68 }
69
70 /** The answer for a claim that was not taken. */
71 function claimRefused(result: Exclude<DraftClaimResult, { ok: true }>) {
72 if (result.reason === "unconfirmed") {
73 return NextResponse.json({ error: "could not confirm the draft claim; nothing was done, retry" }, { status: 503 });
74 }
75 if (result.reason === "resolved") {
76 return NextResponse.json({ error: `draft already ${result.resolution.state}` }, { status: 409 });
77 }
78 return NextResponse.json(
79 { error: "another request is acting on this draft; check GitHub, then retry in a minute" },
80 { status: 409 }
81 );
82 }
83
84 const discarded = () => NextResponse.json({ ok: true, action: "discarded" });
85
86 export async function POST(req: Request) {
87 const env = await getAgentEnv();
88
89 const origin = req.headers.get("origin");
90 if (origin && !ALLOWED_ORIGINS.has(origin)) {
91 return NextResponse.json({ error: "forbidden origin" }, { status: 403 });
92 }
93
94 const auth = await checkAuth(req, env);
95 if (!auth.ok) {
96 return NextResponse.json(
97 { error: auth.error ?? "unauthorized" },
98 { status: auth.status ?? 401, headers: { "Cache-Control": "no-store" } }
99 );
100 }
101
102 if (!req.headers.get("content-type")?.toLowerCase().startsWith("application/json")) {
103 return NextResponse.json({ error: "content-type must be application/json" }, { status: 415 });
104 }
105
106 // Count the real body bytes (Content-Length is only an early rejection)
107 // and answer malformed JSON with a 400 instead of an unhandled 500.
108 let body: unknown;
109 try {
110 const bytes = await readBoundedBody(req, MAX_BODY_BYTES);
111 body = JSON.parse(new TextDecoder().decode(bytes));
112 } catch (e) {
113 if (e instanceof BodyReadError) {
114 return NextResponse.json({ error: e.message }, { status: e.status });
115 }
116 return NextResponse.json({ error: "invalid JSON body" }, { status: 400 });
117 }
118 if (!body || typeof body !== "object" || Array.isArray(body)) {
119 return NextResponse.json({ error: "invalid JSON body" }, { status: 400 });
120 }
121 const { action, draftKey, editedBody, lang, reviewedSha256 } = body as {
122 action?: unknown;
123 draftKey?: unknown;
124 editedBody?: unknown;
125 lang?: unknown;
126 reviewedSha256?: unknown;
127 };
128
129 if (action !== "post" && action !== "discard") {
130 return NextResponse.json({ error: "unknown action" }, { status: 400 });
131 }
132 if (typeof draftKey !== "string" || !draftKey || draftKey.length > 256) {
133 return NextResponse.json({ error: "missing or invalid draftKey" }, { status: 400 });
134 }
135 const parsedKey = parseDraftKey(draftKey);
136 if (!parsedKey) {
137 return NextResponse.json({ error: "invalid draftKey namespace" }, { status: 400 });
138 }
139 if (editedBody !== undefined && typeof editedBody !== "string") {
140 return NextResponse.json({ error: "invalid editedBody" }, { status: 400 });
141 }
142 if (editedBody !== undefined && editedBody.length > MAX_BODY_BYTES) {
143 return NextResponse.json({ error: "editedBody too long" }, { status: 413 });
144 }
145 if (lang !== undefined && lang !== "en" && lang !== "zh") {
146 return NextResponse.json({ error: "invalid lang" }, { status: 400 });
147 }
148 if (typeof reviewedSha256 !== "string" || !/^[0-9a-f]{64}$/.test(reviewedSha256)) {
149 return NextResponse.json({ error: "missing or invalid reviewedSha256" }, { status: 400 });
150 }
151 const reviewLang = lang === "zh" ? "zh" : "en";
152
153 const resolution = await getDraftResolution(env.CURATED_KV, parsedKey.type, parsedKey.id);
154 if (resolution) {
155 if (action === "discard" && resolution.state === "discarded") return discarded();
156 return claimRefused({ ok: false, reason: "resolved", resolution });
157 }
158 let result: DraftClaimResult;
159 try {
160 result = await claimDraft(env, parsedKey.type, parsedKey.id, action);
161 } catch (e) {
162 return NextResponse.json({ error: `could not claim draft: ${String(e)}` }, { status: 500 });
163 }
164 if (!result.ok) {
165 if (action === "discard" && (
166 (result.reason === "resolved" && result.resolution.state === "discarded") ||
167 (result.reason === "held" && result.holder === "discard")
168 )) return discarded();
169 return claimRefused(result);
170 }
171 const heldClaim = result.claim;
172 const loadReviewed = async () => {
173 const draft = await getDraft(env.CURATED_KV, draftKey);
174 if (!draft) return NextResponse.json({ error: "draft not found" }, { status: 404 });
175 const originalBody = reviewLang === "zh" ? draft.bodyZh : draft.bodyEn;
176 if ((await reviewedBodyHash(originalBody)) !== reviewedSha256 ||
177 (heldClaim.revision && (await reviewedBodyHash(JSON.stringify(draft))) !== heldClaim.revision)) {
178 return NextResponse.json({ error: "draft changed since it was loaded; reload and review it again" }, { status: 409 });
179 }
180 if (draft.posted) return NextResponse.json({ error: "draft already posted" }, { status: 409 });
181 if (action === "post" && !env.MAINTAINER_GITHUB_PAT) {
182 return NextResponse.json({ error: "MAINTAINER_GITHUB_PAT not configured" }, { status: 500 });
183 }
184 if (action === "post" && draft.type !== "digest" && !draft.targetNumber) {
185 return NextResponse.json({ error: "no target number" }, { status: 400 });
186 }
187 return { draft, originalBody };
188 };
189 const reviewed = await loadReviewed().catch(async (error: unknown) => {
190 await releaseDraftClaim(env.CURATED_KV, heldClaim).catch(() => undefined);
191 throw error;
192 });
193 if (reviewed instanceof Response) {
194 await releaseDraftClaim(env.CURATED_KV, heldClaim).catch(() => undefined);
195 return reviewed;
196 }
197 const { draft, originalBody } = reviewed;
198
199 if (action === "discard") {
200 let recorded = false;
201 try {
202 // The marker stops the next cron run from regenerating this draft.
203 await markDraftResolved(env.CURATED_KV, parsedKey.type, parsedKey.id, "discarded");
204 await deleteDraft(env.CURATED_KV, draftKey);
205 if (draft.type === "digest") {
206 await deleteDigestRecord(env.CURATED_KV, draft.id);
207 }
208 recorded = true;
209 } catch (e) {
210 return NextResponse.json({ error: `discard failed: ${String(e)}` }, { status: 500 });
211 } finally {
212 // The marker (or, if it failed, the draft) now carries the decision.
213 await releaseDraftClaim(env.CURATED_KV, heldClaim, { recorded }).catch(() => undefined);
214 }
215 if (draft.type === "digest") revalidateDigestPage();
216 return discarded();
217 }
218
219 if (action === "post") {
220 try {
221 // Keeps the cron from regenerating the draft while the post is in flight.
222 await markDraftResolved(env.CURATED_KV, parsedKey.type, parsedKey.id, "posting");
223 } catch (e) {
224 await releaseDraftClaim(env.CURATED_KV, heldClaim).catch(() => undefined);
225 return NextResponse.json({ error: `could not claim draft: ${String(e)}` }, { status: 500 });
226 }
227
228 const commentBody = editedBody ?? originalBody;
229
230 // GitHub has no idempotency key. If an earlier attempt's outcome was
231 // unknown, the post it may have created is looked for (from shortly
232 // before that attempt) instead of posting blind a second time.
233 const identity = await reviewedBodyHash(JSON.stringify({
234 repo: env.GITHUB_REPO ?? "codewhale-hq/CodeWhale", type: draft.type,
235 target: draft.targetNumber, body: commentBody,
236 }));
237 let unknownAt: string | null;
238 try {
239 unknownAt = await getPostOutcomeUnknown(env, parsedKey.type, parsedKey.id, identity);
240 } catch (error) {
241 await clearDraftResolution(env.CURATED_KV, parsedKey.type, parsedKey.id).catch(() => undefined);
242 await releaseDraftClaim(env.CURATED_KV, heldClaim).catch(() => undefined);
243 const changed = error instanceof Error && error.message === "unresolved post has different text or target";
244 return NextResponse.json({ error: changed
245 ? "an earlier post with different text or target is unresolved; check GitHub before retrying; nothing was posted"
246 : "could not read the earlier post receipt; nothing was posted" }, { status: changed ? 409 : 503 });
247 }
248 const lookSince = unknownAt ? new Date(Date.parse(unknownAt) - 10 * 60 * 1000).toISOString() : null;
249 const githubFind = async (url: string, authScheme: "token" | "Bearer", matches: (item: Record<string, unknown>) => boolean): Promise<Record<string, unknown> | undefined> => {
250 const signal = AbortSignal.timeout(30_000);
251 for (let page = 1; page <= 10; page++) {
252 const pageUrl = new URL(url);
253 pageUrl.searchParams.set("page", String(page));
254 const res = await fetch(pageUrl.toString(), {
255 headers: {
256 Accept: "application/vnd.github+json",
257 Authorization: `${authScheme} ${env.MAINTAINER_GITHUB_PAT}`,
258 "X-GitHub-Api-Version": "2022-11-28",
259 }, signal,
260 });
261 if (!res.ok) throw new Error(`GitHub ${res.status}`);
262 const list: unknown = JSON.parse(new TextDecoder().decode(await readBoundedBody(res, 2 * 1024 * 1024)));
263 if (!Array.isArray(list) || list.some(item => !item || typeof item !== "object")) throw new Error("GitHub returned no valid list");
264 const found = list.find(matches);
265 if (found) return found;
266 if (list.length < 100) return undefined;
267 }
268 // A capped search is unknown, never proof that GitHub lacks the post.
269 throw new Error("GitHub reconciliation page limit exceeded");
270 };
271 // This request posted nothing, so the draft is free again.
272 const lookupFailed = async () => {
273 try {
274 await clearDraftResolution(env.CURATED_KV, parsedKey.type, parsedKey.id);
275 await releaseDraftClaim(env.CURATED_KV, heldClaim);
276 } catch { /* the claim expires on its own */ }
277 return NextResponse.json(
278 { error: "could not check GitHub for the post an earlier attempt may have created; nothing was posted, retry" },
279 { status: 502 }
280 );
281 };
282 const alreadyPosted = "An earlier attempt whose outcome was unknown had already posted this; it was not posted again.";
283
284 // After GitHub accepted the post, bookkeeping failures must not turn into
285 // an error the maintainer would "fix" by posting again.
286 const recordPosted = async (): Promise<string | undefined> => {
287 try {
288 await markDraftResolved(env.CURATED_KV, parsedKey.type, parsedKey.id, "posted");
289 // The marker now carries the decision, so a later claim sees it; a
290 // reopened draft (new activity clears the marker) is postable again.
291 await env.CURATED_KV?.put(draftKey, JSON.stringify(draft), { expirationTtl: 60 * 60 * 24 * 7 });
292 await clearPostOutcomeUnknown(env, parsedKey.type, parsedKey.id, heldClaim);
293 await releaseDraftClaim(env.CURATED_KV, heldClaim, { recorded: true }).catch(() => undefined);
294 return undefined;
295 } catch (e) {
296 return `Posted to GitHub, but saving the draft state failed (${String(e)}). Do not post it again; it may reappear as pending.`;
297 }
298 };
299
300 const postToGitHub = async (url: string, payload: unknown, authScheme: "token" | "Bearer") => {
301 await markPostOutcomeUnknown(env, parsedKey.type, parsedKey.id, heldClaim, identity);
302 try {
303 return await fetch(url, {
304 method: "POST",
305 headers: {
306 Accept: "application/vnd.github+json",
307 Authorization: `${authScheme} ${env.MAINTAINER_GITHUB_PAT}`,
308 "X-GitHub-Api-Version": "2022-11-28",
309 "Content-Type": "application/json",
310 },
311 signal: AbortSignal.timeout(30_000),
312 body: JSON.stringify(payload),
313 });
314 } catch {
315 // Outcome unknown: keep the short-lived claim so an immediate retry
316 // cannot double-post.
317 return null;
318 }
319 };
320 const unknownOutcome = async (detail: string) => {
321 // Remembered past the claim, so a later retry looks before posting.
322 // The durable receipt was persisted before the outbound POST.
323 return NextResponse.json(
324 { error: `${detail}; check GitHub before retrying (retry unlocks in 15 minutes)` },
325 { status: 502 }
326 );
327 };
328 const githubFailed = async (res: Response) => {
329 const text = await res.text().catch(() => "");
330 if (!githubDefinitelyRejected(res.status)) {
331 // Keep the claim: GitHub may have created the post anyway.
332 return unknownOutcome(`GitHub ${res.status}: ${text}`);
333 }
334 try {
335 await clearPostOutcomeUnknown(env, parsedKey.type, parsedKey.id, heldClaim);
336 await clearDraftResolution(env.CURATED_KV, parsedKey.type, parsedKey.id);
337 await releaseDraftClaim(env.CURATED_KV, heldClaim);
338 } catch { /* receipt remains; the next retry must reconcile */ }
339 return NextResponse.json({ error: `GitHub ${res.status}: ${text}` }, { status: 502 });
340 };
341
342 if (draft.type === "digest") {
343 const digestBody = commentBody;
344 const firstLine = digestBody.split("\n")[0].replace(/^#+\s*/, "").trim();
345 const title = firstLine || `Weekly Digest ${draft.id}`;
346
347 const digestRepo = env.GITHUB_REPO ?? "codewhale-hq/CodeWhale";
348 const issuesUrl = `https://api.github.com/repos/${digestRepo}/issues`;
349
350 let issue: { number?: number; html_url?: string } | undefined;
351 if (lookSince) {
352 try {
353 const listUrl = `${issuesUrl}?labels=digest&state=all&since=${encodeURIComponent(lookSince)}&per_page=100`;
354 const found = await githubFind(listUrl, "token", (item) => !item.pull_request && item.title === title && item.body === digestBody);
355 if (found) {
356 issue = {
357 number: typeof found.number === "number" ? found.number : undefined,
358 html_url: typeof found.html_url === "string" ? found.html_url : undefined,
359 };
360 }
361 } catch {
362 return lookupFailed();
363 }
364 }
365 const reconciled = issue !== undefined;
366 if (!issue) {
367 let digestRes: Response | null;
368 try { digestRes = await postToGitHub(issuesUrl, { title, body: digestBody, labels: ["digest"] }, "token"); }
369 catch { return lookupFailed(); }
370 if (!digestRes) return unknownOutcome("GitHub request failed");
371 if (!digestRes.ok) return githubFailed(digestRes);
372 issue = await digestRes.json().catch(() => ({})) as { number?: number; html_url?: string };
373 }
374
375 draft.posted = true;
376 if (typeof issue.number === "number") draft.targetNumber = issue.number;
377 if (typeof issue.html_url === "string") draft.targetUrl = issue.html_url;
378 let warning = await recordPosted();
379 if (reconciled) warning ??= alreadyPosted;
380
381 // Publishing to /digest is the approval, for the language shown to the
382 // maintainer only, and only of the record that renders to exactly the
383 // text they reviewed. An edited digest is posted to GitHub but not
384 // published there, since the record holds the unedited text.
385 let published = false;
386 if (editedBody === undefined || editedBody === originalBody) {
387 try {
388 const approval = await approveDigestRecord(env.CURATED_KV, draft, reviewLang);
389 published = approval === "published";
390 if (published) revalidateDigestPage();
391 else if (approval === "missing") {
392 warning ??= "Posted to GitHub, but the weekly record is gone, so /digest does not show it.";
393 } else {
394 warning ??= "Posted to GitHub, but the stored weekly record does not match the reviewed text, so /digest does not show it.";
395 }
396 } catch (e) {
397 warning ??= `Posted to GitHub, but publishing the digest page failed (${String(e)}).`;
398 }
399 } else {
400 warning ??= "Posted to GitHub. The text was edited, so /digest does not show this week.";
401 }
402
403 return NextResponse.json({
404 ok: true,
405 action: "posted",
406 number: issue.number,
407 url: issue.html_url,
408 published,
409 ...(warning ? { warning } : {}),
410 });
411 }
412
413 const repo = env.GITHUB_REPO ?? "codewhale-hq/CodeWhale";
414 const commentUrl = `https://api.github.com/repos/${repo}/issues/${draft.targetNumber}/comments`;
415
416 let reconciled = false;
417 if (lookSince) {
418 try {
419 const listUrl = `${commentUrl}?since=${encodeURIComponent(lookSince)}&per_page=100`;
420 reconciled = (await githubFind(listUrl, "Bearer", (comment) => comment.body === commentBody)) !== undefined;
421 } catch {
422 return lookupFailed();
423 }
424 }
425 if (!reconciled) {
426 let ghRes: Response | null;
427 try { ghRes = await postToGitHub(commentUrl, { body: commentBody }, "Bearer"); }
428 catch { return lookupFailed(); }
429 if (!ghRes) return unknownOutcome("GitHub request failed");
430 if (!ghRes.ok) return githubFailed(ghRes);
431 }
432
433 // Mark as posted
434 draft.posted = true;
435 const warning = (await recordPosted()) ?? (reconciled ? alreadyPosted : undefined);
436
437 return NextResponse.json({ ok: true, action: "posted", ...(warning ? { warning } : {}) });
438 }
439
440 // ALLOWED_ACTIONS guard above means this is unreachable.
441 return NextResponse.json({ error: "unknown action" }, { status: 400 });
442 }
443
443 lines TYPESCRIPT