@allbluecn/collab-server 0.0.0-stage → 0.1.6

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 (39) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +126 -2
  3. package/package.json +64 -3
  4. package/src/__tests__/clients.test.ts +93 -0
  5. package/src/__tests__/embed.test.ts +227 -0
  6. package/src/__tests__/env-setup.ts +33 -0
  7. package/src/__tests__/exporters-bug.test.ts +552 -0
  8. package/src/__tests__/exporters-case.test.ts +356 -0
  9. package/src/__tests__/exporters-design.test.ts +356 -0
  10. package/src/__tests__/exporters-knowledge.test.ts +366 -0
  11. package/src/__tests__/exporters-stats.test.ts +105 -0
  12. package/src/__tests__/exporters-story.test.ts +519 -0
  13. package/src/__tests__/internal-apply-channel.test.ts +233 -0
  14. package/src/__tests__/internal-apply-race.test.ts +165 -0
  15. package/src/__tests__/internal-apply.test.ts +418 -0
  16. package/src/__tests__/multiplex.test.ts +166 -0
  17. package/src/__tests__/persistence-retry.test.ts +262 -0
  18. package/src/__tests__/persistence.test.ts +302 -0
  19. package/src/__tests__/server.test.ts +145 -0
  20. package/src/__tests__/share-room-limit.test.ts +183 -0
  21. package/src/__tests__/shutdown.test.ts +130 -0
  22. package/src/__tests__/test-utils.ts +176 -0
  23. package/src/auth.ts +84 -0
  24. package/src/clients.ts +133 -0
  25. package/src/embed.ts +156 -0
  26. package/src/exporters/bug.ts +454 -0
  27. package/src/exporters/case.ts +317 -0
  28. package/src/exporters/design.ts +268 -0
  29. package/src/exporters/entity-shared.ts +75 -0
  30. package/src/exporters/knowledge.ts +259 -0
  31. package/src/exporters/story.ts +483 -0
  32. package/src/exporters.ts +173 -0
  33. package/src/index.ts +354 -0
  34. package/src/internal-apply-limit.ts +99 -0
  35. package/src/internal-apply.ts +888 -0
  36. package/src/metrics.ts +82 -0
  37. package/src/persistence.ts +409 -0
  38. package/src/rooms.ts +32 -0
  39. package/src/share-room-limit.ts +73 -0
