@allbluecn/collab-server 0.0.0-stage → 0.1.7

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
package/src/auth.ts ADDED
@@ -0,0 +1,84 @@
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
+ // §4.2 连接鉴权:verifyTicket + room 一致性 + exp,拒绝一律 throw
19
+ // (Hocuspocus onAuthenticate 抛错 → 服务端下发 permissionDenied 并拒建连)。
20
+ // reason 会原样透传到客户端 authenticationFailed 事件,保持小写短横线风格。
21
+
22
+ import { verifyTicket } from "@allbluecn/collab-core/ticket";
23
+ import type {
24
+ CollabAvatarBrief,
25
+ CollabTicketKind,
26
+ } from "@allbluecn/collab-core/types";
27
+ import { resolveRoomName } from "./rooms";
28
+
29
+ /** 鉴权失败(携带透传给客户端的 reason) */
30
+ export class CollabAuthError extends Error {
31
+ readonly reason: string;
32
+
33
+ constructor(reason: string) {
34
+ super(`协作连接被拒:${reason}`);
35
+ this.name = "CollabAuthError";
36
+ this.reason = reason;
37
+ }
38
+ }
39
+
40
+ /** 协作者(ticket payload 的白名单投影,apiKey/权限类字段禁止进入) */
41
+ export interface CollabUser {
42
+ sub: string;
43
+ name: string;
44
+ avatarBrief: CollabAvatarBrief;
45
+ kind: CollabTicketKind;
46
+ }
47
+
48
+ /** onAuthenticate 通过后写入连接 context 的形状 */
49
+ export interface CollabContext {
50
+ readOnly: boolean;
51
+ user: CollabUser;
52
+ }
53
+
54
+ /**
55
+ * 鉴权三步(任一失败 throw CollabAuthError):
56
+ * ① room 名可被 §3.1 注册表解析(fail-closed)
57
+ * ② ticket HMAC 验签 + exp 未过(verifyTicket 内含)
58
+ * ③ ticket.room 与连接的 room 严格相等(防 ticket 换 room 重放)
59
+ */
60
+ export function authenticateConnection(
61
+ token: string,
62
+ documentName: string,
63
+ secret: string,
64
+ ): CollabContext {
65
+ const room = resolveRoomName(documentName);
66
+ if (!room) throw new CollabAuthError("invalid-room");
67
+
68
+ const payload = verifyTicket(token, secret);
69
+ if (!payload) throw new CollabAuthError("invalid-ticket");
70
+
71
+ if (payload.room !== documentName) {
72
+ throw new CollabAuthError("room-mismatch");
73
+ }
74
+
75
+ return {
76
+ readOnly: payload.role === "view",
77
+ user: {
78
+ sub: payload.sub,
79
+ name: payload.name,
80
+ avatarBrief: payload.avatarBrief,
81
+ kind: payload.kind,
82
+ },
83
+ };
84
+ }
package/src/clients.ts ADDED
@@ -0,0 +1,133 @@
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
+ // CollabClient 映射层(§5.1 / §10.2):room 内 Yjs clientID → userId 的
19
+ // 「连接期映射」。内存缓存为一级 lookup(onChange 高频路径零 DB 查询),
20
+ // 数据库为持久事实(30 天 seenAt 清理的清算是唯一持久口径)。
21
+ //
22
+ // 为什么映射不在 onConnect/onAuthenticate 建立:Yjs clientID 在客户端本地
23
+ // 生成,握手与 ticket 载荷都不携带;它随该连接的**首条 awareness/update
24
+ // 消息**才到达服务端。故映射经 onAwarenessUpdate(连接后即刻触发)与
25
+ // onChange(首条编辑兜底)两条路径 upsert——两处都会在解析前回填
26
+ // connection context 的 user,保证首条 update 即可归属(尽力归属)。
27
+ //
28
+ // seenAt 刷新策略:仅在新映射落库时写 seenAt;已在缓存的 client 不重复
29
+ // 写库(awareness 光标移动是高频事件,逐条刷 seenAt 等于把日志表当计数器)。
30
+ // 30 天窗口内活跃 client 的 seenAt 由「页面刷新即新 clientID」的再累积
31
+ // 自然续期,长连接 30 天不刷新导致的过期只降级为后续 update 归属 null,
32
+ // 不丢数据(尽力归属语义)。
33
+
34
+ import * as Y from "yjs";
35
+
36
+ /** 待写库的映射行(与 CollabClient 表列对齐;clientId 落库为 BigInt) */
37
+ export interface CollabClientRow {
38
+ roomName: string;
39
+ clientId: bigint;
40
+ userId: string | null;
41
+ }
42
+
43
+ interface CacheEntry {
44
+ userId: string | null;
45
+ }
46
+
47
+ /** roomName → (clientID → 映射)。进程内存态,多实例不共享(与 index.ts 边界声明一致) */
48
+ const cache = new Map<string, Map<number, CacheEntry>>();
49
+
50
+ /**
51
+ * 从 Yjs update 字节提取来源 clientID 集合——全公开 API:
52
+ * encodeStateVectorFromUpdate 算出该 update 的「末态向量」,
53
+ * decodeStateVector 展开为 clientID → clock 映射,键集即来源 clientID。
54
+ * 纯 delete-set 的 update(无新 struct)返回空数组(无归属可记)。
55
+ */
56
+ export function clientIdsFromUpdate(update: Uint8Array): number[] {
57
+ const stateVector = Y.encodeStateVectorFromUpdate(update);
58
+ return [...Y.decodeStateVector(stateVector).keys()];
59
+ }
60
+
61
+ /**
62
+ * 记录映射(内存 + 返回需写库的行)。已缓存且 userId 未变的 client 不重复
63
+ * 返回(去重累积,@@unique([roomName, clientId]) 兜底);userId 变化(如同
64
+ * room 内身份切换)则以新值重写。调用方对返回行执行 upsert 即完成
65
+ * 「新映射 + seenAt 刷新」。
66
+ */
67
+ export function collectClientWrites(
68
+ roomName: string,
69
+ clientIds: number[],
70
+ userId: string | null,
71
+ ): CollabClientRow[] {
72
+ let roomCache = cache.get(roomName);
73
+ if (!roomCache) {
74
+ roomCache = new Map();
75
+ cache.set(roomName, roomCache);
76
+ }
77
+ const rows: CollabClientRow[] = [];
78
+ for (const clientId of clientIds) {
79
+ const existing = roomCache.get(clientId);
80
+ if (existing && existing.userId === userId) continue;
81
+ roomCache.set(clientId, { userId });
82
+ // yjs clientID 为 random.uint32(可达 2^32-1,超 Int32 上限),落库转 BigInt
83
+ rows.push({ roomName, clientId: BigInt(clientId), userId });
84
+ }
85
+ return rows;
86
+ }
87
+
88
+ /**
89
+ * 尽力归属(§5.1「authorId 由 CollabClient 映射解析」):clientID 集合经
90
+ * 映射后恰有一个非空 userId → 归属之;归属冲突(≥2 个不同 userId,如客户
91
+ * 端合并重传他人 struct;或已缓存的 null(guest/无归属)与成员 id 混存)
92
+ * → null,宁缺勿错。未缓存(无映射记录)的 clientID 不参与判定——无归属
93
+ * 信息 ≠ 归属为 null,混入未知来源时按已缓存条目尽力归属。
94
+ */
95
+ export function resolveAuthorId(roomName: string, clientIds: number[]): string | null {
96
+ const roomCache = cache.get(roomName);
97
+ if (!roomCache) return null;
98
+ // author: undefined = 尚未见已缓存条目;null = 缓存命中但无归属(guest)
99
+ let author: string | null | undefined;
100
+ for (const clientId of clientIds) {
101
+ const entry = roomCache.get(clientId);
102
+ if (entry === undefined) continue;
103
+ if (author === undefined || author === entry.userId) {
104
+ author = entry.userId;
105
+ continue;
106
+ }
107
+ return null; // 归属冲突(含 null 与成员 id 共存——归属不明,宁缺勿错)
108
+ }
109
+ return author ?? null;
110
+ }
111
+
112
+ /** 映射写库:upsert(新映射建行 + seenAt 刷新 + userId 重绑定一体完成) */
113
+ export async function upsertCollabClients(rows: CollabClientRow[]): Promise<void> {
114
+ if (rows.length === 0) return;
115
+ const { prisma } = await import("@allbluecn/database");
116
+ const now = new Date();
117
+ await prisma.$transaction(
118
+ rows.map((row) =>
119
+ prisma.collabClient.upsert({
120
+ where: {
121
+ roomName_clientId: { roomName: row.roomName, clientId: row.clientId },
122
+ },
123
+ create: { ...row, seenAt: now },
124
+ update: { userId: row.userId, seenAt: now },
125
+ }),
126
+ ),
127
+ );
128
+ }
129
+
130
+ /** 释放某 room 的内存映射(文档卸载时调用,防长驻进程缓慢累积) */
131
+ export function forgetRoomClients(roomName: string): void {
132
+ cache.delete(roomName);
133
+ }
package/src/embed.ts ADDED
@@ -0,0 +1,156 @@
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
+ // 嵌入形态 API(P4 服务形态统一 任务 30)。对标 DSH「webserver 唯一监听面 +
19
+ // WS 同端口」:Hocuspocus 从独立端口进程改为挂到宿主进程既有 HTTP server 的
20
+ // upgrade 事件,路径分流 /collab;独立启动形态退役(src/index.ts 仅保留
21
+ // COLLAB_STANDALONE=1 门禁下的回退入口)。
22
+ //
23
+ // 两条挂载路径(宿主形态决定走哪条,语义等价):
24
+ // ① attachCollabUpgradeListener——宿主持有裸 node:http.Server(Vite dev、
25
+ // Pro harness worker entry 等):把 Server 内部 httpServer 的 upgrade
26
+ // 监听器摘出,以路径过滤包装后挂到宿主 server。与 internal-apply.ts 的
27
+ // 「请求监听器置换」同型(上游公开 API 面之上,不做侵入)。
28
+ // ② createCollabCrosswsHooks——宿主为 nitro(upgrade 事件被 nitro
29
+ // features.websocket 的 crossws adapter 全量接管,无法直接挂监听器):
30
+ // 暴露与 Server.ts 构造器内部等价的 open/message/close 门面,宿主经
31
+ // crossws hooks 载荷注入(nitro resolveWebsocketHooks 读响应的
32
+ // crossws 属性或请求载荷上的 kWebSocketHooks)。
33
+ //
34
+ // 嵌入形态下 /internal/apply HTTP 通道不再经 loopback:web 侧 write-guard
35
+ // 通过 handleInternalApply 进程内直调(信封签发/验签语义不变,见 web 端
36
+ // embed-registry)。内部 httpServer 在嵌入形态不监听(attachInternalApply
37
+ // Channel 的置换仍在但为死面)。
38
+
39
+ import type { Server as HttpServer, IncomingMessage } from "node:http";
40
+ import type { Duplex } from "node:stream";
41
+ import type { Hocuspocus, Server } from "@hocuspocus/server";
42
+ import type { CollabContext } from "./auth";
43
+
44
+ /** 内嵌形态的 WS upgrade 分流路径(DSH 对标:同端口路径分流) */
45
+ export const DEFAULT_COLLAB_WS_PATH = "/collab";
46
+
47
+ // ── ① 监听器置换(裸 node:http.Server 宿主)─────────────────────────────
48
+
49
+ type UpgradeListener = (
50
+ request: IncomingMessage,
51
+ socket: Duplex,
52
+ head: Buffer,
53
+ ) => void;
54
+
55
+ /**
56
+ * 把 Hocuspocus Server 的 WS upgrade 挂到宿主 HTTP server 的指定路径:
57
+ * 摘出内部 httpServer 的 upgrade 监听器 → 在宿主 server 上注册路径过滤
58
+ * 包装(非协作路径原样放行给宿主既有监听器——Vite HMR / 终端 WS 互不干扰)。
59
+ * 嵌入形态下内部 httpServer 不监听(createCollabServer 的 port 配置仅
60
+ * standalone 形态消费)。
61
+ */
62
+ export function attachCollabUpgradeListener(
63
+ server: Server,
64
+ external: HttpServer,
65
+ path: string = DEFAULT_COLLAB_WS_PATH,
66
+ ): void {
67
+ const upgraders = server.httpServer.listeners("upgrade") as UpgradeListener[];
68
+ if (upgraders.length === 0) {
69
+ throw new Error(
70
+ "attachCollabUpgradeListener:Hocuspocus 内部 httpServer 上没有 upgrade 监听器(上游结构漂移,挂载中止)",
71
+ );
72
+ }
73
+ server.httpServer.removeAllListeners("upgrade");
74
+ external.on("upgrade", (request, socket, head) => {
75
+ const requestPath = (request.url ?? "").split("?")[0];
76
+ if (requestPath !== path) return;
77
+ for (const upgrader of upgraders) upgrader(request, socket, head);
78
+ });
79
+ }
80
+
81
+ // ── ② crossws hooks 门面(nitro 宿主经 hooks 载荷注入)──────────────────
82
+
83
+ /** 门面消费的 peer 最小面(crossws Peer 的结构子集;websocket 传给 Hocuspocus) */
84
+ export interface CollabWsPeerLike {
85
+ readonly id: string;
86
+ readonly websocket: {
87
+ send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void;
88
+ close(code?: number, reason?: string): void;
89
+ readyState: number;
90
+ };
91
+ readonly request: Request;
92
+ }
93
+
94
+ /** crossws Message 的消费面(二进制载荷) */
95
+ export interface CollabWsMessageLike {
96
+ uint8Array(): Uint8Array;
97
+ }
98
+
99
+ /**
100
+ * crossws hooks 门面(结构类型——宿主侧按各自 crossws 实例的类型断言接入)。
101
+ * upgrade 钩子缺省不设:Hocuspocus 的鉴权在 open 后的 onAuthenticate 消息层
102
+ * (token 随首条 auth 消息),upgrade 层无需鉴权(与 standalone 形态一致——
103
+ * Server.ts 仅透传 onUpgrade 配置钩子,collab 未配置)。
104
+ */
105
+ export interface CollabCrosswsHooks {
106
+ open(peer: CollabWsPeerLike): void;
107
+ message(peer: CollabWsPeerLike, message: CollabWsMessageLike): void;
108
+ close(peer: CollabWsPeerLike, event: { code: number; reason?: string }): void;
109
+ error(peer: CollabWsPeerLike, error: unknown): void;
110
+ }
111
+
112
+ /**
113
+ * 从 Hocuspocus 实例构造 crossws hooks 门面。与 @hocuspocus/server 的
114
+ * Server.ts 构造器内 crossws({ hooks }) 装配逐行同构(上游私有实例不可
115
+ * 复用);上游升级时须对照 Server.ts 复核本门面。
116
+ */
117
+ export function createCollabCrosswsHooks(
118
+ hocuspocus: Hocuspocus<CollabContext>,
119
+ ): CollabCrosswsHooks {
120
+ return {
121
+ open: (peer) => {
122
+ const clientConnection = hocuspocus.handleConnection(
123
+ peer.websocket as unknown as Parameters<
124
+ Hocuspocus<CollabContext>["handleConnection"]
125
+ >[0],
126
+ peer.request,
127
+ );
128
+ (peer as { _hocuspocus?: unknown })._hocuspocus = clientConnection;
129
+ },
130
+ message: (peer, message) => {
131
+ (
132
+ peer as { _hocuspocus?: { handleMessage(data: Uint8Array): void } }
133
+ )._hocuspocus?.handleMessage(message.uint8Array());
134
+ },
135
+ close: (peer, event) => {
136
+ (
137
+ peer as {
138
+ _hocuspocus?: {
139
+ handleClose(event?: { code: number; reason?: string }): void;
140
+ };
141
+ }
142
+ )._hocuspocus?.handleClose({ code: event.code, reason: event.reason });
143
+ },
144
+ error: (peer, error) => {
145
+ console.error("WebSocket error for peer:", peer.id);
146
+ console.error(error);
147
+ },
148
+ };
149
+ }
150
+
151
+ // web 端嵌入消费面(与 index.ts 分列 import,避免 embed ↔ index 环):
152
+ // - @allbluecn/collab-server/embed → 本文件(挂载原语 + hooks 门面 + 直调通道)
153
+ // - @allbluecn/collab-server → index.ts(createCollabServer /
154
+ // parseCollabEnvSettings / registerCollabExporters / 类型)
155
+ export { handleInternalApply } from "./internal-apply";
156
+ export { setKnowledgeReindexNotifier } from "./exporters/knowledge";