@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.
Files changed (46) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +86 -2
  3. package/dist/src/client/comments.browser.js +245 -0
  4. package/dist/src/client/index.d.ts +19 -0
  5. package/dist/src/client/index.js +39 -0
  6. package/dist/src/client/solver.browser.js +118 -0
  7. package/dist/src/crypto.d.ts +64 -0
  8. package/dist/src/crypto.js +170 -0
  9. package/dist/src/errors.d.ts +38 -0
  10. package/dist/src/errors.js +61 -0
  11. package/dist/src/fixtures/comment-text.json +335 -0
  12. package/dist/src/hashes.d.ts +70 -0
  13. package/dist/src/hashes.js +191 -0
  14. package/dist/src/index.d.ts +24 -0
  15. package/dist/src/index.js +24 -0
  16. package/dist/src/limits.d.ts +73 -0
  17. package/dist/src/limits.js +227 -0
  18. package/dist/src/linkify.d.ts +53 -0
  19. package/dist/src/linkify.js +142 -0
  20. package/dist/src/model.d.ts +287 -0
  21. package/dist/src/model.js +341 -0
  22. package/dist/src/normalize.d.ts +17 -0
  23. package/dist/src/normalize.js +125 -0
  24. package/dist/src/pipeline.d.ts +176 -0
  25. package/dist/src/pipeline.js +898 -0
  26. package/dist/src/pow.d.ts +86 -0
  27. package/dist/src/pow.js +239 -0
  28. package/dist/src/purge.d.ts +87 -0
  29. package/dist/src/purge.js +186 -0
  30. package/dist/src/retention.d.ts +32 -0
  31. package/dist/src/retention.js +106 -0
  32. package/dist/src/rules.d.ts +68 -0
  33. package/dist/src/rules.js +218 -0
  34. package/dist/src/settings.d.ts +108 -0
  35. package/dist/src/settings.js +347 -0
  36. package/dist/src/sql/index.d.ts +7 -0
  37. package/dist/src/sql/index.js +29 -0
  38. package/dist/src/sql/portability.d.ts +113 -0
  39. package/dist/src/sql/portability.js +514 -0
  40. package/dist/src/sql/rows.d.ts +54 -0
  41. package/dist/src/sql/rows.js +145 -0
  42. package/dist/src/sql/store.d.ts +312 -0
  43. package/dist/src/sql/store.js +2111 -0
  44. package/dist/src/thread.d.ts +35 -0
  45. package/dist/src/thread.js +64 -0
  46. package/package.json +61 -3
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Text normalising (RFC-0007 §6.4), applied by the server to everything a reader sends before the
3
+ * content rules run and before the result is checked against the stored `Comment` contract:
4
+ *
5
+ * - **Text:** NFC; `\r\n` and `\r` → `\n`; control characters other than tab and line feed, C1
6
+ * controls and the bidirectional embedding, override and isolate characters (U+202A–U+202E,
7
+ * U+2066–U+2069) removed; so are the directional marks (LRM U+200E, RLM U+200F, ALM U+061C)
8
+ * and the zero-width characters (ZWSP U+200B, ZWNJ U+200C, ZWJ U+200D, WJ U+2060, BOM U+FEFF),
9
+ * except a ZWJ joining two emoji (👩‍💻 stays one emoji); trailing whitespace per line removed;
10
+ * more than two blank lines collapsed to two; trimmed.
11
+ * - **Names:** NFC; the same characters removed, every ZWJ included (tabs and line breaks become
12
+ * spaces); internal whitespace collapsed to one space; trimmed.
13
+ * - **Email:** trimmed and lower-cased.
14
+ *
15
+ * The contract refuses control and bidi characters; the server removes them rather than refusing
16
+ * the comment, so a reader who pasted an invisible character is not stuck, and a comment cannot
17
+ * disguise itself in Studio either way. Directional marks and zero-width characters are removed
18
+ * too, so they cannot split a blocked word, glue look-alike names or hide in a link, but the
19
+ * contract still allows them: imported comments (other systems, Persian text with ZWNJ, emoji
20
+ * sequences) stay valid. Lengths count Unicode code points, as the validator does.
21
+ */
22
+ import { EMAIL_MAX, NAME_MAX, TEXT_MAX, TEXT_MIN } from "./model.js";
23
+
24
+ /** C0 controls except tab and LF, DEL, C1 controls, bidi embeddings/overrides/isolates. */
25
+ // Built from strings so the source never holds a literal control or bidi character.
26
+ const BIDI = "\\u202A-\\u202E\\u2066-\\u2069";
27
+ const UNSAFE_IN_TEXT = new RegExp(`[\\u0000-\\u0008\\u000B-\\u001F\\u007F-\\u009F${BIDI}]`, "gu");
28
+ const UNSAFE_IN_NAME = new RegExp(`[\\u0000-\\u001F\\u007F-\\u009F${BIDI}]`, "gu");
29
+ /** Directional marks and zero-width characters (ZWJ is handled apart in text, see below). */
30
+ const INVISIBLE = "\\u061C\\u200B\\u200C\\u200E\\u200F\\u2060\\uFEFF";
31
+ const INVISIBLE_RE = new RegExp(`[${INVISIBLE}]`, "gu");
32
+ const ZWJ_RE = /\u200D/gu;
33
+ /** A ZWJ not between two emoji (an emoji may carry VS16 or a skin tone before the joiner). */
34
+ const LONE_ZWJ_RE =
35
+ /(?<!\p{Extended_Pictographic}|\u{FE0F}|[\u{1F3FB}-\u{1F3FF}])\u200D|\u200D(?!\p{Extended_Pictographic})/gu;
36
+
37
+ /** The contract's own refusal set (for tests and defensive checks). */
38
+ export const CONTRACT_FORBIDDEN = new RegExp(`[\\u0000-\\u0008\\u000B-\\u001F\\u007F${BIDI}]`, "u");
39
+
40
+ /** Length in Unicode code points (what JSON Schema `minLength`/`maxLength` count). */
41
+ export const codePoints = (s ) => {
42
+ let n = 0;
43
+ for (const _ of s) n++;
44
+ return n;
45
+ };
46
+
47
+ /** Cuts to at most `max` code points without splitting a surrogate pair. */
48
+ export function cutCodePoints(s , max ) {
49
+ if (s.length <= max) return s;
50
+ let out = "";
51
+ let n = 0;
52
+ for (const ch of s) {
53
+ if (n++ >= max) break;
54
+ out += ch;
55
+ }
56
+ return out;
57
+ }
58
+
59
+ export function normalizeText(raw ) {
60
+ return raw
61
+ .normalize("NFC")
62
+ .replace(/\r\n?/g, "\n")
63
+ .replace(UNSAFE_IN_TEXT, "")
64
+ .replace(INVISIBLE_RE, "")
65
+ .replace(LONE_ZWJ_RE, "")
66
+ .split("\n")
67
+ .map((line) => line.replace(/[^\S\n]+$/u, ""))
68
+ .join("\n")
69
+ .replace(/\n{4,}/g, "\n\n\n")
70
+ .trim();
71
+ }
72
+
73
+ export function normalizeName(raw ) {
74
+ return raw
75
+ .normalize("NFC")
76
+ .replace(/[\t\n\r\v\f]/g, " ")
77
+ .replace(UNSAFE_IN_NAME, "")
78
+ .replace(INVISIBLE_RE, "")
79
+ .replace(ZWJ_RE, "")
80
+ .replace(/\s+/gu, " ")
81
+ .trim();
82
+ }
83
+
84
+ /** `undefined` for an empty value (forms send empty strings for optional fields). */
85
+ export function normalizeEmail(raw ) {
86
+ if (raw === undefined) return undefined;
87
+ const e = raw.trim().toLowerCase();
88
+ return e.length === 0 ? undefined : e;
89
+ }
90
+
91
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: the contract forbids control characters
92
+ const EMAIL_RE = /^[^\s@\x00-\x1F\x7F]{1,64}@[^\s@\x00-\x1F\x7F]{1,189}$/u;
93
+
94
+
95
+
96
+
97
+
98
+
99
+
100
+
101
+
102
+ /** Checks a normalised name (§6.4): 1–80 characters, no `://`, no `www.`. */
103
+ export function checkName(name ) {
104
+ if (name.length === 0) return "required";
105
+ if (codePoints(name) > NAME_MAX) return "too_long";
106
+ if (/:\/\/|www\./i.test(name)) return "link_in_name";
107
+ if (CONTRACT_FORBIDDEN.test(name)) return "invalid";
108
+ return undefined;
109
+ }
110
+
111
+ /** Checks a normalised text (§6.4): 2–5,000 characters. */
112
+ export function checkText(text ) {
113
+ const n = codePoints(text);
114
+ if (n === 0) return "required";
115
+ if (n < TEXT_MIN) return "too_short";
116
+ if (n > TEXT_MAX) return "too_long";
117
+ if (CONTRACT_FORBIDDEN.test(text)) return "invalid";
118
+ return undefined;
119
+ }
120
+
121
+ /** Checks a normalised email: ≤ 254, one `@`, no whitespace or control characters. */
122
+ export function checkEmail(email ) {
123
+ if (email.length > EMAIL_MAX || !EMAIL_RE.test(email)) return "invalid";
124
+ return undefined;
125
+ }
@@ -0,0 +1,176 @@
1
+ import { type CommentKeys } from "./crypto.js";
2
+ import { type CommentLimiter, type DailyCount } from "./limits.js";
3
+ import { type PreparedReport, type PreparedSubmission, type SubmitResult, type ThreadRow } from "./model.js";
4
+ import { type ChallengeKind, type IssuedChallenge, type ReplayCache } from "./pow.js";
5
+ import { type CommentSettings } from "./settings.js";
6
+ export declare const MAX_BODY_BYTES: number;
7
+ /** A published entry as the renderer's resolver sees it (§6.2 step 5). */
8
+ export interface PublishedEntry {
9
+ readonly nodeId: string;
10
+ readonly collection: string;
11
+ /** The entry's current public path (`/posts/ferries`): where the form returns to. */
12
+ readonly path: string;
13
+ /** First publication; the 90-day close counts from here. */
14
+ readonly publishedAt: string | null;
15
+ }
16
+ export interface TurnstileResult {
17
+ readonly success: boolean;
18
+ readonly hostname?: string;
19
+ readonly action?: string;
20
+ }
21
+ /** Calls `siteverify` with the site's secret; throws on an outage (the pipeline fails closed). */
22
+ export type TurnstileVerify = (input: {
23
+ readonly token: string;
24
+ readonly remoteip: string;
25
+ readonly idempotencyKey: string;
26
+ }) => Promise<TurnstileResult>;
27
+ /** The store reads and writes the pipeline needs (implemented by `SqlCommentStore`). */
28
+ export interface SubmissionStore {
29
+ thread(siteId: string, nodeId: string): Promise<ThreadRow | null>;
30
+ /** An approved comment of the site, or `null`. */
31
+ approvedComment(siteId: string, commentId: string): Promise<{
32
+ readonly id: string;
33
+ readonly nodeId: string;
34
+ readonly parentId: string | null;
35
+ } | null>;
36
+ /** This month's salt, read only (`undefined` when no comment created it yet). */
37
+ readSalt(month: string): Promise<string | undefined>;
38
+ clientActivity(siteId: string, ipHmac: string, since: {
39
+ readonly hour: string;
40
+ readonly day: string;
41
+ readonly noScript: string;
42
+ }): Promise<{
43
+ readonly hour: number;
44
+ readonly day: number;
45
+ readonly noScript: number;
46
+ }>;
47
+ isDuplicate(siteId: string, nodeId: string, text: string, since: string): Promise<boolean>;
48
+ storedSince(siteId: string, since: string): Promise<{
49
+ readonly total: number;
50
+ readonly withoutScript: number;
51
+ }>;
52
+ pendingOnEntry(siteId: string, nodeId: string): Promise<number>;
53
+ isBanned(siteId: string, subjects: {
54
+ readonly emailHmac?: string;
55
+ readonly ipHmac?: string;
56
+ }, now: string): Promise<boolean>;
57
+ submit(siteId: string, input: PreparedSubmission): Promise<SubmitResult>;
58
+ reportActivity(siteId: string, ipHmac: string | null, since: {
59
+ readonly hour: string;
60
+ readonly day: string;
61
+ }): Promise<{
62
+ readonly clientHour: number;
63
+ readonly siteDay: number;
64
+ }>;
65
+ report(siteId: string, input: PreparedReport): Promise<SubmitResult>;
66
+ }
67
+ export interface PipelineDeps {
68
+ /** The site Worker's own `CLOUDHAL_SITE_ID` — never taken from input (C14). */
69
+ readonly siteId: string;
70
+ /** `comments.available` for the deployment (`cloudhal.json`). */
71
+ readonly available: boolean;
72
+ /** Hosts the site answers on (lower case, with port when not default). */
73
+ readonly hosts: readonly string[];
74
+ /** The address the runtime vouches for (`CF-Connecting-IP`, the socket address). */
75
+ readonly clientAddress: string;
76
+ readonly keys: CommentKeys;
77
+ readonly now: () => Date;
78
+ /** The site's settings (memoised 60 s); `null` = no row (off). A throw counts as off. */
79
+ readonly settings: () => Promise<CommentSettings | null>;
80
+ readonly resolveEntry: (nodeId: string) => Promise<PublishedEntry | null>;
81
+ readonly store: SubmissionStore;
82
+ readonly limiter: CommentLimiter;
83
+ readonly daily: DailyCount;
84
+ readonly replay: ReplayCache;
85
+ /** The optional Rate Limiting binding (`comments.rateLimit`): true when allowed. */
86
+ readonly rateLimit?: (clientKey: string) => Promise<boolean>;
87
+ /** Required when the site uses Turnstile; absent → `503 try_again` (fail closed). */
88
+ readonly turnstile?: TurnstileVerify;
89
+ }
90
+ export type SubmissionError = "method_not_allowed" | "not_found" | "forbidden" | "unsupported_media_type" | "too_large" | "invalid" | "challenge_expired" | "script_required" | "closed" | "rate_limited" | "proof_failed" | "try_again" | "paused";
91
+ /** Why a "pending" answer stored nothing (never shown to the client). */
92
+ export type DropReason = "honeypot" | "bad_proof" | "too_fast" | "replay" | "duplicate" | "banned";
93
+ export type SubmissionOutcome = {
94
+ readonly kind: "pending";
95
+ readonly stored: boolean;
96
+ readonly id?: string;
97
+ readonly status?: "pending" | "spam";
98
+ readonly dropped?: DropReason;
99
+ readonly returnTo?: string;
100
+ /** The request was a form post (no JavaScript): answer with a redirect. */
101
+ readonly form: boolean;
102
+ } | {
103
+ readonly kind: "error";
104
+ readonly status: number;
105
+ readonly error: SubmissionError;
106
+ readonly fields?: readonly string[];
107
+ readonly retryAfter?: number;
108
+ readonly returnTo?: string;
109
+ readonly form: boolean;
110
+ };
111
+ /** A rule-matched blocked word: the statement of reasons for a `spam` comment (DSA Art. 17). */
112
+ export declare const RULES_ACTOR: {
113
+ readonly kind: "system";
114
+ readonly id: "sys_commentrules";
115
+ readonly name: "Comment rules";
116
+ };
117
+ /** A safe local path to return to: one leading slash, no scheme, no `//`, no backslash. */
118
+ export declare function safeReturnPath(path: string): string;
119
+ /** Step 2: same origin (RFC-0006's rule). */
120
+ export declare function isSameOrigin(request: Request, hosts: readonly string[]): boolean;
121
+ type BodyRead = {
122
+ readonly ok: true;
123
+ readonly fields: Record<string, unknown>;
124
+ readonly form: boolean;
125
+ } | {
126
+ readonly ok: false;
127
+ readonly status: number;
128
+ readonly error: SubmissionError;
129
+ readonly form: boolean;
130
+ };
131
+ /** Step 3: type, size and strict UTF-8, then the raw object (form or JSON). */
132
+ export declare function readSubmissionBody(request: Request, max?: number): Promise<BodyRead>;
133
+ /**
134
+ * Step 4: builds the submission (the endpoint sets `kind`, the server `schemaVersion`; empty
135
+ * optional strings from forms are dropped) and checks it with the precompiled validator.
136
+ */
137
+ export declare function buildSubmission(fields: Record<string, unknown>, kind: ChallengeKind): {
138
+ ok: true;
139
+ value: Record<string, unknown>;
140
+ } | {
141
+ ok: false;
142
+ fields: string[];
143
+ };
144
+ export declare function handleCommentSubmission(request: Request, deps: PipelineDeps): Promise<SubmissionOutcome>;
145
+ /**
146
+ * A report (§6.6, DSA Art. 16): steps 1–4, 6–8 and 10. Only an approved comment can be reported;
147
+ * a report never changes the comment's status.
148
+ */
149
+ export declare function handleReportSubmission(request: Request, deps: PipelineDeps): Promise<SubmissionOutcome>;
150
+ export type ChallengeOutcome = {
151
+ readonly kind: "challenge";
152
+ readonly challenge: IssuedChallenge;
153
+ } | {
154
+ readonly kind: "error";
155
+ readonly status: number;
156
+ readonly error: SubmissionError;
157
+ readonly retryAfter?: number;
158
+ };
159
+ /**
160
+ * Issues a challenge (§6.1, §7.2): `?node=<entry id>&for=comment` for an open thread, or
161
+ * `?node=<comment id>&for=report` for an approved comment; `404` otherwise. 20 a minute per client
162
+ * (isolate). Difficulty ramps with today's stored submissions. Writes nothing.
163
+ */
164
+ export declare function handleChallengeRequest(request: Request, deps: PipelineDeps): Promise<ChallengeOutcome>;
165
+ /**
166
+ * Turns an outcome into the response of §6.3: form posts get `303 See Other` to a fragment of the
167
+ * entry's cached page (`#comment-pending`, `#comment-invalid`, …); the module gets JSON. Every
168
+ * answer is `no-store`. Dropped submissions are indistinguishable from stored ones. `pendingFragment`
169
+ * lets the report endpoint answer `#comment-reported`.
170
+ */
171
+ export declare function submissionResponse(outcome: SubmissionOutcome, options?: {
172
+ readonly pendingFragment?: string;
173
+ }): Response;
174
+ /** The challenge endpoint's answer (JSON, `no-store`). */
175
+ export declare function challengeResponse(outcome: ChallengeOutcome): Response;
176
+ export {};