ai_co_discuss 0.4.21 → 0.4.23
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/package.json +1 -1
- package/runner/discussion_launch.mjs +11 -0
- package/runner/relay_channel.mjs +327 -326
- package/web/app.js +13 -10
- package/web/modern.css +1 -1
- package/web/modern.js +52 -52
package/runner/relay_channel.mjs
CHANGED
|
@@ -1,326 +1,327 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Keep one hibernating WebSocket per paired website so the administrator's devices reach this computer at once:
|
|
3
|
-
* each encrypted request is answered here, room reads and writes go to the local website with this computer's bridge
|
|
4
|
-
* credential, and the local website's change notices are passed on. The website only ever forwards ciphertext.
|
|
5
|
-
*/
|
|
6
|
-
import { createHash, randomBytes } from 'node:crypto';
|
|
7
|
-
import { existsSync, readFileSync } from 'node:fs';
|
|
8
|
-
import { join } from 'node:path';
|
|
9
|
-
import { setTimeout as sleep } from 'node:timers/promises';
|
|
10
|
-
import { gzipSync } from 'node:zlib';
|
|
11
|
-
|
|
12
|
-
import { atomic_json } from './files.mjs';
|
|
13
|
-
import { remote_room_files, remote_room_media, remote_room_page } from './discussion_launch.mjs';
|
|
14
|
-
import { acquire_lock } from './discussion_runner.mjs';
|
|
15
|
-
import { local_settings } from './discussion_setup.mjs';
|
|
16
|
-
import { machine_links, relay_cipher, save_machine_links, relayed_command, ROOM_ACTIONS, run_launch_command, sync_remote_launches, unseal } from './remote_launch.mjs';
|
|
17
|
-
import { claim_relayed_command } from './remote_policy.mjs';
|
|
18
|
-
import { audit, DEVICE_ACTIONS, device_command, open_signed_request } from './device_auth.mjs';
|
|
19
|
-
|
|
20
|
-
const RELAY_PROTOCOL = 'codiscuss-relay';
|
|
21
|
-
const BRIDGE_TOKEN_BYTES = 32;
|
|
22
|
-
const RETRY_MIN_MS = 2000;
|
|
23
|
-
const RETRY_MAX_MS = 60000;
|
|
24
|
-
// A ping still unanswered at the next one means the connection is stalled, so it is replaced within two of these.
|
|
25
|
-
const PING_MS = 15000;
|
|
26
|
-
// The site gives up on a request after 9 seconds, so the local website must answer before then.
|
|
27
|
-
const LOCAL_TIMEOUT_MS = 8000;
|
|
28
|
-
const EVENT_RETRY_MS = 3000;
|
|
29
|
-
// Diagnostics: a request answered slower than this, or not delivered, is written to the service log (action and route only).
|
|
30
|
-
const SLOW_REQUEST_MS = 3000;
|
|
31
|
-
// A WebSocket frame on the website is at most 1 MiB; leave room for the envelope around the ciphertext.
|
|
32
|
-
const RESPONSE_MAX_BYTES = 700 * 1024;
|
|
33
|
-
const ROOM_API_PATH = /^\/api\/(rooms|folders|revisions)(\/[A-Za-z0-9_.~-]+)*(\?[A-Za-z0-9_.~%=&,:+-]*)?$/;
|
|
34
|
-
// Attachment uploads arrive in parts and are sent to the local website whole, as one browser upload would be.
|
|
35
|
-
const UPLOAD_PATH = /^\/api\/rooms\/[A-Za-z0-9_-]+\/attachments(\/[A-Za-z0-9_-]+\/import)?(\?[A-Za-z0-9_.~%=&,:+-]*)?$/;
|
|
36
|
-
const UPLOAD_MAX_BYTES = 20 * 1024 * 1024;
|
|
37
|
-
const UPLOAD_TTL_MS = 10 * 60 * 1000;
|
|
38
|
-
const uploads = new Map();
|
|
39
|
-
|
|
40
|
-
/** The bridge token for one website, created on first use; the local website keeps only its hash, next to the connection. */
|
|
41
|
-
export function bridge_token(home, site) {
|
|
42
|
-
const links = machine_links(home);
|
|
43
|
-
const link = links.sites[site];
|
|
44
|
-
if (!link) return '';
|
|
45
|
-
if (!link.bridge_token) {
|
|
46
|
-
link.bridge_token = randomBytes(BRIDGE_TOKEN_BYTES).toString('hex');
|
|
47
|
-
save_machine_links(home, links);
|
|
48
|
-
}
|
|
49
|
-
const path = join(home, 'site-connections.json');
|
|
50
|
-
const hashed = createHash('sha256').update(link.bridge_token).digest('hex');
|
|
51
|
-
const settings = existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : { sites: {} };
|
|
52
|
-
// The entry also tells the local website that this site reaches it only through the relay, so a browser connection
|
|
53
|
-
// credential kept from before no longer works. A website disconnected meanwhile has lost its pairing: no bridge then.
|
|
54
|
-
if (settings.sites[site]?.bridge_hash !== hashed) {
|
|
55
|
-
const release = acquire_lock(join(home, 'connection-lock'));
|
|
56
|
-
try {
|
|
57
|
-
const latest = existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : { sites: {} };
|
|
58
|
-
if (machine_links(home).sites[site]) atomic_json(path, { ...latest, sites: { ...latest.sites, [site]: { ...latest.sites[site], bridge_hash: hashed } } });
|
|
59
|
-
} finally { release(); }
|
|
60
|
-
}
|
|
61
|
-
return link.bridge_token;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
/** Encrypt a compressed answer bound to its request, so the website cannot swap one answer into another request. */
|
|
65
|
-
async function seal_compressed(key, value, label) {
|
|
66
|
-
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
67
|
-
const data = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: new TextEncoder().encode(label) }, key,
|
|
68
|
-
gzipSync(Buffer.from(JSON.stringify(value))));
|
|
69
|
-
return { iv: Buffer.from(iv).toString('base64'), data: Buffer.from(data).toString('base64'), encoding: 'gzip' };
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
/**
|
|
73
|
-
* Read or write one room route on the local website as this computer's bridge. Only room, folder and revision routes
|
|
74
|
-
* of the local website itself are reachable; the device cannot name another address. Binary content comes back as base64.
|
|
75
|
-
*/
|
|
76
|
-
export async function room_api(home, site, payload, { fetcher = fetch, device } = {}) {
|
|
77
|
-
const { method = 'GET', path, body, token, offset = 0, etag } = payload || {};
|
|
78
|
-
if (!['GET', 'POST'].includes(method) || typeof path !== 'string' || !ROOM_API_PATH.test(path) || path.includes('..')
|
|
79
|
-
|| !Number.isSafeInteger(offset) || offset < 0) {
|
|
80
|
-
return { status: 400, body: { error: '中转请求地址无效' } };
|
|
81
|
-
}
|
|
82
|
-
const headers = bridge_headers(home, site);
|
|
83
|
-
if (typeof token === 'string' && token) headers['X-Discussion-Token'] = token;
|
|
84
|
-
if (body !== undefined) headers['Content-Type'] = 'application/json';
|
|
85
|
-
// A read the device already holds is asked conditionally; unchanged, the answer is a bare 304 with no body.
|
|
86
|
-
if (method === 'GET' && typeof etag === 'string' && /^"[0-9a-f]{1,64}"$/.test(etag)) headers['If-None-Match'] = etag;
|
|
87
|
-
const response = await fetcher(`${local_origin(home)}${path}`, { method, headers, redirect: 'error',
|
|
88
|
-
body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(LOCAL_TIMEOUT_MS) });
|
|
89
|
-
const tag = response.headers.get('ETag');
|
|
90
|
-
if (response.status === 304) return { status: 304, etag: tag || etag };
|
|
91
|
-
const type = response.headers.get('Content-Type') || '';
|
|
92
|
-
if (type.startsWith('application/json')) return { status: response.status, body: await response.json(), ...(tag ? { etag: tag } : {}) };
|
|
93
|
-
// A file larger than one frame comes back in parts; the device asks again from where the previous part ended.
|
|
94
|
-
const bytes = Buffer.from(await response.arrayBuffer());
|
|
95
|
-
return { status: response.status, content_type: type, offset, total: bytes.length,
|
|
96
|
-
body_base64: bytes.subarray(offset, offset + RESPONSE_MAX_BYTES).toString('base64') };
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
/** The local website this computer runs. */
|
|
100
|
-
function local_origin(home) {
|
|
101
|
-
return `http://127.0.0.1:${local_settings(home).port || 8765}`;
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
/** The headers that make a request to the local website act as this computer's bridge for one paired website. */
|
|
105
|
-
function bridge_headers(home, site) {
|
|
106
|
-
return { 'X-CoDiscuss-Bridge': bridge_token(home, site), 'X-CoDiscuss-Bridge-Site': site };
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
/**
|
|
110
|
-
* Collect one part of an attachment upload; once every part has arrived, send the whole file to the local website as
|
|
111
|
-
* the bridge. Parts may be resent; an unfinished upload is dropped after ten minutes.
|
|
112
|
-
*/
|
|
113
|
-
export async function room_upload(home, site, payload, { fetcher = fetch, now = Date.now() } = {}) {
|
|
114
|
-
const { id, path, index, total, size, content_type = 'application/octet-stream', data } = payload || {};
|
|
115
|
-
if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{16,80}$/.test(id) || typeof path !== 'string' || !UPLOAD_PATH.test(path)
|
|
116
|
-
|| !Number.isSafeInteger(total) || total < 1 || !Number.isSafeInteger(index) || index < 0 || index >= total
|
|
117
|
-
|| !Number.isSafeInteger(size) || size < 0 || size > UPLOAD_MAX_BYTES || typeof data !== 'string' || typeof content_type !== 'string') {
|
|
118
|
-
return { status: 400, body: { error: '附件上传请求无效' } };
|
|
119
|
-
}
|
|
120
|
-
for (const [key, item] of uploads) if (now - item.at > UPLOAD_TTL_MS) uploads.delete(key);
|
|
121
|
-
const upload = uploads.get(id) ?? { path, total, size, parts: [], at: now };
|
|
122
|
-
if (upload.path !== path || upload.total !== total || upload.size !== size) return { status: 400, body: { error: '附件上传请求无效' } };
|
|
123
|
-
upload.parts[index] = Buffer.from(data, 'base64');
|
|
124
|
-
upload.at = now;
|
|
125
|
-
uploads.set(id, upload);
|
|
126
|
-
const received = upload.parts.filter(Boolean).length;
|
|
127
|
-
if (received < total) return { status: 200, body: { received } };
|
|
128
|
-
uploads.delete(id);
|
|
129
|
-
const bytes = Buffer.concat(upload.parts);
|
|
130
|
-
if (bytes.length !== size) return { status: 400, body: { error: '附件不完整,请重新上传' } };
|
|
131
|
-
const response = await fetcher(`${local_origin(home)}${path}`, { method: 'POST', redirect: 'error', body: bytes,
|
|
132
|
-
headers: { ...bridge_headers(home, site), 'Content-Type': content_type }, signal: AbortSignal.timeout(LOCAL_TIMEOUT_MS) });
|
|
133
|
-
return { status: response.status, body: await response.json() };
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
/** Room credentials and website of the rooms this computer serves on its own local website, by room. */
|
|
137
|
-
function local_rooms(home) {
|
|
138
|
-
const path = join(home, 'rooms.json'), port = local_settings(home).port || 8765, rooms = new Map();
|
|
139
|
-
const configs = existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')).configs ?? [] : [];
|
|
140
|
-
for (const config_path of configs) {
|
|
141
|
-
try {
|
|
142
|
-
const config = JSON.parse(readFileSync(config_path, 'utf8'));
|
|
143
|
-
const url = new URL(config.site);
|
|
144
|
-
if (['127.0.0.1', 'localhost'].includes(url.hostname) && Number(url.port) === port && typeof config.token === 'string') {
|
|
145
|
-
rooms.set(config.room, { site: url.origin, token: config.token });
|
|
146
|
-
}
|
|
147
|
-
} catch { /* A broken configuration grants nothing. */ }
|
|
148
|
-
}
|
|
149
|
-
return rooms;
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
/**
|
|
153
|
-
* A local operation for the rooms on this computer's own website, asked for by an administrator's device: room
|
|
154
|
-
* operations run against the local website with the room credentials this computer already keeps; others as before.
|
|
155
|
-
*/
|
|
156
|
-
export function computer_command(home, site, action, payload) {
|
|
157
|
-
if (!ROOM_ACTIONS.has(action)) return relayed_command(site, action, payload);
|
|
158
|
-
const rooms = local_rooms(home), input = { ...payload };
|
|
159
|
-
const room = rooms.get(input.room_id);
|
|
160
|
-
if (input.room_id && !input.token) input.token = room?.token ?? '';
|
|
161
|
-
if (input.source_room_id && !input.source_token) input.source_token = rooms.get(input.source_room_id)?.token ?? '';
|
|
162
|
-
return relayed_command(room?.site ?? local_origin(home), action, input);
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
/**
|
|
166
|
-
* Run one local operation; browsing project files
|
|
167
|
-
* are asked for on every folder opened or
|
|
168
|
-
*/
|
|
169
|
-
async function run_command(home, command, run) {
|
|
170
|
-
if (run !== run_launch_command) return run(command);
|
|
171
|
-
if (command.command === 'room-files') return { status: 200, body: await remote_room_files(home, command.input) };
|
|
172
|
-
if (command.command === 'room-page') return { status: 200, body: await remote_room_page(home, command.input) };
|
|
173
|
-
if (command.command === 'room-media') return { status: 200, body: await remote_room_media(home, command.input) };
|
|
174
|
-
return
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
const
|
|
181
|
-
const
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
: action === '
|
|
193
|
-
: action === 'room-
|
|
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
|
-
const
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
finished
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
//
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
if (
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
if (
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
const
|
|
288
|
-
const
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
*
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
const
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Keep one hibernating WebSocket per paired website so the administrator's devices reach this computer at once:
|
|
3
|
+
* each encrypted request is answered here, room reads and writes go to the local website with this computer's bridge
|
|
4
|
+
* credential, and the local website's change notices are passed on. The website only ever forwards ciphertext.
|
|
5
|
+
*/
|
|
6
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
7
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
8
|
+
import { join } from 'node:path';
|
|
9
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
10
|
+
import { gzipSync } from 'node:zlib';
|
|
11
|
+
|
|
12
|
+
import { atomic_json } from './files.mjs';
|
|
13
|
+
import { remote_execution_details, remote_room_files, remote_room_media, remote_room_page } from './discussion_launch.mjs';
|
|
14
|
+
import { acquire_lock } from './discussion_runner.mjs';
|
|
15
|
+
import { local_settings } from './discussion_setup.mjs';
|
|
16
|
+
import { machine_links, relay_cipher, save_machine_links, relayed_command, ROOM_ACTIONS, run_launch_command, sync_remote_launches, unseal } from './remote_launch.mjs';
|
|
17
|
+
import { claim_relayed_command } from './remote_policy.mjs';
|
|
18
|
+
import { audit, DEVICE_ACTIONS, device_command, open_signed_request } from './device_auth.mjs';
|
|
19
|
+
|
|
20
|
+
const RELAY_PROTOCOL = 'codiscuss-relay';
|
|
21
|
+
const BRIDGE_TOKEN_BYTES = 32;
|
|
22
|
+
const RETRY_MIN_MS = 2000;
|
|
23
|
+
const RETRY_MAX_MS = 60000;
|
|
24
|
+
// A ping still unanswered at the next one means the connection is stalled, so it is replaced within two of these.
|
|
25
|
+
const PING_MS = 15000;
|
|
26
|
+
// The site gives up on a request after 9 seconds, so the local website must answer before then.
|
|
27
|
+
const LOCAL_TIMEOUT_MS = 8000;
|
|
28
|
+
const EVENT_RETRY_MS = 3000;
|
|
29
|
+
// Diagnostics: a request answered slower than this, or not delivered, is written to the service log (action and route only).
|
|
30
|
+
const SLOW_REQUEST_MS = 3000;
|
|
31
|
+
// A WebSocket frame on the website is at most 1 MiB; leave room for the envelope around the ciphertext.
|
|
32
|
+
const RESPONSE_MAX_BYTES = 700 * 1024;
|
|
33
|
+
const ROOM_API_PATH = /^\/api\/(rooms|folders|revisions)(\/[A-Za-z0-9_.~-]+)*(\?[A-Za-z0-9_.~%=&,:+-]*)?$/;
|
|
34
|
+
// Attachment uploads arrive in parts and are sent to the local website whole, as one browser upload would be.
|
|
35
|
+
const UPLOAD_PATH = /^\/api\/rooms\/[A-Za-z0-9_-]+\/attachments(\/[A-Za-z0-9_-]+\/import)?(\?[A-Za-z0-9_.~%=&,:+-]*)?$/;
|
|
36
|
+
const UPLOAD_MAX_BYTES = 20 * 1024 * 1024;
|
|
37
|
+
const UPLOAD_TTL_MS = 10 * 60 * 1000;
|
|
38
|
+
const uploads = new Map();
|
|
39
|
+
|
|
40
|
+
/** The bridge token for one website, created on first use; the local website keeps only its hash, next to the connection. */
|
|
41
|
+
export function bridge_token(home, site) {
|
|
42
|
+
const links = machine_links(home);
|
|
43
|
+
const link = links.sites[site];
|
|
44
|
+
if (!link) return '';
|
|
45
|
+
if (!link.bridge_token) {
|
|
46
|
+
link.bridge_token = randomBytes(BRIDGE_TOKEN_BYTES).toString('hex');
|
|
47
|
+
save_machine_links(home, links);
|
|
48
|
+
}
|
|
49
|
+
const path = join(home, 'site-connections.json');
|
|
50
|
+
const hashed = createHash('sha256').update(link.bridge_token).digest('hex');
|
|
51
|
+
const settings = existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : { sites: {} };
|
|
52
|
+
// The entry also tells the local website that this site reaches it only through the relay, so a browser connection
|
|
53
|
+
// credential kept from before no longer works. A website disconnected meanwhile has lost its pairing: no bridge then.
|
|
54
|
+
if (settings.sites[site]?.bridge_hash !== hashed) {
|
|
55
|
+
const release = acquire_lock(join(home, 'connection-lock'));
|
|
56
|
+
try {
|
|
57
|
+
const latest = existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : { sites: {} };
|
|
58
|
+
if (machine_links(home).sites[site]) atomic_json(path, { ...latest, sites: { ...latest.sites, [site]: { ...latest.sites[site], bridge_hash: hashed } } });
|
|
59
|
+
} finally { release(); }
|
|
60
|
+
}
|
|
61
|
+
return link.bridge_token;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Encrypt a compressed answer bound to its request, so the website cannot swap one answer into another request. */
|
|
65
|
+
async function seal_compressed(key, value, label) {
|
|
66
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
67
|
+
const data = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: new TextEncoder().encode(label) }, key,
|
|
68
|
+
gzipSync(Buffer.from(JSON.stringify(value))));
|
|
69
|
+
return { iv: Buffer.from(iv).toString('base64'), data: Buffer.from(data).toString('base64'), encoding: 'gzip' };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Read or write one room route on the local website as this computer's bridge. Only room, folder and revision routes
|
|
74
|
+
* of the local website itself are reachable; the device cannot name another address. Binary content comes back as base64.
|
|
75
|
+
*/
|
|
76
|
+
export async function room_api(home, site, payload, { fetcher = fetch, device } = {}) {
|
|
77
|
+
const { method = 'GET', path, body, token, offset = 0, etag } = payload || {};
|
|
78
|
+
if (!['GET', 'POST'].includes(method) || typeof path !== 'string' || !ROOM_API_PATH.test(path) || path.includes('..')
|
|
79
|
+
|| !Number.isSafeInteger(offset) || offset < 0) {
|
|
80
|
+
return { status: 400, body: { error: '中转请求地址无效' } };
|
|
81
|
+
}
|
|
82
|
+
const headers = bridge_headers(home, site);
|
|
83
|
+
if (typeof token === 'string' && token) headers['X-Discussion-Token'] = token;
|
|
84
|
+
if (body !== undefined) headers['Content-Type'] = 'application/json';
|
|
85
|
+
// A read the device already holds is asked conditionally; unchanged, the answer is a bare 304 with no body.
|
|
86
|
+
if (method === 'GET' && typeof etag === 'string' && /^"[0-9a-f]{1,64}"$/.test(etag)) headers['If-None-Match'] = etag;
|
|
87
|
+
const response = await fetcher(`${local_origin(home)}${path}`, { method, headers, redirect: 'error',
|
|
88
|
+
body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(LOCAL_TIMEOUT_MS) });
|
|
89
|
+
const tag = response.headers.get('ETag');
|
|
90
|
+
if (response.status === 304) return { status: 304, etag: tag || etag };
|
|
91
|
+
const type = response.headers.get('Content-Type') || '';
|
|
92
|
+
if (type.startsWith('application/json')) return { status: response.status, body: await response.json(), ...(tag ? { etag: tag } : {}) };
|
|
93
|
+
// A file larger than one frame comes back in parts; the device asks again from where the previous part ended.
|
|
94
|
+
const bytes = Buffer.from(await response.arrayBuffer());
|
|
95
|
+
return { status: response.status, content_type: type, offset, total: bytes.length,
|
|
96
|
+
body_base64: bytes.subarray(offset, offset + RESPONSE_MAX_BYTES).toString('base64') };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The local website this computer runs. */
|
|
100
|
+
function local_origin(home) {
|
|
101
|
+
return `http://127.0.0.1:${local_settings(home).port || 8765}`;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** The headers that make a request to the local website act as this computer's bridge for one paired website. */
|
|
105
|
+
function bridge_headers(home, site) {
|
|
106
|
+
return { 'X-CoDiscuss-Bridge': bridge_token(home, site), 'X-CoDiscuss-Bridge-Site': site };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Collect one part of an attachment upload; once every part has arrived, send the whole file to the local website as
|
|
111
|
+
* the bridge. Parts may be resent; an unfinished upload is dropped after ten minutes.
|
|
112
|
+
*/
|
|
113
|
+
export async function room_upload(home, site, payload, { fetcher = fetch, now = Date.now() } = {}) {
|
|
114
|
+
const { id, path, index, total, size, content_type = 'application/octet-stream', data } = payload || {};
|
|
115
|
+
if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{16,80}$/.test(id) || typeof path !== 'string' || !UPLOAD_PATH.test(path)
|
|
116
|
+
|| !Number.isSafeInteger(total) || total < 1 || !Number.isSafeInteger(index) || index < 0 || index >= total
|
|
117
|
+
|| !Number.isSafeInteger(size) || size < 0 || size > UPLOAD_MAX_BYTES || typeof data !== 'string' || typeof content_type !== 'string') {
|
|
118
|
+
return { status: 400, body: { error: '附件上传请求无效' } };
|
|
119
|
+
}
|
|
120
|
+
for (const [key, item] of uploads) if (now - item.at > UPLOAD_TTL_MS) uploads.delete(key);
|
|
121
|
+
const upload = uploads.get(id) ?? { path, total, size, parts: [], at: now };
|
|
122
|
+
if (upload.path !== path || upload.total !== total || upload.size !== size) return { status: 400, body: { error: '附件上传请求无效' } };
|
|
123
|
+
upload.parts[index] = Buffer.from(data, 'base64');
|
|
124
|
+
upload.at = now;
|
|
125
|
+
uploads.set(id, upload);
|
|
126
|
+
const received = upload.parts.filter(Boolean).length;
|
|
127
|
+
if (received < total) return { status: 200, body: { received } };
|
|
128
|
+
uploads.delete(id);
|
|
129
|
+
const bytes = Buffer.concat(upload.parts);
|
|
130
|
+
if (bytes.length !== size) return { status: 400, body: { error: '附件不完整,请重新上传' } };
|
|
131
|
+
const response = await fetcher(`${local_origin(home)}${path}`, { method: 'POST', redirect: 'error', body: bytes,
|
|
132
|
+
headers: { ...bridge_headers(home, site), 'Content-Type': content_type }, signal: AbortSignal.timeout(LOCAL_TIMEOUT_MS) });
|
|
133
|
+
return { status: response.status, body: await response.json() };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Room credentials and website of the rooms this computer serves on its own local website, by room. */
|
|
137
|
+
function local_rooms(home) {
|
|
138
|
+
const path = join(home, 'rooms.json'), port = local_settings(home).port || 8765, rooms = new Map();
|
|
139
|
+
const configs = existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')).configs ?? [] : [];
|
|
140
|
+
for (const config_path of configs) {
|
|
141
|
+
try {
|
|
142
|
+
const config = JSON.parse(readFileSync(config_path, 'utf8'));
|
|
143
|
+
const url = new URL(config.site);
|
|
144
|
+
if (['127.0.0.1', 'localhost'].includes(url.hostname) && Number(url.port) === port && typeof config.token === 'string') {
|
|
145
|
+
rooms.set(config.room, { site: url.origin, token: config.token });
|
|
146
|
+
}
|
|
147
|
+
} catch { /* A broken configuration grants nothing. */ }
|
|
148
|
+
}
|
|
149
|
+
return rooms;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* A local operation for the rooms on this computer's own website, asked for by an administrator's device: room
|
|
154
|
+
* operations run against the local website with the room credentials this computer already keeps; others as before.
|
|
155
|
+
*/
|
|
156
|
+
export function computer_command(home, site, action, payload) {
|
|
157
|
+
if (!ROOM_ACTIONS.has(action)) return relayed_command(site, action, payload);
|
|
158
|
+
const rooms = local_rooms(home), input = { ...payload };
|
|
159
|
+
const room = rooms.get(input.room_id);
|
|
160
|
+
if (input.room_id && !input.token) input.token = room?.token ?? '';
|
|
161
|
+
if (input.source_room_id && !input.source_token) input.source_token = rooms.get(input.source_room_id)?.token ?? '';
|
|
162
|
+
return relayed_command(room?.site ?? local_origin(home), action, input);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Run one local operation; browsing project files, reading an HTML page and a turn's steps are answered in this
|
|
167
|
+
* process, since they are asked for on every folder opened, page part or private-chat poll.
|
|
168
|
+
*/
|
|
169
|
+
async function run_command(home, command, run) {
|
|
170
|
+
if (run !== run_launch_command) return run(command);
|
|
171
|
+
if (command.command === 'room-files') return { status: 200, body: await remote_room_files(home, command.input) };
|
|
172
|
+
if (command.command === 'room-page') return { status: 200, body: await remote_room_page(home, command.input) };
|
|
173
|
+
if (command.command === 'room-media') return { status: 200, body: await remote_room_media(home, command.input) };
|
|
174
|
+
if (command.command === 'execution-details') return { status: 200, body: await remote_execution_details(home, command.input) };
|
|
175
|
+
return run(command);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Answer one relayed request: room routes and uploads go to the local website, everything else to the local entrypoint as before. */
|
|
179
|
+
export async function answer_request(home, site, link, frame, { run = run_launch_command, fetcher, report } = {}) {
|
|
180
|
+
const { id, envelope } = frame;
|
|
181
|
+
const key = await relay_cipher(link.private_key, envelope.key);
|
|
182
|
+
const sealed = await unseal(key, envelope, id);
|
|
183
|
+
let response, request = {};
|
|
184
|
+
try {
|
|
185
|
+
// Only a paired device's signed request runs; an unpaired browser may only prove a pairing code.
|
|
186
|
+
const opened = await open_signed_request(home, id, sealed, link.id);
|
|
187
|
+
request = opened.request;
|
|
188
|
+
const { action, payload, target } = request;
|
|
189
|
+
claim_relayed_command(home, id, request.sent_at);
|
|
190
|
+
const device = opened.device_id;
|
|
191
|
+
response = DEVICE_ACTIONS.has(action) ? await device_command(home, { site, machine_id: link.id, device_id: device, on_change: () => sync_remote_launches(home) }, action, payload)
|
|
192
|
+
: action === 'computer-site' ? { status: 200, body: { site: local_origin(home) } }
|
|
193
|
+
: action === 'room-api' ? await room_api(home, site, payload, { fetcher, device })
|
|
194
|
+
: action === 'room-upload' ? await room_upload(home, site, payload, { fetcher })
|
|
195
|
+
: await run_command(home, { ...(target === 'computer' ? computer_command(home, site, action, payload) : relayed_command(site, action, payload)), device }, run);
|
|
196
|
+
} catch (error) { response = { status: 400, body: { error: error.message, ...(error.need ? { need: error.need } : {}) } }; }
|
|
197
|
+
// Remote writes go to this computer's audit log: kind, route, device and outcome, never content. Reads are not logged.
|
|
198
|
+
if (request.action && !(request.action === 'room-api' && (request.payload?.method || 'GET') === 'GET') && !DEVICE_ACTIONS.has(request.action) && request.action !== 'computer-site') {
|
|
199
|
+
audit(home, { event: 'command', action: request.action, route: typeof request.payload?.path === 'string' ? request.payload.path.split('?')[0] : '',
|
|
200
|
+
device: sealed.device_id || null, status: response.status });
|
|
201
|
+
}
|
|
202
|
+
// Only what kind of request it was and how it ended: never its content or query.
|
|
203
|
+
report?.({ action: request.action, route: typeof request.payload?.path === 'string' ? request.payload.path.split('?')[0] : '', status: response.status });
|
|
204
|
+
return { type: 'response', id, envelope: await seal_compressed(key, response, `${id}:response`) };
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Pass the local website's change notices to the devices while the relay is connected. */
|
|
208
|
+
async function forward_changes(home, socket, signal) {
|
|
209
|
+
while (!signal.aborted && socket.readyState === WebSocket.OPEN) {
|
|
210
|
+
try {
|
|
211
|
+
const response = await fetch(`http://127.0.0.1:${local_settings(home).port || 8765}/api/updates`, { signal, headers: { accept: 'text/event-stream' } });
|
|
212
|
+
if (!response.ok || !response.body) throw new Error(`HTTP ${response.status}`);
|
|
213
|
+
const decoder = new TextDecoder();
|
|
214
|
+
let buffer = '';
|
|
215
|
+
for await (const chunk of response.body) {
|
|
216
|
+
buffer += decoder.decode(chunk, { stream: true }).replaceAll('\r\n', '\n');
|
|
217
|
+
for (let end = buffer.indexOf('\n\n'); end >= 0; end = buffer.indexOf('\n\n')) {
|
|
218
|
+
const frame = buffer.slice(0, end);
|
|
219
|
+
buffer = buffer.slice(end + 2);
|
|
220
|
+
if (!/^event: change$/m.test(frame) || socket.readyState !== WebSocket.OPEN) continue;
|
|
221
|
+
let rooms = null;
|
|
222
|
+
try { rooms = JSON.parse(frame.match(/^data: (.*)$/m)?.[1] ?? '{}').rooms ?? null; } catch { /* Every room may have changed. */ }
|
|
223
|
+
socket.send(JSON.stringify({ type: 'event', rooms }));
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
} catch { /* Reconnect below; devices fall back to their own polling meanwhile. */ }
|
|
227
|
+
await sleep(EVENT_RETRY_MS, undefined, { signal }).catch(() => {});
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Hold one website's relay connection, reconnecting with backoff; `connected` tracks which websites are live. */
|
|
232
|
+
async function hold_channel(home, site, { connected, log, signal }) {
|
|
233
|
+
let delay = RETRY_MIN_MS;
|
|
234
|
+
while (!signal.aborted) {
|
|
235
|
+
// Read the pairing each time: reconnecting the website replaces the token, and disconnecting removes it.
|
|
236
|
+
const link = machine_links(home).sites[site];
|
|
237
|
+
if (!link?.private_key) return;
|
|
238
|
+
const url = `${site.replace(/^http/, 'ws')}/api/machines/${encodeURIComponent(link.id)}/relay`;
|
|
239
|
+
const closed = new Promise(resolve => {
|
|
240
|
+
let socket;
|
|
241
|
+
try { socket = new WebSocket(url, [RELAY_PROTOCOL, `m.${link.token}`]); } catch { return resolve(false); }
|
|
242
|
+
const events = new AbortController();
|
|
243
|
+
let ping, finished = false;
|
|
244
|
+
// Only the first finish counts: a stalled socket may report its close long after its replacement connected.
|
|
245
|
+
const finish = opened => {
|
|
246
|
+
if (finished) return;
|
|
247
|
+
finished = true;
|
|
248
|
+
clearInterval(ping);
|
|
249
|
+
events.abort();
|
|
250
|
+
connected.delete(site);
|
|
251
|
+
resolve(opened);
|
|
252
|
+
};
|
|
253
|
+
// Only a pong proves both directions work: requests can keep arriving while this computer's answers are stuck.
|
|
254
|
+
// A website that never answers pings is not judged by them.
|
|
255
|
+
let opened = false, awaiting_pong = false, pong_seen = false;
|
|
256
|
+
socket.addEventListener('open', () => {
|
|
257
|
+
opened = true;
|
|
258
|
+
connected.add(site);
|
|
259
|
+
log(`${site}: 中转已连接`);
|
|
260
|
+
ping = setInterval(() => {
|
|
261
|
+
if (socket.readyState !== WebSocket.OPEN) return;
|
|
262
|
+
if (awaiting_pong && pong_seen) {
|
|
263
|
+
log(`${site}: 中转心跳 ${PING_MS / 1000} 秒未回应,重新连接`);
|
|
264
|
+
try { socket.close(4000, 'stalled'); } catch { /* Already closing. */ }
|
|
265
|
+
return finish(opened);
|
|
266
|
+
}
|
|
267
|
+
awaiting_pong = true;
|
|
268
|
+
socket.send('ping');
|
|
269
|
+
}, PING_MS);
|
|
270
|
+
forward_changes(home, socket, events.signal);
|
|
271
|
+
});
|
|
272
|
+
socket.addEventListener('message', async event => {
|
|
273
|
+
if (event.data === 'pong') { awaiting_pong = false; pong_seen = true; return; }
|
|
274
|
+
if (typeof event.data !== 'string') return;
|
|
275
|
+
let frame;
|
|
276
|
+
try { frame = JSON.parse(event.data); } catch { return; }
|
|
277
|
+
if (frame.type !== 'request' || typeof frame.id !== 'string' || !frame.envelope) return;
|
|
278
|
+
// Disconnecting or re-pairing the website ends this connection at once, not at its next reconnect.
|
|
279
|
+
const current = machine_links(home).sites[site];
|
|
280
|
+
if (current?.token !== link.token || current?.private_key?.d !== link.private_key?.d) {
|
|
281
|
+
log(`${site}: 配对已撤销或更换,关闭中转连接`);
|
|
282
|
+
return socket.close(1000, 'unpaired');
|
|
283
|
+
}
|
|
284
|
+
const received = Date.now();
|
|
285
|
+
let kind = { action: '?', route: '', status: 0 };
|
|
286
|
+
try {
|
|
287
|
+
const answer = await answer_request(home, site, link, frame, { report: value => { kind = value; } });
|
|
288
|
+
const answered = Date.now();
|
|
289
|
+
const open = socket.readyState === WebSocket.OPEN;
|
|
290
|
+
if (open) socket.send(JSON.stringify(answer));
|
|
291
|
+
const label = `${kind.action}${kind.route ? ` ${kind.route}` : ''} → ${kind.status}`;
|
|
292
|
+
if (!open) log(`${site}: 中转回应未送出(连接已断开):${label},处理 ${answered - received} ms`);
|
|
293
|
+
else if (answered - received > SLOW_REQUEST_MS) log(`${site}: 中转请求较慢:${label},处理 ${answered - received} ms`);
|
|
294
|
+
} catch (error) { log(`${site}: 中转请求 ${frame.id} 无法处理(${Date.now() - received} ms):${error.message}`); }
|
|
295
|
+
});
|
|
296
|
+
socket.addEventListener('close', event => {
|
|
297
|
+
if (opened && !finished && !signal.aborted) log(`${site}: 中转连接断开(${event.code || '无代码'}${event.reason ? ` ${event.reason}` : ''}),稍后重连`);
|
|
298
|
+
finish(opened);
|
|
299
|
+
});
|
|
300
|
+
socket.addEventListener('error', () => { try { socket.close(); } catch { /* Already closing. */ } });
|
|
301
|
+
signal.addEventListener('abort', () => { try { socket.close(1000, 'stopping'); } catch { /* Already closed. */ } }, { once: true });
|
|
302
|
+
});
|
|
303
|
+
const opened = await closed;
|
|
304
|
+
if (signal.aborted) return;
|
|
305
|
+
// A website without the relay refuses the upgrade every time; back off fully so it is only asked now and then.
|
|
306
|
+
delay = opened ? RETRY_MIN_MS : Math.min(delay * 2, RETRY_MAX_MS);
|
|
307
|
+
await sleep(delay, undefined, { signal }).catch(() => {});
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* Keep a relay channel open to every paired website that has a command key; returns the set of websites currently
|
|
313
|
+
* connected, so the D1 command queue can skip them. New pairings are picked up when `refresh` is called.
|
|
314
|
+
*/
|
|
315
|
+
export function start_relay_channels(home, { log = () => {}, signal }) {
|
|
316
|
+
const connected = new Set(), held = new Map();
|
|
317
|
+
const refresh = () => {
|
|
318
|
+
for (const [site, link] of Object.entries(machine_links(home).sites)) {
|
|
319
|
+
if (!link.private_key || held.has(site)) continue;
|
|
320
|
+
held.set(site, hold_channel(home, site, { connected, log, signal }).finally(() => held.delete(site)));
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
refresh();
|
|
324
|
+
return { connected, refresh, done: () => Promise.all(held.values()) };
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
export { RELAY_PROTOCOL };
|