@cloudhal/comments 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +86 -2
- package/dist/src/client/comments.browser.js +245 -0
- package/dist/src/client/index.d.ts +19 -0
- package/dist/src/client/index.js +39 -0
- package/dist/src/client/solver.browser.js +118 -0
- package/dist/src/crypto.d.ts +64 -0
- package/dist/src/crypto.js +170 -0
- package/dist/src/errors.d.ts +38 -0
- package/dist/src/errors.js +61 -0
- package/dist/src/fixtures/comment-text.json +335 -0
- package/dist/src/hashes.d.ts +70 -0
- package/dist/src/hashes.js +191 -0
- package/dist/src/index.d.ts +24 -0
- package/dist/src/index.js +24 -0
- package/dist/src/limits.d.ts +73 -0
- package/dist/src/limits.js +227 -0
- package/dist/src/linkify.d.ts +53 -0
- package/dist/src/linkify.js +142 -0
- package/dist/src/model.d.ts +287 -0
- package/dist/src/model.js +341 -0
- package/dist/src/normalize.d.ts +17 -0
- package/dist/src/normalize.js +125 -0
- package/dist/src/pipeline.d.ts +176 -0
- package/dist/src/pipeline.js +898 -0
- package/dist/src/pow.d.ts +86 -0
- package/dist/src/pow.js +239 -0
- package/dist/src/purge.d.ts +87 -0
- package/dist/src/purge.js +186 -0
- package/dist/src/retention.d.ts +32 -0
- package/dist/src/retention.js +106 -0
- package/dist/src/rules.d.ts +68 -0
- package/dist/src/rules.js +218 -0
- package/dist/src/settings.d.ts +108 -0
- package/dist/src/settings.js +347 -0
- package/dist/src/sql/index.d.ts +7 -0
- package/dist/src/sql/index.js +29 -0
- package/dist/src/sql/portability.d.ts +113 -0
- package/dist/src/sql/portability.js +514 -0
- package/dist/src/sql/rows.d.ts +54 -0
- package/dist/src/sql/rows.js +145 -0
- package/dist/src/sql/store.d.ts +312 -0
- package/dist/src/sql/store.js +2111 -0
- package/dist/src/thread.d.ts +35 -0
- package/dist/src/thread.js +64 -0
- package/package.json +61 -3
|
@@ -0,0 +1,898 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The submission pipeline (RFC-0007 §6.2–§6.6), pure: it takes the request and injected
|
|
3
|
+
* dependencies (settings, the published-entry resolver, the store's reads and its one write,
|
|
4
|
+
* isolate limits, the replay cache, keys and a clock) and returns an outcome. The site Worker
|
|
5
|
+
* (rollout step 4) wires the dependencies and turns the outcome into a response with
|
|
6
|
+
* `submissionResponse`.
|
|
7
|
+
*
|
|
8
|
+
* `POST /__cloudhal/comments`, in order — **nothing is written before step 12** (invariant C2):
|
|
9
|
+
*
|
|
10
|
+
* 1. method `POST`, comments available, the site's settings `enabled` (a read error is "off");
|
|
11
|
+
* 2. same origin (`Sec-Fetch-Site`, else `Origin`/`Referer` host = `Host` ∈ the site's hosts);
|
|
12
|
+
* 3. `Content-Type` form or JSON, at most 32 KiB, strict UTF-8;
|
|
13
|
+
* 4. the `CommentSubmission` contract (`assertValid`, precompiled; the endpoint sets `kind`);
|
|
14
|
+
* 5. a published entry with an open thread; a reply only to an approved comment of that entry;
|
|
15
|
+
* the page to return to is the entry's current path, computed here;
|
|
16
|
+
* 6. honeypot → the "pending" answer, nothing stored;
|
|
17
|
+
* 7. proof: Turnstile, else proof of work (expired → `400 challenge_expired`; anything else wrong
|
|
18
|
+
* → "pending", nothing stored), else a JavaScript-less form post when the site allows it;
|
|
19
|
+
* 8. rate limits: isolate per client and per site, the optional binding, then stored-per-client
|
|
20
|
+
* counts (indexed reads);
|
|
21
|
+
* 9. content rules on the normalised name, email and text; a duplicate on the entry within 24 h →
|
|
22
|
+
* "pending", nothing stored;
|
|
23
|
+
* 10. the daily cap (and the JavaScript-less cap, and pending per entry) → `503 paused`;
|
|
24
|
+
* 11. bans → "pending", nothing stored;
|
|
25
|
+
* 12. one `batch()`: the commenter email row (when given) and the comment, `pending` (or `spam` on
|
|
26
|
+
* a blocked word), with the rule labels. A replayed challenge fails the unique index and is
|
|
27
|
+
* answered like a duplicate.
|
|
28
|
+
*
|
|
29
|
+
* The one exception to "nothing before step 12": none. This month's IP salt, when it does not
|
|
30
|
+
* exist yet, is inserted inside step 12's batch (the comment insert is guarded on it).
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
import { validationErrors } from "@cloudhal/core-contracts";
|
|
34
|
+
import { sha256Hex } from "./crypto.js";
|
|
35
|
+
import {
|
|
36
|
+
emailHmac,
|
|
37
|
+
ID_PREFIX,
|
|
38
|
+
ipHmac,
|
|
39
|
+
isClientAddress,
|
|
40
|
+
newCommentsId,
|
|
41
|
+
randomSalt,
|
|
42
|
+
sealEmail,
|
|
43
|
+
UNKNOWN_CLIENT,
|
|
44
|
+
} from "./hashes.js";
|
|
45
|
+
import { STORED_LIMITS } from "./limits.js";
|
|
46
|
+
import {
|
|
47
|
+
addMs,
|
|
48
|
+
DAY_MS,
|
|
49
|
+
HOUR_MS,
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
REPORT_DETAILS_MAX,
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
utcDayStart,
|
|
57
|
+
utcMonth,
|
|
58
|
+
} from "./model.js";
|
|
59
|
+
import {
|
|
60
|
+
checkEmail,
|
|
61
|
+
checkName,
|
|
62
|
+
checkText,
|
|
63
|
+
cutCodePoints,
|
|
64
|
+
|
|
65
|
+
normalizeEmail,
|
|
66
|
+
normalizeName,
|
|
67
|
+
normalizeText,
|
|
68
|
+
} from "./normalize.js";
|
|
69
|
+
import {
|
|
70
|
+
|
|
71
|
+
difficultyFor,
|
|
72
|
+
|
|
73
|
+
issueChallenge,
|
|
74
|
+
|
|
75
|
+
verifyChallenge,
|
|
76
|
+
} from "./pow.js";
|
|
77
|
+
import { compileWordList, evaluateContent, ruleLabels } from "./rules.js";
|
|
78
|
+
import { withoutScriptAllowed } from "./settings.js";
|
|
79
|
+
import { threadState } from "./thread.js";
|
|
80
|
+
|
|
81
|
+
export const MAX_BODY_BYTES = 32 * 1024;
|
|
82
|
+
|
|
83
|
+
/** A published entry as the renderer's resolver sees it (§6.2 step 5). */
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
/** Calls `siteverify` with the site's secret; throws on an outage (the pipeline fails closed). */
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
/** The store reads and writes the pipeline needs (implemented by `SqlCommentStore`). */
|
|
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
|
+
/** Why a "pending" answer stored nothing (never shown to the client). */
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
/** A rule-matched blocked word: the statement of reasons for a `spam` comment (DSA Art. 17). */
|
|
209
|
+
export const RULES_ACTOR = {
|
|
210
|
+
kind: "system",
|
|
211
|
+
id: "sys_commentrules",
|
|
212
|
+
name: "Comment rules",
|
|
213
|
+
} ;
|
|
214
|
+
|
|
215
|
+
const wordCache = new WeakMap
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
();
|
|
219
|
+
function compiledLists(s ) {
|
|
220
|
+
let c = wordCache.get(s);
|
|
221
|
+
if (!c) {
|
|
222
|
+
c = { watch: compileWordList(s.watchWords), blocked: compileWordList(s.blockedWords) };
|
|
223
|
+
wordCache.set(s, c);
|
|
224
|
+
}
|
|
225
|
+
return c;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: paths never hold control characters
|
|
229
|
+
const CONTROL = /[\u0000-\u001F\u007F]/;
|
|
230
|
+
|
|
231
|
+
/** A safe local path to return to: one leading slash, no scheme, no `//`, no backslash. */
|
|
232
|
+
export function safeReturnPath(path ) {
|
|
233
|
+
if (!path.startsWith("/") || path.startsWith("//") || /[\\\s]/.test(path) || CONTROL.test(path))
|
|
234
|
+
return "/";
|
|
235
|
+
return path;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// ───────────────────────────── steps 1–4 ─────────────────────────────
|
|
239
|
+
|
|
240
|
+
/** Step 2: same origin (RFC-0006's rule). */
|
|
241
|
+
export function isSameOrigin(request , hosts ) {
|
|
242
|
+
const h = request.headers;
|
|
243
|
+
const host = (h.get("host") ?? new URL(request.url).host).toLowerCase();
|
|
244
|
+
if (!hosts.map((x) => x.toLowerCase()).includes(host)) return false;
|
|
245
|
+
const site = h.get("sec-fetch-site");
|
|
246
|
+
if (site !== null) return site === "same-origin";
|
|
247
|
+
const source = h.get("origin") ?? h.get("referer");
|
|
248
|
+
if (!source || source === "null") return false;
|
|
249
|
+
try {
|
|
250
|
+
return new URL(source).host.toLowerCase() === host;
|
|
251
|
+
} catch {
|
|
252
|
+
return false;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
/** Step 3: type, size and strict UTF-8, then the raw object (form or JSON). */
|
|
266
|
+
export async function readSubmissionBody(
|
|
267
|
+
request ,
|
|
268
|
+
max = MAX_BODY_BYTES,
|
|
269
|
+
) {
|
|
270
|
+
const type = (request.headers.get("content-type") ?? "").split(";")[0]?.trim().toLowerCase();
|
|
271
|
+
const form = type === "application/x-www-form-urlencoded";
|
|
272
|
+
if (!form && type !== "application/json")
|
|
273
|
+
return { ok: false, status: 415, error: "unsupported_media_type", form: false };
|
|
274
|
+
const declared = request.headers.get("content-length");
|
|
275
|
+
if (declared !== null && (!/^\d+$/.test(declared) || Number(declared) > max))
|
|
276
|
+
return { ok: false, status: 413, error: "too_large", form };
|
|
277
|
+
let bytes ;
|
|
278
|
+
if (!request.body) bytes = new Uint8Array(0);
|
|
279
|
+
else {
|
|
280
|
+
const reader = request.body.getReader();
|
|
281
|
+
const chunks = [];
|
|
282
|
+
let total = 0;
|
|
283
|
+
for (;;) {
|
|
284
|
+
const { done, value } = await reader.read();
|
|
285
|
+
if (done) break;
|
|
286
|
+
total += value.byteLength;
|
|
287
|
+
if (total > max) {
|
|
288
|
+
await reader.cancel().catch(() => {});
|
|
289
|
+
return { ok: false, status: 413, error: "too_large", form };
|
|
290
|
+
}
|
|
291
|
+
chunks.push(value);
|
|
292
|
+
}
|
|
293
|
+
bytes = new Uint8Array(total);
|
|
294
|
+
let at = 0;
|
|
295
|
+
for (const c of chunks) {
|
|
296
|
+
bytes.set(c, at);
|
|
297
|
+
at += c.byteLength;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
let text ;
|
|
301
|
+
try {
|
|
302
|
+
text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: false }).decode(bytes);
|
|
303
|
+
} catch {
|
|
304
|
+
return { ok: false, status: 400, error: "invalid", form };
|
|
305
|
+
}
|
|
306
|
+
if (form) {
|
|
307
|
+
const fields = {};
|
|
308
|
+
for (const [k, v] of new URLSearchParams(text)) {
|
|
309
|
+
if (Object.hasOwn(fields, k)) return { ok: false, status: 400, error: "invalid", form };
|
|
310
|
+
fields[k] = v;
|
|
311
|
+
}
|
|
312
|
+
return { ok: true, fields, form };
|
|
313
|
+
}
|
|
314
|
+
let parsed ;
|
|
315
|
+
try {
|
|
316
|
+
parsed = JSON.parse(text);
|
|
317
|
+
} catch {
|
|
318
|
+
return { ok: false, status: 400, error: "invalid", form };
|
|
319
|
+
}
|
|
320
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
|
|
321
|
+
return { ok: false, status: 400, error: "invalid", form };
|
|
322
|
+
return { ok: true, fields: { ...(parsed ) }, form };
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const OPTIONAL_STRINGS = [
|
|
326
|
+
"parentId",
|
|
327
|
+
"email",
|
|
328
|
+
"challenge",
|
|
329
|
+
"solution",
|
|
330
|
+
"turnstileToken",
|
|
331
|
+
"website",
|
|
332
|
+
"details",
|
|
333
|
+
];
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* Step 4: builds the submission (the endpoint sets `kind`, the server `schemaVersion`; empty
|
|
337
|
+
* optional strings from forms are dropped) and checks it with the precompiled validator.
|
|
338
|
+
*/
|
|
339
|
+
export function buildSubmission(
|
|
340
|
+
fields ,
|
|
341
|
+
kind ,
|
|
342
|
+
) {
|
|
343
|
+
const value = { ...fields, kind, schemaVersion: 1 };
|
|
344
|
+
for (const k of OPTIONAL_STRINGS) if (value[k] === "") delete value[k];
|
|
345
|
+
const errors = validationErrors("comment-submission", value);
|
|
346
|
+
if (errors.length === 0) return { ok: true, value };
|
|
347
|
+
// errors of the other `oneOf` branch say nothing about this endpoint's fields
|
|
348
|
+
const other = `#/oneOf/${kind === "comment" ? 1 : 0}/`;
|
|
349
|
+
const out = new Set ();
|
|
350
|
+
for (const e of errors) {
|
|
351
|
+
if (e.schemaPath.startsWith(other) || e.keyword === "oneOf") continue;
|
|
352
|
+
const top = e.instancePath.split("/")[1];
|
|
353
|
+
if (top && top !== "kind" && top !== "schemaVersion") out.add(top);
|
|
354
|
+
const params = e.params ;
|
|
355
|
+
if (e.keyword === "additionalProperties" && typeof params.additionalProperty === "string")
|
|
356
|
+
out.add(params.additionalProperty.slice(0, 40));
|
|
357
|
+
if (e.keyword === "required" && typeof params.missingProperty === "string")
|
|
358
|
+
out.add(params.missingProperty);
|
|
359
|
+
}
|
|
360
|
+
if (out.size === 0) out.add(kind === "comment" ? "body" : "reason");
|
|
361
|
+
return { ok: false, fields: [...out].sort() };
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// ───────────────────────────── shared steps ─────────────────────────────
|
|
365
|
+
|
|
366
|
+
const err = (
|
|
367
|
+
status ,
|
|
368
|
+
error ,
|
|
369
|
+
form ,
|
|
370
|
+
extra = {},
|
|
371
|
+
) => ({ kind: "error", status, error, form, ...extra });
|
|
372
|
+
|
|
373
|
+
const drop = (dropped , form , returnTo ) =>
|
|
374
|
+
returnTo === undefined
|
|
375
|
+
? { kind: "pending", stored: false, dropped, form }
|
|
376
|
+
: { kind: "pending", stored: false, dropped, form, returnTo };
|
|
377
|
+
|
|
378
|
+
async function loadSettings(deps ) {
|
|
379
|
+
if (!deps.available) return null;
|
|
380
|
+
try {
|
|
381
|
+
const s = await deps.settings();
|
|
382
|
+
return s?.enabled ? s : null;
|
|
383
|
+
} catch {
|
|
384
|
+
return null;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
/** Step 7. */
|
|
398
|
+
async function checkProof(
|
|
399
|
+
deps ,
|
|
400
|
+
settings ,
|
|
401
|
+
sub ,
|
|
402
|
+
ctx ,
|
|
403
|
+
) {
|
|
404
|
+
const { form, returnTo } = ctx;
|
|
405
|
+
const challenge = typeof sub.challenge === "string" ? sub.challenge : undefined;
|
|
406
|
+
const solution = typeof sub.solution === "string" ? sub.solution : undefined;
|
|
407
|
+
const token = typeof sub.turnstileToken === "string" ? sub.turnstileToken : undefined;
|
|
408
|
+
const anyProof = challenge !== undefined || solution !== undefined || token !== undefined;
|
|
409
|
+
if (!anyProof && form) {
|
|
410
|
+
if (!withoutScriptAllowed(settings))
|
|
411
|
+
return { ok: false, outcome: err(403, "script_required", form, { returnTo }) };
|
|
412
|
+
return { ok: true, proof: "none", challengeId: null };
|
|
413
|
+
}
|
|
414
|
+
if (settings.protection === "turnstile") {
|
|
415
|
+
if (token === undefined)
|
|
416
|
+
return { ok: false, outcome: err(403, "proof_failed", form, { returnTo }) };
|
|
417
|
+
if (!deps.turnstile) return { ok: false, outcome: err(503, "try_again", form, { returnTo }) };
|
|
418
|
+
const tokenHash = (await sha256Hex(token)).slice(0, 32);
|
|
419
|
+
let result ;
|
|
420
|
+
try {
|
|
421
|
+
result = await deps.turnstile({
|
|
422
|
+
token,
|
|
423
|
+
remoteip: deps.clientAddress,
|
|
424
|
+
idempotencyKey: tokenHash,
|
|
425
|
+
});
|
|
426
|
+
} catch {
|
|
427
|
+
return { ok: false, outcome: err(503, "try_again", form, { returnTo }) };
|
|
428
|
+
}
|
|
429
|
+
const hosts = deps.hosts.map((h) => h.toLowerCase().replace(/:\d+$/, ""));
|
|
430
|
+
if (
|
|
431
|
+
!result.success ||
|
|
432
|
+
!result.hostname ||
|
|
433
|
+
!hosts.includes(result.hostname.toLowerCase()) ||
|
|
434
|
+
result.action !== ctx.kind
|
|
435
|
+
)
|
|
436
|
+
return { ok: false, outcome: err(403, "proof_failed", form, { returnTo }) };
|
|
437
|
+
return { ok: true, proof: "turnstile", challengeId: `ts_${tokenHash}` };
|
|
438
|
+
}
|
|
439
|
+
if (challenge === undefined || solution === undefined)
|
|
440
|
+
return { ok: false, outcome: drop("bad_proof", form, returnTo) };
|
|
441
|
+
const check = await verifyChallenge(deps.keys.pow, challenge, solution, {
|
|
442
|
+
siteId: deps.siteId,
|
|
443
|
+
target: ctx.target,
|
|
444
|
+
kind: ctx.kind,
|
|
445
|
+
now: ctx.now,
|
|
446
|
+
});
|
|
447
|
+
if (!check.ok) {
|
|
448
|
+
if (check.reason === "expired")
|
|
449
|
+
return { ok: false, outcome: err(400, "challenge_expired", form, { returnTo }) };
|
|
450
|
+
return {
|
|
451
|
+
ok: false,
|
|
452
|
+
outcome: drop(check.reason === "too_fast" ? "too_fast" : "bad_proof", form, returnTo),
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
if (deps.replay.has(check.id, ctx.now))
|
|
456
|
+
return { ok: false, outcome: drop("replay", form, returnTo) };
|
|
457
|
+
return { ok: true, proof: "pow", challengeId: check.id, expiresS: check.payload.e };
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/** Isolate limits and the optional binding (first part of step 8). */
|
|
461
|
+
async function isolateLimits(
|
|
462
|
+
deps ,
|
|
463
|
+
form ,
|
|
464
|
+
returnTo ,
|
|
465
|
+
) {
|
|
466
|
+
const clientKey = await deps.limiter.clientKey(deps.clientAddress);
|
|
467
|
+
const retryAfter = deps.limiter.retryAfterS();
|
|
468
|
+
if (!deps.limiter.allowSubmission(clientKey) || !deps.limiter.allowSite(deps.siteId))
|
|
469
|
+
return err(429, "rate_limited", form, { retryAfter, returnTo });
|
|
470
|
+
if (deps.rateLimit) {
|
|
471
|
+
let allowed = true;
|
|
472
|
+
try {
|
|
473
|
+
allowed = await deps.rateLimit(clientKey);
|
|
474
|
+
} catch {
|
|
475
|
+
allowed = true; // the binding is an extra; the D1 limits below still apply
|
|
476
|
+
}
|
|
477
|
+
if (!allowed) return err(429, "rate_limited", form, { retryAfter: 60, returnTo });
|
|
478
|
+
}
|
|
479
|
+
return undefined;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/** This month's salt (read only) and the client's IP hash; a new salt is stored at step 12. */
|
|
483
|
+
async function clientHash(
|
|
484
|
+
deps ,
|
|
485
|
+
now ,
|
|
486
|
+
salt ,
|
|
487
|
+
) {
|
|
488
|
+
const month = utcMonth(now);
|
|
489
|
+
const stored = salt ?? (await deps.store.readSalt(month));
|
|
490
|
+
// without an address the runtime vouches for, every such client shares the `unknown` hash: one
|
|
491
|
+
// bucket for the D1 limits (stricter), which an IP ban never targets (SqlCommentStore.ban)
|
|
492
|
+
const address = isClientAddress(deps.clientAddress) ? deps.clientAddress : UNKNOWN_CLIENT;
|
|
493
|
+
if (stored) return { ipHmac: await ipHmac(stored, deps.siteId, address) };
|
|
494
|
+
const fresh = randomSalt();
|
|
495
|
+
return {
|
|
496
|
+
ipHmac: await ipHmac(fresh, deps.siteId, address),
|
|
497
|
+
newSalt: { month, salt: fresh },
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
async function prepareEmail(
|
|
502
|
+
deps ,
|
|
503
|
+
email ,
|
|
504
|
+
) {
|
|
505
|
+
if (email === undefined) return {};
|
|
506
|
+
const hmac = await emailHmac(deps.keys, email);
|
|
507
|
+
const sealed = await sealEmail(deps.keys, deps.siteId, email);
|
|
508
|
+
return {
|
|
509
|
+
hmac,
|
|
510
|
+
email: {
|
|
511
|
+
id: newCommentsId(ID_PREFIX.commenter),
|
|
512
|
+
hmac,
|
|
513
|
+
ciphertext: sealed.ciphertext,
|
|
514
|
+
iv: sealed.iv,
|
|
515
|
+
},
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
// ───────────────────────────── POST /__cloudhal/comments ─────────────────────────────
|
|
520
|
+
|
|
521
|
+
export async function handleCommentSubmission(
|
|
522
|
+
request ,
|
|
523
|
+
deps ,
|
|
524
|
+
) {
|
|
525
|
+
// 1. method and feature
|
|
526
|
+
if (request.method !== "POST") return err(405, "method_not_allowed", false);
|
|
527
|
+
const settings = await loadSettings(deps);
|
|
528
|
+
if (!settings) return err(404, "not_found", false);
|
|
529
|
+
// 2. same origin
|
|
530
|
+
if (!isSameOrigin(request, deps.hosts)) return err(403, "forbidden", false);
|
|
531
|
+
// 3. size and type
|
|
532
|
+
const body = await readSubmissionBody(request);
|
|
533
|
+
if (!body.ok) return err(body.status, body.error, body.form);
|
|
534
|
+
const form = body.form;
|
|
535
|
+
// 4. schema
|
|
536
|
+
const built = buildSubmission(body.fields, "comment");
|
|
537
|
+
if (!built.ok) return err(400, "invalid", form, { fields: built.fields });
|
|
538
|
+
const sub = built.value;
|
|
539
|
+
const nodeId = sub.nodeId ;
|
|
540
|
+
const now = deps.now();
|
|
541
|
+
|
|
542
|
+
// 5. thread
|
|
543
|
+
const entry = await deps.resolveEntry(nodeId);
|
|
544
|
+
if (!entry || entry.nodeId !== nodeId) return err(404, "not_found", form);
|
|
545
|
+
const returnTo = safeReturnPath(entry.path);
|
|
546
|
+
const thread = await deps.store.thread(deps.siteId, nodeId);
|
|
547
|
+
const state = threadState({ settings, entry, thread, now });
|
|
548
|
+
if (state === "closed") return err(403, "closed", form, { returnTo });
|
|
549
|
+
if (state !== "open") return err(404, "not_found", form);
|
|
550
|
+
let parentId ;
|
|
551
|
+
let inReplyToId ;
|
|
552
|
+
if (typeof sub.parentId === "string") {
|
|
553
|
+
const parent = await deps.store.approvedComment(deps.siteId, sub.parentId);
|
|
554
|
+
if (!parent || parent.nodeId !== nodeId)
|
|
555
|
+
return err(400, "invalid", form, { fields: ["parentId"], returnTo });
|
|
556
|
+
parentId = parent.parentId ?? parent.id;
|
|
557
|
+
if (parent.parentId) inReplyToId = parent.id;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
// 6. honeypot
|
|
561
|
+
if (typeof sub.website === "string" && sub.website.length > 0)
|
|
562
|
+
return drop("honeypot", form, returnTo);
|
|
563
|
+
|
|
564
|
+
// 7. proof
|
|
565
|
+
const proof = await checkProof(deps, settings, sub, {
|
|
566
|
+
kind: "comment",
|
|
567
|
+
target: nodeId,
|
|
568
|
+
form,
|
|
569
|
+
returnTo,
|
|
570
|
+
now,
|
|
571
|
+
});
|
|
572
|
+
if (!proof.ok) return proof.outcome;
|
|
573
|
+
const withoutScript = proof.proof === "none";
|
|
574
|
+
|
|
575
|
+
// 8. rate limits
|
|
576
|
+
const limited = await isolateLimits(deps, form, returnTo);
|
|
577
|
+
if (limited) return limited;
|
|
578
|
+
let client = await clientHash(deps, now);
|
|
579
|
+
if (!client.newSalt) {
|
|
580
|
+
const a = await deps.store.clientActivity(deps.siteId, client.ipHmac, {
|
|
581
|
+
hour: addMs(now, -HOUR_MS),
|
|
582
|
+
day: addMs(now, -DAY_MS),
|
|
583
|
+
noScript: addMs(now, -STORED_LIMITS.noScriptWindowMs),
|
|
584
|
+
});
|
|
585
|
+
if (a.hour >= STORED_LIMITS.commentsPerClientPerHour)
|
|
586
|
+
return err(429, "rate_limited", form, { retryAfter: 3600, returnTo });
|
|
587
|
+
if (a.day >= STORED_LIMITS.commentsPerClientPerDay)
|
|
588
|
+
return err(429, "rate_limited", form, { retryAfter: 86_400, returnTo });
|
|
589
|
+
if (withoutScript && a.noScript >= 1)
|
|
590
|
+
return err(429, "rate_limited", form, { retryAfter: 600, returnTo });
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
// 9. content rules
|
|
594
|
+
const name = normalizeName(sub.name );
|
|
595
|
+
const text = normalizeText(sub.body );
|
|
596
|
+
const email = normalizeEmail(sub.email );
|
|
597
|
+
const problems = [
|
|
598
|
+
["name", checkName(name)],
|
|
599
|
+
["email", email === undefined ? undefined : checkEmail(email)],
|
|
600
|
+
["body", checkText(text)],
|
|
601
|
+
];
|
|
602
|
+
const bad = problems.filter(([, p]) => p !== undefined).map(([f]) => f);
|
|
603
|
+
if (bad.length > 0) return err(400, "invalid", form, { fields: bad, returnTo });
|
|
604
|
+
const lists = compiledLists(settings);
|
|
605
|
+
const decision = evaluateContent(
|
|
606
|
+
{ name, text },
|
|
607
|
+
{ linkLimit: settings.linkLimit, watchWords: lists.watch, blockedWords: lists.blocked },
|
|
608
|
+
);
|
|
609
|
+
if (!decision.ok) return err(400, "invalid", form, { fields: [decision.field], returnTo });
|
|
610
|
+
if (await deps.store.isDuplicate(deps.siteId, nodeId, text, addMs(now, -DAY_MS)))
|
|
611
|
+
return drop("duplicate", form, returnTo);
|
|
612
|
+
|
|
613
|
+
// 10. daily cap, JavaScript-less cap, pending per entry
|
|
614
|
+
const today = await deps.daily.get(deps.siteId, utcDayStart(now), () =>
|
|
615
|
+
deps.store.storedSince(deps.siteId, utcDayStart(now)),
|
|
616
|
+
);
|
|
617
|
+
if (today.total >= settings.dailyCap) return err(503, "paused", form, { returnTo });
|
|
618
|
+
if (withoutScript && today.withoutScript >= STORED_LIMITS.noScriptPerSitePerDay)
|
|
619
|
+
return err(503, "paused", form, { returnTo });
|
|
620
|
+
if ((await deps.store.pendingOnEntry(deps.siteId, nodeId)) >= STORED_LIMITS.pendingPerEntry)
|
|
621
|
+
return err(503, "paused", form, { returnTo });
|
|
622
|
+
|
|
623
|
+
// 11. bans
|
|
624
|
+
const sealed = await prepareEmail(deps, email);
|
|
625
|
+
if (
|
|
626
|
+
await deps.store.isBanned(
|
|
627
|
+
deps.siteId,
|
|
628
|
+
{ ...(sealed.hmac ? { emailHmac: sealed.hmac } : {}), ipHmac: client.ipHmac },
|
|
629
|
+
now.toISOString(),
|
|
630
|
+
)
|
|
631
|
+
)
|
|
632
|
+
return drop("banned", form, returnTo);
|
|
633
|
+
|
|
634
|
+
// 12. moderation decision and write
|
|
635
|
+
const at = now.toISOString();
|
|
636
|
+
const labels = ruleLabels(decision.labels, at);
|
|
637
|
+
const moderation =
|
|
638
|
+
decision.status === "spam"
|
|
639
|
+
? {
|
|
640
|
+
action: "spam",
|
|
641
|
+
actor: RULES_ACTOR,
|
|
642
|
+
at,
|
|
643
|
+
reasonCode: "spam",
|
|
644
|
+
note: "Matched a blocked word.",
|
|
645
|
+
automated: true,
|
|
646
|
+
}
|
|
647
|
+
: undefined;
|
|
648
|
+
const id = newCommentsId(ID_PREFIX.comment);
|
|
649
|
+
const prepare = (c ) => ({
|
|
650
|
+
id,
|
|
651
|
+
nodeId,
|
|
652
|
+
...(parentId ? { parentId } : {}),
|
|
653
|
+
...(inReplyToId ? { inReplyToId } : {}),
|
|
654
|
+
name,
|
|
655
|
+
text,
|
|
656
|
+
status: decision.status,
|
|
657
|
+
labels,
|
|
658
|
+
...(moderation ? { moderation } : {}),
|
|
659
|
+
...(sealed.email ? { email: sealed.email } : {}),
|
|
660
|
+
ipHmac: c.ipHmac,
|
|
661
|
+
challengeId: proof.challengeId,
|
|
662
|
+
proof: proof.proof,
|
|
663
|
+
createdAt: at,
|
|
664
|
+
...(c.newSalt ? { newSalt: c.newSalt } : {}),
|
|
665
|
+
});
|
|
666
|
+
let result = await deps.store.submit(deps.siteId, prepare(client));
|
|
667
|
+
if ("saltConflict" in result) {
|
|
668
|
+
const salt = await deps.store.readSalt(utcMonth(now));
|
|
669
|
+
if (!salt) return err(503, "try_again", form, { returnTo });
|
|
670
|
+
client = await clientHash(deps, now, salt);
|
|
671
|
+
result = await deps.store.submit(deps.siteId, prepare(client));
|
|
672
|
+
if ("saltConflict" in result) return err(503, "try_again", form, { returnTo });
|
|
673
|
+
}
|
|
674
|
+
if ("duplicate" in result) return drop("replay", form, returnTo);
|
|
675
|
+
if (proof.challengeId && proof.expiresS !== undefined)
|
|
676
|
+
deps.replay.add(proof.challengeId, proof.expiresS);
|
|
677
|
+
deps.daily.increment(deps.siteId, withoutScript);
|
|
678
|
+
return { kind: "pending", stored: true, id: result.id, status: decision.status, form, returnTo };
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
// ───────────────────────────── POST /__cloudhal/comments/report ─────────────────────────────
|
|
682
|
+
|
|
683
|
+
/**
|
|
684
|
+
* A report (§6.6, DSA Art. 16): steps 1–4, 6–8 and 10. Only an approved comment can be reported;
|
|
685
|
+
* a report never changes the comment's status.
|
|
686
|
+
*/
|
|
687
|
+
export async function handleReportSubmission(
|
|
688
|
+
request ,
|
|
689
|
+
deps ,
|
|
690
|
+
) {
|
|
691
|
+
if (request.method !== "POST") return err(405, "method_not_allowed", false);
|
|
692
|
+
const settings = await loadSettings(deps);
|
|
693
|
+
if (!settings) return err(404, "not_found", false);
|
|
694
|
+
if (!isSameOrigin(request, deps.hosts)) return err(403, "forbidden", false);
|
|
695
|
+
const body = await readSubmissionBody(request);
|
|
696
|
+
if (!body.ok) return err(body.status, body.error, body.form);
|
|
697
|
+
const form = body.form;
|
|
698
|
+
const built = buildSubmission(body.fields, "report");
|
|
699
|
+
if (!built.ok) return err(400, "invalid", form, { fields: built.fields });
|
|
700
|
+
const sub = built.value;
|
|
701
|
+
const commentId = sub.commentId ;
|
|
702
|
+
const now = deps.now();
|
|
703
|
+
|
|
704
|
+
const target = await deps.store.approvedComment(deps.siteId, commentId);
|
|
705
|
+
if (!target) return err(404, "not_found", form);
|
|
706
|
+
const entry = await deps.resolveEntry(target.nodeId);
|
|
707
|
+
if (!entry) return err(404, "not_found", form);
|
|
708
|
+
const returnTo = safeReturnPath(entry.path);
|
|
709
|
+
|
|
710
|
+
if (typeof sub.website === "string" && sub.website.length > 0)
|
|
711
|
+
return drop("honeypot", form, returnTo);
|
|
712
|
+
const proof = await checkProof(deps, settings, sub, {
|
|
713
|
+
kind: "report",
|
|
714
|
+
target: commentId,
|
|
715
|
+
form,
|
|
716
|
+
returnTo,
|
|
717
|
+
now,
|
|
718
|
+
});
|
|
719
|
+
if (!proof.ok) return proof.outcome;
|
|
720
|
+
|
|
721
|
+
const limited = await isolateLimits(deps, form, returnTo);
|
|
722
|
+
if (limited) return limited;
|
|
723
|
+
let client = await clientHash(deps, now);
|
|
724
|
+
const activity = await deps.store.reportActivity(
|
|
725
|
+
deps.siteId,
|
|
726
|
+
client.newSalt ? null : client.ipHmac,
|
|
727
|
+
{
|
|
728
|
+
hour: addMs(now, -HOUR_MS),
|
|
729
|
+
day: utcDayStart(now),
|
|
730
|
+
},
|
|
731
|
+
);
|
|
732
|
+
if (activity.clientHour >= STORED_LIMITS.reportsPerClientPerHour)
|
|
733
|
+
return err(429, "rate_limited", form, { retryAfter: 3600, returnTo });
|
|
734
|
+
|
|
735
|
+
const details =
|
|
736
|
+
typeof sub.details === "string"
|
|
737
|
+
? cutCodePoints(normalizeText(sub.details), REPORT_DETAILS_MAX) || null
|
|
738
|
+
: null;
|
|
739
|
+
const email = normalizeEmail(sub.email );
|
|
740
|
+
if (email !== undefined && checkEmail(email))
|
|
741
|
+
return err(400, "invalid", form, { fields: ["email"], returnTo });
|
|
742
|
+
|
|
743
|
+
if (activity.siteDay >= STORED_LIMITS.reportsPerSitePerDay)
|
|
744
|
+
return err(503, "paused", form, { returnTo });
|
|
745
|
+
|
|
746
|
+
const sealed = await prepareEmail(deps, email);
|
|
747
|
+
const id = newCommentsId(ID_PREFIX.report);
|
|
748
|
+
const prepare = (c ) => ({
|
|
749
|
+
id,
|
|
750
|
+
commentId,
|
|
751
|
+
reason: sub.reason ,
|
|
752
|
+
details,
|
|
753
|
+
...(sealed.email ? { email: sealed.email } : {}),
|
|
754
|
+
ipHmac: c.ipHmac,
|
|
755
|
+
challengeId: proof.challengeId,
|
|
756
|
+
createdAt: now.toISOString(),
|
|
757
|
+
...(c.newSalt ? { newSalt: c.newSalt } : {}),
|
|
758
|
+
});
|
|
759
|
+
let result = await deps.store.report(deps.siteId, prepare(client));
|
|
760
|
+
if ("saltConflict" in result) {
|
|
761
|
+
const salt = await deps.store.readSalt(utcMonth(now));
|
|
762
|
+
if (!salt) return err(503, "try_again", form, { returnTo });
|
|
763
|
+
client = await clientHash(deps, now, salt);
|
|
764
|
+
result = await deps.store.report(deps.siteId, prepare(client));
|
|
765
|
+
if ("saltConflict" in result) return err(503, "try_again", form, { returnTo });
|
|
766
|
+
}
|
|
767
|
+
if ("duplicate" in result) return drop("replay", form, returnTo);
|
|
768
|
+
if (proof.challengeId && proof.expiresS !== undefined)
|
|
769
|
+
deps.replay.add(proof.challengeId, proof.expiresS);
|
|
770
|
+
return { kind: "pending", stored: true, id: result.id, form, returnTo };
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
// ───────────────────────────── GET /__cloudhal/comments/challenge ─────────────────────────────
|
|
774
|
+
|
|
775
|
+
|
|
776
|
+
|
|
777
|
+
|
|
778
|
+
|
|
779
|
+
|
|
780
|
+
|
|
781
|
+
|
|
782
|
+
|
|
783
|
+
|
|
784
|
+
/**
|
|
785
|
+
* Issues a challenge (§6.1, §7.2): `?node=<entry id>&for=comment` for an open thread, or
|
|
786
|
+
* `?node=<comment id>&for=report` for an approved comment; `404` otherwise. 20 a minute per client
|
|
787
|
+
* (isolate). Difficulty ramps with today's stored submissions. Writes nothing.
|
|
788
|
+
*/
|
|
789
|
+
export async function handleChallengeRequest(
|
|
790
|
+
request ,
|
|
791
|
+
deps ,
|
|
792
|
+
) {
|
|
793
|
+
if (request.method !== "GET") return { kind: "error", status: 405, error: "method_not_allowed" };
|
|
794
|
+
const settings = await loadSettings(deps);
|
|
795
|
+
if (!settings) return { kind: "error", status: 404, error: "not_found" };
|
|
796
|
+
const url = new URL(request.url);
|
|
797
|
+
const target = url.searchParams.get("node") ?? "";
|
|
798
|
+
const kind = (url.searchParams.get("for") ?? "comment") ;
|
|
799
|
+
if (kind !== "comment" && kind !== "report")
|
|
800
|
+
return { kind: "error", status: 400, error: "invalid" };
|
|
801
|
+
const idRe = kind === "comment" ? /^[a-z]+_[A-Za-z0-9]{6,32}$/ : /^cmt_[A-Za-z0-9]{6,32}$/;
|
|
802
|
+
if (!idRe.test(target)) return { kind: "error", status: 400, error: "invalid" };
|
|
803
|
+
const clientKey = await deps.limiter.clientKey(deps.clientAddress);
|
|
804
|
+
if (!deps.limiter.allowChallenge(clientKey))
|
|
805
|
+
return {
|
|
806
|
+
kind: "error",
|
|
807
|
+
status: 429,
|
|
808
|
+
error: "rate_limited",
|
|
809
|
+
retryAfter: deps.limiter.retryAfterS(),
|
|
810
|
+
};
|
|
811
|
+
const now = deps.now();
|
|
812
|
+
if (kind === "comment") {
|
|
813
|
+
const entry = await deps.resolveEntry(target);
|
|
814
|
+
if (!entry) return { kind: "error", status: 404, error: "not_found" };
|
|
815
|
+
const thread = await deps.store.thread(deps.siteId, target);
|
|
816
|
+
if (threadState({ settings, entry, thread, now }) !== "open")
|
|
817
|
+
return { kind: "error", status: 404, error: "not_found" };
|
|
818
|
+
} else {
|
|
819
|
+
const c = await deps.store.approvedComment(deps.siteId, target);
|
|
820
|
+
if (!c) return { kind: "error", status: 404, error: "not_found" };
|
|
821
|
+
}
|
|
822
|
+
const today = await deps.daily.get(deps.siteId, utcDayStart(now), () =>
|
|
823
|
+
deps.store.storedSince(deps.siteId, utcDayStart(now)),
|
|
824
|
+
);
|
|
825
|
+
const challenge = await issueChallenge(deps.keys.pow, {
|
|
826
|
+
siteId: deps.siteId,
|
|
827
|
+
target,
|
|
828
|
+
kind,
|
|
829
|
+
bits: difficultyFor(today.total, settings.dailyCap),
|
|
830
|
+
now,
|
|
831
|
+
});
|
|
832
|
+
return { kind: "challenge", challenge };
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
// ───────────────────────────── answers (§6.3) ─────────────────────────────
|
|
836
|
+
|
|
837
|
+
const FRAGMENTS = {
|
|
838
|
+
invalid: "comment-invalid",
|
|
839
|
+
closed: "comment-closed",
|
|
840
|
+
script_required: "comment-script-required",
|
|
841
|
+
rate_limited: "comment-slow-down",
|
|
842
|
+
proof_failed: "comment-try-again",
|
|
843
|
+
try_again: "comment-try-again",
|
|
844
|
+
challenge_expired: "comment-try-again",
|
|
845
|
+
paused: "comment-paused",
|
|
846
|
+
};
|
|
847
|
+
|
|
848
|
+
const NO_STORE = { "cache-control": "no-store" } ;
|
|
849
|
+
|
|
850
|
+
/**
|
|
851
|
+
* Turns an outcome into the response of §6.3: form posts get `303 See Other` to a fragment of the
|
|
852
|
+
* entry's cached page (`#comment-pending`, `#comment-invalid`, …); the module gets JSON. Every
|
|
853
|
+
* answer is `no-store`. Dropped submissions are indistinguishable from stored ones. `pendingFragment`
|
|
854
|
+
* lets the report endpoint answer `#comment-reported`.
|
|
855
|
+
*/
|
|
856
|
+
export function submissionResponse(
|
|
857
|
+
outcome ,
|
|
858
|
+
options = {},
|
|
859
|
+
) {
|
|
860
|
+
if (outcome.kind === "pending") {
|
|
861
|
+
if (outcome.form)
|
|
862
|
+
return new Response(null, {
|
|
863
|
+
status: 303,
|
|
864
|
+
headers: {
|
|
865
|
+
...NO_STORE,
|
|
866
|
+
location: `${outcome.returnTo ?? "/"}#${options.pendingFragment ?? "comment-pending"}`,
|
|
867
|
+
},
|
|
868
|
+
});
|
|
869
|
+
return Response.json({ status: "pending" }, { status: 200, headers: NO_STORE });
|
|
870
|
+
}
|
|
871
|
+
const headers = { ...NO_STORE };
|
|
872
|
+
if (outcome.retryAfter !== undefined) headers["retry-after"] = String(outcome.retryAfter);
|
|
873
|
+
if (outcome.status === 405) headers.allow = "POST";
|
|
874
|
+
const fragment = FRAGMENTS[outcome.error];
|
|
875
|
+
if (outcome.form && fragment && outcome.returnTo !== undefined)
|
|
876
|
+
return new Response(null, {
|
|
877
|
+
status: 303,
|
|
878
|
+
headers: { ...headers, location: `${outcome.returnTo}#${fragment}` },
|
|
879
|
+
});
|
|
880
|
+
if (outcome.form) return new Response(outcome.error, { status: outcome.status, headers });
|
|
881
|
+
return Response.json(
|
|
882
|
+
{
|
|
883
|
+
error: outcome.error,
|
|
884
|
+
...(outcome.fields ? { fields: outcome.fields } : {}),
|
|
885
|
+
...(outcome.retryAfter !== undefined ? { retryAfter: outcome.retryAfter } : {}),
|
|
886
|
+
},
|
|
887
|
+
{ status: outcome.status, headers },
|
|
888
|
+
);
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
/** The challenge endpoint's answer (JSON, `no-store`). */
|
|
892
|
+
export function challengeResponse(outcome ) {
|
|
893
|
+
if (outcome.kind === "challenge") return Response.json(outcome.challenge, { headers: NO_STORE });
|
|
894
|
+
const headers = { ...NO_STORE };
|
|
895
|
+
if (outcome.retryAfter !== undefined) headers["retry-after"] = String(outcome.retryAfter);
|
|
896
|
+
if (outcome.status === 405) headers.allow = "GET";
|
|
897
|
+
return Response.json({ error: outcome.error }, { status: outcome.status, headers });
|
|
898
|
+
}
|