@cloudhal/comments

中文文档
0.6.5发布于 2026/11/09Apache-2.0TypeScriptES Module构建来源已验证近 30 天下载 4509

Cloudhal reader comments (RFC-0007): settings and thread state, text normalising and content rules, linkify, first-party proof of work, the submission pipeline, purge planner, retention plan and the SQLite/D1 store. Worker-safe.

原始使用文档
文档目录6 节
  1. Settings and thread state (§4.5)
  2. Text (§6.4, §8.1)
  3. Proof of work (§7)
  4. The pipeline (§6.2–§6.6)
  5. Store ( @cloudhal/comments/sql )
  6. Purge planner and retention (§8.4, §9.3)

@cloudhal/comments

First-party reader comments for Cloudhal sites (RFC-0007, ADR-0022). 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.

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).

EntryWhat
@cloudhal/commentsSettings 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.
@cloudhal/comments/sqlSqlCommentStore over SqlDriver (SQLite locally and on Node, D1 on Cloudflare) for migration 0016_comments.
@cloudhal/comments/clientThe 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.
@cloudhal/comments/testingdescribeCommentStoreConformance, describeCommentPipelineSuite, countingDriver, expectContractComment (vitest).
@cloudhal/comments/fixtures/comment-text.jsonThe shared link-rule fixture (parseCommentText input → paragraphs), for the renderer and Studio's blocks.

Settings and thread state (§4.5)

import { applySettingsInput, defaultCommentSettings, threadClosesAt, threadState } from "@cloudhal/comments";

const settings = await store.settings(siteId); // the row, or the defaults (off, rev 0)
threadState({ settings, entry: { nodeId, collection: "posts", publishedAt }, thread, hasApproved, now });
// → "open" | "closed" | "hidden" | "off"   (90 days after first publication by default)

CommentSettingsInput is validated by applySettingsInput (unknown keys refused; CommentSettingsError, code invalid_settings). collectionEnabled, closeAfterDaysFor, threadVisible and DEFAULT_RETENTION are exported too.

Text (§6.4, §8.1)

  • 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.
  • 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.
  • 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.

Proof of work (§7)

import { deriveCommentKeys, difficultyFor, issueChallenge, verifyChallenge, ReplayCache } from "@cloudhal/comments";
const keys = await deriveCommentKeys(env.CLOUDHAL_COMMENTS_KEY); // HKDF per purpose: pow, emailHmac, email, secrets
const { challenge, bits, expiresAt } = await issueChallenge(keys.pow, { siteId, target: nodeId, kind: "comment", bits: difficultyFor(today, cap), now });

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.

The pipeline (§6.2–§6.6)

import { handleCommentSubmission, handleReportSubmission, handleChallengeRequest,
         submissionResponse, challengeResponse, CommentLimiter, DailyCount, ReplayCache, memoize } from "@cloudhal/comments";
import { SqlCommentStore } from "@cloudhal/comments/sql";

// once per isolate
const limiter = new CommentLimiter(), daily = new DailyCount(), replay = new ReplayCache();
const settings = memoize(() => store.settings(env.CLOUDHAL_SITE_ID)); // 60 s

const deps: PipelineDeps = {
  siteId: env.CLOUDHAL_SITE_ID, available: true, hosts, clientAddress: request.headers.get("cf-connecting-ip")!,
  keys, now: () => new Date(), settings, resolveEntry, store, limiter, daily, replay,
  rateLimit?: (key) => …,           // optional Rate Limiting binding
  turnstile?: ({ token, remoteip, idempotencyKey }) => siteverify(…), // when the site uses Turnstile
};
return submissionResponse(await handleCommentSubmission(request, deps));
// reports: submissionResponse(await handleReportSubmission(request, deps), { pendingFragment: "comment-reported" })
// challenges: challengeResponse(await handleChallengeRequest(request, deps))

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.

Store (@cloudhal/comments/sql)

new SqlCommentStore(sql, { now? }):

AreaMethods
Settings, secretssettings, putSettings(siteId, input, rev, by), putSecret, readSecret, secretInfo, deleteSecret
Threadsthread, putThread(siteId, nodeId, { mode, closesAt? }, rev, by, { purge?, audit? })
Pipeline (SubmissionStore)submit, report, approvedComment, readSalt, clientActivity, isDuplicate, storedSince, pendingOnEntry, isBanned, reportActivity
Readsget, list(siteId, { status | "reported", nodeId, nodeIds, label, since, cursor, limit ≤ 50, order }), threadComments, renderPage(siteId, nodeId, page), counts, history, stateHash(siteId, ids, threads) (cm1:)
Moderationmoderate(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
People onlyfindCommenter, 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
ReportslistReports, resolveReport
purgeQueuequeued, sites, enqueue, recent, log (the publish path's purge log row), sent, failed — feed planPurge
retentionrun(siteId, retentionPlan(settings.retention, now)), deleteEntries(siteId, deletedEntriesDue(…)), runDeployment(now, oldestSaltMonthToKeep(now))

approve, restore, delete, replies, erasure and bans need a human actor (CommentForbiddenError, code forbidden); stale revs 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.

Purge planner and retention (§8.4, §9.3)

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).

版本与发布记录

@cloudhal/comments 共发布 26 个版本,首次发布于 2026/10/20;过去 12 个月发布了 26 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.6.5latest2026/11/091 天前
0.6.42026/11/081 天前
0.6.32026/11/081 天前
0.6.22026/10/2614 天前
0.6.12026/10/2417 天前
0.6.02026/10/2317 天前

关于 @cloudhal/comments 的常见问题

@cloudhal/comments 是什么?

Cloudhal reader comments (RFC-0007): settings and thread state, text normalising and content rules, linkify, first-party proof of work, the submission pipeline, purge planner, retention plan and the SQLite/D1 store. Worker-safe.

如何安装 @cloudhal/comments?

在项目目录运行 npm install @cloudhal/comments,或使用 pnpm add / yarn add / bun add。

@cloudhal/comments 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@cloudhal/comments 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@cloudhal/comments 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=24。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@cloudhal/comments 可以商用吗?

@cloudhal/comments 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@cloudhal/comments 的下载量有多少?

根据 npm 官方下载统计,@cloudhal/comments 在 2026/10/10 – 2026/11/08 这 30 天内被下载 4,509 次,日均约 150 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@cloudhal/comments 还在维护吗?

最新版本 0.6.5 发布于 2026/11/09(1 天前);至今共发布 26 个版本,其中过去 12 个月发布了 26 个;首次发布于 2026/10/20。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。