@fnndsc/calypso 0.29.15 → 0.30.0

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 (79) hide show
  1. package/dist/calypso.js +19 -8
  2. package/dist/calypso.js.map +1 -1
  3. package/dist/daemon/attachFile.d.ts +26 -19
  4. package/dist/daemon/attachFile.js +42 -51
  5. package/dist/daemon/attachFile.js.map +1 -1
  6. package/dist/daemon/attachOrigin.d.ts +69 -0
  7. package/dist/daemon/attachOrigin.js +125 -0
  8. package/dist/daemon/attachOrigin.js.map +1 -0
  9. package/dist/daemon/berth.d.ts +265 -26
  10. package/dist/daemon/berth.js +521 -158
  11. package/dist/daemon/berth.js.map +1 -1
  12. package/dist/daemon/claims.js +19 -9
  13. package/dist/daemon/claims.js.map +1 -1
  14. package/dist/daemon/commandLane.d.ts +317 -0
  15. package/dist/daemon/commandLane.js +409 -0
  16. package/dist/daemon/commandLane.js.map +1 -0
  17. package/dist/daemon/console.d.ts +0 -2
  18. package/dist/daemon/console.js +7 -10
  19. package/dist/daemon/console.js.map +1 -1
  20. package/dist/daemon/consoleSession.js +4 -1
  21. package/dist/daemon/consoleSession.js.map +1 -1
  22. package/dist/daemon/elevation.d.ts +0 -3
  23. package/dist/daemon/elevation.js +1 -3
  24. package/dist/daemon/elevation.js.map +1 -1
  25. package/dist/daemon/face.d.ts +18 -4
  26. package/dist/daemon/face.js +77 -32
  27. package/dist/daemon/face.js.map +1 -1
  28. package/dist/daemon/hostControl.d.ts +114 -1
  29. package/dist/daemon/hostControl.js +104 -4
  30. package/dist/daemon/hostControl.js.map +1 -1
  31. package/dist/daemon/hostPtyRelay.d.ts +118 -0
  32. package/dist/daemon/hostPtyRelay.js +186 -0
  33. package/dist/daemon/hostPtyRelay.js.map +1 -0
  34. package/dist/daemon/httpRoutes.d.ts +257 -0
  35. package/dist/daemon/httpRoutes.js +537 -0
  36. package/dist/daemon/httpRoutes.js.map +1 -0
  37. package/dist/daemon/instance.d.ts +37 -0
  38. package/dist/daemon/instance.js +59 -0
  39. package/dist/daemon/instance.js.map +1 -0
  40. package/dist/daemon/launch.d.ts +17 -0
  41. package/dist/daemon/launch.js +198 -194
  42. package/dist/daemon/launch.js.map +1 -1
  43. package/dist/daemon/launchBanner.d.ts +76 -0
  44. package/dist/daemon/launchBanner.js +80 -0
  45. package/dist/daemon/launchBanner.js.map +1 -0
  46. package/dist/daemon/rival.d.ts +65 -0
  47. package/dist/daemon/rival.js +67 -0
  48. package/dist/daemon/rival.js.map +1 -0
  49. package/dist/daemon/server.d.ts +104 -190
  50. package/dist/daemon/server.js +358 -866
  51. package/dist/daemon/server.js.map +1 -1
  52. package/dist/daemon/settings.d.ts +42 -0
  53. package/dist/daemon/settings.js +43 -0
  54. package/dist/daemon/settings.js.map +1 -0
  55. package/dist/daemon/surface.d.ts +103 -0
  56. package/dist/daemon/surface.js +71 -0
  57. package/dist/daemon/surface.js.map +1 -0
  58. package/dist/daemon/surfaceReplies.d.ts +109 -0
  59. package/dist/daemon/surfaceReplies.js +108 -0
  60. package/dist/daemon/surfaceReplies.js.map +1 -0
  61. package/dist/daemon/terminals.js +5 -2
  62. package/dist/daemon/terminals.js.map +1 -1
  63. package/dist/daemon/token.d.ts +41 -5
  64. package/dist/daemon/token.js +43 -12
  65. package/dist/daemon/token.js.map +1 -1
  66. package/dist/daemon/uploadHold.d.ts +85 -0
  67. package/dist/daemon/uploadHold.js +205 -0
  68. package/dist/daemon/uploadHold.js.map +1 -0
  69. package/dist/daemon/vfsHeaders.d.ts +11 -0
  70. package/dist/daemon/vfsHeaders.js +60 -0
  71. package/dist/daemon/vfsHeaders.js.map +1 -0
  72. package/dist/index.d.ts +5 -5
  73. package/dist/index.js +3 -4
  74. package/dist/index.js.map +1 -1
  75. package/dist/notes.json +1 -1
  76. package/package.json +9 -4
  77. package/dist/daemon/discovery.d.ts +0 -23
  78. package/dist/daemon/discovery.js +0 -57
  79. package/dist/daemon/discovery.js.map +0 -1
