@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,73 @@
|
|
|
1
|
+
export declare const ISOLATE_LIMITS: {
|
|
2
|
+
readonly challengesPerClientPerMinute: 20;
|
|
3
|
+
readonly submissionsPerClientPerMinute: 3;
|
|
4
|
+
readonly submissionsPerSitePerMinute: 30;
|
|
5
|
+
/** Every request without a client address, together (one shared, stricter bucket). */
|
|
6
|
+
readonly unknownChallengesPerMinute: 5;
|
|
7
|
+
readonly unknownSubmissionsPerMinute: 1;
|
|
8
|
+
};
|
|
9
|
+
/** The isolate key of requests without a client address (an HMAC key is 24 hex characters). */
|
|
10
|
+
export declare const UNKNOWN_CLIENT_KEY = "unknown-client";
|
|
11
|
+
/** Stored-row limits read from D1 (§6.5). */
|
|
12
|
+
export declare const STORED_LIMITS: {
|
|
13
|
+
readonly commentsPerClientPerHour: 5;
|
|
14
|
+
readonly commentsPerClientPerDay: 20;
|
|
15
|
+
/** One JavaScript-less post per client per 10 minutes. */
|
|
16
|
+
readonly noScriptWindowMs: number;
|
|
17
|
+
readonly noScriptPerSitePerDay: 20;
|
|
18
|
+
readonly pendingPerEntry: 200;
|
|
19
|
+
readonly reportsPerClientPerHour: 5;
|
|
20
|
+
readonly reportsPerSitePerDay: 200;
|
|
21
|
+
};
|
|
22
|
+
export interface CommentLimiterOptions {
|
|
23
|
+
readonly challengesPerMinute?: number;
|
|
24
|
+
readonly submissionsPerMinute?: number;
|
|
25
|
+
readonly sitePerMinute?: number;
|
|
26
|
+
readonly unknownChallengesPerMinute?: number;
|
|
27
|
+
readonly unknownSubmissionsPerMinute?: number;
|
|
28
|
+
readonly now?: () => number;
|
|
29
|
+
}
|
|
30
|
+
/** The isolate's counters. One instance per isolate, shared by every request. */
|
|
31
|
+
export declare class CommentLimiter {
|
|
32
|
+
#private;
|
|
33
|
+
constructor(options?: CommentLimiterOptions);
|
|
34
|
+
/**
|
|
35
|
+
* HMAC(per-isolate key, client network): the isolate's client key; never stored. An IPv6
|
|
36
|
+
* address counts by its /64, so rotating within one's own prefix gains nothing; a request
|
|
37
|
+
* without an address gets `UNKNOWN_CLIENT_KEY`.
|
|
38
|
+
*/
|
|
39
|
+
clientKey(address: string): Promise<string>;
|
|
40
|
+
allowChallenge(clientKey: string): boolean;
|
|
41
|
+
allowSubmission(clientKey: string): boolean;
|
|
42
|
+
allowSite(siteId: string): boolean;
|
|
43
|
+
/** Seconds a limited client should wait. */
|
|
44
|
+
retryAfterS(): number;
|
|
45
|
+
}
|
|
46
|
+
export interface StoredToday {
|
|
47
|
+
readonly total: number;
|
|
48
|
+
readonly withoutScript: number;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Today's stored submissions for a site, memoised `ttlMs` (30 s) per isolate and incremented
|
|
52
|
+
* locally after each store, so the daily cap needs one indexed `COUNT` per isolate every 30 s.
|
|
53
|
+
*/
|
|
54
|
+
export declare class DailyCount {
|
|
55
|
+
#private;
|
|
56
|
+
constructor(options?: {
|
|
57
|
+
ttlMs?: number;
|
|
58
|
+
now?: () => number;
|
|
59
|
+
});
|
|
60
|
+
get(siteId: string, day: string, load: () => Promise<StoredToday>): Promise<StoredToday>;
|
|
61
|
+
/** Counts one stored submission in the memo. */
|
|
62
|
+
increment(siteId: string, withoutScript: boolean): void;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* A memo for a loader (the site's settings, 60 s per isolate). A failed load is not cached, so
|
|
66
|
+
* the next request tries again; callers treat a failure as "off" (fail closed).
|
|
67
|
+
*/
|
|
68
|
+
export declare function memoize<T>(load: () => Promise<T>, options?: {
|
|
69
|
+
ttlMs?: number;
|
|
70
|
+
now?: () => number;
|
|
71
|
+
}): (() => Promise<T>) & {
|
|
72
|
+
reset(): void;
|
|
73
|
+
};
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-isolate limits and memos for the site Worker (RFC-0007 §6.5). Nothing here is stored and no
|
|
3
|
+
* IP address is kept: clients are counted by HMAC(per-isolate random key, network) — an IPv6
|
|
4
|
+
* address by its /64, like the D1 limits and the IP hash — and the counters are dropped every
|
|
5
|
+
* window. Requests without an address the runtime vouches for share one separate bucket with
|
|
6
|
+
* stricter limits, so they can neither pass as many clients nor use up real clients' allowance.
|
|
7
|
+
*
|
|
8
|
+
* | Limit | Default |
|
|
9
|
+
* |---|---|
|
|
10
|
+
* | Challenges per client | 20 a minute |
|
|
11
|
+
* | Submissions per client | 3 a minute |
|
|
12
|
+
* | Challenges / submissions, all clients without an address together | 5 / 1 a minute |
|
|
13
|
+
* | Submissions per site | 30 a minute |
|
|
14
|
+
*
|
|
15
|
+
* The cross-isolate limits (stored comments per client, the daily cap, JavaScript-less posts,
|
|
16
|
+
* pending per entry, reports) are indexed D1 reads in the pipeline; `DailyCount` memoises the daily
|
|
17
|
+
* count for 30 s and increments it locally after each store.
|
|
18
|
+
*/
|
|
19
|
+
import { hmac, toHex, utf8 } from "./crypto.js";
|
|
20
|
+
import { clientNetwork, isClientAddress } from "./hashes.js";
|
|
21
|
+
import { MINUTE_MS } from "./model.js";
|
|
22
|
+
|
|
23
|
+
export const ISOLATE_LIMITS = {
|
|
24
|
+
challengesPerClientPerMinute: 20,
|
|
25
|
+
submissionsPerClientPerMinute: 3,
|
|
26
|
+
submissionsPerSitePerMinute: 30,
|
|
27
|
+
/** Every request without a client address, together (one shared, stricter bucket). */
|
|
28
|
+
unknownChallengesPerMinute: 5,
|
|
29
|
+
unknownSubmissionsPerMinute: 1,
|
|
30
|
+
} ;
|
|
31
|
+
|
|
32
|
+
/** The isolate key of requests without a client address (an HMAC key is 24 hex characters). */
|
|
33
|
+
export const UNKNOWN_CLIENT_KEY = "unknown-client";
|
|
34
|
+
|
|
35
|
+
/** Stored-row limits read from D1 (§6.5). */
|
|
36
|
+
export const STORED_LIMITS = {
|
|
37
|
+
commentsPerClientPerHour: 5,
|
|
38
|
+
commentsPerClientPerDay: 20,
|
|
39
|
+
/** One JavaScript-less post per client per 10 minutes. */
|
|
40
|
+
noScriptWindowMs: 10 * MINUTE_MS,
|
|
41
|
+
noScriptPerSitePerDay: 20,
|
|
42
|
+
pendingPerEntry: 200,
|
|
43
|
+
reportsPerClientPerHour: 5,
|
|
44
|
+
reportsPerSitePerDay: 200,
|
|
45
|
+
} ;
|
|
46
|
+
|
|
47
|
+
const MAX_KEYS = 20_000;
|
|
48
|
+
|
|
49
|
+
class WindowCounter {
|
|
50
|
+
#window = -1;
|
|
51
|
+
#counts = new Map ();
|
|
52
|
+
#windowMs ;
|
|
53
|
+
|
|
54
|
+
constructor(windowMs ) {
|
|
55
|
+
this.#windowMs = windowMs;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Counts one hit; true while the key is within `limit` in the current window. */
|
|
59
|
+
hit(key , limit , nowMs ) {
|
|
60
|
+
const w = Math.floor(nowMs / this.#windowMs);
|
|
61
|
+
if (w !== this.#window) {
|
|
62
|
+
this.#window = w;
|
|
63
|
+
this.#counts = new Map();
|
|
64
|
+
}
|
|
65
|
+
if (this.#counts.size >= MAX_KEYS && !this.#counts.has(key)) return false;
|
|
66
|
+
const n = (this.#counts.get(key) ?? 0) + 1;
|
|
67
|
+
this.#counts.set(key, n);
|
|
68
|
+
return n <= limit;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Milliseconds until the window ends. */
|
|
72
|
+
retryAfterMs(nowMs ) {
|
|
73
|
+
return this.#windowMs - (nowMs % this.#windowMs);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
/** The isolate's counters. One instance per isolate, shared by every request. */
|
|
87
|
+
export class CommentLimiter {
|
|
88
|
+
#now ;
|
|
89
|
+
#challenges = new WindowCounter(MINUTE_MS);
|
|
90
|
+
#submissions = new WindowCounter(MINUTE_MS);
|
|
91
|
+
#site = new WindowCounter(MINUTE_MS);
|
|
92
|
+
#limits ;
|
|
93
|
+
#key ;
|
|
94
|
+
|
|
95
|
+
constructor(options = {}) {
|
|
96
|
+
this.#now = options.now ?? Date.now;
|
|
97
|
+
this.#limits = {
|
|
98
|
+
challengesPerMinute:
|
|
99
|
+
options.challengesPerMinute ?? ISOLATE_LIMITS.challengesPerClientPerMinute,
|
|
100
|
+
submissionsPerMinute:
|
|
101
|
+
options.submissionsPerMinute ?? ISOLATE_LIMITS.submissionsPerClientPerMinute,
|
|
102
|
+
sitePerMinute: options.sitePerMinute ?? ISOLATE_LIMITS.submissionsPerSitePerMinute,
|
|
103
|
+
unknownChallengesPerMinute:
|
|
104
|
+
options.unknownChallengesPerMinute ?? ISOLATE_LIMITS.unknownChallengesPerMinute,
|
|
105
|
+
unknownSubmissionsPerMinute:
|
|
106
|
+
options.unknownSubmissionsPerMinute ?? ISOLATE_LIMITS.unknownSubmissionsPerMinute,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* HMAC(per-isolate key, client network): the isolate's client key; never stored. An IPv6
|
|
112
|
+
* address counts by its /64, so rotating within one's own prefix gains nothing; a request
|
|
113
|
+
* without an address gets `UNKNOWN_CLIENT_KEY`.
|
|
114
|
+
*/
|
|
115
|
+
async clientKey(address ) {
|
|
116
|
+
if (!isClientAddress(address)) return UNKNOWN_CLIENT_KEY;
|
|
117
|
+
this.#key ??= crypto.subtle.generateKey({ name: "HMAC", hash: "SHA-256" }, false, [
|
|
118
|
+
"sign",
|
|
119
|
+
]) ;
|
|
120
|
+
return toHex((await hmac(await this.#key, utf8(clientNetwork(address)))).slice(0, 12));
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
allowChallenge(clientKey ) {
|
|
124
|
+
const limit =
|
|
125
|
+
clientKey === UNKNOWN_CLIENT_KEY
|
|
126
|
+
? this.#limits.unknownChallengesPerMinute
|
|
127
|
+
: this.#limits.challengesPerMinute;
|
|
128
|
+
return this.#challenges.hit(clientKey, limit, this.#now());
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
allowSubmission(clientKey ) {
|
|
132
|
+
const limit =
|
|
133
|
+
clientKey === UNKNOWN_CLIENT_KEY
|
|
134
|
+
? this.#limits.unknownSubmissionsPerMinute
|
|
135
|
+
: this.#limits.submissionsPerMinute;
|
|
136
|
+
return this.#submissions.hit(clientKey, limit, this.#now());
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
allowSite(siteId ) {
|
|
140
|
+
return this.#site.hit(siteId, this.#limits.sitePerMinute, this.#now());
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Seconds a limited client should wait. */
|
|
144
|
+
retryAfterS() {
|
|
145
|
+
return Math.max(1, Math.ceil(this.#submissions.retryAfterMs(this.#now()) / 1000));
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Today's stored submissions for a site, memoised `ttlMs` (30 s) per isolate and incremented
|
|
156
|
+
* locally after each store, so the daily cap needs one indexed `COUNT` per isolate every 30 s.
|
|
157
|
+
*/
|
|
158
|
+
export class DailyCount {
|
|
159
|
+
#ttl ;
|
|
160
|
+
#now ;
|
|
161
|
+
#memo = new Map
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
();
|
|
165
|
+
|
|
166
|
+
constructor(options = {}) {
|
|
167
|
+
this.#ttl = options.ttlMs ?? 30_000;
|
|
168
|
+
this.#now = options.now ?? Date.now;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async get(siteId , day , load ) {
|
|
172
|
+
const t = this.#now();
|
|
173
|
+
let m = this.#memo.get(siteId);
|
|
174
|
+
if (!m || m.day !== day || t - m.at >= this.#ttl) {
|
|
175
|
+
const value = load();
|
|
176
|
+
m = { day, at: t, value, extra: { total: 0, withoutScript: 0 } };
|
|
177
|
+
this.#memo.set(siteId, m);
|
|
178
|
+
value.catch(() => {
|
|
179
|
+
if (this.#memo.get(siteId)?.value === value) this.#memo.delete(siteId);
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
const base = await m.value;
|
|
183
|
+
return {
|
|
184
|
+
total: base.total + m.extra.total,
|
|
185
|
+
withoutScript: base.withoutScript + m.extra.withoutScript,
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Counts one stored submission in the memo. */
|
|
190
|
+
increment(siteId , withoutScript ) {
|
|
191
|
+
const m = this.#memo.get(siteId);
|
|
192
|
+
if (!m) return;
|
|
193
|
+
m.extra = {
|
|
194
|
+
total: m.extra.total + 1,
|
|
195
|
+
withoutScript: m.extra.withoutScript + (withoutScript ? 1 : 0),
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* A memo for a loader (the site's settings, 60 s per isolate). A failed load is not cached, so
|
|
202
|
+
* the next request tries again; callers treat a failure as "off" (fail closed).
|
|
203
|
+
*/
|
|
204
|
+
export function memoize (
|
|
205
|
+
load ,
|
|
206
|
+
options = {},
|
|
207
|
+
) {
|
|
208
|
+
const ttl = options.ttlMs ?? 60_000;
|
|
209
|
+
const now = options.now ?? Date.now;
|
|
210
|
+
let memo ;
|
|
211
|
+
const fn = () => {
|
|
212
|
+
const t = now();
|
|
213
|
+
if (!memo || t - memo.at >= ttl) {
|
|
214
|
+
const value = load();
|
|
215
|
+
memo = { at: t, value };
|
|
216
|
+
value.catch(() => {
|
|
217
|
+
if (memo?.value === value) memo = undefined;
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
return memo.value;
|
|
221
|
+
};
|
|
222
|
+
return Object.assign(fn, {
|
|
223
|
+
reset: () => {
|
|
224
|
+
memo = undefined;
|
|
225
|
+
},
|
|
226
|
+
});
|
|
227
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plain text → paragraphs, lines and safe links (RFC-0007 §6.4, §8.1, §14, invariant C7). The one
|
|
3
|
+
* link rule shared by the public renderer and Studio's comment blocks, so the preview a moderator
|
|
4
|
+
* sees is the page readers get. Worker-safe; no DOM.
|
|
5
|
+
*
|
|
6
|
+
* - Candidates are `https?://…` and `www.…` runs up to whitespace, `<`, `>`, quotes or a backtick
|
|
7
|
+
* (what §6.4 counts as links). A candidate glued to a letter, digit or `_` is not a link.
|
|
8
|
+
* - Sentence punctuation and unbalanced closing brackets are trimmed from the end.
|
|
9
|
+
* - Only `https:` URLs with a dotted host and no user name or password become links
|
|
10
|
+
* (`https://bank.example@evil.example` stays text); `http:`, bare `www.`, `javascript:` and every
|
|
11
|
+
* other scheme stay literal text. `href` is the parsed URL (international hosts in punycode);
|
|
12
|
+
* the link text is what was typed.
|
|
13
|
+
* - Paragraphs split on blank lines, lines on single line feeds.
|
|
14
|
+
*
|
|
15
|
+
* These rules are identical to the interim copy in `@cloudhal/ui` (`blocks/comment-model.ts`,
|
|
16
|
+
* `parseCommentText`/`safeCommentHref`), checked by the shared fixture
|
|
17
|
+
* `@cloudhal/comments/fixtures/comment-text.json`. `commentTextHtml` adds the escaping for
|
|
18
|
+
* server-rendered HTML.
|
|
19
|
+
*/
|
|
20
|
+
export declare const COMMENT_LINK_REL = "ugc nofollow noopener noreferrer";
|
|
21
|
+
export type TextSegment = {
|
|
22
|
+
readonly kind: "text";
|
|
23
|
+
readonly text: string;
|
|
24
|
+
} | {
|
|
25
|
+
readonly kind: "link";
|
|
26
|
+
readonly text: string;
|
|
27
|
+
readonly href: string;
|
|
28
|
+
};
|
|
29
|
+
/** One line of a paragraph: text and link segments, in order. */
|
|
30
|
+
export type TextLine = TextSegment[];
|
|
31
|
+
/** A paragraph: lines separated by single line feeds. */
|
|
32
|
+
export type TextParagraph = TextLine[];
|
|
33
|
+
export declare const escapeHtml: (s: string) => string;
|
|
34
|
+
/**
|
|
35
|
+
* The link rule: the normalised `href` of an `https:` URL with a dotted host and no credentials,
|
|
36
|
+
* or `undefined` when the candidate must stay text.
|
|
37
|
+
*/
|
|
38
|
+
export declare function safeCommentHref(candidate: string): string | undefined;
|
|
39
|
+
/** Splits one line into text and link segments. */
|
|
40
|
+
export declare function linkifyCommentLine(line: string): TextLine;
|
|
41
|
+
/** Segments of a whole text; line feeds stay inside text segments. */
|
|
42
|
+
export declare function linkify(text: string): TextSegment[];
|
|
43
|
+
/**
|
|
44
|
+
* Comment text as paragraphs (split on blank lines) of lines (split on line feeds) of segments.
|
|
45
|
+
* `\r\n` is folded too, so imported text renders the same.
|
|
46
|
+
*/
|
|
47
|
+
export declare function parseCommentText(text: string): TextParagraph[];
|
|
48
|
+
/**
|
|
49
|
+
* Server-rendered HTML for the public page: `<p>` per paragraph, `<br>` between lines, every
|
|
50
|
+
* character escaped, links with `rel="ugc nofollow noopener noreferrer"`. No `target`: the public
|
|
51
|
+
* page leaves that to the reader (Studio's block opens links in a new tab).
|
|
52
|
+
*/
|
|
53
|
+
export declare function commentTextHtml(text: string): string;
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plain text → paragraphs, lines and safe links (RFC-0007 §6.4, §8.1, §14, invariant C7). The one
|
|
3
|
+
* link rule shared by the public renderer and Studio's comment blocks, so the preview a moderator
|
|
4
|
+
* sees is the page readers get. Worker-safe; no DOM.
|
|
5
|
+
*
|
|
6
|
+
* - Candidates are `https?://…` and `www.…` runs up to whitespace, `<`, `>`, quotes or a backtick
|
|
7
|
+
* (what §6.4 counts as links). A candidate glued to a letter, digit or `_` is not a link.
|
|
8
|
+
* - Sentence punctuation and unbalanced closing brackets are trimmed from the end.
|
|
9
|
+
* - Only `https:` URLs with a dotted host and no user name or password become links
|
|
10
|
+
* (`https://bank.example@evil.example` stays text); `http:`, bare `www.`, `javascript:` and every
|
|
11
|
+
* other scheme stay literal text. `href` is the parsed URL (international hosts in punycode);
|
|
12
|
+
* the link text is what was typed.
|
|
13
|
+
* - Paragraphs split on blank lines, lines on single line feeds.
|
|
14
|
+
*
|
|
15
|
+
* These rules are identical to the interim copy in `@cloudhal/ui` (`blocks/comment-model.ts`,
|
|
16
|
+
* `parseCommentText`/`safeCommentHref`), checked by the shared fixture
|
|
17
|
+
* `@cloudhal/comments/fixtures/comment-text.json`. `commentTextHtml` adds the escaping for
|
|
18
|
+
* server-rendered HTML.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
export const COMMENT_LINK_REL = "ugc nofollow noopener noreferrer";
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
/** One line of a paragraph: text and link segments, in order. */
|
|
27
|
+
|
|
28
|
+
/** A paragraph: lines separated by single line feeds. */
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
const ESCAPES = {
|
|
32
|
+
"&": "&",
|
|
33
|
+
"<": "<",
|
|
34
|
+
">": ">",
|
|
35
|
+
'"': """,
|
|
36
|
+
"'": "'",
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
export const escapeHtml = (s ) => s.replace(/[&<>"']/g, (c) => ESCAPES[c] ?? c);
|
|
40
|
+
|
|
41
|
+
const CANDIDATE = /(?:https?:\/\/|www\.)[^\s<>"'`]+/gi;
|
|
42
|
+
const TRAILING = /[.,;:!?'"’”»)\]}>]$/;
|
|
43
|
+
const PAIRS = { ")": "(", "]": "[", "}": "{" };
|
|
44
|
+
|
|
45
|
+
/** Strips sentence punctuation (and unbalanced closing brackets) from the end of a candidate. */
|
|
46
|
+
function trimCandidate(candidate ) {
|
|
47
|
+
let out = candidate;
|
|
48
|
+
while (TRAILING.test(out)) {
|
|
49
|
+
const last = out.at(-1) ;
|
|
50
|
+
const open = PAIRS[last];
|
|
51
|
+
if (open && out.split(open).length - 1 >= out.split(last).length - 1) break;
|
|
52
|
+
out = out.slice(0, -1);
|
|
53
|
+
}
|
|
54
|
+
return out;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The link rule: the normalised `href` of an `https:` URL with a dotted host and no credentials,
|
|
59
|
+
* or `undefined` when the candidate must stay text.
|
|
60
|
+
*/
|
|
61
|
+
export function safeCommentHref(candidate ) {
|
|
62
|
+
if (!/^https:\/\//i.test(candidate)) return undefined;
|
|
63
|
+
let url ;
|
|
64
|
+
try {
|
|
65
|
+
url = new URL(candidate);
|
|
66
|
+
} catch {
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
if (url.protocol !== "https:" || url.username || url.password) return undefined;
|
|
70
|
+
if (!url.hostname.includes(".") || url.hostname.endsWith(".")) return undefined;
|
|
71
|
+
return url.href;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Splits one line into text and link segments. */
|
|
75
|
+
export function linkifyCommentLine(line ) {
|
|
76
|
+
const out = [];
|
|
77
|
+
let at = 0;
|
|
78
|
+
const pushText = (text ) => {
|
|
79
|
+
if (!text) return;
|
|
80
|
+
const prev = out.at(-1);
|
|
81
|
+
if (prev?.kind === "text") out[out.length - 1] = { kind: "text", text: prev.text + text };
|
|
82
|
+
else out.push({ kind: "text", text });
|
|
83
|
+
};
|
|
84
|
+
for (const m of line.matchAll(CANDIDATE)) {
|
|
85
|
+
const start = m.index ?? 0;
|
|
86
|
+
// a candidate glued to a word ("foohttps://…") is not a link
|
|
87
|
+
if (start > 0 && /[\p{L}\p{N}_]/u.test(line[start - 1] )) continue;
|
|
88
|
+
const text = trimCandidate(m[0]);
|
|
89
|
+
const href = safeCommentHref(text);
|
|
90
|
+
if (!href) continue;
|
|
91
|
+
pushText(line.slice(at, start));
|
|
92
|
+
out.push({ kind: "link", text, href });
|
|
93
|
+
at = start + text.length;
|
|
94
|
+
}
|
|
95
|
+
pushText(line.slice(at));
|
|
96
|
+
return out;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Segments of a whole text; line feeds stay inside text segments. */
|
|
100
|
+
export function linkify(text ) {
|
|
101
|
+
const out = [];
|
|
102
|
+
const push = (s ) => {
|
|
103
|
+
const prev = out.at(-1);
|
|
104
|
+
if (s.kind === "text" && prev?.kind === "text")
|
|
105
|
+
out[out.length - 1] = { kind: "text", text: prev.text + s.text };
|
|
106
|
+
else out.push(s);
|
|
107
|
+
};
|
|
108
|
+
text.split("\n").forEach((line, i) => {
|
|
109
|
+
if (i > 0) push({ kind: "text", text: "\n" });
|
|
110
|
+
for (const s of linkifyCommentLine(line)) push(s);
|
|
111
|
+
});
|
|
112
|
+
return out;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Comment text as paragraphs (split on blank lines) of lines (split on line feeds) of segments.
|
|
117
|
+
* `\r\n` is folded too, so imported text renders the same.
|
|
118
|
+
*/
|
|
119
|
+
export function parseCommentText(text ) {
|
|
120
|
+
const normalised = text.replace(/\r\n?/g, "\n").trim();
|
|
121
|
+
if (!normalised) return [];
|
|
122
|
+
return normalised
|
|
123
|
+
.split(/\n[ \t]*\n+/)
|
|
124
|
+
.map((p) => p.replace(/^\n+|\n+$/g, ""))
|
|
125
|
+
.filter((p) => p.trim().length > 0)
|
|
126
|
+
.map((p) => p.split("\n").map(linkifyCommentLine));
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Server-rendered HTML for the public page: `<p>` per paragraph, `<br>` between lines, every
|
|
131
|
+
* character escaped, links with `rel="ugc nofollow noopener noreferrer"`. No `target`: the public
|
|
132
|
+
* page leaves that to the reader (Studio's block opens links in a new tab).
|
|
133
|
+
*/
|
|
134
|
+
export function commentTextHtml(text ) {
|
|
135
|
+
const segment = (s ) =>
|
|
136
|
+
s.kind === "text"
|
|
137
|
+
? escapeHtml(s.text)
|
|
138
|
+
: `<a href="${escapeHtml(s.href)}" rel="${COMMENT_LINK_REL}">${escapeHtml(s.text)}</a>`;
|
|
139
|
+
return parseCommentText(text)
|
|
140
|
+
.map((p) => `<p>${p.map((line) => line.map(segment).join("")).join("<br>")}</p>`)
|
|
141
|
+
.join("");
|
|
142
|
+
}
|