@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.
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
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,87 @@
1
- # Temporary Holding Version
1
+ # @cloudhal/comments
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ First-party reader comments for Cloudhal sites ([RFC-0007](../../docs/rfcs/0007-reader-comments.md), [ADR-0022](../../docs/adr/0022-reader-comments.md)). Guest comments are held for moderation, live in D1 **outside the site graph**, are server-rendered into the cached article page and purged by tag (`cloudhal-comments-<nodeId>`) within the Free-tier purge budget. Bots pay with a first-party proof of work; Turnstile is opt-in.
4
+
5
+ Everything here is **Worker-safe**: no Node-only import at any entry. The stored and returned record is the `Comment` contract of `@cloudhal/core-contracts`; no API returns an email address, an IP hash or a challenge outside the `commenter` accessors (invariant C1).
6
+
7
+ | Entry | What |
8
+ |---|---|
9
+ | `@cloudhal/comments` | Settings model and `threadState`, normalising, content rules, linkify, proof of work, the submission/report/challenge pipelines and their answers, keys and hashes, isolate limits, purge planner, retention plan. No storage dependency. |
10
+ | `@cloudhal/comments/sql` | `SqlCommentStore` over `SqlDriver` (SQLite locally and on Node, D1 on Cloudflare) for migration `0016_comments`. |
11
+ | `@cloudhal/comments/client` | The browser sources (Node build input only): the comments module (`/_cloudhal/c.<hash>.js`, ≤ 4 KB gzipped) and its proof-of-work worker (`/_cloudhal/cw.<hash>.js`, pure-JS SHA-256, ≤ 1 KB), built by the `cloudhal()` integration; endpoint names and budgets. |
12
+ | `@cloudhal/comments/testing` | `describeCommentStoreConformance`, `describeCommentPipelineSuite`, `countingDriver`, `expectContractComment` (vitest). |
13
+ | `@cloudhal/comments/fixtures/comment-text.json` | The shared link-rule fixture (`parseCommentText` input → paragraphs), for the renderer and Studio's blocks. |
14
+
15
+ ## Settings and thread state (§4.5)
16
+
17
+ ```ts
18
+ import { applySettingsInput, defaultCommentSettings, threadClosesAt, threadState } from "@cloudhal/comments";
19
+
20
+ const settings = await store.settings(siteId); // the row, or the defaults (off, rev 0)
21
+ threadState({ settings, entry: { nodeId, collection: "posts", publishedAt }, thread, hasApproved, now });
22
+ // → "open" | "closed" | "hidden" | "off" (90 days after first publication by default)
23
+ ```
24
+
25
+ `CommentSettingsInput` is validated by `applySettingsInput` (unknown keys refused; `CommentSettingsError`, code `invalid_settings`). `collectionEnabled`, `closeAfterDaysFor`, `threadVisible` and `DEFAULT_RETENTION` are exported too.
26
+
27
+ ## Text (§6.4, §8.1)
28
+
29
+ - `normalizeText`, `normalizeName`, `normalizeEmail`, `checkText`, `checkName`, `checkEmail`, `codePoints`, `cutCodePoints`, `CONTRACT_FORBIDDEN` — NFC, CRLF → LF, control and bidi characters removed (the contract refuses them), lengths in code points.
30
+ - `evaluateContent({ name, text }, { linkLimit, watchWords, blockedWords })` → `{ ok, status: "pending" | "spam", labels }` or `{ ok: false, field, problem }`; `compileWordList`, `matchesWordList`, `wordTokens`, `foldForMatch` (NFKC, Turkish `İ`/`I`/`ı` folded together, whole words), `countLinks`, `instructionLikeRules`/`isInstructionLike` (`INSTRUCTION_RULES_VERSION`, English and Turkish), `ruleLabels`.
31
+ - **Links:** `parseCommentText(text)` → paragraphs → lines → `{kind:"text"}|{kind:"link", href}` segments; `safeCommentHref`, `linkifyCommentLine`, `linkify`; `commentTextHtml(text)` for server-rendered HTML (escaped, `<p>`/`<br>`, `rel="ugc nofollow noopener noreferrer"` = `COMMENT_LINK_REL`). Only `https:` URLs with a dotted host and no userinfo become links. The rules match `@cloudhal/ui`'s interim `comment-model.ts`; the fixture pins them.
32
+
33
+ ## Proof of work (§7)
34
+
35
+ ```ts
36
+ import { deriveCommentKeys, difficultyFor, issueChallenge, verifyChallenge, ReplayCache } from "@cloudhal/comments";
37
+ const keys = await deriveCommentKeys(env.CLOUDHAL_COMMENTS_KEY); // HKDF per purpose: pow, emailHmac, email, secrets
38
+ const { challenge, bits, expiresAt } = await issueChallenge(keys.pow, { siteId, target: nodeId, kind: "comment", bits: difficultyFor(today, cap), now });
39
+ ```
40
+
41
+ `v1.<payload>.<mac>`, stateless, 10 minutes, ≥ 3 s fill time, 18 bits rising to 20/21 with the daily cap. `solveChallenge` is the reference solver (tests, the browser worker's algorithm). Single use: `ReplayCache` per isolate plus the unique index on `challenge_id`.
42
+
43
+ ## The pipeline (§6.2–§6.6)
44
+
45
+ ```ts
46
+ import { handleCommentSubmission, handleReportSubmission, handleChallengeRequest,
47
+ submissionResponse, challengeResponse, CommentLimiter, DailyCount, ReplayCache, memoize } from "@cloudhal/comments";
48
+ import { SqlCommentStore } from "@cloudhal/comments/sql";
49
+
50
+ // once per isolate
51
+ const limiter = new CommentLimiter(), daily = new DailyCount(), replay = new ReplayCache();
52
+ const settings = memoize(() => store.settings(env.CLOUDHAL_SITE_ID)); // 60 s
53
+
54
+ const deps: PipelineDeps = {
55
+ siteId: env.CLOUDHAL_SITE_ID, available: true, hosts, clientAddress: request.headers.get("cf-connecting-ip")!,
56
+ keys, now: () => new Date(), settings, resolveEntry, store, limiter, daily, replay,
57
+ rateLimit?: (key) => …, // optional Rate Limiting binding
58
+ turnstile?: ({ token, remoteip, idempotencyKey }) => siteverify(…), // when the site uses Turnstile
59
+ };
60
+ return submissionResponse(await handleCommentSubmission(request, deps));
61
+ // reports: submissionResponse(await handleReportSubmission(request, deps), { pendingFragment: "comment-reported" })
62
+ // challenges: challengeResponse(await handleChallengeRequest(request, deps))
63
+ ```
64
+
65
+ `resolveEntry(nodeId)` returns the **published** entry (`{ nodeId, collection, path, publishedAt }`) or `null`. Outcomes are `{ kind: "pending", stored, dropped? }` (honeypot, bad proof, replay, duplicate and bans are indistinguishable from a stored comment) or `{ kind: "error", status, error, fields?, retryAfter? }`; form posts answer `303` to `#comment-pending`, `#comment-invalid`, `#comment-closed`, `#comment-script-required`, `#comment-slow-down`, `#comment-try-again`, `#comment-paused`. Nothing is written before step 12; a month's first IP salt is inserted inside step 12's batch.
66
+
67
+ ## Store (`@cloudhal/comments/sql`)
68
+
69
+ `new SqlCommentStore(sql, { now? })`:
70
+
71
+ | Area | Methods |
72
+ |---|---|
73
+ | Settings, secrets | `settings`, `putSettings(siteId, input, rev, by)`, `putSecret`, `readSecret`, `secretInfo`, `deleteSecret` |
74
+ | Threads | `thread`, `putThread(siteId, nodeId, { mode, closesAt? }, rev, by, { purge?, audit? })` |
75
+ | Pipeline (`SubmissionStore`) | `submit`, `report`, `approvedComment`, `readSalt`, `clientActivity`, `isDuplicate`, `storedSince`, `pendingOnEntry`, `isBanned`, `reportActivity` |
76
+ | Reads | `get`, `list(siteId, { status \| "reported", nodeId, nodeIds, label, since, cursor, limit ≤ 50, order })`, `threadComments`, `renderPage(siteId, nodeId, page)`, `counts`, `history`, `stateHash(siteId, ids, threads)` (`cm1:`) |
77
+ | Moderation | `moderate(siteId, { ids ≤ 50, action, actor, reasonCode?, note?, expectedRevs, approvalId?, ownNodeIds?, audit? })` → per-comment results; `label(siteId, { items, actor, source, expectedRevs?, ownNodeIds?, audit? })`; `reply(siteId, StaffReply)`; `editReply` |
78
+ | People only | `findCommenter`, `commenter(siteId, id, keys)` (decrypts the email), `commenters(siteId, ids, keys)` (three reads for any number), `commenterComments(siteId, id)` (one read), `hideApprovedOf(siteId, commentId, { actor, reasonCode })` (bounded, `more`), `erase(siteId, { commenterId } \| { commentIds }, "anonymise" \| "delete-text", person, { note?, audit? })`, `ban`, `listBans(siteId, { commentId? })` (a commenter's bans from one of their comments), `liftBan` |
79
+ | Reports | `listReports`, `resolveReport` |
80
+ | `purgeQueue` | `queued`, `sites`, `enqueue`, `recent`, `log` (the publish path's purge log row), `sent`, `failed` — feed `planPurge` |
81
+ | `retention` | `run(siteId, retentionPlan(settings.retention, now))`, `deleteEntries(siteId, deletedEntriesDue(…))`, `runDeployment(now, oldestSaltMonthToKeep(now))` |
82
+
83
+ `approve`, `restore`, `delete`, replies, erasure and bans need a human actor (`CommentForbiddenError`, code `forbidden`); stale `rev`s are `CommentConflictError` (`conflict`) for single writes and per-comment `conflict` results for bulk writes. `audit` statements are appended to the same batch, last. Statement counts per path are in the store's header and asserted by the conformance suite.
84
+
85
+ ## Purge planner and retention (§8.4, §9.3)
86
+
87
+ `planPurge({ rows, recent, now })` → `{ requests, nextCheckAt, takedownWaiting }`: takedowns at once (normal tags ride along), normal tags after 20 s and only while the last minute shows fewer than 3 purge requests (publish included), 100 tags a request. `purgeBackoffMs`, `settingsPurgeTags` (or "everything" above 300 entries), `commentsCacheTag`, `PURGE_LIMITS`. `retentionPlan` lists the bounded steps (500 rows a run).
@@ -0,0 +1,245 @@
1
+ /**
2
+ * The comments module (RFC-0007 §8.2), served first-party as `/_cloudhal/c.<hash>.js` and loaded
3
+ * only on pages with an open thread. It enhances the server-rendered section
4
+ * (`[data-cloudhal-comments]`), whose plain HTML forms work without it:
5
+ *
6
+ * 1. when the reader focuses a form, it fetches a challenge and solves it in the dedicated worker
7
+ * (`__CLOUDHAL_SOLVER__`, replaced at build time with its hashed URL) — or, with Turnstile on,
8
+ * loads Cloudflare's widget with the form's action;
9
+ * 2. on submit it posts JSON (waiting for the proof if needed, and at least 3 s after the challenge
10
+ * was issued, the server's minimum fill time) and shows the reader's own comment inline with an
11
+ * "awaiting moderation" badge, built from what they typed (nothing is fetched back);
12
+ * 3. "Reply" moves the form under a comment and sets `parentId`;
13
+ * 4. "More comments" loads the next page (the same cached HTML) in place;
14
+ * 5. outcomes show the section's own notes (`#comment-pending`, …) and are announced in a polite
15
+ * live region.
16
+ *
17
+ * It stores nothing on the device, sets no cookie and sends no identifier. Every step is wrapped,
18
+ * so it never throws into the page; when anything fails the plain form still posts.
19
+ */
20
+ /* global __CLOUDHAL_SOLVER__ */
21
+
22
+ const ROOT = "/__cloudhal/comments";
23
+ const TURNSTILE = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
24
+ /** Errors the server answers → the note that explains them (§6.3). */
25
+ const NOTES = {
26
+ invalid: "comment-invalid",
27
+ closed: "comment-closed",
28
+ rate_limited: "comment-slow-down",
29
+ paused: "comment-paused",
30
+ script_required: "comment-script-required",
31
+ };
32
+
33
+ const make = (tag, props) => Object.assign(document.createElement(tag), props);
34
+
35
+ /** @param {HTMLElement} section */
36
+ const enhance = (section) => {
37
+ const text = section.dataset;
38
+ const live = section.querySelector("[data-live]");
39
+ const form = section.querySelector("form[data-kind=comment]");
40
+ const home = document.createComment("");
41
+ form?.before(home);
42
+ const say = (message) => {
43
+ if (live) live.textContent = message;
44
+ };
45
+ const note = (id) => {
46
+ const el = document.getElementById(id);
47
+ if (!el) return;
48
+ location.replace(`#${id}`); // shows it (`:target`) and scrolls to it
49
+ say(el.textContent.trim());
50
+ };
51
+
52
+ /** @type {WeakMap<HTMLFormElement, { until: number, ready: Promise<Record<string, string>> }>} */
53
+ const proofs = new WeakMap();
54
+ let turnstileApi;
55
+
56
+ const pow = async (kind, target) => {
57
+ const res = await fetch(`${ROOT}/challenge?node=${encodeURIComponent(target)}&for=${kind}`, {
58
+ credentials: "omit",
59
+ });
60
+ if (!res.ok) throw new Error(String(res.status));
61
+ const issued = Date.now();
62
+ const { challenge, bits } = await res.json();
63
+ const solution = await new Promise((resolve, reject) => {
64
+ const worker = new Worker(__CLOUDHAL_SOLVER__, { type: "module" });
65
+ worker.onmessage = (e) => {
66
+ worker.terminate();
67
+ resolve(e.data);
68
+ };
69
+ worker.onerror = (e) => {
70
+ worker.terminate();
71
+ reject(e);
72
+ };
73
+ worker.postMessage({ c: challenge, b: bits });
74
+ });
75
+ // the server drops solutions sooner than 3 s after issue (a person takes longer)
76
+ const wait = issued + 3200 - Date.now();
77
+ if (wait > 0) await new Promise((r) => setTimeout(r, wait));
78
+ return { challenge, solution };
79
+ };
80
+
81
+ const turnstile = async (f, kind) => {
82
+ turnstileApi ??= new Promise((resolve, reject) => {
83
+ const script = make("script", { src: TURNSTILE, async: true });
84
+ script.onload = () => resolve(window.turnstile);
85
+ script.onerror = reject;
86
+ document.head.append(script);
87
+ });
88
+ const api = await turnstileApi;
89
+ return new Promise((resolve, reject) => {
90
+ const box = make("div");
91
+ f.querySelector("[data-turnstile]")?.replaceChildren(box);
92
+ api.render(box, {
93
+ sitekey: text.sitekey,
94
+ action: kind,
95
+ "response-field": false,
96
+ callback: (token) => resolve({ turnstileToken: token }),
97
+ "error-callback": reject,
98
+ "expired-callback": () => proofs.delete(f),
99
+ });
100
+ });
101
+ };
102
+
103
+ /** Starts (or reuses) the proof for a form; a proof is used once. */
104
+ const prepare = (f) => {
105
+ const current = proofs.get(f);
106
+ if (current && current.until > Date.now()) return current.ready;
107
+ const kind = f.dataset.kind;
108
+ const target = f.elements.namedItem(kind === "report" ? "commentId" : "nodeId")?.value ?? "";
109
+ const ready = text.protection === "turnstile" ? turnstile(f, kind) : pow(kind, target);
110
+ // challenges live 10 minutes; ask for a fresh one a minute early
111
+ proofs.set(f, { until: Date.now() + 540_000, ready });
112
+ ready.catch(() => proofs.delete(f));
113
+ return ready;
114
+ };
115
+
116
+ const cancelReply = () => {
117
+ if (!form) return;
118
+ home.after(form);
119
+ form.elements.namedItem("parentId").value = "";
120
+ for (const el of form.querySelectorAll("[data-replying],[data-cancel-reply]")) el.hidden = true;
121
+ };
122
+
123
+ /** The reader's own comment, inline, awaiting moderation (built from what they typed). */
124
+ const showOwn = (body) => {
125
+ const li = make("li", { className: "cloudhal-comment cloudhal-comment-own" });
126
+ const article = li.appendChild(make("article"));
127
+ article
128
+ .appendChild(make("header", { className: "cloudhal-comment-meta" }))
129
+ .append(
130
+ make("strong", { className: "cloudhal-comment-author", textContent: body.name.trim() }),
131
+ " ",
132
+ make("span", { className: "cloudhal-comment-badge", textContent: text.pendingLabel }),
133
+ );
134
+ const content = article.appendChild(make("div", { className: "cloudhal-comment-body" }));
135
+ for (const p of body.body.trim().split(/\n\s*\n/))
136
+ content.append(make("p", { textContent: p.trim() }));
137
+ const thread = body.parentId
138
+ ? document.getElementById(`comment-${body.parentId}`)?.closest("[data-thread]")
139
+ : null;
140
+ let list = thread
141
+ ? thread.querySelector("ol")
142
+ : section.querySelector(".cloudhal-comment-list");
143
+ if (!list && thread)
144
+ list = thread.appendChild(make("ol", { className: "cloudhal-comment-replies" }));
145
+ if (list) {
146
+ list.hidden = false;
147
+ list.append(li);
148
+ }
149
+ };
150
+
151
+ const submit = async (f) => {
152
+ if (f.dataset.busy) return;
153
+ f.dataset.busy = "1";
154
+ const button = f.querySelector("[type=submit]");
155
+ const label = button?.textContent;
156
+ if (button) button.textContent = text.sending;
157
+ say(text.sending);
158
+ for (const el of f.querySelectorAll("[aria-invalid]")) el.removeAttribute("aria-invalid");
159
+ try {
160
+ for (let attempt = 0; attempt < 2; attempt++) {
161
+ const body = { ...Object.fromEntries(new FormData(f)), ...(await prepare(f)) };
162
+ proofs.delete(f);
163
+ const res = await fetch(f.action, {
164
+ method: "POST",
165
+ headers: { "content-type": "application/json" },
166
+ body: JSON.stringify(body),
167
+ credentials: "omit",
168
+ });
169
+ const answer = await res.json().catch(() => ({}));
170
+ if (res.ok) {
171
+ if (f.dataset.kind === "report") {
172
+ f.reset();
173
+ f.closest("details")?.removeAttribute("open");
174
+ return note("comment-reported");
175
+ }
176
+ showOwn(body);
177
+ f.elements.namedItem("body").value = "";
178
+ cancelReply();
179
+ return note("comment-pending");
180
+ }
181
+ if (answer.error === "challenge_expired" && attempt === 0) continue;
182
+ for (const name of answer.fields ?? [])
183
+ f.elements.namedItem(name)?.setAttribute?.("aria-invalid", "true");
184
+ return note(NOTES[answer.error] ?? "comment-try-again");
185
+ }
186
+ } catch {
187
+ note("comment-try-again");
188
+ } finally {
189
+ delete f.dataset.busy;
190
+ if (button) button.textContent = label;
191
+ }
192
+ };
193
+
194
+ const more = async (link) => {
195
+ const html = await (await fetch(link.href, { credentials: "omit" })).text();
196
+ const next = new DOMParser()
197
+ .parseFromString(html, "text/html")
198
+ .querySelector("[data-cloudhal-comments]");
199
+ const list = section.querySelector(".cloudhal-comment-list");
200
+ if (!next || !list) throw new Error("no comments");
201
+ list.append(...next.querySelectorAll(".cloudhal-comment-list > li"));
202
+ for (const b of list.querySelectorAll("[data-reply]")) b.hidden = !form;
203
+ const after = next.querySelector("[data-more]")?.getAttribute("href");
204
+ if (after) link.setAttribute("href", after);
205
+ else link.closest("nav")?.remove();
206
+ };
207
+
208
+ section.addEventListener("focusin", (e) => {
209
+ const f = e.target.closest?.("form[data-kind]");
210
+ if (f) prepare(f).catch(() => {});
211
+ });
212
+ section.addEventListener("submit", (e) => {
213
+ const f = e.target.closest?.("form[data-kind]");
214
+ if (!f) return;
215
+ e.preventDefault();
216
+ submit(f);
217
+ });
218
+ section.addEventListener("click", (e) => {
219
+ const reply = e.target.closest?.("[data-reply]");
220
+ if (reply && form) {
221
+ const li = document.getElementById(`comment-${reply.dataset.reply}`);
222
+ li?.querySelector("article")?.after(form);
223
+ form.elements.namedItem("parentId").value = reply.dataset.reply;
224
+ const replying = form.querySelector("[data-replying]");
225
+ if (replying) replying.textContent = `${text.replyLabel} ${reply.dataset.name ?? ""}`.trim();
226
+ for (const el of form.querySelectorAll("[data-replying],[data-cancel-reply]"))
227
+ el.hidden = false;
228
+ form.elements.namedItem("body").focus();
229
+ }
230
+ if (e.target.closest?.("[data-cancel-reply]")) cancelReply();
231
+ const link = e.target.closest?.("[data-more]");
232
+ if (link) {
233
+ e.preventDefault();
234
+ more(link).catch(() => {
235
+ location.href = link.href;
236
+ });
237
+ }
238
+ });
239
+ for (const b of section.querySelectorAll("[data-reply]")) b.hidden = !form;
240
+ };
241
+
242
+ try {
243
+ const section = document.querySelector("[data-cloudhal-comments]");
244
+ if (section) enhance(section);
245
+ } catch {}
@@ -0,0 +1,19 @@
1
+ /** Where the scripts are served (a static-assets directory of the site build). */
2
+ export declare const CLIENT_DIR = "/_cloudhal/";
3
+ /** The endpoints the module talks to (answered by the site Worker before Astro, §6.1). */
4
+ export declare const COMMENTS_ENDPOINT = "/__cloudhal/comments";
5
+ export declare const COMMENTS_REPORT_ENDPOINT = "/__cloudhal/comments/report";
6
+ export declare const COMMENTS_CHALLENGE_ENDPOINT = "/__cloudhal/comments/challenge";
7
+ /** The module's size budget, gzipped (RFC-0007 §8.2: ≤ 4 KB). */
8
+ export declare const MODULE_GZIP_BUDGET = 4096;
9
+ /** The worker's size budget, gzipped (RFC-0007 §8.2: ≈ 1 KB). */
10
+ export declare const SOLVER_GZIP_BUDGET = 1024;
11
+ /** Replaced in the module source with the worker's hashed URL. */
12
+ export declare const SOLVER_URL_DEFINE = "__CLOUDHAL_SOLVER__";
13
+ /** The only third-party origin the module may load from, and only with Turnstile on (§7.6). */
14
+ export declare const TURNSTILE_ORIGIN = "https://challenges.cloudflare.com";
15
+ /** Absolute paths of the two entry files (plain browser JavaScript, no imports). */
16
+ export declare const COMMENTS_CLIENT_SOURCES: {
17
+ readonly module: string;
18
+ readonly solver: string;
19
+ };
@@ -0,0 +1,39 @@
1
+ /**
2
+ * @cloudhal/comments/client — the browser sources of reader comments (RFC-0007 §7.3, §8.2) and the
3
+ * names they are served under. The `cloudhal()` Astro integration bundles them into two hashed
4
+ * static assets; nothing here runs in a Worker or in the browser as-is (Node build input only, like
5
+ * `@cloudhal/analytics/client`).
6
+ *
7
+ * - `module`: `/_cloudhal/c.<hash>.js`, loaded (`type="module"`) only on pages with an open thread.
8
+ * Progressive enhancement of the plain HTML form: it fetches a challenge when the reader focuses
9
+ * a form, solves it in the worker, posts JSON, shows the reader's own comment inline as awaiting
10
+ * moderation, moves the form under a comment for "Reply", loads more comments in place, and with
11
+ * Turnstile on (owner opt-in) loads Cloudflare's widget instead. ≤ `MODULE_GZIP_BUDGET` gzipped.
12
+ * - `solver`: `/_cloudhal/cw.<hash>.js`, a dedicated Web Worker with a pure-JS SHA-256 (no
13
+ * WebAssembly, so the CSP needs no `'wasm-unsafe-eval'`), so the page never janks while it
14
+ * searches. ≤ `SOLVER_GZIP_BUDGET` gzipped.
15
+ *
16
+ * Neither stores anything on the device, sets a cookie or sends an identifier.
17
+ */
18
+ import { fileURLToPath } from "node:url";
19
+
20
+ /** Where the scripts are served (a static-assets directory of the site build). */
21
+ export const CLIENT_DIR = "/_cloudhal/";
22
+ /** The endpoints the module talks to (answered by the site Worker before Astro, §6.1). */
23
+ export const COMMENTS_ENDPOINT = "/__cloudhal/comments";
24
+ export const COMMENTS_REPORT_ENDPOINT = "/__cloudhal/comments/report";
25
+ export const COMMENTS_CHALLENGE_ENDPOINT = "/__cloudhal/comments/challenge";
26
+ /** The module's size budget, gzipped (RFC-0007 §8.2: ≤ 4 KB). */
27
+ export const MODULE_GZIP_BUDGET = 4096;
28
+ /** The worker's size budget, gzipped (RFC-0007 §8.2: ≈ 1 KB). */
29
+ export const SOLVER_GZIP_BUDGET = 1024;
30
+ /** Replaced in the module source with the worker's hashed URL. */
31
+ export const SOLVER_URL_DEFINE = "__CLOUDHAL_SOLVER__";
32
+ /** The only third-party origin the module may load from, and only with Turnstile on (§7.6). */
33
+ export const TURNSTILE_ORIGIN = "https://challenges.cloudflare.com";
34
+
35
+ /** Absolute paths of the two entry files (plain browser JavaScript, no imports). */
36
+ export const COMMENTS_CLIENT_SOURCES = {
37
+ module: fileURLToPath(new URL("./comments.browser.js", import.meta.url).href),
38
+ solver: fileURLToPath(new URL("./solver.browser.js", import.meta.url).href),
39
+ } ;