@cloudhal/comments 0.0.0-stage → 0.1.1
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,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* First-party proof of work (RFC-0007 §7): signed, stateless challenges.
|
|
3
|
+
*
|
|
4
|
+
* - **Issue:** `v1.<payload>.<mac>` (base64url). `payload` is JSON
|
|
5
|
+
* `{s: siteId, n: nodeId or commentId, k: "comment"|"report", t: issuedAt, e: t + 600, b: bits,
|
|
6
|
+
* r: 16 random bytes}` with times in Unix seconds; `mac` is the first 16 bytes of
|
|
7
|
+
* HMAC-SHA-256(K_pow, "v1." ‖ payload) — the version prefix is signed too. Issuing writes nothing.
|
|
8
|
+
* - **Solve:** the smallest decimal counter `x` with SHA-256(challenge ‖ ":" ‖ x) starting with `b`
|
|
9
|
+
* zero bits.
|
|
10
|
+
* - **Verify:** parse; MAC in constant time; site, target and kind match; not expired; at least 3 s
|
|
11
|
+
* after issue; one SHA-256 of the solution. Microseconds of CPU.
|
|
12
|
+
* - **Single use:** `r` is the challenge id. An isolate `ReplayCache` answers repeats cheaply and
|
|
13
|
+
* the unique indexes on `comments.challenge_id` and `comment_reports.challenge_id` make a solved
|
|
14
|
+
* challenge single use across isolates at no extra write (§7.4, invariant C12). A challenge is
|
|
15
|
+
* consumed only when something is stored, so a reader who fixes a too-short comment can resend.
|
|
16
|
+
* - **Difficulty:** 18 bits; 20 once today's stored submissions pass 50 % of the daily cap, 21
|
|
17
|
+
* past 80 % (the ceiling, so a low-end phone stays under about 20 s).
|
|
18
|
+
*/
|
|
19
|
+
import { type HmacKey } from "./crypto.js";
|
|
20
|
+
export type ChallengeKind = "comment" | "report";
|
|
21
|
+
export declare const CHALLENGE_TTL_S = 600;
|
|
22
|
+
export declare const MIN_FILL_MS = 3000;
|
|
23
|
+
export declare const DEFAULT_BITS = 18;
|
|
24
|
+
export declare const RAMP_BITS = 20;
|
|
25
|
+
export declare const MAX_BITS = 21;
|
|
26
|
+
export interface ChallengePayload {
|
|
27
|
+
readonly s: string;
|
|
28
|
+
readonly n: string;
|
|
29
|
+
readonly k: ChallengeKind;
|
|
30
|
+
readonly t: number;
|
|
31
|
+
readonly e: number;
|
|
32
|
+
readonly b: number;
|
|
33
|
+
readonly r: string;
|
|
34
|
+
}
|
|
35
|
+
export interface IssuedChallenge {
|
|
36
|
+
readonly challenge: string;
|
|
37
|
+
readonly bits: number;
|
|
38
|
+
readonly expiresAt: string;
|
|
39
|
+
}
|
|
40
|
+
/** Bits for new challenges from today's stored submissions against the daily cap (§7.2). */
|
|
41
|
+
export declare function difficultyFor(storedToday: number, dailyCap: number): number;
|
|
42
|
+
export declare function issueChallenge(key: HmacKey, input: {
|
|
43
|
+
readonly siteId: string;
|
|
44
|
+
readonly target: string;
|
|
45
|
+
readonly kind: ChallengeKind;
|
|
46
|
+
readonly bits: number;
|
|
47
|
+
readonly now: Date;
|
|
48
|
+
}): Promise<IssuedChallenge>;
|
|
49
|
+
export type ChallengeFailure = "malformed" | "bad_mac" | "mismatch" | "expired" | "too_fast" | "wrong_solution";
|
|
50
|
+
export type ChallengeCheck = {
|
|
51
|
+
readonly ok: true;
|
|
52
|
+
readonly id: string;
|
|
53
|
+
readonly payload: ChallengePayload;
|
|
54
|
+
} | {
|
|
55
|
+
readonly ok: false;
|
|
56
|
+
readonly reason: ChallengeFailure;
|
|
57
|
+
};
|
|
58
|
+
/** Number of leading zero bits of a digest. */
|
|
59
|
+
export declare function leadingZeroBits(digest: Uint8Array): number;
|
|
60
|
+
export declare function solutionBits(challenge: string, solution: string): Promise<number>;
|
|
61
|
+
/**
|
|
62
|
+
* Checks a challenge and its solution for one site, target and kind (§7.4). The result names why
|
|
63
|
+
* it failed; callers answer `expired` with `400 challenge_expired` and every other failure with the
|
|
64
|
+
* silent "pending" answer (it is a bot).
|
|
65
|
+
*/
|
|
66
|
+
export declare function verifyChallenge(key: HmacKey, challenge: string, solution: string, expect: {
|
|
67
|
+
readonly siteId: string;
|
|
68
|
+
readonly target: string;
|
|
69
|
+
readonly kind: ChallengeKind;
|
|
70
|
+
readonly now: Date;
|
|
71
|
+
readonly minFillMs?: number;
|
|
72
|
+
}): Promise<ChallengeCheck>;
|
|
73
|
+
/** Finds the smallest solving counter (tests, the CLI seeder, and the browser worker's algorithm). */
|
|
74
|
+
export declare function solveChallenge(challenge: string, maxTries?: number): Promise<string>;
|
|
75
|
+
/**
|
|
76
|
+
* Recently used challenge ids in this isolate (§7.4). Bounded; entries leave when their challenge
|
|
77
|
+
* expires or when the oldest is evicted. The unique index is the real guarantee across isolates.
|
|
78
|
+
*/
|
|
79
|
+
export declare class ReplayCache {
|
|
80
|
+
#private;
|
|
81
|
+
constructor(max?: number);
|
|
82
|
+
has(id: string, now: Date): boolean;
|
|
83
|
+
/** Records a used challenge until it expires (Unix seconds `e`). */
|
|
84
|
+
add(id: string, expiresAtS: number): void;
|
|
85
|
+
get size(): number;
|
|
86
|
+
}
|
package/dist/src/pow.js
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* First-party proof of work (RFC-0007 §7): signed, stateless challenges.
|
|
3
|
+
*
|
|
4
|
+
* - **Issue:** `v1.<payload>.<mac>` (base64url). `payload` is JSON
|
|
5
|
+
* `{s: siteId, n: nodeId or commentId, k: "comment"|"report", t: issuedAt, e: t + 600, b: bits,
|
|
6
|
+
* r: 16 random bytes}` with times in Unix seconds; `mac` is the first 16 bytes of
|
|
7
|
+
* HMAC-SHA-256(K_pow, "v1." ‖ payload) — the version prefix is signed too. Issuing writes nothing.
|
|
8
|
+
* - **Solve:** the smallest decimal counter `x` with SHA-256(challenge ‖ ":" ‖ x) starting with `b`
|
|
9
|
+
* zero bits.
|
|
10
|
+
* - **Verify:** parse; MAC in constant time; site, target and kind match; not expired; at least 3 s
|
|
11
|
+
* after issue; one SHA-256 of the solution. Microseconds of CPU.
|
|
12
|
+
* - **Single use:** `r` is the challenge id. An isolate `ReplayCache` answers repeats cheaply and
|
|
13
|
+
* the unique indexes on `comments.challenge_id` and `comment_reports.challenge_id` make a solved
|
|
14
|
+
* challenge single use across isolates at no extra write (§7.4, invariant C12). A challenge is
|
|
15
|
+
* consumed only when something is stored, so a reader who fixes a too-short comment can resend.
|
|
16
|
+
* - **Difficulty:** 18 bits; 20 once today's stored submissions pass 50 % of the daily cap, 21
|
|
17
|
+
* past 80 % (the ceiling, so a low-end phone stays under about 20 s).
|
|
18
|
+
*/
|
|
19
|
+
import {
|
|
20
|
+
constantTimeEqual,
|
|
21
|
+
fromBase64Url,
|
|
22
|
+
|
|
23
|
+
hmac,
|
|
24
|
+
randomBytes,
|
|
25
|
+
toBase64Url,
|
|
26
|
+
utf8,
|
|
27
|
+
} from "./crypto.js";
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
export const CHALLENGE_TTL_S = 600;
|
|
32
|
+
export const MIN_FILL_MS = 3000;
|
|
33
|
+
export const DEFAULT_BITS = 18;
|
|
34
|
+
export const RAMP_BITS = 20;
|
|
35
|
+
export const MAX_BITS = 21;
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
/** Bits for new challenges from today's stored submissions against the daily cap (§7.2). */
|
|
54
|
+
export function difficultyFor(storedToday , dailyCap ) {
|
|
55
|
+
if (dailyCap > 0 && storedToday * 5 > dailyCap * 4) return MAX_BITS;
|
|
56
|
+
if (dailyCap > 0 && storedToday * 2 > dailyCap) return RAMP_BITS;
|
|
57
|
+
return DEFAULT_BITS;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async function sign(key , signed ) {
|
|
61
|
+
return (await hmac(key, utf8(signed))).slice(0, 16);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export async function issueChallenge(
|
|
65
|
+
key ,
|
|
66
|
+
input
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
,
|
|
73
|
+
) {
|
|
74
|
+
if (!Number.isInteger(input.bits) || input.bits < 0 || input.bits > 32)
|
|
75
|
+
throw new Error("bits must be a whole number from 0 to 32");
|
|
76
|
+
const t = Math.floor(input.now.getTime() / 1000);
|
|
77
|
+
const payload = {
|
|
78
|
+
s: input.siteId,
|
|
79
|
+
n: input.target,
|
|
80
|
+
k: input.kind,
|
|
81
|
+
t,
|
|
82
|
+
e: t + CHALLENGE_TTL_S,
|
|
83
|
+
b: input.bits,
|
|
84
|
+
r: toBase64Url(randomBytes(16)),
|
|
85
|
+
};
|
|
86
|
+
const signed = `v1.${toBase64Url(utf8(JSON.stringify(payload)))}`;
|
|
87
|
+
const mac = await sign(key, signed);
|
|
88
|
+
return {
|
|
89
|
+
challenge: `${signed}.${toBase64Url(mac)}`,
|
|
90
|
+
bits: input.bits,
|
|
91
|
+
expiresAt: new Date(payload.e * 1000).toISOString(),
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
function parsePayload(segment ) {
|
|
108
|
+
const bytes = fromBase64Url(segment);
|
|
109
|
+
if (!bytes) return undefined;
|
|
110
|
+
let v ;
|
|
111
|
+
try {
|
|
112
|
+
v = JSON.parse(new TextDecoder("utf-8", { fatal: true, ignoreBOM: false }).decode(bytes));
|
|
113
|
+
} catch {
|
|
114
|
+
return undefined;
|
|
115
|
+
}
|
|
116
|
+
if (v === null || typeof v !== "object") return undefined;
|
|
117
|
+
const p = v ;
|
|
118
|
+
const int = (x ) => typeof x === "number" && Number.isInteger(x) && x >= 0;
|
|
119
|
+
if (
|
|
120
|
+
typeof p.s !== "string" ||
|
|
121
|
+
typeof p.n !== "string" ||
|
|
122
|
+
(p.k !== "comment" && p.k !== "report") ||
|
|
123
|
+
!int(p.t) ||
|
|
124
|
+
!int(p.e) ||
|
|
125
|
+
!int(p.b) ||
|
|
126
|
+
(p.b ) > 32 ||
|
|
127
|
+
typeof p.r !== "string" ||
|
|
128
|
+
!/^[A-Za-z0-9_-]{22}$/.test(p.r)
|
|
129
|
+
)
|
|
130
|
+
return undefined;
|
|
131
|
+
return p ;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Number of leading zero bits of a digest. */
|
|
135
|
+
export function leadingZeroBits(digest ) {
|
|
136
|
+
let n = 0;
|
|
137
|
+
for (const byte of digest) {
|
|
138
|
+
if (byte === 0) {
|
|
139
|
+
n += 8;
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
return n + Math.clz32(byte) - 24;
|
|
143
|
+
}
|
|
144
|
+
return n;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export async function solutionBits(challenge , solution ) {
|
|
148
|
+
const digest = new Uint8Array(
|
|
149
|
+
await crypto.subtle.digest("SHA-256", utf8(`${challenge}:${solution}`)),
|
|
150
|
+
);
|
|
151
|
+
return leadingZeroBits(digest);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Checks a challenge and its solution for one site, target and kind (§7.4). The result names why
|
|
156
|
+
* it failed; callers answer `expired` with `400 challenge_expired` and every other failure with the
|
|
157
|
+
* silent "pending" answer (it is a bot).
|
|
158
|
+
*/
|
|
159
|
+
export async function verifyChallenge(
|
|
160
|
+
key ,
|
|
161
|
+
challenge ,
|
|
162
|
+
solution ,
|
|
163
|
+
expect
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
,
|
|
170
|
+
) {
|
|
171
|
+
const parts = challenge.split(".");
|
|
172
|
+
if (parts.length !== 3 || parts[0] !== "v1" || !/^(?:0|[1-9][0-9]{0,15})$/.test(solution))
|
|
173
|
+
return { ok: false, reason: "malformed" };
|
|
174
|
+
const [, body = "", macPart = ""] = parts;
|
|
175
|
+
const mac = fromBase64Url(macPart);
|
|
176
|
+
if (mac?.length !== 16) return { ok: false, reason: "malformed" };
|
|
177
|
+
const expected = await sign(key, `v1.${body}`);
|
|
178
|
+
if (!constantTimeEqual(mac, expected)) return { ok: false, reason: "bad_mac" };
|
|
179
|
+
const payload = parsePayload(body);
|
|
180
|
+
if (!payload) return { ok: false, reason: "malformed" };
|
|
181
|
+
if (payload.s !== expect.siteId || payload.n !== expect.target || payload.k !== expect.kind)
|
|
182
|
+
return { ok: false, reason: "mismatch" };
|
|
183
|
+
const nowMs = expect.now.getTime();
|
|
184
|
+
if (payload.e * 1000 <= nowMs) return { ok: false, reason: "expired" };
|
|
185
|
+
if (payload.t * 1000 > nowMs - (expect.minFillMs ?? MIN_FILL_MS))
|
|
186
|
+
return { ok: false, reason: "too_fast" };
|
|
187
|
+
if ((await solutionBits(challenge, solution)) < payload.b)
|
|
188
|
+
return { ok: false, reason: "wrong_solution" };
|
|
189
|
+
return { ok: true, id: payload.r, payload };
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Finds the smallest solving counter (tests, the CLI seeder, and the browser worker's algorithm). */
|
|
193
|
+
export async function solveChallenge(challenge , maxTries = 1 << 26) {
|
|
194
|
+
const segment = challenge.split(".")[1] ?? "";
|
|
195
|
+
const payload = parsePayload(segment);
|
|
196
|
+
if (!payload) throw new Error("malformed challenge");
|
|
197
|
+
for (let x = 0; x < maxTries; x++) {
|
|
198
|
+
if ((await solutionBits(challenge, String(x))) >= payload.b) return String(x);
|
|
199
|
+
}
|
|
200
|
+
throw new Error("no solution within the limit");
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Recently used challenge ids in this isolate (§7.4). Bounded; entries leave when their challenge
|
|
205
|
+
* expires or when the oldest is evicted. The unique index is the real guarantee across isolates.
|
|
206
|
+
*/
|
|
207
|
+
export class ReplayCache {
|
|
208
|
+
#max ;
|
|
209
|
+
#seen = new Map ();
|
|
210
|
+
|
|
211
|
+
constructor(max = 10_000) {
|
|
212
|
+
this.#max = max;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
has(id , now ) {
|
|
216
|
+
const until = this.#seen.get(id);
|
|
217
|
+
if (until === undefined) return false;
|
|
218
|
+
if (until <= now.getTime()) {
|
|
219
|
+
this.#seen.delete(id);
|
|
220
|
+
return false;
|
|
221
|
+
}
|
|
222
|
+
return true;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Records a used challenge until it expires (Unix seconds `e`). */
|
|
226
|
+
add(id , expiresAtS ) {
|
|
227
|
+
this.#seen.delete(id);
|
|
228
|
+
this.#seen.set(id, expiresAtS * 1000);
|
|
229
|
+
while (this.#seen.size > this.#max) {
|
|
230
|
+
const oldest = this.#seen.keys().next().value;
|
|
231
|
+
if (oldest === undefined) break;
|
|
232
|
+
this.#seen.delete(oldest);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
get size() {
|
|
237
|
+
return this.#seen.size;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The purge planner (RFC-0007 §8.3–§8.4, invariant C6). Workers Cache always uses the Free-tier
|
|
3
|
+
* purge limit — 5 requests a minute, a bucket of 25, 100 tags a request — and publishing shares
|
|
4
|
+
* it, so comment moderation never purges directly:
|
|
5
|
+
*
|
|
6
|
+
* 1. The batch that changes what readers see also upserts `cloudhal-comments-<nodeId>` into
|
|
7
|
+
* `comment_purge_queue` (the store does this; bulk moderation of 50 comments on 12 entries is
|
|
8
|
+
* 12 rows and later one request).
|
|
9
|
+
* 2. **Takedowns go first and fast**: every due takedown tag is sent at once (after a 2 s
|
|
10
|
+
* micro-batch in the flusher), up to 100 a request; normal tags ride along in spare room.
|
|
11
|
+
* Takedowns may use the whole budget.
|
|
12
|
+
* 3. **Normal changes coalesce**: sent once the oldest normal row is ≥ 20 s old, and only while
|
|
13
|
+
* the last 60 s show fewer than 3 purge requests in total (publish included, from
|
|
14
|
+
* `cache_purge_log`), so a publish always finds room.
|
|
15
|
+
* 4. **Failure** keeps the rows and backs off 30 s × 2^attempts, at most 5 minutes. A takedown
|
|
16
|
+
* still waiting after 2 minutes raises `comments-purge-waiting`.
|
|
17
|
+
*
|
|
18
|
+
* Pure: the admin Worker's flusher reads the queue and the log, sends what the plan says through
|
|
19
|
+
* the `SITE` binding to `/__cloudhal/purge`, and reports back to the store.
|
|
20
|
+
*/
|
|
21
|
+
import { COMMENTS_TAG_PREFIX, commentsCacheTag } from "@cloudhal/core-ts/cache-tags";
|
|
22
|
+
export { COMMENTS_TAG_PREFIX, commentsCacheTag };
|
|
23
|
+
export type PurgePriority = "takedown" | "normal";
|
|
24
|
+
export declare const PURGE_LIMITS: {
|
|
25
|
+
readonly tagsPerRequest: 100;
|
|
26
|
+
/** Normal rows wait this long so a burst of approvals is one request. */
|
|
27
|
+
readonly normalDelayMs: 20000;
|
|
28
|
+
/** The flusher waits this long after a takedown write so a bulk hide is one request. */
|
|
29
|
+
readonly takedownMicrobatchMs: 2000;
|
|
30
|
+
/** The window the shared budget is counted over. */
|
|
31
|
+
readonly windowMs: 60000;
|
|
32
|
+
/** Normal comment purges are sent only while the window holds fewer requests than this. */
|
|
33
|
+
readonly normalMaxInWindow: 3;
|
|
34
|
+
/** Takedown requests per flush (Cloudflare's per-minute rate). */
|
|
35
|
+
readonly takedownMaxPerFlush: 5;
|
|
36
|
+
readonly backoffBaseMs: 30000;
|
|
37
|
+
readonly backoffMaxMs: 300000;
|
|
38
|
+
/** A takedown still queued after this raises `comments-purge-waiting`. */
|
|
39
|
+
readonly takedownAlertMs: 120000;
|
|
40
|
+
/** Above this many entries a settings change purges the whole site instead (§8.3). */
|
|
41
|
+
readonly siteWideAbove: 300;
|
|
42
|
+
};
|
|
43
|
+
export interface PurgeQueueRow {
|
|
44
|
+
readonly tag: string;
|
|
45
|
+
readonly priority: PurgePriority;
|
|
46
|
+
readonly enqueuedAt: string;
|
|
47
|
+
readonly attempts: number;
|
|
48
|
+
readonly nextAt: string;
|
|
49
|
+
}
|
|
50
|
+
/** A purge request recorded in `cache_purge_log` (publish or comments). */
|
|
51
|
+
export interface PurgeLogEntry {
|
|
52
|
+
readonly at: string;
|
|
53
|
+
readonly requests: number;
|
|
54
|
+
}
|
|
55
|
+
export interface PurgeRequestPlan {
|
|
56
|
+
readonly priority: PurgePriority;
|
|
57
|
+
readonly tags: readonly string[];
|
|
58
|
+
}
|
|
59
|
+
export interface PurgePlan {
|
|
60
|
+
/** Requests to send now, takedowns first. */
|
|
61
|
+
readonly requests: readonly PurgeRequestPlan[];
|
|
62
|
+
/** When the flusher should look again (`null` when the queue will be empty). */
|
|
63
|
+
readonly nextCheckAt: string | null;
|
|
64
|
+
/** A takedown has waited longer than 2 minutes (the bell's `comments-purge-waiting`). */
|
|
65
|
+
readonly takedownWaiting: boolean;
|
|
66
|
+
}
|
|
67
|
+
/** Plans one flush of a site's queue against the shared budget. */
|
|
68
|
+
export declare function planPurge(input: {
|
|
69
|
+
readonly rows: readonly PurgeQueueRow[];
|
|
70
|
+
/** Purge requests of the last 60 s, any source. */
|
|
71
|
+
readonly recent: readonly PurgeLogEntry[];
|
|
72
|
+
readonly now: Date;
|
|
73
|
+
}): PurgePlan;
|
|
74
|
+
/** Back-off after a failed purge request: 30 s × 2^attempts, at most 5 minutes (§8.4 step 5). */
|
|
75
|
+
export declare function purgeBackoffMs(attempts: number): number;
|
|
76
|
+
/**
|
|
77
|
+
* What a settings change that alters rendering purges (§8.3): the entries' comment tags, or the
|
|
78
|
+
* whole site (`everything`) when there are more than 300.
|
|
79
|
+
*/
|
|
80
|
+
export declare function settingsPurgeTags(nodeIds: readonly string[]): {
|
|
81
|
+
readonly everything: true;
|
|
82
|
+
} | {
|
|
83
|
+
readonly everything: false;
|
|
84
|
+
readonly tags: readonly string[];
|
|
85
|
+
};
|
|
86
|
+
/** True for a tag this package enqueues. */
|
|
87
|
+
export declare const isCommentsCacheTag: (tag: string) => boolean;
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The purge planner (RFC-0007 §8.3–§8.4, invariant C6). Workers Cache always uses the Free-tier
|
|
3
|
+
* purge limit — 5 requests a minute, a bucket of 25, 100 tags a request — and publishing shares
|
|
4
|
+
* it, so comment moderation never purges directly:
|
|
5
|
+
*
|
|
6
|
+
* 1. The batch that changes what readers see also upserts `cloudhal-comments-<nodeId>` into
|
|
7
|
+
* `comment_purge_queue` (the store does this; bulk moderation of 50 comments on 12 entries is
|
|
8
|
+
* 12 rows and later one request).
|
|
9
|
+
* 2. **Takedowns go first and fast**: every due takedown tag is sent at once (after a 2 s
|
|
10
|
+
* micro-batch in the flusher), up to 100 a request; normal tags ride along in spare room.
|
|
11
|
+
* Takedowns may use the whole budget.
|
|
12
|
+
* 3. **Normal changes coalesce**: sent once the oldest normal row is ≥ 20 s old, and only while
|
|
13
|
+
* the last 60 s show fewer than 3 purge requests in total (publish included, from
|
|
14
|
+
* `cache_purge_log`), so a publish always finds room.
|
|
15
|
+
* 4. **Failure** keeps the rows and backs off 30 s × 2^attempts, at most 5 minutes. A takedown
|
|
16
|
+
* still waiting after 2 minutes raises `comments-purge-waiting`.
|
|
17
|
+
*
|
|
18
|
+
* Pure: the admin Worker's flusher reads the queue and the log, sends what the plan says through
|
|
19
|
+
* the `SITE` binding to `/__cloudhal/purge`, and reports back to the store.
|
|
20
|
+
*/
|
|
21
|
+
import { COMMENTS_TAG_PREFIX, commentsCacheTag } from "@cloudhal/core-ts/cache-tags";
|
|
22
|
+
|
|
23
|
+
export { COMMENTS_TAG_PREFIX, commentsCacheTag };
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
export const PURGE_LIMITS = {
|
|
28
|
+
tagsPerRequest: 100,
|
|
29
|
+
/** Normal rows wait this long so a burst of approvals is one request. */
|
|
30
|
+
normalDelayMs: 20_000,
|
|
31
|
+
/** The flusher waits this long after a takedown write so a bulk hide is one request. */
|
|
32
|
+
takedownMicrobatchMs: 2_000,
|
|
33
|
+
/** The window the shared budget is counted over. */
|
|
34
|
+
windowMs: 60_000,
|
|
35
|
+
/** Normal comment purges are sent only while the window holds fewer requests than this. */
|
|
36
|
+
normalMaxInWindow: 3,
|
|
37
|
+
/** Takedown requests per flush (Cloudflare's per-minute rate). */
|
|
38
|
+
takedownMaxPerFlush: 5,
|
|
39
|
+
backoffBaseMs: 30_000,
|
|
40
|
+
backoffMaxMs: 300_000,
|
|
41
|
+
/** A takedown still queued after this raises `comments-purge-waiting`. */
|
|
42
|
+
takedownAlertMs: 120_000,
|
|
43
|
+
/** Above this many entries a settings change purges the whole site instead (§8.3). */
|
|
44
|
+
siteWideAbove: 300,
|
|
45
|
+
} ;
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
/** A purge request recorded in `cache_purge_log` (publish or comments). */
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
const ms = (iso ) => Date.parse(iso);
|
|
76
|
+
|
|
77
|
+
function chunk (xs , n ) {
|
|
78
|
+
const out = [];
|
|
79
|
+
for (let i = 0; i < xs.length; i += n) out.push(xs.slice(i, i + n));
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Plans one flush of a site's queue against the shared budget. */
|
|
84
|
+
export function planPurge(input
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
) {
|
|
90
|
+
const now = input.now.getTime();
|
|
91
|
+
const L = PURGE_LIMITS;
|
|
92
|
+
const byAge = [...input.rows].sort(
|
|
93
|
+
(a, b) => ms(a.enqueuedAt) - ms(b.enqueuedAt) || a.tag.localeCompare(b.tag),
|
|
94
|
+
);
|
|
95
|
+
const due = byAge.filter((r) => ms(r.nextAt) <= now);
|
|
96
|
+
const takedowns = due.filter((r) => r.priority === "takedown").map((r) => r.tag);
|
|
97
|
+
let normals = due.filter((r) => r.priority === "normal");
|
|
98
|
+
const requests = [];
|
|
99
|
+
|
|
100
|
+
// 2. takedowns first; spare room carries due normal tags of any age
|
|
101
|
+
for (const tags of chunk(takedowns, L.tagsPerRequest).slice(0, L.takedownMaxPerFlush)) {
|
|
102
|
+
const room = L.tagsPerRequest - tags.length;
|
|
103
|
+
const ride = normals.slice(0, room).map((r) => r.tag);
|
|
104
|
+
normals = normals.slice(ride.length);
|
|
105
|
+
requests.push({ priority: "takedown", tags: [...tags, ...ride] });
|
|
106
|
+
}
|
|
107
|
+
const takedownsLeft = Math.max(0, takedowns.length - L.takedownMaxPerFlush * L.tagsPerRequest);
|
|
108
|
+
|
|
109
|
+
// 3. normal rows once the oldest is 20 s old, while the window has room
|
|
110
|
+
const windowStart = now - L.windowMs;
|
|
111
|
+
const inWindow = input.recent
|
|
112
|
+
.filter((e) => ms(e.at) > windowStart && ms(e.at) <= now)
|
|
113
|
+
.reduce((n, e) => n + e.requests, 0);
|
|
114
|
+
let budgetBlockedUntil ;
|
|
115
|
+
const oldest = normals[0];
|
|
116
|
+
const ripe = oldest !== undefined && ms(oldest.enqueuedAt) + L.normalDelayMs <= now;
|
|
117
|
+
if (ripe) {
|
|
118
|
+
let used = inWindow + requests.length;
|
|
119
|
+
for (const tags of chunk(
|
|
120
|
+
normals.map((r) => r.tag),
|
|
121
|
+
L.tagsPerRequest,
|
|
122
|
+
)) {
|
|
123
|
+
if (used >= L.normalMaxInWindow) break;
|
|
124
|
+
requests.push({ priority: "normal", tags });
|
|
125
|
+
used++;
|
|
126
|
+
normals = normals.slice(tags.length);
|
|
127
|
+
}
|
|
128
|
+
if (normals.length > 0) {
|
|
129
|
+
// room returns when the oldest request in the window leaves it
|
|
130
|
+
const times = input.recent
|
|
131
|
+
.filter((e) => ms(e.at) > windowStart)
|
|
132
|
+
.map((e) => ms(e.at))
|
|
133
|
+
.sort((a, b) => a - b);
|
|
134
|
+
budgetBlockedUntil = (times[0] ?? now) + L.windowMs;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// when to look again
|
|
139
|
+
const sent = new Set(requests.flatMap((r) => r.tags));
|
|
140
|
+
const candidates = [];
|
|
141
|
+
for (const r of byAge) {
|
|
142
|
+
if (sent.has(r.tag)) continue;
|
|
143
|
+
const next = ms(r.nextAt);
|
|
144
|
+
if (next > now) candidates.push(next);
|
|
145
|
+
else if (r.priority === "normal")
|
|
146
|
+
candidates.push(Math.max(ms(r.enqueuedAt) + L.normalDelayMs, budgetBlockedUntil ?? now));
|
|
147
|
+
else candidates.push(now + L.takedownMicrobatchMs);
|
|
148
|
+
}
|
|
149
|
+
if (takedownsLeft > 0) candidates.push(now + L.takedownMicrobatchMs);
|
|
150
|
+
const nextCheck = candidates.length > 0 ? Math.min(...candidates) : undefined;
|
|
151
|
+
|
|
152
|
+
return {
|
|
153
|
+
requests,
|
|
154
|
+
nextCheckAt: nextCheck === undefined ? null : new Date(Math.max(nextCheck, now)).toISOString(),
|
|
155
|
+
takedownWaiting: input.rows.some(
|
|
156
|
+
(r) => r.priority === "takedown" && ms(r.enqueuedAt) + L.takedownAlertMs <= now,
|
|
157
|
+
),
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Back-off after a failed purge request: 30 s × 2^attempts, at most 5 minutes (§8.4 step 5). */
|
|
162
|
+
export function purgeBackoffMs(attempts ) {
|
|
163
|
+
return Math.min(
|
|
164
|
+
PURGE_LIMITS.backoffBaseMs * 2 ** Math.max(0, attempts),
|
|
165
|
+
PURGE_LIMITS.backoffMaxMs,
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* What a settings change that alters rendering purges (§8.3): the entries' comment tags, or the
|
|
171
|
+
* whole site (`everything`) when there are more than 300.
|
|
172
|
+
*/
|
|
173
|
+
export function settingsPurgeTags(
|
|
174
|
+
nodeIds ,
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
{
|
|
178
|
+
const unique = [...new Set(nodeIds)];
|
|
179
|
+
if (unique.length > PURGE_LIMITS.siteWideAbove) return { everything: true };
|
|
180
|
+
return { everything: false, tags: unique.map(commentsCacheTag) };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** True for a tag this package enqueues. */
|
|
184
|
+
export const isCommentsCacheTag = (tag ) =>
|
|
185
|
+
tag.startsWith(COMMENTS_TAG_PREFIX) &&
|
|
186
|
+
/^[A-Za-z0-9_]{1,64}$/.test(tag.slice(COMMENTS_TAG_PREFIX.length));
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type RetentionSettings } from "./settings.js";
|
|
2
|
+
export declare const RETENTION_BUDGET = 500;
|
|
3
|
+
/** Comments of a deleted entry are deleted this long after the entry. */
|
|
4
|
+
export declare const DELETED_ENTRY_DAYS = 30;
|
|
5
|
+
/** `cache_purge_log` rows older than this are deleted (the budget window is 60 s). */
|
|
6
|
+
export declare const PURGE_LOG_KEEP_MS = 3600000;
|
|
7
|
+
export type RetentionStepKind = "pending" | "spam" | "deleted" | "hidden" | "tombstones" | "client-data" | "reports" | "events" | "emails" | "bans";
|
|
8
|
+
export interface RetentionStep {
|
|
9
|
+
readonly kind: RetentionStepKind;
|
|
10
|
+
/** Rows older than this instant are affected (bans: expired before it). */
|
|
11
|
+
readonly cutoff: string;
|
|
12
|
+
}
|
|
13
|
+
export interface RetentionPlan {
|
|
14
|
+
readonly steps: readonly RetentionStep[];
|
|
15
|
+
/** Rows the run may touch in total. */
|
|
16
|
+
readonly budget: number;
|
|
17
|
+
}
|
|
18
|
+
/** A site's retention steps, in the order they must run (comments before the emails they free). */
|
|
19
|
+
export declare function retentionPlan(retention: RetentionSettings | undefined, now: Date, budget?: number): RetentionPlan;
|
|
20
|
+
/** Salts of months before the previous one are deleted (§9.2): the oldest month to keep. */
|
|
21
|
+
export declare function oldestSaltMonthToKeep(now: Date): string;
|
|
22
|
+
/** Entries deleted at least 30 days ago whose comments the job may delete. */
|
|
23
|
+
export declare function deletedEntriesDue(deleted: readonly {
|
|
24
|
+
readonly nodeId: string;
|
|
25
|
+
readonly deletedAt: string;
|
|
26
|
+
}[], now: Date): string[];
|
|
27
|
+
export interface RetentionReport {
|
|
28
|
+
/** Rows touched per step. */
|
|
29
|
+
readonly counts: Readonly<Partial<Record<RetentionStepKind | "entries", number>>>;
|
|
30
|
+
/** True when the budget ran out (the next run continues). */
|
|
31
|
+
readonly more: boolean;
|
|
32
|
+
}
|