@walkhi/code-relax 0.1.0-beta.30 → 0.1.0-beta.31

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 (185) hide show
  1. package/README.md +95 -89
  2. package/dist/bin/cleanup-accounts.mjs +63 -63
  3. package/dist/bin/codex-remote.mjs +374 -367
  4. package/dist/bin/manage-relay-admin.mjs +20 -20
  5. package/dist/bin/migrate-relay-db.mjs +109 -109
  6. package/dist/bin/publish-android-release.mjs +62 -58
  7. package/dist/bin/self-relay-admin.mjs +8 -8
  8. package/dist/bin/self-relay-demo.mjs +33 -33
  9. package/dist/bin/self-relay-server.mjs +66 -66
  10. package/dist/build-platform.json +1 -1
  11. package/dist/get-lan-networks.ps1 +40 -40
  12. package/dist/get-shared-service-url.ps1 +6 -6
  13. package/dist/shared/app-server-events.cjs +422 -412
  14. package/dist/shared/code-browser.cjs +159 -159
  15. package/dist/shared/file-changes.cjs +31 -31
  16. package/dist/shared/file-citations.cjs +117 -117
  17. package/dist/shared/file-mentions.cjs +92 -92
  18. package/dist/shared/message-delivery.cjs +54 -54
  19. package/dist/shared/p2p-data-channel.cjs +72 -72
  20. package/dist/shared/p2p-diagnostics.cjs +28 -28
  21. package/dist/shared/p2p-file-channel.cjs +74 -74
  22. package/dist/shared/plan-pricing.cjs +32 -32
  23. package/dist/shared/question-attention.cjs +40 -0
  24. package/dist/shared/server-requests.cjs +219 -219
  25. package/dist/shared/timeline-sync.cjs +173 -173
  26. package/dist/skills/code-relax/SKILL.md +22 -22
  27. package/dist/src/archived-threads.mjs +22 -0
  28. package/dist/src/background-process.mjs +18 -18
  29. package/dist/src/bounded-process-log.mjs +63 -63
  30. package/dist/src/celsius-client.mjs +107 -107
  31. package/dist/src/code-browser.mjs +100 -100
  32. package/dist/src/desktop-launcher.mjs +46 -46
  33. package/dist/src/dots-approval-timeline.mjs +99 -99
  34. package/dist/src/dots-avatar.mjs +42 -42
  35. package/dist/src/dots-chat-projection.mjs +50 -50
  36. package/dist/src/dots-chat-server.mjs +461 -461
  37. package/dist/src/dots-message-images.mjs +319 -319
  38. package/dist/src/dots-profile.mjs +77 -77
  39. package/dist/src/dots-room-activity.mjs +94 -94
  40. package/dist/src/dots-room-client.mjs +135 -135
  41. package/dist/src/dots-room-projection.mjs +94 -94
  42. package/dist/src/dots-schedules.mjs +66 -66
  43. package/dist/src/dots-summary-tasks.mjs +32 -32
  44. package/dist/src/dots-task-catalog.mjs +430 -430
  45. package/dist/src/dots-task-files.mjs +52 -52
  46. package/dist/src/execution-health.mjs +26 -26
  47. package/dist/src/file-transfer-range.mjs +22 -22
  48. package/dist/src/file-upload-session.mjs +130 -130
  49. package/dist/src/hosted-history-app-server.mjs +103 -103
  50. package/dist/src/hosted-history-cache.mjs +113 -113
  51. package/dist/src/lan-socket-server.mjs +265 -263
  52. package/dist/src/managed-app-server.mjs +244 -244
  53. package/dist/src/message-images.mjs +9 -9
  54. package/dist/src/message-upload-files.mjs +74 -74
  55. package/dist/src/onboarding.mjs +12 -12
  56. package/dist/src/plan-pricing.mjs +47 -47
  57. package/dist/src/platform/README.md +12 -12
  58. package/dist/src/platform/codex-protocol.mjs +46 -46
  59. package/dist/src/platform/codex-runtime.mjs +3 -3
  60. package/dist/src/platform/credential-store.mjs +3 -3
  61. package/dist/src/platform/desktop-host.mjs +3 -3
  62. package/dist/src/platform/desktop-project-registration.mjs +3 -3
  63. package/dist/src/platform/desktop-project-store.mjs +208 -149
  64. package/dist/src/platform/file-opener.mjs +9 -0
  65. package/dist/src/platform/linux/README.md +3 -3
  66. package/dist/src/platform/linux/codex-runtime.mjs +56 -0
  67. package/dist/src/platform/linux/credential-store.mjs +28 -0
  68. package/dist/src/platform/linux/desktop-host.mjs +83 -0
  69. package/dist/src/platform/linux/desktop-installation.mjs +36 -0
  70. package/dist/src/platform/linux/desktop-project-registration.mjs +11 -0
  71. package/dist/src/platform/linux/network-info.mjs +11 -0
  72. package/dist/src/platform/linux/process.mjs +42 -0
  73. package/dist/src/platform/linux/project-locations.mjs +17 -0
  74. package/dist/src/platform/linux/resident-startup.mjs +52 -0
  75. package/dist/src/platform/linux/retained-runtime.mjs +76 -0
  76. package/dist/src/platform/linux/service-host.mjs +18 -0
  77. package/dist/src/platform/linux/system.mjs +49 -0
  78. package/dist/src/platform/linux/user-environment.mjs +7 -0
  79. package/dist/src/platform/macos/README.md +3 -3
  80. package/dist/src/platform/macos/codex-runtime.mjs +125 -125
  81. package/dist/src/platform/macos/credential-store.mjs +10 -10
  82. package/dist/src/platform/macos/desktop-host.mjs +82 -82
  83. package/dist/src/platform/macos/desktop-project-registration.mjs +11 -10
  84. package/dist/src/platform/macos/network-info.mjs +8 -28
  85. package/dist/src/platform/macos/project-locations.mjs +8 -8
  86. package/dist/src/platform/macos/resident-startup.mjs +84 -84
  87. package/dist/src/platform/macos/retained-runtime.mjs +127 -127
  88. package/dist/src/platform/macos/service-host.mjs +18 -18
  89. package/dist/src/platform/macos/system.mjs +29 -29
  90. package/dist/src/platform/macos/user-environment.mjs +7 -7
  91. package/dist/src/platform/native-package.mjs +58 -46
  92. package/dist/src/platform/network-info.mjs +3 -3
  93. package/dist/src/platform/path-identity.mjs +5 -5
  94. package/dist/src/platform/posix/network-candidates.mjs +23 -0
  95. package/dist/src/platform/posix/runtime-paths.mjs +25 -25
  96. package/dist/src/platform/project-locations.mjs +3 -3
  97. package/dist/src/platform/runtime-paths.mjs +8 -8
  98. package/dist/src/platform/select.mjs +5 -5
  99. package/dist/src/platform/service-host.mjs +3 -3
  100. package/dist/src/platform/user-environment.mjs +3 -3
  101. package/dist/src/platform/windows/IsolatedProcess.cs +79 -79
  102. package/dist/src/platform/windows/activate-desktop.ps1 +48 -48
  103. package/dist/src/platform/windows/background-process.mjs +30 -30
  104. package/dist/src/platform/windows/codex-runtime.mjs +215 -215
  105. package/dist/src/platform/windows/credential-store.mjs +27 -27
  106. package/dist/src/platform/windows/credential-store.ps1 +49 -49
  107. package/dist/src/platform/windows/desktop-helper.mjs +179 -179
  108. package/dist/src/platform/windows/desktop-host.mjs +58 -58
  109. package/dist/src/platform/windows/desktop-info.ps1 +14 -14
  110. package/dist/src/platform/windows/desktop-project-registration.mjs +4 -4
  111. package/dist/src/platform/windows/desktop-runtime.ps1 +10 -10
  112. package/dist/src/platform/windows/desktop-shortcuts.ps1 +21 -21
  113. package/dist/src/platform/windows/dots-profile.mjs +49 -49
  114. package/dist/src/platform/windows/launch-worker.mjs +41 -41
  115. package/dist/src/platform/windows/network-info.mjs +34 -34
  116. package/dist/src/platform/windows/project-locations.mjs +16 -16
  117. package/dist/src/platform/windows/resident-start.js +20 -20
  118. package/dist/src/platform/windows/resident-start.ps1 +7 -7
  119. package/dist/src/platform/windows/resident-startup.ps1 +83 -83
  120. package/dist/src/platform/windows/resolve-state-root.ps1 +14 -14
  121. package/dist/src/platform/windows/runtime-paths.mjs +20 -20
  122. package/dist/src/platform/windows/rustdesk-video-probe.mjs +167 -167
  123. package/dist/src/platform/windows/service-host.mjs +31 -31
  124. package/dist/src/platform/windows/start-hidden-console.ps1 +49 -49
  125. package/dist/src/platform/windows/stop-desktop.ps1 +22 -22
  126. package/dist/src/platform/windows/user-environment.mjs +50 -50
  127. package/dist/src/platform/windows/user-environment.ps1 +41 -41
  128. package/dist/src/project-archive.mjs +30 -0
  129. package/dist/src/project-create.mjs +121 -119
  130. package/dist/src/project-management.mjs +59 -69
  131. package/dist/src/project-remove.mjs +55 -0
  132. package/dist/src/project-update.mjs +56 -0
  133. package/dist/src/runtime-discovery.mjs +47 -47
  134. package/dist/src/self-relay/account-cleanup.mjs +30 -30
  135. package/dist/src/self-relay/account-connections.mjs +52 -52
  136. package/dist/src/self-relay/admin-cloud.mjs +101 -101
  137. package/dist/src/self-relay/admin-page.mjs +80 -80
  138. package/dist/src/self-relay/admin-server.mjs +74 -74
  139. package/dist/src/self-relay/admin-state.mjs +127 -127
  140. package/dist/src/self-relay/admin-style.mjs +14 -14
  141. package/dist/src/self-relay/android-releases.mjs +61 -61
  142. package/dist/src/self-relay/client.mjs +61 -61
  143. package/dist/src/self-relay/connector.mjs +439 -438
  144. package/dist/src/self-relay/debug-allowlist.mjs +33 -33
  145. package/dist/src/self-relay/demo.mjs +37 -37
  146. package/dist/src/self-relay/device-info.mjs +27 -0
  147. package/dist/src/self-relay/device-store.mjs +92 -84
  148. package/dist/src/self-relay/diagnostics.mjs +54 -54
  149. package/dist/src/self-relay/email-accounts.mjs +183 -183
  150. package/dist/src/self-relay/file-wire.mjs +13 -13
  151. package/dist/src/self-relay/lan-authorizations.mjs +71 -42
  152. package/dist/src/self-relay/lifecycle.mjs +264 -250
  153. package/dist/src/self-relay/long-pairing.mjs +40 -40
  154. package/dist/src/self-relay/mysql-state.mjs +118 -105
  155. package/dist/src/self-relay/p2p-probe.mjs +159 -159
  156. package/dist/src/self-relay/privacy-page.mjs +26 -26
  157. package/dist/src/self-relay/public-releases.mjs +34 -0
  158. package/dist/src/self-relay/rtc-file-bridge.mjs +41 -41
  159. package/dist/src/self-relay/server.mjs +1006 -932
  160. package/dist/src/self-relay/usage-daily.mjs +55 -55
  161. package/dist/src/self-relay/usage-meter.mjs +141 -141
  162. package/dist/src/self-relay/windows-route-helper.mjs +75 -75
  163. package/dist/src/self-relay/wire.mjs +36 -36
  164. package/dist/src/server.mjs +1861 -1778
  165. package/dist/src/service-control.mjs +82 -82
  166. package/dist/src/service-doctor.mjs +110 -110
  167. package/dist/src/service-health.mjs +33 -33
  168. package/dist/src/service-install.mjs +91 -91
  169. package/dist/src/service-lifecycle.mjs +138 -138
  170. package/dist/src/service-restart.mjs +81 -81
  171. package/dist/src/shared-app-server.mjs +615 -611
  172. package/dist/src/shared-catalog.mjs +132 -132
  173. package/dist/src/shared-recovery.mjs +146 -146
  174. package/dist/src/shared-thread-stream.mjs +164 -164
  175. package/dist/src/skill-install.mjs +51 -51
  176. package/dist/src/thread-title-generation.mjs +150 -150
  177. package/dist/src/turn-model-history.mjs +47 -47
  178. package/dist/src/usage-reset.mjs +17 -17
  179. package/dist/src/workstation-downloads.mjs +120 -120
  180. package/dist/tools/rtc-route-helper.ps1 +99 -99
  181. package/dist/tools/start-rtc-route-helper.ps1 +15 -15
  182. package/dist/web/vendor/markdown-it.LICENSE.txt +22 -22
  183. package/dist/web/vendor/markdown-it.umd.min.js +13 -13
  184. package/package.json +7 -6
  185. package/tools/postinstall.mjs +127 -127
