@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.
- package/README.md +95 -89
- package/dist/bin/cleanup-accounts.mjs +63 -63
- package/dist/bin/codex-remote.mjs +374 -367
- package/dist/bin/manage-relay-admin.mjs +20 -20
- package/dist/bin/migrate-relay-db.mjs +109 -109
- package/dist/bin/publish-android-release.mjs +62 -58
- package/dist/bin/self-relay-admin.mjs +8 -8
- package/dist/bin/self-relay-demo.mjs +33 -33
- package/dist/bin/self-relay-server.mjs +66 -66
- package/dist/build-platform.json +1 -1
- package/dist/get-lan-networks.ps1 +40 -40
- package/dist/get-shared-service-url.ps1 +6 -6
- package/dist/shared/app-server-events.cjs +422 -412
- package/dist/shared/code-browser.cjs +159 -159
- package/dist/shared/file-changes.cjs +31 -31
- package/dist/shared/file-citations.cjs +117 -117
- package/dist/shared/file-mentions.cjs +92 -92
- package/dist/shared/message-delivery.cjs +54 -54
- package/dist/shared/p2p-data-channel.cjs +72 -72
- package/dist/shared/p2p-diagnostics.cjs +28 -28
- package/dist/shared/p2p-file-channel.cjs +74 -74
- package/dist/shared/plan-pricing.cjs +32 -32
- package/dist/shared/question-attention.cjs +40 -0
- package/dist/shared/server-requests.cjs +219 -219
- package/dist/shared/timeline-sync.cjs +173 -173
- package/dist/skills/code-relax/SKILL.md +22 -22
- package/dist/src/archived-threads.mjs +22 -0
- package/dist/src/background-process.mjs +18 -18
- package/dist/src/bounded-process-log.mjs +63 -63
- package/dist/src/celsius-client.mjs +107 -107
- package/dist/src/code-browser.mjs +100 -100
- package/dist/src/desktop-launcher.mjs +46 -46
- package/dist/src/dots-approval-timeline.mjs +99 -99
- package/dist/src/dots-avatar.mjs +42 -42
- package/dist/src/dots-chat-projection.mjs +50 -50
- package/dist/src/dots-chat-server.mjs +461 -461
- package/dist/src/dots-message-images.mjs +319 -319
- package/dist/src/dots-profile.mjs +77 -77
- package/dist/src/dots-room-activity.mjs +94 -94
- package/dist/src/dots-room-client.mjs +135 -135
- package/dist/src/dots-room-projection.mjs +94 -94
- package/dist/src/dots-schedules.mjs +66 -66
- package/dist/src/dots-summary-tasks.mjs +32 -32
- package/dist/src/dots-task-catalog.mjs +430 -430
- package/dist/src/dots-task-files.mjs +52 -52
- package/dist/src/execution-health.mjs +26 -26
- package/dist/src/file-transfer-range.mjs +22 -22
- package/dist/src/file-upload-session.mjs +130 -130
- package/dist/src/hosted-history-app-server.mjs +103 -103
- package/dist/src/hosted-history-cache.mjs +113 -113
- package/dist/src/lan-socket-server.mjs +265 -263
- package/dist/src/managed-app-server.mjs +244 -244
- package/dist/src/message-images.mjs +9 -9
- package/dist/src/message-upload-files.mjs +74 -74
- package/dist/src/onboarding.mjs +12 -12
- package/dist/src/plan-pricing.mjs +47 -47
- package/dist/src/platform/README.md +12 -12
- package/dist/src/platform/codex-protocol.mjs +46 -46
- package/dist/src/platform/codex-runtime.mjs +3 -3
- package/dist/src/platform/credential-store.mjs +3 -3
- package/dist/src/platform/desktop-host.mjs +3 -3
- package/dist/src/platform/desktop-project-registration.mjs +3 -3
- package/dist/src/platform/desktop-project-store.mjs +208 -149
- package/dist/src/platform/file-opener.mjs +9 -0
- package/dist/src/platform/linux/README.md +3 -3
- package/dist/src/platform/linux/codex-runtime.mjs +56 -0
- package/dist/src/platform/linux/credential-store.mjs +28 -0
- package/dist/src/platform/linux/desktop-host.mjs +83 -0
- package/dist/src/platform/linux/desktop-installation.mjs +36 -0
- package/dist/src/platform/linux/desktop-project-registration.mjs +11 -0
- package/dist/src/platform/linux/network-info.mjs +11 -0
- package/dist/src/platform/linux/process.mjs +42 -0
- package/dist/src/platform/linux/project-locations.mjs +17 -0
- package/dist/src/platform/linux/resident-startup.mjs +52 -0
- package/dist/src/platform/linux/retained-runtime.mjs +76 -0
- package/dist/src/platform/linux/service-host.mjs +18 -0
- package/dist/src/platform/linux/system.mjs +49 -0
- package/dist/src/platform/linux/user-environment.mjs +7 -0
- package/dist/src/platform/macos/README.md +3 -3
- package/dist/src/platform/macos/codex-runtime.mjs +125 -125
- package/dist/src/platform/macos/credential-store.mjs +10 -10
- package/dist/src/platform/macos/desktop-host.mjs +82 -82
- package/dist/src/platform/macos/desktop-project-registration.mjs +11 -10
- package/dist/src/platform/macos/network-info.mjs +8 -28
- package/dist/src/platform/macos/project-locations.mjs +8 -8
- package/dist/src/platform/macos/resident-startup.mjs +84 -84
- package/dist/src/platform/macos/retained-runtime.mjs +127 -127
- package/dist/src/platform/macos/service-host.mjs +18 -18
- package/dist/src/platform/macos/system.mjs +29 -29
- package/dist/src/platform/macos/user-environment.mjs +7 -7
- package/dist/src/platform/native-package.mjs +58 -46
- package/dist/src/platform/network-info.mjs +3 -3
- package/dist/src/platform/path-identity.mjs +5 -5
- package/dist/src/platform/posix/network-candidates.mjs +23 -0
- package/dist/src/platform/posix/runtime-paths.mjs +25 -25
- package/dist/src/platform/project-locations.mjs +3 -3
- package/dist/src/platform/runtime-paths.mjs +8 -8
- package/dist/src/platform/select.mjs +5 -5
- package/dist/src/platform/service-host.mjs +3 -3
- package/dist/src/platform/user-environment.mjs +3 -3
- package/dist/src/platform/windows/IsolatedProcess.cs +79 -79
- package/dist/src/platform/windows/activate-desktop.ps1 +48 -48
- package/dist/src/platform/windows/background-process.mjs +30 -30
- package/dist/src/platform/windows/codex-runtime.mjs +215 -215
- package/dist/src/platform/windows/credential-store.mjs +27 -27
- package/dist/src/platform/windows/credential-store.ps1 +49 -49
- package/dist/src/platform/windows/desktop-helper.mjs +179 -179
- package/dist/src/platform/windows/desktop-host.mjs +58 -58
- package/dist/src/platform/windows/desktop-info.ps1 +14 -14
- package/dist/src/platform/windows/desktop-project-registration.mjs +4 -4
- package/dist/src/platform/windows/desktop-runtime.ps1 +10 -10
- package/dist/src/platform/windows/desktop-shortcuts.ps1 +21 -21
- package/dist/src/platform/windows/dots-profile.mjs +49 -49
- package/dist/src/platform/windows/launch-worker.mjs +41 -41
- package/dist/src/platform/windows/network-info.mjs +34 -34
- package/dist/src/platform/windows/project-locations.mjs +16 -16
- package/dist/src/platform/windows/resident-start.js +20 -20
- package/dist/src/platform/windows/resident-start.ps1 +7 -7
- package/dist/src/platform/windows/resident-startup.ps1 +83 -83
- package/dist/src/platform/windows/resolve-state-root.ps1 +14 -14
- package/dist/src/platform/windows/runtime-paths.mjs +20 -20
- package/dist/src/platform/windows/rustdesk-video-probe.mjs +167 -167
- package/dist/src/platform/windows/service-host.mjs +31 -31
- package/dist/src/platform/windows/start-hidden-console.ps1 +49 -49
- package/dist/src/platform/windows/stop-desktop.ps1 +22 -22
- package/dist/src/platform/windows/user-environment.mjs +50 -50
- package/dist/src/platform/windows/user-environment.ps1 +41 -41
- package/dist/src/project-archive.mjs +30 -0
- package/dist/src/project-create.mjs +121 -119
- package/dist/src/project-management.mjs +59 -69
- package/dist/src/project-remove.mjs +55 -0
- package/dist/src/project-update.mjs +56 -0
- package/dist/src/runtime-discovery.mjs +47 -47
- package/dist/src/self-relay/account-cleanup.mjs +30 -30
- package/dist/src/self-relay/account-connections.mjs +52 -52
- package/dist/src/self-relay/admin-cloud.mjs +101 -101
- package/dist/src/self-relay/admin-page.mjs +80 -80
- package/dist/src/self-relay/admin-server.mjs +74 -74
- package/dist/src/self-relay/admin-state.mjs +127 -127
- package/dist/src/self-relay/admin-style.mjs +14 -14
- package/dist/src/self-relay/android-releases.mjs +61 -61
- package/dist/src/self-relay/client.mjs +61 -61
- package/dist/src/self-relay/connector.mjs +439 -438
- package/dist/src/self-relay/debug-allowlist.mjs +33 -33
- package/dist/src/self-relay/demo.mjs +37 -37
- package/dist/src/self-relay/device-info.mjs +27 -0
- package/dist/src/self-relay/device-store.mjs +92 -84
- package/dist/src/self-relay/diagnostics.mjs +54 -54
- package/dist/src/self-relay/email-accounts.mjs +183 -183
- package/dist/src/self-relay/file-wire.mjs +13 -13
- package/dist/src/self-relay/lan-authorizations.mjs +71 -42
- package/dist/src/self-relay/lifecycle.mjs +264 -250
- package/dist/src/self-relay/long-pairing.mjs +40 -40
- package/dist/src/self-relay/mysql-state.mjs +118 -105
- package/dist/src/self-relay/p2p-probe.mjs +159 -159
- package/dist/src/self-relay/privacy-page.mjs +26 -26
- package/dist/src/self-relay/public-releases.mjs +34 -0
- package/dist/src/self-relay/rtc-file-bridge.mjs +41 -41
- package/dist/src/self-relay/server.mjs +1006 -932
- package/dist/src/self-relay/usage-daily.mjs +55 -55
- package/dist/src/self-relay/usage-meter.mjs +141 -141
- package/dist/src/self-relay/windows-route-helper.mjs +75 -75
- package/dist/src/self-relay/wire.mjs +36 -36
- package/dist/src/server.mjs +1861 -1778
- package/dist/src/service-control.mjs +82 -82
- package/dist/src/service-doctor.mjs +110 -110
- package/dist/src/service-health.mjs +33 -33
- package/dist/src/service-install.mjs +91 -91
- package/dist/src/service-lifecycle.mjs +138 -138
- package/dist/src/service-restart.mjs +81 -81
- package/dist/src/shared-app-server.mjs +615 -611
- package/dist/src/shared-catalog.mjs +132 -132
- package/dist/src/shared-recovery.mjs +146 -146
- package/dist/src/shared-thread-stream.mjs +164 -164
- package/dist/src/skill-install.mjs +51 -51
- package/dist/src/thread-title-generation.mjs +150 -150
- package/dist/src/turn-model-history.mjs +47 -47
- package/dist/src/usage-reset.mjs +17 -17
- package/dist/src/workstation-downloads.mjs +120 -120
- package/dist/tools/rtc-route-helper.ps1 +99 -99
- package/dist/tools/start-rtc-route-helper.ps1 +15 -15
- package/dist/web/vendor/markdown-it.LICENSE.txt +22 -22
- package/dist/web/vendor/markdown-it.umd.min.js +13 -13
- package/package.json +7 -6
- 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 (
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
if (
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
const
|
|
121
|
-
|
|
122
|
-
if (
|
|
123
|
-
ws.
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
const
|
|
127
|
-
|
|
128
|
-
alive
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
ws.on('
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
stopped
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
active.
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
ws.on('
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
if (!
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
const
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
if (
|
|
169
|
-
if (type === '
|
|
170
|
-
if (
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
const
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
(
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
const
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
if (
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
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
|
+
}
|