@@ -0,0 +1,537 @@
1
+ /**
2
+ * @file The daemon's plain HTTP side: the file route, the session's facts, and the web surface it serves.
3
+ *
4
+ * One loopback port carries both the wire (WebSocket upgrades) and plain requests. The plain requests are routed
5
+ * here: `/vfs` serves one ChRIS file's bytes, streamed, and takes an upload; `/instance` proves which daemon
6
+ * answers; `/backend` and `/joblets` say what the session runs over and what runs in it; anything else is the web
7
+ * root's, or not found. Every route but `/instance` and the web root is gated by the attach token, compared in
8
+ * constant time, and a wrong one is not found. The downloads being served (for their progress and stop) and the
9
+ * bytes held for uploads in flight are this module's.
10
+ *
11
+ * Key components:
12
+ * - DaemonHttp: the routes, the download ledger and the upload hold.
13
+ * - VFS_POST_LIMIT: the largest file `POST /vfs` takes.
14
+ *
15
+ * Typical usage:
16
+ * ```ts
17
+ * const http: DaemonHttp = new DaemonHttp(engine, token, { webRoot, backend, uploadHeld }, log);
18
+ * createServer((request, response): void => { http.request_route(request, response); });
19
+ * ```
20
+ *
21
+ * Dependencies: the engine's file seams (engine.ts), downloads.ts, uploadHold.ts, vfsHeaders.ts, vfsBreak.ts,
22
+ * static.ts, instance.ts, token.ts.
23
+ *
24
+ * @module
25
+ */
26
+ import { DownloadLedger, downloadId_valid } from './downloads.js';
27
+ import { instanceRequest_serve } from './instance.js';
28
+ import { staticRequest_handle } from './static.js';
29
+ import { token_matches } from './token.js';
30
+ import { UploadHold, upload_take } from './uploadHold.js';
31
+ import { byteStream_normalise, errorFacts_read, vfsBreak_format } from './vfsBreak.js';
32
+ import { vfsHeaders_build } from './vfsHeaders.js';
33
+ /**
34
+ * The largest file `POST /vfs` will take, in bytes.
35
+ *
36
+ * A cap rather than a stream to the store: the route exists so an operator
37
+ * can put a document, a manifest or an image into the folder they are
38
+ * looking at, and a surface able to post unbounded bytes to a loopback port
39
+ * is a surface able to fill the machine.
40
+ */
41
+ export const VFS_POST_LIMIT = 256 * 1024 * 1024;
42
+ /**
43
+ * The daemon's plain HTTP routes.
44
+ *
45
+ * @example
46
+ * ```ts
47
+ * const http: DaemonHttp = new DaemonHttp(engine, token, { webRoot, backend: undefined, uploadHeld }, console.error);
48
+ * http.instance_set({ probeKey, identity, pid: process.pid, booted });
49
+ * ```
50
+ */
51
+ export class DaemonHttp {
52
+ engine;
53
+ token;
54
+ log;
55
+ /** The downloads this daemon is serving, for their progress (downloads.ts). */
56
+ downloads = new DownloadLedger();
57
+ /** The bytes this daemon holds for uploads in flight, under its ceiling (uploadHold.ts). */
58
+ uploads;
59
+ /** The facts this daemon proves itself by at `/instance`; null until its record is written. */
60
+ instance = null;
61
+ /** The built web surface, when one is served. */
62
+ webRoot;
63
+ /** The session's backend id. */
64
+ backend;
65
+ /**
66
+ * @param engine - The engine whose files the routes read and write.
67
+ * @param token - The attach token every gated route asks for.
68
+ * @param options - The web root, the backend id and the upload ceiling.
69
+ * @param log - Writes a line of the daemon's own log.
70
+ */
71
+ constructor(engine, token, options, log) {
72
+ this.engine = engine;
73
+ this.token = token;
74
+ this.log = log;
75
+ this.webRoot = options.webRoot;
76
+ this.backend = options.backend;
77
+ this.uploads = new UploadHold(options.uploadHeld);
78
+ }
79
+ /**
80
+ * Sets the facts this daemon proves itself by at `/instance`, the ones its berth record holds.
81
+ *
82
+ * @param facts - The launch's probe key, identity, pid and boot time.
83
+ *
84
+ * @example
85
+ * ```ts
86
+ * http.instance_set({ probeKey, identity, pid: process.pid, booted });
87
+ * ```
88
+ */
89
+ instance_set(facts) {
90
+ this.instance = facts;
91
+ }
92
+ /**
93
+ * Answers one plain request by its path.
94
+ *
95
+ * @param request - The incoming HTTP request.
96
+ * @param response - The response to write.
97
+ *
98
+ * @example
99
+ * ```ts
100
+ * createServer((request, response): void => { http.request_route(request, response); });
101
+ * ```
102
+ */
103
+ request_route(request, response) {
104
+ const requestPath = (request.url ?? '/').split('?')[0] ?? '/';
105
+ if (requestPath === '/vfs') {
106
+ // A file route that throws is answered and said, never left to end the session.
107
+ this.vfs_serve(request, response).catch((error) => {
108
+ this.log(`[!] vfs: ${request.url?.split('?')[0] ?? '/vfs'}: ${errorFacts_read(error).message}`);
109
+ if (!response.headersSent) {
110
+ response.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
111
+ response.end(`the session could not serve that file: ${errorFacts_read(error).message}`);
112
+ }
113
+ else {
114
+ response.destroy();
115
+ }
116
+ });
117
+ return;
118
+ }
119
+ if (requestPath === '/instance') {
120
+ instanceRequest_serve(request, response, this.instance);
121
+ return;
122
+ }
123
+ if (requestPath === '/backend') {
124
+ this.backend_serve(request, response);
125
+ return;
126
+ }
127
+ if (requestPath === '/joblets') {
128
+ this.joblets_serve(request, response);
129
+ return;
130
+ }
131
+ if (this.webRoot !== undefined) {
132
+ staticRequest_handle(this.webRoot, request, response);
133
+ return;
134
+ }
135
+ response.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
136
+ response.end('not found');
137
+ }
138
+ /**
139
+ * Says which backend the session runs over, before a surface builds:
140
+ * `{"backend": "chris"}`. A surface chooses its composition from it, and
141
+ * the attach answer says the same once it attaches. The attach token gates
142
+ * it as it gates `/vfs` (a wrong one is not found).
143
+ *
144
+ * @param request - The incoming HTTP request.
145
+ * @param response - The response to write.
146
+ */
147
+ backend_serve(request, response) {
148
+ const query = new URL(request.url ?? '/', 'http://localhost').searchParams;
149
+ if (!token_matches(this.token, query.get('token') ?? '')) {
150
+ response.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
151
+ response.end('not found');
152
+ return;
153
+ }
154
+ response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
155
+ response.end(JSON.stringify({ backend: this.backend ?? null }));
156
+ }
157
+ /**
158
+ * Says which joblets run now (`line &`): `{"joblets": [{number, line,
159
+ * waiting}]}`. A host about to restart the session (porter, for a new
160
+ * release) asks first, since a restart ends them (#1273). Gated by the
161
+ * attach token, as `/backend` is.
162
+ *
163
+ * @param request - The incoming HTTP request.
164
+ * @param response - The response to write.
165
+ */
166
+ joblets_serve(request, response) {
167
+ const query = new URL(request.url ?? '/', 'http://localhost').searchParams;
168
+ if (!token_matches(this.token, query.get('token') ?? '')) {
169
+ response.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
170
+ response.end('not found');
171
+ return;
172
+ }
173
+ response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
174
+ response.end(JSON.stringify({ joblets: this.engine.joblets_running?.() ?? [] }));
175
+ }
176
+ /**
177
+ * Writes a plain-text `/vfs` refusal response.
178
+ *
179
+ * @param response - HTTP response to write.
180
+ * @param status - HTTP status code.
181
+ * @param message - Plain-text refusal body.
182
+ */
183
+ vfs_refuse(response, status, message) {
184
+ response.writeHead(status, { 'content-type': 'text/plain; charset=utf-8' });
185
+ response.end(message);
186
+ }
187
+ /**
188
+ * Answers a `/vfs?progress=...` or `/vfs?cancel=...` download status/stop request.
189
+ *
190
+ * @param asked - Requested download id.
191
+ * @param stopping - True when the request cancels the download.
192
+ * @param response - HTTP response to write.
193
+ */
194
+ vfsDownloadQuery_answer(asked, stopping, response) {
195
+ const id = downloadId_valid(asked) ? asked : null;
196
+ if (id !== null && stopping)
197
+ this.downloads.cancel(id);
198
+ const report = id === null ? null : this.downloads.report(id);
199
+ response.writeHead(report === null ? 404 : 200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
200
+ response.end(JSON.stringify(report ?? { reason: 'no such download' }));
201
+ }
202
+ /**
203
+ * Reads a file whole through `read` and writes the HTTP response or refusal.
204
+ *
205
+ * @param read - Engine file reader.
206
+ * @param filePath - Path of the file to read.
207
+ * @param request - Incoming HTTP request.
208
+ * @param query - Parsed URL query parameters.
209
+ * @param response - HTTP response to write.
210
+ */
211
+ async vfsBuffered_serve(read, filePath, request, query, response) {
212
+ try {
213
+ const bytes = await read(filePath);
214
+ response.writeHead(200, vfsHeaders_build(filePath, query.get('download') === '1', bytes.length));
215
+ response.end(request.method === 'HEAD' ? undefined : bytes);
216
+ }
217
+ catch (error) {
218
+ // The kernel says why it refused (status and a line); the route
219
+ // passes both on. It used to answer 404 for everything, and a
220
+ // surface could only say REFUSED.
221
+ if (error === null || error === undefined)
222
+ throw new TypeError('Cannot read properties of null or undefined');
223
+ if (typeof error === 'object') {
224
+ const status = Reflect.get(error, 'status');
225
+ const reason = typeof status === 'number' ? Reflect.get(error, 'reason') : undefined;
226
+ if (typeof status === 'number' && typeof reason === 'string') {
227
+ this.vfs_refuse(response, status, reason);
228
+ return;
229
+ }
230
+ }
231
+ this.vfs_refuse(response, 404, 'not found');
232
+ }
233
+ }
234
+ /**
235
+ * Serves a validated `GET`/`HEAD` file request via streaming or buffered read.
236
+ *
237
+ * @param request - Incoming HTTP request.
238
+ * @param query - Parsed URL query parameters.
239
+ * @param response - HTTP response to write.
240
+ * @param refuse - Refusal writer.
241
+ */
242
+ async vfsFile_serve(request, query, response, refuse) {
243
+ const filePath = query.get('path');
244
+ const read = this.engine.file_read?.bind(this.engine);
245
+ if (filePath === null || filePath.length === 0 || read === undefined) {
246
+ refuse(404, 'not found');
247
+ return;
248
+ }
249
+ const open = this.engine.file_stream?.bind(this.engine);
250
+ // A download's probe asks by HEAD: the file's headers, its bytes held.
251
+ if (open !== undefined && (request.method === 'GET' || (request.method === 'HEAD' && query.get('probe') === '1'))) {
252
+ await this.vfs_stream(open, filePath, query, response, refuse);
253
+ return;
254
+ }
255
+ await this.vfsBuffered_serve(read, filePath, request, query, response);
256
+ }
257
+ /**
258
+ * Serves one ChRIS file's bytes over HTTP: `GET /vfs?path=...&token=...`.
259
+ *
260
+ * The route exists so browser surfaces can render file content natively
261
+ * (an image in a panel) instead of through the terminal stream. It is
262
+ * gated by the same attach token as the wire (compared in constant time)
263
+ * and requires the hosted engine to provide `file_read`; refusals and
264
+ * failures answer 404 so the response does not confirm what exists.
265
+ *
266
+ * With `download=1` the same bytes come down as an attachment named for
267
+ * the file, which is how a browser is told to save rather than show: a
268
+ * surface's DOWNLOAD is this URL behind an anchor, so a file reaches the
269
+ * operator's disk the way every other download does.
270
+ *
271
+ * @param request - The incoming HTTP request.
272
+ * @param response - The response to write.
273
+ */
274
+ async vfs_serve(request, response) {
275
+ const refuse = (status, message) => {
276
+ this.vfs_refuse(response, status, message);
277
+ };
278
+ const query = new URL(request.url ?? '/', 'http://localhost').searchParams;
279
+ if (!token_matches(this.token, query.get('token') ?? '')) {
280
+ refuse(404, 'not found');
281
+ return;
282
+ }
283
+ // A download's stop changes something, and so is a POST: a GET changes nothing here, which is what
284
+ // lets a door in front ask only a request that is not a GET where it came from.
285
+ const stopping = query.has('cancel');
286
+ // One ask names one download for one purpose: a stop and a progress ask together, or either twice, would
287
+ // leave it to the order of reading which download is meant.
288
+ if (query.getAll('cancel').length + query.getAll('progress').length > 1) {
289
+ refuse(400, 'one of progress or cancel, once');
290
+ return;
291
+ }
292
+ if (request.method === 'POST' && !stopping) {
293
+ await this.vfs_receive(request, response, query, refuse);
294
+ return;
295
+ }
296
+ if (stopping && request.method !== 'POST') {
297
+ response.setHeader('allow', 'POST');
298
+ refuse(405, 'a download is stopped by POST');
299
+ return;
300
+ }
301
+ if (request.method !== 'GET' && request.method !== 'HEAD' && request.method !== 'POST') {
302
+ refuse(405, 'method not allowed');
303
+ return;
304
+ }
305
+ // A download's progress, and its stop: the surface asks by its own id.
306
+ const asked = query.get('progress') ?? query.get('cancel');
307
+ if (asked !== null) {
308
+ this.vfsDownloadQuery_answer(asked, stopping, response);
309
+ return;
310
+ }
311
+ await this.vfsFile_serve(request, query, response, refuse);
312
+ }
313
+ /**
314
+ * Serves one file's bytes as they arrive: the length in the header when
315
+ * the store gave one (so a browser draws its own progress), the body
316
+ * piped, nothing held whole. A 3.7 GB DICOM used to be read into one
317
+ * buffer behind a 30 s deadline and answered 404. A failure to open the
318
+ * file answers with the kernel's status and reason. The status waits for
319
+ * CUBE's first byte, so a file whose bytes never start is a 502 that says
320
+ * why. A break after bytes have gone cuts the socket, which the porter and
321
+ * the browser see as a body that stopped rather than a short file. Either
322
+ * break is one line in the daemon's log (vfsBreak.ts): the path, the bytes
323
+ * sent of the size CUBE stated, the time taken and the cause.
324
+ *
325
+ * A download with an id (`dl`) is counted for its progress; its probe
326
+ * (HEAD, `probe=1`) opens the file and answers the headers alone, holding the
327
+ * stream for the save that follows (downloads.ts).
328
+ *
329
+ * @param open - The engine's stream seam.
330
+ * @param filePath - The file asked for.
331
+ * @param query - The request's query (`download=1` names an attachment).
332
+ * @param response - The response to write.
333
+ * @param refuse - Answers a refusal before any byte is sent.
334
+ */
335
+ async vfs_stream(open, filePath, query, response, refuse) {
336
+ const startedAt = Date.now();
337
+ const dl = downloadId_valid(query.get('dl')) ? query.get('dl') : null;
338
+ const probe = dl !== null && query.get('probe') === '1';
339
+ // The browser's save takes the file its probe opened, when one is held.
340
+ // A cancelled download stays cancelled: its save is refused, not begun again.
341
+ if (dl !== null && this.downloads.cancelled(dl)) {
342
+ refuse(410, 'cancelled');
343
+ return;
344
+ }
345
+ let opened = dl !== null && !probe ? this.downloads.claim(dl) : null;
346
+ if (opened === null) {
347
+ if (dl !== null)
348
+ this.downloads.begin(dl, filePath);
349
+ try {
350
+ opened = await open(filePath);
351
+ }
352
+ catch (error) {
353
+ this.openFailure_answer(error, dl, refuse);
354
+ return;
355
+ }
356
+ }
357
+ const headers = vfsHeaders_build(filePath, query.get('download') === '1', opened.size);
358
+ if (probe && dl !== null) {
359
+ this.vfsProbe_answer(dl, opened, headers, response, refuse);
360
+ return;
361
+ }
362
+ await this.vfsBody_pipe(opened, headers, filePath, dl, startedAt, response, refuse);
363
+ }
364
+ /**
365
+ * Answers a download's probe with the file's headers alone, its stream parked for the save that follows.
366
+ *
367
+ * @param dl - The download's id.
368
+ * @param opened - The opened file.
369
+ * @param headers - The file's headers.
370
+ * @param response - The response to write.
371
+ * @param refuse - Answers a refusal before any byte is sent.
372
+ */
373
+ vfsProbe_answer(dl, opened, headers, response, refuse) {
374
+ // The probe's answer is the file's headers; the bytes wait for the save.
375
+ if (!this.downloads.park(dl, opened)) {
376
+ refuse(410, 'cancelled');
377
+ return;
378
+ }
379
+ response.writeHead(200, headers);
380
+ response.end();
381
+ }
382
+ /**
383
+ * Answers a file the store would not open: with the kernel's status and reason when it gave them, else not found;
384
+ * a download with an id is marked failed.
385
+ *
386
+ * @param error - Why it would not open.
387
+ * @param dl - The download's id, or null.
388
+ * @param refuse - Answers a refusal before any byte is sent.
389
+ */
390
+ openFailure_answer(error, dl, refuse) {
391
+ const named = error;
392
+ const known = typeof named.status === 'number' && typeof named.reason === 'string';
393
+ if (dl !== null)
394
+ this.downloads.fail(dl, known ? String(named.reason) : 'not found');
395
+ if (known)
396
+ refuse(named.status, named.reason);
397
+ else
398
+ refuse(404, 'not found');
399
+ }
400
+ /**
401
+ * Pipes an opened file's bytes to the response: the status waits for the first byte, and a break is logged and
402
+ * cuts the socket.
403
+ *
404
+ * @param opened - The opened file.
405
+ * @param headers - The file's headers, sent with its first byte.
406
+ * @param filePath - The file asked for.
407
+ * @param dl - The download's id, or null.
408
+ * @param startedAt - When the request was taken, from `Date.now()`.
409
+ * @param response - The response to write.
410
+ * @param refuse - Answers a refusal before any byte is sent.
411
+ */
412
+ async vfsBody_pipe(opened, headers, filePath, dl, startedAt, response, refuse) {
413
+ let stream;
414
+ try {
415
+ stream = await byteStream_normalise(opened.stream);
416
+ }
417
+ catch (error) {
418
+ const { message } = errorFacts_read(error);
419
+ this.log(`[!] vfs: ${filePath}: ${message}`);
420
+ if (dl !== null)
421
+ this.downloads.fail(dl, message);
422
+ refuse(500, message);
423
+ return;
424
+ }
425
+ const statedBytes = opened.size;
426
+ let browserLeft = false;
427
+ // The browser left (a cancelled download): stop pulling from CUBE.
428
+ response.on('close', () => {
429
+ if (response.writableFinished)
430
+ return;
431
+ browserLeft = true;
432
+ stream.destroy?.();
433
+ });
434
+ const chunks = stream[Symbol.asyncIterator]();
435
+ let sentBytes = 0;
436
+ const break_log = (error) => {
437
+ if (browserLeft)
438
+ return;
439
+ this.log(vfsBreak_format({ path: filePath, sentBytes, statedBytes, elapsedMs: Date.now() - startedAt, ...errorFacts_read(error) }));
440
+ };
441
+ // The status waits for CUBE's first byte: a file that never starts is
442
+ // still a refusal with its reason, not a 200 cut off before its body.
443
+ let first;
444
+ try {
445
+ first = await chunks.next();
446
+ }
447
+ catch (error) {
448
+ break_log(error);
449
+ const { message } = errorFacts_read(error);
450
+ if (dl !== null)
451
+ this.downloads.fail(dl, `the file did not arrive from CUBE: ${message}`);
452
+ if (!browserLeft)
453
+ refuse(502, `the file did not arrive from CUBE: ${message}`);
454
+ return;
455
+ }
456
+ response.writeHead(200, headers);
457
+ const rest = async function* () {
458
+ let step = first;
459
+ while (step.done !== true) {
460
+ const chunk = Buffer.isBuffer(step.value) ? step.value : Buffer.from(step.value);
461
+ sentBytes += chunk.length;
462
+ yield chunk;
463
+ step = await chunks.next();
464
+ }
465
+ };
466
+ try {
467
+ const { pipeline } = await import('node:stream/promises');
468
+ if (dl !== null)
469
+ await pipeline(rest, this.downloads.counter(dl, response), response);
470
+ else
471
+ await pipeline(rest, response);
472
+ }
473
+ catch (error) {
474
+ break_log(error);
475
+ // The status is sent and cannot change: the socket is cut, so the
476
+ // porter and the browser see a body that stopped, never a whole short file.
477
+ if (dl !== null)
478
+ this.downloads.fail(dl, `the file stopped arriving from CUBE: ${errorFacts_read(error).message}`);
479
+ response.destroy();
480
+ }
481
+ }
482
+ /**
483
+ * Takes one file's bytes from a surface: `POST /vfs?path=...&token=...`.
484
+ *
485
+ * A browser cannot reach the machine the daemon runs on, so `upload` is
486
+ * not a verb it can speak: the bytes travel here and the ENGINE puts them
487
+ * in the store, which keeps the write on the kernel's own path rather
488
+ * than letting a surface talk to CUBE.
489
+ *
490
+ * Gated by the same attach token as the read, and capped: a surface that
491
+ * can post unbounded bytes to a loopback port is a surface that can fill
492
+ * the machine.
493
+ *
494
+ * One request is capped, and so is what all requests in flight hold
495
+ * together (`uploadHold.ts`): the body's bytes are reserved before they
496
+ * are read and stay reserved until the store has them or has refused.
497
+ *
498
+ * @param request - The incoming request, whose body is the file.
499
+ * @param response - The response to write.
500
+ * @param query - The parsed query string (path and token).
501
+ * @param refuse - How this route says no.
502
+ */
503
+ async vfs_receive(request, response, query, refuse) {
504
+ const filePath = query.get('path');
505
+ const write = this.engine.file_write?.bind(this.engine);
506
+ if (filePath === null || filePath.length === 0 || write === undefined) {
507
+ refuse(404, 'not found');
508
+ return;
509
+ }
510
+ const taken = await upload_take(request, this.uploads, VFS_POST_LIMIT);
511
+ if ('refusal' in taken) {
512
+ // The body may not have been read to its end: the answer is sent, the
513
+ // connection is closed with it, and nothing more is taken from it.
514
+ response.setHeader('connection', 'close');
515
+ if (taken.refusal.retryAfter !== undefined)
516
+ response.setHeader('retry-after', String(taken.refusal.retryAfter));
517
+ response.once('finish', () => { request.destroy(); });
518
+ refuse(taken.refusal.status, taken.refusal.message);
519
+ return;
520
+ }
521
+ const received = taken.bytes.length;
522
+ try {
523
+ await write(filePath, taken.bytes);
524
+ }
525
+ catch (error) {
526
+ refuse(502, error instanceof Error ? error.message : 'the store refused the write');
527
+ return;
528
+ }
529
+ finally {
530
+ // Held through the write, and given back however it ended.
531
+ taken.release();
532
+ }
533
+ response.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
534
+ response.end(JSON.stringify({ path: filePath, bytes: received }));
535
+ }
536
+ }
537
+ //# sourceMappingURL=httpRoutes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"httpRoutes.js","sourceRoot":"","sources":["../../src/daemon/httpRoutes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAIH,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAwC,MAAM,gBAAgB,CAAC;AAExG,OAAO,EAAE,qBAAqB,EAAsB,MAAM,eAAe,CAAC;AAC1E,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,WAAW,EAAwC,MAAM,iBAAiB,C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AE,CAAC;QAClB,CAAC;QACD,QAAQ,CAAC,SAAS,CAAC,GAAG,EAAE,EAAE,cAAc,EAAE,iCAAiC,EAAE,CAAC,CAAC;QAC/E,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC;IACpE,CAAC;CACF"}
@@ -0,0 +1,37 @@
1
+ /**
2
+ * @file The instance route: a daemon proves it is the instance its berth record names.
3
+ *
4
+ * A record's address can outlive its daemon, and the port can be taken by another program, another account's
5
+ * among them. A client that holds the record asks `GET /instance?nonce=<64 lowercase hex>` and checks the answer
6
+ * against the record's probe key (`berthInstance_probe`): only the instance that wrote the record can answer with
7
+ * the proof. The request carries no secret and the answer gives none away.
8
+ *
9
+ * Key components:
10
+ * - instanceRequest_serve: answers `GET /instance` with the proof, or a refusal.
11
+ *
12
+ * Typical usage:
13
+ * ```ts
14
+ * if (requestPath === '/instance') instanceRequest_serve(request, response, this.instance);
15
+ * ```
16
+ *
17
+ * Dependencies: node:http (types only), ./berth.js (instanceProof_compute).
18
+ *
19
+ * @module
20
+ */
21
+ import type { IncomingMessage, ServerResponse } from 'node:http';
22
+ import { type InstanceFacts } from './berth.js';
23
+ export type { InstanceFacts } from './berth.js';
24
+ /**
25
+ * Answers an instance probe: the proof for the nonce asked with, or a refusal. Only `GET`, and only a query of
26
+ * exactly one nonce of 64 lowercase hex characters (400 otherwise), so nothing else enters the proof.
27
+ *
28
+ * @param request - The request, its path `/instance`.
29
+ * @param response - Where the answer goes.
30
+ * @param facts - This daemon's instance facts, or null before its record is written (then 404).
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * if (requestPath === '/instance') instanceRequest_serve(request, response, this.instance);
35
+ * ```
36
+ */
37
+ export declare function instanceRequest_serve(request: IncomingMessage, response: ServerResponse, facts: InstanceFacts | null): void;
@@ -0,0 +1,59 @@
1
+ /**
2
+ * @file The instance route: a daemon proves it is the instance its berth record names.
3
+ *
4
+ * A record's address can outlive its daemon, and the port can be taken by another program, another account's
5
+ * among them. A client that holds the record asks `GET /instance?nonce=<64 lowercase hex>` and checks the answer
6
+ * against the record's probe key (`berthInstance_probe`): only the instance that wrote the record can answer with
7
+ * the proof. The request carries no secret and the answer gives none away.
8
+ *
9
+ * Key components:
10
+ * - instanceRequest_serve: answers `GET /instance` with the proof, or a refusal.
11
+ *
12
+ * Typical usage:
13
+ * ```ts
14
+ * if (requestPath === '/instance') instanceRequest_serve(request, response, this.instance);
15
+ * ```
16
+ *
17
+ * Dependencies: node:http (types only), ./berth.js (instanceProof_compute).
18
+ *
19
+ * @module
20
+ */
21
+ import { instanceProof_compute } from './berth.js';
22
+ /** The one query the route takes. */
23
+ const INSTANCE_QUERY = /^\?nonce=([0-9a-f]{64})$/;
24
+ /**
25
+ * Answers an instance probe: the proof for the nonce asked with, or a refusal. Only `GET`, and only a query of
26
+ * exactly one nonce of 64 lowercase hex characters (400 otherwise), so nothing else enters the proof.
27
+ *
28
+ * @param request - The request, its path `/instance`.
29
+ * @param response - Where the answer goes.
30
+ * @param facts - This daemon's instance facts, or null before its record is written (then 404).
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * if (requestPath === '/instance') instanceRequest_serve(request, response, this.instance);
35
+ * ```
36
+ */
37
+ export function instanceRequest_serve(request, response, facts) {
38
+ const headers = { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' };
39
+ if (request.method !== 'GET') {
40
+ response.writeHead(405, { ...headers, allow: 'GET' });
41
+ response.end('only GET');
42
+ return;
43
+ }
44
+ if (facts === null) {
45
+ response.writeHead(404, headers);
46
+ response.end('not yet');
47
+ return;
48
+ }
49
+ const url = request.url ?? '';
50
+ const asked = INSTANCE_QUERY.exec(url.slice(url.indexOf('?') < 0 ? url.length : url.indexOf('?')));
51
+ if (asked === null) {
52
+ response.writeHead(400, headers);
53
+ response.end('a probe is ?nonce=<64 lowercase hex>');
54
+ return;
55
+ }
56
+ response.writeHead(200, { ...headers, 'content-type': 'application/json' });
57
+ response.end(JSON.stringify({ proof: instanceProof_compute(facts, asked[1]) }));
58
+ }
59
+ //# sourceMappingURL=instance.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"instance.js","sourceRoot":"","sources":["../../src/daemon/instance.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAIH,OAAO,EAAE,qBAAqB,EAAsB,MAAM,YAAY,CAAC;AAIvE,qCAAqC;AACrC,MAAM,cAAc,GAAW,0BAA0B,CAAC;AAE1D;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,qBAAqB,CAAC,OAAwB,EAAE,QAAwB,EAAE,KAA2B;IACnH,MAAM,OAAO,GAA2B,EAAE,cAAc,EAAE,2BAA2B,EAAE,eAAe,EAAE,UAAU,EAAE,CAAC;IACrH,IAAI,OAAO,CAAC,MAAM,KAAK,KAAK,EAAE,CAAC;QAC7B,QAAQ,CAAC,SAAS,CAAC,GAAG,EAAE,EAAE,GAAG,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;QACtD,QAAQ,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QACzB,OAAO;IACT,CAAC;IACD,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;QACnB,QAAQ,CAAC,SAAS,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;QACjC,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;QACxB,OAAO;IACT,CAAC;IACD,MAAM,GAAG,GAAW,OAAO,CAAC,GAAG,IAAI,EAAE,CAAC;IACtC,MAAM,KAAK,GAA2B,cAAc,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;IAC3H,IA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