@@ -1,263 +1,265 @@
1
- import { EventEmitter } from 'node:events';
2
- import crypto from 'node:crypto';
3
- import { WebSocketServer, WebSocket } from 'ws';
4
- import timelineSync from '../shared/timeline-sync.cjs';
5
- import { createFileUploadSession, FILE_CHUNK_BYTES, MAX_FILE_BYTES, MAX_FILE_COUNT, MAX_TOTAL_BYTES } from './file-upload-session.mjs';
6
- import { FILE_READ_LIMIT } from './file-transfer-range.mjs';
7
-
8
- // One authenticated connection carries requests and explicitly owned subscriptions.
9
- // The dispatcher is shared business routing, not an HTTP loopback proxy.
10
- export function attachLanSocket(server, { token, dispatch, authorizeDevice = () => false, onDeviceAuthorizationsChanged, uploadsRoot }) {
11
- // Allow four individually valid images to reach the aggregate-size validator,
12
- // so an oversized composition returns an error instead of dropping the connection.
13
- const wss = new WebSocketServer({ noServer: true, maxPayload: 48 * 1024 * 1024, perMessageDeflate: false });
14
- const uploadWss = new WebSocketServer({ noServer: true, maxPayload: 512 * 1024, perMessageDeflate: false });
15
- const activeUploads = new Map();
16
- const deviceConnections = new Map();
17
- const stopWatching = onDeviceAuthorizationsChanged?.(() => {
18
- for (const connection of deviceConnections.values()) {
19
- if (!authorizeDevice(connection.clientId, connection.credential)) connection.revoke();
20
- }
21
- });
22
- server.on('upgrade', (request, socket, head) => {
23
- const origin = request.headers.origin;
24
- const upload = request.url === '/api/file-transfer' && Boolean(uploadsRoot);
25
- let allowed = request.url === '/api/socket' || upload;
26
- // Packaged ArkWeb pages have an opaque ("null") origin; device authentication remains required.
27
- if (origin && origin !== 'null') {
28
- try {
29
- const originUrl = new URL(origin);
30
- const requestUrl = new URL(`http://${request.headers.host}`);
31
- const nativeClient = request.headers['x-code-relax-native'] === '1';
32
- allowed &&= ['http:', 'https:'].includes(originUrl.protocol) &&
33
- (originUrl.host === request.headers.host || (nativeClient && originUrl.hostname === requestUrl.hostname));
34
- }
35
- catch { allowed = false; }
36
- }
37
- if (!allowed) { socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n'); return; }
38
- const target = upload ? uploadWss : wss;
39
- target.handleUpgrade(request, socket, head, ws => target.emit('connection', ws));
40
- });
41
- uploadWss.on('connection', ws => {
42
- let authenticated = false, stopped = false, identity = '', upload, purpose, chunk;
43
- let queued = 0;
44
- let pending = Promise.resolve();
45
- const authTimer = setTimeout(() => ws.close(1008, 'Authentication required'), 5000);
46
- const reply = value => { if (!stopped && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(value)); };
47
- ws.on('error', () => {});
48
- const stop = () => {
49
- if (stopped) return;
50
- stopped = true;
51
- deviceConnections.delete(ws);
52
- clearTimeout(authTimer);
53
- void pending.finally(async () => {
54
- await upload?.close();
55
- activeUploads.delete(ws);
56
- });
57
- };
58
- ws.on('close', stop);
59
- ws.on('message', (bytes, binary) => {
60
- if (stopped || ws.readyState !== WebSocket.OPEN) return;
61
- if (++queued > 4) { stop(); ws.close(1013, 'File request queue exceeded'); return; }
62
- pending = pending.then(async () => {
63
- if (stopped || ws.readyState !== WebSocket.OPEN) return;
64
- if (binary) {
65
- if (!authenticated || purpose !== 'upload' || !chunk || bytes.length !== chunk.length) throw new Error('无效的文件分片');
66
- const current = chunk; chunk = undefined;
67
- reply(await upload.receive({ ...current, data: bytes })); return;
68
- }
69
- if (bytes.length > 16 * 1024 || chunk) throw new Error('无效的文件请求');
70
- const message = JSON.parse(bytes.toString());
71
- if (!authenticated) {
72
- purpose = message.purpose;
73
- if (!['upload', 'download'].includes(purpose)) throw new Error('文件通道用途无效');
74
- if (message?.type === 'device-auth' && typeof message.clientId === 'string' &&
75
- authorizeDevice(message.clientId, message.credential) === true) identity = `device:${message.clientId}`;
76
- else if (token && message?.type === 'auth' && typeof message.token === 'string') {
77
- const supplied = Buffer.from(message.token), expected = Buffer.from(token || '');
78
- if (supplied.length === expected.length && crypto.timingSafeEqual(supplied, expected)) identity = 'local-token';
79
- }
80
- const same = [...activeUploads.values()].filter(item => item.identity === identity && item.purpose === purpose);
81
- const uploads = [...activeUploads.values()].filter(item => item.purpose === 'upload').length;
82
- if (!identity || same.length >= (purpose === 'upload' ? 1 : 3) || activeUploads.size >= 8 ||
83
- (purpose === 'upload' && uploads >= 2)) throw new Error('文件身份无效或文件任务过多');
84
- if (message.type === 'device-auth') deviceConnections.set(ws, {
85
- clientId: message.clientId, credential: message.credential,
86
- revoke() { stop(); ws.close(4401, 'Device authorization revoked'); },
87
- });
88
- activeUploads.set(ws, { identity, purpose }); authenticated = true; clearTimeout(authTimer);
89
- if (purpose === 'upload') upload = createFileUploadSession(uploadsRoot);
90
- reply({ type: 'ready', version: 2, purpose, maxDownloadBytes: FILE_READ_LIMIT, maxFileBytes: MAX_FILE_BYTES, maxFileCount: MAX_FILE_COUNT,
91
- maxTotalBytes: MAX_TOTAL_BYTES, chunkBytes: FILE_CHUNK_BYTES });
92
- return;
93
- }
94
- if (purpose === 'download') {
95
- if (message.type !== 'read' || typeof message.path !== 'string' || message.path.length > 12000 ||
96
- !/^\/api\/(?:images\/[a-f0-9]{64}|files\/(?:local|[a-f0-9]{64})|code\/(?:image|binary)|desktop\/frames\/[a-f0-9]{32})(?:\?|$)/.test(message.path) || message.path.includes('#')) throw new Error('无效的文件读取请求');
97
- await dispatch({ method: 'GET', url: message.path, headers: {}, socketRequest: true, fileTransfer: true }, {
98
- json(status, body) { reply({ type: 'error', status, error: body?.error || '文件读取失败' }); },
99
- filePart(metadata, data) {
100
- if (stopped || ws.readyState !== WebSocket.OPEN) return;
101
- if (!Buffer.isBuffer(data) || data.length > FILE_CHUNK_BYTES || ws.bufferedAmount > 1024 * 1024) throw new Error('文件接收过慢或分片无效');
102
- reply({ type: 'part', ...metadata, length: data.length });
103
- ws.send(data);
104
- },
105
- });
106
- return;
107
- }
108
- if (message.type === 'chunk') {
109
- if (!Number.isSafeInteger(message.length) || message.length < 1 || message.length > FILE_CHUNK_BYTES) throw new Error('文件分片大小无效');
110
- chunk = message; return;
111
- }
112
- reply(await upload.receive(message));
113
- }).catch(error => { reply({ type: 'error', error: error.message }); stop(); ws.close(1008, 'File request rejected'); })
114
- .finally(() => { queued--; });
115
- });
116
- });
117
- wss.on('connection', ws => {
118
- let authenticated = false, alive = true, stopped = false;
119
- const active = new Map();
120
- const send = value => {
121
- if (stopped || ws.readyState !== WebSocket.OPEN) return;
122
- if (ws.bufferedAmount > 64 * 1024 * 1024) { ws.close(1013, 'Client too slow'); return; }
123
- ws.send(JSON.stringify(value));
124
- };
125
- const authTimer = setTimeout(() => ws.close(1008, 'Authentication required'), 5000);
126
- const heartbeat = setInterval(() => {
127
- if (!alive) { ws.terminate(); return; }
128
- alive = false; ws.ping();
129
- }, 30000);
130
- ws.on('pong', () => { alive = true; });
131
- ws.on('error', () => {}); // close rejects requests and releases every subscription.
132
- const stop = () => {
133
- if (stopped) return;
134
- stopped = true;
135
- deviceConnections.delete(ws);
136
- clearTimeout(authTimer); clearInterval(heartbeat);
137
- for (const reply of active.values()) reply.end();
138
- active.clear();
139
- };
140
- ws.on('close', stop);
141
- ws.on('message', async (bytes, binary) => {
142
- if (stopped || ws.readyState !== WebSocket.OPEN) return;
143
- let message;
144
- try { if (binary) throw new Error(); message = JSON.parse(bytes.toString()); }
145
- catch { ws.close(1008, 'Invalid JSON'); return; }
146
- if (!message || typeof message !== 'object') { ws.close(1008, 'Invalid message'); return; }
147
- if (!authenticated) {
148
- let accepted = false;
149
- if (message.type === 'device-auth') {
150
- accepted = authorizeDevice(message.clientId, message.credential) === true;
151
- } else if (message.type === 'auth') {
152
- const supplied = Buffer.from(typeof message.token === 'string' ? message.token : '');
153
- const expected = Buffer.from(token || '');
154
- accepted = supplied.length === expected.length && crypto.timingSafeEqual(supplied, expected);
155
- }
156
- if (!accepted) {
157
- ws.close(1008, 'Authentication failed'); return;
158
- }
159
- if (message.type === 'device-auth') deviceConnections.set(ws, {
160
- clientId: message.clientId, credential: message.credential,
161
- revoke() { stop(); ws.close(4401, 'Device authorization revoked'); },
162
- });
163
- authenticated = true; clearTimeout(authTimer); send({ type: 'ready', version: 1 }); return;
164
- }
165
- const { id, type } = message;
166
- if (!Number.isSafeInteger(id) || id < 1) { ws.close(1008, 'Invalid request id'); return; }
167
- if (type === 'response-ack') { active.get(id)?.acknowledge?.(message.batch); return; }
168
- if (type === 'cancel') { active.get(id)?.end(); return; }
169
- if (type === 'unsubscribe') { const reply = active.get(id); if (reply?.subscription) reply.end(); return; }
170
- if (!['request', 'subscribe'].includes(type) || active.has(id)) { ws.close(1008, 'Invalid request'); return; }
171
- const subscription = type === 'subscribe';
172
- const path = message.path;
173
- const isStream = typeof path === 'string' && /^\/api\/(?:usage-events|thread-events|turn-events|shared-recovery\/events|threads\/[^/?]+\/(?:events|dots-activity-events))(?:\?|$)/.test(path);
174
- // Native recovery, usage, catalog, current chat, and the main Dot's sidebar
175
- // share one station connection (including when viewing a delegated task).
176
- if (active.size >= 32 || (subscription && [...active.values()].filter(r => r.subscription).length >= 5)) {
177
- send({ type: 'response', id, status: 429, body: { error: '同时进行的请求过多' } }); return;
178
- }
179
- if (typeof path !== 'string' || !path.startsWith('/api/') || path.includes('#') ||
180
- path.startsWith('/api/attachments/') || path === '/api/socket' || path === '/api/uploads' ||
181
- subscription !== isStream || !['GET', 'POST', 'PUT', 'DELETE'].includes(message.method || 'GET') ||
182
- (subscription && message.method && message.method !== 'GET') ||
183
- (message.body !== undefined && (!message.body || typeof message.body !== 'object' || Array.isArray(message.body)))) {
184
- send({ type: 'response', id, status: 400, body: { error: '无效的连接请求' } }); return;
185
- }
186
- const reply = new EventEmitter();
187
- let waiting, batch = 0;
188
- const sendPart = (pieces, pageEnd = false) => new Promise((resolve, reject) => {
189
- const timer = setTimeout(() => reject(new Error('历史接收确认超时')), 20000);
190
- waiting = { resolve, reject, timer, batch: ++batch };
191
- send({ type: subscription ? 'event-part' : 'response-part', id, batch, pieces, ...(pageEnd ? { pageEnd: true } : {}) });
192
- });
193
- const sendTimeline = async (status, body, event) => {
194
- if (event) batch = 0;
195
- try {
196
- for (const pieces of timelineSync.timelineBatches(body)) {
197
- if (reply.writableEnded) return;
198
- await sendPart(pieces);
199
- }
200
- if (!reply.writableEnded) {
201
- send(event ? { type: 'event', id, event, streamed: true } : { type: 'response', id, status, streamed: true });
202
- if (!event) reply.end();
203
- }
204
- } catch (error) {
205
- if (!reply.writableEnded) {
206
- send(event ? { type: 'event', id, event: 'bridge-error', data: { error: error.message } }
207
- : { type: 'response', id, status: 500, body: { error: error.message } });
208
- reply.end();
209
- }
210
- }
211
- };
212
- Object.assign(reply, {
213
- subscription, headersSent: false, writableEnded: false, destroyed: false,
214
- async historyPage(page) {
215
- const parts = timelineSync.timelineBatches(page);
216
- let part = parts.next();
217
- while (!part.done) {
218
- if (this.writableEnded) throw new Error('历史读取已取消');
219
- const next = parts.next();
220
- await sendPart(part.value, next.done);
221
- part = next;
222
- }
223
- },
224
- json(status, body) {
225
- if (this.writableEnded) return;
226
- if (status < 400 && body?.schemaVersion === 1 && Array.isArray(body.turns)) {
227
- void sendTimeline(status, body); return;
228
- }
229
- send({ type: 'response', id, status, body }); this.end();
230
- },
231
- acknowledge(sequence) {
232
- if (!waiting || sequence !== waiting.batch) return;
233
- const completed = waiting; waiting = null; clearTimeout(completed.timer);
234
- this.emit('progress'); completed.resolve();
235
- },
236
- startEvents() {
237
- if (this.writableEnded) return;
238
- this.headersSent = true; send({ type: 'subscribed', id });
239
- },
240
- event(event, data) {
241
- if (this.writableEnded) return;
242
- if (event === 'update' && data?.schemaVersion === 1) return sendTimeline(200, data, event);
243
- send({ type: 'event', id, event, data });
244
- },
245
- end() {
246
- if (this.writableEnded) return;
247
- this.writableEnded = this.destroyed = true; active.delete(id);
248
- if (waiting) { clearTimeout(waiting.timer); waiting.reject(new Error('历史读取已取消')); waiting = null; }
249
- if (subscription) send({ type: 'end', id });
250
- this.emit('close');
251
- },
252
- });
253
- active.set(id, reply);
254
- try { await dispatch({ method: message.method || 'GET', url: path, body: message.body || {}, headers: {}, socketRequest: true }, reply); }
255
- catch (error) { reply.json(500, { error: error.message }); }
256
- });
257
- });
258
- return { close() {
259
- stopWatching?.();
260
- for (const ws of wss.clients) ws.terminate(); wss.close();
261
- for (const ws of uploadWss.clients) ws.terminate(); uploadWss.close();
262
- } };
263
- }
1
+ import { EventEmitter } from 'node:events';
2
+ import crypto from 'node:crypto';
3
+ import { WebSocketServer, WebSocket } from 'ws';
4
+ import timelineSync from '../shared/timeline-sync.cjs';
5
+ import { createFileUploadSession, FILE_CHUNK_BYTES, MAX_FILE_BYTES, MAX_FILE_COUNT, MAX_TOTAL_BYTES } from './file-upload-session.mjs';
6
+ import { FILE_READ_LIMIT } from './file-transfer-range.mjs';
7
+
8
+ // One authenticated connection carries requests and explicitly owned subscriptions.
9
+ // The dispatcher is shared business routing, not an HTTP loopback proxy.
10
+ export function attachLanSocket(server, { token, dispatch, authorizeDevice = () => false, onDeviceAuthorizationsChanged, onDeviceConnected, uploadsRoot }) {
11
+ // Allow four individually valid images to reach the aggregate-size validator,
12
+ // so an oversized composition returns an error instead of dropping the connection.
13
+ const wss = new WebSocketServer({ noServer: true, maxPayload: 48 * 1024 * 1024, perMessageDeflate: false });
14
+ const uploadWss = new WebSocketServer({ noServer: true, maxPayload: 512 * 1024, perMessageDeflate: false });
15
+ const activeUploads = new Map();
16
+ const deviceConnections = new Map();
17
+ const stopWatching = onDeviceAuthorizationsChanged?.(() => {
18
+ for (const connection of deviceConnections.values()) {
19
+ if (!authorizeDevice(connection.clientId, connection.credential)) connection.revoke();
20
+ }
21
+ });
22
+ server.on('upgrade', (request, socket, head) => {
23
+ const origin = request.headers.origin;
24
+ const upload = request.url === '/api/file-transfer' && Boolean(uploadsRoot);
25
+ let allowed = request.url === '/api/socket' || upload;
26
+ // Packaged ArkWeb pages have an opaque ("null") origin; device authentication remains required.
27
+ if (origin && origin !== 'null') {
28
+ try {
29
+ const originUrl = new URL(origin);
30
+ const requestUrl = new URL(`http://${request.headers.host}`);
31
+ const nativeClient = request.headers['x-code-relax-native'] === '1';
32
+ allowed &&= ['http:', 'https:'].includes(originUrl.protocol) &&
33
+ (originUrl.host === request.headers.host || (nativeClient && originUrl.hostname === requestUrl.hostname));
34
+ }
35
+ catch { allowed = false; }
36
+ }
37
+ if (!allowed) { socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n'); return; }
38
+ const target = upload ? uploadWss : wss;
39
+ target.handleUpgrade(request, socket, head, ws => target.emit('connection', ws));
40
+ });
41
+ uploadWss.on('connection', ws => {
42
+ let authenticated = false, stopped = false, identity = '', upload, purpose, chunk;
43
+ let queued = 0;
44
+ let pending = Promise.resolve();
45
+ const authTimer = setTimeout(() => ws.close(1008, 'Authentication required'), 5000);
46
+ const reply = value => { if (!stopped && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(value)); };
47
+ ws.on('error', () => {});
48
+ const stop = () => {
49
+ if (stopped) return;
50
+ stopped = true;
51
+ deviceConnections.delete(ws);
52
+ clearTimeout(authTimer);
53
+ void pending.finally(async () => {
54
+ await upload?.close();
55
+ activeUploads.delete(ws);
56
+ });
57
+ };
58
+ ws.on('close', stop);
59
+ ws.on('message', (bytes, binary) => {
60
+ if (stopped || ws.readyState !== WebSocket.OPEN) return;
61
+ if (++queued > 4) { stop(); ws.close(1013, 'File request queue exceeded'); return; }
62
+ pending = pending.then(async () => {
63
+ if (stopped || ws.readyState !== WebSocket.OPEN) return;
64
+ if (binary) {
65
+ if (!authenticated || purpose !== 'upload' || !chunk || bytes.length !== chunk.length) throw new Error('无效的文件分片');
66
+ const current = chunk; chunk = undefined;
67
+ reply(await upload.receive({ ...current, data: bytes })); return;
68
+ }
69
+ if (bytes.length > 16 * 1024 || chunk) throw new Error('无效的文件请求');
70
+ const message = JSON.parse(bytes.toString());
71
+ if (!authenticated) {
72
+ purpose = message.purpose;
73
+ if (!['upload', 'download'].includes(purpose)) throw new Error('文件通道用途无效');
74
+ if (message?.type === 'device-auth' && typeof message.clientId === 'string' &&
75
+ authorizeDevice(message.clientId, message.credential) === true) identity = `device:${message.clientId}`;
76
+ else if (token && message?.type === 'auth' && typeof message.token === 'string') {
77
+ const supplied = Buffer.from(message.token), expected = Buffer.from(token || '');
78
+ if (supplied.length === expected.length && crypto.timingSafeEqual(supplied, expected)) identity = 'local-token';
79
+ }
80
+ const same = [...activeUploads.values()].filter(item => item.identity === identity && item.purpose === purpose);
81
+ const uploads = [...activeUploads.values()].filter(item => item.purpose === 'upload').length;
82
+ if (!identity || same.length >= (purpose === 'upload' ? 1 : 3) || activeUploads.size >= 8 ||
83
+ (purpose === 'upload' && uploads >= 2)) throw new Error('文件身份无效或文件任务过多');
84
+ if (message.type === 'device-auth') deviceConnections.set(ws, {
85
+ clientId: message.clientId, credential: message.credential,
86
+ revoke() { stop(); ws.close(4401, 'Device authorization revoked'); },
87
+ });
88
+ activeUploads.set(ws, { identity, purpose }); authenticated = true; clearTimeout(authTimer);
89
+ if (message.type === 'device-auth') onDeviceConnected?.(message.clientId, message);
90
+ if (purpose === 'upload') upload = createFileUploadSession(uploadsRoot);
91
+ reply({ type: 'ready', version: 2, purpose, maxDownloadBytes: FILE_READ_LIMIT, maxFileBytes: MAX_FILE_BYTES, maxFileCount: MAX_FILE_COUNT,
92
+ maxTotalBytes: MAX_TOTAL_BYTES, chunkBytes: FILE_CHUNK_BYTES });
93
+ return;
94
+ }
95
+ if (purpose === 'download') {
96
+ if (message.type !== 'read' || typeof message.path !== 'string' || message.path.length > 12000 ||
97
+ !/^\/api\/(?:images\/[a-f0-9]{64}|files\/(?:local|[a-f0-9]{64})|code\/(?:image|binary)|desktop\/frames\/[a-f0-9]{32})(?:\?|$)/.test(message.path) || message.path.includes('#')) throw new Error('无效的文件读取请求');
98
+ await dispatch({ method: 'GET', url: message.path, headers: {}, socketRequest: true, fileTransfer: true }, {
99
+ json(status, body) { reply({ type: 'error', status, error: body?.error || '文件读取失败' }); },
100
+ filePart(metadata, data) {
101
+ if (stopped || ws.readyState !== WebSocket.OPEN) return;
102
+ if (!Buffer.isBuffer(data) || data.length > FILE_CHUNK_BYTES || ws.bufferedAmount > 1024 * 1024) throw new Error('文件接收过慢或分片无效');
103
+ reply({ type: 'part', ...metadata, length: data.length });
104
+ ws.send(data);
105
+ },
106
+ });
107
+ return;
108
+ }
109
+ if (message.type === 'chunk') {
110
+ if (!Number.isSafeInteger(message.length) || message.length < 1 || message.length > FILE_CHUNK_BYTES) throw new Error('文件分片大小无效');
111
+ chunk = message; return;
112
+ }
113
+ reply(await upload.receive(message));
114
+ }).catch(error => { reply({ type: 'error', error: error.message }); stop(); ws.close(1008, 'File request rejected'); })
115
+ .finally(() => { queued--; });
116
+ });
117
+ });
118
+ wss.on('connection', ws => {
119
+ let authenticated = false, alive = true, stopped = false;
120
+ const active = new Map();
121
+ const send = value => {
122
+ if (stopped || ws.readyState !== WebSocket.OPEN) return;
123
+ if (ws.bufferedAmount > 64 * 1024 * 1024) { ws.close(1013, 'Client too slow'); return; }
124
+ ws.send(JSON.stringify(value));
125
+ };
126
+ const authTimer = setTimeout(() => ws.close(1008, 'Authentication required'), 5000);
127
+ const heartbeat = setInterval(() => {
128
+ if (!alive) { ws.terminate(); return; }
129
+ alive = false; ws.ping();
130
+ }, 30000);
131
+ ws.on('pong', () => { alive = true; });
132
+ ws.on('error', () => {}); // close rejects requests and releases every subscription.
133
+ const stop = () => {
134
+ if (stopped) return;
135
+ stopped = true;
136
+ deviceConnections.delete(ws);
137
+ clearTimeout(authTimer); clearInterval(heartbeat);
138
+ for (const reply of active.values()) reply.end();
139
+ active.clear();
140
+ };
141
+ ws.on('close', stop);
142
+ ws.on('message', async (bytes, binary) => {
143
+ if (stopped || ws.readyState !== WebSocket.OPEN) return;
144
+ let message;
145
+ try { if (binary) throw new Error(); message = JSON.parse(bytes.toString()); }
146
+ catch { ws.close(1008, 'Invalid JSON'); return; }
147
+ if (!message || typeof message !== 'object') { ws.close(1008, 'Invalid message'); return; }
148
+ if (!authenticated) {
149
+ let accepted = false;
150
+ if (message.type === 'device-auth') {
151
+ accepted = authorizeDevice(message.clientId, message.credential) === true;
152
+ } else if (message.type === 'auth') {
153
+ const supplied = Buffer.from(typeof message.token === 'string' ? message.token : '');
154
+ const expected = Buffer.from(token || '');
155
+ accepted = supplied.length === expected.length && crypto.timingSafeEqual(supplied, expected);
156
+ }
157
+ if (!accepted) {
158
+ ws.close(1008, 'Authentication failed'); return;
159
+ }
160
+ if (message.type === 'device-auth') onDeviceConnected?.(message.clientId, message);
161
+ if (message.type === 'device-auth') deviceConnections.set(ws, {
162
+ clientId: message.clientId, credential: message.credential,
163
+ revoke() { stop(); ws.close(4401, 'Device authorization revoked'); },
164
+ });
165
+ authenticated = true; clearTimeout(authTimer); send({ type: 'ready', version: 1 }); return;
166
+ }
167
+ const { id, type } = message;
168
+ if (!Number.isSafeInteger(id) || id < 1) { ws.close(1008, 'Invalid request id'); return; }
169
+ if (type === 'response-ack') { active.get(id)?.acknowledge?.(message.batch); return; }
170
+ if (type === 'cancel') { active.get(id)?.end(); return; }
171
+ if (type === 'unsubscribe') { const reply = active.get(id); if (reply?.subscription) reply.end(); return; }
172
+ if (!['request', 'subscribe'].includes(type) || active.has(id)) { ws.close(1008, 'Invalid request'); return; }
173
+ const subscription = type === 'subscribe';
174
+ const path = message.path;
175
+ const isStream = typeof path === 'string' && /^\/api\/(?:usage-events|thread-events|turn-events|shared-recovery\/events|threads\/[^/?]+\/(?:events|dots-activity-events))(?:\?|$)/.test(path);
176
+ // Native recovery, usage, catalog, current chat, and the main Dot's sidebar
177
+ // share one station connection (including when viewing a delegated task).
178
+ if (active.size >= 32 || (subscription && [...active.values()].filter(r => r.subscription).length >= 5)) {
179
+ send({ type: 'response', id, status: 429, body: { error: '同时进行的请求过多' } }); return;
180
+ }
181
+ if (typeof path !== 'string' || !path.startsWith('/api/') || path.includes('#') ||
182
+ path.startsWith('/api/attachments/') || path === '/api/socket' || path === '/api/uploads' ||
183
+ subscription !== isStream || !['GET', 'POST', 'PUT', 'DELETE'].includes(message.method || 'GET') ||
184
+ (subscription && message.method && message.method !== 'GET') ||
185
+ (message.body !== undefined && (!message.body || typeof message.body !== 'object' || Array.isArray(message.body)))) {
186
+ send({ type: 'response', id, status: 400, body: { error: '无效的连接请求' } }); return;
187
+ }
188
+ const reply = new EventEmitter();
189
+ let waiting, batch = 0;
190
+ const sendPart = (pieces, pageEnd = false) => new Promise((resolve, reject) => {
191
+ const timer = setTimeout(() => reject(new Error('历史接收确认超时')), 20000);
192
+ waiting = { resolve, reject, timer, batch: ++batch };
193
+ send({ type: subscription ? 'event-part' : 'response-part', id, batch, pieces, ...(pageEnd ? { pageEnd: true } : {}) });
194
+ });
195
+ const sendTimeline = async (status, body, event) => {
196
+ if (event) batch = 0;
197
+ try {
198
+ for (const pieces of timelineSync.timelineBatches(body)) {
199
+ if (reply.writableEnded) return;
200
+ await sendPart(pieces);
201
+ }
202
+ if (!reply.writableEnded) {
203
+ send(event ? { type: 'event', id, event, streamed: true } : { type: 'response', id, status, streamed: true });
204
+ if (!event) reply.end();
205
+ }
206
+ } catch (error) {
207
+ if (!reply.writableEnded) {
208
+ send(event ? { type: 'event', id, event: 'bridge-error', data: { error: error.message } }
209
+ : { type: 'response', id, status: 500, body: { error: error.message } });
210
+ reply.end();
211
+ }
212
+ }
213
+ };
214
+ Object.assign(reply, {
215
+ subscription, headersSent: false, writableEnded: false, destroyed: false,
216
+ async historyPage(page) {
217
+ const parts = timelineSync.timelineBatches(page);
218
+ let part = parts.next();
219
+ while (!part.done) {
220
+ if (this.writableEnded) throw new Error('历史读取已取消');
221
+ const next = parts.next();
222
+ await sendPart(part.value, next.done);
223
+ part = next;
224
+ }
225
+ },
226
+ json(status, body) {
227
+ if (this.writableEnded) return;
228
+ if (status < 400 && body?.schemaVersion === 1 && Array.isArray(body.turns)) {
229
+ void sendTimeline(status, body); return;
230
+ }
231
+ send({ type: 'response', id, status, body }); this.end();
232
+ },
233
+ acknowledge(sequence) {
234
+ if (!waiting || sequence !== waiting.batch) return;
235
+ const completed = waiting; waiting = null; clearTimeout(completed.timer);
236
+ this.emit('progress'); completed.resolve();
237
+ },
238
+ startEvents() {
239
+ if (this.writableEnded) return;
240
+ this.headersSent = true; send({ type: 'subscribed', id });
241
+ },
242
+ event(event, data) {
243
+ if (this.writableEnded) return;
244
+ if (event === 'update' && data?.schemaVersion === 1) return sendTimeline(200, data, event);
245
+ send({ type: 'event', id, event, data });
246
+ },
247
+ end() {
248
+ if (this.writableEnded) return;
249
+ this.writableEnded = this.destroyed = true; active.delete(id);
250
+ if (waiting) { clearTimeout(waiting.timer); waiting.reject(new Error('历史读取已取消')); waiting = null; }
251
+ if (subscription) send({ type: 'end', id });
252
+ this.emit('close');
253
+ },
254
+ });
255
+ active.set(id, reply);
256
+ try { await dispatch({ method: message.method || 'GET', url: path, body: message.body || {}, headers: {}, socketRequest: true }, reply); }
257
+ catch (error) { reply.json(500, { error: error.message }); }
258
+ });
259
+ });
260
+ return { close() {
261
+ stopWatching?.();
262
+ for (const ws of wss.clients) ws.terminate(); wss.close();
263
+ for (const ws of uploadWss.clients) ws.terminate(); uploadWss.close();
264
+ } };
265
+ }