@ekrooh/bare 0.6.2 → 0.8.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.
- package/README.md +3 -2
- package/dist/errors-Bl5w-m62.mjs +56 -0
- package/dist/events-wkidvYuN.mjs +40 -0
- package/dist/{index-Do-kTNXw.d.mts → index-B3AmX7mC.d.mts} +35 -146
- package/dist/index.d.mts +2 -1
- package/dist/index.mjs +3 -1
- package/dist/{messages-CMNIFMFY.mjs → messages-B5HQRbFA.mjs} +185 -76
- package/dist/plugin-a3LvQrmS.mjs +111 -0
- package/dist/plugins-BjPAr5r8.mjs +77 -0
- package/dist/plugins-discovery-events.d.mts +1 -1
- package/dist/plugins-discovery-events.mjs +1 -1
- package/dist/plugins-health-events.d.mts +1 -1
- package/dist/plugins-health-events.mjs +1 -1
- package/dist/plugins-logs-events.d.mts +2 -1
- package/dist/plugins-logs-events.mjs +1 -1
- package/dist/plugins-media-events.d.mts +1 -1
- package/dist/plugins-media-events.mjs +1 -26
- package/dist/plugins-permissions-events.d.mts +2 -1
- package/dist/plugins-permissions-events.mjs +11 -3
- package/dist/plugins.d.mts +7 -4
- package/dist/plugins.mjs +1 -1
- package/dist/runtime.d.mts +31 -7
- package/dist/runtime.mjs +657 -124
- package/dist/{static-file-server-COxd-PFR.d.mts → static-file-server-drT1AHqV.d.mts} +26 -4
- package/dist/{store-DTg1jN5E.mjs → store-Bd2wL58k.mjs} +11 -2
- package/dist/sync.d.mts +40 -0
- package/dist/sync.mjs +372 -0
- package/dist/transports.d.mts +34 -1
- package/dist/transports.mjs +348 -168
- package/dist/types-BC39OoZB.d.mts +152 -0
- package/package.json +10 -8
- package/dist/plugins-BnpdCi3A.mjs +0 -156
package/dist/runtime.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { t as
|
|
1
|
+
import { a as isCanonicalErrorCode, c as MAX_HEADER_BYTES, i as CoreError, l as MessageType, o as ErrorCode, s as MAX_FRAME_BYTES } from "./errors-Bl5w-m62.mjs";
|
|
2
|
+
import { c as createRequestId, f as timerMs, m as isShortId, n as createBareRuntimeContext, p as FrameContentError } from "./messages-B5HQRbFA.mjs";
|
|
3
|
+
import { t as createDefaultPlugins } from "./plugins-BjPAr5r8.mjs";
|
|
4
|
+
import { t as createLogRingBuffer } from "./store-Bd2wL58k.mjs";
|
|
4
5
|
import { TextDecoder, TextEncoder } from "bare-encoding";
|
|
5
6
|
import fs from "bare-fs";
|
|
6
7
|
import path from "bare-path";
|
|
@@ -186,25 +187,37 @@ var ChannelHealth = class {
|
|
|
186
187
|
}
|
|
187
188
|
};
|
|
188
189
|
// core/messages/encode-response.ts
|
|
190
|
+
/** Echoes a routing id only when it is a short string; anything else could push
|
|
191
|
+
* the fallback response itself past the header cap. */
|
|
192
|
+
function shortId(value) {
|
|
193
|
+
return isShortId(value) ? value : "";
|
|
194
|
+
}
|
|
189
195
|
/** Encodes a routed response. A response that cannot be encoded (a result over
|
|
190
196
|
* the 64 KB header limit, or one that does not serialize) is replaced by an
|
|
191
197
|
* error response for the same request, so the caller fails fast instead of
|
|
192
|
-
* waiting for a timeout that never explains why.
|
|
198
|
+
* waiting for a timeout that never explains why. The fallback carries a fixed
|
|
199
|
+
* message and only short routing ids, so it always fits: this function never
|
|
200
|
+
* throws. */
|
|
193
201
|
function encodeResponse(protocol, response) {
|
|
194
202
|
try {
|
|
195
203
|
return protocol.encode(MessageType.ENVELOPE, response, null);
|
|
196
204
|
} catch (err) {
|
|
197
205
|
const reason = err instanceof Error ? err.message : String(err);
|
|
198
206
|
const tooLarge = /too large/i.test(reason);
|
|
199
|
-
|
|
207
|
+
const pluginId = shortId(response.pluginId);
|
|
208
|
+
const event = shortId(response.event);
|
|
209
|
+
try {
|
|
210
|
+
console.error(`Response for ${pluginId}.${event} dropped: ${reason.slice(0, 200)}`);
|
|
211
|
+
} catch {}
|
|
212
|
+
const requestId = shortId(response.requestId);
|
|
200
213
|
return protocol.encode(MessageType.ENVELOPE, {
|
|
201
214
|
type: "INVOKE_RESPONSE",
|
|
202
|
-
pluginId
|
|
203
|
-
event
|
|
204
|
-
requestId:
|
|
215
|
+
pluginId,
|
|
216
|
+
event,
|
|
217
|
+
requestId: requestId === "" ? void 0 : requestId,
|
|
205
218
|
error: {
|
|
206
219
|
code: tooLarge ? ErrorCode.FRAME_TOO_LARGE : ErrorCode.INVALID_RESPONSE,
|
|
207
|
-
message:
|
|
220
|
+
message: tooLarge ? "Response could not be sent: it exceeds the frame size limit" : "Response could not be sent: it could not be encoded"
|
|
208
221
|
}
|
|
209
222
|
}, null);
|
|
210
223
|
}
|
|
@@ -216,7 +229,7 @@ const MIN_PARTIAL_BYTES = 64;
|
|
|
216
229
|
/** A partial-frame buffer larger than this is released once drained, so one
|
|
217
230
|
* large frame does not pin its memory for the rest of the session. */
|
|
218
231
|
const RETAIN_BYTES = 65536;
|
|
219
|
-
function createFrameDecoder(protocol) {
|
|
232
|
+
function createFrameDecoder(protocol, onRejected) {
|
|
220
233
|
/** Partial-frame storage: the first `length` bytes are buffered data. Empty
|
|
221
234
|
* whenever nothing is buffered, so a chunk of whole frames is decoded
|
|
222
235
|
* straight from the caller's bytes without being copied in first. */
|
|
@@ -293,6 +306,10 @@ function createFrameDecoder(protocol) {
|
|
|
293
306
|
try {
|
|
294
307
|
out.push(protocol.decode(frame));
|
|
295
308
|
} catch (err) {
|
|
309
|
+
if (err instanceof FrameContentError) {
|
|
310
|
+
onRejected?.(err);
|
|
311
|
+
continue;
|
|
312
|
+
}
|
|
296
313
|
fail(err instanceof Error ? err : new Error(String(err)));
|
|
297
314
|
return out;
|
|
298
315
|
}
|
|
@@ -316,7 +333,8 @@ function createFrameDecoder(protocol) {
|
|
|
316
333
|
// core/messages/frame-channel.ts
|
|
317
334
|
function createFrameChannel(options) {
|
|
318
335
|
const { name, protocol, router, onMalformed } = options;
|
|
319
|
-
|
|
336
|
+
let rejected = [];
|
|
337
|
+
const decoder = createFrameDecoder(protocol, (err) => rejected.push(err));
|
|
320
338
|
const health = onMalformed.kind === "tolerate" ? new ChannelHealth(onMalformed.maxConsecutiveFailures) : null;
|
|
321
339
|
const gate = options.inbound ? createInboundGate({
|
|
322
340
|
high: options.inbound.maxPending,
|
|
@@ -325,6 +343,16 @@ function createFrameChannel(options) {
|
|
|
325
343
|
resume: options.inbound.resume
|
|
326
344
|
}) : null;
|
|
327
345
|
let stopped = false;
|
|
346
|
+
/** Writes one frame; a failing write is logged, never thrown into a promise
|
|
347
|
+
* chain where it would become an unhandled rejection. */
|
|
348
|
+
function safeWrite(frame) {
|
|
349
|
+
try {
|
|
350
|
+
options.write(frame);
|
|
351
|
+
} catch (err) {
|
|
352
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
353
|
+
console.error(`${name} write failed: ${reason}`);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
328
356
|
/** Handles a malformed chunk per the channel's policy. */
|
|
329
357
|
function malformed(reason) {
|
|
330
358
|
console.error(`${name} malformed frame dropped: ${reason}`);
|
|
@@ -340,26 +368,79 @@ function createFrameChannel(options) {
|
|
|
340
368
|
}
|
|
341
369
|
decoder.clear();
|
|
342
370
|
}
|
|
371
|
+
/** Answers a frame whose content was rejected, when its routing fields
|
|
372
|
+
* survived: a request gets a `FRAME_INVALID` response, and a host response
|
|
373
|
+
* fails the call waiting on it. Nothing else is echoed back. */
|
|
374
|
+
function answerRejected(err) {
|
|
375
|
+
console.error(`${name} invalid frame skipped: ${err.message.slice(0, 200)}`);
|
|
376
|
+
const recovered = err.recovered;
|
|
377
|
+
const requestId = recovered?.requestId;
|
|
378
|
+
if (!recovered || !requestId) return;
|
|
379
|
+
const error = {
|
|
380
|
+
code: ErrorCode.FRAME_INVALID,
|
|
381
|
+
message: "Frame could not be decoded"
|
|
382
|
+
};
|
|
383
|
+
if (recovered.type === "HOST_INVOKE_RESPONSE" || recovered.type === "HOST_CAPABILITIES_RESPONSE") {
|
|
384
|
+
const header = recovered.type === "HOST_CAPABILITIES_RESPONSE" ? {
|
|
385
|
+
type: "HOST_CAPABILITIES_RESPONSE",
|
|
386
|
+
requestId,
|
|
387
|
+
capabilities: [],
|
|
388
|
+
error
|
|
389
|
+
} : {
|
|
390
|
+
type: "HOST_INVOKE_RESPONSE",
|
|
391
|
+
requestId,
|
|
392
|
+
pluginId: recovered.pluginId ?? "",
|
|
393
|
+
event: recovered.event ?? "",
|
|
394
|
+
error
|
|
395
|
+
};
|
|
396
|
+
options.intercept?.({
|
|
397
|
+
type: MessageType.ENVELOPE,
|
|
398
|
+
header,
|
|
399
|
+
payload: /* @__PURE__ */ new Uint8Array(0)
|
|
400
|
+
});
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
if (recovered.type === "INVOKE_REQUEST") safeWrite(encodeResponse(protocol, {
|
|
404
|
+
type: "INVOKE_RESPONSE",
|
|
405
|
+
pluginId: recovered.pluginId ?? "",
|
|
406
|
+
event: recovered.event ?? "",
|
|
407
|
+
requestId,
|
|
408
|
+
error
|
|
409
|
+
}));
|
|
410
|
+
}
|
|
411
|
+
/** The answer to an invoke whose routing threw. The detail stays in the log;
|
|
412
|
+
* the peer gets a fixed message. */
|
|
413
|
+
function routingFailure(header) {
|
|
414
|
+
if (header.type === "INVOKE_REQUEST" && typeof header.requestId === "string" && typeof header.pluginId === "string" && typeof header.event === "string") safeWrite(encodeResponse(protocol, {
|
|
415
|
+
type: "INVOKE_RESPONSE",
|
|
416
|
+
pluginId: header.pluginId,
|
|
417
|
+
event: header.event,
|
|
418
|
+
requestId: header.requestId,
|
|
419
|
+
error: {
|
|
420
|
+
code: ErrorCode.PLUGIN_ERROR,
|
|
421
|
+
message: `${header.pluginId}.${header.event} failed`
|
|
422
|
+
}
|
|
423
|
+
}));
|
|
424
|
+
}
|
|
343
425
|
function route(message) {
|
|
344
|
-
const work = router.route(message.header, message.payload).then((response) => {
|
|
345
|
-
if (response)
|
|
346
|
-
}
|
|
426
|
+
const work = Promise.resolve().then(() => router.route(message.header, message.payload, { channel: name })).then((response) => {
|
|
427
|
+
if (response) safeWrite(encodeResponse(protocol, response));
|
|
428
|
+
}, (err) => {
|
|
347
429
|
const reason = err instanceof Error ? err.message : String(err);
|
|
348
430
|
console.error(`${name} routing failed: ${reason}`);
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
event: header.event,
|
|
354
|
-
requestId: header.requestId,
|
|
355
|
-
error: {
|
|
356
|
-
code: ErrorCode.PLUGIN_ERROR,
|
|
357
|
-
message: `${header.pluginId}.${header.event} failed: ${reason}`
|
|
358
|
-
}
|
|
359
|
-
}));
|
|
431
|
+
routingFailure(message.header);
|
|
432
|
+
}).catch((err) => {
|
|
433
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
434
|
+
console.error(`${name} response failed: ${reason}`);
|
|
360
435
|
});
|
|
361
436
|
gate?.track(work);
|
|
362
437
|
}
|
|
438
|
+
function handle(messages) {
|
|
439
|
+
for (const message of messages) {
|
|
440
|
+
if (options.intercept?.(message)) continue;
|
|
441
|
+
route(message);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
363
444
|
return {
|
|
364
445
|
push(chunk) {
|
|
365
446
|
if (stopped) return;
|
|
@@ -376,16 +457,17 @@ function createFrameChannel(options) {
|
|
|
376
457
|
return;
|
|
377
458
|
}
|
|
378
459
|
if (bytes.byteLength === 0) return;
|
|
460
|
+
rejected = [];
|
|
379
461
|
const messages = decoder.push(bytes);
|
|
462
|
+
const skipped = rejected;
|
|
463
|
+
rejected = [];
|
|
464
|
+
handle(messages);
|
|
465
|
+
for (const err of skipped) answerRejected(err);
|
|
380
466
|
if (decoder.error) {
|
|
381
467
|
malformed(decoder.error.message);
|
|
382
468
|
return;
|
|
383
469
|
}
|
|
384
470
|
health?.noteSuccess();
|
|
385
|
-
for (const message of messages) {
|
|
386
|
-
if (options.intercept?.(message)) continue;
|
|
387
|
-
route(message);
|
|
388
|
-
}
|
|
389
471
|
},
|
|
390
472
|
close() {
|
|
391
473
|
stopped = true;
|
|
@@ -401,9 +483,24 @@ const MAX_CONCURRENT_HOST_CALLS = 1024;
|
|
|
401
483
|
/** Sane default for a host invoke: five-minute waits let a single stalled host
|
|
402
484
|
* call pin a slot indefinitely, so we default to 30s instead. */
|
|
403
485
|
const DEFAULT_HOST_INVOKE_TIMEOUT_MS = 3e4;
|
|
486
|
+
/** App-scoped error code a host handler may return (`app.photos/not-found`). */
|
|
487
|
+
const APP_ERROR_CODE = /^[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)+\/[A-Za-z0-9._-]+$/;
|
|
488
|
+
const MAX_HOST_ERROR_CODE_LENGTH = 64;
|
|
489
|
+
const MAX_HOST_ERROR_MESSAGE_LENGTH = 512;
|
|
490
|
+
/** The host's error as the page may see it: a canonical code or an app-scoped
|
|
491
|
+
* one passes, anything else becomes `HOST_ERROR`; the message is bounded. */
|
|
492
|
+
function sanitizeHostError(error) {
|
|
493
|
+
if (!error) return void 0;
|
|
494
|
+
return {
|
|
495
|
+
code: isCanonicalErrorCode(error.code) || error.code.length <= MAX_HOST_ERROR_CODE_LENGTH && APP_ERROR_CODE.test(error.code) ? error.code : ErrorCode.HOST_ERROR,
|
|
496
|
+
message: error.message.slice(0, MAX_HOST_ERROR_MESSAGE_LENGTH)
|
|
497
|
+
};
|
|
498
|
+
}
|
|
404
499
|
function createHostIpcBridge(config) {
|
|
405
500
|
const { ipc, protocol, platform } = config;
|
|
406
501
|
const pending = /* @__PURE__ */ new Map();
|
|
502
|
+
/** Set by `close()`: every later call rejects at once with this reason. */
|
|
503
|
+
let closedReason = null;
|
|
407
504
|
function track(requestId, slot) {
|
|
408
505
|
if (pending.size >= MAX_CONCURRENT_HOST_CALLS) {
|
|
409
506
|
const oldest = pending.keys().next().value;
|
|
@@ -426,10 +523,14 @@ function createHostIpcBridge(config) {
|
|
|
426
523
|
}
|
|
427
524
|
function waitFor(requestId, expectedType, timeoutMs) {
|
|
428
525
|
return new Promise((resolve, reject) => {
|
|
526
|
+
if (closedReason !== null) {
|
|
527
|
+
reject(new Error(closedReason));
|
|
528
|
+
return;
|
|
529
|
+
}
|
|
429
530
|
const timer = setTimeout(() => {
|
|
430
531
|
pending.delete(requestId);
|
|
431
|
-
reject(
|
|
432
|
-
}, timeoutMs);
|
|
532
|
+
reject(new CoreError(ErrorCode.TIMEOUT, `Host IPC timeout waiting for ${String(expectedType)} (${requestId})`));
|
|
533
|
+
}, timerMs(timeoutMs, DEFAULT_HOST_INVOKE_TIMEOUT_MS));
|
|
433
534
|
track(requestId, {
|
|
434
535
|
timer,
|
|
435
536
|
resolve: (h) => {
|
|
@@ -462,6 +563,18 @@ function createHostIpcBridge(config) {
|
|
|
462
563
|
return true;
|
|
463
564
|
}
|
|
464
565
|
return {
|
|
566
|
+
/** Stops the bridge (the runtime is closing): clears every pending timer,
|
|
567
|
+
* rejects every pending call with `reason`, and makes later calls reject
|
|
568
|
+
* at once instead of writing to a dead channel. */
|
|
569
|
+
close(reason = "host bridge closed") {
|
|
570
|
+
closedReason = reason;
|
|
571
|
+
const slots = [...pending.values()];
|
|
572
|
+
pending.clear();
|
|
573
|
+
for (const slot of slots) {
|
|
574
|
+
clearTimeout(slot.timer);
|
|
575
|
+
slot.reject(new Error(reason));
|
|
576
|
+
}
|
|
577
|
+
},
|
|
465
578
|
tryConsumeDownstream: consumeDownstream,
|
|
466
579
|
tryConsumeDownstreamFromHost(raw) {
|
|
467
580
|
let msg;
|
|
@@ -475,6 +588,7 @@ function createHostIpcBridge(config) {
|
|
|
475
588
|
return consumeDownstream(msg);
|
|
476
589
|
},
|
|
477
590
|
async queryCapabilities(timeoutMs = 5e3) {
|
|
591
|
+
if (closedReason !== null) throw new Error(closedReason);
|
|
478
592
|
const requestId = createRequestId(platform);
|
|
479
593
|
const promise = waitFor(requestId, "HOST_CAPABILITIES_RESPONSE", timeoutMs);
|
|
480
594
|
const header = {
|
|
@@ -482,12 +596,18 @@ function createHostIpcBridge(config) {
|
|
|
482
596
|
requestId
|
|
483
597
|
};
|
|
484
598
|
ipc.write(toIpcChunk(protocol.encode(MessageType.ENVELOPE, header, null)));
|
|
485
|
-
|
|
599
|
+
const response = await promise;
|
|
600
|
+
if (response.error) throw new CoreError(response.error.code, response.error.message);
|
|
601
|
+
return response.capabilities ?? [];
|
|
486
602
|
},
|
|
487
|
-
|
|
603
|
+
/** Runs `header` on the host. `timeoutMs` bounds the wait (default
|
|
604
|
+
* 30 s); a user-mediated call (picker, camera, permission prompt) passes
|
|
605
|
+
* its own, longer deadline. */
|
|
606
|
+
async invokeOnHost(header, payload, timeoutMs) {
|
|
607
|
+
if (closedReason !== null) throw new Error(closedReason);
|
|
488
608
|
if (!header.requestId) return null;
|
|
489
609
|
const requestId = createRequestId(platform);
|
|
490
|
-
const promise = waitFor(requestId, "HOST_INVOKE_RESPONSE", timeoutMs);
|
|
610
|
+
const promise = waitFor(requestId, "HOST_INVOKE_RESPONSE", timerMs(timeoutMs, DEFAULT_HOST_INVOKE_TIMEOUT_MS));
|
|
491
611
|
const hostHeader = {
|
|
492
612
|
type: "HOST_INVOKE_REQUEST",
|
|
493
613
|
requestId,
|
|
@@ -499,17 +619,17 @@ function createHostIpcBridge(config) {
|
|
|
499
619
|
const hostResp = await promise;
|
|
500
620
|
return {
|
|
501
621
|
type: "INVOKE_RESPONSE",
|
|
502
|
-
pluginId:
|
|
503
|
-
event:
|
|
622
|
+
pluginId: header.pluginId,
|
|
623
|
+
event: header.event,
|
|
504
624
|
requestId: header.requestId,
|
|
505
625
|
result: hostResp.result,
|
|
506
|
-
error: hostResp.error
|
|
626
|
+
error: sanitizeHostError(hostResp.error)
|
|
507
627
|
};
|
|
508
628
|
}
|
|
509
629
|
};
|
|
510
630
|
}
|
|
511
631
|
// core/logs/capture.ts
|
|
512
|
-
const LEVEL_RANK = {
|
|
632
|
+
const LEVEL_RANK$1 = {
|
|
513
633
|
debug: 0,
|
|
514
634
|
info: 1,
|
|
515
635
|
warn: 2,
|
|
@@ -524,9 +644,15 @@ function safeStringify(value) {
|
|
|
524
644
|
return String(value);
|
|
525
645
|
}
|
|
526
646
|
}
|
|
647
|
+
/** Longest captured backend message, in UTF-16 code units. The ring holds a
|
|
648
|
+
* fixed number of entries, so this (with the ingest caps in `routes.ts`) is
|
|
649
|
+
* what bounds its memory: a backend line can echo page-supplied text (a
|
|
650
|
+
* plugin error, a rejected header), and must not pin capacity × that. */
|
|
651
|
+
const MAX_CAPTURED_MESSAGE_CHARS = 16384;
|
|
527
652
|
function formatArgs(args) {
|
|
528
653
|
if (args.length === 0) return "";
|
|
529
|
-
|
|
654
|
+
const message = args.map((a) => safeStringify(a)).join(" ");
|
|
655
|
+
return message.length > 16384 ? `${message.slice(0, MAX_CAPTURED_MESSAGE_CHARS)}…` : message;
|
|
530
656
|
}
|
|
531
657
|
/**
|
|
532
658
|
* Installs console interception at startup: binds the original console methods,
|
|
@@ -535,7 +661,7 @@ function formatArgs(args) {
|
|
|
535
661
|
* seam can never break boot or swallow the consumer's own log call.
|
|
536
662
|
*/
|
|
537
663
|
function installConsoleCapture(store, source = "backend", options = {}) {
|
|
538
|
-
const minRank = LEVEL_RANK[options.minLevel ?? "debug"];
|
|
664
|
+
const minRank = LEVEL_RANK$1[options.minLevel ?? "debug"];
|
|
539
665
|
const original = {
|
|
540
666
|
debug: console.debug,
|
|
541
667
|
log: console.log,
|
|
@@ -544,7 +670,7 @@ function installConsoleCapture(store, source = "backend", options = {}) {
|
|
|
544
670
|
error: console.error
|
|
545
671
|
};
|
|
546
672
|
const wrap = (method, level) => {
|
|
547
|
-
const recorded = LEVEL_RANK[level] >= minRank;
|
|
673
|
+
const recorded = LEVEL_RANK$1[level] >= minRank;
|
|
548
674
|
return (...args) => {
|
|
549
675
|
if (recorded) try {
|
|
550
676
|
store.append({
|
|
@@ -577,8 +703,29 @@ function installConsoleCapture(store, source = "backend", options = {}) {
|
|
|
577
703
|
};
|
|
578
704
|
}
|
|
579
705
|
// core/server/loopback-gate.ts
|
|
706
|
+
/** Default lifetime of an unredeemed bootstrap nonce, counted from the first
|
|
707
|
+
* public request (the host loading the page) in running time: the clock
|
|
708
|
+
* pauses while the worklet is suspended (`pauseBootstrapClock`), so an app
|
|
709
|
+
* backgrounded between the page load and `/login` still logs in on resume. A
|
|
710
|
+
* nonce still unspent after two running minutes is one the page never used:
|
|
711
|
+
* it must not stay a live credential for the whole process lifetime. A reload
|
|
712
|
+
* after that logs in with the surviving session cookie, not the nonce. */
|
|
713
|
+
const BOOTSTRAP_TTL_MS = 12e4;
|
|
714
|
+
/** Upper bound for `bootstrapTtlMs`. */
|
|
715
|
+
const BOOTSTRAP_TTL_MAX_MS = 6e5;
|
|
716
|
+
/** Lifetime of a nonce whose page never loaded at all (no public request),
|
|
717
|
+
* counted from `bind` in running time. */
|
|
718
|
+
const BOOTSTRAP_UNLOADED_TTL_MS = 6e5;
|
|
580
719
|
const COOKIE_PREFIX = "bare_session";
|
|
581
720
|
const ORIGIN_PATTERN = /^https?:\/\/[^/?#\s]+$/;
|
|
721
|
+
/** `Sec-Fetch-Site` values a credentialed request may carry. Cookies are
|
|
722
|
+
* scoped to the host, not the port (RFC 6265 §8.5), so a page served from
|
|
723
|
+
* another port on `127.0.0.1` is *same-site* with this server: `SameSite=Strict`
|
|
724
|
+
* still attaches the session cookie to its no-`Origin` GETs (`<img>`,
|
|
725
|
+
* `<video>`, navigations). Fetch metadata names that case, so it is refused. A
|
|
726
|
+
* client that sends no `Sec-Fetch-Site` (a non-browser client, an older
|
|
727
|
+
* WebView) is judged by the Host/Origin rule alone. */
|
|
728
|
+
const ALLOWED_FETCH_SITES = /* @__PURE__ */ new Set(["same-origin", "none"]);
|
|
582
729
|
/** Reads the token from the `X-Bare-Token` request header (parser-lowercased).
|
|
583
730
|
* `fetch`-based non-browser clients that cannot carry cookies use this. It
|
|
584
731
|
* travels the cleartext loopback like the cookie, and is only trusted from an
|
|
@@ -637,13 +784,52 @@ function createLoopbackGate(options) {
|
|
|
637
784
|
for (const origin of options.allowedOrigins ?? []) if (!ORIGIN_PATTERN.test(origin)) throw new Error(`allowedOrigins entry is not a bare origin (scheme://host[:port]): '${origin}'`);
|
|
638
785
|
const token = options.token ?? randomSecret();
|
|
639
786
|
const cookieValue = sessionNonce(token);
|
|
787
|
+
const requestedTtl = options.bootstrapTtlMs;
|
|
788
|
+
const bootstrapTtlMs = typeof requestedTtl === "number" && Number.isFinite(requestedTtl) && requestedTtl > 0 ? Math.min(requestedTtl, BOOTSTRAP_TTL_MAX_MS) : BOOTSTRAP_TTL_MS;
|
|
789
|
+
const unloadedTtlMs = Math.max(BOOTSTRAP_UNLOADED_TTL_MS, bootstrapTtlMs);
|
|
640
790
|
let bootstrapNonce = randomSecret();
|
|
791
|
+
/** Running-time clock: wall time minus the time spent suspended. */
|
|
792
|
+
let pausedAt = null;
|
|
793
|
+
let pausedTotal = 0;
|
|
794
|
+
const runningNow = () => (pausedAt ?? Date.now()) - pausedTotal;
|
|
795
|
+
/** Running time at `bind` and at the first public request (null until). */
|
|
796
|
+
let boundAt = null;
|
|
797
|
+
let firstPublicAt = null;
|
|
641
798
|
/** The most recently spent bootstrap nonce, kept only to answer replays of
|
|
642
799
|
* it with 409 (valid once but consumed) instead of 401 (bad credential). */
|
|
643
800
|
let spentBootstrapNonce = null;
|
|
644
801
|
let allowedHosts = /* @__PURE__ */ new Set();
|
|
645
802
|
let allowedOrigins = /* @__PURE__ */ new Set();
|
|
803
|
+
const explicitOrigins = new Set(options.allowedOrigins ?? []);
|
|
646
804
|
let cookieName = COOKIE_PREFIX;
|
|
805
|
+
/** The nonce, or null once it is spent or has expired unredeemed. An expired
|
|
806
|
+
* nonce is dropped for good, so it can never come back to life. */
|
|
807
|
+
function liveNonce() {
|
|
808
|
+
if (bootstrapNonce !== null && boundAt !== null) {
|
|
809
|
+
const now = runningNow();
|
|
810
|
+
if (firstPublicAt !== null ? now - firstPublicAt >= bootstrapTtlMs : now - boundAt >= unloadedTtlMs) {
|
|
811
|
+
console.warn(`[loopback] bootstrap nonce expired unredeemed (${firstPublicAt !== null ? `${bootstrapTtlMs}ms after the page load` : `${unloadedTtlMs}ms with no page load`})`);
|
|
812
|
+
bootstrapNonce = null;
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
return bootstrapNonce;
|
|
816
|
+
}
|
|
817
|
+
/** The cross-port rule (see `ALLOWED_FETCH_SITES`). Only applies with auth
|
|
818
|
+
* on: it protects the session credential, and with auth off (dev) there is
|
|
819
|
+
* none, while the Vite dev page legitimately loads backend media
|
|
820
|
+
* cross-site. */
|
|
821
|
+
function checkFetchSite(headers) {
|
|
822
|
+
if (!auth) return { ok: true };
|
|
823
|
+
const origin = headers["origin"];
|
|
824
|
+
if (typeof origin === "string" && explicitOrigins.has(origin)) return { ok: true };
|
|
825
|
+
const site = headers["sec-fetch-site"];
|
|
826
|
+
if (site === void 0 || ALLOWED_FETCH_SITES.has(String(site))) return { ok: true };
|
|
827
|
+
return {
|
|
828
|
+
ok: false,
|
|
829
|
+
status: 403,
|
|
830
|
+
reason: `cross-site request (Sec-Fetch-Site: ${String(site)})`
|
|
831
|
+
};
|
|
832
|
+
}
|
|
647
833
|
function hasCredential(headers) {
|
|
648
834
|
if (!auth) return true;
|
|
649
835
|
if (secretEquals(tokenFromHeaders(headers) ?? "", token)) return true;
|
|
@@ -684,6 +870,7 @@ function createLoopbackGate(options) {
|
|
|
684
870
|
const port = hostPort.slice(hostPort.lastIndexOf(":") + 1);
|
|
685
871
|
allowedHosts = /* @__PURE__ */ new Set([hostPort, ...loopbackHosts(port)]);
|
|
686
872
|
cookieName = sessionCookieName(port);
|
|
873
|
+
boundAt = runningNow();
|
|
687
874
|
allowedOrigins = /* @__PURE__ */ new Set([
|
|
688
875
|
origin,
|
|
689
876
|
...loopbackHosts(port).map((h) => `http://${h}`),
|
|
@@ -691,11 +878,17 @@ function createLoopbackGate(options) {
|
|
|
691
878
|
]);
|
|
692
879
|
},
|
|
693
880
|
token: () => token,
|
|
694
|
-
bootstrap: () =>
|
|
881
|
+
bootstrap: () => liveNonce() ?? "",
|
|
695
882
|
admitRequest(headers, resource) {
|
|
696
883
|
const origin = checkOrigin(headers, false);
|
|
697
884
|
if (!origin.ok) return origin;
|
|
698
|
-
if (resource === "
|
|
885
|
+
if (resource === "public") {
|
|
886
|
+
if (boundAt !== null && firstPublicAt === null && liveNonce() !== null) firstPublicAt = runningNow();
|
|
887
|
+
return { ok: true };
|
|
888
|
+
}
|
|
889
|
+
const site = checkFetchSite(headers);
|
|
890
|
+
if (!site.ok) return site;
|
|
891
|
+
if (!hasCredential(headers)) return {
|
|
699
892
|
ok: false,
|
|
700
893
|
status: 401,
|
|
701
894
|
reason: "unauthorized"
|
|
@@ -705,6 +898,8 @@ function createLoopbackGate(options) {
|
|
|
705
898
|
admitUpgrade(headers) {
|
|
706
899
|
const origin = checkOrigin(headers, auth);
|
|
707
900
|
if (!origin.ok) return origin;
|
|
901
|
+
const site = checkFetchSite(headers);
|
|
902
|
+
if (!site.ok) return site;
|
|
708
903
|
if (!hasCredential(headers)) return {
|
|
709
904
|
ok: false,
|
|
710
905
|
status: 401,
|
|
@@ -718,14 +913,15 @@ function createLoopbackGate(options) {
|
|
|
718
913
|
cookie: null
|
|
719
914
|
};
|
|
720
915
|
const credential = body.trim();
|
|
721
|
-
const
|
|
916
|
+
const nonce = liveNonce();
|
|
917
|
+
const byBootstrap = nonce !== null && secretEquals(credential, nonce);
|
|
722
918
|
const bySession = hasCredential(headers);
|
|
723
919
|
if (!byBootstrap && !bySession) return {
|
|
724
920
|
ok: false,
|
|
725
921
|
status: spentBootstrapNonce !== null && secretEquals(credential, spentBootstrapNonce) ? 409 : 401
|
|
726
922
|
};
|
|
727
923
|
if (byBootstrap) {
|
|
728
|
-
spentBootstrapNonce =
|
|
924
|
+
spentBootstrapNonce = nonce;
|
|
729
925
|
bootstrapNonce = null;
|
|
730
926
|
}
|
|
731
927
|
return {
|
|
@@ -733,6 +929,14 @@ function createLoopbackGate(options) {
|
|
|
733
929
|
cookie: `${cookieName}=${cookieValue}; HttpOnly; SameSite=Strict; Path=/`
|
|
734
930
|
};
|
|
735
931
|
},
|
|
932
|
+
pauseBootstrapClock() {
|
|
933
|
+
if (pausedAt === null) pausedAt = Date.now();
|
|
934
|
+
},
|
|
935
|
+
resumeBootstrapClock() {
|
|
936
|
+
if (pausedAt === null) return;
|
|
937
|
+
pausedTotal += Math.max(0, Date.now() - pausedAt);
|
|
938
|
+
pausedAt = null;
|
|
939
|
+
},
|
|
736
940
|
socketSource(headers) {
|
|
737
941
|
const host = headers["host"];
|
|
738
942
|
return `ws://${typeof host === "string" ? host : ""}`;
|
|
@@ -740,6 +944,11 @@ function createLoopbackGate(options) {
|
|
|
740
944
|
};
|
|
741
945
|
}
|
|
742
946
|
// core/server/protocol-socket.ts
|
|
947
|
+
/** WebSocket close code sent to a protocol socket evicted by a newer one: the
|
|
948
|
+
* page reads it as "another document took over" and does not fast-reconnect
|
|
949
|
+
* (which would evict the newer socket in turn). */
|
|
950
|
+
const REPLACED_CLOSE_CODE = 4001;
|
|
951
|
+
const REPLACED_CLOSE_REASON = "replaced";
|
|
743
952
|
function createProtocolSocketSlot(options) {
|
|
744
953
|
const handlers = [];
|
|
745
954
|
let active = null;
|
|
@@ -788,8 +997,13 @@ function createProtocolSocketSlot(options) {
|
|
|
788
997
|
raw.destroy();
|
|
789
998
|
}
|
|
790
999
|
});
|
|
1000
|
+
/** Set once a newer socket took the slot: the close handshake can take
|
|
1001
|
+
* a moment, and no frame read during it may still reach a plugin. */
|
|
1002
|
+
let evicted = false;
|
|
791
1003
|
const client = {
|
|
792
|
-
on: (event, listener) => raw.on(
|
|
1004
|
+
on: (event, listener) => event === "data" ? raw.on("data", (chunk) => {
|
|
1005
|
+
if (!evicted) listener(chunk);
|
|
1006
|
+
}) : raw.on(event, listener),
|
|
793
1007
|
write: (data) => writer.write(data),
|
|
794
1008
|
destroy: () => raw.destroy(),
|
|
795
1009
|
pause: () => raw.pause(),
|
|
@@ -798,12 +1012,21 @@ function createProtocolSocketSlot(options) {
|
|
|
798
1012
|
const previous = active;
|
|
799
1013
|
active = {
|
|
800
1014
|
client,
|
|
801
|
-
writer
|
|
1015
|
+
writer,
|
|
1016
|
+
evict() {
|
|
1017
|
+
evicted = true;
|
|
1018
|
+
writer.clear();
|
|
1019
|
+
try {
|
|
1020
|
+
raw.close(REPLACED_CLOSE_CODE, REPLACED_CLOSE_REASON);
|
|
1021
|
+
} catch {
|
|
1022
|
+
raw.destroy();
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
802
1025
|
};
|
|
803
1026
|
activeSince = Date.now();
|
|
804
1027
|
if (previous) {
|
|
805
1028
|
console.warn("[loopback] replaced the existing protocol socket");
|
|
806
|
-
previous.
|
|
1029
|
+
previous.evict();
|
|
807
1030
|
}
|
|
808
1031
|
raw.on("close", () => {
|
|
809
1032
|
writer.clear();
|
|
@@ -865,6 +1088,112 @@ function mimeTypeFor(filePath) {
|
|
|
865
1088
|
const ext = filePath.split(".").pop()?.toLowerCase() ?? "";
|
|
866
1089
|
return MIME_BY_EXTENSION[ext] ?? "application/octet-stream";
|
|
867
1090
|
}
|
|
1091
|
+
function closeQuietly(fd) {
|
|
1092
|
+
try {
|
|
1093
|
+
fs.closeSync(fd);
|
|
1094
|
+
} catch {}
|
|
1095
|
+
}
|
|
1096
|
+
/** Opens `realPath` (already resolved by `realpathSync` and checked to lie in
|
|
1097
|
+
* its mount) and proves the descriptor is that file. A path component swapped
|
|
1098
|
+
* for a symlink between the check and the open would make the open land
|
|
1099
|
+
* elsewhere, so after opening the real path must still resolve to itself and
|
|
1100
|
+
* its `lstat` must be the opened inode. Returns null (descriptor closed) when
|
|
1101
|
+
* anything moved, or when it is not a regular file. */
|
|
1102
|
+
function openVerified(realPath) {
|
|
1103
|
+
let fd;
|
|
1104
|
+
try {
|
|
1105
|
+
fd = fs.openSync(realPath, "r");
|
|
1106
|
+
} catch {
|
|
1107
|
+
return null;
|
|
1108
|
+
}
|
|
1109
|
+
try {
|
|
1110
|
+
const stat = fs.fstatSync(fd);
|
|
1111
|
+
if (!stat.isFile()) {
|
|
1112
|
+
closeQuietly(fd);
|
|
1113
|
+
return null;
|
|
1114
|
+
}
|
|
1115
|
+
if (fs.realpathSync(realPath) !== realPath) {
|
|
1116
|
+
console.warn(`[static-server] refused a file that moved while it was opened: ${realPath}`);
|
|
1117
|
+
closeQuietly(fd);
|
|
1118
|
+
return null;
|
|
1119
|
+
}
|
|
1120
|
+
const link = fs.lstatSync(realPath);
|
|
1121
|
+
if (!link.isFile() || link.ino !== stat.ino || link.dev !== stat.dev) {
|
|
1122
|
+
console.warn(`[static-server] refused a file that moved while it was opened: ${realPath}`);
|
|
1123
|
+
closeQuietly(fd);
|
|
1124
|
+
return null;
|
|
1125
|
+
}
|
|
1126
|
+
return {
|
|
1127
|
+
filePath: realPath,
|
|
1128
|
+
fd,
|
|
1129
|
+
stat
|
|
1130
|
+
};
|
|
1131
|
+
} catch {
|
|
1132
|
+
closeQuietly(fd);
|
|
1133
|
+
return null;
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
/** Whether a platform's default filesystem ignores case (and, on Apple,
|
|
1137
|
+
* Unicode normalization): APFS on macOS and iOS, NTFS on Windows. Android and
|
|
1138
|
+
* Linux filesystems are case-sensitive, so folding there would refuse
|
|
1139
|
+
* layouts that are fine (`/x/Media` next to `/x/media`). */
|
|
1140
|
+
function platformFoldsPathCase(platform) {
|
|
1141
|
+
return platform === "darwin" || platform === "ios" || platform === "win32";
|
|
1142
|
+
}
|
|
1143
|
+
/** The running platform: `Bare.platform` in the worklet, `process.platform`
|
|
1144
|
+
* under Node (tests, tooling). */
|
|
1145
|
+
function currentPlatform() {
|
|
1146
|
+
const bare = globalThis.Bare;
|
|
1147
|
+
if (typeof bare?.platform === "string") return bare.platform;
|
|
1148
|
+
return typeof process !== "undefined" ? process.platform : "";
|
|
1149
|
+
}
|
|
1150
|
+
/** A path in the form mount roots are compared in. `fold` lowercases and
|
|
1151
|
+
* NFC-normalizes it for a case-insensitive filesystem. */
|
|
1152
|
+
function comparablePath(p, fold) {
|
|
1153
|
+
return fold ? p.normalize("NFC").toLowerCase() : p;
|
|
1154
|
+
}
|
|
1155
|
+
/** A mount root's real path, or null while it does not exist (a root may be
|
|
1156
|
+
* created after it is mounted). */
|
|
1157
|
+
function realRoot(dirPath) {
|
|
1158
|
+
try {
|
|
1159
|
+
return fs.realpathSync(dirPath);
|
|
1160
|
+
} catch {
|
|
1161
|
+
return null;
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
/** The longest Origin/Host value echoed into a log line. */
|
|
1165
|
+
const MAX_LOGGED_REASON_CHARS = 200;
|
|
1166
|
+
/** Upgrade rejections logged per window; the rest are counted and reported
|
|
1167
|
+
* once when the window ends. Any website can trigger a rejected upgrade, so
|
|
1168
|
+
* without a limit one could evict every real diagnostic from the log ring. */
|
|
1169
|
+
const UPGRADE_REJECTION_LOG_LIMIT = 10;
|
|
1170
|
+
const UPGRADE_REJECTION_LOG_WINDOW_MS = 1e4;
|
|
1171
|
+
/** Rate limiter for upgrade-rejection log lines. Each window logs up to
|
|
1172
|
+
* `limit` lines; the first rejection of a later window first reports how
|
|
1173
|
+
* many were suppressed in the one before it. */
|
|
1174
|
+
function createRejectionLogger(log, options = {}) {
|
|
1175
|
+
const limit = options.limit ?? UPGRADE_REJECTION_LOG_LIMIT;
|
|
1176
|
+
const windowMs = options.windowMs ?? UPGRADE_REJECTION_LOG_WINDOW_MS;
|
|
1177
|
+
const now = options.now ?? Date.now;
|
|
1178
|
+
let windowStart = -Infinity;
|
|
1179
|
+
let logged = 0;
|
|
1180
|
+
let suppressed = 0;
|
|
1181
|
+
return (reason) => {
|
|
1182
|
+
const t = now();
|
|
1183
|
+
if (t - windowStart >= windowMs) {
|
|
1184
|
+
if (suppressed > 0) log(`[loopback] upgrade rejected: ${suppressed} more rejections suppressed`);
|
|
1185
|
+
windowStart = t;
|
|
1186
|
+
logged = 0;
|
|
1187
|
+
suppressed = 0;
|
|
1188
|
+
}
|
|
1189
|
+
if (logged >= limit) {
|
|
1190
|
+
suppressed++;
|
|
1191
|
+
return;
|
|
1192
|
+
}
|
|
1193
|
+
logged++;
|
|
1194
|
+
log(`[loopback] upgrade rejected: ${reason.length > MAX_LOGGED_REASON_CHARS ? `${reason.slice(0, MAX_LOGGED_REASON_CHARS)}…` : reason}`);
|
|
1195
|
+
};
|
|
1196
|
+
}
|
|
868
1197
|
/** Files under `assets/` whose name ends in an 8-character content hash before
|
|
869
1198
|
* the extension (the Vite/Rolldown default, e.g. `assets/main-DkY3x9qZ.js`)
|
|
870
1199
|
* are treated as content-addressed. Anything else — including `index.html` —
|
|
@@ -969,6 +1298,26 @@ function mountKey(mountPath) {
|
|
|
969
1298
|
function isLoopbackHost(host) {
|
|
970
1299
|
return host === "localhost" || host === "::1" || host === "[::1]" || /^127(\.\d{1,3}){3}$/.test(host);
|
|
971
1300
|
}
|
|
1301
|
+
/** Whether `candidate` lies strictly below `root` (not `root` itself). */
|
|
1302
|
+
function isStrictlyWithin(root, candidate) {
|
|
1303
|
+
return root !== candidate && isWithin(root, candidate);
|
|
1304
|
+
}
|
|
1305
|
+
/** Whether a response has already been ended by its handler. Node exposes
|
|
1306
|
+
* `writableEnded`; bare-http1 responses are streamx writables, whose state
|
|
1307
|
+
* says `ending` once `end()` has been called. */
|
|
1308
|
+
function responseEnded(res) {
|
|
1309
|
+
const r = res;
|
|
1310
|
+
return r.writableEnded === true || r.destroyed === true || r._writableState?.ending === true;
|
|
1311
|
+
}
|
|
1312
|
+
/** Drops every header a handler set before it failed, so a 500 carries only
|
|
1313
|
+
* the framework's own headers (never a handler's `Set-Cookie` or
|
|
1314
|
+
* `Content-Type`). Node has `removeHeader`; bare-http1 has a `headers`
|
|
1315
|
+
* setter. */
|
|
1316
|
+
function clearHeaders(res) {
|
|
1317
|
+
const r = res;
|
|
1318
|
+
if (typeof r.removeHeader === "function") for (const name of Object.keys(res.getHeaders())) r.removeHeader(name);
|
|
1319
|
+
else r.headers = {};
|
|
1320
|
+
}
|
|
972
1321
|
/** Whether `candidate` is `root` or lies below it. Both must be absolute,
|
|
973
1322
|
* normalized paths. */
|
|
974
1323
|
function isWithin(root, candidate) {
|
|
@@ -989,10 +1338,13 @@ function createLoopbackServer(options = {}) {
|
|
|
989
1338
|
const port = options.port ?? 0;
|
|
990
1339
|
const auth = options.auth ?? true;
|
|
991
1340
|
if (!auth && !isLoopbackHost(host)) throw new Error(`refusing to bind '${host}' with auth off: only a loopback address may serve without a credential`);
|
|
1341
|
+
const bindHost = host.replace(/^\[(.*)\]$/, "$1");
|
|
1342
|
+
const originHost = bindHost.includes(":") ? `[${bindHost}]` : bindHost;
|
|
992
1343
|
const gate = createLoopbackGate({
|
|
993
1344
|
auth,
|
|
994
1345
|
token: options.token,
|
|
995
|
-
allowedOrigins: options.allowedOrigins
|
|
1346
|
+
allowedOrigins: options.allowedOrigins,
|
|
1347
|
+
bootstrapTtlMs: options.bootstrapTtlMs
|
|
996
1348
|
});
|
|
997
1349
|
const slot = createProtocolSocketSlot({
|
|
998
1350
|
idleTimeoutMs: options.wsIdleTimeoutMs ?? 6e4,
|
|
@@ -1002,17 +1354,55 @@ function createLoopbackServer(options = {}) {
|
|
|
1002
1354
|
});
|
|
1003
1355
|
const fileMounts = /* @__PURE__ */ new Map();
|
|
1004
1356
|
const dirMounts = /* @__PURE__ */ new Map();
|
|
1357
|
+
const foldCase = options.foldPathCase ?? platformFoldsPathCase(currentPlatform());
|
|
1358
|
+
/** Directory mount key → its root in comparable form. Resolved once at
|
|
1359
|
+
* mount time instead of per request; a root that did not exist yet stays
|
|
1360
|
+
* null and is retried until it does, and a gated mount's own requests
|
|
1361
|
+
* refresh it (they resolve the root anyway). */
|
|
1362
|
+
const rootCache = /* @__PURE__ */ new Map();
|
|
1363
|
+
function cachedRoot(key) {
|
|
1364
|
+
let root = rootCache.get(key) ?? null;
|
|
1365
|
+
if (root === null) {
|
|
1366
|
+
const dirPath = dirMounts.get(key);
|
|
1367
|
+
const real = dirPath === void 0 ? null : realRoot(dirPath);
|
|
1368
|
+
if (real !== null) {
|
|
1369
|
+
root = comparablePath(real, foldCase);
|
|
1370
|
+
rootCache.set(key, root);
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
return root;
|
|
1374
|
+
}
|
|
1005
1375
|
const publicDirMounts = /* @__PURE__ */ new Set();
|
|
1006
1376
|
const routeHandlers = /* @__PURE__ */ new Map();
|
|
1007
1377
|
let originPromise = null;
|
|
1008
|
-
|
|
1378
|
+
const logUpgradeRejection = createRejectionLogger((line) => console.error(line));
|
|
1379
|
+
/** `Cross-Origin-Resource-Policy` stops another site embedding a gated
|
|
1380
|
+
* response (`<img>`, `<script>`) even if a credential rode along. CORP
|
|
1381
|
+
* governs no-cors embedding only, never a CORS `fetch`, so it does not
|
|
1382
|
+
* interact with the `allowedOrigins` exemptions in the gate.
|
|
1383
|
+
* - Auth off (dev): left off. The Vite dev page on `localhost:5173` loads
|
|
1384
|
+
* backend media cross-site, and there is no credential to protect.
|
|
1385
|
+
* - Auth on: `same-origin`, `allowedOrigins` or not. An allowed page's
|
|
1386
|
+
* embed could not authenticate anyway: from another site the
|
|
1387
|
+
* `SameSite=Strict` cookie is not sent, and from another loopback port
|
|
1388
|
+
* (same-site) the no-`Origin` request is refused by the gate's
|
|
1389
|
+
* `Sec-Fetch-Site` rule, since an embed cannot prove which page made it. */
|
|
1390
|
+
const resourcePolicy = auth ? { "Cross-Origin-Resource-Policy": "same-origin" } : {};
|
|
1391
|
+
/** Headers every framework-built response carries. */
|
|
1392
|
+
const BASE_HEADERS = {
|
|
1393
|
+
"Referrer-Policy": "no-referrer",
|
|
1394
|
+
"X-Content-Type-Options": "nosniff"
|
|
1395
|
+
};
|
|
1396
|
+
function writeError(res, status, message, extra = {}) {
|
|
1009
1397
|
if (res.headersSent) {
|
|
1010
1398
|
res.destroy();
|
|
1011
1399
|
return;
|
|
1012
1400
|
}
|
|
1013
1401
|
res.writeHead(status, {
|
|
1014
1402
|
"Content-Type": "text/plain",
|
|
1015
|
-
|
|
1403
|
+
...BASE_HEADERS,
|
|
1404
|
+
...resourcePolicy,
|
|
1405
|
+
...extra
|
|
1016
1406
|
});
|
|
1017
1407
|
res.end(message);
|
|
1018
1408
|
}
|
|
@@ -1021,6 +1411,8 @@ function createLoopbackServer(options = {}) {
|
|
|
1021
1411
|
function writeInternalError(res, context, err) {
|
|
1022
1412
|
const message = err instanceof Error ? err.message : String(err);
|
|
1023
1413
|
console.error(`[loopback] ${context} failed: ${message}`);
|
|
1414
|
+
if (responseEnded(res)) return;
|
|
1415
|
+
if (!res.headersSent) clearHeaders(res);
|
|
1024
1416
|
writeError(res, 500, "Internal Server Error");
|
|
1025
1417
|
}
|
|
1026
1418
|
function handleLogin(req, res) {
|
|
@@ -1033,12 +1425,16 @@ function createLoopbackServer(options = {}) {
|
|
|
1033
1425
|
const headers = {
|
|
1034
1426
|
"Content-Type": "text/plain",
|
|
1035
1427
|
"Cache-Control": "no-store",
|
|
1036
|
-
|
|
1428
|
+
...BASE_HEADERS,
|
|
1429
|
+
...resourcePolicy
|
|
1037
1430
|
};
|
|
1038
1431
|
if (verdict.cookie !== null) headers["Set-Cookie"] = verdict.cookie;
|
|
1039
1432
|
res.writeHead(200, headers);
|
|
1040
1433
|
res.end("ok");
|
|
1041
|
-
}, () =>
|
|
1434
|
+
}, () => {
|
|
1435
|
+
res.on("finish", () => req.destroy());
|
|
1436
|
+
writeError(res, 413, "Request Entity Too Large", { Connection: "close" });
|
|
1437
|
+
}).catch((err) => writeInternalError(res, "POST /login", err));
|
|
1042
1438
|
}
|
|
1043
1439
|
/** Resolves a request path to a file mount, or a directory mount + the path
|
|
1044
1440
|
* segments below it. Directory mounts win on longest-prefix match. */
|
|
@@ -1056,6 +1452,7 @@ function createLoopbackServer(options = {}) {
|
|
|
1056
1452
|
if (depth <= bestDepth) continue;
|
|
1057
1453
|
if (!prefixSegments.every((s, i) => segments[i] === s)) continue;
|
|
1058
1454
|
best = {
|
|
1455
|
+
key: prefix,
|
|
1059
1456
|
dirPath,
|
|
1060
1457
|
rel: segments.slice(depth),
|
|
1061
1458
|
public: publicDirMounts.has(prefix)
|
|
@@ -1082,22 +1479,50 @@ function createLoopbackServer(options = {}) {
|
|
|
1082
1479
|
console.debug(`[static-server] mount root ${mount.dirPath} is missing — 404`);
|
|
1083
1480
|
return null;
|
|
1084
1481
|
}
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1482
|
+
if (!mount.public) rootCache.set(mount.key, comparablePath(root, foldCase));
|
|
1483
|
+
const served = (file) => {
|
|
1484
|
+
if (file === null) return null;
|
|
1485
|
+
if (mount.public && insideGatedMount(mount.key, file.filePath)) {
|
|
1486
|
+
console.warn(`[static-server] refused a gated file through the public mount: ${file.filePath}`);
|
|
1487
|
+
closeQuietly(file.fd);
|
|
1488
|
+
return null;
|
|
1489
|
+
}
|
|
1490
|
+
return {
|
|
1491
|
+
...file,
|
|
1492
|
+
rel: path.relative(root, file.filePath).split(path.sep).join("/")
|
|
1493
|
+
};
|
|
1088
1494
|
};
|
|
1089
1495
|
if (mount.rel.length > 0) {
|
|
1090
|
-
const found = fileWithin(root, path.join(root, ...mount.rel));
|
|
1091
|
-
if (found) return
|
|
1496
|
+
const found = served(fileWithin(root, path.join(root, ...mount.rel)));
|
|
1497
|
+
if (found) return found;
|
|
1092
1498
|
if (!mount.public) return null;
|
|
1093
1499
|
const accept = headers["accept"];
|
|
1094
1500
|
if (typeof accept !== "string" || !accept.includes("text/html")) return null;
|
|
1095
1501
|
}
|
|
1096
1502
|
return served(fileWithin(root, path.join(root, "index.html")));
|
|
1097
1503
|
}
|
|
1098
|
-
/**
|
|
1099
|
-
*
|
|
1100
|
-
*
|
|
1504
|
+
/** Whether a file the public mount `publicKey` is about to serve lies in
|
|
1505
|
+
* a gated directory mount's root nested inside it. The public mount refuses
|
|
1506
|
+
* such a file even if the layout check in `mountDir` was sidestepped (a
|
|
1507
|
+
* root that became a symlink into the web app after it was mounted, a case
|
|
1508
|
+
* alias on a case-insensitive volume). A gated root that contains the whole
|
|
1509
|
+
* public root is skipped: everything the public mount serves is meant to be
|
|
1510
|
+
* public, and refusing it would take the app down. */
|
|
1511
|
+
function insideGatedMount(publicKey, realPath) {
|
|
1512
|
+
const candidate = comparablePath(realPath, foldCase);
|
|
1513
|
+
const publicRoot = cachedRoot(publicKey);
|
|
1514
|
+
for (const key of dirMounts.keys()) {
|
|
1515
|
+
if (publicDirMounts.has(key)) continue;
|
|
1516
|
+
const gatedRoot = cachedRoot(key);
|
|
1517
|
+
if (gatedRoot === null) continue;
|
|
1518
|
+
if (publicRoot !== null && isStrictlyWithin(gatedRoot, publicRoot)) continue;
|
|
1519
|
+
if (isWithin(gatedRoot, candidate)) return true;
|
|
1520
|
+
}
|
|
1521
|
+
return false;
|
|
1522
|
+
}
|
|
1523
|
+
/** `candidate` opened for serving when it exists, is a regular file, and
|
|
1524
|
+
* its real path stays inside `root`. A missing file is routine (every SPA
|
|
1525
|
+
* route, every missing asset), so it is not logged. */
|
|
1101
1526
|
function fileWithin(root, candidate) {
|
|
1102
1527
|
let real;
|
|
1103
1528
|
try {
|
|
@@ -1109,15 +1534,7 @@ function createLoopbackServer(options = {}) {
|
|
|
1109
1534
|
console.warn(`[static-server] refused a path that resolves outside its mount: ${candidate}`);
|
|
1110
1535
|
return null;
|
|
1111
1536
|
}
|
|
1112
|
-
|
|
1113
|
-
const stat = fs.statSync(real);
|
|
1114
|
-
return stat.isFile() ? {
|
|
1115
|
-
filePath: real,
|
|
1116
|
-
stat
|
|
1117
|
-
} : null;
|
|
1118
|
-
} catch {
|
|
1119
|
-
return null;
|
|
1120
|
-
}
|
|
1537
|
+
return openVerified(real);
|
|
1121
1538
|
}
|
|
1122
1539
|
/** Strict Content-Security-Policy for HTML documents served by the loopback
|
|
1123
1540
|
* server. Subresources stay same-origin; `connect-src` names the one
|
|
@@ -1132,24 +1549,15 @@ function createLoopbackServer(options = {}) {
|
|
|
1132
1549
|
* opened as a document, so a hostile file (an SVG with script) runs in an
|
|
1133
1550
|
* opaque, script-less sandbox instead of the app origin. */
|
|
1134
1551
|
const MOUNTED_FILE_CSP = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
|
|
1135
|
-
function serveFile(req, res,
|
|
1136
|
-
|
|
1137
|
-
if (knownStat) stat = knownStat;
|
|
1138
|
-
else try {
|
|
1139
|
-
stat = fs.statSync(filePath);
|
|
1140
|
-
} catch {
|
|
1141
|
-
console.debug(`[static-server] serveFile: stat failed for ${filePath} — 404`);
|
|
1142
|
-
writeError(res, 404, "Not found");
|
|
1143
|
-
return;
|
|
1144
|
-
}
|
|
1145
|
-
if (!stat.isFile()) {
|
|
1146
|
-
writeError(res, 404, "Not found");
|
|
1147
|
-
return;
|
|
1148
|
-
}
|
|
1552
|
+
function serveFile(req, res, file, cache = "no-store", sandboxed = false) {
|
|
1553
|
+
const { filePath, fd, stat } = file;
|
|
1149
1554
|
const contentType = mimeTypeFor(filePath);
|
|
1150
|
-
const
|
|
1151
|
-
|
|
1152
|
-
...sandboxed ? {
|
|
1555
|
+
const policyHeaders = {
|
|
1556
|
+
...BASE_HEADERS,
|
|
1557
|
+
...sandboxed ? {
|
|
1558
|
+
"Content-Security-Policy": MOUNTED_FILE_CSP,
|
|
1559
|
+
...resourcePolicy
|
|
1560
|
+
} : contentType === "text/html" ? { "Content-Security-Policy": cspFor(gate.socketSource(req.headers)) } : {}
|
|
1153
1561
|
};
|
|
1154
1562
|
const range = parseRange(req.headers["range"], stat.size);
|
|
1155
1563
|
if (range) {
|
|
@@ -1158,12 +1566,11 @@ function createLoopbackServer(options = {}) {
|
|
|
1158
1566
|
"Content-Range": `bytes ${range.start}-${range.end}/${stat.size}`,
|
|
1159
1567
|
"Content-Length": range.end - range.start + 1,
|
|
1160
1568
|
"Accept-Ranges": "bytes",
|
|
1161
|
-
...
|
|
1162
|
-
"Referrer-Policy": "no-referrer",
|
|
1569
|
+
...policyHeaders,
|
|
1163
1570
|
"Cache-Control": "no-store"
|
|
1164
1571
|
});
|
|
1165
1572
|
res.flushHeaders();
|
|
1166
|
-
pipeFile(res,
|
|
1573
|
+
pipeFile(res, file, range);
|
|
1167
1574
|
return;
|
|
1168
1575
|
}
|
|
1169
1576
|
const cacheHeaders = cache === "no-store" ? { "Cache-Control": "no-store" } : {
|
|
@@ -1171,9 +1578,10 @@ function createLoopbackServer(options = {}) {
|
|
|
1171
1578
|
ETag: etagFor(stat)
|
|
1172
1579
|
};
|
|
1173
1580
|
if (cache !== "no-store" && etagMatches(req.headers["if-none-match"], cacheHeaders.ETag)) {
|
|
1581
|
+
closeQuietly(fd);
|
|
1174
1582
|
res.writeHead(304, {
|
|
1175
1583
|
...cacheHeaders,
|
|
1176
|
-
|
|
1584
|
+
...BASE_HEADERS
|
|
1177
1585
|
});
|
|
1178
1586
|
res.end();
|
|
1179
1587
|
return;
|
|
@@ -1182,24 +1590,23 @@ function createLoopbackServer(options = {}) {
|
|
|
1182
1590
|
"Content-Type": contentType,
|
|
1183
1591
|
"Content-Length": stat.size,
|
|
1184
1592
|
"Accept-Ranges": "bytes",
|
|
1185
|
-
...
|
|
1186
|
-
"Referrer-Policy": "no-referrer",
|
|
1593
|
+
...policyHeaders,
|
|
1187
1594
|
...cacheHeaders
|
|
1188
1595
|
});
|
|
1189
1596
|
res.flushHeaders();
|
|
1190
|
-
pipeFile(res,
|
|
1597
|
+
pipeFile(res, file);
|
|
1191
1598
|
}
|
|
1192
|
-
/**
|
|
1193
|
-
*
|
|
1194
|
-
*
|
|
1195
|
-
* an unhandled error would crash the whole worklet. Headers are flushed
|
|
1599
|
+
/** Streams an opened file's bytes to the response from its descriptor (the
|
|
1600
|
+
* stream closes it), with an error handler: a read error must never become
|
|
1601
|
+
* an unhandled `'error'` that crashes the whole worklet. Headers are flushed
|
|
1196
1602
|
* before piping, so a mid-stream error aborts the response rather than
|
|
1197
1603
|
* writing a late status. */
|
|
1198
|
-
function pipeFile(res,
|
|
1199
|
-
const stream =
|
|
1604
|
+
function pipeFile(res, file, range) {
|
|
1605
|
+
const stream = fs.createReadStream(file.filePath, range ? {
|
|
1606
|
+
fd: file.fd,
|
|
1200
1607
|
start: range.start,
|
|
1201
1608
|
end: range.end
|
|
1202
|
-
}
|
|
1609
|
+
} : { fd: file.fd });
|
|
1203
1610
|
stream.on("error", (err) => {
|
|
1204
1611
|
if (!res.headersSent) {
|
|
1205
1612
|
writeError(res, err.code === "ENOENT" ? 404 : 500, "Failed to read file");
|
|
@@ -1209,6 +1616,32 @@ function createLoopbackServer(options = {}) {
|
|
|
1209
1616
|
});
|
|
1210
1617
|
stream.pipe(res);
|
|
1211
1618
|
}
|
|
1619
|
+
/** Opens a file mount's target. The host chose the path, so it is not
|
|
1620
|
+
* confined to a root, but it is still served from a verified descriptor so a
|
|
1621
|
+
* file evicted (or swapped) after the lookup is a 404, not a crash. */
|
|
1622
|
+
function openFileMount(filePath) {
|
|
1623
|
+
let real;
|
|
1624
|
+
try {
|
|
1625
|
+
real = fs.realpathSync(filePath);
|
|
1626
|
+
} catch {
|
|
1627
|
+
return null;
|
|
1628
|
+
}
|
|
1629
|
+
return openVerified(real);
|
|
1630
|
+
}
|
|
1631
|
+
function runRoute(route, req, res, label) {
|
|
1632
|
+
for (const [name, value] of Object.entries({
|
|
1633
|
+
...BASE_HEADERS,
|
|
1634
|
+
...resourcePolicy
|
|
1635
|
+
})) res.setHeader(name, value);
|
|
1636
|
+
let result;
|
|
1637
|
+
try {
|
|
1638
|
+
result = route(req, res);
|
|
1639
|
+
} catch (err) {
|
|
1640
|
+
writeInternalError(res, label, err);
|
|
1641
|
+
return;
|
|
1642
|
+
}
|
|
1643
|
+
if (result instanceof Promise || typeof result === "object" && result !== null && typeof result.then === "function") result.then(void 0, (err) => writeInternalError(res, label, err));
|
|
1644
|
+
}
|
|
1212
1645
|
function handleRequest(req, res) {
|
|
1213
1646
|
const headers = req.headers;
|
|
1214
1647
|
const segments = pathSegments(req.url ?? "/");
|
|
@@ -1233,11 +1666,7 @@ function createLoopbackServer(options = {}) {
|
|
|
1233
1666
|
writeError(res, verdict.status, verdict.status === 401 ? "Unauthorized" : "Forbidden");
|
|
1234
1667
|
return;
|
|
1235
1668
|
}
|
|
1236
|
-
|
|
1237
|
-
route(req, res);
|
|
1238
|
-
} catch (err) {
|
|
1239
|
-
writeInternalError(res, `route ${req.method} ${cleanPath}`, err);
|
|
1240
|
-
}
|
|
1669
|
+
runRoute(route, req, res, `route ${req.method} ${cleanPath}`);
|
|
1241
1670
|
return;
|
|
1242
1671
|
}
|
|
1243
1672
|
const mount = resolveMount(cleanPath, segments);
|
|
@@ -1251,7 +1680,13 @@ function createLoopbackServer(options = {}) {
|
|
|
1251
1680
|
return;
|
|
1252
1681
|
}
|
|
1253
1682
|
if (mount.kind === "file") {
|
|
1254
|
-
|
|
1683
|
+
const file = openFileMount(mount.filePath);
|
|
1684
|
+
if (file === null) {
|
|
1685
|
+
console.debug(`[static-server] file mount target ${mount.filePath} is unreadable — 404`);
|
|
1686
|
+
writeError(res, 404, "Not found");
|
|
1687
|
+
return;
|
|
1688
|
+
}
|
|
1689
|
+
serveFile(req, res, file, "no-store", true);
|
|
1255
1690
|
return;
|
|
1256
1691
|
}
|
|
1257
1692
|
const resolved = resolveDirFile(mount, headers);
|
|
@@ -1259,7 +1694,7 @@ function createLoopbackServer(options = {}) {
|
|
|
1259
1694
|
writeError(res, 404, "Not found");
|
|
1260
1695
|
return;
|
|
1261
1696
|
}
|
|
1262
|
-
serveFile(req, res, resolved
|
|
1697
|
+
serveFile(req, res, resolved, cachePolicyFor(resolved.rel, mount.public), !mount.public);
|
|
1263
1698
|
}
|
|
1264
1699
|
const server = http.createServer((req, res) => {
|
|
1265
1700
|
try {
|
|
@@ -1271,9 +1706,9 @@ function createLoopbackServer(options = {}) {
|
|
|
1271
1706
|
function origin() {
|
|
1272
1707
|
if (!originPromise) originPromise = new Promise((resolve, reject) => {
|
|
1273
1708
|
server.on("error", reject);
|
|
1274
|
-
server.listen(port,
|
|
1709
|
+
server.listen(port, bindHost, () => {
|
|
1275
1710
|
const address = server.address();
|
|
1276
|
-
const bound = `http://${
|
|
1711
|
+
const bound = `http://${originHost}:${address?.port}`;
|
|
1277
1712
|
gate.bind(bound);
|
|
1278
1713
|
resolve(bound);
|
|
1279
1714
|
});
|
|
@@ -1282,7 +1717,7 @@ function createLoopbackServer(options = {}) {
|
|
|
1282
1717
|
}
|
|
1283
1718
|
server.on("upgrade", (req, socket, head) => {
|
|
1284
1719
|
const reject = (reason, status) => {
|
|
1285
|
-
|
|
1720
|
+
logUpgradeRejection(reason);
|
|
1286
1721
|
if (status === void 0) {
|
|
1287
1722
|
socket.destroy();
|
|
1288
1723
|
return;
|
|
@@ -1309,6 +1744,8 @@ Referrer-Policy: no-referrer\r
|
|
|
1309
1744
|
origin,
|
|
1310
1745
|
url,
|
|
1311
1746
|
token: () => gate.token(),
|
|
1747
|
+
pauseBootstrapClock: () => gate.pauseBootstrapClock(),
|
|
1748
|
+
resumeBootstrapClock: () => gate.resumeBootstrapClock(),
|
|
1312
1749
|
async credentials() {
|
|
1313
1750
|
const originUrl = await origin();
|
|
1314
1751
|
return {
|
|
@@ -1326,13 +1763,24 @@ Referrer-Policy: no-referrer\r
|
|
|
1326
1763
|
},
|
|
1327
1764
|
mountDir(prefix, dirPath, opts) {
|
|
1328
1765
|
const key = mountKey(prefix);
|
|
1766
|
+
const isPublic = opts?.public === true;
|
|
1767
|
+
const real = realRoot(dirPath);
|
|
1768
|
+
const root = comparablePath(real ?? path.resolve(dirPath), foldCase);
|
|
1769
|
+
for (const [otherKey, otherPath] of dirMounts) {
|
|
1770
|
+
if (otherKey === key) continue;
|
|
1771
|
+
if (publicDirMounts.has(otherKey) === isPublic) continue;
|
|
1772
|
+
const other = cachedRoot(otherKey) ?? comparablePath(path.resolve(otherPath), foldCase);
|
|
1773
|
+
const [publicRoot, gatedRoot] = isPublic ? [root, other] : [other, root];
|
|
1774
|
+
if (isWithin(publicRoot, gatedRoot)) throw new Error(`mountDir('${prefix}'): '${dirPath}' overlaps the ${isPublic ? "gated" : "public"} mount '${otherKey}' at '${otherPath}'; a gated directory mount must not be inside the public one`);
|
|
1775
|
+
}
|
|
1329
1776
|
dirMounts.set(key, dirPath);
|
|
1330
|
-
|
|
1777
|
+
rootCache.set(key, real === null ? null : root);
|
|
1778
|
+
if (isPublic) publicDirMounts.add(key);
|
|
1331
1779
|
else publicDirMounts.delete(key);
|
|
1332
1780
|
},
|
|
1333
1781
|
onConnection: (handler) => slot.onConnection(handler),
|
|
1334
1782
|
registerRoute(method, path, handler) {
|
|
1335
|
-
routeHandlers.set(`${method.toUpperCase()} ${path}`, handler);
|
|
1783
|
+
routeHandlers.set(`${method.toUpperCase()} ${mountKey(path)}`, handler);
|
|
1336
1784
|
},
|
|
1337
1785
|
push: (frame) => slot.push(frame),
|
|
1338
1786
|
close(cb) {
|
|
@@ -1631,14 +2079,73 @@ function resolveCliConfig(argv = readBareArgv()) {
|
|
|
1631
2079
|
}
|
|
1632
2080
|
return parsed;
|
|
1633
2081
|
}
|
|
2082
|
+
const LEVEL_RANK = {
|
|
2083
|
+
debug: 0,
|
|
2084
|
+
info: 1,
|
|
2085
|
+
warn: 2,
|
|
2086
|
+
error: 3
|
|
2087
|
+
};
|
|
2088
|
+
/** Process-wide console capture shared by every live runtime. The console is
|
|
2089
|
+
* patched once, when the first runtime is created, and restored when the
|
|
2090
|
+
* last one closes, so N runtimes in one process (the harness) never stack
|
|
2091
|
+
* wrappers and a closed runtime's store stops receiving (and retaining) logs. */
|
|
2092
|
+
const consoleSinks = /* @__PURE__ */ new Set();
|
|
2093
|
+
let sharedConsoleCapture = null;
|
|
2094
|
+
const fanOutStore = {
|
|
2095
|
+
capacity: 0,
|
|
2096
|
+
append(entry) {
|
|
2097
|
+
const rank = LEVEL_RANK[entry.level];
|
|
2098
|
+
for (const sink of consoleSinks) {
|
|
2099
|
+
if (rank < sink.minRank) continue;
|
|
2100
|
+
try {
|
|
2101
|
+
sink.store.append(entry);
|
|
2102
|
+
} catch {}
|
|
2103
|
+
}
|
|
2104
|
+
},
|
|
2105
|
+
view: () => [],
|
|
2106
|
+
clear: () => 0
|
|
2107
|
+
};
|
|
2108
|
+
function attachConsoleSink(store, minLevel) {
|
|
2109
|
+
const sink = {
|
|
2110
|
+
store,
|
|
2111
|
+
minRank: LEVEL_RANK[minLevel ?? "debug"]
|
|
2112
|
+
};
|
|
2113
|
+
consoleSinks.add(sink);
|
|
2114
|
+
if (!sharedConsoleCapture) sharedConsoleCapture = installConsoleCapture(fanOutStore, "backend");
|
|
2115
|
+
return () => {
|
|
2116
|
+
if (!consoleSinks.delete(sink)) return;
|
|
2117
|
+
if (consoleSinks.size === 0 && sharedConsoleCapture) {
|
|
2118
|
+
sharedConsoleCapture.restore();
|
|
2119
|
+
sharedConsoleCapture = null;
|
|
2120
|
+
}
|
|
2121
|
+
};
|
|
2122
|
+
}
|
|
2123
|
+
/** Writes `handoff.json` atomically (temp file + rename), so a host polling
|
|
2124
|
+
* the storage dir never reads a half-written file. Owner-only permissions:
|
|
2125
|
+
* the file carries the bootstrap nonce. */
|
|
2126
|
+
function writeHandoffFile(storage, handoff) {
|
|
2127
|
+
const target = path.join(storage, "handoff.json");
|
|
2128
|
+
const temp = path.join(storage, "handoff.json.tmp");
|
|
2129
|
+
try {
|
|
2130
|
+
fs.writeFileSync(temp, JSON.stringify(handoff), { mode: 384 });
|
|
2131
|
+
fs.renameSync(temp, target);
|
|
2132
|
+
} catch (err) {
|
|
2133
|
+
try {
|
|
2134
|
+
fs.rmSync(temp, { force: true });
|
|
2135
|
+
} catch {}
|
|
2136
|
+
throw err;
|
|
2137
|
+
}
|
|
2138
|
+
}
|
|
1634
2139
|
/**
|
|
1635
|
-
* Creates one worklet runtime — a per-instance
|
|
1636
|
-
*
|
|
2140
|
+
* Creates one worklet runtime — a per-instance factory (no hardcoded port;
|
|
2141
|
+
* the only process-wide state is the shared console capture, which fans out
|
|
2142
|
+
* to every live runtime's log store) so the dev/test backend can host
|
|
1637
2143
|
* N of them and a consumer worklet entry can be just "register plugins +
|
|
1638
2144
|
* wire p2p". Mirrors the reference wiring in `core/main.core.ts`.
|
|
1639
2145
|
*/
|
|
1640
2146
|
function createWorkletRuntime(options = {}) {
|
|
1641
2147
|
const deviceMode = options.deviceMode ?? true;
|
|
2148
|
+
if (deviceMode && options.auth === false) throw new Error("createWorkletRuntime: auth: false requires deviceMode: false (the dev backend). Device mode always runs with auth on.");
|
|
1642
2149
|
const auth = options.auth ?? deviceMode;
|
|
1643
2150
|
const port = options.port ?? (deviceMode ? 0 : 8080);
|
|
1644
2151
|
const ipc = getIPC();
|
|
@@ -1656,8 +2163,10 @@ function createWorkletRuntime(options = {}) {
|
|
|
1656
2163
|
let hostBridge = null;
|
|
1657
2164
|
const { protocol, pluginRegistry, pluginRouter } = createBareRuntimeContext([], {
|
|
1658
2165
|
maxInflight: options.maxInflight,
|
|
2166
|
+
maxInflightPerChannel: options.maxInflightPerChannel,
|
|
2167
|
+
maxInflightPerPlugin: options.maxInflightPerPlugin,
|
|
1659
2168
|
serialPlugins: options.serialPlugins,
|
|
1660
|
-
delegateToHost: (header, payload) => hostBridge?.invokeOnHost(header, payload) ?? Promise.resolve(null),
|
|
2169
|
+
delegateToHost: (header, payload, timeoutMs) => hostBridge?.invokeOnHost(header, payload, timeoutMs) ?? Promise.resolve(null),
|
|
1661
2170
|
getHostCapabilities: () => hostBridge?.queryCapabilities() ?? Promise.resolve([])
|
|
1662
2171
|
});
|
|
1663
2172
|
hostBridge = ipc ? createHostIpcBridge({
|
|
@@ -1666,16 +2175,22 @@ function createWorkletRuntime(options = {}) {
|
|
|
1666
2175
|
platform: barePlatform
|
|
1667
2176
|
}) : null;
|
|
1668
2177
|
const logStore = createLogRingBuffer(options.logsCapacity ?? 500);
|
|
1669
|
-
installConsoleCapture(logStore, "backend", { minLevel: options.logsMinLevel });
|
|
1670
2178
|
registerLogRoutes(server, logStore);
|
|
1671
2179
|
for (const plugin of createDefaultPlugins({
|
|
1672
2180
|
listBareCapabilities: () => pluginRegistry.listCapabilities(),
|
|
1673
2181
|
queryHostCapabilities: () => hostBridge?.queryCapabilities() ?? Promise.resolve([]),
|
|
1674
2182
|
staticServer: server,
|
|
1675
|
-
invokeOnHost: (header, payload) => hostBridge?.invokeOnHost(header, payload) ?? Promise.resolve(null),
|
|
2183
|
+
invokeOnHost: (header, payload, timeoutMs) => hostBridge?.invokeOnHost(header, payload, timeoutMs) ?? Promise.resolve(null),
|
|
1676
2184
|
store: logStore
|
|
1677
2185
|
})) pluginRegistry.register(plugin);
|
|
1678
2186
|
for (const plugin of options.plugins ?? []) pluginRegistry.register(plugin);
|
|
2187
|
+
const detachConsole = attachConsoleSink(logStore, options.logsMinLevel);
|
|
2188
|
+
const onSuspend = () => server.pauseBootstrapClock?.();
|
|
2189
|
+
const onResume = () => server.resumeBootstrapClock?.();
|
|
2190
|
+
const bareEvents = typeof Bare !== "undefined" && typeof Bare?.on === "function" ? Bare : null;
|
|
2191
|
+
bareEvents?.on?.("suspend", onSuspend);
|
|
2192
|
+
bareEvents?.on?.("resume", onResume);
|
|
2193
|
+
let onIpcData = null;
|
|
1679
2194
|
if (ipc) {
|
|
1680
2195
|
const bridge = hostBridge;
|
|
1681
2196
|
const channel = createFrameChannel({
|
|
@@ -1686,11 +2201,15 @@ function createWorkletRuntime(options = {}) {
|
|
|
1686
2201
|
onMalformed: { kind: "tolerate" },
|
|
1687
2202
|
intercept: (message) => bridge?.tryConsumeDownstream(message) ?? false
|
|
1688
2203
|
});
|
|
1689
|
-
|
|
2204
|
+
onIpcData = (data) => channel.push(data);
|
|
2205
|
+
ipc.on("data", onIpcData);
|
|
1690
2206
|
}
|
|
1691
|
-
|
|
2207
|
+
let closed = false;
|
|
2208
|
+
let started = null;
|
|
2209
|
+
async function startOnce() {
|
|
1692
2210
|
if (options.storage) try {
|
|
1693
2211
|
fs.rmSync(path.join(options.storage, "handoff.json"), { force: true });
|
|
2212
|
+
fs.rmSync(path.join(options.storage, "handoff.json.tmp"), { force: true });
|
|
1694
2213
|
} catch {
|
|
1695
2214
|
console.debug("[runtime] no existing handoff file to remove");
|
|
1696
2215
|
}
|
|
@@ -1704,14 +2223,14 @@ function createWorkletRuntime(options = {}) {
|
|
|
1704
2223
|
if (auth && options.storage && options.handoffFile !== false) {
|
|
1705
2224
|
const { origin, port, bootstrap } = credentials;
|
|
1706
2225
|
try {
|
|
1707
|
-
|
|
2226
|
+
writeHandoffFile(options.storage, {
|
|
1708
2227
|
origin,
|
|
1709
2228
|
port,
|
|
1710
2229
|
bootstrap
|
|
1711
|
-
})
|
|
2230
|
+
});
|
|
1712
2231
|
} catch (err) {
|
|
1713
2232
|
const message = err instanceof Error ? err.message : String(err);
|
|
1714
|
-
|
|
2233
|
+
throw new Error(`[runtime] failed to write the handoff file: ${message}`);
|
|
1715
2234
|
}
|
|
1716
2235
|
}
|
|
1717
2236
|
return credentials;
|
|
@@ -1728,8 +2247,22 @@ function createWorkletRuntime(options = {}) {
|
|
|
1728
2247
|
cache: options.cache,
|
|
1729
2248
|
deviceMode
|
|
1730
2249
|
},
|
|
1731
|
-
start
|
|
2250
|
+
start() {
|
|
2251
|
+
if (closed) return Promise.reject(/* @__PURE__ */ new Error("[runtime] start() after close()"));
|
|
2252
|
+
started ??= startOnce();
|
|
2253
|
+
return started;
|
|
2254
|
+
},
|
|
1732
2255
|
close(cb) {
|
|
2256
|
+
if (closed) {
|
|
2257
|
+
cb?.(null);
|
|
2258
|
+
return;
|
|
2259
|
+
}
|
|
2260
|
+
closed = true;
|
|
2261
|
+
bareEvents?.off?.("suspend", onSuspend);
|
|
2262
|
+
bareEvents?.off?.("resume", onResume);
|
|
2263
|
+
detachConsole();
|
|
2264
|
+
if (ipc && onIpcData) ipc.removeListener("data", onIpcData);
|
|
2265
|
+
hostBridge?.close?.("worklet runtime closed");
|
|
1733
2266
|
server.close(cb);
|
|
1734
2267
|
}
|
|
1735
2268
|
};
|