@@ -0,0 +1,888 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // AllBlue - 理想之海
3
+ // Copyright (C) 2026 AllBlue Contributors
4
+ //
5
+ // This program is free software: you can redistribute it and/or modify
6
+ // it under the terms of the GNU Affero General Public License as published by
7
+ // the Free Software Foundation, either version 3 of the License, or
8
+ // (at your option) any later version.
9
+ //
10
+ // This program is distributed in the hope that it will be useful,
11
+ // but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ // GNU Affero General Public License for more details.
14
+ //
15
+ // You should have received a copy of the GNU Affero General Public License
16
+ // along with this program. If not, see <https://www.gnu.org/licenses/>.
17
+
18
+ // 内部应用通道(Yjs 多人协作 §5.3 写入路由协议,任务 17):web 的写入门卫
19
+ // 在 CollabDocument 存在时把旁路写入转发到此端点,**活跃判定在 collab 侧**
20
+ // (复审修正:web 进程不做活跃判定):
21
+ //
22
+ // - room 在线(有连接):以「系统 client(userId=actor)」把 patch 应用到
23
+ // Y.Doc 并广播。content patch 是整文档 replace 语义:用业务 patch 的
24
+ // content.html 经 seedYDocFromHtml 同构转换(与种子化同一扩展组合)→
25
+ // 清空 live room 的 default fragment → 合并 source update(新增 items 以
26
+ // source clientID 并入,广播由 Hocuspocus Document 的 update 监听自动
27
+ // 完成并回写各连接)。**覆盖协同者未落库的中间态——规格接受:DB 旁路写
28
+ // 是权威时刻**。落库走 onStoreDocument 统一链路(本模块显式调度
29
+ // debounced store,无后续 WS 流量也保证最终落库)。归属:应用以 internal
30
+ // origin 事务进行,persistence 的 onChange 据此把 update 归属 actor
31
+ // (系统 client 映射 CollabClient + 日志 authorId + 审计主作者全链路一致)。
32
+ // - room 离线(无连接):**直接落库业务列**(patch.content 原样写入
33
+ // KnowledgeDocument.content,与 web 直写同语义)+ 视为旁路写(重种子化
34
+ // 兜底生效:任务 14 的 updatedAt 对比在下次协同打开时以 DB 覆盖 Y)+
35
+ // 触发向量索引重建通知(内容变更的索引口径单源于导出器)。
36
+ // - 实体已删(幽灵 room):409 拒绝且不落库——web 侧收到非 2xx 降级直写,
37
+ // 由属主校验自然报「未找到或无权限」。
38
+ //
39
+ // HTTP 形态:Hocuspocus Server 自带 node:http 服务器(WS 升级与默认
40
+ // 「Welcome to Hocuspocus!」请求处理器共用端口)。onRequest hook 无法阻止
41
+ // 默认响应(写后二次 writeHead → ERR_HTTP_HEADERS_SENT → 未处理拒绝),
42
+ // 故用**请求监听器置换**:摘除 Hocuspocus 的 request 监听器,内部路由
43
+ // 自理、其余原样委托(httpServer / requestHandler 均为上游公开 API 面)。
44
+ //
45
+ // 认证:内部 HMAC 信封(@allbluecn/collab-core/internal,域
46
+ // collab-internal-apply:v1,ts 偏移 >60s 拒)——与 ticket 同密钥不同域。
47
+
48
+ import type { IncomingMessage, ServerResponse } from "node:http";
49
+ import type { Hocuspocus, Server } from "@hocuspocus/server";
50
+ import type { CollabRoomName } from "@allbluecn/collab-core/rooms";
51
+ import { parseRoomName, buildRoomName } from "@allbluecn/collab-core/rooms";
52
+ import {
53
+ INTERNAL_DOMAIN_APPLY,
54
+ INTERNAL_SIGNATURE_HEADER,
55
+ verifyInternalRequest,
56
+ } from "@allbluecn/collab-core/internal";
57
+ import {
58
+ COLLAB_XML_FRAGMENT,
59
+ seedYDocFromHtml,
60
+ } from "@allbluecn/collab-core/tiptap-export";
61
+ import { seedYTreeFromCanvas } from "@allbluecn/collab-core/canvas-package";
62
+ import { DESIGN_DOC_FRAGMENT } from "@allbluecn/collab-core/canvas-tree";
63
+ import { createKnowledgeExtensions } from "@allbluecn/collab-core/knowledge-schema";
64
+ import { createKnowledgeDocAdditions } from "@allbluecn/collab-core/knowledge-additions";
65
+ import * as Y from "yjs";
66
+ import type { Document as CollabDocument } from "@hocuspocus/server";
67
+ import type { Prisma } from "@allbluecn/database";
68
+ import { runRoomGuard } from "./exporters";
69
+ import {
70
+ ensureServerDom,
71
+ notifyKnowledgeReindex,
72
+ } from "./exporters/knowledge";
73
+ import {
74
+ COLLAB_FIELDS_MAP_KEY,
75
+ storyDocExtensions,
76
+ writeStoryColumns,
77
+ type StoryFieldsPatch,
78
+ } from "./exporters/story";
79
+ import { writeBugColumns, notifyBugActivityHint, type BugActivityHint, type BugFieldsPatch } from "./exporters/bug";
80
+ import { writeCaseColumns, type CaseFieldsPatch } from "./exporters/case";
81
+ import { writeDesignColumns, designDocExtensions } from "./exporters/design";
82
+ import { applyStepsToDoc, normalizeCollabSteps, type CollabStep } from "@allbluecn/collab-core/steps";
83
+ import { createApplyAdmission, type ApplyAdmission } from "./internal-apply-limit";
84
+
85
+ // ── internal origin(系统 client 归属标记)────────────────────────────
86
+
87
+ const INTERNAL_APPLY_ORIGIN_TAG = "__collabInternalApply";
88
+
89
+ /** internal-apply 事务 origin:persistence.onChange 据此归属 actor */
90
+ export interface InternalApplyOrigin {
91
+ [INTERNAL_APPLY_ORIGIN_TAG]: true;
92
+ actorUserId: string;
93
+ }
94
+
95
+ export function createInternalApplyOrigin(actorUserId: string): InternalApplyOrigin {
96
+ return { [INTERNAL_APPLY_ORIGIN_TAG]: true, actorUserId };
97
+ }
98
+
99
+ /** 读 internal origin 的归属主体;非 internal origin 返回 null */
100
+ export function readInternalApplyActor(origin: unknown): string | null {
101
+ if (
102
+ typeof origin === "object" &&
103
+ origin !== null &&
104
+ (origin as Record<string, unknown>)[INTERNAL_APPLY_ORIGIN_TAG] === true
105
+ ) {
106
+ const actor = (origin as Record<string, unknown>).actorUserId;
107
+ return typeof actor === "string" && actor.length > 0 ? actor : null;
108
+ }
109
+ return null;
110
+ }
111
+
112
+ // ── 请求处理核心(框架无关,单测直调)─────────────────────────────────
113
+
114
+ /** 与 web 种子化完全同一扩展组合(默认集 + 追加集) */
115
+ function knowledgeDocExtensions() {
116
+ return [...createKnowledgeExtensions(), ...createKnowledgeDocAdditions()];
117
+ }
118
+
119
+ interface ApplyRequest {
120
+ roomName?: unknown;
121
+ docId?: unknown;
122
+ actor?: unknown;
123
+ patch?: unknown;
124
+ /** 语义活动 hint(机器/旁路写入,如 reopened_by_sdk;仅 entity-bug 消费) */
125
+ activity?: unknown;
126
+ }
127
+
128
+ /** 解析语义活动 hint:action 必须为字符串,其余字段透传;非法/缺失 = undefined */
129
+ function parseActivityHint(raw: unknown, actor: string): BugActivityHint | undefined {
130
+ if (typeof raw !== "object" || raw === null) return undefined;
131
+ const action = (raw as Record<string, unknown>).action;
132
+ if (typeof action !== "string" || action.length === 0) return undefined;
133
+ const { field, oldValue, newValue } = raw as Record<string, unknown>;
134
+ return {
135
+ action,
136
+ actor,
137
+ ...(field !== undefined && { field }),
138
+ ...(oldValue !== undefined && { oldValue }),
139
+ ...(newValue !== undefined && { newValue }),
140
+ };
141
+ }
142
+
143
+ export interface InternalApplyResponse {
144
+ status: number;
145
+ body: Record<string, unknown>;
146
+ }
147
+
148
+ /**
149
+ * 处理一条 /internal/apply 请求(HTTP adapter 只做传输层;验签在此)。
150
+ * 返回 { status, body },由 HTTP adapter 序列化。
151
+ */
152
+ export async function handleInternalApply(opts: {
153
+ hocuspocus: Hocuspocus;
154
+ secret: string;
155
+ body: string;
156
+ signature: string;
157
+ }): Promise<InternalApplyResponse> {
158
+ const verified = verifyInternalRequest({
159
+ secret: opts.secret,
160
+ domain: INTERNAL_DOMAIN_APPLY,
161
+ body: opts.body,
162
+ signature: opts.signature,
163
+ });
164
+ if (!verified.ok) {
165
+ console.warn(`[collab-internal] /internal/apply 信封验签拒绝 reason=${verified.reason}`);
166
+ return { status: 401, body: { error: "unauthorized", reason: verified.reason } };
167
+ }
168
+
169
+ const payload = verified.payload as ApplyRequest;
170
+ if (
171
+ typeof payload.roomName !== "string" ||
172
+ typeof payload.docId !== "string" ||
173
+ typeof payload.actor !== "string" ||
174
+ payload.actor.length === 0
175
+ ) {
176
+ return { status: 400, body: { error: "roomName/docId/actor required" } };
177
+ }
178
+ const room = parseRoomName(payload.roomName);
179
+ if (!room) {
180
+ return { status: 400, body: { error: "invalid room" } };
181
+ }
182
+ const patch = (payload.patch ?? {}) as {
183
+ content?: unknown;
184
+ fields?: unknown;
185
+ steps?: unknown;
186
+ canvas?: unknown;
187
+ };
188
+ const content = patch.content;
189
+ const html =
190
+ typeof content === "object" && content !== null
191
+ ? (content as Record<string, unknown>).html
192
+ : undefined;
193
+
194
+ // P2 首站 knowledge-doc(任务 17);P3 扩 entity-story(任务 21,§5.3.4)。
195
+ // room 与 docId 必须互相印证(防换 doc 打 room)。
196
+ if (room.kind === "knowledge-doc") {
197
+ if (room.docId !== payload.docId) {
198
+ return { status: 400, body: { error: "invalid room" } };
199
+ }
200
+ // content patch 是知识库 Y 的唯一属主面:必须有合法 html
201
+ if (typeof html !== "string") {
202
+ return { status: 400, body: { error: "patch.content.html required" } };
203
+ }
204
+ const document = opts.hocuspocus.documents.get(payload.roomName);
205
+ const online = document !== undefined && document.getConnectionsCount() > 0;
206
+
207
+ if (online && document) {
208
+ return applyKnowledgeToLiveDoc(opts.hocuspocus, document, html, payload.actor);
209
+ }
210
+ const result = await writeBusinessRow(room, content);
211
+ // I3 竞态复查(任务 17 复审修复):离线判定与直写之间若有连接在途
212
+ // (已建连未计数 / 文档装载中——载入的是直写前的旧快照),该会话会以旧
213
+ // Y 态继续编辑并在落库时覆盖刚直写的 content(T14 重种子化只救「直写后
214
+ // 才打开」的会话)。落库后进程内复查:room 已装载(含装载中)→ 补一次
215
+ // 同内容 apply(幂等)——进程内直调与 HTTP 在线分支走同一应用代码路径
216
+ // (信封仅跨进程需要),内存态与 DB 直写结果强制收敛。
217
+ const live = await resolveLiveDocument(opts.hocuspocus, payload.roomName);
218
+ if (live) {
219
+ await applyKnowledgeToLiveDoc(opts.hocuspocus, live, html, payload.actor);
220
+ return { status: 202, body: { applied: "db", reapplied: "ydoc" } };
221
+ }
222
+ return result;
223
+ }
224
+
225
+ if (room.kind === "entity-story") {
226
+ if (room.storyId !== payload.docId) {
227
+ return { status: 400, body: { error: "invalid room" } };
228
+ }
229
+ // Story 的 Y 属主面 = description fragment + fields Y.Map(锚点 L):
230
+ // content({html})与 fields(JSON 兼容字段 patch)均可选,但至少其一。
231
+ const storyHtml = typeof html === "string" ? html : undefined;
232
+ const fields = parseEntityFieldsPatch(patch.fields);
233
+ if (storyHtml === undefined && fields === null) {
234
+ return { status: 400, body: { error: "patch.content.html or patch.fields required" } };
235
+ }
236
+ const document = opts.hocuspocus.documents.get(payload.roomName);
237
+ const online = document !== undefined && document.getConnectionsCount() > 0;
238
+
239
+ if (online && document) {
240
+ return applyEntityToLiveDoc(opts.hocuspocus, document, {
241
+ html: storyHtml,
242
+ fields,
243
+ actor: payload.actor,
244
+ });
245
+ }
246
+ const result = await writeStoryBusinessRow(room, content, fields, payload.actor);
247
+ // I3 同款竞态复查(语义同知识库):直写后进程内复查补应用到 Y
248
+ const live = await resolveLiveDocument(opts.hocuspocus, payload.roomName);
249
+ if (live) {
250
+ await applyEntityToLiveDoc(opts.hocuspocus, live, {
251
+ html: storyHtml,
252
+ fields,
253
+ actor: payload.actor,
254
+ });
255
+ return { status: 202, body: { applied: "db", reapplied: "ydoc" } };
256
+ }
257
+ return result;
258
+ }
259
+
260
+ // P3 扩 entity-bug / entity-case(任务 22,§5.3.4)。Y 属主面 =
261
+ // description fragment(仅 bug)+ fields Y.Map + steps Y.Array(锚点 L)。
262
+ if (room.kind === "entity-bug" || room.kind === "entity-case") {
263
+ const entityId = room.kind === "entity-bug" ? room.bugId : room.caseId;
264
+ if (entityId !== payload.docId) {
265
+ return { status: 400, body: { error: "invalid room" } };
266
+ }
267
+ const entityHtml = room.kind === "entity-bug" && typeof html === "string" ? html : undefined;
268
+ const fields = parseEntityFieldsPatch(patch.fields);
269
+ // steps 面:门卫归一化数组(order 已剥——数组顺序即顺序);非法/缺失 = null
270
+ const steps = parseStepsFace(patch.steps);
271
+ if (entityHtml === undefined && fields === null && steps === null) {
272
+ return { status: 400, body: { error: "patch.content.html or patch.fields or patch.steps required" } };
273
+ }
274
+ // 语义活动 hint 仅 entity-bug 消费(BugActivity 语义 action)
275
+ const activityHint =
276
+ room.kind === "entity-bug" ? parseActivityHint(payload.activity, payload.actor) : undefined;
277
+
278
+ const document = opts.hocuspocus.documents.get(payload.roomName);
279
+ const online = document !== undefined && document.getConnectionsCount() > 0;
280
+
281
+ if (online && document) {
282
+ return applyEntityToLiveDoc(opts.hocuspocus, document, {
283
+ html: entityHtml,
284
+ fields,
285
+ steps,
286
+ actor: payload.actor,
287
+ ...(activityHint && { activityHint }),
288
+ });
289
+ }
290
+ const result =
291
+ room.kind === "entity-bug"
292
+ ? await writeBugBusinessRow(room, content, fields as Map<string, unknown> | null, steps, payload.actor, activityHint)
293
+ : await writeCaseBusinessRow(room, fields as Map<string, unknown> | null, steps, payload.actor);
294
+ // I3 同款竞态复查:直写后进程内复查补应用到 Y。
295
+ // 补应用不传 hint——语义活动已由离线直落的活动行携带,再入队会重复
296
+ const live = await resolveLiveDocument(opts.hocuspocus, payload.roomName);
297
+ if (live) {
298
+ await applyEntityToLiveDoc(opts.hocuspocus, live, {
299
+ html: entityHtml,
300
+ fields,
301
+ steps,
302
+ actor: payload.actor,
303
+ });
304
+ return { status: 202, body: { applied: "db", reapplied: "ydoc" } };
305
+ }
306
+ return result;
307
+ }
308
+
309
+ // P4 扩 design-canvas(任务 29,§7.1 设计画布行)。Y 属主面 = canvas 根
310
+ // Y.Map + 文档 fragment(同 room 双载体)。canvas patch 应用语义 =
311
+ // **整场景 replace**(LeaferJSONPackage / 旧扁平 SceneDocument →
312
+ // seedYTreeFromCanvas 覆写 Y 树——DB 旁路写是权威时刻);content patch =
313
+ // 文档 fragment replace(html,story 同语义)。改 Y 后远端方向桥应用回
314
+ // 引擎正是 T27 的职责,本通道只管写 Y + 落库调度。
315
+ if (room.kind === "design-canvas") {
316
+ if (room.pageId !== payload.docId) {
317
+ return { status: 400, body: { error: "invalid room" } };
318
+ }
319
+ const designHtml = typeof html === "string" ? html : undefined;
320
+ const designMarkdown =
321
+ typeof content === "object" && content !== null
322
+ ? (content as Record<string, unknown>).markdown
323
+ : undefined;
324
+ // canvas 面:仅对象合法(LeaferJSONPackage / 旧扁平 SceneDocument 均为
325
+ // JSON 对象;垃圾形状 = undefined 拒绝)。存在即视为属主写入(不深检内容
326
+ // 形状——应用侧 seedYTreeFromCanvas 对空/垃圾 fail-closed 跳过画布面)
327
+ const canvas =
328
+ typeof patch.canvas === "object" && patch.canvas !== null
329
+ ? (patch.canvas as Record<string, unknown>)
330
+ : undefined;
331
+ if (canvas === undefined && designHtml === undefined) {
332
+ return { status: 400, body: { error: "patch.canvas or patch.content.html required" } };
333
+ }
334
+ const document = opts.hocuspocus.documents.get(payload.roomName);
335
+ const online = document !== undefined && document.getConnectionsCount() > 0;
336
+
337
+ if (online && document) {
338
+ return applyDesignToLiveDoc(opts.hocuspocus, document, {
339
+ canvas,
340
+ html: designHtml,
341
+ actor: payload.actor,
342
+ });
343
+ }
344
+ const result = await writeDesignBusinessRow(
345
+ room,
346
+ canvas,
347
+ designHtml,
348
+ typeof designMarkdown === "string" ? designMarkdown : undefined,
349
+ payload.actor,
350
+ );
351
+ // I3 同款竞态复查:直写后进程内复查补应用到 Y
352
+ const live = await resolveLiveDocument(opts.hocuspocus, payload.roomName);
353
+ if (live) {
354
+ await applyDesignToLiveDoc(opts.hocuspocus, live, {
355
+ canvas,
356
+ html: designHtml,
357
+ actor: payload.actor,
358
+ });
359
+ return { status: 202, body: { applied: "db", reapplied: "ydoc" } };
360
+ }
361
+ return result;
362
+ }
363
+
364
+ return { status: 400, body: { error: "invalid room" } };
365
+ }
366
+
367
+ /**
368
+ * fields patch 解析(entity room):仅收 JSON 兼容纯对象,键值原样透传
369
+ * (写端 zod 保证形状;Y.Map 值侧再由 exporter 落库时做 FK/格式防御)。
370
+ * 非对象返回 null(非法);空对象返回空 Map(合法 no-op)。
371
+ */
372
+ function parseEntityFieldsPatch(raw: unknown): Map<string, unknown> | null {
373
+ if (raw === undefined) return null;
374
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null;
375
+ return new Map(Object.entries(raw as Record<string, unknown>));
376
+ }
377
+
378
+ /**
379
+ * steps patch 解析(entity-bug/entity-case):门卫归一化数组(collab-core
380
+ * normalizeCollabSteps 口径——数组顺序即步骤顺序)。缺失/非法/空数组返回
381
+ * null(空数组永不合法——业务 schema 步骤 min(1),门卫不会转发)。
382
+ */
383
+ function parseStepsFace(raw: unknown): CollabStep[] | null {
384
+ return normalizeCollabSteps(raw);
385
+ }
386
+
387
+ /**
388
+ * 已装载(或装载中)的 room 文档。装载中的 Promise 可能以幽灵拒绝告终
389
+ * (onLoadDocument 抛错),按离线处理返回 undefined。
390
+ */
391
+ async function resolveLiveDocument(
392
+ hocuspocus: Hocuspocus,
393
+ roomName: string,
394
+ ): Promise<CollabDocument | undefined> {
395
+ const loaded = hocuspocus.documents.get(roomName);
396
+ if (loaded) return loaded;
397
+ const loading = hocuspocus.loadingDocuments.get(roomName);
398
+ if (!loading) return undefined;
399
+ try {
400
+ return await loading;
401
+ } catch {
402
+ return undefined;
403
+ }
404
+ }
405
+
406
+ /**
407
+ * room 在线:整文档 replace 语义应用到 Y 并广播(知识库——content 是唯一
408
+ * 属主面)。清空 default fragment + 合并 source update 在同一事务(internal
409
+ * origin)内进行——persistence.onChange 经 origin 归属 actor;末尾显式调度
410
+ * debounced onStoreDocument(与自然流量共用同一 debounce id,幂等),
411
+ * 保证无后续 WS 流量也最终落库。
412
+ */
413
+ async function applyKnowledgeToLiveDoc(
414
+ hocuspocus: Hocuspocus,
415
+ document: CollabDocument,
416
+ html: string,
417
+ actor: string,
418
+ ): Promise<InternalApplyResponse> {
419
+ await ensureServerDom();
420
+ const normalized = html.trim() === "" ? "<p></p>" : html;
421
+ const source = seedYDocFromHtml(normalized, knowledgeDocExtensions());
422
+ const sourceUpdate = Y.encodeStateAsUpdate(source);
423
+ const fragment = document.getXmlFragment(COLLAB_XML_FRAGMENT);
424
+ document.transact(() => {
425
+ fragment.delete(0, fragment.length);
426
+ Y.applyUpdate(document, sourceUpdate);
427
+ }, createInternalApplyOrigin(actor));
428
+
429
+ scheduleStore(hocuspocus, document, actor);
430
+
431
+ return {
432
+ status: 202,
433
+ body: { applied: "ydoc", connections: document.getConnectionsCount() },
434
+ };
435
+ }
436
+
437
+ /**
438
+ * room 在线(entity:*,任务 21/22):entity room 的 Y 属主面是「description
439
+ * fragment(story/bug)+ fields Y.Map + steps Y.Array(bug/case)」混合——
440
+ * content 走整文档 replace(与知识库同语义,与种子化同一扩展组合);fields
441
+ * 逐 key merge 进 fields Map(per-key LWW,未出现的 key 不触碰——patch 语义);
442
+ * steps 走整列表 replace(清空重灌,数组顺序即顺序)。同一 internal origin
443
+ * 事务内进行,归属 actor;末尾同一 store 调度。
444
+ */
445
+ async function applyEntityToLiveDoc(
446
+ hocuspocus: Hocuspocus,
447
+ document: CollabDocument,
448
+ face: {
449
+ html?: string;
450
+ fields: Map<string, unknown> | null;
451
+ steps?: CollabStep[] | null;
452
+ actor: string;
453
+ /** 语义活动 hint(entity-bug;Y 应用成功后入队,落库时出队成行) */
454
+ activityHint?: BugActivityHint;
455
+ },
456
+ ): Promise<InternalApplyResponse> {
457
+ await ensureServerDom();
458
+ document.transact(() => {
459
+ if (face.html !== undefined) {
460
+ const normalized = face.html.trim() === "" ? "<p></p>" : face.html;
461
+ const source = seedYDocFromHtml(normalized, storyDocExtensions());
462
+ const sourceUpdate = Y.encodeStateAsUpdate(source);
463
+ const fragment = document.getXmlFragment(COLLAB_XML_FRAGMENT);
464
+ fragment.delete(0, fragment.length);
465
+ Y.applyUpdate(document, sourceUpdate);
466
+ }
467
+ if (face.fields && face.fields.size > 0) {
468
+ const fieldsMap = document.getMap<unknown>(COLLAB_FIELDS_MAP_KEY);
469
+ for (const [key, value] of face.fields) {
470
+ fieldsMap.set(key, value);
471
+ }
472
+ }
473
+ if (face.steps && face.steps.length > 0) {
474
+ // replace 语义(外层 transact 已开——嵌套并入、origin 保留)
475
+ applyStepsToDoc(document, face.steps);
476
+ }
477
+ }, createInternalApplyOrigin(face.actor));
478
+
479
+ // hint 在 Y 应用成功后入队(与 Y 未落库状态同生共死:store 前 crash 同丢)
480
+ if (face.activityHint) {
481
+ notifyBugActivityHint(document.name, face.activityHint);
482
+ }
483
+
484
+ scheduleStore(hocuspocus, document, face.actor);
485
+
486
+ return {
487
+ status: 202,
488
+ body: { applied: "ydoc", connections: document.getConnectionsCount() },
489
+ };
490
+ }
491
+
492
+ /** 显式调度 debounced onStoreDocument(internal origin 归属 actor) */
493
+ function scheduleStore(hocuspocus: Hocuspocus, document: CollabDocument, actor: string): void {
494
+ void hocuspocus.storeDocumentHooks(document, {
495
+ clientsCount: document.getConnectionsCount(),
496
+ document,
497
+ documentName: document.name,
498
+ instance: hocuspocus,
499
+ lastContext: undefined,
500
+ lastTransactionOrigin: createInternalApplyOrigin(actor),
501
+ }).catch((err: unknown) => {
502
+ console.error(`[collab-internal] store 调度失败 room=${document.name}(自然流量兜底):`, err);
503
+ });
504
+ }
505
+
506
+ /**
507
+ * room 在线(design-canvas,任务 29):双载体 replace 语义应用到 Y 并广播——
508
+ * canvas 走整场景 replace(seedYTreeFromCanvas:LeaferJSONPackage / 旧扁平
509
+ * 格式 → sceneToYTree 覆写 Y 树,垃圾/空形状内部 fail-closed 跳过);文档
510
+ * fragment 走整文档 replace(html → seedYDocFromHtml,与 knowledge/entity 同
511
+ * 语义)。同一 internal origin 事务(origin 为 internal-apply 专属对象标记,
512
+ * 与 web 客户端 CANVAS_LOCAL_ORIGIN 无共享值域——T28 禁令:internal 通道
513
+ * 复用客户端 origin 会骗过 T27 桥的回声过滤),归属 actor;末尾同一 store
514
+ * 调度。远端方向(改 Y → 广播 → 各端 T27 桥应用回引擎)由既有链路承接。
515
+ */
516
+ async function applyDesignToLiveDoc(
517
+ hocuspocus: Hocuspocus,
518
+ document: CollabDocument,
519
+ face: {
520
+ canvas?: Record<string, unknown>;
521
+ html?: string;
522
+ actor: string;
523
+ },
524
+ ): Promise<InternalApplyResponse> {
525
+ await ensureServerDom();
526
+ document.transact(() => {
527
+ if (face.canvas !== undefined) {
528
+ seedYTreeFromCanvas(face.canvas, document);
529
+ }
530
+ if (face.html !== undefined) {
531
+ const normalized = face.html.trim() === "" ? "<p></p>" : face.html;
532
+ const source = seedYDocFromHtml(normalized, designDocExtensions());
533
+ const sourceUpdate = Y.encodeStateAsUpdate(source);
534
+ const fragment = document.getXmlFragment(DESIGN_DOC_FRAGMENT);
535
+ fragment.delete(0, fragment.length);
536
+ Y.applyUpdate(document, sourceUpdate);
537
+ }
538
+ }, createInternalApplyOrigin(face.actor));
539
+
540
+ scheduleStore(hocuspocus, document, face.actor);
541
+
542
+ return {
543
+ status: 202,
544
+ body: { applied: "ydoc", connections: document.getConnectionsCount() },
545
+ };
546
+ }
547
+
548
+ /**
549
+ * room 离线(知识库):直接落库业务列(patch.content 原样,与 web 直写同语义),
550
+ * 视为旁路写——重种子化兜底在下次协同打开时以 DB 覆盖 Y。写入前复核实体
551
+ * 存在且未软删(幽灵 room 拒绝:web 降级直写后由属主校验报错)。
552
+ */
553
+ async function writeBusinessRow(
554
+ room: Extract<CollabRoomName, { kind: "knowledge-doc" }>,
555
+ content: unknown,
556
+ ): Promise<InternalApplyResponse> {
557
+ const alive = await runRoomGuard(room);
558
+ if (!alive) {
559
+ return { status: 409, body: { error: "entity-missing" } };
560
+ }
561
+ const db = await import("@allbluecn/database");
562
+ await db.prisma.knowledgeDocument.update({
563
+ where: { id: room.docId },
564
+ // unknown → Prisma InputJsonValue(patch.content 原样透传,JSON 兼容由
565
+ // web 侧 validator 保证)
566
+ data: { content: content as Prisma.InputJsonValue },
567
+ });
568
+ // 内容变更的索引口径单源于导出器:离线直落同样触发重建通知
569
+ notifyKnowledgeReindex(room.docId);
570
+ return { status: 202, body: { applied: "db" } };
571
+ }
572
+
573
+ /**
574
+ * room 离线(entity:story,任务 21):collab 直落业务列——description 双轨
575
+ * JSON 串 + 字段列 + StoryLabel diff + StoryActivity(归属 actor + 变更流水),
576
+ * 与 web 直写同语义的 DB 终态(web 侧 degraded 直写也产生活动)。不触碰快照
577
+ * 行——旁路写必须让业务列反超快照(T14 重种子化判定的正确输入)。写前守卫
578
+ * 复核(幽灵 409);共享写入口 writeStoryColumns 与 exporter 单源。
579
+ */
580
+ async function writeStoryBusinessRow(
581
+ room: Extract<CollabRoomName, { kind: "entity-story" }>,
582
+ content: unknown,
583
+ fields: Map<string, unknown> | null,
584
+ actor: string,
585
+ ): Promise<InternalApplyResponse> {
586
+ const alive = await runRoomGuard(room);
587
+ if (!alive) {
588
+ return { status: 409, body: { error: "entity-missing" } };
589
+ }
590
+ const html =
591
+ typeof content === "object" && content !== null
592
+ ? (content as Record<string, unknown>).html
593
+ : undefined;
594
+ const markdown =
595
+ typeof content === "object" && content !== null
596
+ ? (content as Record<string, unknown>).markdown
597
+ : undefined;
598
+ const db = await import("@allbluecn/database");
599
+ await db.prisma.$transaction((tx) =>
600
+ writeStoryColumns(tx, {
601
+ storyId: room.storyId,
602
+ roomName: buildRoomName({ kind: "entity-story", storyId: room.storyId }),
603
+ ...(typeof html === "string" && {
604
+ descriptionHtml: html,
605
+ ...(typeof markdown === "string" && { descriptionMarkdown: markdown }),
606
+ }),
607
+ ...(fields && { fields: Object.fromEntries(fields) as StoryFieldsPatch }),
608
+ actor,
609
+ touchSnapshot: false,
610
+ }),
611
+ );
612
+ return { status: 202, body: { applied: "db" } };
613
+ }
614
+
615
+ /**
616
+ * room 离线(entity:bug,任务 22):collab 直落业务列——description 双轨
617
+ * JSON 串 + 6 字段列 + BugLabel diff + reproduceSteps.steps + BugActivity
618
+ * (actorType="collab" + 归属 actor),与 web 直写同语义的 DB 终态。不触碰
619
+ * 快照行——旁路写必须让业务列反超快照(T14 重种子化判定的正确输入)。写前
620
+ * 守卫复核(幽灵 409);共享写入口 writeBugColumns 与 exporter 单源。
621
+ */
622
+ async function writeBugBusinessRow(
623
+ room: Extract<CollabRoomName, { kind: "entity-bug" }>,
624
+ content: unknown,
625
+ fields: Map<string, unknown> | null,
626
+ steps: CollabStep[] | null,
627
+ actor: string,
628
+ activityHint?: BugActivityHint,
629
+ ): Promise<InternalApplyResponse> {
630
+ const alive = await runRoomGuard(room);
631
+ if (!alive) {
632
+ return { status: 409, body: { error: "entity-missing" } };
633
+ }
634
+ const html =
635
+ typeof content === "object" && content !== null
636
+ ? (content as Record<string, unknown>).html
637
+ : undefined;
638
+ const markdown =
639
+ typeof content === "object" && content !== null
640
+ ? (content as Record<string, unknown>).markdown
641
+ : undefined;
642
+ const db = await import("@allbluecn/database");
643
+ await db.prisma.$transaction((tx) =>
644
+ writeBugColumns(tx, {
645
+ bugId: room.bugId,
646
+ roomName: buildRoomName({ kind: "entity-bug", bugId: room.bugId }),
647
+ ...(typeof html === "string" && {
648
+ descriptionHtml: html,
649
+ ...(typeof markdown === "string" && { descriptionMarkdown: markdown }),
650
+ }),
651
+ ...(fields && { fields: Object.fromEntries(fields) as BugFieldsPatch }),
652
+ ...(steps && steps.length > 0 && { steps }),
653
+ actor,
654
+ // 离线直落:语义活动随行写(hint 不再入队——无 Y 应用)
655
+ ...(activityHint && {
656
+ activityAction: activityHint.action,
657
+ activityExtra: {
658
+ ...(activityHint.field !== undefined && { field: activityHint.field }),
659
+ ...(activityHint.oldValue !== undefined && { oldValue: activityHint.oldValue }),
660
+ ...(activityHint.newValue !== undefined && { newValue: activityHint.newValue }),
661
+ },
662
+ }),
663
+ touchSnapshot: false,
664
+ }),
665
+ );
666
+ return { status: 202, body: { applied: "db" } };
667
+ }
668
+
669
+ /**
670
+ * room 离线(entity:case,任务 22):collab 直落业务列——6 字段列 + steps.steps
671
+ * (内容面变更 version+1)+ ProjectActivity(归属 actor)。不触碰快照行。
672
+ * 写前守卫复核(幽灵 409);共享写入口 writeCaseColumns 与 exporter 单源。
673
+ */
674
+ async function writeCaseBusinessRow(
675
+ room: Extract<CollabRoomName, { kind: "entity-case" }>,
676
+ fields: Map<string, unknown> | null,
677
+ steps: CollabStep[] | null,
678
+ actor: string,
679
+ ): Promise<InternalApplyResponse> {
680
+ const alive = await runRoomGuard(room);
681
+ if (!alive) {
682
+ return { status: 409, body: { error: "entity-missing" } };
683
+ }
684
+ const db = await import("@allbluecn/database");
685
+ await db.prisma.$transaction((tx) =>
686
+ writeCaseColumns(tx, {
687
+ caseId: room.caseId,
688
+ roomName: buildRoomName({ kind: "entity-case", caseId: room.caseId }),
689
+ ...(fields && { fields: Object.fromEntries(fields) as CaseFieldsPatch }),
690
+ ...(steps && steps.length > 0 && { steps }),
691
+ actor,
692
+ touchSnapshot: false,
693
+ }),
694
+ );
695
+ return { status: 202, body: { applied: "db" } };
696
+ }
697
+
698
+ /**
699
+ * room 离线(design-canvas,任务 29):collab 直落业务列——canvas(patch
700
+ * 原值,LeaferJSONPackage / 旧扁平与 web 直写同语义)+ content 双轨 + version
701
+ * 自增(内容面变更;writeDesignColumns 单源)+ AuditLog 活动(归属 actor)。
702
+ * 不触碰快照行——旁路写必须让业务列反超快照(T14 重种子化判定的正确输入)。
703
+ * 写前守卫复核(幽灵 409)。
704
+ */
705
+ async function writeDesignBusinessRow(
706
+ room: Extract<CollabRoomName, { kind: "design-canvas" }>,
707
+ canvas: Record<string, unknown> | undefined,
708
+ html: string | undefined,
709
+ markdown: string | undefined,
710
+ actor: string,
711
+ ): Promise<InternalApplyResponse> {
712
+ const alive = await runRoomGuard(room);
713
+ if (!alive) {
714
+ return { status: 409, body: { error: "entity-missing" } };
715
+ }
716
+ const db = await import("@allbluecn/database");
717
+ await db.prisma.$transaction((tx) =>
718
+ writeDesignColumns(tx, {
719
+ pageId: room.pageId,
720
+ roomName: buildRoomName({ kind: "design-canvas", pageId: room.pageId }),
721
+ canvas,
722
+ ...(html !== undefined && {
723
+ content: { html, markdown: markdown ?? html },
724
+ }),
725
+ actor,
726
+ touchSnapshot: false,
727
+ }),
728
+ );
729
+ return { status: 202, body: { applied: "db" } };
730
+ }
731
+
732
+ // ── HTTP 挂载(Hocuspocus 同端口请求监听器置换)───────────────────────
733
+
734
+ /** 内部路由(仅 POST /internal/apply;其余请求原样委托 Hocuspocus) */
735
+ const INTERNAL_APPLY_PATH = "/internal/apply";
736
+
737
+ type RequestListener = (request: IncomingMessage, response: ServerResponse) => void;
738
+
739
+ /** node:http 头值归一(重复头取首个;缺失返回空串交由验签 fail-closed) */
740
+ function signatureHeader(value: string | string[] | undefined): string {
741
+ return Array.isArray(value) ? (value[0] ?? "") : (value ?? "");
742
+ }
743
+
744
+ /** 统一 JSON 响应(headersSent 守卫;onFlushed 在响应交付后执行,如断开socket) */
745
+ function respondJson(
746
+ response: ServerResponse,
747
+ status: number,
748
+ body: Record<string, unknown>,
749
+ onFlushed?: () => void,
750
+ ): void {
751
+ if (!response.headersSent) {
752
+ response.writeHead(status, { "content-type": "application/json" });
753
+ }
754
+ response.end(JSON.stringify(body), onFlushed);
755
+ }
756
+
757
+ /**
758
+ * 请求体上限(I2,任务 17 复审加固):端口与 WS 同址公网可达,验签在读体
759
+ * 之后——无上限的未认证 POST 即内存 DoS 面。知识库 content patch 为
760
+ * {html, markdown} 双轨,超大富文本文档数百 KB 量级,2MB 留足余量;
761
+ * 声明头超限在读体前拒绝(零缓冲),流式读取按同一上限截断(防谎报/
762
+ * 缺失 content-length)。
763
+ */
764
+ export const INTERNAL_APPLY_MAX_BODY_BYTES = 2 * 1024 * 1024;
765
+
766
+ /**
767
+ * 读体(流式上限):累计超 maxBytes 返回 null(调用方回 413 并断开)。
768
+ * 请求流 error(客户端中断上传 / RST → ECONNRESET)时 reject——调用方
769
+ * 必须在 try/catch 内 await(公网可打的中断面,未捕获即进程崩溃)。
770
+ */
771
+ function readBody(request: IncomingMessage, maxBytes: number): Promise<string | null> {
772
+ return new Promise((resolve, reject) => {
773
+ const chunks: Buffer[] = [];
774
+ let total = 0;
775
+ let settled = false;
776
+ const settle = (fn: () => void) => {
777
+ if (settled) return;
778
+ settled = true;
779
+ fn();
780
+ };
781
+ request.on("data", (chunk: Buffer) => {
782
+ total += chunk.length;
783
+ if (total > maxBytes) {
784
+ request.pause();
785
+ settle(() => resolve(null));
786
+ return;
787
+ }
788
+ chunks.push(chunk);
789
+ });
790
+ request.on("end", () => settle(() => resolve(Buffer.concat(chunks).toString("utf8"))));
791
+ request.on("error", (err: Error) => settle(() => reject(err)));
792
+ });
793
+ }
794
+
795
+ /**
796
+ * 把 /internal/apply 挂到 Hocuspocus Server 的同端口 HTTP 面:
797
+ * 摘除原 request 监听器 → 内部路由自理、其余原样委托(保留「Welcome to
798
+ * Hocuspocus!」默认响应与 onRequest hooks 语义);WS upgrade 走独立
799
+ * upgrade 监听器,不受影响。
800
+ *
801
+ * 准入防线(同端口公网可达):① 全局并发读体上限(超限 503)② per-IP
802
+ * 验签失败滑动窗(超限 429,读体前拒绝)——web 转发端对非 2xx 重试至
803
+ * TTL 后降级直写,4xx/5xx 均为兼容响应。admission 可注入(测试隔离),
804
+ * 缺省内存单例(单实例边界声明同 index.ts)。
805
+ */
806
+ export function attachInternalApplyChannel(
807
+ server: Server,
808
+ secret: string,
809
+ options: { admission?: ApplyAdmission } = {},
810
+ ): void {
811
+ const httpServer = server.httpServer;
812
+ const delegated = httpServer.listeners("request") as RequestListener[];
813
+ const admission = options.admission ?? createApplyAdmission();
814
+ httpServer.removeAllListeners("request");
815
+ httpServer.on("request", (request, response) => {
816
+ const path = (request.url ?? "").split("?")[0];
817
+ if (request.method !== "POST" || path !== INTERNAL_APPLY_PATH) {
818
+ for (const listener of delegated) listener(request, response);
819
+ return;
820
+ }
821
+ const ip = request.socket.remoteAddress ?? "unknown";
822
+ // 客户端中断后响应写失败(EPIPE/ECONNRESET)走 response 的 error 事件
823
+ // ——静默吞掉(连接已死,无处理意义),防未处理 error 事件炸进程
824
+ response.on("error", () => {});
825
+ void (async () => {
826
+ try {
827
+ // 验签失败超限的 IP 读体前拒绝(不进体积/并发预算)
828
+ if (admission.isVerifyBlocked(ip)) {
829
+ respondJson(response, 429, { error: "too many attempts" });
830
+ return;
831
+ }
832
+ // 全局并发读体上限:封顶「验签前反复推送 2MB」的内存放大面
833
+ if (!admission.begin()) {
834
+ respondJson(response, 503, { error: "busy" });
835
+ return;
836
+ }
837
+ try {
838
+ // I2:验签在读体之后,体积守卫必须在最前——声明头超限零缓冲拒绝
839
+ const declared = Number(request.headers["content-length"]);
840
+ if (Number.isInteger(declared) && declared > INTERNAL_APPLY_MAX_BODY_BYTES) {
841
+ respondJson(response, 413, { error: "payload too large" });
842
+ return;
843
+ }
844
+ // 读体中断(客户端断开/RST)必须就地捕获回 4xx——rejection 逃逸
845
+ // 即 unhandledRejection,Node ≥15 默认策略为进程崩溃
846
+ let body: string;
847
+ try {
848
+ const read = await readBody(request, INTERNAL_APPLY_MAX_BODY_BYTES);
849
+ if (read === null) {
850
+ // 谎报/缺失 content-length 的流式超限:回 413 并在响应交付后
851
+ // 断开——pause 不 destroy 会让超限连接半开滞留至对端超时
852
+ respondJson(response, 413, { error: "payload too large" }, () =>
853
+ request.destroy(),
854
+ );
855
+ return;
856
+ }
857
+ body = read;
858
+ } catch (err) {
859
+ console.warn("[collab-internal] /internal/apply 读体中断(客户端断开),已拒绝:", err);
860
+ respondJson(response, 400, { error: "bad request" }, () => request.destroy());
861
+ return;
862
+ }
863
+ let result: InternalApplyResponse;
864
+ try {
865
+ result = await handleInternalApply({
866
+ hocuspocus: server.hocuspocus,
867
+ secret,
868
+ body,
869
+ signature: signatureHeader(request.headers[INTERNAL_SIGNATURE_HEADER]),
870
+ });
871
+ } catch (err) {
872
+ console.error("[collab-internal] /internal/apply 处理失败(web 侧将降级直写):", err);
873
+ result = { status: 500, body: { error: "internal" } };
874
+ }
875
+ // 验签失败计入 per-IP 滑动窗(伪造/探测的廉价放大防线)
876
+ if (result.status === 401) admission.noteVerifyFailure(ip);
877
+ respondJson(response, result.status, result.body);
878
+ } finally {
879
+ admission.end();
880
+ }
881
+ } catch (err) {
882
+ // 通道兜底(响应序列化等意外路径):任何 rejection 不得逃逸出本处理器
883
+ console.error("[collab-internal] /internal/apply 通道异常:", err);
884
+ respondJson(response, 500, { error: "internal" }, () => request.destroy());
885
+ }
886
+ })();
887
+ });
888
+ }