@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,2111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `SqlCommentStore` — the comment tables of migration `0016_comments` through `SqlDriver` (SQLite
|
|
3
|
+
* locally and on Node, D1 on Cloudflare). Worker-safe.
|
|
4
|
+
*
|
|
5
|
+
* Writes follow RFC-0007 §4.4 and AGENTS.md rule 4: no interactive transactions, every write is
|
|
6
|
+
* one statement or one atomic `batch()`, and statements that follow a compare-and-swap in the
|
|
7
|
+
* same batch are guarded on what that CAS wrote (a fresh operation id `op` and the new content
|
|
8
|
+
* `hash`), never on `rev + 1`. Statement counts per path (asserted by the conformance suite):
|
|
9
|
+
*
|
|
10
|
+
* | Path | Statements |
|
|
11
|
+
* |---|---|
|
|
12
|
+
* | submit / report | 1–2 (+1 the first time a month's salt is stored) |
|
|
13
|
+
* | moderate (1–50 ids) | 2–3 + audit, however many comments |
|
|
14
|
+
* | label (1–50 ids) | 2 + audit |
|
|
15
|
+
* | staff reply | 3 + audit |
|
|
16
|
+
* | settings | 1 |
|
|
17
|
+
* | thread | 1–2 + audit |
|
|
18
|
+
* | erase | ≤ 5 + audit per 200 comments |
|
|
19
|
+
*
|
|
20
|
+
* Bulk statements pass their per-row data as one JSON parameter read with `json_each`, so they
|
|
21
|
+
* stay far below D1's 100 bound parameters whatever the number of comments.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
import { fromBase64Url, toBase64Url, utf8 } from "../crypto.js";
|
|
26
|
+
import {
|
|
27
|
+
CommentConflictError,
|
|
28
|
+
CommentForbiddenError,
|
|
29
|
+
CommentInputError,
|
|
30
|
+
CommentNotFoundError,
|
|
31
|
+
} from "../errors.js";
|
|
32
|
+
import {
|
|
33
|
+
commentRecordHash,
|
|
34
|
+
commentStateHash,
|
|
35
|
+
ID_PREFIX,
|
|
36
|
+
ipHmac,
|
|
37
|
+
newCommentsId,
|
|
38
|
+
openEmail,
|
|
39
|
+
openSecret,
|
|
40
|
+
sealSecret,
|
|
41
|
+
UNKNOWN_CLIENT,
|
|
42
|
+
} from "../hashes.js";
|
|
43
|
+
import {
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
HIDE_PAST_BATCH,
|
|
58
|
+
HIDE_PAST_BATCHES,
|
|
59
|
+
isPerson,
|
|
60
|
+
LABELS,
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
MAX_BULK,
|
|
64
|
+
MAX_LABELS,
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
NOTE_MAX,
|
|
69
|
+
num,
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
REASON_CODES,
|
|
73
|
+
RENDER_PAGE_SIZE,
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
utcMonth,
|
|
84
|
+
} from "../model.js";
|
|
85
|
+
import {
|
|
86
|
+
CONTRACT_FORBIDDEN,
|
|
87
|
+
checkName,
|
|
88
|
+
checkText,
|
|
89
|
+
normalizeName,
|
|
90
|
+
normalizeText,
|
|
91
|
+
} from "../normalize.js";
|
|
92
|
+
|
|
93
|
+
import {
|
|
94
|
+
COMMENTS_TAG_PREFIX,
|
|
95
|
+
commentsCacheTag,
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
purgeBackoffMs,
|
|
100
|
+
} from "../purge.js";
|
|
101
|
+
import {
|
|
102
|
+
PURGE_LOG_KEEP_MS,
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
} from "../retention.js";
|
|
107
|
+
import {
|
|
108
|
+
applySettingsInput,
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
defaultCommentSettings,
|
|
112
|
+
} from "../settings.js";
|
|
113
|
+
import {
|
|
114
|
+
|
|
115
|
+
SETTINGS_COLUMNS,
|
|
116
|
+
|
|
117
|
+
settingsValues,
|
|
118
|
+
toComment,
|
|
119
|
+
toSettings,
|
|
120
|
+
} from "./rows.js";
|
|
121
|
+
|
|
122
|
+
const COMMENT_ID = /^cmt_[A-Za-z0-9]{6,32}$/;
|
|
123
|
+
const PERSON_ID = /^user_[A-Za-z0-9]{6,32}$/;
|
|
124
|
+
const ERASED_AUTHOR = JSON.stringify({ kind: "erased" });
|
|
125
|
+
const json = (v ) => JSON.stringify(v);
|
|
126
|
+
|
|
127
|
+
/** Which statuses each action may move a comment from (RFC-0007 §4.2), and where to. */
|
|
128
|
+
const TRANSITIONS = {
|
|
129
|
+
approve: { from: ["pending", "hidden", "spam"], to: "approved" },
|
|
130
|
+
restore: { from: ["hidden", "spam"], to: "approved" },
|
|
131
|
+
hide: { from: ["pending", "approved", "spam"], to: "hidden" },
|
|
132
|
+
spam: { from: ["pending", "approved", "hidden"], to: "spam" },
|
|
133
|
+
hold: { from: ["approved", "hidden", "spam"], to: "pending" },
|
|
134
|
+
delete: { from: ["pending", "approved", "hidden", "spam"], to: "deleted" },
|
|
135
|
+
};
|
|
136
|
+
const NEEDS_REASON = ["hide", "spam", "delete"];
|
|
137
|
+
const PERSON_ONLY = ["approve", "restore", "delete"];
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
/** Thread write options: the purge the change needs (the caller knows the effective states). */
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
/** What `comments_summary` and Studio's "Today" read (RFC-0007 §11.1): counts, never reader text. */
|
|
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
|
+
function assertNote(note ) {
|
|
182
|
+
if (note === undefined) return;
|
|
183
|
+
if (typeof note !== "string" || note.length > NOTE_MAX || CONTRACT_FORBIDDEN.test(note))
|
|
184
|
+
throw new CommentInputError(`a note is plain text of at most ${NOTE_MAX} characters`);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function assertIds(ids ) {
|
|
188
|
+
if (!Array.isArray(ids) || ids.length === 0 || ids.length > MAX_BULK)
|
|
189
|
+
throw new CommentInputError(`between 1 and ${MAX_BULK} comment ids`);
|
|
190
|
+
if (new Set(ids).size !== ids.length) throw new CommentInputError("comment ids repeat");
|
|
191
|
+
for (const id of ids)
|
|
192
|
+
if (!COMMENT_ID.test(id))
|
|
193
|
+
throw new CommentInputError(`"${String(id).slice(0, 40)}" is not a comment id`);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const encodeCursor = (createdAt , id ) =>
|
|
197
|
+
toBase64Url(utf8(JSON.stringify([createdAt, id])));
|
|
198
|
+
|
|
199
|
+
function decodeCursor(cursor ) {
|
|
200
|
+
const bytes = fromBase64Url(cursor);
|
|
201
|
+
try {
|
|
202
|
+
const v = bytes ? (JSON.parse(new TextDecoder().decode(bytes)) ) : undefined;
|
|
203
|
+
if (Array.isArray(v) && v.length === 2 && typeof v[0] === "string" && typeof v[1] === "string")
|
|
204
|
+
return [v[0], v[1]];
|
|
205
|
+
} catch {
|
|
206
|
+
// fall through
|
|
207
|
+
}
|
|
208
|
+
throw new CommentInputError("invalid cursor");
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const auditStatements = (audit ) =>
|
|
212
|
+
(audit ?? []).map((a) => ({ sql: a.sql, params: (a.params ?? []) }));
|
|
213
|
+
|
|
214
|
+
export class SqlCommentStore {
|
|
215
|
+
sql ;
|
|
216
|
+
#now ;
|
|
217
|
+
|
|
218
|
+
constructor(sql , options = {}) {
|
|
219
|
+
this.sql = sql;
|
|
220
|
+
this.#now = options.now ?? (() => new Date());
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// ───────────────────────────── settings ─────────────────────────────
|
|
224
|
+
|
|
225
|
+
/** A site's settings: the stored row, or the defaults (`rev: 0`, comments off). */
|
|
226
|
+
async settings(siteId ) {
|
|
227
|
+
const row = await this.sql.get (
|
|
228
|
+
"SELECT * FROM comment_settings WHERE site_id = ?",
|
|
229
|
+
[siteId],
|
|
230
|
+
);
|
|
231
|
+
return row ? toSettings(row) : defaultCommentSettings(siteId);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* CAS on `rev` (one statement): `rev` 0 inserts the first row, later writes need the current
|
|
236
|
+
* `rev`. A stale `rev` throws `CommentConflictError` and changes nothing.
|
|
237
|
+
*/
|
|
238
|
+
async putSettings(
|
|
239
|
+
siteId ,
|
|
240
|
+
input ,
|
|
241
|
+
rev ,
|
|
242
|
+
by ,
|
|
243
|
+
) {
|
|
244
|
+
const before = await this.settings(siteId);
|
|
245
|
+
if (before.rev !== rev)
|
|
246
|
+
throw new CommentConflictError("comment settings changed somewhere else");
|
|
247
|
+
const next = applySettingsInput(before, input);
|
|
248
|
+
const stamp = this.#now().toISOString();
|
|
249
|
+
const values = settingsValues(next);
|
|
250
|
+
const res =
|
|
251
|
+
rev === 0
|
|
252
|
+
? await this.sql.run(
|
|
253
|
+
`INSERT INTO comment_settings (${SETTINGS_COLUMNS}, updated_at, updated_by, site_id, rev)
|
|
254
|
+
VALUES (${values.map(() => "?").join(", ")}, ?, ?, ?, 1) ON CONFLICT (site_id) DO NOTHING`,
|
|
255
|
+
[...values, stamp, by, siteId],
|
|
256
|
+
)
|
|
257
|
+
: await this.sql.run(
|
|
258
|
+
`UPDATE comment_settings SET ${SETTINGS_COLUMNS.split(", ")
|
|
259
|
+
.map((c) => `${c} = ?`)
|
|
260
|
+
.join(
|
|
261
|
+
", ",
|
|
262
|
+
)}, updated_at = ?, updated_by = ?, rev = rev + 1 WHERE site_id = ? AND rev = ?`,
|
|
263
|
+
[...values, stamp, by, siteId, rev],
|
|
264
|
+
);
|
|
265
|
+
if (res.changes !== 1)
|
|
266
|
+
throw new CommentConflictError("comment settings changed somewhere else");
|
|
267
|
+
return { before, after: { ...next, rev: rev + 1, updatedAt: stamp, updatedBy: by } };
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// ───────────────────────────── secrets ─────────────────────────────
|
|
271
|
+
|
|
272
|
+
/** Stores an owner-supplied secret, encrypted (write-only through the API). */
|
|
273
|
+
async putSecret(
|
|
274
|
+
siteId ,
|
|
275
|
+
name ,
|
|
276
|
+
value ,
|
|
277
|
+
keys ,
|
|
278
|
+
by ,
|
|
279
|
+
) {
|
|
280
|
+
if (!/^[a-z][a-z0-9-]{0,63}$/.test(name)) throw new CommentInputError("invalid secret name");
|
|
281
|
+
if (typeof value !== "string" || value.length === 0 || value.length > 4096)
|
|
282
|
+
throw new CommentInputError("a secret is 1 to 4,096 characters");
|
|
283
|
+
const sealed = await sealSecret(keys, siteId, name, value);
|
|
284
|
+
await this.sql.run(
|
|
285
|
+
`INSERT INTO comment_secrets (site_id, name, ciphertext, iv, updated_at, updated_by) VALUES (?, ?, ?, ?, ?, ?)
|
|
286
|
+
ON CONFLICT (site_id, name) DO UPDATE SET ciphertext = excluded.ciphertext, iv = excluded.iv, updated_at = excluded.updated_at, updated_by = excluded.updated_by`,
|
|
287
|
+
[siteId, name, sealed.ciphertext, sealed.iv, this.#now().toISOString(), by],
|
|
288
|
+
);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** The decrypted secret (site Worker only), or `null`. */
|
|
292
|
+
async readSecret(siteId , name , keys ) {
|
|
293
|
+
const row = await this.sql.get (
|
|
294
|
+
"SELECT ciphertext, iv FROM comment_secrets WHERE site_id = ? AND name = ?",
|
|
295
|
+
[siteId, name],
|
|
296
|
+
);
|
|
297
|
+
return row ? openSecret(keys, siteId, name, row) : null;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** Whether a secret is stored and when (Studio shows "Saved"), never its value. */
|
|
301
|
+
async secretInfo(
|
|
302
|
+
siteId ,
|
|
303
|
+
name ,
|
|
304
|
+
) {
|
|
305
|
+
const row = await this.sql.get (
|
|
306
|
+
"SELECT updated_at, updated_by FROM comment_secrets WHERE site_id = ? AND name = ?",
|
|
307
|
+
[siteId, name],
|
|
308
|
+
);
|
|
309
|
+
return row ? { updatedAt: row.updated_at, updatedBy: row.updated_by } : null;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
async deleteSecret(siteId , name ) {
|
|
313
|
+
return (
|
|
314
|
+
(
|
|
315
|
+
await this.sql.run("DELETE FROM comment_secrets WHERE site_id = ? AND name = ?", [
|
|
316
|
+
siteId,
|
|
317
|
+
name,
|
|
318
|
+
])
|
|
319
|
+
).changes === 1
|
|
320
|
+
);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// ───────────────────────────── threads ─────────────────────────────
|
|
324
|
+
|
|
325
|
+
async thread(siteId , nodeId ) {
|
|
326
|
+
const r = await this.sql.get (
|
|
327
|
+
"SELECT * FROM comment_threads WHERE site_id = ? AND node_id = ?",
|
|
328
|
+
[siteId, nodeId],
|
|
329
|
+
);
|
|
330
|
+
if (!r) return null;
|
|
331
|
+
return {
|
|
332
|
+
siteId,
|
|
333
|
+
nodeId,
|
|
334
|
+
mode: String(r.mode) ,
|
|
335
|
+
closesAt: r.closes_at === null ? null : String(r.closes_at),
|
|
336
|
+
rev: num(r.rev),
|
|
337
|
+
updatedAt: String(r.updated_at),
|
|
338
|
+
updatedBy: String(r.updated_by),
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* Sets an entry's thread override with CAS on `rev` (`0` when no row exists). The purge row the
|
|
344
|
+
* change needs (`options.purge`, default `normal`; `hidden` should pass `takedown`) is upserted
|
|
345
|
+
* in the same batch, guarded on what the CAS wrote.
|
|
346
|
+
*/
|
|
347
|
+
async putThread(
|
|
348
|
+
siteId ,
|
|
349
|
+
nodeId ,
|
|
350
|
+
input ,
|
|
351
|
+
rev ,
|
|
352
|
+
by ,
|
|
353
|
+
options = {},
|
|
354
|
+
) {
|
|
355
|
+
if (!["default", "open", "closed", "hidden"].includes(input.mode))
|
|
356
|
+
throw new CommentInputError("mode must be default, open, closed or hidden");
|
|
357
|
+
if (
|
|
358
|
+
input.closesAt !== undefined &&
|
|
359
|
+
input.closesAt !== null &&
|
|
360
|
+
Number.isNaN(Date.parse(input.closesAt))
|
|
361
|
+
)
|
|
362
|
+
throw new CommentInputError("closesAt must be an ISO timestamp or null");
|
|
363
|
+
const current = await this.thread(siteId, nodeId);
|
|
364
|
+
if ((current?.rev ?? 0) !== rev)
|
|
365
|
+
throw new CommentConflictError("the thread changed somewhere else");
|
|
366
|
+
const closesAt =
|
|
367
|
+
input.closesAt === undefined
|
|
368
|
+
? (current?.closesAt ?? null)
|
|
369
|
+
: input.closesAt === null
|
|
370
|
+
? null
|
|
371
|
+
: new Date(input.closesAt).toISOString();
|
|
372
|
+
const stamp = this.#now().toISOString();
|
|
373
|
+
const write =
|
|
374
|
+
rev === 0
|
|
375
|
+
? {
|
|
376
|
+
sql: "INSERT INTO comment_threads (site_id, node_id, mode, closes_at, rev, updated_at, updated_by) VALUES (?, ?, ?, ?, 1, ?, ?) ON CONFLICT (site_id, node_id) DO NOTHING",
|
|
377
|
+
params: [siteId, nodeId, input.mode, closesAt, stamp, by],
|
|
378
|
+
}
|
|
379
|
+
: {
|
|
380
|
+
sql: "UPDATE comment_threads SET mode = ?, closes_at = ?, rev = rev + 1, updated_at = ?, updated_by = ? WHERE site_id = ? AND node_id = ? AND rev = ?",
|
|
381
|
+
params: [input.mode, closesAt, stamp, by, siteId, nodeId, rev],
|
|
382
|
+
};
|
|
383
|
+
const guard =
|
|
384
|
+
"EXISTS (SELECT 1 FROM comment_threads WHERE site_id = ? AND node_id = ? AND rev = ? AND updated_at = ? AND updated_by = ? AND mode = ?)";
|
|
385
|
+
const guardParams = [siteId, nodeId, rev + 1, stamp, by, input.mode];
|
|
386
|
+
const purge = options.purge === undefined ? "normal" : options.purge;
|
|
387
|
+
const statements = [write];
|
|
388
|
+
if (purge)
|
|
389
|
+
statements.push(
|
|
390
|
+
this.#purgeUpsert(siteId, [commentsCacheTag(nodeId)], purge, stamp, guard, guardParams),
|
|
391
|
+
);
|
|
392
|
+
statements.push(...auditStatements(options.audit));
|
|
393
|
+
const [res] = await this.sql.batch(statements);
|
|
394
|
+
if (res?.changes !== 1) throw new CommentConflictError("the thread changed somewhere else");
|
|
395
|
+
return {
|
|
396
|
+
siteId,
|
|
397
|
+
nodeId,
|
|
398
|
+
mode: input.mode,
|
|
399
|
+
closesAt,
|
|
400
|
+
rev: rev + 1,
|
|
401
|
+
updatedAt: stamp,
|
|
402
|
+
updatedBy: by,
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
// ───────────────────────────── pipeline reads ─────────────────────────────
|
|
407
|
+
|
|
408
|
+
async approvedComment(siteId , commentId ) {
|
|
409
|
+
if (!COMMENT_ID.test(commentId)) return null;
|
|
410
|
+
const r = await this.sql.get (
|
|
411
|
+
"SELECT id, node_id, parent_id FROM comments WHERE id = ? AND site_id = ? AND status = 'approved'",
|
|
412
|
+
[commentId, siteId],
|
|
413
|
+
);
|
|
414
|
+
return r ? { id: r.id, nodeId: r.node_id, parentId: r.parent_id } : null;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
async readSalt(month ) {
|
|
418
|
+
const r = await this.sql.get (
|
|
419
|
+
"SELECT salt FROM comment_salts WHERE month = ?",
|
|
420
|
+
[month],
|
|
421
|
+
);
|
|
422
|
+
return r?.salt;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
async clientActivity(
|
|
426
|
+
siteId ,
|
|
427
|
+
ipHmac ,
|
|
428
|
+
since ,
|
|
429
|
+
) {
|
|
430
|
+
const r = await this.sql.get (
|
|
431
|
+
`SELECT COUNT(*) AS day,
|
|
432
|
+
COALESCE(SUM(created_at >= ?), 0) AS hour,
|
|
433
|
+
COALESCE(SUM(proof = 'none' AND created_at >= ?), 0) AS no_script
|
|
434
|
+
FROM comments WHERE site_id = ? AND ip_hmac = ? AND created_at >= ?`,
|
|
435
|
+
[since.hour, since.noScript, siteId, ipHmac, since.day],
|
|
436
|
+
);
|
|
437
|
+
return { hour: num(r?.hour), day: num(r?.day), noScript: num(r?.no_script) };
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
async isDuplicate(siteId , nodeId , text , since ) {
|
|
441
|
+
const r = await this.sql.get(
|
|
442
|
+
`SELECT 1 AS hit FROM (SELECT body FROM comments WHERE site_id = ? AND node_id = ? AND created_at >= ?
|
|
443
|
+
ORDER BY created_at DESC LIMIT 200) WHERE body = ? LIMIT 1`,
|
|
444
|
+
[siteId, nodeId, since, text],
|
|
445
|
+
);
|
|
446
|
+
return r !== undefined;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
async storedSince(
|
|
450
|
+
siteId ,
|
|
451
|
+
since ,
|
|
452
|
+
) {
|
|
453
|
+
const r = await this.sql.get (
|
|
454
|
+
`SELECT COUNT(*) AS total, COALESCE(SUM(proof = 'none'), 0) AS no_script FROM comments
|
|
455
|
+
WHERE site_id = ? AND created_at >= ? AND proof IN ('pow', 'turnstile', 'none')`,
|
|
456
|
+
[siteId, since],
|
|
457
|
+
);
|
|
458
|
+
return { total: num(r?.total), withoutScript: num(r?.no_script) };
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
async pendingOnEntry(siteId , nodeId ) {
|
|
462
|
+
const r = await this.sql.get (
|
|
463
|
+
"SELECT COUNT(*) AS n FROM comments WHERE site_id = ? AND node_id = ? AND status = 'pending'",
|
|
464
|
+
[siteId, nodeId],
|
|
465
|
+
);
|
|
466
|
+
return num(r?.n);
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
async isBanned(
|
|
470
|
+
siteId ,
|
|
471
|
+
subjects ,
|
|
472
|
+
now ,
|
|
473
|
+
) {
|
|
474
|
+
if (!subjects.emailHmac && !subjects.ipHmac) return false;
|
|
475
|
+
const r = await this.sql.get(
|
|
476
|
+
`SELECT 1 AS hit FROM comment_bans WHERE site_id = ?
|
|
477
|
+
AND ((subject = 'email' AND value = ?) OR (subject = 'ip' AND value = ?))
|
|
478
|
+
AND (until IS NULL OR until > ?) LIMIT 1`,
|
|
479
|
+
[siteId, subjects.emailHmac ?? null, subjects.ipHmac ?? null, now],
|
|
480
|
+
);
|
|
481
|
+
return r !== undefined;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
async reportActivity(
|
|
485
|
+
siteId ,
|
|
486
|
+
ipHmac ,
|
|
487
|
+
since ,
|
|
488
|
+
) {
|
|
489
|
+
// the site count is "since 00:00 UTC", the client count "in the last hour"
|
|
490
|
+
const r = await this.sql.get (
|
|
491
|
+
`SELECT COALESCE(SUM(created_at >= ?), 0) AS site_day, COALESCE(SUM(ip_hmac = ? AND created_at >= ?), 0) AS client_hour
|
|
492
|
+
FROM comment_reports WHERE site_id = ? AND created_at >= ?`,
|
|
493
|
+
[since.day, ipHmac, since.hour, siteId, since.day < since.hour ? since.day : since.hour],
|
|
494
|
+
);
|
|
495
|
+
return { clientHour: num(r?.client_hour), siteDay: num(r?.site_day) };
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
// ───────────────────────────── submissions ─────────────────────────────
|
|
499
|
+
|
|
500
|
+
#saltStatements(
|
|
501
|
+
salt ,
|
|
502
|
+
at ,
|
|
503
|
+
) {
|
|
504
|
+
if (!salt) return { pre: [], guard: "", params: [] };
|
|
505
|
+
return {
|
|
506
|
+
pre: [
|
|
507
|
+
{
|
|
508
|
+
sql: "INSERT OR IGNORE INTO comment_salts (month, salt, created_at) VALUES (?, ?, ?)",
|
|
509
|
+
params: [salt.month, salt.salt, at],
|
|
510
|
+
},
|
|
511
|
+
],
|
|
512
|
+
guard: " AND EXISTS (SELECT 1 FROM comment_salts WHERE month = ? AND salt = ?)",
|
|
513
|
+
params: [salt.month, salt.salt],
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
async #afterIgnoredInsert(salt ) {
|
|
518
|
+
if (salt && (await this.readSalt(salt.month)) !== salt.salt) return { saltConflict: true };
|
|
519
|
+
return { duplicate: true };
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/**
|
|
523
|
+
* Stores a guest comment (§6.2 step 12) in one batch: the commenter email row when given
|
|
524
|
+
* (`INSERT OR IGNORE`, one row per address and site) and the comment, whose `email_id` comes from
|
|
525
|
+
* a sub-select. A replayed challenge hits the unique index on `challenge_id` and is answered
|
|
526
|
+
* `{ duplicate: true }` with nothing written.
|
|
527
|
+
*/
|
|
528
|
+
async submit(siteId , p ) {
|
|
529
|
+
if (!COMMENT_ID.test(p.id)) throw new CommentInputError("invalid comment id");
|
|
530
|
+
const record = {
|
|
531
|
+
schemaVersion: 1,
|
|
532
|
+
id: p.id,
|
|
533
|
+
siteId,
|
|
534
|
+
nodeId: p.nodeId,
|
|
535
|
+
...(p.parentId ? { parentId: p.parentId } : {}),
|
|
536
|
+
...(p.inReplyToId ? { inReplyToId: p.inReplyToId } : {}),
|
|
537
|
+
source: "native",
|
|
538
|
+
author: { kind: "guest", name: p.name },
|
|
539
|
+
body: { format: "text", text: p.text },
|
|
540
|
+
status: p.status,
|
|
541
|
+
...(p.labels.length > 0 ? { labels: [...p.labels] } : {}),
|
|
542
|
+
...(p.moderation ? { moderation: p.moderation } : {}),
|
|
543
|
+
createdAt: p.createdAt,
|
|
544
|
+
rev: 1,
|
|
545
|
+
};
|
|
546
|
+
const hash = await commentRecordHash(record);
|
|
547
|
+
const salt = this.#saltStatements(p.newSalt, p.createdAt);
|
|
548
|
+
const statements = [...salt.pre];
|
|
549
|
+
if (p.email)
|
|
550
|
+
statements.push(this.#emailInsert(siteId, p.email, p.createdAt, "comments", p.challengeId));
|
|
551
|
+
statements.push({
|
|
552
|
+
sql: `INSERT OR IGNORE INTO comments (id, site_id, node_id, parent_id, in_reply_to_id, source, origin, author, body, status, labels, moderation, email_id, ip_hmac, challenge_id, proof, op, hash, created_at, edited_at, rev)
|
|
553
|
+
SELECT ?, ?, ?, ?, ?, 'native', NULL, ?, ?, ?, ?, ?, ${p.email ? "(SELECT id FROM commenter_emails WHERE site_id = ? AND email_hmac = ?)" : "NULL"}, ?, ?, ?, NULL, ?, ?, NULL, 1
|
|
554
|
+
WHERE 1 = 1${salt.guard}`,
|
|
555
|
+
params: [
|
|
556
|
+
p.id,
|
|
557
|
+
siteId,
|
|
558
|
+
p.nodeId,
|
|
559
|
+
p.parentId ?? null,
|
|
560
|
+
p.inReplyToId ?? null,
|
|
561
|
+
json(record.author),
|
|
562
|
+
p.text,
|
|
563
|
+
p.status,
|
|
564
|
+
json(p.labels),
|
|
565
|
+
p.moderation ? json(p.moderation) : null,
|
|
566
|
+
...(p.email ? [siteId, p.email.hmac] : []),
|
|
567
|
+
p.ipHmac,
|
|
568
|
+
p.challengeId,
|
|
569
|
+
p.proof,
|
|
570
|
+
hash,
|
|
571
|
+
p.createdAt,
|
|
572
|
+
...salt.params,
|
|
573
|
+
],
|
|
574
|
+
});
|
|
575
|
+
const results = await this.sql.batch(statements);
|
|
576
|
+
if (results.at(-1)?.changes !== 1) return this.#afterIgnoredInsert(p.newSalt);
|
|
577
|
+
return { id: p.id };
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
#emailInsert(
|
|
581
|
+
siteId ,
|
|
582
|
+
e ,
|
|
583
|
+
at ,
|
|
584
|
+
table ,
|
|
585
|
+
challengeId ,
|
|
586
|
+
) {
|
|
587
|
+
// a replayed challenge must not leave an email row behind
|
|
588
|
+
const guard = challengeId
|
|
589
|
+
? ` WHERE NOT EXISTS (SELECT 1 FROM ${table} WHERE challenge_id = ?)`
|
|
590
|
+
: "";
|
|
591
|
+
return {
|
|
592
|
+
sql: `INSERT OR IGNORE INTO commenter_emails (id, site_id, email_hmac, email_ciphertext, email_iv, created_at) SELECT ?, ?, ?, ?, ?, ?${guard}`,
|
|
593
|
+
params: [e.id, siteId, e.hmac, e.ciphertext, e.iv, at, ...(challengeId ? [challengeId] : [])],
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/** Stores a report (§6.6) of a comment that is still approved; a report never changes it. */
|
|
598
|
+
async report(siteId , p ) {
|
|
599
|
+
const salt = this.#saltStatements(p.newSalt, p.createdAt);
|
|
600
|
+
const statements = [...salt.pre];
|
|
601
|
+
if (p.email)
|
|
602
|
+
statements.push(
|
|
603
|
+
this.#emailInsert(siteId, p.email, p.createdAt, "comment_reports", p.challengeId),
|
|
604
|
+
);
|
|
605
|
+
statements.push({
|
|
606
|
+
sql: `INSERT OR IGNORE INTO comment_reports (id, site_id, comment_id, reason, details, email_id, ip_hmac, challenge_id, created_at)
|
|
607
|
+
SELECT ?, ?, ?, ?, ?, ${p.email ? "(SELECT id FROM commenter_emails WHERE site_id = ? AND email_hmac = ?)" : "NULL"}, ?, ?, ?
|
|
608
|
+
WHERE EXISTS (SELECT 1 FROM comments WHERE id = ? AND site_id = ? AND status = 'approved')${salt.guard}`,
|
|
609
|
+
params: [
|
|
610
|
+
p.id,
|
|
611
|
+
siteId,
|
|
612
|
+
p.commentId,
|
|
613
|
+
p.reason,
|
|
614
|
+
p.details,
|
|
615
|
+
...(p.email ? [siteId, p.email.hmac] : []),
|
|
616
|
+
p.ipHmac,
|
|
617
|
+
p.challengeId,
|
|
618
|
+
p.createdAt,
|
|
619
|
+
p.commentId,
|
|
620
|
+
siteId,
|
|
621
|
+
...salt.params,
|
|
622
|
+
],
|
|
623
|
+
});
|
|
624
|
+
const results = await this.sql.batch(statements);
|
|
625
|
+
if (results.at(-1)?.changes !== 1) return this.#afterIgnoredInsert(p.newSalt);
|
|
626
|
+
return { id: p.id };
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
// ───────────────────────────── reads ─────────────────────────────
|
|
630
|
+
|
|
631
|
+
async get(siteId , id ) {
|
|
632
|
+
if (!COMMENT_ID.test(id)) return null;
|
|
633
|
+
const r = await this.sql.get (
|
|
634
|
+
"SELECT * FROM comments WHERE id = ? AND site_id = ?",
|
|
635
|
+
[id, siteId],
|
|
636
|
+
);
|
|
637
|
+
return r ? toComment(r) : null;
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/** Several comments of a site in one read (≤ 50 ids; unknown ids are left out). */
|
|
641
|
+
async getMany(siteId , ids ) {
|
|
642
|
+
if (ids.length === 0) return [];
|
|
643
|
+
if (ids.length > MAX_BULK) throw new CommentInputError(`at most ${MAX_BULK} comment ids`);
|
|
644
|
+
const rows = await this.#rows(
|
|
645
|
+
siteId,
|
|
646
|
+
ids.filter((id) => COMMENT_ID.test(id)),
|
|
647
|
+
);
|
|
648
|
+
return ids.flatMap((id) => {
|
|
649
|
+
const r = rows.get(id);
|
|
650
|
+
return r ? [toComment(r)] : [];
|
|
651
|
+
});
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
async #rows(siteId , ids ) {
|
|
655
|
+
const rows = await this.sql.all (
|
|
656
|
+
"SELECT * FROM comments WHERE site_id = ? AND id IN (SELECT value FROM json_each(?))",
|
|
657
|
+
[siteId, json(ids)],
|
|
658
|
+
);
|
|
659
|
+
return new Map(rows.map((r) => [r.id, r]));
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
/** Comments of a site, newest first by default, keyset-paginated (§11.1 `list_comments`). */
|
|
663
|
+
async list(
|
|
664
|
+
siteId ,
|
|
665
|
+
q = {},
|
|
666
|
+
) {
|
|
667
|
+
const limit = q.limit ?? 20;
|
|
668
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 50)
|
|
669
|
+
throw new CommentInputError("limit must be 1 to 50");
|
|
670
|
+
const where = ["site_id = ?"];
|
|
671
|
+
const params = [siteId];
|
|
672
|
+
if (q.status === "reported") {
|
|
673
|
+
where.push(
|
|
674
|
+
"EXISTS (SELECT 1 FROM comment_reports r WHERE r.comment_id = comments.id AND r.resolved_at IS NULL)",
|
|
675
|
+
);
|
|
676
|
+
} else if (q.status !== undefined) {
|
|
677
|
+
if (!["pending", "approved", "hidden", "spam", "deleted"].includes(q.status))
|
|
678
|
+
throw new CommentInputError("unknown status");
|
|
679
|
+
where.push("status = ?");
|
|
680
|
+
params.push(q.status);
|
|
681
|
+
}
|
|
682
|
+
if (q.nodeId !== undefined) {
|
|
683
|
+
where.push("node_id = ?");
|
|
684
|
+
params.push(q.nodeId);
|
|
685
|
+
}
|
|
686
|
+
if (q.nodeIds !== undefined) {
|
|
687
|
+
where.push("node_id IN (SELECT value FROM json_each(?))");
|
|
688
|
+
params.push(json(q.nodeIds));
|
|
689
|
+
}
|
|
690
|
+
if (q.label !== undefined) {
|
|
691
|
+
if (!(LABELS ).includes(q.label))
|
|
692
|
+
throw new CommentInputError("unknown label");
|
|
693
|
+
where.push(
|
|
694
|
+
"EXISTS (SELECT 1 FROM json_each(comments.labels) l WHERE json_extract(l.value, '$.label') = ?)",
|
|
695
|
+
);
|
|
696
|
+
params.push(q.label);
|
|
697
|
+
}
|
|
698
|
+
if (q.since !== undefined) {
|
|
699
|
+
where.push("created_at >= ?");
|
|
700
|
+
params.push(q.since);
|
|
701
|
+
}
|
|
702
|
+
const newest = (q.order ?? "newest") === "newest";
|
|
703
|
+
if (q.cursor !== undefined) {
|
|
704
|
+
const [c, id] = decodeCursor(q.cursor);
|
|
705
|
+
where.push(
|
|
706
|
+
newest
|
|
707
|
+
? "(created_at < ? OR (created_at = ? AND id < ?))"
|
|
708
|
+
: "(created_at > ? OR (created_at = ? AND id > ?))",
|
|
709
|
+
);
|
|
710
|
+
params.push(c, c, id);
|
|
711
|
+
}
|
|
712
|
+
const dir = newest ? "DESC" : "ASC";
|
|
713
|
+
const rows = await this.sql.all (
|
|
714
|
+
`SELECT * FROM comments WHERE ${where.join(" AND ")} ORDER BY created_at ${dir}, id ${dir} LIMIT ?`,
|
|
715
|
+
[...params, limit + 1],
|
|
716
|
+
);
|
|
717
|
+
const page = rows.slice(0, limit);
|
|
718
|
+
const last = page.at(-1);
|
|
719
|
+
return {
|
|
720
|
+
comments: page.map(toComment),
|
|
721
|
+
...(rows.length > limit && last
|
|
722
|
+
? { nextCursor: encodeCursor(last.created_at, last.id) }
|
|
723
|
+
: {}),
|
|
724
|
+
};
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/** A thread in display order (§4.3): top-level oldest first, each followed by its replies. */
|
|
728
|
+
async threadComments(
|
|
729
|
+
siteId ,
|
|
730
|
+
nodeId ,
|
|
731
|
+
options = {},
|
|
732
|
+
) {
|
|
733
|
+
const statuses =
|
|
734
|
+
options.includePending === false
|
|
735
|
+
? ["approved"]
|
|
736
|
+
: ["pending", "approved", "hidden", "spam", "deleted"];
|
|
737
|
+
const rows = await this.sql.all (
|
|
738
|
+
`SELECT * FROM comments WHERE site_id = ? AND node_id = ? AND status IN (SELECT value FROM json_each(?)) ORDER BY created_at, id LIMIT 1000`,
|
|
739
|
+
[siteId, nodeId, json(statuses)],
|
|
740
|
+
);
|
|
741
|
+
const top = rows.filter((r) => !r.parent_id);
|
|
742
|
+
const byParent = new Map ();
|
|
743
|
+
for (const r of rows)
|
|
744
|
+
if (r.parent_id) byParent.set(r.parent_id, [...(byParent.get(r.parent_id) ?? []), r]);
|
|
745
|
+
const out = [];
|
|
746
|
+
const placed = new Set ();
|
|
747
|
+
for (const t of top) {
|
|
748
|
+
out.push(toComment(t));
|
|
749
|
+
placed.add(t.id);
|
|
750
|
+
for (const r of byParent.get(t.id) ?? []) {
|
|
751
|
+
out.push(toComment(r));
|
|
752
|
+
placed.add(r.id);
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
for (const r of rows) if (!placed.has(r.id)) out.push(toComment(r)); // replies whose parent left
|
|
756
|
+
return out;
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
/**
|
|
760
|
+
* One rendered page of approved comments (§8.1): up to 50 top-level comments, oldest first, with
|
|
761
|
+
* their approved replies. A top-level comment that is no longer public but has approved replies
|
|
762
|
+
* renders as "removed". `page` past the end returns no items (the renderer answers 404).
|
|
763
|
+
*/
|
|
764
|
+
async renderPage(siteId , nodeId , page = 1) {
|
|
765
|
+
if (!Number.isInteger(page) || page < 1) throw new CommentInputError("page must be 1 or more");
|
|
766
|
+
const visibleTop = `parent_id IS NULL AND (status = 'approved' OR EXISTS (SELECT 1 FROM comments r WHERE r.parent_id = c.id AND r.status = 'approved'))`;
|
|
767
|
+
const counts = await this.sql.get (
|
|
768
|
+
`SELECT (SELECT COUNT(*) FROM comments WHERE site_id = ? AND node_id = ? AND status = 'approved') AS total,
|
|
769
|
+
(SELECT COUNT(*) FROM comments c WHERE c.site_id = ? AND c.node_id = ? AND ${visibleTop}) AS tops`,
|
|
770
|
+
[siteId, nodeId, siteId, nodeId],
|
|
771
|
+
);
|
|
772
|
+
const total = num(counts?.total);
|
|
773
|
+
const pageCount = Math.max(1, Math.ceil(num(counts?.tops) / RENDER_PAGE_SIZE));
|
|
774
|
+
if (page > pageCount) return { items: [], total, page, pageCount };
|
|
775
|
+
const tops = await this.sql.all (
|
|
776
|
+
`SELECT * FROM comments c WHERE c.site_id = ? AND c.node_id = ? AND ${visibleTop} ORDER BY c.created_at, c.id LIMIT ? OFFSET ?`,
|
|
777
|
+
[siteId, nodeId, RENDER_PAGE_SIZE, (page - 1) * RENDER_PAGE_SIZE],
|
|
778
|
+
);
|
|
779
|
+
const replies =
|
|
780
|
+
tops.length === 0
|
|
781
|
+
? []
|
|
782
|
+
: await this.sql.all (
|
|
783
|
+
`SELECT * FROM comments WHERE site_id = ? AND node_id = ? AND status = 'approved' AND parent_id IN (SELECT value FROM json_each(?)) ORDER BY created_at, id`,
|
|
784
|
+
[siteId, nodeId, json(tops.map((t) => t.id))],
|
|
785
|
+
);
|
|
786
|
+
const items = tops.map((t) => {
|
|
787
|
+
const rs = replies.filter((r) => r.parent_id === t.id).map(toComment);
|
|
788
|
+
return t.status === "approved"
|
|
789
|
+
? { comment: toComment(t), replies: rs }
|
|
790
|
+
: { removed: { id: t.id, createdAt: t.created_at }, replies: rs };
|
|
791
|
+
});
|
|
792
|
+
return { items, total, page, pageCount };
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
/** Counts by status and open reports, optionally for some entries (indexed COUNTs). */
|
|
796
|
+
async counts(siteId , q = {}) {
|
|
797
|
+
const where = ["site_id = ?"];
|
|
798
|
+
const params = [siteId];
|
|
799
|
+
if (q.nodeId !== undefined) {
|
|
800
|
+
where.push("node_id = ?");
|
|
801
|
+
params.push(q.nodeId);
|
|
802
|
+
}
|
|
803
|
+
if (q.nodeIds !== undefined) {
|
|
804
|
+
where.push("node_id IN (SELECT value FROM json_each(?))");
|
|
805
|
+
params.push(json(q.nodeIds));
|
|
806
|
+
}
|
|
807
|
+
const rows = await this.sql.all (
|
|
808
|
+
`SELECT status, COUNT(*) AS n FROM comments WHERE ${where.join(" AND ")} GROUP BY status`,
|
|
809
|
+
params,
|
|
810
|
+
);
|
|
811
|
+
const reported = await this.sql.get (
|
|
812
|
+
`SELECT COUNT(DISTINCT r.comment_id) AS n FROM comment_reports r JOIN comments c ON c.id = r.comment_id
|
|
813
|
+
WHERE r.site_id = ? AND r.resolved_at IS NULL AND c.${where.join(" AND c.")}`,
|
|
814
|
+
[siteId, ...params],
|
|
815
|
+
);
|
|
816
|
+
const out = {
|
|
817
|
+
pending: 0,
|
|
818
|
+
approved: 0,
|
|
819
|
+
hidden: 0,
|
|
820
|
+
spam: 0,
|
|
821
|
+
deleted: 0,
|
|
822
|
+
reported: num(reported?.n),
|
|
823
|
+
};
|
|
824
|
+
for (const r of rows) if (r.status in out) out[r.status ] = num(r.n);
|
|
825
|
+
return out;
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
/** Entries of a site that have comments (the hourly job looks for deleted entries among them). */
|
|
829
|
+
async nodeIds(siteId ) {
|
|
830
|
+
const rows = await this.sql.all (
|
|
831
|
+
"SELECT DISTINCT node_id FROM comments WHERE site_id = ? ORDER BY node_id",
|
|
832
|
+
[siteId],
|
|
833
|
+
);
|
|
834
|
+
return rows.map((r) => r.node_id);
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
/** Every thread override of a site (the hourly job computes closing times from them). */
|
|
838
|
+
async threads(siteId ) {
|
|
839
|
+
const rows = await this.sql.all (
|
|
840
|
+
"SELECT * FROM comment_threads WHERE site_id = ? ORDER BY node_id",
|
|
841
|
+
[siteId],
|
|
842
|
+
);
|
|
843
|
+
return rows.map((r) => ({
|
|
844
|
+
siteId,
|
|
845
|
+
nodeId: String(r.node_id),
|
|
846
|
+
mode: String(r.mode) ,
|
|
847
|
+
closesAt: r.closes_at === null ? null : String(r.closes_at),
|
|
848
|
+
rev: num(r.rev),
|
|
849
|
+
updatedAt: String(r.updated_at),
|
|
850
|
+
updatedBy: String(r.updated_by),
|
|
851
|
+
}));
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
/**
|
|
855
|
+
* Activity since `since` for summaries (RFC-0007 §11.1 `comments_summary`): five indexed reads,
|
|
856
|
+
* counts only. `nodeIds` limits it to some entries (an Author's own).
|
|
857
|
+
*/
|
|
858
|
+
async summary(
|
|
859
|
+
siteId ,
|
|
860
|
+
since ,
|
|
861
|
+
q = {},
|
|
862
|
+
) {
|
|
863
|
+
const scope = q.nodeIds ? " AND c.node_id IN (SELECT value FROM json_each(?))" : "";
|
|
864
|
+
const scopeParams = q.nodeIds ? [json(q.nodeIds)] : [];
|
|
865
|
+
const guest = "c.proof IN ('pow', 'turnstile', 'none', 'import')";
|
|
866
|
+
const busiest = await this.sql.all (
|
|
867
|
+
`SELECT c.node_id, COUNT(*) AS n FROM comments c WHERE c.site_id = ? AND c.created_at >= ? AND ${guest}${scope}
|
|
868
|
+
GROUP BY c.node_id ORDER BY n DESC, c.node_id LIMIT 10`,
|
|
869
|
+
[siteId, since, ...scopeParams],
|
|
870
|
+
);
|
|
871
|
+
const total = await this.sql.get (
|
|
872
|
+
`SELECT COUNT(*) AS n FROM comments c WHERE c.site_id = ? AND c.created_at >= ? AND ${guest}${scope}`,
|
|
873
|
+
[siteId, since, ...scopeParams],
|
|
874
|
+
);
|
|
875
|
+
const labels = await this.sql.all (
|
|
876
|
+
`SELECT json_extract(l.value, '$.label') AS label, COUNT(*) AS n FROM comments c, json_each(c.labels) l
|
|
877
|
+
WHERE c.site_id = ? AND c.created_at >= ?${scope} GROUP BY label ORDER BY label`,
|
|
878
|
+
[siteId, since, ...scopeParams],
|
|
879
|
+
);
|
|
880
|
+
const pending = await this.sql.get (
|
|
881
|
+
`SELECT COUNT(*) AS n, MIN(c.created_at) AS oldest FROM comments c WHERE c.site_id = ? AND c.status = 'pending'${scope}`,
|
|
882
|
+
[siteId, ...scopeParams],
|
|
883
|
+
);
|
|
884
|
+
const n = num(pending?.n);
|
|
885
|
+
const median =
|
|
886
|
+
n === 0
|
|
887
|
+
? undefined
|
|
888
|
+
: await this.sql.get (
|
|
889
|
+
`SELECT c.created_at FROM comments c WHERE c.site_id = ? AND c.status = 'pending'${scope}
|
|
890
|
+
ORDER BY c.created_at LIMIT 1 OFFSET ?`,
|
|
891
|
+
[siteId, ...scopeParams, Math.floor((n - 1) / 2)],
|
|
892
|
+
);
|
|
893
|
+
const unanswered = await this.sql.get (
|
|
894
|
+
`SELECT COUNT(*) AS n FROM comments c WHERE c.site_id = ? AND c.created_at >= ? AND c.status IN ('pending', 'approved')${scope}
|
|
895
|
+
AND EXISTS (SELECT 1 FROM json_each(c.labels) l WHERE json_extract(l.value, '$.label') IN ('question', 'needs-reply'))
|
|
896
|
+
AND NOT EXISTS (SELECT 1 FROM comments r WHERE r.site_id = c.site_id AND r.proof = 'staff'
|
|
897
|
+
AND (r.in_reply_to_id = c.id OR (r.parent_id = c.id AND r.in_reply_to_id IS NULL)))`,
|
|
898
|
+
[siteId, since, ...scopeParams],
|
|
899
|
+
);
|
|
900
|
+
const labelCounts = {};
|
|
901
|
+
for (const l of labels)
|
|
902
|
+
if ((LABELS ).includes(l.label))
|
|
903
|
+
labelCounts[l.label ] = num(l.n);
|
|
904
|
+
return {
|
|
905
|
+
newComments: num(total?.n),
|
|
906
|
+
busiest: busiest.map((b) => ({ nodeId: b.node_id, comments: num(b.n) })),
|
|
907
|
+
labels: labelCounts,
|
|
908
|
+
pending: {
|
|
909
|
+
count: n,
|
|
910
|
+
oldestAt: pending?.oldest ?? null,
|
|
911
|
+
medianAt: median?.created_at ?? null,
|
|
912
|
+
},
|
|
913
|
+
unansweredQuestions: num(unanswered?.n),
|
|
914
|
+
};
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
/** The `cm1:` binding of an approval to these comments and threads (§10.3). */
|
|
918
|
+
async stateHash(
|
|
919
|
+
siteId ,
|
|
920
|
+
ids ,
|
|
921
|
+
threads ,
|
|
922
|
+
) {
|
|
923
|
+
const rows = await this.#rows(siteId, ids);
|
|
924
|
+
const threadRevs = new Map ();
|
|
925
|
+
if (threads.length > 0) {
|
|
926
|
+
const tr = await this.sql.all (
|
|
927
|
+
"SELECT node_id, rev FROM comment_threads WHERE site_id = ? AND node_id IN (SELECT value FROM json_each(?))",
|
|
928
|
+
[siteId, json(threads.map((t) => t.nodeId))],
|
|
929
|
+
);
|
|
930
|
+
for (const t of tr) threadRevs.set(t.node_id, num(t.rev));
|
|
931
|
+
}
|
|
932
|
+
return commentStateHash({
|
|
933
|
+
comments: ids.map((id) => {
|
|
934
|
+
const r = rows.get(id);
|
|
935
|
+
return r
|
|
936
|
+
? { id, rev: num(r.rev), status: r.status }
|
|
937
|
+
: { id, rev: 0, status: "missing" };
|
|
938
|
+
}),
|
|
939
|
+
threads: threads.map((t) => ({
|
|
940
|
+
nodeId: t.nodeId,
|
|
941
|
+
rev: threadRevs.get(t.nodeId) ?? 0,
|
|
942
|
+
state: t.state,
|
|
943
|
+
})),
|
|
944
|
+
});
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
/** A comment's moderation history (statements of reasons), oldest first. */
|
|
948
|
+
async history(siteId , commentId ) {
|
|
949
|
+
const rows = await this.sql.all (
|
|
950
|
+
"SELECT * FROM comment_events WHERE comment_id = ? AND site_id = ? ORDER BY at, id",
|
|
951
|
+
[commentId, siteId],
|
|
952
|
+
);
|
|
953
|
+
return rows.map((r) => ({
|
|
954
|
+
id: String(r.id),
|
|
955
|
+
commentId: String(r.comment_id),
|
|
956
|
+
action: String(r.action) ,
|
|
957
|
+
actor: JSON.parse(String(r.actor)) ,
|
|
958
|
+
reasonCode: r.reason_code === null ? null : (String(r.reason_code) ),
|
|
959
|
+
note: r.note === null ? null : String(r.note),
|
|
960
|
+
automated: num(r.automated) === 1,
|
|
961
|
+
approvalId: r.approval_id === null ? null : String(r.approval_id),
|
|
962
|
+
op: r.op === null ? null : String(r.op),
|
|
963
|
+
at: String(r.at),
|
|
964
|
+
}));
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
// ───────────────────────────── moderation ─────────────────────────────
|
|
968
|
+
|
|
969
|
+
/**
|
|
970
|
+
* Moderates up to 50 comments in one batch of 2–3 statements plus the audit rows (§4.4):
|
|
971
|
+
* a set-based UPDATE marks every comment whose `(id, rev)` still matches with a fresh `op` (and
|
|
972
|
+
* its new `hash`); the events and the purge rows are inserted from the rows carrying that `op`.
|
|
973
|
+
* Each comment is independent: the result says which were done and which met a conflict,
|
|
974
|
+
* were not found, are not the caller's own, or cannot make that transition.
|
|
975
|
+
*/
|
|
976
|
+
async moderate(siteId , op ) {
|
|
977
|
+
assertIds(op.ids);
|
|
978
|
+
const t = TRANSITIONS[op.action];
|
|
979
|
+
if (!t) throw new CommentInputError("unknown moderation action");
|
|
980
|
+
if (PERSON_ONLY.includes(op.action) && !isPerson(op.actor))
|
|
981
|
+
throw new CommentForbiddenError(`only a person can ${op.action} comments`);
|
|
982
|
+
if (NEEDS_REASON.includes(op.action) && op.reasonCode === undefined)
|
|
983
|
+
throw new CommentInputError(`${op.action} needs a reasonCode`);
|
|
984
|
+
if (op.reasonCode !== undefined && !(REASON_CODES ).includes(op.reasonCode))
|
|
985
|
+
throw new CommentInputError("unknown reasonCode");
|
|
986
|
+
assertNote(op.note);
|
|
987
|
+
for (const id of op.ids)
|
|
988
|
+
if (!Number.isInteger(op.expectedRevs[id]))
|
|
989
|
+
throw new CommentInputError(`expectedRevs has no rev for ${id}`);
|
|
990
|
+
|
|
991
|
+
const now = this.#now().toISOString();
|
|
992
|
+
const opId = newCommentsId(ID_PREFIX.op);
|
|
993
|
+
const moderation = {
|
|
994
|
+
action: op.action,
|
|
995
|
+
actor: op.actor,
|
|
996
|
+
at: now,
|
|
997
|
+
...(op.reasonCode ? { reasonCode: op.reasonCode } : {}),
|
|
998
|
+
...(op.note ? { note: op.note } : {}),
|
|
999
|
+
automated: !isPerson(op.actor),
|
|
1000
|
+
};
|
|
1001
|
+
const rows = await this.#rows(siteId, op.ids);
|
|
1002
|
+
const own = op.ownNodeIds ? new Set(op.ownNodeIds) : undefined;
|
|
1003
|
+
const early = new Map ();
|
|
1004
|
+
const changes = [];
|
|
1005
|
+
const purgeIds = [];
|
|
1006
|
+
for (const id of op.ids) {
|
|
1007
|
+
const r = rows.get(id);
|
|
1008
|
+
if (!r) early.set(id, { id, ok: false, error: "not_found" });
|
|
1009
|
+
else if (own && !own.has(r.node_id)) early.set(id, { id, ok: false, error: "not_own" });
|
|
1010
|
+
else if (num(r.rev) !== op.expectedRevs[id])
|
|
1011
|
+
early.set(id, { id, ok: false, error: "conflict" });
|
|
1012
|
+
else if (!t.from.includes(r.status ))
|
|
1013
|
+
early.set(id, { id, ok: false, error: "invalid_transition" });
|
|
1014
|
+
else {
|
|
1015
|
+
const before = toComment(r);
|
|
1016
|
+
const { body: _body, ...rest } = before;
|
|
1017
|
+
const after = {
|
|
1018
|
+
...(op.action === "delete" ? rest : before),
|
|
1019
|
+
status: t.to,
|
|
1020
|
+
moderation,
|
|
1021
|
+
rev: before.rev + 1,
|
|
1022
|
+
};
|
|
1023
|
+
changes.push([id, before.rev, await commentRecordHash(after)]);
|
|
1024
|
+
if (t.to === "approved" || before.status === "approved") purgeIds.push(id);
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
if (changes.length > 0) {
|
|
1028
|
+
const statements = [
|
|
1029
|
+
{
|
|
1030
|
+
sql: `UPDATE comments SET status = ?, moderation = ?, rev = rev + 1, op = ?${op.action === "delete" ? ", body = NULL" : ""},
|
|
1031
|
+
hash = (SELECT json_extract(j.value, '$[2]') FROM json_each(?) j WHERE json_extract(j.value, '$[0]') = comments.id)
|
|
1032
|
+
WHERE site_id = ? AND (id, rev) IN (SELECT json_extract(value, '$[0]'), json_extract(value, '$[1]') FROM json_each(?))`,
|
|
1033
|
+
params: [t.to, json(moderation), opId, json(changes), siteId, json(changes)],
|
|
1034
|
+
},
|
|
1035
|
+
this.#eventsFromOp(
|
|
1036
|
+
siteId,
|
|
1037
|
+
opId,
|
|
1038
|
+
changes.map((c) => c[0]),
|
|
1039
|
+
op.action,
|
|
1040
|
+
op.actor,
|
|
1041
|
+
op.reasonCode ?? null,
|
|
1042
|
+
op.note ?? null,
|
|
1043
|
+
!isPerson(op.actor),
|
|
1044
|
+
op.approvalId ?? null,
|
|
1045
|
+
now,
|
|
1046
|
+
),
|
|
1047
|
+
];
|
|
1048
|
+
if (purgeIds.length > 0)
|
|
1049
|
+
statements.push(
|
|
1050
|
+
this.#purgeFromOp(
|
|
1051
|
+
siteId,
|
|
1052
|
+
opId,
|
|
1053
|
+
purgeIds,
|
|
1054
|
+
t.to === "approved" ? "normal" : "takedown",
|
|
1055
|
+
now,
|
|
1056
|
+
),
|
|
1057
|
+
);
|
|
1058
|
+
statements.push(...auditStatements(op.audit));
|
|
1059
|
+
await this.sql.batch(statements);
|
|
1060
|
+
}
|
|
1061
|
+
return this.#results(siteId, op.ids, opId, early);
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
#eventsFromOp(
|
|
1065
|
+
siteId ,
|
|
1066
|
+
opId ,
|
|
1067
|
+
ids ,
|
|
1068
|
+
action ,
|
|
1069
|
+
actor ,
|
|
1070
|
+
reasonCode ,
|
|
1071
|
+
note ,
|
|
1072
|
+
automated ,
|
|
1073
|
+
approvalId ,
|
|
1074
|
+
at ,
|
|
1075
|
+
) {
|
|
1076
|
+
return {
|
|
1077
|
+
sql: `INSERT INTO comment_events (id, site_id, comment_id, action, actor, reason_code, note, automated, approval_id, op, at)
|
|
1078
|
+
SELECT ? || '.' || id, site_id, id, ?, ?, ?, ?, ?, ?, op, ? FROM comments
|
|
1079
|
+
WHERE site_id = ? AND id IN (SELECT value FROM json_each(?)) AND op = ?`,
|
|
1080
|
+
params: [
|
|
1081
|
+
opId,
|
|
1082
|
+
action,
|
|
1083
|
+
json(actor),
|
|
1084
|
+
reasonCode,
|
|
1085
|
+
note,
|
|
1086
|
+
automated ? 1 : 0,
|
|
1087
|
+
approvalId,
|
|
1088
|
+
at,
|
|
1089
|
+
siteId,
|
|
1090
|
+
json(ids),
|
|
1091
|
+
opId,
|
|
1092
|
+
],
|
|
1093
|
+
};
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
#purgeFromOp(
|
|
1097
|
+
siteId ,
|
|
1098
|
+
opId ,
|
|
1099
|
+
ids ,
|
|
1100
|
+
priority ,
|
|
1101
|
+
at ,
|
|
1102
|
+
) {
|
|
1103
|
+
return {
|
|
1104
|
+
sql: `INSERT INTO comment_purge_queue (site_id, tag, priority, enqueued_at, attempts, next_at)
|
|
1105
|
+
SELECT DISTINCT site_id, ? || node_id, ?, ?, 0, ? FROM comments
|
|
1106
|
+
WHERE site_id = ? AND id IN (SELECT value FROM json_each(?)) AND op = ?
|
|
1107
|
+
${PURGE_UPSERT}`,
|
|
1108
|
+
params: [COMMENTS_TAG_PREFIX, priority, at, at, siteId, json(ids), opId],
|
|
1109
|
+
};
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
#purgeUpsert(
|
|
1113
|
+
siteId ,
|
|
1114
|
+
tags ,
|
|
1115
|
+
priority ,
|
|
1116
|
+
at ,
|
|
1117
|
+
guard ,
|
|
1118
|
+
guardParams = [],
|
|
1119
|
+
) {
|
|
1120
|
+
return {
|
|
1121
|
+
sql: `INSERT INTO comment_purge_queue (site_id, tag, priority, enqueued_at, attempts, next_at)
|
|
1122
|
+
SELECT ?, value, ?, ?, 0, ? FROM json_each(?) WHERE ${guard ?? "1 = 1"}
|
|
1123
|
+
${PURGE_UPSERT}`,
|
|
1124
|
+
params: [siteId, priority, at, at, json(tags), ...guardParams],
|
|
1125
|
+
};
|
|
1126
|
+
}
|
|
1127
|
+
|
|
1128
|
+
async #results(
|
|
1129
|
+
siteId ,
|
|
1130
|
+
ids ,
|
|
1131
|
+
opId ,
|
|
1132
|
+
early ,
|
|
1133
|
+
) {
|
|
1134
|
+
const pending = ids.filter((id) => !early.has(id));
|
|
1135
|
+
const after =
|
|
1136
|
+
pending.length > 0 ? await this.#rows(siteId, pending) : new Map ();
|
|
1137
|
+
return ids.map((id) => {
|
|
1138
|
+
const e = early.get(id);
|
|
1139
|
+
if (e) return e;
|
|
1140
|
+
const r = after.get(id);
|
|
1141
|
+
if (!r) return { id, ok: false, error: "not_found" };
|
|
1142
|
+
if (r.op === opId)
|
|
1143
|
+
return { id, ok: true, status: r.status , rev: num(r.rev) };
|
|
1144
|
+
return { id, ok: false, error: "conflict" };
|
|
1145
|
+
});
|
|
1146
|
+
}
|
|
1147
|
+
|
|
1148
|
+
/**
|
|
1149
|
+
* Adds and removes advisory labels (§6.7, §11.1) on up to 50 comments: one UPDATE with each
|
|
1150
|
+
* comment's new labels and hash, one event insert, plus the audit rows. Labels bump `rev` (an
|
|
1151
|
+
* approval requested before a label changed is void) but never change status or purge (C9).
|
|
1152
|
+
* Agents add and remove only `agent` labels.
|
|
1153
|
+
*/
|
|
1154
|
+
async label(siteId , op ) {
|
|
1155
|
+
const ids = op.items.map((i) => i.commentId);
|
|
1156
|
+
assertIds(ids);
|
|
1157
|
+
if (!["agent", "person", "classifier"].includes(op.source))
|
|
1158
|
+
throw new CommentInputError("unknown label source");
|
|
1159
|
+
if (op.source === "person" && !isPerson(op.actor))
|
|
1160
|
+
throw new CommentForbiddenError("person labels need a person");
|
|
1161
|
+
for (const item of op.items) {
|
|
1162
|
+
for (const l of [...(item.add ?? []), ...(item.remove ?? [])])
|
|
1163
|
+
if (!(LABELS ).includes(l))
|
|
1164
|
+
throw new CommentInputError(`unknown label "${String(l).slice(0, 40)}"`);
|
|
1165
|
+
if (
|
|
1166
|
+
item.confidence !== undefined &&
|
|
1167
|
+
(!Number.isInteger(item.confidence) || item.confidence < 0 || item.confidence > 100)
|
|
1168
|
+
)
|
|
1169
|
+
throw new CommentInputError("confidence is a whole number from 0 to 100");
|
|
1170
|
+
}
|
|
1171
|
+
const now = this.#now().toISOString();
|
|
1172
|
+
const opId = newCommentsId(ID_PREFIX.op);
|
|
1173
|
+
const rows = await this.#rows(siteId, ids);
|
|
1174
|
+
const own = op.ownNodeIds ? new Set(op.ownNodeIds) : undefined;
|
|
1175
|
+
const early = new Map ();
|
|
1176
|
+
const changes = [];
|
|
1177
|
+
for (const item of op.items) {
|
|
1178
|
+
const id = item.commentId;
|
|
1179
|
+
const r = rows.get(id);
|
|
1180
|
+
const expected = op.expectedRevs?.[id];
|
|
1181
|
+
if (!r) {
|
|
1182
|
+
early.set(id, { id, ok: false, error: "not_found" });
|
|
1183
|
+
continue;
|
|
1184
|
+
}
|
|
1185
|
+
if (own && !own.has(r.node_id)) {
|
|
1186
|
+
early.set(id, { id, ok: false, error: "not_own" });
|
|
1187
|
+
continue;
|
|
1188
|
+
}
|
|
1189
|
+
if (expected !== undefined && num(r.rev) !== expected) {
|
|
1190
|
+
early.set(id, { id, ok: false, error: "conflict" });
|
|
1191
|
+
continue;
|
|
1192
|
+
}
|
|
1193
|
+
const before = toComment(r);
|
|
1194
|
+
const removable = (l ) => op.source === "person" || l.source === op.source;
|
|
1195
|
+
const remove = new Set ([...(item.remove ?? []), ...(item.add ?? [])]);
|
|
1196
|
+
let labels = (before.labels ?? []).filter((l) => !(remove.has(l.label) && removable(l)));
|
|
1197
|
+
for (const name of item.add ?? []) {
|
|
1198
|
+
if (labels.some((l) => l.label === name && l.source === op.source)) continue;
|
|
1199
|
+
labels.push({
|
|
1200
|
+
label: name,
|
|
1201
|
+
source: op.source,
|
|
1202
|
+
...(op.source === "classifier" ? {} : { by: op.actor }),
|
|
1203
|
+
...(item.confidence !== undefined ? { confidence: item.confidence } : {}),
|
|
1204
|
+
at: now,
|
|
1205
|
+
});
|
|
1206
|
+
}
|
|
1207
|
+
if (labels.length > MAX_LABELS) labels = labels.slice(labels.length - MAX_LABELS);
|
|
1208
|
+
if (json(labels) === json(before.labels ?? [])) {
|
|
1209
|
+
early.set(id, { id, ok: true, status: before.status, rev: before.rev });
|
|
1210
|
+
continue;
|
|
1211
|
+
}
|
|
1212
|
+
const after = { ...before, rev: before.rev + 1 };
|
|
1213
|
+
if (labels.length > 0) after.labels = labels;
|
|
1214
|
+
else delete after.labels;
|
|
1215
|
+
changes.push([id, before.rev, await commentRecordHash(after), json(labels)]);
|
|
1216
|
+
}
|
|
1217
|
+
if (changes.length > 0) {
|
|
1218
|
+
const summary = op.items
|
|
1219
|
+
.map((i) =>
|
|
1220
|
+
[...(i.add ?? []).map((l) => `+${l}`), ...(i.remove ?? []).map((l) => `-${l}`)].join(" "),
|
|
1221
|
+
)
|
|
1222
|
+
.find((s) => s.length > 0);
|
|
1223
|
+
await this.sql.batch([
|
|
1224
|
+
{
|
|
1225
|
+
sql: `UPDATE comments SET rev = rev + 1, op = ?,
|
|
1226
|
+
hash = (SELECT json_extract(j.value, '$[2]') FROM json_each(?) j WHERE json_extract(j.value, '$[0]') = comments.id),
|
|
1227
|
+
labels = (SELECT json_extract(j.value, '$[3]') FROM json_each(?) j WHERE json_extract(j.value, '$[0]') = comments.id)
|
|
1228
|
+
WHERE site_id = ? AND (id, rev) IN (SELECT json_extract(value, '$[0]'), json_extract(value, '$[1]') FROM json_each(?))`,
|
|
1229
|
+
params: [opId, json(changes), json(changes), siteId, json(changes)],
|
|
1230
|
+
},
|
|
1231
|
+
this.#eventsFromOp(
|
|
1232
|
+
siteId,
|
|
1233
|
+
opId,
|
|
1234
|
+
changes.map((c) => c[0]),
|
|
1235
|
+
"label",
|
|
1236
|
+
op.actor,
|
|
1237
|
+
null,
|
|
1238
|
+
summary ? summary.slice(0, NOTE_MAX) : null,
|
|
1239
|
+
!isPerson(op.actor),
|
|
1240
|
+
null,
|
|
1241
|
+
now,
|
|
1242
|
+
),
|
|
1243
|
+
...auditStatements(op.audit),
|
|
1244
|
+
]);
|
|
1245
|
+
}
|
|
1246
|
+
return this.#results(siteId, ids, opId, early);
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
/**
|
|
1250
|
+
* A person's reply on the site's behalf (§4.2): stored `approved` at once, under the comment it
|
|
1251
|
+
* answers (two levels). One batch: the comment (guarded on its parent still being approved), the
|
|
1252
|
+
* `reply` event and the normal purge row (both guarded on the new hash), and the audit rows.
|
|
1253
|
+
*/
|
|
1254
|
+
async reply(siteId , input ) {
|
|
1255
|
+
if (!PERSON_ID.test(input.person.id))
|
|
1256
|
+
throw new CommentForbiddenError("a reply on the site's behalf is a person's");
|
|
1257
|
+
if (input.badge !== "author" && input.badge !== "team")
|
|
1258
|
+
throw new CommentInputError("badge must be author or team");
|
|
1259
|
+
const name = normalizeName(input.person.name);
|
|
1260
|
+
if (checkName(name)) throw new CommentInputError("invalid name");
|
|
1261
|
+
const text = normalizeText(input.text);
|
|
1262
|
+
if (checkText(text)) throw new CommentInputError("a reply is 2 to 5,000 characters");
|
|
1263
|
+
const parent = await this.get(siteId, input.commentId);
|
|
1264
|
+
if (!parent) throw new CommentNotFoundError("the comment answered does not exist");
|
|
1265
|
+
if (parent.status !== "approved")
|
|
1266
|
+
throw new CommentInputError("replies go only to approved comments");
|
|
1267
|
+
const now = this.#now().toISOString();
|
|
1268
|
+
const record = {
|
|
1269
|
+
schemaVersion: 1,
|
|
1270
|
+
id: newCommentsId(ID_PREFIX.comment),
|
|
1271
|
+
siteId,
|
|
1272
|
+
nodeId: parent.nodeId,
|
|
1273
|
+
parentId: parent.parentId ?? parent.id,
|
|
1274
|
+
...(parent.parentId ? { inReplyToId: parent.id } : {}),
|
|
1275
|
+
source: "native",
|
|
1276
|
+
author: {
|
|
1277
|
+
kind: "staff",
|
|
1278
|
+
personId: input.person.id,
|
|
1279
|
+
name,
|
|
1280
|
+
badge: input.badge,
|
|
1281
|
+
...(input.draftedBy ? { draftedBy: input.draftedBy } : {}),
|
|
1282
|
+
},
|
|
1283
|
+
body: { format: "text", text },
|
|
1284
|
+
status: "approved",
|
|
1285
|
+
createdAt: now,
|
|
1286
|
+
rev: 1,
|
|
1287
|
+
};
|
|
1288
|
+
const hash = await commentRecordHash(record);
|
|
1289
|
+
const actor = { kind: "human", id: input.person.id, name };
|
|
1290
|
+
const guard = "EXISTS (SELECT 1 FROM comments WHERE id = ? AND hash = ?)";
|
|
1291
|
+
const [res] = await this.sql.batch([
|
|
1292
|
+
{
|
|
1293
|
+
sql: `INSERT INTO comments (id, site_id, node_id, parent_id, in_reply_to_id, source, origin, author, body, status, labels, moderation, email_id, ip_hmac, challenge_id, proof, op, hash, created_at, edited_at, rev)
|
|
1294
|
+
SELECT ?, ?, ?, ?, ?, 'native', NULL, ?, ?, 'approved', '[]', NULL, NULL, NULL, NULL, 'staff', NULL, ?, ?, NULL, 1
|
|
1295
|
+
WHERE EXISTS (SELECT 1 FROM comments WHERE id = ? AND site_id = ? AND status = 'approved' AND rev = ?)`,
|
|
1296
|
+
params: [
|
|
1297
|
+
record.id,
|
|
1298
|
+
siteId,
|
|
1299
|
+
record.nodeId,
|
|
1300
|
+
record.parentId ?? null,
|
|
1301
|
+
record.inReplyToId ?? null,
|
|
1302
|
+
json(record.author),
|
|
1303
|
+
text,
|
|
1304
|
+
hash,
|
|
1305
|
+
now,
|
|
1306
|
+
parent.id,
|
|
1307
|
+
siteId,
|
|
1308
|
+
parent.rev,
|
|
1309
|
+
],
|
|
1310
|
+
},
|
|
1311
|
+
{
|
|
1312
|
+
sql: `INSERT INTO comment_events (id, site_id, comment_id, action, actor, reason_code, note, automated, approval_id, op, at)
|
|
1313
|
+
SELECT ?, ?, ?, 'reply', ?, NULL, NULL, 0, ?, NULL, ? WHERE ${guard}`,
|
|
1314
|
+
params: [
|
|
1315
|
+
`${record.id}.reply`,
|
|
1316
|
+
siteId,
|
|
1317
|
+
record.id,
|
|
1318
|
+
json(actor),
|
|
1319
|
+
input.approvalId ?? null,
|
|
1320
|
+
now,
|
|
1321
|
+
record.id,
|
|
1322
|
+
hash,
|
|
1323
|
+
],
|
|
1324
|
+
},
|
|
1325
|
+
this.#purgeUpsert(siteId, [commentsCacheTag(record.nodeId)], "normal", now, guard, [
|
|
1326
|
+
record.id,
|
|
1327
|
+
hash,
|
|
1328
|
+
]),
|
|
1329
|
+
...auditStatements(input.audit),
|
|
1330
|
+
]);
|
|
1331
|
+
if (res?.changes !== 1)
|
|
1332
|
+
throw new CommentConflictError("the comment answered changed; reload and retry");
|
|
1333
|
+
return record;
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
/** Edits a person's own staff reply (sets `editedAt`), CAS on `rev`; purges the entry. */
|
|
1337
|
+
async editReply(
|
|
1338
|
+
siteId ,
|
|
1339
|
+
id ,
|
|
1340
|
+
text ,
|
|
1341
|
+
rev ,
|
|
1342
|
+
personId ,
|
|
1343
|
+
) {
|
|
1344
|
+
const current = await this.get(siteId, id);
|
|
1345
|
+
if (!current) throw new CommentNotFoundError();
|
|
1346
|
+
if (current.author.kind !== "staff" || current.author.personId !== personId)
|
|
1347
|
+
throw new CommentForbiddenError("only the person who wrote a reply can edit it");
|
|
1348
|
+
if (current.rev !== rev) throw new CommentConflictError();
|
|
1349
|
+
const normal = normalizeText(text);
|
|
1350
|
+
if (checkText(normal)) throw new CommentInputError("a reply is 2 to 5,000 characters");
|
|
1351
|
+
const now = this.#now().toISOString();
|
|
1352
|
+
const after = {
|
|
1353
|
+
...current,
|
|
1354
|
+
body: { format: "text", text: normal },
|
|
1355
|
+
editedAt: now,
|
|
1356
|
+
rev: rev + 1,
|
|
1357
|
+
};
|
|
1358
|
+
const hash = await commentRecordHash(after);
|
|
1359
|
+
const [res] = await this.sql.batch([
|
|
1360
|
+
{
|
|
1361
|
+
sql: "UPDATE comments SET body = ?, edited_at = ?, rev = rev + 1, hash = ? WHERE id = ? AND site_id = ? AND rev = ?",
|
|
1362
|
+
params: [normal, now, hash, id, siteId, rev],
|
|
1363
|
+
},
|
|
1364
|
+
...(current.status === "approved"
|
|
1365
|
+
? [
|
|
1366
|
+
this.#purgeUpsert(
|
|
1367
|
+
siteId,
|
|
1368
|
+
[commentsCacheTag(current.nodeId)],
|
|
1369
|
+
"normal",
|
|
1370
|
+
now,
|
|
1371
|
+
"EXISTS (SELECT 1 FROM comments WHERE id = ? AND hash = ?)",
|
|
1372
|
+
[id, hash],
|
|
1373
|
+
),
|
|
1374
|
+
]
|
|
1375
|
+
: []),
|
|
1376
|
+
]);
|
|
1377
|
+
if (res?.changes !== 1) throw new CommentConflictError();
|
|
1378
|
+
return after;
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
// ───────────────────────────── commenters, erasure ─────────────────────────────
|
|
1382
|
+
|
|
1383
|
+
/** A commenter's id from their address's keyed hash, or from one of their comments. */
|
|
1384
|
+
async findCommenter(
|
|
1385
|
+
siteId ,
|
|
1386
|
+
by ,
|
|
1387
|
+
) {
|
|
1388
|
+
if ("emailHmac" in by) {
|
|
1389
|
+
const r = await this.sql.get (
|
|
1390
|
+
"SELECT id FROM commenter_emails WHERE site_id = ? AND email_hmac = ?",
|
|
1391
|
+
[siteId, by.emailHmac],
|
|
1392
|
+
);
|
|
1393
|
+
return r?.id ?? null;
|
|
1394
|
+
}
|
|
1395
|
+
const r = await this.sql.get (
|
|
1396
|
+
"SELECT email_id FROM comments WHERE id = ? AND site_id = ?",
|
|
1397
|
+
[by.commentId, siteId],
|
|
1398
|
+
);
|
|
1399
|
+
return r?.email_id ?? null;
|
|
1400
|
+
}
|
|
1401
|
+
|
|
1402
|
+
/** A commenter with the decrypted address (`commenters:data` routes only, C10). */
|
|
1403
|
+
async commenter(
|
|
1404
|
+
siteId ,
|
|
1405
|
+
commenterId ,
|
|
1406
|
+
keys ,
|
|
1407
|
+
) {
|
|
1408
|
+
return (await this.commenters(siteId, [commenterId], keys))[0] ?? null;
|
|
1409
|
+
}
|
|
1410
|
+
|
|
1411
|
+
/**
|
|
1412
|
+
* Several commenters with their decrypted addresses in three reads, whatever their number (a
|
|
1413
|
+
* personal-data export page stays inside D1 Free's 50 queries per invocation). Unknown ids are
|
|
1414
|
+
* left out; the order is the order of `ids`.
|
|
1415
|
+
*/
|
|
1416
|
+
async commenters(
|
|
1417
|
+
siteId ,
|
|
1418
|
+
ids ,
|
|
1419
|
+
keys ,
|
|
1420
|
+
) {
|
|
1421
|
+
const wanted = [...new Set(ids)];
|
|
1422
|
+
if (wanted.length === 0) return [];
|
|
1423
|
+
const rows = await this.sql.all (
|
|
1424
|
+
"SELECT id, email_ciphertext, email_iv, created_at FROM commenter_emails WHERE site_id = ? AND id IN (SELECT value FROM json_each(?))",
|
|
1425
|
+
[siteId, json(wanted)],
|
|
1426
|
+
);
|
|
1427
|
+
if (rows.length === 0) return [];
|
|
1428
|
+
const found = rows.map((r) => String(r.id));
|
|
1429
|
+
const linked = async (table ) => {
|
|
1430
|
+
const out = new Map ();
|
|
1431
|
+
const refs = await this.sql.all (
|
|
1432
|
+
`SELECT id, email_id FROM ${table} WHERE site_id = ? AND email_id IN (SELECT value FROM json_each(?)) ORDER BY created_at, id`,
|
|
1433
|
+
[siteId, json(found)],
|
|
1434
|
+
);
|
|
1435
|
+
for (const r of refs) out.set(r.email_id, [...(out.get(r.email_id) ?? []), r.id]);
|
|
1436
|
+
return out;
|
|
1437
|
+
};
|
|
1438
|
+
const [comments, reports] = [await linked("comments"), await linked("comment_reports")];
|
|
1439
|
+
const byId = new Map(rows.map((r) => [String(r.id), r]));
|
|
1440
|
+
const out = [];
|
|
1441
|
+
for (const id of wanted) {
|
|
1442
|
+
const r = byId.get(id);
|
|
1443
|
+
if (!r) continue;
|
|
1444
|
+
out.push({
|
|
1445
|
+
id,
|
|
1446
|
+
email: await openEmail(keys, siteId, {
|
|
1447
|
+
ciphertext: String(r.email_ciphertext),
|
|
1448
|
+
iv: String(r.email_iv),
|
|
1449
|
+
}),
|
|
1450
|
+
firstSeen: String(r.created_at),
|
|
1451
|
+
commentIds: comments.get(id) ?? [],
|
|
1452
|
+
reportIds: reports.get(id) ?? [],
|
|
1453
|
+
});
|
|
1454
|
+
}
|
|
1455
|
+
return out;
|
|
1456
|
+
}
|
|
1457
|
+
|
|
1458
|
+
/** Every comment linked to a commenter, oldest first, in one read (a commenter's export). */
|
|
1459
|
+
async commenterComments(siteId , commenterId ) {
|
|
1460
|
+
const rows = await this.sql.all (
|
|
1461
|
+
"SELECT * FROM comments WHERE site_id = ? AND email_id = ? ORDER BY created_at, id",
|
|
1462
|
+
[siteId, commenterId],
|
|
1463
|
+
);
|
|
1464
|
+
return rows.map(toComment);
|
|
1465
|
+
}
|
|
1466
|
+
|
|
1467
|
+
/**
|
|
1468
|
+
* "Ban and hide past comments" (§14): hides the approved comments of a comment's author — every
|
|
1469
|
+
* approved comment linked to the same email, or the comment itself when it has none. Runs at
|
|
1470
|
+
* most `batches` set-based batches of `batch` comments (each one read and one batch of three
|
|
1471
|
+
* statements, with the audit rows in the first), so one request stays inside D1 Free's 50
|
|
1472
|
+
* queries per invocation; `more` says approved comments remain (send the request again).
|
|
1473
|
+
*/
|
|
1474
|
+
async hideApprovedOf(
|
|
1475
|
+
siteId ,
|
|
1476
|
+
commentId ,
|
|
1477
|
+
input
|
|
1478
|
+
|
|
1479
|
+
|
|
1480
|
+
|
|
1481
|
+
|
|
1482
|
+
,
|
|
1483
|
+
o = {},
|
|
1484
|
+
) {
|
|
1485
|
+
if (!isPerson(input.actor)) throw new CommentForbiddenError("only a person can do this");
|
|
1486
|
+
if (!(REASON_CODES ).includes(input.reasonCode))
|
|
1487
|
+
throw new CommentInputError("unknown reasonCode");
|
|
1488
|
+
assertNote(input.note);
|
|
1489
|
+
if (!COMMENT_ID.test(commentId)) throw new CommentNotFoundError();
|
|
1490
|
+
const size = o.batch ?? HIDE_PAST_BATCH;
|
|
1491
|
+
const batches = o.batches ?? HIDE_PAST_BATCHES;
|
|
1492
|
+
const now = this.#now().toISOString();
|
|
1493
|
+
const moderation = {
|
|
1494
|
+
action: "hide",
|
|
1495
|
+
actor: input.actor,
|
|
1496
|
+
at: now,
|
|
1497
|
+
reasonCode: input.reasonCode,
|
|
1498
|
+
...(input.note ? { note: input.note } : {}),
|
|
1499
|
+
automated: false,
|
|
1500
|
+
};
|
|
1501
|
+
const nodeIds = new Set ();
|
|
1502
|
+
let hidden = 0;
|
|
1503
|
+
let audit = input.audit ?? [];
|
|
1504
|
+
for (let i = 0; i < batches; i++) {
|
|
1505
|
+
const rows = await this.sql.all (
|
|
1506
|
+
`SELECT * FROM comments WHERE site_id = ? AND status = 'approved'
|
|
1507
|
+
AND (id = ? OR email_id = (SELECT email_id FROM comments WHERE id = ? AND site_id = ?))
|
|
1508
|
+
ORDER BY id LIMIT ?`,
|
|
1509
|
+
[siteId, commentId, commentId, siteId, size + 1],
|
|
1510
|
+
);
|
|
1511
|
+
const page = rows.slice(0, size);
|
|
1512
|
+
if (page.length === 0) return { hidden, nodeIds: [...nodeIds].sort(), more: false };
|
|
1513
|
+
const opId = newCommentsId(ID_PREFIX.op);
|
|
1514
|
+
const changes = [];
|
|
1515
|
+
for (const r of page) {
|
|
1516
|
+
const before = toComment(r);
|
|
1517
|
+
const after = { ...before, status: "hidden", moderation, rev: before.rev + 1 };
|
|
1518
|
+
changes.push([r.id, before.rev, await commentRecordHash(after)]);
|
|
1519
|
+
nodeIds.add(r.node_id);
|
|
1520
|
+
}
|
|
1521
|
+
const ids = changes.map((c) => c[0]);
|
|
1522
|
+
const results = await this.sql.batch([
|
|
1523
|
+
{
|
|
1524
|
+
sql: `UPDATE comments SET status = 'hidden', moderation = ?, rev = rev + 1, op = ?,
|
|
1525
|
+
hash = (SELECT json_extract(j.value, '$[2]') FROM json_each(?) j WHERE json_extract(j.value, '$[0]') = comments.id)
|
|
1526
|
+
WHERE site_id = ? AND status = 'approved' AND (id, rev) IN (SELECT json_extract(value, '$[0]'), json_extract(value, '$[1]') FROM json_each(?))`,
|
|
1527
|
+
params: [json(moderation), opId, json(changes), siteId, json(changes)],
|
|
1528
|
+
},
|
|
1529
|
+
this.#eventsFromOp(
|
|
1530
|
+
siteId,
|
|
1531
|
+
opId,
|
|
1532
|
+
ids,
|
|
1533
|
+
"hide",
|
|
1534
|
+
input.actor,
|
|
1535
|
+
input.reasonCode,
|
|
1536
|
+
input.note ?? null,
|
|
1537
|
+
false,
|
|
1538
|
+
null,
|
|
1539
|
+
now,
|
|
1540
|
+
),
|
|
1541
|
+
this.#purgeFromOp(siteId, opId, ids, "takedown", now),
|
|
1542
|
+
...auditStatements(audit),
|
|
1543
|
+
]);
|
|
1544
|
+
audit = [];
|
|
1545
|
+
hidden += results[0]?.changes ?? 0;
|
|
1546
|
+
if (rows.length <= size) return { hidden, nodeIds: [...nodeIds].sort(), more: false };
|
|
1547
|
+
}
|
|
1548
|
+
return { hidden, nodeIds: [...nodeIds].sort(), more: true };
|
|
1549
|
+
}
|
|
1550
|
+
|
|
1551
|
+
/**
|
|
1552
|
+
* Erasure (§9.4, GDPR Art. 17), people with `commenters:data` only. `anonymise` (the default)
|
|
1553
|
+
* gives every comment the `erased` author and clears its email link, IP hash and challenge;
|
|
1554
|
+
* `delete-text` also removes the text (status `deleted`). The commenter's email row is deleted
|
|
1555
|
+
* and their reports lose the email. Each comment gets an `erase` event with reason
|
|
1556
|
+
* `erasure-request`; approved ones a takedown purge. Up to 200 comments a batch of ≤ 5 statements
|
|
1557
|
+
* plus the audit rows (on the last batch).
|
|
1558
|
+
*/
|
|
1559
|
+
async erase(
|
|
1560
|
+
siteId ,
|
|
1561
|
+
target ,
|
|
1562
|
+
mode ,
|
|
1563
|
+
by ,
|
|
1564
|
+
options = {},
|
|
1565
|
+
) {
|
|
1566
|
+
if (!isPerson(by))
|
|
1567
|
+
throw new CommentForbiddenError("only a person can erase a commenter's data");
|
|
1568
|
+
if (mode !== "anonymise" && mode !== "delete-text")
|
|
1569
|
+
throw new CommentInputError("mode must be anonymise or delete-text");
|
|
1570
|
+
assertNote(options.note);
|
|
1571
|
+
const commenterId = target.commenterId;
|
|
1572
|
+
if (!commenterId && !target.commentIds?.length)
|
|
1573
|
+
throw new CommentInputError("name a commenter or comments");
|
|
1574
|
+
if (target.commentIds)
|
|
1575
|
+
for (const id of target.commentIds)
|
|
1576
|
+
if (!COMMENT_ID.test(id)) throw new CommentInputError("invalid comment id");
|
|
1577
|
+
if (commenterId) {
|
|
1578
|
+
const exists = await this.sql.get(
|
|
1579
|
+
"SELECT 1 AS hit FROM commenter_emails WHERE id = ? AND site_id = ?",
|
|
1580
|
+
[commenterId, siteId],
|
|
1581
|
+
);
|
|
1582
|
+
if (!exists) throw new CommentNotFoundError("no such commenter");
|
|
1583
|
+
}
|
|
1584
|
+
const now = this.#now().toISOString();
|
|
1585
|
+
const moderation = {
|
|
1586
|
+
action: "erase",
|
|
1587
|
+
actor: by,
|
|
1588
|
+
at: now,
|
|
1589
|
+
reasonCode: "erasure-request",
|
|
1590
|
+
...(options.note ? { note: options.note } : {}),
|
|
1591
|
+
automated: false,
|
|
1592
|
+
};
|
|
1593
|
+
const nodeIds = new Set ();
|
|
1594
|
+
let comments = 0;
|
|
1595
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
1596
|
+
const rows = commenterId
|
|
1597
|
+
? await this.sql.all (
|
|
1598
|
+
"SELECT * FROM comments WHERE site_id = ? AND email_id = ? ORDER BY id LIMIT 200",
|
|
1599
|
+
[siteId, commenterId],
|
|
1600
|
+
)
|
|
1601
|
+
: await this.sql.all (
|
|
1602
|
+
`SELECT * FROM comments WHERE site_id = ? AND id IN (SELECT value FROM json_each(?))
|
|
1603
|
+
AND (author != ? OR ip_hmac IS NOT NULL OR challenge_id IS NOT NULL OR email_id IS NOT NULL ${mode === "delete-text" ? "OR body IS NOT NULL" : ""}) ORDER BY id LIMIT 200`,
|
|
1604
|
+
[siteId, json(target.commentIds ?? []), ERASED_AUTHOR],
|
|
1605
|
+
);
|
|
1606
|
+
if (rows.length === 0) break;
|
|
1607
|
+
const opId = newCommentsId(ID_PREFIX.op);
|
|
1608
|
+
const changes = [];
|
|
1609
|
+
const takedown = [];
|
|
1610
|
+
for (const r of rows) {
|
|
1611
|
+
const before = toComment(r);
|
|
1612
|
+
const { body: _b, ...rest } = before;
|
|
1613
|
+
const after = {
|
|
1614
|
+
...(mode === "delete-text" ? rest : before),
|
|
1615
|
+
author: { kind: "erased" },
|
|
1616
|
+
...(mode === "delete-text" && before.status !== "deleted"
|
|
1617
|
+
? { status: "deleted" }
|
|
1618
|
+
: {}),
|
|
1619
|
+
moderation,
|
|
1620
|
+
rev: before.rev + 1,
|
|
1621
|
+
};
|
|
1622
|
+
changes.push([r.id, before.rev, await commentRecordHash(after)]);
|
|
1623
|
+
if (before.status === "approved") {
|
|
1624
|
+
takedown.push(r.id);
|
|
1625
|
+
nodeIds.add(r.node_id);
|
|
1626
|
+
}
|
|
1627
|
+
}
|
|
1628
|
+
const statements = [
|
|
1629
|
+
{
|
|
1630
|
+
sql: `UPDATE comments SET author = ?, moderation = ?, rev = rev + 1, op = ?, email_id = NULL, ip_hmac = NULL, challenge_id = NULL
|
|
1631
|
+
${mode === "delete-text" ? ", body = NULL, status = 'deleted'" : ""},
|
|
1632
|
+
hash = (SELECT json_extract(j.value, '$[2]') FROM json_each(?) j WHERE json_extract(j.value, '$[0]') = comments.id)
|
|
1633
|
+
WHERE site_id = ? AND (id, rev) IN (SELECT json_extract(value, '$[0]'), json_extract(value, '$[1]') FROM json_each(?))`,
|
|
1634
|
+
params: [ERASED_AUTHOR, json(moderation), opId, json(changes), siteId, json(changes)],
|
|
1635
|
+
},
|
|
1636
|
+
this.#eventsFromOp(
|
|
1637
|
+
siteId,
|
|
1638
|
+
opId,
|
|
1639
|
+
changes.map((c) => c[0]),
|
|
1640
|
+
"erase",
|
|
1641
|
+
by,
|
|
1642
|
+
"erasure-request",
|
|
1643
|
+
options.note ?? null,
|
|
1644
|
+
false,
|
|
1645
|
+
null,
|
|
1646
|
+
now,
|
|
1647
|
+
),
|
|
1648
|
+
];
|
|
1649
|
+
if (takedown.length > 0)
|
|
1650
|
+
statements.push(this.#purgeFromOp(siteId, opId, takedown, "takedown", now));
|
|
1651
|
+
const results = await this.sql.batch(statements);
|
|
1652
|
+
comments += results[0]?.changes ?? 0;
|
|
1653
|
+
}
|
|
1654
|
+
let reports = 0;
|
|
1655
|
+
let emailDeleted = false;
|
|
1656
|
+
const tail = [];
|
|
1657
|
+
if (commenterId) {
|
|
1658
|
+
tail.push(
|
|
1659
|
+
{
|
|
1660
|
+
sql: "UPDATE comment_reports SET email_id = NULL, ip_hmac = NULL, challenge_id = NULL WHERE site_id = ? AND email_id = ?",
|
|
1661
|
+
params: [siteId, commenterId],
|
|
1662
|
+
},
|
|
1663
|
+
{
|
|
1664
|
+
sql: "DELETE FROM commenter_emails WHERE id = ? AND site_id = ? AND NOT EXISTS (SELECT 1 FROM comments WHERE email_id = ?)",
|
|
1665
|
+
params: [commenterId, siteId, commenterId],
|
|
1666
|
+
},
|
|
1667
|
+
);
|
|
1668
|
+
}
|
|
1669
|
+
tail.push(...auditStatements(options.audit));
|
|
1670
|
+
if (tail.length > 0) {
|
|
1671
|
+
const res = await this.sql.batch(tail);
|
|
1672
|
+
if (commenterId) {
|
|
1673
|
+
reports = res[0]?.changes ?? 0;
|
|
1674
|
+
emailDeleted = (res[1]?.changes ?? 0) === 1;
|
|
1675
|
+
}
|
|
1676
|
+
}
|
|
1677
|
+
return { comments, reports, emailDeleted, nodeIds: [...nodeIds].sort() };
|
|
1678
|
+
}
|
|
1679
|
+
|
|
1680
|
+
// ───────────────────────────── bans ─────────────────────────────
|
|
1681
|
+
|
|
1682
|
+
/**
|
|
1683
|
+
* Bans a comment's author by email and/or this month's IP hash (§10.1: REST only, people). The
|
|
1684
|
+
* store resolves the hashes from the comment, so nobody needs to see an address. An IP ban
|
|
1685
|
+
* lasts until the month's salt rotates; a comment whose IP hash was already cleared has none.
|
|
1686
|
+
*/
|
|
1687
|
+
async ban(siteId , input ) {
|
|
1688
|
+
if (!isPerson(input.by)) throw new CommentForbiddenError("bans are a person's decision");
|
|
1689
|
+
if (!(REASON_CODES ).includes(input.reasonCode))
|
|
1690
|
+
throw new CommentInputError("unknown reasonCode");
|
|
1691
|
+
assertNote(input.note);
|
|
1692
|
+
if (input.until !== null && Number.isNaN(Date.parse(input.until)))
|
|
1693
|
+
throw new CommentInputError("until must be an ISO timestamp or null");
|
|
1694
|
+
const row = await this.sql.get
|
|
1695
|
+
|
|
1696
|
+
|
|
1697
|
+
|
|
1698
|
+
(
|
|
1699
|
+
`SELECT c.ip_hmac, e.email_hmac, c.created_at FROM comments c LEFT JOIN commenter_emails e ON e.id = c.email_id WHERE c.id = ? AND c.site_id = ?`,
|
|
1700
|
+
[input.commentId, siteId],
|
|
1701
|
+
);
|
|
1702
|
+
if (!row) throw new CommentNotFoundError();
|
|
1703
|
+
// Requests without a client address share one hash (§6.5); banning it would ban all of them.
|
|
1704
|
+
if (row.ip_hmac && input.subjects.includes("ip")) {
|
|
1705
|
+
const salt = await this.readSalt(utcMonth(new Date(row.created_at)));
|
|
1706
|
+
if (salt && row.ip_hmac === (await ipHmac(salt, siteId, UNKNOWN_CLIENT))) row.ip_hmac = null;
|
|
1707
|
+
}
|
|
1708
|
+
const now = this.#now().toISOString();
|
|
1709
|
+
const out = [];
|
|
1710
|
+
const statements = [];
|
|
1711
|
+
for (const subject of new Set(input.subjects)) {
|
|
1712
|
+
const value = subject === "email" ? row.email_hmac : row.ip_hmac;
|
|
1713
|
+
if (!value) continue;
|
|
1714
|
+
const id = newCommentsId(ID_PREFIX.ban);
|
|
1715
|
+
statements.push({
|
|
1716
|
+
sql: `INSERT INTO comment_bans (id, site_id, subject, value, until, reason_code, note, by_actor, at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
1717
|
+
ON CONFLICT (site_id, subject, value) DO UPDATE SET until = excluded.until, reason_code = excluded.reason_code, note = excluded.note, by_actor = excluded.by_actor, at = excluded.at`,
|
|
1718
|
+
params: [
|
|
1719
|
+
id,
|
|
1720
|
+
siteId,
|
|
1721
|
+
subject,
|
|
1722
|
+
value,
|
|
1723
|
+
input.until,
|
|
1724
|
+
input.reasonCode,
|
|
1725
|
+
input.note ?? null,
|
|
1726
|
+
json(input.by),
|
|
1727
|
+
now,
|
|
1728
|
+
],
|
|
1729
|
+
});
|
|
1730
|
+
out.push({
|
|
1731
|
+
id,
|
|
1732
|
+
subject,
|
|
1733
|
+
until: input.until,
|
|
1734
|
+
reasonCode: input.reasonCode,
|
|
1735
|
+
note: input.note ?? null,
|
|
1736
|
+
by: input.by,
|
|
1737
|
+
at: now,
|
|
1738
|
+
});
|
|
1739
|
+
}
|
|
1740
|
+
if (statements.length > 0) await this.sql.batch(statements);
|
|
1741
|
+
return out;
|
|
1742
|
+
}
|
|
1743
|
+
|
|
1744
|
+
/**
|
|
1745
|
+
* The site's bans, newest first; with `commentId`, only those that match that comment's author
|
|
1746
|
+
* (its email's keyed hash or its network hash), so Studio can show and lift a commenter's ban
|
|
1747
|
+
* without anyone seeing an address.
|
|
1748
|
+
*/
|
|
1749
|
+
async listBans(siteId , q = {}) {
|
|
1750
|
+
const rows = q.commentId
|
|
1751
|
+
? await this.sql.all (
|
|
1752
|
+
`SELECT b.* FROM comment_bans b, comments c LEFT JOIN commenter_emails e ON e.id = c.email_id
|
|
1753
|
+
WHERE b.site_id = ? AND c.site_id = b.site_id AND c.id = ?
|
|
1754
|
+
AND ((b.subject = 'email' AND b.value = e.email_hmac) OR (b.subject = 'ip' AND b.value = c.ip_hmac))
|
|
1755
|
+
ORDER BY b.at DESC, b.id`,
|
|
1756
|
+
[siteId, q.commentId],
|
|
1757
|
+
)
|
|
1758
|
+
: await this.sql.all (
|
|
1759
|
+
"SELECT * FROM comment_bans WHERE site_id = ? ORDER BY at DESC, id",
|
|
1760
|
+
[siteId],
|
|
1761
|
+
);
|
|
1762
|
+
return rows.map((r) => ({
|
|
1763
|
+
id: String(r.id),
|
|
1764
|
+
subject: String(r.subject) ,
|
|
1765
|
+
until: r.until === null ? null : String(r.until),
|
|
1766
|
+
reasonCode: String(r.reason_code) ,
|
|
1767
|
+
note: r.note === null ? null : String(r.note),
|
|
1768
|
+
by: JSON.parse(String(r.by_actor)) ,
|
|
1769
|
+
at: String(r.at),
|
|
1770
|
+
}));
|
|
1771
|
+
}
|
|
1772
|
+
|
|
1773
|
+
async liftBan(siteId , banId ) {
|
|
1774
|
+
return (
|
|
1775
|
+
(await this.sql.run("DELETE FROM comment_bans WHERE id = ? AND site_id = ?", [banId, siteId]))
|
|
1776
|
+
.changes === 1
|
|
1777
|
+
);
|
|
1778
|
+
}
|
|
1779
|
+
|
|
1780
|
+
// ───────────────────────────── reports ─────────────────────────────
|
|
1781
|
+
|
|
1782
|
+
async listReports(
|
|
1783
|
+
siteId ,
|
|
1784
|
+
q = {},
|
|
1785
|
+
) {
|
|
1786
|
+
const where = ["site_id = ?"];
|
|
1787
|
+
const params = [siteId];
|
|
1788
|
+
if (q.open === true) where.push("resolved_at IS NULL");
|
|
1789
|
+
if (q.open === false) where.push("resolved_at IS NOT NULL");
|
|
1790
|
+
if (q.commentId) {
|
|
1791
|
+
where.push("comment_id = ?");
|
|
1792
|
+
params.push(q.commentId);
|
|
1793
|
+
}
|
|
1794
|
+
const rows = await this.sql.all (
|
|
1795
|
+
`SELECT * FROM comment_reports WHERE ${where.join(" AND ")} ORDER BY created_at DESC, id DESC LIMIT ?`,
|
|
1796
|
+
[...params, Math.min(Math.max(q.limit ?? 50, 1), 200)],
|
|
1797
|
+
);
|
|
1798
|
+
return rows.map((r) => ({
|
|
1799
|
+
id: String(r.id),
|
|
1800
|
+
commentId: String(r.comment_id),
|
|
1801
|
+
reason: String(r.reason) ,
|
|
1802
|
+
details: r.details === null ? null : String(r.details),
|
|
1803
|
+
hasEmail: r.email_id !== null,
|
|
1804
|
+
createdAt: String(r.created_at),
|
|
1805
|
+
resolvedAt: r.resolved_at === null ? null : String(r.resolved_at),
|
|
1806
|
+
resolvedBy: r.resolved_by === null ? null : String(r.resolved_by),
|
|
1807
|
+
resolution: r.resolution === null ? null : String(r.resolution),
|
|
1808
|
+
}));
|
|
1809
|
+
}
|
|
1810
|
+
|
|
1811
|
+
/** One report of a site, or `null`. */
|
|
1812
|
+
async getReport(siteId , reportId ) {
|
|
1813
|
+
const r = await this.sql.get (
|
|
1814
|
+
"SELECT id, comment_id FROM comment_reports WHERE id = ? AND site_id = ?",
|
|
1815
|
+
[reportId, siteId],
|
|
1816
|
+
);
|
|
1817
|
+
if (!r) return null;
|
|
1818
|
+
const all = await this.listReports(siteId, { commentId: String(r.comment_id), limit: 200 });
|
|
1819
|
+
return all.find((x) => x.id === reportId) ?? null;
|
|
1820
|
+
}
|
|
1821
|
+
|
|
1822
|
+
/** Commenter ids of a site, oldest first (a personal-data export; people only). */
|
|
1823
|
+
async commenterIds(siteId , limit = 1000) {
|
|
1824
|
+
const rows = await this.sql.all (
|
|
1825
|
+
"SELECT id FROM commenter_emails WHERE site_id = ? ORDER BY created_at, id LIMIT ?",
|
|
1826
|
+
[siteId, limit],
|
|
1827
|
+
);
|
|
1828
|
+
return rows.map((r) => r.id);
|
|
1829
|
+
}
|
|
1830
|
+
|
|
1831
|
+
/** Records a person's decision on a report; a resolved report cannot be resolved again (409). */
|
|
1832
|
+
async resolveReport(
|
|
1833
|
+
siteId ,
|
|
1834
|
+
reportId ,
|
|
1835
|
+
resolution ,
|
|
1836
|
+
by ,
|
|
1837
|
+
) {
|
|
1838
|
+
if (!/^[a-z][a-z-]{0,39}$/.test(resolution))
|
|
1839
|
+
throw new CommentInputError("resolution is a short code");
|
|
1840
|
+
const res = await this.sql.run(
|
|
1841
|
+
"UPDATE comment_reports SET resolved_at = ?, resolved_by = ?, resolution = ? WHERE id = ? AND site_id = ? AND resolved_at IS NULL",
|
|
1842
|
+
[this.#now().toISOString(), json(by), resolution, reportId, siteId],
|
|
1843
|
+
);
|
|
1844
|
+
if (res.changes !== 1)
|
|
1845
|
+
throw new CommentConflictError("the report is resolved or does not exist");
|
|
1846
|
+
}
|
|
1847
|
+
|
|
1848
|
+
// ───────────────────────────── purge queue ─────────────────────────────
|
|
1849
|
+
|
|
1850
|
+
purgeQueue = {
|
|
1851
|
+
/** A site's queued tags. */
|
|
1852
|
+
queued: async (siteId ) => {
|
|
1853
|
+
const rows = await this.sql.all (
|
|
1854
|
+
"SELECT * FROM comment_purge_queue WHERE site_id = ? ORDER BY enqueued_at, tag",
|
|
1855
|
+
[siteId],
|
|
1856
|
+
);
|
|
1857
|
+
return rows.map((r) => ({
|
|
1858
|
+
tag: String(r.tag),
|
|
1859
|
+
priority: String(r.priority) ,
|
|
1860
|
+
enqueuedAt: String(r.enqueued_at),
|
|
1861
|
+
attempts: num(r.attempts),
|
|
1862
|
+
nextAt: String(r.next_at),
|
|
1863
|
+
}));
|
|
1864
|
+
},
|
|
1865
|
+
/** Sites with queued tags (the hourly backstop). */
|
|
1866
|
+
sites: async () =>
|
|
1867
|
+
(
|
|
1868
|
+
await this.sql.all (
|
|
1869
|
+
"SELECT DISTINCT site_id FROM comment_purge_queue ORDER BY site_id",
|
|
1870
|
+
)
|
|
1871
|
+
).map((r) => r.site_id),
|
|
1872
|
+
/** Enqueues tags (settings changes, closing threads) in one statement. */
|
|
1873
|
+
enqueue: async (
|
|
1874
|
+
siteId ,
|
|
1875
|
+
tags ,
|
|
1876
|
+
priority ,
|
|
1877
|
+
) => {
|
|
1878
|
+
if (tags.length === 0) return;
|
|
1879
|
+
await this.sql.batch([this.#purgeUpsert(siteId, tags, priority, this.#now().toISOString())]);
|
|
1880
|
+
},
|
|
1881
|
+
/** Purge requests of the last 60 s (any source), for the shared budget. */
|
|
1882
|
+
recent: async (now = this.#now()) => {
|
|
1883
|
+
const rows = await this.sql.all (
|
|
1884
|
+
"SELECT at, requests FROM cache_purge_log WHERE at > ? ORDER BY at",
|
|
1885
|
+
[new Date(now.getTime() - 60_000).toISOString()],
|
|
1886
|
+
);
|
|
1887
|
+
return rows.map((r) => ({ at: r.at, requests: num(r.requests) }));
|
|
1888
|
+
},
|
|
1889
|
+
/** Records a purge request sent by publishing or anything else (the publish path's one statement). */
|
|
1890
|
+
log: async (source , requests = 1, at = this.#now()) => {
|
|
1891
|
+
await this.sql.run("INSERT INTO cache_purge_log (at, source, requests) VALUES (?, ?, ?)", [
|
|
1892
|
+
at.toISOString(),
|
|
1893
|
+
source,
|
|
1894
|
+
requests,
|
|
1895
|
+
]);
|
|
1896
|
+
},
|
|
1897
|
+
/**
|
|
1898
|
+
* A request for `tags` succeeded: removes the rows not re-enqueued since `sentAt` (a change
|
|
1899
|
+
* after the request keeps its row) and logs the request, in one batch.
|
|
1900
|
+
*/
|
|
1901
|
+
sent: async (siteId , tags , sentAt ) => {
|
|
1902
|
+
await this.sql.batch([
|
|
1903
|
+
{
|
|
1904
|
+
sql: "DELETE FROM comment_purge_queue WHERE site_id = ? AND tag IN (SELECT value FROM json_each(?)) AND next_at <= ?",
|
|
1905
|
+
params: [siteId, json(tags), sentAt.toISOString()],
|
|
1906
|
+
},
|
|
1907
|
+
{
|
|
1908
|
+
sql: "INSERT INTO cache_purge_log (at, source, requests) VALUES (?, 'comments', 1)",
|
|
1909
|
+
params: [sentAt.toISOString()],
|
|
1910
|
+
},
|
|
1911
|
+
]);
|
|
1912
|
+
},
|
|
1913
|
+
/** A request failed: back off each row (30 s × 2^attempts, ≤ 5 min) and log the attempt. */
|
|
1914
|
+
failed: async (siteId , rows , at ) => {
|
|
1915
|
+
if (rows.length === 0) return;
|
|
1916
|
+
const next = rows.map((r) => [
|
|
1917
|
+
r.tag,
|
|
1918
|
+
new Date(at.getTime() + purgeBackoffMs(r.attempts)).toISOString(),
|
|
1919
|
+
]);
|
|
1920
|
+
await this.sql.batch([
|
|
1921
|
+
{
|
|
1922
|
+
sql: `UPDATE comment_purge_queue SET attempts = attempts + 1,
|
|
1923
|
+
next_at = (SELECT json_extract(j.value, '$[1]') FROM json_each(?) j WHERE json_extract(j.value, '$[0]') = comment_purge_queue.tag)
|
|
1924
|
+
WHERE site_id = ? AND tag IN (SELECT json_extract(value, '$[0]') FROM json_each(?)) AND next_at <= ?`,
|
|
1925
|
+
params: [json(next), siteId, json(next), at.toISOString()],
|
|
1926
|
+
},
|
|
1927
|
+
{
|
|
1928
|
+
sql: "INSERT INTO cache_purge_log (at, source, requests) VALUES (?, 'comments', 1)",
|
|
1929
|
+
params: [at.toISOString()],
|
|
1930
|
+
},
|
|
1931
|
+
]);
|
|
1932
|
+
},
|
|
1933
|
+
};
|
|
1934
|
+
|
|
1935
|
+
// ───────────────────────────── retention ─────────────────────────────
|
|
1936
|
+
|
|
1937
|
+
retention = {
|
|
1938
|
+
/**
|
|
1939
|
+
* Runs a site's retention plan in order, each step one bounded statement (two for client
|
|
1940
|
+
* data), stopping when the plan's row budget is spent (`more: true`; the next run continues).
|
|
1941
|
+
*/
|
|
1942
|
+
run: async (siteId , plan ) => {
|
|
1943
|
+
let budget = plan.budget;
|
|
1944
|
+
const counts = {};
|
|
1945
|
+
const cut = new Map(plan.steps.map((s) => [s.kind, s.cutoff]));
|
|
1946
|
+
const noApprovedReplies =
|
|
1947
|
+
"NOT EXISTS (SELECT 1 FROM comments r WHERE r.parent_id = c.id AND r.status = 'approved')";
|
|
1948
|
+
const decided = "COALESCE(json_extract(c.moderation, '$.at'), c.created_at)";
|
|
1949
|
+
const deleteComments = (status , timeExpr , cutoff ) => ({
|
|
1950
|
+
sql: `DELETE FROM comments WHERE id IN (SELECT c.id FROM comments c WHERE c.site_id = ? AND c.status = ? AND ${timeExpr} < ? AND ${noApprovedReplies} LIMIT ?)`,
|
|
1951
|
+
params: [siteId, status, cutoff],
|
|
1952
|
+
});
|
|
1953
|
+
for (const step of plan.steps) {
|
|
1954
|
+
if (budget <= 0) break;
|
|
1955
|
+
let n = 0;
|
|
1956
|
+
const run = async (s ) => {
|
|
1957
|
+
const res = await this.sql.run(s.sql, [...s.params, budget - n]);
|
|
1958
|
+
n += res.changes;
|
|
1959
|
+
};
|
|
1960
|
+
switch (step.kind) {
|
|
1961
|
+
case "pending":
|
|
1962
|
+
await run(deleteComments("pending", "c.created_at", step.cutoff));
|
|
1963
|
+
break;
|
|
1964
|
+
case "spam":
|
|
1965
|
+
case "deleted":
|
|
1966
|
+
case "hidden":
|
|
1967
|
+
await run(deleteComments(step.kind, decided, step.cutoff));
|
|
1968
|
+
break;
|
|
1969
|
+
case "tombstones":
|
|
1970
|
+
n = await this.#tombstones(siteId, cut, budget);
|
|
1971
|
+
break;
|
|
1972
|
+
case "client-data":
|
|
1973
|
+
await run({
|
|
1974
|
+
sql: "UPDATE comments SET ip_hmac = NULL, challenge_id = NULL WHERE rowid IN (SELECT rowid FROM comments WHERE site_id = ? AND created_at < ? AND (ip_hmac IS NOT NULL OR challenge_id IS NOT NULL) LIMIT ?)",
|
|
1975
|
+
params: [siteId, step.cutoff],
|
|
1976
|
+
});
|
|
1977
|
+
if (budget - n > 0)
|
|
1978
|
+
await run({
|
|
1979
|
+
sql: "UPDATE comment_reports SET ip_hmac = NULL, challenge_id = NULL WHERE rowid IN (SELECT rowid FROM comment_reports WHERE site_id = ? AND created_at < ? AND (ip_hmac IS NOT NULL OR challenge_id IS NOT NULL) LIMIT ?)",
|
|
1980
|
+
params: [siteId, step.cutoff],
|
|
1981
|
+
});
|
|
1982
|
+
break;
|
|
1983
|
+
case "reports":
|
|
1984
|
+
await run({
|
|
1985
|
+
sql: "DELETE FROM comment_reports WHERE id IN (SELECT id FROM comment_reports WHERE site_id = ? AND resolved_at IS NOT NULL AND resolved_at < ? LIMIT ?)",
|
|
1986
|
+
params: [siteId, step.cutoff],
|
|
1987
|
+
});
|
|
1988
|
+
break;
|
|
1989
|
+
case "events":
|
|
1990
|
+
await run({
|
|
1991
|
+
sql: "DELETE FROM comment_events WHERE id IN (SELECT e.id FROM comment_events e WHERE e.site_id = ? AND e.at < ? AND NOT EXISTS (SELECT 1 FROM comments c WHERE c.id = e.comment_id) LIMIT ?)",
|
|
1992
|
+
params: [siteId, step.cutoff],
|
|
1993
|
+
});
|
|
1994
|
+
break;
|
|
1995
|
+
case "emails":
|
|
1996
|
+
await run({
|
|
1997
|
+
sql: `DELETE FROM commenter_emails WHERE id IN (SELECT m.id FROM commenter_emails m WHERE m.site_id = ?
|
|
1998
|
+
AND NOT EXISTS (SELECT 1 FROM comments c WHERE c.email_id = m.id)
|
|
1999
|
+
AND NOT EXISTS (SELECT 1 FROM comment_reports r WHERE r.email_id = m.id) LIMIT ?)`,
|
|
2000
|
+
params: [siteId],
|
|
2001
|
+
});
|
|
2002
|
+
break;
|
|
2003
|
+
case "bans":
|
|
2004
|
+
await run({
|
|
2005
|
+
sql: "DELETE FROM comment_bans WHERE id IN (SELECT id FROM comment_bans WHERE site_id = ? AND until IS NOT NULL AND until <= ? LIMIT ?)",
|
|
2006
|
+
params: [siteId, step.cutoff],
|
|
2007
|
+
});
|
|
2008
|
+
break;
|
|
2009
|
+
}
|
|
2010
|
+
counts[step.kind] = n;
|
|
2011
|
+
budget -= n;
|
|
2012
|
+
}
|
|
2013
|
+
return { counts, more: budget <= 0 };
|
|
2014
|
+
},
|
|
2015
|
+
/** Comments, reports and threads of entries deleted ≥ 30 days ago (`deletedEntriesDue`). */
|
|
2016
|
+
deleteEntries: async (
|
|
2017
|
+
siteId ,
|
|
2018
|
+
nodeIds ,
|
|
2019
|
+
budget = 500,
|
|
2020
|
+
) => {
|
|
2021
|
+
if (nodeIds.length === 0) return 0;
|
|
2022
|
+
const [reports, comments] = await this.sql.batch([
|
|
2023
|
+
{
|
|
2024
|
+
sql: "DELETE FROM comment_reports WHERE site_id = ? AND comment_id IN (SELECT id FROM comments WHERE site_id = ? AND node_id IN (SELECT value FROM json_each(?)) LIMIT ?)",
|
|
2025
|
+
params: [siteId, siteId, json(nodeIds), budget],
|
|
2026
|
+
},
|
|
2027
|
+
{
|
|
2028
|
+
sql: "DELETE FROM comments WHERE id IN (SELECT id FROM comments WHERE site_id = ? AND node_id IN (SELECT value FROM json_each(?)) LIMIT ?)",
|
|
2029
|
+
params: [siteId, json(nodeIds), budget],
|
|
2030
|
+
},
|
|
2031
|
+
{
|
|
2032
|
+
sql: "DELETE FROM comment_threads WHERE site_id = ? AND node_id IN (SELECT value FROM json_each(?)) AND NOT EXISTS (SELECT 1 FROM comments WHERE site_id = ? AND node_id = comment_threads.node_id)",
|
|
2033
|
+
params: [siteId, json(nodeIds), siteId],
|
|
2034
|
+
},
|
|
2035
|
+
]);
|
|
2036
|
+
return (reports?.changes ?? 0) + (comments?.changes ?? 0);
|
|
2037
|
+
},
|
|
2038
|
+
/** Deployment-wide: salts older than the previous month, purge-log rows older than an hour. */
|
|
2039
|
+
runDeployment: async (
|
|
2040
|
+
now ,
|
|
2041
|
+
oldestMonthToKeep ,
|
|
2042
|
+
) => {
|
|
2043
|
+
const [salts, log] = await this.sql.batch([
|
|
2044
|
+
{ sql: "DELETE FROM comment_salts WHERE month < ?", params: [oldestMonthToKeep] },
|
|
2045
|
+
{
|
|
2046
|
+
sql: "DELETE FROM cache_purge_log WHERE at < ?",
|
|
2047
|
+
params: [new Date(now.getTime() - PURGE_LOG_KEEP_MS).toISOString()],
|
|
2048
|
+
},
|
|
2049
|
+
]);
|
|
2050
|
+
return { salts: salts?.changes ?? 0, purgeLog: log?.changes ?? 0 };
|
|
2051
|
+
},
|
|
2052
|
+
};
|
|
2053
|
+
|
|
2054
|
+
/**
|
|
2055
|
+
* Rows due for deletion that approved replies still hang under become tombstones: no text, the
|
|
2056
|
+
* `erased` author, status `deleted` (§9.3). One read and one guarded UPDATE.
|
|
2057
|
+
*/
|
|
2058
|
+
async #tombstones(
|
|
2059
|
+
siteId ,
|
|
2060
|
+
cut ,
|
|
2061
|
+
budget ,
|
|
2062
|
+
) {
|
|
2063
|
+
const conds = [];
|
|
2064
|
+
const params = [siteId];
|
|
2065
|
+
const decided = "COALESCE(json_extract(c.moderation, '$.at'), c.created_at)";
|
|
2066
|
+
for (const [status, time] of [
|
|
2067
|
+
["pending", "c.created_at"],
|
|
2068
|
+
["spam", decided],
|
|
2069
|
+
["deleted", decided],
|
|
2070
|
+
["hidden", decided],
|
|
2071
|
+
] ) {
|
|
2072
|
+
const cutoff = cut.get(status);
|
|
2073
|
+
if (cutoff === undefined) continue;
|
|
2074
|
+
conds.push(`(c.status = ? AND ${time} < ?)`);
|
|
2075
|
+
params.push(status, cutoff);
|
|
2076
|
+
}
|
|
2077
|
+
if (conds.length === 0) return 0;
|
|
2078
|
+
const rows = await this.sql.all (
|
|
2079
|
+
`SELECT * FROM comments c WHERE c.site_id = ? AND (${conds.join(" OR ")})
|
|
2080
|
+
AND (c.body IS NOT NULL OR c.author != ? OR c.status != 'deleted')
|
|
2081
|
+
AND EXISTS (SELECT 1 FROM comments r WHERE r.parent_id = c.id AND r.status = 'approved') LIMIT ?`,
|
|
2082
|
+
[...params, ERASED_AUTHOR, Math.min(budget, 200)],
|
|
2083
|
+
);
|
|
2084
|
+
if (rows.length === 0) return 0;
|
|
2085
|
+
const changes = [];
|
|
2086
|
+
for (const r of rows) {
|
|
2087
|
+
const { body: _b, ...rest } = toComment(r);
|
|
2088
|
+
changes.push([
|
|
2089
|
+
r.id,
|
|
2090
|
+
num(r.rev),
|
|
2091
|
+
await commentRecordHash({
|
|
2092
|
+
...rest,
|
|
2093
|
+
author: { kind: "erased" },
|
|
2094
|
+
status: "deleted",
|
|
2095
|
+
rev: num(r.rev) + 1,
|
|
2096
|
+
}),
|
|
2097
|
+
]);
|
|
2098
|
+
}
|
|
2099
|
+
const res = await this.sql.run(
|
|
2100
|
+
`UPDATE comments SET body = NULL, author = ?, status = 'deleted', rev = rev + 1, op = NULL,
|
|
2101
|
+
hash = (SELECT json_extract(j.value, '$[2]') FROM json_each(?) j WHERE json_extract(j.value, '$[0]') = comments.id)
|
|
2102
|
+
WHERE site_id = ? AND (id, rev) IN (SELECT json_extract(value, '$[0]'), json_extract(value, '$[1]') FROM json_each(?))`,
|
|
2103
|
+
[ERASED_AUTHOR, json(changes), siteId, json(changes)],
|
|
2104
|
+
);
|
|
2105
|
+
return res.changes;
|
|
2106
|
+
}
|
|
2107
|
+
}
|
|
2108
|
+
|
|
2109
|
+
const PURGE_UPSERT = `ON CONFLICT (site_id, tag) DO UPDATE SET
|
|
2110
|
+
priority = CASE WHEN excluded.priority = 'takedown' THEN 'takedown' ELSE comment_purge_queue.priority END,
|
|
2111
|
+
next_at = excluded.next_at, attempts = 0`;
|