@mostra/runtime 0.6.2 → 0.7.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/dist/bin.js +1 -1
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/{instance-DpD340-W.js → instance-CYPYPCIb.js} +2650 -553
- package/dist/instance-CYPYPCIb.js.map +1 -0
- package/package.json +5 -5
- package/src/addressing/index.ts +85 -31
- package/src/gateway/browser.ts +3 -1
- package/src/gateway/capabilities.ts +227 -18
- package/src/gateway/http.ts +12 -2
- package/src/gateway/identity.ts +75 -0
- package/src/gateway/index.ts +1254 -437
- package/src/gateway/routes.ts +52 -7
- package/src/gateway/worker.ts +204 -0
- package/src/instance/index.ts +72 -0
- package/src/interaction/index.ts +8 -0
- package/src/interaction/viewers.ts +21 -2
- package/src/ledger/migrations.ts +61 -0
- package/src/platform/index.ts +1 -0
- package/src/platform/tools.ts +145 -0
- package/src/processes/manager.ts +10 -2
- package/src/protocol-server/index.ts +4 -0
- package/src/publish/methods.ts +6 -2
- package/src/share/cloudflare.ts +136 -0
- package/src/share/index.ts +823 -0
- package/src/share/tailscale.ts +217 -0
- package/src/share/tunnel.ts +186 -0
- package/dist/instance-DpD340-W.js.map +0 -1
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { C as STAGING_FILES, S as LIVE_DECLARATION, _ as DEV_METHOD, a as nameKey, c as removeTree, d as replaceDirectoryLink, f as samePath, g as DEV_CHANGED_METHOD, h as BUILD_METHOD, i as linkTarget, l as renamePath, m as sealTree, o as pathKey, p as sealPlaced, r as linkDirectory, s as realPath, t as fsyncPath, u as renamePathSync, v as DEV_RELOAD_METHOD, y as DEV_SECRET_HEADER } from "./files-FygSJIzK.js";
|
|
2
2
|
import { a as pathsOf, c as currentUserSid, d as runtimeRoot$1, f as serviceLauncherPath, i as ownedDirectory, l as helperPath, n as WINDOWS, o as runtimeDirFor, p as stopServiceLauncher, r as defaultHome, s as socketPathLimit, t as OS, u as runHelperAsync } from "./directories-mJ1qlVht.js";
|
|
3
3
|
import { builtinModules, createRequire } from "node:module";
|
|
4
|
-
import { appendFileSync, chmodSync, closeSync, constants, createReadStream, createWriteStream, existsSync, fsyncSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, watch, writeFileSync, writeSync } from "node:fs";
|
|
4
|
+
import { accessSync, appendFileSync, chmodSync, closeSync, constants, createReadStream, createWriteStream, existsSync, fsyncSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, watch, writeFileSync, writeSync } from "node:fs";
|
|
5
5
|
import { basename, delimiter, dirname, extname, join, relative, resolve, sep, win32 } from "node:path";
|
|
6
6
|
import { fileURLToPath } from "node:url";
|
|
7
|
-
import { ACTION_ARGS_MAX, ACTION_RESULT_MAX, ALL_SCOPES, ARTIFACT_MANIFEST_KEYS, ARTIFACT_PROGRESS, ArtifactId, ArtifactManifest, BROWSER_PROTOCOL_REVISION, BROWSER_PROTOCOL_REVISIONS, BUNDLE_NAME, CLI_CLIENT_NAME, CallRequest, ChooseRequest, DEFAULT_WORKER_LIMITS, DEV_NOTIFY, DeliveryId, EVENTS_NOTIFY, FieldsRequest, FollowRequest, HOST_PROTOCOL_REVISIONS, LIVE_RING_DEFAULT, LIVE_RING_MAX, LIVE_VALUE_MAX, LineSplitter, LiveRequest, MAX_LINE_LENGTH, MutationId, RUN_LOG_MAX, RUN_LOG_TRUNCATED, RpcError, RpcPeer, RunAttachRequest, RunCancelRequest, RunId, RunRequest, SECRET_NAME_PATTERN, SECRET_VALUE_MAX, SIGNAL_NAME_PATTERN, SIGNAL_PAYLOAD_MAX_BYTES, ServerEmitParams, ServerLiveValueParams, ServerSecretParams, ServerSignalParams, ServerStateGetParams, ServerStatePatchParams, ShellSubmitRequest, SignalRequest, SubmissionId, SubmissionPolicy, SubmitRequest, TokenId, VERIFY_RUNNER_METHODS, VerifyVerdict, VersionId, ViewId, ViewerId, WORKER_METHODS, WorkerBatchParams, WorkerCallOutcome, WorkerPingResult, WorkerStartResult, ariaSummary, artifactCreateMethod, artifactGetMethod, artifactListMethod, artifactPublishMethod, artifactVerifyMethod, canonicalJson, checkArgumentFrames, checkRequest, createDiagnostic, depsAddMethod, devStartMethod, devStopMethod, durationMs, encodeLine, estimateImageTokens, eventsAckMethod, eventsReadMethod, eventsSubscribeMethod, eventsUnsubscribeMethod, fromBase64, gcRunMethod, instanceCheckMethod, instanceStatusMethod, isFieldId, isFinalRunStatus, livePushMethod, mostraInitializeMethod, mostraShutdownMethod, negotiateRevision, normalizeScopes, parseParams, portDraftsMirrorMethod, portIdentityResolveMethod, portSecretsGetMethod, portSubmissionsDeliverMethod, portTrustedControlsActivatedMethod, portTrustedControlsPolicyMethod, refusal, resultsGetMethod, safeEqual, safePath, scopeAllows, secretDeleteMethod, secretListMethod, secretSetMethod, serializeAll, stateGetMethod, statePatchMethod, toBase64, viewDefaultMethod, viewLaunchMethod, viewRevokeMethod, viewRotateMethod, viewUrlMethod, viewportsFor, waitMethod } from "@mostra/protocol";
|
|
7
|
+
import { ACTION_ARGS_MAX, ACTION_RESULT_MAX, ALL_SCOPES, ARTIFACT_MANIFEST_KEYS, ARTIFACT_PROGRESS, ArtifactId, ArtifactManifest, BROWSER_PROTOCOL_REVISION, BROWSER_PROTOCOL_REVISIONS, BUNDLE_NAME, CLI_CLIENT_NAME, CallRequest, ChooseRequest, DEFAULT_WORKER_LIMITS, DEV_NOTIFY, DeliveryId, EVENTS_NOTIFY, EnterRequest, FRAME_SESSION_HEADER, FieldsRequest, FollowRequest, HOST_PROTOCOL_REVISIONS, LIVE_RING_DEFAULT, LIVE_RING_MAX, LIVE_VALUE_MAX, LineSplitter, LiveRequest, MAX_LINE_LENGTH, MutationId, PUBLIC_SHARE_DEFAULT_TTL, PUBLIC_SHARE_MAX_TTL_MS, RUN_LOG_MAX, RUN_LOG_TRUNCATED, RpcError, RpcPeer, RunAttachRequest, RunCancelRequest, RunId, RunRequest, SECRET_NAME_PATTERN, SECRET_VALUE_MAX, SIGNAL_NAME_PATTERN, SIGNAL_PAYLOAD_MAX_BYTES, ServerEmitParams, ServerLiveValueParams, ServerSecretParams, ServerSignalParams, ServerStateGetParams, ServerStatePatchParams, ShareId, ShellSubmitRequest, SignalRequest, StreamTicketRequest, SubmissionId, SubmissionPolicy, SubmitRequest, TokenId, VERIFY_RUNNER_METHODS, VerifyVerdict, VersionId, ViewId, ViewerId, WORKER_METHODS, WorkerBatchParams, WorkerCallOutcome, WorkerPingResult, WorkerStartResult, ariaSummary, artifactCreateMethod, artifactGetMethod, artifactListMethod, artifactPublishMethod, artifactVerifyMethod, canonicalJson, checkArgumentFrames, checkRequest, createDiagnostic, depsAddMethod, devStartMethod, devStopMethod, durationMs, encodeLine, estimateImageTokens, eventsAckMethod, eventsReadMethod, eventsSubscribeMethod, eventsUnsubscribeMethod, fromBase64, gcRunMethod, instanceCheckMethod, instanceStatusMethod, isFieldId, isFinalRunStatus, livePushMethod, mostraInitializeMethod, mostraShutdownMethod, negotiateRevision, normalizeScopes, parseParams, portAddressingExternalBaseMethod, portDraftsMirrorMethod, portIdentityResolveMethod, portSecretsGetMethod, portSubmissionsDeliverMethod, portTrustedControlsActivatedMethod, portTrustedControlsPolicyMethod, refusal, resultsGetMethod, safeEqual, safePath, scopeAllows, secretDeleteMethod, secretListMethod, secretSetMethod, serializeAll, shareListMethod, shareStartMethod, shareStopMethod, stateGetMethod, statePatchMethod, toBase64, viewDefaultMethod, viewLaunchMethod, viewRevokeMethod, viewRotateMethod, viewUrlMethod, viewportsFor, waitMethod } from "@mostra/protocol";
|
|
8
8
|
import { createHash, createHmac, randomBytes, randomInt, randomUUID } from "node:crypto";
|
|
9
9
|
import { connect, createConnection, createServer, isIP } from "node:net";
|
|
10
10
|
import { execFile, execFileSync, spawn } from "node:child_process";
|
|
@@ -22,6 +22,7 @@ import { getRequestListener } from "@hono/node-server";
|
|
|
22
22
|
import { Hono } from "hono";
|
|
23
23
|
import ignore from "ignore";
|
|
24
24
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
25
|
+
import { Resolver } from "node:dns/promises";
|
|
25
26
|
//#region src/log.ts
|
|
26
27
|
/**
|
|
27
28
|
* The supervisor's log: JSON lines in `<home>/logs/supervisor.log`, rotated by size (DATA_MODEL
|
|
@@ -709,6 +710,16 @@ const LEASE_FIRST_PORT = 2e4;
|
|
|
709
710
|
const LEASE_LAST_PORT = 32767;
|
|
710
711
|
/** How many free ports to try before giving up on a lease. */
|
|
711
712
|
const LEASE_ATTEMPTS = 64;
|
|
713
|
+
/** The address every face listens on: loopback, whatever `--bind` says (D158 item 1). */
|
|
714
|
+
const FACE_BIND_ADDRESS = "127.0.0.1";
|
|
715
|
+
/**
|
|
716
|
+
* The exact `Host` a browser sends for an origin: its host, with the port only when it isn't the
|
|
717
|
+
* scheme's default (`https://a.ts.net` is `a.ts.net`, `https://a.ts.net:8443` is
|
|
718
|
+
* `a.ts.net:8443`), lowercase. Registered tunnel addresses join the allowlist this way.
|
|
719
|
+
*/
|
|
720
|
+
function hostOf(origin) {
|
|
721
|
+
return new URL(origin).host.toLowerCase();
|
|
722
|
+
}
|
|
712
723
|
/** The unspecified addresses, as {@link authorityHost} writes them: each listens everywhere. */
|
|
713
724
|
const WILDCARDS = /* @__PURE__ */ new Set([
|
|
714
725
|
"0.0.0.0",
|
|
@@ -789,6 +800,37 @@ function createAddressing(options) {
|
|
|
789
800
|
});
|
|
790
801
|
};
|
|
791
802
|
const taken = () => new Set(ledger.read((db) => db.all("SELECT port FROM port_lease")).map((row) => row.port));
|
|
803
|
+
/**
|
|
804
|
+
* Binds `server` to the owner's leased port on `address`, or to a newly leased one when it has
|
|
805
|
+
* none or another program holds it (`MOSTRA_ENV_PORT_TAKEN`).
|
|
806
|
+
*/
|
|
807
|
+
const leaseAndListen = async (server, owner, address) => {
|
|
808
|
+
const previous = leased(owner);
|
|
809
|
+
if (previous !== void 0) {
|
|
810
|
+
if (await tryListen(server, previous, address)) return previous;
|
|
811
|
+
log.warn("addressing.port_taken", {
|
|
812
|
+
code: "MOSTRA_ENV_PORT_TAKEN",
|
|
813
|
+
purpose: owner.purpose,
|
|
814
|
+
owner: owner.owner,
|
|
815
|
+
port: previous
|
|
816
|
+
});
|
|
817
|
+
}
|
|
818
|
+
const others = taken();
|
|
819
|
+
for (let attempt = 0; attempt < LEASE_ATTEMPTS; attempt++) {
|
|
820
|
+
const port = randomInt(LEASE_FIRST_PORT, 32768);
|
|
821
|
+
if (others.has(port)) continue;
|
|
822
|
+
if (!await tryListen(server, port, address)) continue;
|
|
823
|
+
record(owner, port);
|
|
824
|
+
if (previous !== void 0) log.warn("addressing.port_released", {
|
|
825
|
+
purpose: owner.purpose,
|
|
826
|
+
owner: owner.owner,
|
|
827
|
+
from: previous,
|
|
828
|
+
to: port
|
|
829
|
+
});
|
|
830
|
+
return port;
|
|
831
|
+
}
|
|
832
|
+
throw bindFailed(`No free port between ${LEASE_FIRST_PORT} and ${LEASE_LAST_PORT} on ${address} after ${LEASE_ATTEMPTS} attempts.`);
|
|
833
|
+
};
|
|
792
834
|
return {
|
|
793
835
|
bindAddress,
|
|
794
836
|
urlHost,
|
|
@@ -808,35 +850,27 @@ function createAddressing(options) {
|
|
|
808
850
|
if (address === null || typeof address === "string") throw new Error("not a TCP listener");
|
|
809
851
|
return address.port;
|
|
810
852
|
}
|
|
811
|
-
|
|
812
|
-
if (previous !== void 0) {
|
|
813
|
-
if (await tryListen(server, previous, bindAddress)) return previous;
|
|
814
|
-
log.warn("addressing.port_taken", {
|
|
815
|
-
code: "MOSTRA_ENV_PORT_TAKEN",
|
|
816
|
-
purpose: owner.purpose,
|
|
817
|
-
owner: owner.owner,
|
|
818
|
-
port: previous
|
|
819
|
-
});
|
|
820
|
-
}
|
|
821
|
-
const others = taken();
|
|
822
|
-
for (let attempt = 0; attempt < LEASE_ATTEMPTS; attempt++) {
|
|
823
|
-
const port = randomInt(LEASE_FIRST_PORT, 32768);
|
|
824
|
-
if (others.has(port)) continue;
|
|
825
|
-
if (!await tryListen(server, port, bindAddress)) continue;
|
|
826
|
-
record(owner, port);
|
|
827
|
-
if (previous !== void 0) log.warn("addressing.port_released", {
|
|
828
|
-
purpose: owner.purpose,
|
|
829
|
-
owner: owner.owner,
|
|
830
|
-
from: previous,
|
|
831
|
-
to: port
|
|
832
|
-
});
|
|
833
|
-
return port;
|
|
834
|
-
}
|
|
835
|
-
throw bindFailed(`No free port between ${LEASE_FIRST_PORT} and ${LEASE_LAST_PORT} on ${bindAddress} after ${LEASE_ATTEMPTS} attempts.`);
|
|
853
|
+
return leaseAndListen(server, owner, bindAddress);
|
|
836
854
|
},
|
|
837
855
|
frameMode(shellOrigin, artifactOrigin) {
|
|
838
856
|
return new URL(shellOrigin).hostname === new URL(artifactOrigin).hostname ? "cookie" : "worker";
|
|
839
|
-
}
|
|
857
|
+
},
|
|
858
|
+
async listenFace(server, face) {
|
|
859
|
+
if (!face.lease) {
|
|
860
|
+
if (!await tryListen(server, 0, "127.0.0.1")) throw bindFailed(`No port is free on ${FACE_BIND_ADDRESS}.`);
|
|
861
|
+
const address = server.address();
|
|
862
|
+
if (address === null || typeof address === "string") throw new Error("not a TCP listener");
|
|
863
|
+
return address.port;
|
|
864
|
+
}
|
|
865
|
+
return leaseAndListen(server, {
|
|
866
|
+
purpose: "face",
|
|
867
|
+
owner: face.key
|
|
868
|
+
}, FACE_BIND_ADDRESS);
|
|
869
|
+
},
|
|
870
|
+
releaseFace(key) {
|
|
871
|
+
ledger.write((db) => db.run("DELETE FROM port_lease WHERE purpose = 'face' AND owner_ref = ?", key));
|
|
872
|
+
},
|
|
873
|
+
faceLocal: (port) => `http://${FACE_BIND_ADDRESS}:${port}`
|
|
840
874
|
};
|
|
841
875
|
}
|
|
842
876
|
//#endregion
|
|
@@ -1686,6 +1720,114 @@ function baseEnvironment(env) {
|
|
|
1686
1720
|
}
|
|
1687
1721
|
return result;
|
|
1688
1722
|
}
|
|
1723
|
+
//#endregion
|
|
1724
|
+
//#region src/platform/tools.ts
|
|
1725
|
+
/**
|
|
1726
|
+
* Where this system keeps the tunnel tools a share drives (D158 item 4): `tailscale` and
|
|
1727
|
+
* `cloudflared`, which Mostra never bundles or downloads. A daemon started by a login service may
|
|
1728
|
+
* run with a short `PATH`, so the tools' usual install locations are searched after it, and an
|
|
1729
|
+
* environment variable names one outright. How to install each is said here too, per system.
|
|
1730
|
+
*/
|
|
1731
|
+
/** The variable that names a tool's executable outright. */
|
|
1732
|
+
const TOOL_VARIABLES = {
|
|
1733
|
+
tailscale: "MOSTRA_TAILSCALE",
|
|
1734
|
+
cloudflared: "MOSTRA_CLOUDFLARED"
|
|
1735
|
+
};
|
|
1736
|
+
/** The usual install locations of each tool, per system, after `PATH`. */
|
|
1737
|
+
function usualLocations(tool, env) {
|
|
1738
|
+
if (WINDOWS) {
|
|
1739
|
+
const programs = env["ProgramFiles"] ?? "C:\\Program Files";
|
|
1740
|
+
const programs86 = env["ProgramFiles(x86)"] ?? "C:\\Program Files (x86)";
|
|
1741
|
+
return tool === "tailscale" ? [join(programs, "Tailscale", "tailscale.exe")] : [join(programs86, "cloudflared", "cloudflared.exe"), join(programs, "cloudflared", "cloudflared.exe")];
|
|
1742
|
+
}
|
|
1743
|
+
if (OS === "darwin") return tool === "tailscale" ? [
|
|
1744
|
+
"/opt/homebrew/bin/tailscale",
|
|
1745
|
+
"/usr/local/bin/tailscale",
|
|
1746
|
+
"/opt/homebrew/opt/tailscale/bin/tailscale",
|
|
1747
|
+
"/usr/local/opt/tailscale/bin/tailscale",
|
|
1748
|
+
"/Applications/Tailscale.app/Contents/MacOS/Tailscale"
|
|
1749
|
+
] : [
|
|
1750
|
+
"/opt/homebrew/bin/cloudflared",
|
|
1751
|
+
"/usr/local/bin/cloudflared",
|
|
1752
|
+
"/opt/homebrew/opt/cloudflared/bin/cloudflared",
|
|
1753
|
+
"/usr/local/opt/cloudflared/bin/cloudflared"
|
|
1754
|
+
];
|
|
1755
|
+
return tool === "tailscale" ? [
|
|
1756
|
+
"/usr/bin/tailscale",
|
|
1757
|
+
"/usr/local/bin/tailscale",
|
|
1758
|
+
"/usr/sbin/tailscale"
|
|
1759
|
+
] : ["/usr/bin/cloudflared", "/usr/local/bin/cloudflared"];
|
|
1760
|
+
}
|
|
1761
|
+
function executable(path) {
|
|
1762
|
+
try {
|
|
1763
|
+
if (!statSync(path).isFile()) return false;
|
|
1764
|
+
if (!WINDOWS) accessSync(path, constants.X_OK);
|
|
1765
|
+
return true;
|
|
1766
|
+
} catch {
|
|
1767
|
+
return false;
|
|
1768
|
+
}
|
|
1769
|
+
}
|
|
1770
|
+
/**
|
|
1771
|
+
* The tool's executable: the variable's (which must exist), else the first on `PATH`, else the
|
|
1772
|
+
* first usual location that exists; `undefined` when there is none.
|
|
1773
|
+
*/
|
|
1774
|
+
function findTool(tool, env) {
|
|
1775
|
+
const named = env[TOOL_VARIABLES[tool]];
|
|
1776
|
+
if (named !== void 0 && named !== "") return executable(named) ? named : void 0;
|
|
1777
|
+
const names = WINDOWS ? [`${tool}.exe`] : [tool];
|
|
1778
|
+
const path = (WINDOWS ? env["Path"] ?? env["PATH"] : env["PATH"]) ?? "";
|
|
1779
|
+
for (const dir of path.split(delimiter)) {
|
|
1780
|
+
if (dir === "") continue;
|
|
1781
|
+
for (const name of names) {
|
|
1782
|
+
const candidate = join(dir, name);
|
|
1783
|
+
if (executable(candidate)) return candidate;
|
|
1784
|
+
}
|
|
1785
|
+
}
|
|
1786
|
+
return usualLocations(tool, env).find(executable);
|
|
1787
|
+
}
|
|
1788
|
+
/**
|
|
1789
|
+
* The variable that replaces both tools with local fakes for tests (`<dir>/tailscale.mjs` and
|
|
1790
|
+
* `<dir>/cloudflared.mjs`, run on this Node.js): the conformance kit's and the suites' own, which
|
|
1791
|
+
* forward on loopback as the real tools forward from their networks (STANDARDS: real side effects
|
|
1792
|
+
* in tests go to local fakes).
|
|
1793
|
+
*/
|
|
1794
|
+
const TEST_TUNNELS_VARIABLE = "MOSTRA_TEST_TUNNELS";
|
|
1795
|
+
/** How to run a tool: {@link findTool}'s executable, or the test fake; `undefined` when missing. */
|
|
1796
|
+
function toolCommand(tool, env) {
|
|
1797
|
+
const fakes = env[TEST_TUNNELS_VARIABLE];
|
|
1798
|
+
if (fakes !== void 0 && fakes !== "") {
|
|
1799
|
+
const script = join(fakes, `${tool}.mjs`);
|
|
1800
|
+
return regularFile(script) ? {
|
|
1801
|
+
command: process.execPath,
|
|
1802
|
+
args: [script],
|
|
1803
|
+
fake: true
|
|
1804
|
+
} : void 0;
|
|
1805
|
+
}
|
|
1806
|
+
const found = findTool(tool, env);
|
|
1807
|
+
return found === void 0 ? void 0 : {
|
|
1808
|
+
command: found,
|
|
1809
|
+
args: [],
|
|
1810
|
+
fake: false
|
|
1811
|
+
};
|
|
1812
|
+
}
|
|
1813
|
+
function regularFile(path) {
|
|
1814
|
+
try {
|
|
1815
|
+
return statSync(path).isFile();
|
|
1816
|
+
} catch {
|
|
1817
|
+
return false;
|
|
1818
|
+
}
|
|
1819
|
+
}
|
|
1820
|
+
/** How to install a tool on this system, as one sentence. */
|
|
1821
|
+
function installHint(tool) {
|
|
1822
|
+
if (tool === "tailscale") {
|
|
1823
|
+
if (WINDOWS) return "Install Tailscale from https://tailscale.com/download/windows (or `winget install tailscale.tailscale`) and sign in.";
|
|
1824
|
+
if (OS === "darwin") return "Install Tailscale from https://tailscale.com/download/mac (or `brew install tailscale`) and sign in.";
|
|
1825
|
+
return "Install Tailscale with `curl -fsSL https://tailscale.com/install.sh | sh` (https://tailscale.com/download/linux), then run `sudo tailscale up`.";
|
|
1826
|
+
}
|
|
1827
|
+
if (WINDOWS) return "Install cloudflared with `winget install --id Cloudflare.cloudflared` (https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/).";
|
|
1828
|
+
if (OS === "darwin") return "Install cloudflared with `brew install cloudflared` (https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/).";
|
|
1829
|
+
return "Install cloudflared from your distribution's Cloudflare package repository or https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/.";
|
|
1830
|
+
}
|
|
1689
1831
|
/** Packages whose versions define the SPA build; they are part of `buildConfigDigest` (VR-01). */
|
|
1690
1832
|
const BUILD_PACKAGES = [
|
|
1691
1833
|
"vite",
|
|
@@ -2457,6 +2599,58 @@ const MIGRATIONS = [
|
|
|
2457
2599
|
up(db) {
|
|
2458
2600
|
db.exec(`
|
|
2459
2601
|
ALTER TABLE session ADD COLUMN viewer_id TEXT REFERENCES viewer(id);
|
|
2602
|
+
`);
|
|
2603
|
+
}
|
|
2604
|
+
},
|
|
2605
|
+
{
|
|
2606
|
+
version: 11,
|
|
2607
|
+
name: "shares and faces",
|
|
2608
|
+
up(db) {
|
|
2609
|
+
db.exec(`
|
|
2610
|
+
CREATE TABLE port_lease_new (
|
|
2611
|
+
port INTEGER PRIMARY KEY CHECK (port BETWEEN 1 AND 65535),
|
|
2612
|
+
purpose TEXT NOT NULL CHECK (purpose IN ('shell', 'artifact', 'demo', 'face')),
|
|
2613
|
+
owner_ref TEXT NOT NULL,
|
|
2614
|
+
leased_at TEXT NOT NULL,
|
|
2615
|
+
UNIQUE (purpose, owner_ref)
|
|
2616
|
+
);
|
|
2617
|
+
INSERT INTO port_lease_new (port, purpose, owner_ref, leased_at)
|
|
2618
|
+
SELECT port, purpose, owner_ref, leased_at FROM port_lease;
|
|
2619
|
+
DROP TABLE port_lease;
|
|
2620
|
+
ALTER TABLE port_lease_new RENAME TO port_lease;
|
|
2621
|
+
CREATE TABLE share (
|
|
2622
|
+
id TEXT PRIMARY KEY,
|
|
2623
|
+
artifact_id TEXT NOT NULL REFERENCES artifact(id),
|
|
2624
|
+
via TEXT NOT NULL CHECK (via IN ('tailnet', 'funnel', 'cloudflare')),
|
|
2625
|
+
hostname TEXT NOT NULL,
|
|
2626
|
+
token_id TEXT NOT NULL REFERENCES token(id),
|
|
2627
|
+
mode TEXT NOT NULL CHECK (mode IN ('cookie', 'worker')),
|
|
2628
|
+
plan_json TEXT NOT NULL,
|
|
2629
|
+
started_at TEXT NOT NULL,
|
|
2630
|
+
expires_at TEXT,
|
|
2631
|
+
stopped_at TEXT,
|
|
2632
|
+
stop_reason TEXT,
|
|
2633
|
+
CHECK ((stopped_at IS NULL) = (stop_reason IS NULL))
|
|
2634
|
+
);
|
|
2635
|
+
CREATE INDEX share_artifact ON share (artifact_id);
|
|
2636
|
+
CREATE INDEX share_active ON share (stopped_at) WHERE stopped_at IS NULL;
|
|
2637
|
+
CREATE TRIGGER share_ends_once BEFORE UPDATE ON share
|
|
2638
|
+
WHEN OLD.stopped_at IS NOT NULL OR NEW.id IS NOT OLD.id
|
|
2639
|
+
OR NEW.artifact_id IS NOT OLD.artifact_id OR NEW.via IS NOT OLD.via
|
|
2640
|
+
OR NEW.token_id IS NOT OLD.token_id OR NEW.started_at IS NOT OLD.started_at
|
|
2641
|
+
OR NEW.expires_at IS NOT OLD.expires_at
|
|
2642
|
+
BEGIN
|
|
2643
|
+
SELECT RAISE(ABORT, 'a share only ever ends, once');
|
|
2644
|
+
END;
|
|
2645
|
+
CREATE TABLE external_base (
|
|
2646
|
+
key TEXT PRIMARY KEY,
|
|
2647
|
+
listener TEXT NOT NULL CHECK (listener IN ('shell', 'artifact')),
|
|
2648
|
+
artifact_id TEXT NOT NULL REFERENCES artifact(id),
|
|
2649
|
+
origin TEXT NOT NULL,
|
|
2650
|
+
mode TEXT CHECK (mode IN ('cookie', 'worker')),
|
|
2651
|
+
client TEXT NOT NULL,
|
|
2652
|
+
updated_at TEXT NOT NULL
|
|
2653
|
+
);
|
|
2460
2654
|
`);
|
|
2461
2655
|
}
|
|
2462
2656
|
}
|
|
@@ -2999,9 +3193,11 @@ function createManager({ ledger, log, redactor, faults = noFaults }) {
|
|
|
2999
3193
|
const lines = createInterface({ input: child.stderr });
|
|
3000
3194
|
drained.push(new Promise((resolve) => lines.once("close", resolve)));
|
|
3001
3195
|
lines.on("line", (line) => {
|
|
3002
|
-
|
|
3196
|
+
const redacted = redactor.redact(line);
|
|
3197
|
+
stderrTail.push(redacted);
|
|
3003
3198
|
if (stderrTail.length > STDERR_TAIL) stderrTail.shift();
|
|
3004
|
-
|
|
3199
|
+
if (spec.onStderr) spec.onStderr(redacted);
|
|
3200
|
+
else log.info("process.stderr", {
|
|
3005
3201
|
kind: spec.kind,
|
|
3006
3202
|
pid,
|
|
3007
3203
|
line
|
|
@@ -4774,6 +4970,7 @@ function sessionMethods(options) {
|
|
|
4774
4970
|
...gateway ? { gateway } : {},
|
|
4775
4971
|
...options.deliveries ? { deliveries: [...options.deliveries()] } : {},
|
|
4776
4972
|
...options.workers ? { workers: [...options.workers()] } : {},
|
|
4973
|
+
...options.shares ? { shares: [...options.shares()] } : {},
|
|
4777
4974
|
...(() => {
|
|
4778
4975
|
const at = options.idleExitAt?.();
|
|
4779
4976
|
return at === void 0 ? {} : { idleExitAt: at };
|
|
@@ -5295,7 +5492,7 @@ function viewerOf(row) {
|
|
|
5295
5492
|
id: row.id,
|
|
5296
5493
|
kind: row.kind,
|
|
5297
5494
|
...row.name !== null ? { name: row.name } : {},
|
|
5298
|
-
...row.kind === "token" || row.kind === "host" ? { ref: row.external_ref } : {}
|
|
5495
|
+
...row.kind === "token" || row.kind === "host" || row.kind === "tailnet" ? { ref: row.external_ref } : {}
|
|
5299
5496
|
};
|
|
5300
5497
|
}
|
|
5301
5498
|
/** The home's local user (created on first use): who every session acts as without a viewer. */
|
|
@@ -5320,6 +5517,24 @@ function viewerForSpec(db, spec) {
|
|
|
5320
5517
|
function viewerForHost(db, spec) {
|
|
5321
5518
|
return viewerByRef(db, "host", spec);
|
|
5322
5519
|
}
|
|
5520
|
+
/**
|
|
5521
|
+
* A tailnet person (D158 item 2): one viewer of kind `tailnet` per Tailscale login, named by the
|
|
5522
|
+
* display name Tailscale Serve sends.
|
|
5523
|
+
*/
|
|
5524
|
+
function viewerForTailnet(db, spec) {
|
|
5525
|
+
return viewerByRef(db, "tailnet", spec);
|
|
5526
|
+
}
|
|
5527
|
+
/**
|
|
5528
|
+
* A link's own viewer (D158 item 2): whoever opens a link over a tunnel without being named (a
|
|
5529
|
+
* public share, a tagged tailnet device) acts as one viewer per link, never as the home's local
|
|
5530
|
+
* user, so a visitor's answers never mix into the owner's draft.
|
|
5531
|
+
*/
|
|
5532
|
+
function viewerForLink(db, tokenId, name) {
|
|
5533
|
+
return viewerByRef(db, "token", {
|
|
5534
|
+
ref: `link:${tokenId}`,
|
|
5535
|
+
name
|
|
5536
|
+
});
|
|
5537
|
+
}
|
|
5323
5538
|
function viewerByRef(db, kind, spec) {
|
|
5324
5539
|
const found = db.get("SELECT * FROM viewer WHERE kind = ? AND external_ref = ?", kind, spec.ref);
|
|
5325
5540
|
if (found) {
|
|
@@ -6903,6 +7118,8 @@ function createInteraction(options) {
|
|
|
6903
7118
|
viewer: (viewerId) => ledger.read((db) => viewer(db, viewerId)),
|
|
6904
7119
|
viewerForSpec,
|
|
6905
7120
|
viewerForHost: (spec) => ledger.write((db) => viewerForHost(db, spec)),
|
|
7121
|
+
viewerForTailnet: (spec) => ledger.write((db) => viewerForTailnet(db, spec)),
|
|
7122
|
+
viewerForLink: (tokenId, name) => ledger.write((db) => viewerForLink(db, tokenId, name)),
|
|
6906
7123
|
openView(input) {
|
|
6907
7124
|
return ledger.write((db) => openView(db, input));
|
|
6908
7125
|
},
|
|
@@ -7822,6 +8039,7 @@ function headerPairs(incoming) {
|
|
|
7822
8039
|
}
|
|
7823
8040
|
/** Whether a request is a navigation that should get an HTML page rather than JSON. */
|
|
7824
8041
|
function wantsDocument(headers) {
|
|
8042
|
+
if (headers.get("x-mostra-navigation") === "1") return true;
|
|
7825
8043
|
const dest = headers.get("sec-fetch-dest");
|
|
7826
8044
|
if (dest !== null) return dest === "document" || dest === "iframe" || dest === "frame";
|
|
7827
8045
|
return (headers.get("accept") ?? "").includes("text/html");
|
|
@@ -7885,9 +8103,12 @@ function cookieValues(header, name) {
|
|
|
7885
8103
|
}
|
|
7886
8104
|
return values;
|
|
7887
8105
|
}
|
|
7888
|
-
/**
|
|
7889
|
-
|
|
7890
|
-
|
|
8106
|
+
/**
|
|
8107
|
+
* The `Set-Cookie` value of a session cookie (D98 item 1): never `Secure` over loopback HTTP,
|
|
8108
|
+
* always over a tunnel's HTTPS address (D158), where it must never travel in clear.
|
|
8109
|
+
*/
|
|
8110
|
+
function sessionCookie(name, value, path, maxAgeSeconds, secure = false) {
|
|
8111
|
+
return `${name}=${value}; Path=${path}; Max-Age=${maxAgeSeconds}; HttpOnly; SameSite=Strict${secure ? "; Secure" : ""}`;
|
|
7891
8112
|
}
|
|
7892
8113
|
/**
|
|
7893
8114
|
* Reads a JSON object body of at most `maxBytes` (default {@link MAX_JSON_BODY}) bytes; a larger,
|
|
@@ -8324,7 +8545,7 @@ function browserRoutes(options) {
|
|
|
8324
8545
|
};
|
|
8325
8546
|
const body = new ReadableStream({
|
|
8326
8547
|
start(controller) {
|
|
8327
|
-
let text = "retry: 2000\n\n";
|
|
8548
|
+
let text = "retry: 2000\n\nevent: ready\ndata: {}\n\n";
|
|
8328
8549
|
if (resume === void 0) text += snapshotText(interaction.pageSnapshot(page));
|
|
8329
8550
|
controller.enqueue(encoder.encode(text));
|
|
8330
8551
|
},
|
|
@@ -8584,11 +8805,23 @@ function browserRoutes(options) {
|
|
|
8584
8805
|
const CROCKFORD$2 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
8585
8806
|
/** How long a frame ticket works (D98). */
|
|
8586
8807
|
const TICKET_TTL_MS = 6e4;
|
|
8808
|
+
/** How often expired tickets are swept at most. */
|
|
8809
|
+
const SWEEP_INTERVAL_MS = 1e3;
|
|
8587
8810
|
const FAILURE_WINDOW_MS = 6e4;
|
|
8588
8811
|
/** How long a session the browser no longer presents is kept: the cookie's own lifetime. */
|
|
8589
8812
|
const SESSION_MAX_AGE_S = 3456e4;
|
|
8590
8813
|
/** How often a session's `last_seen_at` is written at most. */
|
|
8591
8814
|
const TOUCH_INTERVAL_MS = 36e5;
|
|
8815
|
+
/** Whether two origins are on the same scheme and host, whatever their ports. */
|
|
8816
|
+
function sameHost(a, b) {
|
|
8817
|
+
try {
|
|
8818
|
+
const one = new URL(a);
|
|
8819
|
+
const two = new URL(b);
|
|
8820
|
+
return one.protocol === two.protocol && one.hostname === two.hostname;
|
|
8821
|
+
} catch {
|
|
8822
|
+
return false;
|
|
8823
|
+
}
|
|
8824
|
+
}
|
|
8592
8825
|
/** Encodes the first 130 bits of `bytes` as 26 Crockford base32 characters. */
|
|
8593
8826
|
function crockford(bytes) {
|
|
8594
8827
|
let bits = 0;
|
|
@@ -8676,9 +8909,17 @@ var Capabilities = class {
|
|
|
8676
8909
|
#key;
|
|
8677
8910
|
#now;
|
|
8678
8911
|
#shellOrigin;
|
|
8912
|
+
#servesShell;
|
|
8913
|
+
/** Single-use stream and socket tickets (D158 item 5), by the SHA-256 of their secret. */
|
|
8914
|
+
#streamTickets = /* @__PURE__ */ new Map();
|
|
8679
8915
|
#tickets = /* @__PURE__ */ new Map();
|
|
8680
8916
|
/** One-time launch tickets (D140 item 15), by the SHA-256 of their secret. */
|
|
8681
8917
|
#launches = /* @__PURE__ */ new Map();
|
|
8918
|
+
/** The frame tickets and the stream tickets each session holds, oldest first. */
|
|
8919
|
+
#ticketsBySession = /* @__PURE__ */ new Map();
|
|
8920
|
+
#streamTicketsBySession = /* @__PURE__ */ new Map();
|
|
8921
|
+
/** When the tickets were last swept. */
|
|
8922
|
+
#swept = Number.NEGATIVE_INFINITY;
|
|
8682
8923
|
/** Failure times per artifact (`""` for tokens of no artifact in this home). */
|
|
8683
8924
|
#failures = /* @__PURE__ */ new Map();
|
|
8684
8925
|
#touched = /* @__PURE__ */ new Map();
|
|
@@ -8688,6 +8929,7 @@ var Capabilities = class {
|
|
|
8688
8929
|
this.#key = options.key;
|
|
8689
8930
|
this.#now = options.now;
|
|
8690
8931
|
this.#shellOrigin = options.shellOrigin;
|
|
8932
|
+
this.#servesShell = options.servesShell ?? ((origin) => origin === this.#shellOrigin());
|
|
8691
8933
|
}
|
|
8692
8934
|
/** Runs `fn` in the caller's transaction, or in a new one. */
|
|
8693
8935
|
#tx(db, fn) {
|
|
@@ -8707,7 +8949,7 @@ var Capabilities = class {
|
|
|
8707
8949
|
const tokenId = input.tokenId ?? TokenId.create();
|
|
8708
8950
|
const secret = this.secretOf(tokenId);
|
|
8709
8951
|
const scopes = normalizeScopes(input.scopes);
|
|
8710
|
-
const shellOrigin = this.#shellOrigin();
|
|
8952
|
+
const shellOrigin = input.shellOrigin ?? this.#shellOrigin();
|
|
8711
8953
|
db.run("INSERT INTO token (id, secret_hash, artifact_id, scopes_json, viewer_id, expires_at, revoked_at, created_at, is_default, pinned_version, shell_origin) VALUES (?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?)", tokenId, hashSecret(secret), input.artifactId, JSON.stringify(scopes), input.viewerId ?? null, input.expiresAt ?? null, this.#iso(this.#now()), input.isDefault ? 1 : 0, input.pinnedVersion ?? null, shellOrigin);
|
|
8712
8954
|
return {
|
|
8713
8955
|
tokenId,
|
|
@@ -8729,7 +8971,8 @@ var Capabilities = class {
|
|
|
8729
8971
|
expiresAt: input.ttlMs === void 0 ? void 0 : this.#iso(this.#now() + input.ttlMs),
|
|
8730
8972
|
pinnedVersion: input.pinnedVersion,
|
|
8731
8973
|
isDefault: false,
|
|
8732
|
-
viewerId: input.viewerId
|
|
8974
|
+
viewerId: input.viewerId,
|
|
8975
|
+
shellOrigin: input.shellOrigin
|
|
8733
8976
|
}));
|
|
8734
8977
|
}
|
|
8735
8978
|
/**
|
|
@@ -8738,12 +8981,13 @@ var Capabilities = class {
|
|
|
8738
8981
|
* key was replaced) stays valid for whoever holds it, and a new default takes its place; so does
|
|
8739
8982
|
* one minted for another shell address, which works again if the gateway returns there.
|
|
8740
8983
|
*/
|
|
8741
|
-
defaultLink(artifactId) {
|
|
8984
|
+
defaultLink(artifactId, shellOrigin) {
|
|
8985
|
+
const origin = shellOrigin ?? this.#shellOrigin();
|
|
8742
8986
|
return this.#ledger.write((db) => {
|
|
8743
8987
|
const row = db.get("SELECT * FROM token WHERE artifact_id = ? AND is_default = 1", artifactId);
|
|
8744
8988
|
if (row) {
|
|
8745
8989
|
const secret = this.secretOf(row.id);
|
|
8746
|
-
const here = row.shell_origin ===
|
|
8990
|
+
const here = row.shell_origin === origin;
|
|
8747
8991
|
if (here && safeEqual(hashSecret(secret), row.secret_hash)) return {
|
|
8748
8992
|
...grantOf(row),
|
|
8749
8993
|
secret
|
|
@@ -8758,7 +9002,8 @@ var Capabilities = class {
|
|
|
8758
9002
|
return this.#insert(db, {
|
|
8759
9003
|
artifactId,
|
|
8760
9004
|
scopes: ALL_SCOPES,
|
|
8761
|
-
isDefault: true
|
|
9005
|
+
isDefault: true,
|
|
9006
|
+
shellOrigin: origin
|
|
8762
9007
|
});
|
|
8763
9008
|
});
|
|
8764
9009
|
}
|
|
@@ -8770,6 +9015,19 @@ var Capabilities = class {
|
|
|
8770
9015
|
live: this.#live(row)
|
|
8771
9016
|
} : void 0;
|
|
8772
9017
|
}
|
|
9018
|
+
/**
|
|
9019
|
+
* The token that stands for `tokenId` now: itself, or the token its rotations led to (D97 item
|
|
9020
|
+
* 6), so what holds a token ID (a share) follows its link through `view/rotate`.
|
|
9021
|
+
*/
|
|
9022
|
+
current(tokenId) {
|
|
9023
|
+
let id = tokenId;
|
|
9024
|
+
for (let hop = 0; hop < 1e3; hop++) {
|
|
9025
|
+
const next = this.#ledger.read((db) => db.get("SELECT replaced_by FROM token WHERE id = ?", id)?.replaced_by ?? null);
|
|
9026
|
+
if (next === null) return id;
|
|
9027
|
+
id = next;
|
|
9028
|
+
}
|
|
9029
|
+
return id;
|
|
9030
|
+
}
|
|
8773
9031
|
/** The token's link again, from its derived secret, when the current key still derives it. */
|
|
8774
9032
|
reveal(tokenId) {
|
|
8775
9033
|
const row = this.#ledger.read((db) => db.get("SELECT * FROM token WHERE id = ?", tokenId));
|
|
@@ -8818,7 +9076,8 @@ var Capabilities = class {
|
|
|
8818
9076
|
expiresAt: grant.expiresAt,
|
|
8819
9077
|
pinnedVersion: grant.pinnedVersion,
|
|
8820
9078
|
isDefault: grant.isDefault,
|
|
8821
|
-
viewerId: grant.viewerId
|
|
9079
|
+
viewerId: grant.viewerId,
|
|
9080
|
+
shellOrigin: sameHost(grant.shellOrigin, this.#shellOrigin()) && !this.#servesShell(grant.shellOrigin) ? void 0 : grant.shellOrigin
|
|
8822
9081
|
});
|
|
8823
9082
|
appendEvent(db, {
|
|
8824
9083
|
artifactId: grant.artifactId,
|
|
@@ -8867,7 +9126,7 @@ var Capabilities = class {
|
|
|
8867
9126
|
* artifact, is `MOSTRA_HYGIENE_TOKEN_INVALID`; a revoked or expired one, or one minted for
|
|
8868
9127
|
* another shell address, `_TOKEN_REVOKED`. Unknown secrets count towards the limit.
|
|
8869
9128
|
*/
|
|
8870
|
-
presentToken(secret, artifactId) {
|
|
9129
|
+
presentToken(secret, artifactId, shellOrigin) {
|
|
8871
9130
|
const limited = this.limited(artifactId);
|
|
8872
9131
|
if (limited) return limited;
|
|
8873
9132
|
if (!looksLikeSecret(secret)) {
|
|
@@ -8880,7 +9139,7 @@ var Capabilities = class {
|
|
|
8880
9139
|
return refusal("MOSTRA_HYGIENE_TOKEN_INVALID", "No capability token in this home matches this link.");
|
|
8881
9140
|
}
|
|
8882
9141
|
if (!this.#live(row)) return refusal("MOSTRA_HYGIENE_TOKEN_REVOKED", row.revoked_at !== null ? "This link was revoked." : "This link has expired.");
|
|
8883
|
-
if (row.shell_origin !== this.#shellOrigin()) return refusal("MOSTRA_HYGIENE_TOKEN_REVOKED", `This link was made for ${row.shell_origin},
|
|
9142
|
+
if (row.shell_origin !== (shellOrigin ?? this.#shellOrigin())) return refusal("MOSTRA_HYGIENE_TOKEN_REVOKED", `This link was made for ${row.shell_origin}, not this address.`);
|
|
8884
9143
|
return grantOf(row);
|
|
8885
9144
|
}
|
|
8886
9145
|
/** Starts a session for a grant on one origin; returns the cookie secret and CSRF token. */
|
|
@@ -8889,7 +9148,7 @@ var Capabilities = class {
|
|
|
8889
9148
|
const csrf = csrfOf(cookie);
|
|
8890
9149
|
const id = hashSecret(cookie);
|
|
8891
9150
|
const now = this.#iso(this.#now());
|
|
8892
|
-
this.#ledger.write((db) => db.run("INSERT INTO session (id, token_id, origin, mode, csrf, version_id, created_at, last_seen_at, viewer_id) VALUES (?, ?, ?,
|
|
9151
|
+
this.#ledger.write((db) => db.run("INSERT INTO session (id, token_id, origin, mode, csrf, version_id, created_at, last_seen_at, viewer_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", id, input.tokenId, input.origin, input.mode ?? "cookie", hashSecret(csrf), input.versionId ?? null, now, now, input.viewerId ?? null));
|
|
8893
9152
|
return {
|
|
8894
9153
|
cookie,
|
|
8895
9154
|
csrf,
|
|
@@ -8901,13 +9160,13 @@ var Capabilities = class {
|
|
|
8901
9160
|
* value is tried, since another page of the host may have set a cookie of the same name (D98):
|
|
8902
9161
|
* only a session issued for this origin, whose token is live and grants this artifact, counts.
|
|
8903
9162
|
*/
|
|
8904
|
-
session(cookies, origin, artifactId) {
|
|
9163
|
+
session(cookies, origin, artifactId, mode = "cookie") {
|
|
8905
9164
|
let revoked = false;
|
|
8906
9165
|
for (const value of cookies) {
|
|
8907
9166
|
if (!looksLikeSecret(value)) continue;
|
|
8908
9167
|
const found = this.#ledger.read((db) => {
|
|
8909
9168
|
const session = db.get("SELECT * FROM session WHERE id = ?", hashSecret(value));
|
|
8910
|
-
if (!session || session.origin !== origin) return void 0;
|
|
9169
|
+
if (!session || session.origin !== origin || session.mode !== mode) return void 0;
|
|
8911
9170
|
const token = db.get("SELECT * FROM token WHERE id = ?", session.token_id);
|
|
8912
9171
|
return token && token.artifact_id === artifactId ? {
|
|
8913
9172
|
session,
|
|
@@ -8927,6 +9186,7 @@ var Capabilities = class {
|
|
|
8927
9186
|
return {
|
|
8928
9187
|
id: found.session.id,
|
|
8929
9188
|
csrf,
|
|
9189
|
+
mode,
|
|
8930
9190
|
...found.session.version_id !== null ? { versionId: found.session.version_id } : {},
|
|
8931
9191
|
grant,
|
|
8932
9192
|
...viewerId !== void 0 ? { viewerId } : {}
|
|
@@ -8945,17 +9205,30 @@ var Capabilities = class {
|
|
|
8945
9205
|
this.#touched.set(sessionId, now);
|
|
8946
9206
|
this.#ledger.write((db) => db.run("UPDATE session SET last_seen_at = ? WHERE id = ?", this.#iso(now), sessionId));
|
|
8947
9207
|
}
|
|
8948
|
-
/** Mints a single-use frame ticket (D98 item 3). */
|
|
9208
|
+
/** Mints a single-use frame ticket (D98 item 3); a shell session holds at most a few at once. */
|
|
8949
9209
|
mintTicket(grant) {
|
|
8950
9210
|
const ticket = randomSecret();
|
|
8951
9211
|
this.#sweepTickets();
|
|
8952
|
-
|
|
9212
|
+
const key = hashSecret(ticket);
|
|
9213
|
+
this.#tickets.set(key, {
|
|
8953
9214
|
...grant,
|
|
8954
9215
|
expires: this.#now() + TICKET_TTL_MS
|
|
8955
9216
|
});
|
|
9217
|
+
this.#hold(this.#ticketsBySession, this.#tickets, grant.shellSessionId, key);
|
|
8956
9218
|
return ticket;
|
|
8957
9219
|
}
|
|
8958
9220
|
/**
|
|
9221
|
+
* Records a session's new ticket and drops its oldest beyond {@link TICKETS_PER_SESSION}, so no
|
|
9222
|
+
* link holder can make the maps grow without bound by asking for tickets in a loop (Opus review
|
|
9223
|
+
* of WP-13). A page uses one or two at a time.
|
|
9224
|
+
*/
|
|
9225
|
+
#hold(bySession, tickets, sessionId, key) {
|
|
9226
|
+
const held = (bySession.get(sessionId) ?? []).filter((one) => tickets.has(one));
|
|
9227
|
+
held.push(key);
|
|
9228
|
+
while (held.length > 8) tickets.delete(held.shift());
|
|
9229
|
+
bySession.set(sessionId, held);
|
|
9230
|
+
}
|
|
9231
|
+
/**
|
|
8959
9232
|
* Redeems a ticket on `origin`, once, while the shell session that asked for it lives and its
|
|
8960
9233
|
* link is live (D98 item 3).
|
|
8961
9234
|
*/
|
|
@@ -8964,15 +9237,78 @@ var Capabilities = class {
|
|
|
8964
9237
|
const key = looksLikeSecret(ticket) ? hashSecret(ticket) : void 0;
|
|
8965
9238
|
const entry = key === void 0 ? void 0 : this.#tickets.get(key);
|
|
8966
9239
|
if (key !== void 0) this.#tickets.delete(key);
|
|
8967
|
-
if (!entry || entry.origin !== origin) return refusal("MOSTRA_HYGIENE_TOKEN_INVALID", "The frame ticket is unknown, used or expired.");
|
|
9240
|
+
if (!entry || entry.expires <= this.#now() || entry.origin !== origin) return refusal("MOSTRA_HYGIENE_TOKEN_INVALID", "The frame ticket is unknown, used or expired.");
|
|
8968
9241
|
if (this.#ledger.read((db) => db.get("SELECT token_id FROM session WHERE id = ?", entry.shellSessionId))?.token_id !== entry.tokenId) return refusal("MOSTRA_HYGIENE_SESSION_MISSING", "The shell session that asked for this frame ticket has ended.");
|
|
8969
9242
|
if (!this.grant(entry.tokenId)?.live) return refusal("MOSTRA_HYGIENE_TOKEN_REVOKED", "The link behind this frame was revoked or has expired.");
|
|
8970
9243
|
const { expires: _expires, ...rest } = entry;
|
|
8971
9244
|
return rest;
|
|
8972
9245
|
}
|
|
9246
|
+
/**
|
|
9247
|
+
* Mints a single-use ticket that opens one event stream, long poll or WebSocket of a session
|
|
9248
|
+
* without the session's credential (D158 item 5): a worker-mode page's streams bypass its
|
|
9249
|
+
* service worker, which can't carry them. It lives 60 s in memory and is never recorded.
|
|
9250
|
+
*/
|
|
9251
|
+
mintStreamTicket(input) {
|
|
9252
|
+
this.#sweepTickets();
|
|
9253
|
+
const ticket = randomSecret();
|
|
9254
|
+
const expires = this.#now() + TICKET_TTL_MS;
|
|
9255
|
+
const key = hashSecret(ticket);
|
|
9256
|
+
this.#streamTickets.set(key, {
|
|
9257
|
+
...input,
|
|
9258
|
+
expires
|
|
9259
|
+
});
|
|
9260
|
+
this.#hold(this.#streamTicketsBySession, this.#streamTickets, input.sessionId, key);
|
|
9261
|
+
return {
|
|
9262
|
+
ticket,
|
|
9263
|
+
expiresAt: this.#iso(expires)
|
|
9264
|
+
};
|
|
9265
|
+
}
|
|
9266
|
+
/**
|
|
9267
|
+
* Spends a stream ticket on `origin` for `artifactId` and `purpose`, and resolves its session
|
|
9268
|
+
* as a request carrying the session's credential would, its link's liveness included. The
|
|
9269
|
+
* session's CSRF token isn't known here: a ticket opens reads only (streams, polls, sockets).
|
|
9270
|
+
*/
|
|
9271
|
+
redeemStreamTicket(ticket, origin, artifactId, purpose) {
|
|
9272
|
+
this.#sweepTickets();
|
|
9273
|
+
const key = looksLikeSecret(ticket) ? hashSecret(ticket) : void 0;
|
|
9274
|
+
const entry = key === void 0 ? void 0 : this.#streamTickets.get(key);
|
|
9275
|
+
if (key !== void 0) this.#streamTickets.delete(key);
|
|
9276
|
+
if (!entry || entry.expires <= this.#now() || entry.origin !== origin || entry.artifactId !== artifactId || entry.purpose !== purpose) return refusal("MOSTRA_HYGIENE_TOKEN_INVALID", "The stream ticket is unknown, used or expired.");
|
|
9277
|
+
const found = this.#ledger.read((db) => {
|
|
9278
|
+
const session = db.get("SELECT * FROM session WHERE id = ?", entry.sessionId);
|
|
9279
|
+
if (!session || session.origin !== origin) return void 0;
|
|
9280
|
+
const token = db.get("SELECT * FROM token WHERE id = ?", session.token_id);
|
|
9281
|
+
return token && token.artifact_id === artifactId ? {
|
|
9282
|
+
session,
|
|
9283
|
+
token
|
|
9284
|
+
} : void 0;
|
|
9285
|
+
});
|
|
9286
|
+
if (!found) return refusal("MOSTRA_HYGIENE_SESSION_MISSING", "The session behind this ticket has ended.");
|
|
9287
|
+
if (!this.#live(found.token)) return refusal("MOSTRA_HYGIENE_TOKEN_REVOKED", "The link this session came from was revoked or has expired.");
|
|
9288
|
+
const grant = grantOf(found.token);
|
|
9289
|
+
const viewerId = grant.viewerId ?? found.session.viewer_id ?? void 0;
|
|
9290
|
+
return {
|
|
9291
|
+
id: found.session.id,
|
|
9292
|
+
csrf: "",
|
|
9293
|
+
mode: found.session.mode,
|
|
9294
|
+
...found.session.version_id !== null ? { versionId: found.session.version_id } : {},
|
|
9295
|
+
grant,
|
|
9296
|
+
...viewerId !== void 0 ? { viewerId } : {}
|
|
9297
|
+
};
|
|
9298
|
+
}
|
|
9299
|
+
/**
|
|
9300
|
+
* Drops expired tickets, at most once a second: every use checks a ticket's expiry itself, so a
|
|
9301
|
+
* sweep only frees memory, and a burst of requests never makes each one walk every ticket (Opus
|
|
9302
|
+
* review of WP-13).
|
|
9303
|
+
*/
|
|
8973
9304
|
#sweepTickets() {
|
|
8974
9305
|
const now = this.#now();
|
|
9306
|
+
if (now - this.#swept < SWEEP_INTERVAL_MS && now >= this.#swept) return;
|
|
9307
|
+
this.#swept = now;
|
|
9308
|
+
for (const [sessionId, held] of this.#ticketsBySession) if (!held.some((key) => this.#tickets.has(key))) this.#ticketsBySession.delete(sessionId);
|
|
9309
|
+
for (const [sessionId, held] of this.#streamTicketsBySession) if (!held.some((key) => this.#streamTickets.has(key))) this.#streamTicketsBySession.delete(sessionId);
|
|
8975
9310
|
for (const [key, entry] of this.#tickets) if (entry.expires <= now) this.#tickets.delete(key);
|
|
9311
|
+
for (const [key, entry] of this.#streamTickets) if (entry.expires <= now) this.#streamTickets.delete(key);
|
|
8976
9312
|
for (const [key, entry] of this.#launches) if (entry.expires <= now) this.#launches.delete(key);
|
|
8977
9313
|
}
|
|
8978
9314
|
/**
|
|
@@ -8984,7 +9320,7 @@ var Capabilities = class {
|
|
|
8984
9320
|
mintLaunch(tokenId) {
|
|
8985
9321
|
const grant = this.grant(tokenId);
|
|
8986
9322
|
if (!grant) return void 0;
|
|
8987
|
-
if (!grant.live || grant.shellOrigin
|
|
9323
|
+
if (!grant.live || !this.#servesShell(grant.shellOrigin)) return "dead";
|
|
8988
9324
|
this.#sweepTickets();
|
|
8989
9325
|
const ticket = randomSecret();
|
|
8990
9326
|
const expires = this.#now() + TICKET_TTL_MS;
|
|
@@ -9005,18 +9341,19 @@ var Capabilities = class {
|
|
|
9005
9341
|
* once a session exists, so a viewer who chooses between two links (D98 item 8) can still use it
|
|
9006
9342
|
* within its minute.
|
|
9007
9343
|
*/
|
|
9008
|
-
presentLaunch(ticket, artifactId, spend) {
|
|
9344
|
+
presentLaunch(ticket, artifactId, spend, shellOrigin) {
|
|
9009
9345
|
const limited = this.limited(artifactId);
|
|
9010
9346
|
if (limited) return limited;
|
|
9011
9347
|
this.#sweepTickets();
|
|
9012
9348
|
const key = looksLikeSecret(ticket) ? hashSecret(ticket) : void 0;
|
|
9013
|
-
const
|
|
9349
|
+
const found = key === void 0 ? void 0 : this.#launches.get(key);
|
|
9350
|
+
const entry = found && found.expires > this.#now() ? found : void 0;
|
|
9014
9351
|
const grant = entry ? this.grant(entry.tokenId) : void 0;
|
|
9015
9352
|
if (!entry || !grant || grant.artifactId !== artifactId) {
|
|
9016
9353
|
this.#fail(artifactId);
|
|
9017
9354
|
return refusal("MOSTRA_HYGIENE_TOKEN_INVALID", "The launch ticket is unknown, used or expired.");
|
|
9018
9355
|
}
|
|
9019
|
-
if (!grant.live || grant.shellOrigin !== this.#shellOrigin()) return refusal("MOSTRA_HYGIENE_TOKEN_REVOKED", "The link behind this launch ticket was revoked or
|
|
9356
|
+
if (!grant.live || grant.shellOrigin !== (shellOrigin ?? this.#shellOrigin())) return refusal("MOSTRA_HYGIENE_TOKEN_REVOKED", "The link behind this launch ticket was revoked, has expired, or is for another address.");
|
|
9020
9357
|
if (spend && key !== void 0) this.#launches.delete(key);
|
|
9021
9358
|
const { live: _live, ...rest } = grant;
|
|
9022
9359
|
return rest;
|
|
@@ -9028,7 +9365,11 @@ var Capabilities = class {
|
|
|
9028
9365
|
*/
|
|
9029
9366
|
spendLaunch(ticket) {
|
|
9030
9367
|
this.#sweepTickets();
|
|
9031
|
-
|
|
9368
|
+
if (!looksLikeSecret(ticket)) return false;
|
|
9369
|
+
const key = hashSecret(ticket);
|
|
9370
|
+
const entry = this.#launches.get(key);
|
|
9371
|
+
if (!entry || entry.expires <= this.#now()) return false;
|
|
9372
|
+
return this.#launches.delete(key);
|
|
9032
9373
|
}
|
|
9033
9374
|
/** Removes sessions unseen for longer than their cookie lives; no browser holds them any more. */
|
|
9034
9375
|
prune() {
|
|
@@ -9135,6 +9476,144 @@ function devUpgrade(upstream, incoming, socket, head) {
|
|
|
9135
9476
|
});
|
|
9136
9477
|
}
|
|
9137
9478
|
//#endregion
|
|
9479
|
+
//#region src/gateway/identity.ts
|
|
9480
|
+
/**
|
|
9481
|
+
* Who a browser is (D143 item 2). A link minted with a viewer acts for that viewer (D104) and asks
|
|
9482
|
+
* nothing. For a link without one, a host that registered the `identity` port names the person
|
|
9483
|
+
* from the request's headers; without such a host, the session acts as the home's local user.
|
|
9484
|
+
*/
|
|
9485
|
+
/** How long a host has to answer `port/identity.resolve`: a page waits for it, as for D108. */
|
|
9486
|
+
const IDENTITY_TIMEOUT_MS = 5e3;
|
|
9487
|
+
/**
|
|
9488
|
+
* The headers a host sees: names in lower case, without `cookie` (Mostra's sessions and every
|
|
9489
|
+
* other page's of this host) and without Mostra's own `x-mostra-*` headers.
|
|
9490
|
+
*/
|
|
9491
|
+
function identityHeaders(headers) {
|
|
9492
|
+
const seen = {};
|
|
9493
|
+
headers.forEach((value, name) => {
|
|
9494
|
+
const key = name.toLowerCase();
|
|
9495
|
+
if (key === "cookie" || key.startsWith("x-mostra-")) return;
|
|
9496
|
+
seen[key] = value;
|
|
9497
|
+
});
|
|
9498
|
+
return seen;
|
|
9499
|
+
}
|
|
9500
|
+
/**
|
|
9501
|
+
* Asks the host that took identity over. Its outage never makes the session someone else: a
|
|
9502
|
+
* failure, a timeout, an answer the schema refuses, or an expected host that isn't connected is
|
|
9503
|
+
* `unavailable`, and the exchange is refused.
|
|
9504
|
+
*/
|
|
9505
|
+
async function resolveIdentity(input) {
|
|
9506
|
+
const registrant = input.registrant();
|
|
9507
|
+
const unavailable = (message) => ({
|
|
9508
|
+
kind: "unavailable",
|
|
9509
|
+
diagnostic: createDiagnostic("MOSTRA_HOST_IDENTITY_UNAVAILABLE", { message })
|
|
9510
|
+
});
|
|
9511
|
+
if (registrant) try {
|
|
9512
|
+
const answer = await input.call(registrant.session, {
|
|
9513
|
+
artifactId: input.artifactId,
|
|
9514
|
+
via: input.via,
|
|
9515
|
+
headers: identityHeaders(input.headers)
|
|
9516
|
+
});
|
|
9517
|
+
const parsed = portIdentityResolveMethod.result.safeParse(answer);
|
|
9518
|
+
if (parsed.success) return parsed.data === null ? { kind: "default" } : {
|
|
9519
|
+
kind: "person",
|
|
9520
|
+
viewer: parsed.data
|
|
9521
|
+
};
|
|
9522
|
+
input.log.warn("gateway.identity_invalid", {
|
|
9523
|
+
owner: registrant.owner,
|
|
9524
|
+
artifactId: input.artifactId
|
|
9525
|
+
});
|
|
9526
|
+
return unavailable(`The host ${registrant.owner} answered who this is in a form Mostra refuses.`);
|
|
9527
|
+
} catch (error) {
|
|
9528
|
+
input.log.warn("gateway.identity_failed", {
|
|
9529
|
+
owner: registrant.owner,
|
|
9530
|
+
artifactId: input.artifactId,
|
|
9531
|
+
error: error.message
|
|
9532
|
+
});
|
|
9533
|
+
return unavailable(`The host ${registrant.owner} didn't say who this is.`);
|
|
9534
|
+
}
|
|
9535
|
+
const away = input.expected();
|
|
9536
|
+
if (away.length > 0) {
|
|
9537
|
+
input.log.warn("gateway.identity_host_away", {
|
|
9538
|
+
owners: away,
|
|
9539
|
+
artifactId: input.artifactId
|
|
9540
|
+
});
|
|
9541
|
+
return unavailable(`The host that identifies this home's viewers (${away.join(", ")}) isn't running.`);
|
|
9542
|
+
}
|
|
9543
|
+
return { kind: "default" };
|
|
9544
|
+
}
|
|
9545
|
+
/**
|
|
9546
|
+
* Decodes RFC 2047 encoded words (`=?utf-8?q?Ferris_B=C3=BCller?=`, and `b` for base64), as
|
|
9547
|
+
* Tailscale Serve writes a non-ASCII name; text outside encoded words is kept, and whitespace
|
|
9548
|
+
* between two encoded words is dropped (RFC 2047 §6.2). Anything malformed is kept as written.
|
|
9549
|
+
*/
|
|
9550
|
+
function decodeEncodedWords(value) {
|
|
9551
|
+
const word = /=\?([^?\s]+)\?([qQbB])\?([^?\s]*)\?=/g;
|
|
9552
|
+
const decodeOne = (charset, encoding, text) => {
|
|
9553
|
+
let bytes;
|
|
9554
|
+
if (encoding.toLowerCase() === "b") bytes = Buffer.from(text, "base64");
|
|
9555
|
+
else {
|
|
9556
|
+
const out = [];
|
|
9557
|
+
for (let index = 0; index < text.length; index++) {
|
|
9558
|
+
const char = text[index];
|
|
9559
|
+
if (char === "_") out.push(32);
|
|
9560
|
+
else if (char === "=" && /^[0-9A-Fa-f]{2}$/.test(text.slice(index + 1, index + 3))) {
|
|
9561
|
+
out.push(Number.parseInt(text.slice(index + 1, index + 3), 16));
|
|
9562
|
+
index += 2;
|
|
9563
|
+
} else out.push(char.charCodeAt(0) & 255);
|
|
9564
|
+
}
|
|
9565
|
+
bytes = Uint8Array.from(out);
|
|
9566
|
+
}
|
|
9567
|
+
try {
|
|
9568
|
+
return new TextDecoder(charset, { fatal: true }).decode(bytes);
|
|
9569
|
+
} catch {
|
|
9570
|
+
return;
|
|
9571
|
+
}
|
|
9572
|
+
};
|
|
9573
|
+
let result = "";
|
|
9574
|
+
let last = 0;
|
|
9575
|
+
let previousWasWord = false;
|
|
9576
|
+
for (const match of value.matchAll(word)) {
|
|
9577
|
+
const between = value.slice(last, match.index);
|
|
9578
|
+
const decoded = decodeOne(match[1], match[2], match[3]);
|
|
9579
|
+
if (decoded === void 0) {
|
|
9580
|
+
result += between + match[0];
|
|
9581
|
+
previousWasWord = false;
|
|
9582
|
+
} else {
|
|
9583
|
+
result += previousWasWord && /^\s*$/.test(between) ? "" : between;
|
|
9584
|
+
result += decoded;
|
|
9585
|
+
previousWasWord = true;
|
|
9586
|
+
}
|
|
9587
|
+
last = match.index + match[0].length;
|
|
9588
|
+
}
|
|
9589
|
+
return result + value.slice(last);
|
|
9590
|
+
}
|
|
9591
|
+
/** Whether a connection's peer is this machine: the only way a tunnel tool reaches a face. */
|
|
9592
|
+
function isLoopbackPeer(remote) {
|
|
9593
|
+
if (remote === void 0) return false;
|
|
9594
|
+
const address = remote.startsWith("::ffff:") ? remote.slice(7) : remote;
|
|
9595
|
+
return address === "::1" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(address);
|
|
9596
|
+
}
|
|
9597
|
+
/**
|
|
9598
|
+
* The tailnet person Tailscale Serve names in a request (D158 item 2): `Tailscale-User-Login` and
|
|
9599
|
+
* `Tailscale-User-Name`, which Serve sets on every tailnet request after removing any a client
|
|
9600
|
+
* sent. They are believed only from a loopback peer (faces bind loopback, so only `tailscaled` and
|
|
9601
|
+
* this machine's own programs reach them) and never beside `Tailscale-Funnel-Request`, which
|
|
9602
|
+
* marks a public request. A tagged device sends no login, so nobody is named.
|
|
9603
|
+
*/
|
|
9604
|
+
function tailnetPerson(headers, remote) {
|
|
9605
|
+
if (!isLoopbackPeer(remote) || headers.has("tailscale-funnel-request")) return void 0;
|
|
9606
|
+
const login = headers.get("tailscale-user-login");
|
|
9607
|
+
if (login === null) return void 0;
|
|
9608
|
+
const ref = decodeEncodedWords(login).trim();
|
|
9609
|
+
if (ref === "" || ref.length > 512) return void 0;
|
|
9610
|
+
const name = decodeEncodedWords(headers.get("tailscale-user-name") ?? "").trim();
|
|
9611
|
+
return {
|
|
9612
|
+
ref,
|
|
9613
|
+
...name !== "" && name.length <= 256 ? { name } : {}
|
|
9614
|
+
};
|
|
9615
|
+
}
|
|
9616
|
+
//#endregion
|
|
9138
9617
|
//#region src/gateway/integrity.ts
|
|
9139
9618
|
/**
|
|
9140
9619
|
* Integrity of served versions (FAILURE_MODEL §3: reads verify content). Before a version's
|
|
@@ -9236,7 +9715,9 @@ function versionIntegrity(store, log) {
|
|
|
9236
9715
|
* 1. the `Origin` and content type its intent needs (`checkRequest`; the envelope was checked
|
|
9237
9716
|
* before routing);
|
|
9238
9717
|
* 2. the rate limit, on token paths;
|
|
9239
|
-
* 3. the session, bound to this origin, with a live token (401, 410)
|
|
9718
|
+
* 3. the session, bound to this origin, with a live token (401, 410): its cookie in cookie mode,
|
|
9719
|
+
* its frame header in worker mode (D70), or a single-use stream ticket on stream routes
|
|
9720
|
+
* (D158 item 5);
|
|
9240
9721
|
* 4. the session's CSRF token, on mutations;
|
|
9241
9722
|
* 5. the scope.
|
|
9242
9723
|
*
|
|
@@ -9290,9 +9771,12 @@ function mount(app, checks, routes) {
|
|
|
9290
9771
|
const limited = checks.capabilities.limited(artifactId);
|
|
9291
9772
|
if (limited) return refuse(checks, limited, meta);
|
|
9292
9773
|
}
|
|
9774
|
+
const mode = checks.mode?.() ?? "cookie";
|
|
9775
|
+
const ticket = route.intent === "stream" ? url.searchParams.get("ticket") : null;
|
|
9776
|
+
if (route.sse && (checks.streams?.() === false || mode === "worker" && ticket === null)) return refuse(checks, refusal("MOSTRA_HYGIENE_NOT_SERVED", checks.streams?.() === false ? "Event streams don't pass this address; long-poll instead (events/poll)." : "A worker-mode frame opens its event stream with a ticket; long-poll instead.", 503), meta);
|
|
9293
9777
|
let session;
|
|
9294
9778
|
if (route.auth === "session" && artifactId !== void 0) {
|
|
9295
|
-
const resolved = checks.capabilities.session(cookieValues(request.headers.get("cookie"), checks.cookieName()), policy.origin, artifactId);
|
|
9779
|
+
const resolved = ticket !== null ? checks.capabilities.redeemStreamTicket(ticket, policy.origin, artifactId, "stream") : mode === "worker" ? checks.capabilities.session([request.headers.get(FRAME_SESSION_HEADER) ?? ""], policy.origin, artifactId, "worker") : checks.capabilities.session(cookieValues(request.headers.get("cookie"), checks.cookieName()), policy.origin, artifactId);
|
|
9296
9780
|
if (isRefusal(resolved)) return refuse(checks, resolved, meta);
|
|
9297
9781
|
session = resolved;
|
|
9298
9782
|
if (route.intent === "mutation") {
|
|
@@ -9312,7 +9796,8 @@ function mount(app, checks, routes) {
|
|
|
9312
9796
|
params,
|
|
9313
9797
|
artifactId,
|
|
9314
9798
|
...session ? { session } : {},
|
|
9315
|
-
document
|
|
9799
|
+
document,
|
|
9800
|
+
remote: incoming.socket.remoteAddress
|
|
9316
9801
|
});
|
|
9317
9802
|
};
|
|
9318
9803
|
if (route.method === "GET") app.get(route.path, handle);
|
|
@@ -9669,6 +10154,207 @@ function fileResponse(file, request, headers) {
|
|
|
9669
10154
|
});
|
|
9670
10155
|
}
|
|
9671
10156
|
//#endregion
|
|
10157
|
+
//#region src/gateway/worker.ts
|
|
10158
|
+
/**
|
|
10159
|
+
* Worker-mode frame sessions (D70, D158 item 5): where the shell and the artifact are two sites,
|
|
10160
|
+
* no cookie reaches the artifact's frame (VERIFIED_FACTS, cross-site frames). The frame enters
|
|
10161
|
+
* through a bootstrap page instead: it exchanges the shell's single-use ticket for a frame
|
|
10162
|
+
* session, installs Mostra's service worker at `/`, and enters the version, whose every
|
|
10163
|
+
* same-origin request then carries the session in a header. Event streams, polls and WebSockets
|
|
10164
|
+
* bypass the worker with single-use tickets, since Firefox stalls on endless responses a worker
|
|
10165
|
+
* passes on.
|
|
10166
|
+
*
|
|
10167
|
+
* This module holds the two documents the browser runs: the bootstrap page and the worker. Both
|
|
10168
|
+
* are plain scripts with no imports, served by the gateway from the artifact's origin.
|
|
10169
|
+
*/
|
|
10170
|
+
/** Where the service worker is served; its registration's scope is `/`. */
|
|
10171
|
+
const SERVICE_WORKER_PATH = "/_mostra/sw.js";
|
|
10172
|
+
/** The IndexedDB the frame session's secret is kept in, per artifact origin and top-level site. */
|
|
10173
|
+
const DB = "mostra-frame";
|
|
10174
|
+
/**
|
|
10175
|
+
* The service worker (D70): it adds the frame session's header to every same-origin request but
|
|
10176
|
+
* its own script, the bootstrap's, and ticketed ones (`?ticket=`: streams, polls and sockets),
|
|
10177
|
+
* and keeps the secret in IndexedDB, since a browser stops idle workers and their memory goes.
|
|
10178
|
+
* A request a header can't be added to as made (a `no-cors` script or image, a navigation) is
|
|
10179
|
+
* sent again as a same-origin request, which carries it.
|
|
10180
|
+
*/
|
|
10181
|
+
const SERVICE_WORKER_SOURCE = `// Mostra's frame-session worker (D70). It signs this origin's requests for the artifact's frame.
|
|
10182
|
+
"use strict";
|
|
10183
|
+
const HEADER = ${JSON.stringify(FRAME_SESSION_HEADER)};
|
|
10184
|
+
const DB = ${JSON.stringify(DB)};
|
|
10185
|
+
const STORE = "session";
|
|
10186
|
+
let secret;
|
|
10187
|
+
function store(mode, act) {
|
|
10188
|
+
return new Promise((resolve, reject) => {
|
|
10189
|
+
const open = indexedDB.open(DB, 1);
|
|
10190
|
+
open.onupgradeneeded = () => open.result.createObjectStore(STORE);
|
|
10191
|
+
open.onerror = () => reject(open.error);
|
|
10192
|
+
open.onsuccess = () => {
|
|
10193
|
+
const db = open.result;
|
|
10194
|
+
const tx = db.transaction(STORE, mode);
|
|
10195
|
+
const request = act(tx.objectStore(STORE));
|
|
10196
|
+
tx.oncomplete = () => { db.close(); resolve(request.result); };
|
|
10197
|
+
tx.onerror = tx.onabort = () => { db.close(); reject(tx.error); };
|
|
10198
|
+
};
|
|
10199
|
+
});
|
|
10200
|
+
}
|
|
10201
|
+
async function current() {
|
|
10202
|
+
if (secret === undefined) {
|
|
10203
|
+
try { secret = await store("readonly", (s) => s.get("secret")); } catch { secret = undefined; }
|
|
10204
|
+
}
|
|
10205
|
+
return secret;
|
|
10206
|
+
}
|
|
10207
|
+
self.addEventListener("install", () => { self.skipWaiting(); });
|
|
10208
|
+
self.addEventListener("activate", (event) => { event.waitUntil(self.clients.claim()); });
|
|
10209
|
+
self.addEventListener("message", (event) => {
|
|
10210
|
+
const data = event.data;
|
|
10211
|
+
if (!data || data.type !== "mostra/frame-session" || typeof data.secret !== "string") return;
|
|
10212
|
+
secret = data.secret;
|
|
10213
|
+
const port = event.ports[0];
|
|
10214
|
+
event.waitUntil(
|
|
10215
|
+
store("readwrite", (s) => s.put(data.secret, "secret")).then(
|
|
10216
|
+
() => port && port.postMessage({ ok: true }),
|
|
10217
|
+
(error) => port && port.postMessage({ ok: false, message: String(error) }),
|
|
10218
|
+
),
|
|
10219
|
+
);
|
|
10220
|
+
});
|
|
10221
|
+
self.addEventListener("fetch", (event) => {
|
|
10222
|
+
const request = event.request;
|
|
10223
|
+
const url = new URL(request.url);
|
|
10224
|
+
if (url.origin !== self.location.origin) return;
|
|
10225
|
+
if (url.pathname === ${JSON.stringify(SERVICE_WORKER_PATH)} || url.pathname === "/_mostra/enter") return;
|
|
10226
|
+
if (url.searchParams.has("ticket")) return;
|
|
10227
|
+
event.respondWith(signed(request));
|
|
10228
|
+
});
|
|
10229
|
+
async function signed(request) {
|
|
10230
|
+
const value = await current();
|
|
10231
|
+
if (!value) return fetch(request);
|
|
10232
|
+
const headers = new Headers(request.headers);
|
|
10233
|
+
headers.set(HEADER, value);
|
|
10234
|
+
const navigate = request.mode === "navigate";
|
|
10235
|
+
// Sent on, a navigation is an ordinary request: the gateway learns it was one from this header.
|
|
10236
|
+
if (navigate) headers.set("x-mostra-navigation", "1");
|
|
10237
|
+
const init = {
|
|
10238
|
+
method: request.method,
|
|
10239
|
+
headers,
|
|
10240
|
+
mode: navigate || request.mode === "no-cors" ? "same-origin" : request.mode,
|
|
10241
|
+
credentials: request.credentials,
|
|
10242
|
+
cache: request.cache === "only-if-cached" ? "default" : request.cache,
|
|
10243
|
+
redirect: navigate ? "manual" : request.redirect,
|
|
10244
|
+
referrerPolicy: request.referrerPolicy,
|
|
10245
|
+
integrity: request.integrity,
|
|
10246
|
+
keepalive: request.keepalive,
|
|
10247
|
+
signal: request.signal,
|
|
10248
|
+
};
|
|
10249
|
+
if (request.method !== "GET" && request.method !== "HEAD") init.body = await request.arrayBuffer();
|
|
10250
|
+
return fetch(new Request(request.url, init));
|
|
10251
|
+
}
|
|
10252
|
+
`;
|
|
10253
|
+
/**
|
|
10254
|
+
* The bootstrap page at `/_mostra/enter#t=<ticket>` (D70): it takes the ticket from the fragment
|
|
10255
|
+
* (so no server, log or `Referer` sees it), exchanges it at `POST /_mostra/enter` (sending the
|
|
10256
|
+
* session it kept, so a frame that re-enters keeps its session and switches version), installs
|
|
10257
|
+
* the worker at `/`, hands it the secret, tells the shell (`mostra/frameSession.entered`) and
|
|
10258
|
+
* enters the version at `/`. Whatever stops it is reported to the shell as
|
|
10259
|
+
* `mostra/frameSession.failed` with `MOSTRA_HYGIENE_FRAME_SESSION`.
|
|
10260
|
+
*/
|
|
10261
|
+
const BOOTSTRAP_PAGE = `<!doctype html>
|
|
10262
|
+
<html lang="en">
|
|
10263
|
+
<head>
|
|
10264
|
+
<meta charset="utf-8">
|
|
10265
|
+
<meta name="referrer" content="no-referrer">
|
|
10266
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
10267
|
+
<title>Mostra</title>
|
|
10268
|
+
<style>body{font-family:system-ui,sans-serif;margin:0;min-height:100vh;display:flex;justify-content:center;align-items:center;padding:2rem;text-align:center;color-scheme:light dark;opacity:.8}</style>
|
|
10269
|
+
</head>
|
|
10270
|
+
<body>
|
|
10271
|
+
<script>
|
|
10272
|
+
(async () => {
|
|
10273
|
+
"use strict";
|
|
10274
|
+
const HEADER = ${JSON.stringify(FRAME_SESSION_HEADER)};
|
|
10275
|
+
let shell = "*";
|
|
10276
|
+
const fail = (reason, message) => {
|
|
10277
|
+
document.body.textContent = message;
|
|
10278
|
+
parent.postMessage(
|
|
10279
|
+
{ jsonrpc: "2.0", method: "mostra/frameSession.failed",
|
|
10280
|
+
params: { code: "MOSTRA_HYGIENE_FRAME_SESSION", reason, message } },
|
|
10281
|
+
shell,
|
|
10282
|
+
);
|
|
10283
|
+
};
|
|
10284
|
+
const kept = () => new Promise((resolve) => {
|
|
10285
|
+
try {
|
|
10286
|
+
const open = indexedDB.open(${JSON.stringify(DB)}, 1);
|
|
10287
|
+
open.onupgradeneeded = () => open.result.createObjectStore("session");
|
|
10288
|
+
open.onerror = () => resolve(undefined);
|
|
10289
|
+
open.onsuccess = () => {
|
|
10290
|
+
const db = open.result;
|
|
10291
|
+
try {
|
|
10292
|
+
const read = db.transaction("session", "readonly").objectStore("session").get("secret");
|
|
10293
|
+
read.onsuccess = () => { db.close(); resolve(typeof read.result === "string" ? read.result : undefined); };
|
|
10294
|
+
read.onerror = () => { db.close(); resolve(undefined); };
|
|
10295
|
+
} catch { db.close(); resolve(undefined); }
|
|
10296
|
+
};
|
|
10297
|
+
} catch { resolve(undefined); }
|
|
10298
|
+
});
|
|
10299
|
+
const ticket = new URLSearchParams(location.hash.slice(1)).get("t");
|
|
10300
|
+
history.replaceState(null, "", location.pathname);
|
|
10301
|
+
if (!ticket) return fail("refused", "This frame was opened without a ticket.");
|
|
10302
|
+
if (!("serviceWorker" in navigator) || typeof indexedDB === "undefined") {
|
|
10303
|
+
return fail("unsupported", "This browser offers the artifact's frame no service worker here, which this link needs.");
|
|
10304
|
+
}
|
|
10305
|
+
let answer;
|
|
10306
|
+
try {
|
|
10307
|
+
const previous = await kept();
|
|
10308
|
+
const response = await fetch("/_mostra/enter", {
|
|
10309
|
+
method: "POST",
|
|
10310
|
+
credentials: "omit",
|
|
10311
|
+
cache: "no-store",
|
|
10312
|
+
headers: { "content-type": "application/json", ...(previous ? { [HEADER]: previous } : {}) },
|
|
10313
|
+
body: JSON.stringify({ ticket }),
|
|
10314
|
+
});
|
|
10315
|
+
answer = await response.json().catch(() => ({}));
|
|
10316
|
+
if (!response.ok) return fail("refused", answer.message || "The frame's entry was refused.");
|
|
10317
|
+
} catch (error) {
|
|
10318
|
+
return fail("refused", "The frame couldn't reach Mostra: " + error);
|
|
10319
|
+
}
|
|
10320
|
+
shell = answer.shellOrigin;
|
|
10321
|
+
try {
|
|
10322
|
+
const found = await navigator.serviceWorker.getRegistration("/");
|
|
10323
|
+
const script = found && (found.active || found.waiting || found.installing);
|
|
10324
|
+
if (script && new URL(script.scriptURL).pathname !== ${JSON.stringify(SERVICE_WORKER_PATH)}) {
|
|
10325
|
+
console.warn("Mostra replaced another service worker at / on this origin: a worker-mode frame needs its own there (MOSTRA_HYGIENE_FRAME_SESSION).");
|
|
10326
|
+
}
|
|
10327
|
+
const registration = await navigator.serviceWorker.register(${JSON.stringify(SERVICE_WORKER_PATH)}, { scope: "/", updateViaCache: "none" });
|
|
10328
|
+
const worker = registration.installing || registration.waiting || registration.active;
|
|
10329
|
+
if (!worker) throw new Error("no worker");
|
|
10330
|
+
if (worker.state !== "activated") {
|
|
10331
|
+
await new Promise((resolve, reject) => {
|
|
10332
|
+
const timer = setTimeout(() => reject(new Error("the worker didn't activate in 20 s")), 20000);
|
|
10333
|
+
worker.addEventListener("statechange", () => {
|
|
10334
|
+
if (worker.state === "activated") { clearTimeout(timer); resolve(); }
|
|
10335
|
+
if (worker.state === "redundant") { clearTimeout(timer); reject(new Error("the worker was replaced")); }
|
|
10336
|
+
});
|
|
10337
|
+
});
|
|
10338
|
+
}
|
|
10339
|
+
const stored = await new Promise((resolve) => {
|
|
10340
|
+
const channel = new MessageChannel();
|
|
10341
|
+
const timer = setTimeout(() => resolve({ ok: false, message: "no answer" }), 10000);
|
|
10342
|
+
channel.port1.onmessage = (event) => { clearTimeout(timer); resolve(event.data); };
|
|
10343
|
+
worker.postMessage({ type: "mostra/frame-session", secret: answer.session }, [channel.port2]);
|
|
10344
|
+
});
|
|
10345
|
+
if (!stored || !stored.ok) throw new Error(stored && stored.message);
|
|
10346
|
+
} catch (error) {
|
|
10347
|
+
return fail("blocked", "This browser didn't let the artifact's frame install the service worker this link needs (" + error + ").");
|
|
10348
|
+
}
|
|
10349
|
+
// The shell waits for the page from here: this page's own load wasn't the page's.
|
|
10350
|
+
parent.postMessage({ jsonrpc: "2.0", method: "mostra/frameSession.entered", params: {} }, shell);
|
|
10351
|
+
location.replace("/");
|
|
10352
|
+
})();
|
|
10353
|
+
<\/script>
|
|
10354
|
+
</body>
|
|
10355
|
+
</html>
|
|
10356
|
+
`;
|
|
10357
|
+
//#endregion
|
|
9672
10358
|
//#region src/gateway/controls.ts
|
|
9673
10359
|
/**
|
|
9674
10360
|
* The submit channels and trusted controls in force for a view (D40, D108). A host that
|
|
@@ -9727,108 +10413,56 @@ function normalize(policy) {
|
|
|
9727
10413
|
};
|
|
9728
10414
|
}
|
|
9729
10415
|
//#endregion
|
|
9730
|
-
//#region src/gateway/
|
|
10416
|
+
//#region src/gateway/index.ts
|
|
9731
10417
|
/**
|
|
9732
|
-
*
|
|
9733
|
-
*
|
|
9734
|
-
*
|
|
10418
|
+
* The gateway (ARCHITECTURE §5, §10; D38, D96 to D99, D158): the HTTP side of an instance. It
|
|
10419
|
+
* serves the shell on the shell's leased port and each opened artifact on its own leased port, all
|
|
10420
|
+
* on one host, so the shell and every artifact are same-site but different origins. Only
|
|
10421
|
+
* capability holders get in: a link's token becomes a shell session, the shell hands the
|
|
10422
|
+
* artifact's frame a single-use ticket, and the frame's session lets it load its version's files.
|
|
10423
|
+
* Every request goes through the same checks (`routes.ts`), and published versions are served
|
|
10424
|
+
* straight from disk, with no process (RT-05). It also serves `view/url`, `view/rotate` and
|
|
10425
|
+
* `view/revoke`.
|
|
10426
|
+
*
|
|
10427
|
+
* Beside those loopback listeners, the gateway has **faces** (D158 item 1): external addresses of
|
|
10428
|
+
* the shell or one artifact (a tailnet, Funnel or Cloudflare address a share set up, or a host's
|
|
10429
|
+
* external base), each its own listener on loopback with one origin and one exact `Host`. Which
|
|
10430
|
+
* face a request came through is the socket it arrived on, so a tunnel's visitor can't claim
|
|
10431
|
+
* another address. A face pairs with the faces of its group (a share's, a host's): its shell opens
|
|
10432
|
+
* frames on the group's artifact face, in cookie mode when both are one site and in worker mode
|
|
10433
|
+
* (D70) when they are two.
|
|
10434
|
+
*
|
|
10435
|
+
* ```ts
|
|
10436
|
+
* const gateway = createGateway({ ledger, log, addressing, capabilities, artifacts, shellDir });
|
|
10437
|
+
* await gateway.start();
|
|
10438
|
+
* const { url } = await gateway.defaultLink(artifactId); // the publish receipt's URL
|
|
10439
|
+
* const face = await gateway.openFace({ by: "cloudflare", group, listener: "shell", … });
|
|
10440
|
+
* ```
|
|
9735
10441
|
*/
|
|
9736
|
-
|
|
9737
|
-
|
|
10442
|
+
const NO_STORE = { "cache-control": "no-store" };
|
|
10443
|
+
/** How recently an artifact must have been viewed for its port to be bound at start (D129). */
|
|
10444
|
+
const RECENT_VIEW_MS = 6048e5;
|
|
10445
|
+
/** How long a host's answer for an artifact's frame address is reused (D158 item 6). */
|
|
10446
|
+
const EXTERNAL_BASE_REUSE_MS = 3e4;
|
|
9738
10447
|
/**
|
|
9739
|
-
*
|
|
9740
|
-
*
|
|
10448
|
+
* How long a withdrawn face's listener stays open, refusing everything, so the request that
|
|
10449
|
+
* learned of the withdrawal still gets its answer (D158 item 6).
|
|
9741
10450
|
*/
|
|
9742
|
-
|
|
9743
|
-
|
|
9744
|
-
|
|
9745
|
-
|
|
9746
|
-
if (key === "cookie" || key.startsWith("x-mostra-")) return;
|
|
9747
|
-
seen[key] = value;
|
|
9748
|
-
});
|
|
9749
|
-
return seen;
|
|
10451
|
+
const FACE_LINGER_MS = 2e3;
|
|
10452
|
+
/** The key of a face: `<group>:shell`, or `<group>:<artifactId>` for an artifact's. */
|
|
10453
|
+
function faceKey(group, listener, artifactId) {
|
|
10454
|
+
return `${group}:${listener === "shell" ? "shell" : artifactId ?? ""}`;
|
|
9750
10455
|
}
|
|
9751
10456
|
/**
|
|
9752
|
-
* Asks the host that took identity over. Its outage never makes the session someone else: a
|
|
9753
|
-
* failure, a timeout, an answer the schema refuses, or an expected host that isn't connected is
|
|
9754
|
-
* `unavailable`, and the exchange is refused.
|
|
9755
|
-
*/
|
|
9756
|
-
async function resolveIdentity(input) {
|
|
9757
|
-
const registrant = input.registrant();
|
|
9758
|
-
const unavailable = (message) => ({
|
|
9759
|
-
kind: "unavailable",
|
|
9760
|
-
diagnostic: createDiagnostic("MOSTRA_HOST_IDENTITY_UNAVAILABLE", { message })
|
|
9761
|
-
});
|
|
9762
|
-
if (registrant) try {
|
|
9763
|
-
const answer = await input.call(registrant.session, {
|
|
9764
|
-
artifactId: input.artifactId,
|
|
9765
|
-
via: input.via,
|
|
9766
|
-
headers: identityHeaders(input.headers)
|
|
9767
|
-
});
|
|
9768
|
-
const parsed = portIdentityResolveMethod.result.safeParse(answer);
|
|
9769
|
-
if (parsed.success) return parsed.data === null ? { kind: "default" } : {
|
|
9770
|
-
kind: "person",
|
|
9771
|
-
viewer: parsed.data
|
|
9772
|
-
};
|
|
9773
|
-
input.log.warn("gateway.identity_invalid", {
|
|
9774
|
-
owner: registrant.owner,
|
|
9775
|
-
artifactId: input.artifactId
|
|
9776
|
-
});
|
|
9777
|
-
return unavailable(`The host ${registrant.owner} answered who this is in a form Mostra refuses.`);
|
|
9778
|
-
} catch (error) {
|
|
9779
|
-
input.log.warn("gateway.identity_failed", {
|
|
9780
|
-
owner: registrant.owner,
|
|
9781
|
-
artifactId: input.artifactId,
|
|
9782
|
-
error: error.message
|
|
9783
|
-
});
|
|
9784
|
-
return unavailable(`The host ${registrant.owner} didn't say who this is.`);
|
|
9785
|
-
}
|
|
9786
|
-
const away = input.expected();
|
|
9787
|
-
if (away.length > 0) {
|
|
9788
|
-
input.log.warn("gateway.identity_host_away", {
|
|
9789
|
-
owners: away,
|
|
9790
|
-
artifactId: input.artifactId
|
|
9791
|
-
});
|
|
9792
|
-
return unavailable(`The host that identifies this home's viewers (${away.join(", ")}) isn't running.`);
|
|
9793
|
-
}
|
|
9794
|
-
return { kind: "default" };
|
|
9795
|
-
}
|
|
9796
|
-
//#endregion
|
|
9797
|
-
//#region src/gateway/index.ts
|
|
9798
|
-
/**
|
|
9799
|
-
* The gateway (ARCHITECTURE §5, §10; D38, D96 to D99): the HTTP side of an instance. It serves
|
|
9800
|
-
* the shell on the shell's leased port and each opened artifact on its own leased port, all on one
|
|
9801
|
-
* host, so the shell and every artifact are same-site but different origins. Only capability
|
|
9802
|
-
* holders get in: a link's token becomes a shell session, the shell hands the artifact's frame a
|
|
9803
|
-
* single-use ticket, and the frame's session lets it load its version's files. Every request goes
|
|
9804
|
-
* through the same checks (`routes.ts`), and published versions are served straight from disk,
|
|
9805
|
-
* with no process (RT-05). It also serves `view/url`, `view/rotate` and `view/revoke`.
|
|
9806
|
-
*
|
|
9807
|
-
* ```ts
|
|
9808
|
-
* const gateway = createGateway({ ledger, log, addressing, capabilities, artifacts, shellDir });
|
|
9809
|
-
* await gateway.start();
|
|
9810
|
-
* const { url } = await gateway.defaultLink(artifactId); // the publish receipt's URL
|
|
9811
|
-
* ```
|
|
9812
|
-
*/
|
|
9813
|
-
const NO_STORE = { "cache-control": "no-store" };
|
|
9814
|
-
/** How recently an artifact must have been viewed for its port to be bound at start (D129). */
|
|
9815
|
-
const RECENT_VIEW_MS = 6048e5;
|
|
9816
|
-
/**
|
|
9817
10457
|
* The browser-protocol routes of INTERFACES §4 (D96): WP-06 serves `fields`, `submit`, `signal`,
|
|
9818
|
-
* `events` and `events/poll`; the
|
|
10458
|
+
* `events` and `events/poll`; WP-08 the calls, runs and live sources; WP-13 the stream tickets.
|
|
9819
10459
|
*/
|
|
9820
|
-
function laterArtifactRoutes(served, acting) {
|
|
10460
|
+
function laterArtifactRoutes(served, acting, ticket) {
|
|
9821
10461
|
const action = (params) => {
|
|
9822
10462
|
const id = params["fn"];
|
|
9823
10463
|
return id ? `action:${id}` : "any-action";
|
|
9824
10464
|
};
|
|
9825
10465
|
return [
|
|
9826
|
-
{
|
|
9827
|
-
method: "GET",
|
|
9828
|
-
path: "/_mostra/sw.js",
|
|
9829
|
-
intent: "read",
|
|
9830
|
-
auth: "none"
|
|
9831
|
-
},
|
|
9832
10466
|
{
|
|
9833
10467
|
method: "POST",
|
|
9834
10468
|
path: "/_mostra/v/:rev/fields",
|
|
@@ -9896,13 +10530,15 @@ function laterArtifactRoutes(served, acting) {
|
|
|
9896
10530
|
method: "POST",
|
|
9897
10531
|
path: "/_mostra/v/:rev/ticket",
|
|
9898
10532
|
intent: "mutation",
|
|
9899
|
-
auth: "session"
|
|
10533
|
+
auth: "session",
|
|
10534
|
+
handler: ticket
|
|
9900
10535
|
},
|
|
9901
10536
|
{
|
|
9902
10537
|
method: "GET",
|
|
9903
10538
|
path: "/_mostra/v/:rev/events",
|
|
9904
10539
|
intent: "stream",
|
|
9905
10540
|
auth: "session",
|
|
10541
|
+
sse: true,
|
|
9906
10542
|
handler: served.stream
|
|
9907
10543
|
},
|
|
9908
10544
|
{
|
|
@@ -9947,17 +10583,70 @@ function createGateway(options) {
|
|
|
9947
10583
|
};
|
|
9948
10584
|
const artifactListeners = /* @__PURE__ */ new Map();
|
|
9949
10585
|
const opening = /* @__PURE__ */ new Map();
|
|
10586
|
+
const faces = /* @__PURE__ */ new Map();
|
|
10587
|
+
const openingFaces = /* @__PURE__ */ new Map();
|
|
10588
|
+
/** A host's recent answers for artifacts' frame addresses, by face key (D158 item 6). */
|
|
10589
|
+
const askedRecently = /* @__PURE__ */ new Map();
|
|
9950
10590
|
const integrity = versionIntegrity(artifacts, log);
|
|
10591
|
+
const loopbackShell = {
|
|
10592
|
+
listener: "shell",
|
|
10593
|
+
by: "loopback",
|
|
10594
|
+
via: "local",
|
|
10595
|
+
artifactId: void 0,
|
|
10596
|
+
port: () => shellPort ?? 0,
|
|
10597
|
+
origin: () => shellOrigin(),
|
|
10598
|
+
hosts: () => addressing.hosts(shellPort ?? 0),
|
|
10599
|
+
streams: () => true
|
|
10600
|
+
};
|
|
10601
|
+
const loopbackArtifact = (artifactId, port) => ({
|
|
10602
|
+
listener: "artifact",
|
|
10603
|
+
by: "loopback",
|
|
10604
|
+
via: "local",
|
|
10605
|
+
artifactId,
|
|
10606
|
+
port,
|
|
10607
|
+
origin: () => addressing.origin(port()),
|
|
10608
|
+
hosts: () => addressing.hosts(port()),
|
|
10609
|
+
streams: () => true
|
|
10610
|
+
});
|
|
10611
|
+
const faceWay = (entry) => ({
|
|
10612
|
+
listener: entry.spec.listener,
|
|
10613
|
+
by: entry.spec.by,
|
|
10614
|
+
via: entry.spec.via,
|
|
10615
|
+
artifactId: entry.spec.artifactId,
|
|
10616
|
+
port: () => entry.port,
|
|
10617
|
+
origin: () => entry.origin,
|
|
10618
|
+
hosts: () => entry.origin === void 0 ? [] : [hostOf(entry.origin)],
|
|
10619
|
+
streams: () => entry.spec.streams !== false
|
|
10620
|
+
});
|
|
10621
|
+
/** The shell of a way's group: the loopback shell, or the group's shell face. */
|
|
10622
|
+
const shellOf = (way, group) => {
|
|
10623
|
+
if (way.by === "loopback" || group === void 0) return loopbackShell;
|
|
10624
|
+
const entry = faces.get(faceKey(group, "shell"));
|
|
10625
|
+
return entry ? faceWay(entry) : void 0;
|
|
10626
|
+
};
|
|
10627
|
+
/** How an artifact way's frames authenticate: by the pair, unless its keeper said (D70). */
|
|
10628
|
+
const modeOf = (artifact, group) => {
|
|
10629
|
+
if (artifact.by === "loopback" || group === void 0) return "cookie";
|
|
10630
|
+
const entry = faces.get(faceKey(group, "artifact", artifact.artifactId));
|
|
10631
|
+
if (entry?.spec.mode) return entry.spec.mode;
|
|
10632
|
+
const shell = shellOf(artifact, group)?.origin();
|
|
10633
|
+
const own = artifact.origin();
|
|
10634
|
+
return shell !== void 0 && own !== void 0 ? addressing.frameMode(shell, own) : "worker";
|
|
10635
|
+
};
|
|
10636
|
+
/** Whether an origin is `https:`, where every cookie is `Secure`. */
|
|
10637
|
+
const secure = (origin) => origin?.startsWith("https:") === true;
|
|
10638
|
+
/** Whether the gateway serves a shell at this origin now: launch tickets go only there. */
|
|
10639
|
+
const servesShell = (origin) => origin === shellOrigin() || [...faces.values()].some((entry) => entry.spec.listener === "shell" && entry.origin === origin);
|
|
9951
10640
|
/** The answer for a damaged version: a plain page for a navigation, else the diagnostic. */
|
|
9952
|
-
const damaged = (number, damage, document) => refusalResponse({
|
|
10641
|
+
const damaged = (number, damage, document, frameAncestors) => refusalResponse({
|
|
9953
10642
|
status: 500,
|
|
9954
10643
|
diagnostic: createDiagnostic("MOSTRA_HOME_INTEGRITY", { message: `${number === void 0 ? "A version" : `Version ${number}`} of this artifact is damaged: ${damage}.` })
|
|
9955
10644
|
}, {
|
|
9956
10645
|
document,
|
|
9957
|
-
frameAncestors
|
|
10646
|
+
frameAncestors
|
|
9958
10647
|
});
|
|
9959
10648
|
const link = (token) => ({
|
|
9960
|
-
url: `${shellOrigin
|
|
10649
|
+
url: `${token.shellOrigin}/a/${token.artifactId}${token.pinnedVersion !== void 0 ? `/v/${token.pinnedVersion}` : ""}#t=${token.secret}`,
|
|
9961
10650
|
tokenId: token.tokenId,
|
|
9962
10651
|
scopes: token.scopes,
|
|
9963
10652
|
...token.expiresAt !== void 0 ? { expiresAt: token.expiresAt } : {},
|
|
@@ -9972,57 +10661,246 @@ function createGateway(options) {
|
|
|
9972
10661
|
...found.collected !== void 0 ? { collected: found.collected } : {}
|
|
9973
10662
|
} : void 0;
|
|
9974
10663
|
};
|
|
9975
|
-
const
|
|
10664
|
+
const openFace = (spec, origin) => {
|
|
10665
|
+
const key = faceKey(spec.group, spec.listener, spec.artifactId);
|
|
10666
|
+
const open = faces.get(key);
|
|
10667
|
+
if (open) return Promise.resolve(open);
|
|
10668
|
+
const pending = openingFaces.get(key);
|
|
10669
|
+
if (pending) return pending;
|
|
10670
|
+
const started = (async () => {
|
|
10671
|
+
let entry;
|
|
10672
|
+
const way = () => entry ? faceWay(entry) : {
|
|
10673
|
+
...loopbackShell,
|
|
10674
|
+
origin: () => void 0,
|
|
10675
|
+
hosts: () => []
|
|
10676
|
+
};
|
|
10677
|
+
const listener = createListener({
|
|
10678
|
+
policy: () => ({
|
|
10679
|
+
origin: entry?.origin ?? "",
|
|
10680
|
+
hosts: way().hosts()
|
|
10681
|
+
}),
|
|
10682
|
+
log,
|
|
10683
|
+
frameAncestors: () => spec.listener === "shell" ? "'none'" : shellOf(way(), spec.group)?.origin() ?? "'none'",
|
|
10684
|
+
configure: (app) => {
|
|
10685
|
+
if (spec.listener === "shell") mount(app, shellChecks(way), shellRoutes(way, spec.group));
|
|
10686
|
+
else {
|
|
10687
|
+
const artifactId = spec.artifactId;
|
|
10688
|
+
mount(app, artifactChecks(artifactId, way, spec.group), artifactRoutes(artifactId, way, spec.group));
|
|
10689
|
+
}
|
|
10690
|
+
},
|
|
10691
|
+
...spec.listener === "artifact" ? { upgrade: socketUpgrade(spec.artifactId, way, spec.group) } : {},
|
|
10692
|
+
...options.traceRequests ? { traceRequests: true } : {}
|
|
10693
|
+
});
|
|
10694
|
+
await endLingering(key);
|
|
10695
|
+
const port = await addressing.listenFace(listener.server, {
|
|
10696
|
+
key,
|
|
10697
|
+
lease: spec.lease
|
|
10698
|
+
});
|
|
10699
|
+
entry = {
|
|
10700
|
+
key,
|
|
10701
|
+
spec,
|
|
10702
|
+
listener,
|
|
10703
|
+
port,
|
|
10704
|
+
origin
|
|
10705
|
+
};
|
|
10706
|
+
faces.set(key, entry);
|
|
10707
|
+
log.info("gateway.face_open", {
|
|
10708
|
+
key,
|
|
10709
|
+
by: spec.by,
|
|
10710
|
+
local: addressing.faceLocal(port),
|
|
10711
|
+
...origin !== void 0 ? { origin } : {}
|
|
10712
|
+
});
|
|
10713
|
+
return entry;
|
|
10714
|
+
})().finally(() => openingFaces.delete(key));
|
|
10715
|
+
openingFaces.set(key, started);
|
|
10716
|
+
return started;
|
|
10717
|
+
};
|
|
10718
|
+
const handleOf = (entry) => ({
|
|
10719
|
+
key: entry.key,
|
|
10720
|
+
port: entry.port,
|
|
10721
|
+
local: addressing.faceLocal(entry.port),
|
|
10722
|
+
origin: () => entry.origin,
|
|
10723
|
+
setOrigin: (origin) => {
|
|
10724
|
+
if (entry.origin !== origin) log.info("gateway.face_address", {
|
|
10725
|
+
key: entry.key,
|
|
10726
|
+
...origin !== void 0 ? { origin } : {}
|
|
10727
|
+
});
|
|
10728
|
+
entry.origin = origin;
|
|
10729
|
+
}
|
|
10730
|
+
});
|
|
10731
|
+
const closeFace = async (key, release = false) => {
|
|
10732
|
+
const pending = openingFaces.get(key);
|
|
10733
|
+
if (pending) await pending.catch(() => void 0);
|
|
10734
|
+
const entry = faces.get(key);
|
|
10735
|
+
if (entry) {
|
|
10736
|
+
faces.delete(key);
|
|
10737
|
+
await entry.listener.close();
|
|
10738
|
+
log.info("gateway.face_closed", { key });
|
|
10739
|
+
}
|
|
10740
|
+
if (release) addressing.releaseFace(key);
|
|
10741
|
+
};
|
|
10742
|
+
/**
|
|
10743
|
+
* Withdrawn faces' listeners, by face key, closing after {@link FACE_LINGER_MS}; a face of the
|
|
10744
|
+
* same key opened meanwhile, or the gateway's close, closes one at once.
|
|
10745
|
+
*/
|
|
10746
|
+
const lingering = /* @__PURE__ */ new Map();
|
|
10747
|
+
/** Closes a withdrawn face's listener now, if one still lingers, freeing its port. */
|
|
10748
|
+
const endLingering = async (key) => {
|
|
10749
|
+
const listener = lingering.get(key);
|
|
10750
|
+
if (!listener) return;
|
|
10751
|
+
lingering.delete(key);
|
|
10752
|
+
await listener.close();
|
|
10753
|
+
};
|
|
10754
|
+
/**
|
|
10755
|
+
* Withdraws a face at once and closes its listener a moment later: from now on its `Host` is
|
|
10756
|
+
* served nowhere (every request is refused, 421), while the request that learned of the
|
|
10757
|
+
* withdrawal (an exchange that asked the host) still gets its own answer, 410, rather than a
|
|
10758
|
+
* connection closed under it.
|
|
10759
|
+
*/
|
|
10760
|
+
const withdrawFace = (key) => {
|
|
10761
|
+
const entry = faces.get(key);
|
|
10762
|
+
if (!entry) {
|
|
10763
|
+
addressing.releaseFace(key);
|
|
10764
|
+
return;
|
|
10765
|
+
}
|
|
10766
|
+
faces.delete(key);
|
|
10767
|
+
entry.origin = void 0;
|
|
10768
|
+
lingering.set(key, entry.listener);
|
|
10769
|
+
log.info("gateway.face_withdrawn", { key });
|
|
10770
|
+
setTimeout(() => {
|
|
10771
|
+
if (lingering.get(key) !== entry.listener) return;
|
|
10772
|
+
endLingering(key).then(() => {
|
|
10773
|
+
if (!faces.has(key)) addressing.releaseFace(key);
|
|
10774
|
+
});
|
|
10775
|
+
}, FACE_LINGER_MS).unref?.();
|
|
10776
|
+
};
|
|
10777
|
+
/** The kept external bases, so a restart serves their links before the host answers again. */
|
|
10778
|
+
const keptBases = () => options.ledger.read((db) => db.all("SELECT key, listener, artifact_id, origin, mode FROM external_base"));
|
|
10779
|
+
const hostSpec = (artifactId, listener, mode) => ({
|
|
10780
|
+
by: "host",
|
|
10781
|
+
group: `host:${artifactId}`,
|
|
10782
|
+
listener,
|
|
10783
|
+
artifactId,
|
|
10784
|
+
via: "token",
|
|
10785
|
+
lease: true,
|
|
10786
|
+
...mode ? { mode } : {}
|
|
10787
|
+
});
|
|
10788
|
+
/**
|
|
10789
|
+
* The host's face of one of an artifact's listeners, asked again now: the address it gives
|
|
10790
|
+
* (kept, so its links work after a restart), or none. `null`, or another origin, withdraws the
|
|
10791
|
+
* face given before, whose links stop working; a host that fails or is away keeps what it gave.
|
|
10792
|
+
*/
|
|
10793
|
+
const hostFaceTurns = /* @__PURE__ */ new Map();
|
|
10794
|
+
/**
|
|
10795
|
+
* One question to the host per face at a time (Opus review of WP-13): a question that fails
|
|
10796
|
+
* never closes a face another question just set up, and every question reads what the one
|
|
10797
|
+
* before it left.
|
|
10798
|
+
*/
|
|
10799
|
+
const hostFace = (artifactId, listener) => {
|
|
10800
|
+
const key = faceKey(`host:${artifactId}`, listener, artifactId);
|
|
10801
|
+
const turn = (hostFaceTurns.get(key) ?? Promise.resolve()).then(() => askHostFace(artifactId, listener), () => askHostFace(artifactId, listener));
|
|
10802
|
+
const settled = turn.catch(() => void 0);
|
|
10803
|
+
hostFaceTurns.set(key, settled);
|
|
10804
|
+
settled.then(() => {
|
|
10805
|
+
if (hostFaceTurns.get(key) === settled) hostFaceTurns.delete(key);
|
|
10806
|
+
});
|
|
10807
|
+
return turn;
|
|
10808
|
+
};
|
|
10809
|
+
const askHostFace = async (artifactId, listener) => {
|
|
10810
|
+
try {
|
|
10811
|
+
artifacts.get({ artifactId });
|
|
10812
|
+
} catch {
|
|
10813
|
+
return;
|
|
10814
|
+
}
|
|
10815
|
+
const port = options.externalBase;
|
|
10816
|
+
const key = faceKey(`host:${artifactId}`, listener, artifactId);
|
|
10817
|
+
const kept = faces.get(key);
|
|
10818
|
+
if (!port?.registered()) return kept?.origin !== void 0 ? kept : void 0;
|
|
10819
|
+
if (listener === "artifact" && kept && Date.now() - (askedRecently.get(key) ?? 0) < EXTERNAL_BASE_REUSE_MS) return kept;
|
|
10820
|
+
const entry = kept ?? await openFace(hostSpec(artifactId, listener));
|
|
10821
|
+
const answer = await port.ask({
|
|
10822
|
+
artifactId,
|
|
10823
|
+
listener,
|
|
10824
|
+
local: addressing.faceLocal(entry.port)
|
|
10825
|
+
});
|
|
10826
|
+
if (answer.kind === "failed" || answer.kind === "away") {
|
|
10827
|
+
if (kept?.origin !== void 0) return kept;
|
|
10828
|
+
if (!kept) await closeFace(key, true);
|
|
10829
|
+
return;
|
|
10830
|
+
}
|
|
10831
|
+
if (answer.kind === "none") {
|
|
10832
|
+
options.ledger.write((db) => db.run("DELETE FROM external_base WHERE key = ?", key));
|
|
10833
|
+
if (kept?.origin !== void 0) withdrawFace(key);
|
|
10834
|
+
else await closeFace(key, true);
|
|
10835
|
+
return;
|
|
10836
|
+
}
|
|
10837
|
+
const origin = answer.base.origin;
|
|
10838
|
+
const mode = answer.base.mode;
|
|
10839
|
+
if (entry.origin !== origin || (entry.spec.mode ?? null) !== (mode ?? null)) {
|
|
10840
|
+
if ((entry.spec.mode ?? null) !== (mode ?? null)) await closeFace(key);
|
|
10841
|
+
const fresh = faces.get(key) ?? await openFace(hostSpec(artifactId, listener, mode), origin);
|
|
10842
|
+
fresh.origin = origin;
|
|
10843
|
+
options.ledger.write((db) => db.run("INSERT INTO external_base (key, listener, artifact_id, origin, mode, client, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(key) DO UPDATE SET origin = excluded.origin, mode = excluded.mode, updated_at = excluded.updated_at", key, listener, artifactId, origin, mode ?? null, answer.owner, (/* @__PURE__ */ new Date()).toISOString()));
|
|
10844
|
+
askedRecently.set(key, Date.now());
|
|
10845
|
+
return fresh;
|
|
10846
|
+
}
|
|
10847
|
+
askedRecently.set(key, Date.now());
|
|
10848
|
+
return entry;
|
|
10849
|
+
};
|
|
10850
|
+
/** Where an artifact's links point: a host's external base when it gives one, else loopback. */
|
|
10851
|
+
const linkBase = async (artifactId) => {
|
|
10852
|
+
return (await hostFace(artifactId, "shell"))?.origin ?? shellOrigin();
|
|
10853
|
+
};
|
|
10854
|
+
/** The artifact way a shell way opens frames on, or why there is none. */
|
|
10855
|
+
const artifactWayFor = async (shell, group, artifactId) => {
|
|
10856
|
+
if (shell.by === "loopback" || group === void 0) {
|
|
10857
|
+
const port = await openArtifact(artifactId);
|
|
10858
|
+
return {
|
|
10859
|
+
way: loopbackArtifact(artifactId, () => port),
|
|
10860
|
+
group: void 0
|
|
10861
|
+
};
|
|
10862
|
+
}
|
|
10863
|
+
if (shell.by === "host") {
|
|
10864
|
+
const entry = await hostFace(artifactId, "artifact");
|
|
10865
|
+
if (entry?.origin === void 0) return refusal("MOSTRA_HYGIENE_NOT_SERVED", "The host gives this artifact's frame no address here.", 503);
|
|
10866
|
+
return {
|
|
10867
|
+
way: faceWay(entry),
|
|
10868
|
+
group
|
|
10869
|
+
};
|
|
10870
|
+
}
|
|
10871
|
+
const entry = faces.get(faceKey(group, "artifact", artifactId));
|
|
10872
|
+
if (entry?.origin === void 0) return refusal("MOSTRA_HYGIENE_NOT_SERVED", "This artifact isn't shared at this address.");
|
|
10873
|
+
return {
|
|
10874
|
+
way: faceWay(entry),
|
|
10875
|
+
group
|
|
10876
|
+
};
|
|
10877
|
+
};
|
|
10878
|
+
const shellKind = (way) => ({
|
|
9976
10879
|
kind: "shell",
|
|
9977
|
-
origin:
|
|
9978
|
-
shellOrigin:
|
|
10880
|
+
origin: way.origin() ?? "",
|
|
10881
|
+
shellOrigin: way.origin() ?? ""
|
|
9979
10882
|
});
|
|
9980
|
-
const shellChecks = {
|
|
10883
|
+
const shellChecks = (way) => ({
|
|
9981
10884
|
policy: () => ({
|
|
9982
|
-
origin:
|
|
9983
|
-
hosts:
|
|
10885
|
+
origin: way().origin() ?? "",
|
|
10886
|
+
hosts: way().hosts()
|
|
9984
10887
|
}),
|
|
9985
10888
|
capabilities,
|
|
9986
10889
|
log,
|
|
9987
|
-
cookieName: () => `mostra-${
|
|
10890
|
+
cookieName: () => `mostra-${way().port()}`,
|
|
9988
10891
|
frameAncestors: () => "'none'",
|
|
9989
10892
|
artifactOf: (params) => {
|
|
9990
10893
|
const id = params["artifactId"];
|
|
9991
|
-
|
|
9992
|
-
|
|
9993
|
-
|
|
10894
|
+
const own = way().artifactId;
|
|
10895
|
+
return id !== void 0 && ArtifactId.is(id) && (own === void 0 || own === id) ? id : void 0;
|
|
10896
|
+
},
|
|
10897
|
+
streams: () => way().streams()
|
|
10898
|
+
});
|
|
9994
10899
|
const shellMissing = () => jsonResponse(createDiagnostic("MOSTRA_ENV_SHELL_MISSING", { message: "This Mostra runtime has no built shell." }), { status: 503 });
|
|
9995
|
-
/** The
|
|
9996
|
-
const
|
|
9997
|
-
|
|
9998
|
-
|
|
9999
|
-
method: context.request.method,
|
|
10000
|
-
path: new URL(context.request.url).pathname,
|
|
10001
|
-
document: true
|
|
10002
|
-
});
|
|
10003
|
-
const html = readFileSync(join(options.shellDir, "index.html"));
|
|
10004
|
-
return new Response(context.request.method === "HEAD" ? null : html, { headers: {
|
|
10005
|
-
...BASE_HEADERS,
|
|
10006
|
-
...documentHeaders(shellKind(), `http://${addressing.urlHost}:*`),
|
|
10007
|
-
"content-type": "text/html; charset=utf-8",
|
|
10008
|
-
"cache-control": "no-cache"
|
|
10009
|
-
} });
|
|
10010
|
-
};
|
|
10011
|
-
const shellAsset = async (context) => {
|
|
10012
|
-
if (options.shellDir === void 0) return shellMissing();
|
|
10013
|
-
const url = new URL(context.request.url);
|
|
10014
|
-
const path = safePath(url.pathname)?.slice(14) ?? "";
|
|
10015
|
-
const file = path.startsWith("/assets/") ? await findFile(options.shellDir, path) : void 0;
|
|
10016
|
-
if (!file) return refuse(shellChecks, refusal("MOSTRA_HYGIENE_NOT_SERVED", "No shell file at this path."), {
|
|
10017
|
-
method: context.request.method,
|
|
10018
|
-
path: url.pathname,
|
|
10019
|
-
document: false
|
|
10020
|
-
});
|
|
10021
|
-
return fileResponse(file, context.request, {
|
|
10022
|
-
...documentHeaders(shellKind(), `http://${addressing.urlHost}:*`),
|
|
10023
|
-
"cache-control": "public, max-age=31536000, immutable"
|
|
10024
|
-
});
|
|
10025
|
-
};
|
|
10900
|
+
/** The exchanges each browser made, by artifact (WP-12; see `exchange`). */
|
|
10901
|
+
const madeSessions = /* @__PURE__ */ new Map();
|
|
10902
|
+
let exchangeOrder = 0;
|
|
10903
|
+
const browserKey = (artifactId, browser) => typeof browser === "string" && /^[A-Za-z0-9_-]{16,64}$/.test(browser) ? `${artifactId}\u0000${browser}` : void 0;
|
|
10026
10904
|
/** What a link allows, as the shell shows it when two links meet. */
|
|
10027
10905
|
const access = (grant) => ({
|
|
10028
10906
|
scopes: grant.scopes,
|
|
@@ -10040,295 +10918,371 @@ function createGateway(options) {
|
|
|
10040
10918
|
...access(grant)
|
|
10041
10919
|
};
|
|
10042
10920
|
};
|
|
10043
|
-
|
|
10044
|
-
|
|
10045
|
-
|
|
10046
|
-
|
|
10047
|
-
|
|
10048
|
-
|
|
10049
|
-
|
|
10050
|
-
|
|
10051
|
-
|
|
10052
|
-
|
|
10053
|
-
|
|
10054
|
-
|
|
10055
|
-
|
|
10056
|
-
|
|
10057
|
-
|
|
10058
|
-
|
|
10059
|
-
|
|
10060
|
-
|
|
10921
|
+
const shellRoutes = (wayOf, group) => {
|
|
10922
|
+
const checks = shellChecks(wayOf);
|
|
10923
|
+
/** The shell's page: the same for every artifact; it learns everything from its session. */
|
|
10924
|
+
const shellPage = async (context) => {
|
|
10925
|
+
if (options.shellDir === void 0) return shellMissing();
|
|
10926
|
+
const way = wayOf();
|
|
10927
|
+
if (context.artifactId === void 0) return refuse(checks, refusal("MOSTRA_HYGIENE_NOT_SERVED", "No artifact is named at this path."), {
|
|
10928
|
+
method: context.request.method,
|
|
10929
|
+
path: new URL(context.request.url).pathname,
|
|
10930
|
+
document: true
|
|
10931
|
+
});
|
|
10932
|
+
let frames = `http://${addressing.urlHost}:*`;
|
|
10933
|
+
if (way.by !== "loopback") {
|
|
10934
|
+
const found = await artifactWayFor(way, group, context.artifactId).catch(() => void 0);
|
|
10935
|
+
frames = found && !isRefusal(found) ? found.way.origin() ?? "'none'" : "'none'";
|
|
10936
|
+
}
|
|
10937
|
+
const html = readFileSync(join(options.shellDir, "index.html"));
|
|
10938
|
+
return new Response(context.request.method === "HEAD" ? null : html, { headers: {
|
|
10939
|
+
...BASE_HEADERS,
|
|
10940
|
+
...documentHeaders(shellKind(way), frames),
|
|
10941
|
+
"content-type": "text/html; charset=utf-8",
|
|
10942
|
+
"cache-control": "no-cache"
|
|
10943
|
+
} });
|
|
10061
10944
|
};
|
|
10062
|
-
const
|
|
10063
|
-
|
|
10064
|
-
|
|
10065
|
-
|
|
10066
|
-
|
|
10067
|
-
|
|
10068
|
-
|
|
10069
|
-
|
|
10070
|
-
|
|
10071
|
-
|
|
10072
|
-
|
|
10073
|
-
|
|
10074
|
-
|
|
10075
|
-
|
|
10945
|
+
const shellAsset = async (context) => {
|
|
10946
|
+
if (options.shellDir === void 0) return shellMissing();
|
|
10947
|
+
const url = new URL(context.request.url);
|
|
10948
|
+
const path = safePath(url.pathname)?.slice(14) ?? "";
|
|
10949
|
+
const file = path.startsWith("/assets/") ? await findFile(options.shellDir, path) : void 0;
|
|
10950
|
+
if (!file) return refuse(checks, refusal("MOSTRA_HYGIENE_NOT_SERVED", "No shell file at this path."), {
|
|
10951
|
+
method: context.request.method,
|
|
10952
|
+
path: url.pathname,
|
|
10953
|
+
document: false
|
|
10954
|
+
});
|
|
10955
|
+
return fileResponse(file, context.request, {
|
|
10956
|
+
...documentHeaders(shellKind(wayOf()), `http://${addressing.urlHost}:*`),
|
|
10957
|
+
"cache-control": "public, max-age=31536000, immutable"
|
|
10958
|
+
});
|
|
10959
|
+
};
|
|
10960
|
+
/**
|
|
10961
|
+
* Who the session acts as when the link names nobody and no host did (D143 item 2, D158 item
|
|
10962
|
+
* 2): the home's local user on loopback; over a tunnel the tailnet person Tailscale Serve
|
|
10963
|
+
* named, else the link's own viewer, never the home's local user.
|
|
10964
|
+
*/
|
|
10965
|
+
const defaultViewer = (way, context, grant) => {
|
|
10966
|
+
if (way.via === "local") return void 0;
|
|
10967
|
+
if (way.via === "tailnet") {
|
|
10968
|
+
const person = tailnetPerson(context.request.headers, context.remote);
|
|
10969
|
+
if (person) return interaction.viewerForTailnet(person);
|
|
10076
10970
|
}
|
|
10077
|
-
|
|
10971
|
+
return interaction.viewerForLink(grant.tokenId, "Shared link");
|
|
10972
|
+
};
|
|
10973
|
+
const exchange = async (context) => {
|
|
10974
|
+
const way = wayOf();
|
|
10975
|
+
const origin = way.origin() ?? "";
|
|
10976
|
+
const startedAt = exchangeOrder;
|
|
10977
|
+
const meta = {
|
|
10978
|
+
method: "POST",
|
|
10979
|
+
path: new URL(context.request.url).pathname,
|
|
10980
|
+
document: false
|
|
10981
|
+
};
|
|
10982
|
+
if (context.artifactId === void 0) return refuse(checks, refusal("MOSTRA_HYGIENE_NOT_SERVED", "No artifact is served at this path."), meta);
|
|
10983
|
+
const artifactId = context.artifactId;
|
|
10984
|
+
const body = await readJsonObject(context.request);
|
|
10985
|
+
if (isRefusal(body)) return refuse(checks, body, meta);
|
|
10986
|
+
if (way.by === "host") {
|
|
10987
|
+
if ((await hostFace(artifactId, "shell"))?.origin !== origin) return refuse(checks, refusal("MOSTRA_HYGIENE_TOKEN_REVOKED", "The host no longer serves this address.", 410), meta);
|
|
10988
|
+
}
|
|
10989
|
+
const launch = body["token"] === void 0 && body["launch"] !== void 0;
|
|
10990
|
+
const browser = browserKey(artifactId, body["browser"]);
|
|
10991
|
+
let grant = launch ? capabilities.presentLaunch(body["launch"], artifactId, false, origin) : capabilities.presentToken(body["token"], artifactId, origin);
|
|
10992
|
+
if (isRefusal(grant)) return refuse(checks, grant, meta);
|
|
10993
|
+
const existing = capabilities.session(cookieValues(context.request.headers.get("cookie"), checks.cookieName()), origin, artifactId);
|
|
10994
|
+
if (!isRefusal(existing)) {
|
|
10995
|
+
if (existing.grant.tokenId === grant.tokenId) {
|
|
10996
|
+
if (launch) capabilities.spendLaunch(body["launch"]);
|
|
10997
|
+
return jsonResponse({
|
|
10998
|
+
csrf: existing.csrf,
|
|
10999
|
+
...sessionFacts(artifactId, existing.grant)
|
|
11000
|
+
});
|
|
11001
|
+
}
|
|
11002
|
+
if (body["replace"] !== true) {
|
|
11003
|
+
log.info("gateway.session_conflict", {
|
|
11004
|
+
artifactId,
|
|
11005
|
+
origin
|
|
11006
|
+
});
|
|
11007
|
+
return jsonResponse({
|
|
11008
|
+
...refusal("MOSTRA_HYGIENE_SESSION_CONFLICT", "This browser already has this artifact open from another link.").diagnostic,
|
|
11009
|
+
current: access(existing.grant),
|
|
11010
|
+
offered: access(grant)
|
|
11011
|
+
}, { status: 409 });
|
|
11012
|
+
}
|
|
11013
|
+
}
|
|
11014
|
+
let viewerId;
|
|
11015
|
+
if (grant.viewerId === void 0) {
|
|
11016
|
+
const outcome = options.identity ? await options.identity({
|
|
11017
|
+
artifactId,
|
|
11018
|
+
via: way.via,
|
|
11019
|
+
headers: context.request.headers
|
|
11020
|
+
}) : { kind: "default" };
|
|
11021
|
+
if (outcome.kind === "unavailable") {
|
|
11022
|
+
log.warn("gateway.session_refused", {
|
|
11023
|
+
artifactId,
|
|
11024
|
+
code: outcome.diagnostic.code
|
|
11025
|
+
});
|
|
11026
|
+
return jsonResponse(outcome.diagnostic, { status: 503 });
|
|
11027
|
+
}
|
|
11028
|
+
viewerId = outcome.kind === "person" ? interaction.viewerForHost(outcome.viewer) : defaultViewer(way, context, grant);
|
|
11029
|
+
}
|
|
11030
|
+
const now = launch ? capabilities.presentLaunch(body["launch"], artifactId, true, origin) : capabilities.presentToken(body["token"], artifactId, origin);
|
|
11031
|
+
if (isRefusal(now)) return refuse(checks, now, meta);
|
|
11032
|
+
grant = now;
|
|
11033
|
+
const made = browser === void 0 ? void 0 : madeSessions.get(browser);
|
|
11034
|
+
if (made !== void 0 && made.order > startedAt && made.grant.tokenId !== grant.tokenId && body["replace"] !== true) {
|
|
10078
11035
|
log.info("gateway.session_conflict", {
|
|
10079
11036
|
artifactId,
|
|
10080
|
-
origin
|
|
11037
|
+
origin
|
|
10081
11038
|
});
|
|
10082
11039
|
return jsonResponse({
|
|
10083
11040
|
...refusal("MOSTRA_HYGIENE_SESSION_CONFLICT", "This browser already has this artifact open from another link.").diagnostic,
|
|
10084
|
-
current: access(
|
|
11041
|
+
current: access(made.grant),
|
|
10085
11042
|
offered: access(grant)
|
|
10086
11043
|
}, { status: 409 });
|
|
10087
11044
|
}
|
|
10088
|
-
|
|
10089
|
-
|
|
10090
|
-
|
|
10091
|
-
|
|
10092
|
-
artifactId,
|
|
10093
|
-
via: "local",
|
|
10094
|
-
headers: context.request.headers
|
|
11045
|
+
const session = capabilities.createSession({
|
|
11046
|
+
tokenId: grant.tokenId,
|
|
11047
|
+
origin,
|
|
11048
|
+
viewerId
|
|
10095
11049
|
});
|
|
10096
|
-
if (
|
|
10097
|
-
|
|
10098
|
-
|
|
10099
|
-
|
|
11050
|
+
if (browser !== void 0) {
|
|
11051
|
+
exchangeOrder += 1;
|
|
11052
|
+
madeSessions.delete(browser);
|
|
11053
|
+
madeSessions.set(browser, {
|
|
11054
|
+
order: exchangeOrder,
|
|
11055
|
+
grant
|
|
10100
11056
|
});
|
|
10101
|
-
|
|
11057
|
+
if (madeSessions.size > 4096) madeSessions.delete(madeSessions.keys().next().value);
|
|
10102
11058
|
}
|
|
10103
|
-
|
|
10104
|
-
|
|
10105
|
-
const now = launch ? capabilities.presentLaunch(body["launch"], artifactId, true) : capabilities.presentToken(body["token"], artifactId);
|
|
10106
|
-
if (isRefusal(now)) return refuse(shellChecks, now, meta);
|
|
10107
|
-
grant = now;
|
|
10108
|
-
const made = browser === void 0 ? void 0 : madeSessions.get(browser);
|
|
10109
|
-
if (made !== void 0 && made.order > startedAt && made.grant.tokenId !== grant.tokenId && body["replace"] !== true) {
|
|
10110
|
-
log.info("gateway.session_conflict", {
|
|
11059
|
+
log.info("gateway.session_started", {
|
|
11060
|
+
origin,
|
|
10111
11061
|
artifactId,
|
|
10112
|
-
|
|
11062
|
+
tokenId: grant.tokenId
|
|
10113
11063
|
});
|
|
10114
11064
|
return jsonResponse({
|
|
10115
|
-
|
|
10116
|
-
|
|
10117
|
-
|
|
10118
|
-
|
|
10119
|
-
|
|
10120
|
-
|
|
10121
|
-
|
|
10122
|
-
|
|
10123
|
-
|
|
10124
|
-
|
|
10125
|
-
if (browser !== void 0) {
|
|
10126
|
-
exchangeOrder += 1;
|
|
10127
|
-
madeSessions.delete(browser);
|
|
10128
|
-
madeSessions.set(browser, {
|
|
10129
|
-
order: exchangeOrder,
|
|
10130
|
-
grant
|
|
11065
|
+
csrf: session.csrf,
|
|
11066
|
+
...sessionFacts(artifactId, grant)
|
|
11067
|
+
}, { headers: { "set-cookie": sessionCookie(checks.cookieName(), session.cookie, `/a/${artifactId}`, SESSION_MAX_AGE_S, secure(origin)) } });
|
|
11068
|
+
};
|
|
11069
|
+
const readShellSession = (context) => {
|
|
11070
|
+
const session = context.session;
|
|
11071
|
+
if (!session || context.artifactId === void 0) throw new Error("session route without a session");
|
|
11072
|
+
return jsonResponse({
|
|
11073
|
+
csrf: session.csrf,
|
|
11074
|
+
...sessionFacts(context.artifactId, session.grant)
|
|
10131
11075
|
});
|
|
10132
|
-
if (madeSessions.size > 4096) madeSessions.delete(madeSessions.keys().next().value);
|
|
10133
|
-
}
|
|
10134
|
-
log.info("gateway.session_started", {
|
|
10135
|
-
origin: shellOrigin(),
|
|
10136
|
-
artifactId,
|
|
10137
|
-
tokenId: grant.tokenId
|
|
10138
|
-
});
|
|
10139
|
-
return jsonResponse({
|
|
10140
|
-
csrf: session.csrf,
|
|
10141
|
-
...sessionFacts(artifactId, grant)
|
|
10142
|
-
}, { headers: { "set-cookie": sessionCookie(shellChecks.cookieName(), session.cookie, `/a/${artifactId}`, SESSION_MAX_AGE_S) } });
|
|
10143
|
-
};
|
|
10144
|
-
const readShellSession = (context) => {
|
|
10145
|
-
const session = context.session;
|
|
10146
|
-
if (!session || context.artifactId === void 0) throw new Error("session route without a session");
|
|
10147
|
-
return jsonResponse({
|
|
10148
|
-
csrf: session.csrf,
|
|
10149
|
-
...sessionFacts(context.artifactId, session.grant)
|
|
10150
|
-
});
|
|
10151
|
-
};
|
|
10152
|
-
const ticket = async (context) => {
|
|
10153
|
-
const session = context.session;
|
|
10154
|
-
const artifactId = context.artifactId;
|
|
10155
|
-
if (!session || artifactId === void 0) throw new Error("session route without a session");
|
|
10156
|
-
const meta = {
|
|
10157
|
-
method: "POST",
|
|
10158
|
-
path: new URL(context.request.url).pathname,
|
|
10159
|
-
document: false
|
|
10160
11076
|
};
|
|
10161
|
-
const
|
|
10162
|
-
|
|
10163
|
-
|
|
10164
|
-
|
|
10165
|
-
|
|
10166
|
-
|
|
10167
|
-
|
|
10168
|
-
|
|
10169
|
-
|
|
10170
|
-
|
|
10171
|
-
|
|
10172
|
-
|
|
10173
|
-
|
|
10174
|
-
|
|
10175
|
-
|
|
10176
|
-
|
|
10177
|
-
|
|
10178
|
-
|
|
10179
|
-
|
|
10180
|
-
|
|
10181
|
-
|
|
10182
|
-
|
|
10183
|
-
|
|
10184
|
-
|
|
10185
|
-
|
|
10186
|
-
|
|
10187
|
-
|
|
10188
|
-
|
|
10189
|
-
|
|
10190
|
-
viewId: interaction.openView({
|
|
11077
|
+
const ticket = async (context) => {
|
|
11078
|
+
const way = wayOf();
|
|
11079
|
+
const session = context.session;
|
|
11080
|
+
const artifactId = context.artifactId;
|
|
11081
|
+
if (!session || artifactId === void 0) throw new Error("session route without a session");
|
|
11082
|
+
const meta = {
|
|
11083
|
+
method: "POST",
|
|
11084
|
+
path: new URL(context.request.url).pathname,
|
|
11085
|
+
document: false
|
|
11086
|
+
};
|
|
11087
|
+
const body = await readJsonObject(context.request);
|
|
11088
|
+
if (isRefusal(body)) return refuse(checks, body, meta);
|
|
11089
|
+
const asked = body["version"];
|
|
11090
|
+
if (asked !== void 0 && !(Number.isSafeInteger(asked) && asked >= 1)) return refuse(checks, refusal("MOSTRA_HYGIENE_REQUEST_MALFORMED", "`version` must be a version number."), meta);
|
|
11091
|
+
const pinned = session.grant.pinnedVersion;
|
|
11092
|
+
if (pinned !== void 0 && asked !== void 0 && asked !== pinned) return refuse(checks, refusal("MOSTRA_HYGIENE_SCOPE_DENIED", `This link opens version ${pinned} only.`), meta);
|
|
11093
|
+
const detail = artifacts.get({ artifactId });
|
|
11094
|
+
const version = versionOf(detail, asked ?? pinned);
|
|
11095
|
+
const latest = versionOf(detail, void 0);
|
|
11096
|
+
if (!version || !latest) return jsonResponse(createDiagnostic("MOSTRA_ARTIFACT_VERSION_NOT_FOUND", { message: `This artifact has no version ${asked ?? session.grant.pinnedVersion ?? ""}.`.replace(" .", ".") }), { status: 404 });
|
|
11097
|
+
if (version.collected !== void 0) return jsonResponse(collectedDiagnostic(version.number), { status: 410 });
|
|
11098
|
+
const damage = options.dev ? void 0 : await integrity.check(version.id);
|
|
11099
|
+
if (damage !== void 0) return damaged(version.number, damage, false, "'none'");
|
|
11100
|
+
const found = await artifactWayFor(way, group, artifactId);
|
|
11101
|
+
if (isRefusal(found)) return refuse(checks, found, meta);
|
|
11102
|
+
const artifactOrigin = found.way.origin();
|
|
11103
|
+
const mode = modeOf(found.way, found.group);
|
|
11104
|
+
const value = capabilities.mintTicket({
|
|
11105
|
+
tokenId: session.grant.tokenId,
|
|
10191
11106
|
artifactId,
|
|
10192
11107
|
versionId: version.id,
|
|
10193
|
-
|
|
10194
|
-
|
|
10195
|
-
|
|
10196
|
-
|
|
10197
|
-
|
|
10198
|
-
|
|
10199
|
-
|
|
10200
|
-
|
|
10201
|
-
|
|
10202
|
-
|
|
10203
|
-
|
|
11108
|
+
origin: artifactOrigin,
|
|
11109
|
+
shellOrigin: way.origin() ?? "",
|
|
11110
|
+
shellSessionId: session.id,
|
|
11111
|
+
viewerId: session.viewerId
|
|
11112
|
+
});
|
|
11113
|
+
const controls = await options.controls(detail);
|
|
11114
|
+
const viewerId = interaction.viewerOf(session.viewerId);
|
|
11115
|
+
return jsonResponse({
|
|
11116
|
+
artifactId,
|
|
11117
|
+
viewId: interaction.openView({
|
|
11118
|
+
artifactId,
|
|
11119
|
+
versionId: version.id,
|
|
11120
|
+
viewerId,
|
|
11121
|
+
tokenId: session.grant.tokenId,
|
|
11122
|
+
controls
|
|
11123
|
+
}),
|
|
11124
|
+
src: mode === "worker" ? `${artifactOrigin}/_mostra/enter#t=${value}` : `${artifactOrigin}/_mostra/enter?ticket=${value}`,
|
|
11125
|
+
artifactOrigin,
|
|
11126
|
+
version,
|
|
11127
|
+
latest,
|
|
11128
|
+
policy: detail.policy ?? {
|
|
11129
|
+
policy: "once",
|
|
11130
|
+
scope: "per-artifact"
|
|
11131
|
+
},
|
|
11132
|
+
submitChannels: controls.submitChannels,
|
|
11133
|
+
controls: (controls.controls ?? [
|
|
11134
|
+
"submit",
|
|
11135
|
+
"choose",
|
|
11136
|
+
"approve"
|
|
11137
|
+
]).filter((control) => control === "submit" ? scopeAllows(session.grant.scopes, "submit") : control === "choose" ? scopeAllows(session.grant.scopes, "review") : true),
|
|
11138
|
+
target: options.target ?? "live",
|
|
11139
|
+
follow: interaction.following({
|
|
11140
|
+
artifactId,
|
|
11141
|
+
viewerId
|
|
11142
|
+
}),
|
|
11143
|
+
pinned: pinned !== void 0,
|
|
11144
|
+
...options.parked?.(version.id) ? { serverParked: true } : {},
|
|
11145
|
+
...options.dev ? { devPreview: true } : {},
|
|
11146
|
+
...mode === "worker" ? { mode: "worker" } : {}
|
|
11147
|
+
});
|
|
11148
|
+
};
|
|
11149
|
+
return [
|
|
11150
|
+
{
|
|
11151
|
+
method: "GET",
|
|
11152
|
+
path: "/a/:artifactId",
|
|
11153
|
+
intent: "read",
|
|
11154
|
+
auth: "none",
|
|
11155
|
+
handler: shellPage
|
|
11156
|
+
},
|
|
11157
|
+
{
|
|
11158
|
+
method: "GET",
|
|
11159
|
+
path: "/a/:artifactId/",
|
|
11160
|
+
intent: "read",
|
|
11161
|
+
auth: "none",
|
|
11162
|
+
handler: shellPage
|
|
11163
|
+
},
|
|
11164
|
+
{
|
|
11165
|
+
method: "GET",
|
|
11166
|
+
path: "/a/:artifactId/v/:number{[1-9][0-9]{0,8}}",
|
|
11167
|
+
intent: "read",
|
|
11168
|
+
auth: "none",
|
|
11169
|
+
handler: shellPage
|
|
11170
|
+
},
|
|
11171
|
+
{
|
|
11172
|
+
method: "GET",
|
|
11173
|
+
path: "/_mostra/shell/*",
|
|
11174
|
+
intent: "read",
|
|
11175
|
+
auth: "none",
|
|
11176
|
+
handler: shellAsset
|
|
11177
|
+
},
|
|
11178
|
+
{
|
|
11179
|
+
method: "POST",
|
|
11180
|
+
path: "/a/:artifactId/_mostra/session",
|
|
11181
|
+
intent: "exchange",
|
|
11182
|
+
auth: "none",
|
|
11183
|
+
tokenPath: true,
|
|
11184
|
+
handler: exchange
|
|
11185
|
+
},
|
|
11186
|
+
{
|
|
11187
|
+
method: "GET",
|
|
11188
|
+
path: "/a/:artifactId/_mostra/session",
|
|
11189
|
+
intent: "read",
|
|
11190
|
+
auth: "session",
|
|
11191
|
+
handler: readShellSession
|
|
11192
|
+
},
|
|
11193
|
+
{
|
|
11194
|
+
method: "POST",
|
|
11195
|
+
path: "/a/:artifactId/_mostra/ticket",
|
|
11196
|
+
intent: "mutation",
|
|
11197
|
+
auth: "session",
|
|
11198
|
+
handler: ticket
|
|
11199
|
+
},
|
|
11200
|
+
{
|
|
11201
|
+
method: "POST",
|
|
11202
|
+
path: "/a/:artifactId/_mostra/v/:rev/submit",
|
|
11203
|
+
intent: "mutation",
|
|
11204
|
+
auth: "session",
|
|
11205
|
+
scope: () => "submit",
|
|
11206
|
+
handler: served.shellSubmit
|
|
11207
|
+
},
|
|
11208
|
+
{
|
|
11209
|
+
method: "POST",
|
|
11210
|
+
path: "/a/:artifactId/_mostra/v/:rev/review/choose",
|
|
11211
|
+
intent: "mutation",
|
|
11212
|
+
auth: "session",
|
|
11213
|
+
scope: () => "review",
|
|
11214
|
+
handler: served.choose
|
|
11215
|
+
},
|
|
11216
|
+
{
|
|
11217
|
+
method: "POST",
|
|
11218
|
+
path: "/a/:artifactId/_mostra/v/:rev/follow",
|
|
11219
|
+
intent: "mutation",
|
|
11220
|
+
auth: "session",
|
|
11221
|
+
handler: served.follow
|
|
11222
|
+
},
|
|
11223
|
+
{
|
|
11224
|
+
method: "GET",
|
|
11225
|
+
path: "/a/:artifactId/_mostra/v/:rev/carry",
|
|
11226
|
+
intent: "read",
|
|
11227
|
+
auth: "session",
|
|
11228
|
+
handler: served.carry
|
|
10204
11229
|
},
|
|
10205
|
-
|
|
10206
|
-
|
|
10207
|
-
"
|
|
10208
|
-
"
|
|
10209
|
-
"
|
|
10210
|
-
|
|
10211
|
-
|
|
10212
|
-
|
|
10213
|
-
|
|
10214
|
-
|
|
10215
|
-
|
|
10216
|
-
|
|
10217
|
-
|
|
10218
|
-
|
|
10219
|
-
|
|
11230
|
+
{
|
|
11231
|
+
method: "GET",
|
|
11232
|
+
path: "/a/:artifactId/_mostra/v/:rev/events",
|
|
11233
|
+
intent: "stream",
|
|
11234
|
+
auth: "session",
|
|
11235
|
+
sse: true,
|
|
11236
|
+
handler: served.stream
|
|
11237
|
+
},
|
|
11238
|
+
{
|
|
11239
|
+
method: "GET",
|
|
11240
|
+
path: "/a/:artifactId/_mostra/v/:rev/events/poll",
|
|
11241
|
+
intent: "stream",
|
|
11242
|
+
auth: "session",
|
|
11243
|
+
handler: served.poll
|
|
11244
|
+
},
|
|
11245
|
+
{
|
|
11246
|
+
method: "POST",
|
|
11247
|
+
path: "/a/:artifactId/_mostra/v/:rev/review/*",
|
|
11248
|
+
intent: "mutation",
|
|
11249
|
+
auth: "session",
|
|
11250
|
+
scope: () => "review"
|
|
11251
|
+
}
|
|
11252
|
+
];
|
|
10220
11253
|
};
|
|
10221
|
-
const
|
|
10222
|
-
{
|
|
10223
|
-
|
|
10224
|
-
|
|
10225
|
-
|
|
10226
|
-
|
|
10227
|
-
|
|
10228
|
-
}
|
|
10229
|
-
|
|
10230
|
-
|
|
10231
|
-
|
|
10232
|
-
|
|
10233
|
-
|
|
10234
|
-
|
|
10235
|
-
|
|
10236
|
-
|
|
10237
|
-
method: "GET",
|
|
10238
|
-
path: "/a/:artifactId/v/:number{[1-9][0-9]{0,8}}",
|
|
10239
|
-
intent: "read",
|
|
10240
|
-
auth: "none",
|
|
10241
|
-
handler: shellPage
|
|
10242
|
-
},
|
|
10243
|
-
{
|
|
10244
|
-
method: "GET",
|
|
10245
|
-
path: "/_mostra/shell/*",
|
|
10246
|
-
intent: "read",
|
|
10247
|
-
auth: "none",
|
|
10248
|
-
handler: shellAsset
|
|
10249
|
-
},
|
|
10250
|
-
{
|
|
10251
|
-
method: "POST",
|
|
10252
|
-
path: "/a/:artifactId/_mostra/session",
|
|
10253
|
-
intent: "exchange",
|
|
10254
|
-
auth: "none",
|
|
10255
|
-
tokenPath: true,
|
|
10256
|
-
handler: exchange
|
|
10257
|
-
},
|
|
10258
|
-
{
|
|
10259
|
-
method: "GET",
|
|
10260
|
-
path: "/a/:artifactId/_mostra/session",
|
|
10261
|
-
intent: "read",
|
|
10262
|
-
auth: "session",
|
|
10263
|
-
handler: readShellSession
|
|
10264
|
-
},
|
|
10265
|
-
{
|
|
10266
|
-
method: "POST",
|
|
10267
|
-
path: "/a/:artifactId/_mostra/ticket",
|
|
10268
|
-
intent: "mutation",
|
|
10269
|
-
auth: "session",
|
|
10270
|
-
handler: ticket
|
|
10271
|
-
},
|
|
10272
|
-
{
|
|
10273
|
-
method: "POST",
|
|
10274
|
-
path: "/a/:artifactId/_mostra/v/:rev/submit",
|
|
10275
|
-
intent: "mutation",
|
|
10276
|
-
auth: "session",
|
|
10277
|
-
scope: () => "submit",
|
|
10278
|
-
handler: served.shellSubmit
|
|
10279
|
-
},
|
|
10280
|
-
{
|
|
10281
|
-
method: "POST",
|
|
10282
|
-
path: "/a/:artifactId/_mostra/v/:rev/review/choose",
|
|
10283
|
-
intent: "mutation",
|
|
10284
|
-
auth: "session",
|
|
10285
|
-
scope: () => "review",
|
|
10286
|
-
handler: served.choose
|
|
10287
|
-
},
|
|
10288
|
-
{
|
|
10289
|
-
method: "POST",
|
|
10290
|
-
path: "/a/:artifactId/_mostra/v/:rev/follow",
|
|
10291
|
-
intent: "mutation",
|
|
10292
|
-
auth: "session",
|
|
10293
|
-
handler: served.follow
|
|
10294
|
-
},
|
|
10295
|
-
{
|
|
10296
|
-
method: "GET",
|
|
10297
|
-
path: "/a/:artifactId/_mostra/v/:rev/carry",
|
|
10298
|
-
intent: "read",
|
|
10299
|
-
auth: "session",
|
|
10300
|
-
handler: served.carry
|
|
10301
|
-
},
|
|
10302
|
-
{
|
|
10303
|
-
method: "GET",
|
|
10304
|
-
path: "/a/:artifactId/_mostra/v/:rev/events",
|
|
10305
|
-
intent: "stream",
|
|
10306
|
-
auth: "session",
|
|
10307
|
-
handler: served.stream
|
|
10308
|
-
},
|
|
10309
|
-
{
|
|
10310
|
-
method: "GET",
|
|
10311
|
-
path: "/a/:artifactId/_mostra/v/:rev/events/poll",
|
|
10312
|
-
intent: "stream",
|
|
10313
|
-
auth: "session",
|
|
10314
|
-
handler: served.poll
|
|
10315
|
-
},
|
|
10316
|
-
{
|
|
10317
|
-
method: "POST",
|
|
10318
|
-
path: "/a/:artifactId/_mostra/v/:rev/review/*",
|
|
10319
|
-
intent: "mutation",
|
|
10320
|
-
auth: "session",
|
|
10321
|
-
scope: () => "review"
|
|
10322
|
-
}
|
|
10323
|
-
];
|
|
10324
|
-
const artifactRoutes = (artifactId, port) => {
|
|
10325
|
-
const origin = () => addressing.origin(port());
|
|
11254
|
+
const artifactChecks = (artifactId, wayOf, group) => ({
|
|
11255
|
+
policy: () => ({
|
|
11256
|
+
origin: wayOf().origin() ?? "",
|
|
11257
|
+
hosts: wayOf().hosts()
|
|
11258
|
+
}),
|
|
11259
|
+
capabilities,
|
|
11260
|
+
log,
|
|
11261
|
+
cookieName: () => `mostra-${wayOf().port()}`,
|
|
11262
|
+
frameAncestors: () => shellOf(wayOf(), group)?.origin() ?? "'none'",
|
|
11263
|
+
artifactOf: () => artifactId,
|
|
11264
|
+
mode: () => modeOf(wayOf(), group),
|
|
11265
|
+
streams: () => wayOf().streams()
|
|
11266
|
+
});
|
|
11267
|
+
const artifactRoutes = (artifactId, wayOf, group) => {
|
|
11268
|
+
const origin = () => wayOf().origin() ?? "";
|
|
11269
|
+
const shell = () => shellOf(wayOf(), group)?.origin() ?? "";
|
|
10326
11270
|
const kind = () => ({
|
|
10327
11271
|
kind: "artifact",
|
|
10328
11272
|
origin: origin(),
|
|
10329
|
-
shellOrigin:
|
|
11273
|
+
shellOrigin: shell()
|
|
10330
11274
|
});
|
|
10331
|
-
const checks =
|
|
11275
|
+
const checks = artifactChecks(artifactId, wayOf, group);
|
|
11276
|
+
const mode = () => modeOf(wayOf(), group);
|
|
11277
|
+
const notServed = (context, message) => refuse(checks, refusal("MOSTRA_HYGIENE_NOT_SERVED", message), {
|
|
11278
|
+
method: context.request.method,
|
|
11279
|
+
path: new URL(context.request.url).pathname,
|
|
11280
|
+
document: context.document
|
|
11281
|
+
});
|
|
11282
|
+
/**
|
|
11283
|
+
* `GET /_mostra/enter`: in cookie mode the frame's entry with its ticket (D98 item 3); in
|
|
11284
|
+
* worker mode the bootstrap page, whose ticket is in the fragment (D70).
|
|
11285
|
+
*/
|
|
10332
11286
|
const enter = (context) => {
|
|
10333
11287
|
const url = new URL(context.request.url);
|
|
10334
11288
|
const meta = {
|
|
@@ -10336,16 +11290,25 @@ function createGateway(options) {
|
|
|
10336
11290
|
path: url.pathname,
|
|
10337
11291
|
document: true
|
|
10338
11292
|
};
|
|
10339
|
-
if (
|
|
11293
|
+
if (mode() === "worker") {
|
|
11294
|
+
if (url.searchParams.has("ticket")) return notServed(context, "A worker-mode frame enters through its bootstrap page.");
|
|
11295
|
+
return new Response(context.request.method === "HEAD" ? null : BOOTSTRAP_PAGE, { headers: {
|
|
11296
|
+
...BASE_HEADERS,
|
|
11297
|
+
...documentHeaders(kind(), ""),
|
|
11298
|
+
...NO_STORE,
|
|
11299
|
+
"content-type": "text/html; charset=utf-8"
|
|
11300
|
+
} });
|
|
11301
|
+
}
|
|
11302
|
+
if (context.request.headers.get("sec-fetch-site") === "cross-site") return refuse(checks, refusal("MOSTRA_HYGIENE_ORIGIN_REFUSED", "A frame enters only from its shell."), meta);
|
|
10340
11303
|
const redeemed = capabilities.redeemTicket(url.searchParams.get("ticket"), origin());
|
|
10341
|
-
if (isRefusal(redeemed)) return refuse(checks
|
|
10342
|
-
if (redeemed.artifactId !== artifactId) return refuse(checks
|
|
11304
|
+
if (isRefusal(redeemed)) return refuse(checks, redeemed, meta);
|
|
11305
|
+
if (redeemed.artifactId !== artifactId) return refuse(checks, refusal("MOSTRA_HYGIENE_TOKEN_INVALID", "The ticket is for another artifact."), meta);
|
|
10343
11306
|
const headers = {
|
|
10344
11307
|
...BASE_HEADERS,
|
|
10345
11308
|
...NO_STORE,
|
|
10346
11309
|
location: "/"
|
|
10347
11310
|
};
|
|
10348
|
-
const existing = capabilities.session(cookieValues(context.request.headers.get("cookie"), checks
|
|
11311
|
+
const existing = capabilities.session(cookieValues(context.request.headers.get("cookie"), checks.cookieName()), origin(), artifactId);
|
|
10349
11312
|
if (!isRefusal(existing) && existing.grant.tokenId === redeemed.tokenId && existing.viewerId === redeemed.viewerId) capabilities.enterVersion(existing.id, redeemed.versionId);
|
|
10350
11313
|
else {
|
|
10351
11314
|
const session = capabilities.createSession({
|
|
@@ -10354,7 +11317,7 @@ function createGateway(options) {
|
|
|
10354
11317
|
versionId: redeemed.versionId,
|
|
10355
11318
|
viewerId: redeemed.viewerId
|
|
10356
11319
|
});
|
|
10357
|
-
headers["set-cookie"] = sessionCookie(checks
|
|
11320
|
+
headers["set-cookie"] = sessionCookie(checks.cookieName(), session.cookie, "/", SESSION_MAX_AGE_S, secure(origin()));
|
|
10358
11321
|
log.info("gateway.session_started", {
|
|
10359
11322
|
origin: origin(),
|
|
10360
11323
|
artifactId,
|
|
@@ -10366,6 +11329,81 @@ function createGateway(options) {
|
|
|
10366
11329
|
headers
|
|
10367
11330
|
});
|
|
10368
11331
|
};
|
|
11332
|
+
/**
|
|
11333
|
+
* `POST /_mostra/enter` (worker mode, D70): the bootstrap page exchanges the shell's ticket
|
|
11334
|
+
* for a frame session whose secret it hands the service worker. A frame that presents the
|
|
11335
|
+
* session it kept, from the same link and viewer, keeps it and switches version.
|
|
11336
|
+
*/
|
|
11337
|
+
const enterWorker = async (context) => {
|
|
11338
|
+
const meta = {
|
|
11339
|
+
method: "POST",
|
|
11340
|
+
path: new URL(context.request.url).pathname,
|
|
11341
|
+
document: false
|
|
11342
|
+
};
|
|
11343
|
+
if (mode() !== "worker") return notServed(context, "This frame enters in cookie mode, with `GET /_mostra/enter`.");
|
|
11344
|
+
const body = await readJsonObject(context.request);
|
|
11345
|
+
if (isRefusal(body)) return refuse(checks, body, meta);
|
|
11346
|
+
const parsed = EnterRequest.safeParse(body);
|
|
11347
|
+
if (!parsed.success) return refuse(checks, refusal("MOSTRA_HYGIENE_REQUEST_MALFORMED", "The entry needs the frame's `ticket`."), meta);
|
|
11348
|
+
const redeemed = capabilities.redeemTicket(parsed.data.ticket, origin());
|
|
11349
|
+
if (isRefusal(redeemed)) return refuse(checks, redeemed, meta);
|
|
11350
|
+
if (redeemed.artifactId !== artifactId) return refuse(checks, refusal("MOSTRA_HYGIENE_TOKEN_INVALID", "The ticket is for another artifact."), meta);
|
|
11351
|
+
const kept = context.request.headers.get(FRAME_SESSION_HEADER);
|
|
11352
|
+
const existing = kept === null ? void 0 : capabilities.session([kept], origin(), artifactId, "worker");
|
|
11353
|
+
let secret;
|
|
11354
|
+
if (kept !== null && existing !== void 0 && !isRefusal(existing) && existing.grant.tokenId === redeemed.tokenId && existing.viewerId === redeemed.viewerId) {
|
|
11355
|
+
capabilities.enterVersion(existing.id, redeemed.versionId);
|
|
11356
|
+
secret = kept;
|
|
11357
|
+
} else {
|
|
11358
|
+
secret = capabilities.createSession({
|
|
11359
|
+
tokenId: redeemed.tokenId,
|
|
11360
|
+
origin: origin(),
|
|
11361
|
+
versionId: redeemed.versionId,
|
|
11362
|
+
viewerId: redeemed.viewerId,
|
|
11363
|
+
mode: "worker"
|
|
11364
|
+
}).cookie;
|
|
11365
|
+
log.info("gateway.session_started", {
|
|
11366
|
+
origin: origin(),
|
|
11367
|
+
artifactId,
|
|
11368
|
+
tokenId: redeemed.tokenId,
|
|
11369
|
+
mode: "worker"
|
|
11370
|
+
});
|
|
11371
|
+
}
|
|
11372
|
+
return jsonResponse({
|
|
11373
|
+
session: secret,
|
|
11374
|
+
shellOrigin: redeemed.shellOrigin
|
|
11375
|
+
});
|
|
11376
|
+
};
|
|
11377
|
+
/** `GET /_mostra/sw.js`: the worker-mode service worker, allowed to control `/` (D70). */
|
|
11378
|
+
const serviceWorker = (context) => {
|
|
11379
|
+
if (mode() !== "worker") return notServed(context, "This frame enters in cookie mode and has no service worker.");
|
|
11380
|
+
return new Response(context.request.method === "HEAD" ? null : SERVICE_WORKER_SOURCE, { headers: {
|
|
11381
|
+
...BASE_HEADERS,
|
|
11382
|
+
"content-type": "text/javascript; charset=utf-8",
|
|
11383
|
+
"service-worker-allowed": "/",
|
|
11384
|
+
"cache-control": "no-cache"
|
|
11385
|
+
} });
|
|
11386
|
+
};
|
|
11387
|
+
/** `POST /_mostra/v/{rev}/ticket`: a single-use ticket for one stream, poll or socket. */
|
|
11388
|
+
const streamTicket = async (context) => {
|
|
11389
|
+
const session = context.session;
|
|
11390
|
+
if (!session) throw new Error("session route without a session");
|
|
11391
|
+
const meta = {
|
|
11392
|
+
method: "POST",
|
|
11393
|
+
path: new URL(context.request.url).pathname,
|
|
11394
|
+
document: false
|
|
11395
|
+
};
|
|
11396
|
+
const body = await readJsonObject(context.request);
|
|
11397
|
+
if (isRefusal(body)) return refuse(checks, body, meta);
|
|
11398
|
+
const parsed = StreamTicketRequest.safeParse(body);
|
|
11399
|
+
if (!parsed.success) return refuse(checks, refusal("MOSTRA_HYGIENE_REQUEST_MALFORMED", "`purpose` is `stream` or `socket`."), meta);
|
|
11400
|
+
return jsonResponse(capabilities.mintStreamTicket({
|
|
11401
|
+
sessionId: session.id,
|
|
11402
|
+
origin: origin(),
|
|
11403
|
+
artifactId,
|
|
11404
|
+
purpose: parsed.data.purpose ?? "stream"
|
|
11405
|
+
}));
|
|
11406
|
+
};
|
|
10369
11407
|
const frameSession = (context) => {
|
|
10370
11408
|
const session = context.session;
|
|
10371
11409
|
if (!session) throw new Error("session route without a session");
|
|
@@ -10373,13 +11411,15 @@ function createGateway(options) {
|
|
|
10373
11411
|
return jsonResponse({
|
|
10374
11412
|
csrf: session.csrf,
|
|
10375
11413
|
artifactId,
|
|
10376
|
-
shellOrigin:
|
|
11414
|
+
shellOrigin: shell(),
|
|
10377
11415
|
scopes: session.grant.scopes,
|
|
10378
11416
|
viewer: interaction.viewer(interaction.viewerOf(session.viewerId)),
|
|
10379
11417
|
...version ? { version: {
|
|
10380
11418
|
id: version.id,
|
|
10381
11419
|
number: version.number
|
|
10382
|
-
} } : {}
|
|
11420
|
+
} } : {},
|
|
11421
|
+
...mode() === "worker" ? { mode: "worker" } : {},
|
|
11422
|
+
...wayOf().streams() ? {} : { streams: false }
|
|
10383
11423
|
});
|
|
10384
11424
|
};
|
|
10385
11425
|
const files = async (context) => {
|
|
@@ -10391,13 +11431,13 @@ function createGateway(options) {
|
|
|
10391
11431
|
document: context.document
|
|
10392
11432
|
};
|
|
10393
11433
|
const path = safePath(url.pathname);
|
|
10394
|
-
if (path === void 0 || !session?.versionId || path === "/_mostra" || path.startsWith("/_mostra/")) return refuse(checks
|
|
11434
|
+
if (path === void 0 || !session?.versionId || path === "/_mostra" || path.startsWith("/_mostra/")) return refuse(checks, refusal("MOSTRA_HYGIENE_NOT_SERVED", "Nothing is served at this path."), meta);
|
|
10395
11435
|
const headers = { ...documentHeaders(kind(), "") };
|
|
10396
11436
|
if (options.dev) {
|
|
10397
11437
|
const upstream = options.dev.upstream();
|
|
10398
|
-
if (!upstream) return refuse(checks
|
|
11438
|
+
if (!upstream) return refuse(checks, refusal("MOSTRA_HYGIENE_NOT_SERVED", "The dev server isn't running.", 503), meta);
|
|
10399
11439
|
const answered = await devFetch(upstream, context.request, url.pathname + url.search).catch(() => void 0);
|
|
10400
|
-
if (!answered) return refuse(checks
|
|
11440
|
+
if (!answered) return refuse(checks, refusal("MOSTRA_HYGIENE_NOT_SERVED", "The dev server didn't answer.", 502), meta);
|
|
10401
11441
|
const bodiless = context.request.method === "HEAD" || [
|
|
10402
11442
|
204,
|
|
10403
11443
|
205,
|
|
@@ -10429,7 +11469,7 @@ function createGateway(options) {
|
|
|
10429
11469
|
const damage = await integrity.serve(from, checked);
|
|
10430
11470
|
if (damage !== void 0) {
|
|
10431
11471
|
const number = artifacts.get({ artifactId }).versions.find((v) => v.id === from)?.number;
|
|
10432
|
-
return damaged(number, damage, context.document);
|
|
11472
|
+
return damaged(number, damage, context.document, shell() || "'none'");
|
|
10433
11473
|
}
|
|
10434
11474
|
}
|
|
10435
11475
|
if (file && options.target === "verify" && file.path.endsWith(".html")) return verifyDocument(file.path, context.request, {
|
|
@@ -10449,7 +11489,7 @@ function createGateway(options) {
|
|
|
10449
11489
|
...headers,
|
|
10450
11490
|
"cache-control": "no-cache"
|
|
10451
11491
|
});
|
|
10452
|
-
return refuse(checks
|
|
11492
|
+
return refuse(checks, refusal("MOSTRA_HYGIENE_NOT_SERVED", "This version has no file at this path."), meta);
|
|
10453
11493
|
};
|
|
10454
11494
|
return [
|
|
10455
11495
|
{
|
|
@@ -10459,6 +11499,20 @@ function createGateway(options) {
|
|
|
10459
11499
|
auth: "none",
|
|
10460
11500
|
handler: enter
|
|
10461
11501
|
},
|
|
11502
|
+
{
|
|
11503
|
+
method: "POST",
|
|
11504
|
+
path: "/_mostra/enter",
|
|
11505
|
+
intent: "exchange",
|
|
11506
|
+
auth: "none",
|
|
11507
|
+
handler: enterWorker
|
|
11508
|
+
},
|
|
11509
|
+
{
|
|
11510
|
+
method: "GET",
|
|
11511
|
+
path: SERVICE_WORKER_PATH,
|
|
11512
|
+
intent: "read",
|
|
11513
|
+
auth: "none",
|
|
11514
|
+
handler: serviceWorker
|
|
11515
|
+
},
|
|
10462
11516
|
{
|
|
10463
11517
|
method: "GET",
|
|
10464
11518
|
path: "/_mostra/session",
|
|
@@ -10466,7 +11520,7 @@ function createGateway(options) {
|
|
|
10466
11520
|
auth: "session",
|
|
10467
11521
|
handler: frameSession
|
|
10468
11522
|
},
|
|
10469
|
-
...laterArtifactRoutes(served, acting),
|
|
11523
|
+
...laterArtifactRoutes(served, acting, streamTicket),
|
|
10470
11524
|
{
|
|
10471
11525
|
method: "GET",
|
|
10472
11526
|
path: "/*",
|
|
@@ -10476,28 +11530,30 @@ function createGateway(options) {
|
|
|
10476
11530
|
}
|
|
10477
11531
|
];
|
|
10478
11532
|
};
|
|
10479
|
-
const artifactChecks = (artifactId, port) => ({
|
|
10480
|
-
policy: () => ({
|
|
10481
|
-
origin: addressing.origin(port()),
|
|
10482
|
-
hosts: addressing.hosts(port())
|
|
10483
|
-
}),
|
|
10484
|
-
capabilities,
|
|
10485
|
-
log,
|
|
10486
|
-
cookieName: () => `mostra-${port()}`,
|
|
10487
|
-
frameAncestors: () => shellOrigin(),
|
|
10488
|
-
artifactOf: () => artifactId
|
|
10489
|
-
});
|
|
10490
11533
|
/**
|
|
10491
|
-
*
|
|
10492
|
-
*
|
|
11534
|
+
* WebSocket upgrades on an artifact's listener, after the listener checked Host, target and
|
|
11535
|
+
* Origin: a dev sandbox's HMR socket (D140 item 12), and the browser protocol's sockets
|
|
11536
|
+
* (`/_mostra/v/{rev}/term/{session}`), which open with a single-use socket ticket (D158 item 5)
|
|
11537
|
+
* and arrive with the terminals (WP-22, WP-23).
|
|
10493
11538
|
*/
|
|
10494
|
-
const
|
|
10495
|
-
const
|
|
10496
|
-
|
|
10497
|
-
|
|
10498
|
-
|
|
10499
|
-
|
|
10500
|
-
|
|
11539
|
+
const socketUpgrade = (artifactId, wayOf, group) => (incoming, socket, head) => {
|
|
11540
|
+
const way = wayOf();
|
|
11541
|
+
const url = new URL(incoming.url ?? "/", "http://gateway.invalid");
|
|
11542
|
+
if (/^\/_mostra\/v\/[^/]+\/term\/[^/]+$/.test(url.pathname)) {
|
|
11543
|
+
const redeemed = capabilities.redeemStreamTicket(url.searchParams.get("ticket"), way.origin() ?? "", artifactId, "socket");
|
|
11544
|
+
if (isRefusal(redeemed)) return redeemed;
|
|
11545
|
+
return refusal("MOSTRA_HYGIENE_NOT_SERVED", "Live terminals arrive with a later Mostra release.", 501);
|
|
11546
|
+
}
|
|
11547
|
+
if (options.dev && way.by === "loopback" && group === void 0) {
|
|
11548
|
+
const upstream = options.dev.upstream();
|
|
11549
|
+
if (!upstream) return refusal("MOSTRA_HYGIENE_NOT_SERVED", "The dev server isn't running.", 503);
|
|
11550
|
+
const cookie = incoming.headers.cookie;
|
|
11551
|
+
const session = capabilities.session(cookieValues(typeof cookie === "string" ? cookie : null, `mostra-${way.port()}`), way.origin() ?? "", artifactId);
|
|
11552
|
+
if (isRefusal(session)) return session;
|
|
11553
|
+
devUpgrade(upstream, incoming, socket, head);
|
|
11554
|
+
return;
|
|
11555
|
+
}
|
|
11556
|
+
return refusal("MOSTRA_HYGIENE_NOT_SERVED", "This gateway serves no WebSocket here.");
|
|
10501
11557
|
};
|
|
10502
11558
|
/** Binds the artifact's listener on its leased port, once; resolves with the port. */
|
|
10503
11559
|
const openArtifact = (artifactId) => {
|
|
@@ -10507,6 +11563,7 @@ function createGateway(options) {
|
|
|
10507
11563
|
if (pending) return pending;
|
|
10508
11564
|
const started = (async () => {
|
|
10509
11565
|
let port = 0;
|
|
11566
|
+
const way = loopbackArtifact(artifactId, () => port);
|
|
10510
11567
|
const listener = createListener({
|
|
10511
11568
|
policy: () => ({
|
|
10512
11569
|
origin: addressing.origin(port),
|
|
@@ -10514,8 +11571,8 @@ function createGateway(options) {
|
|
|
10514
11571
|
}),
|
|
10515
11572
|
log,
|
|
10516
11573
|
frameAncestors: () => shellOrigin(),
|
|
10517
|
-
configure: (app) => mount(app, artifactChecks(artifactId, () =>
|
|
10518
|
-
|
|
11574
|
+
configure: (app) => mount(app, artifactChecks(artifactId, () => way, void 0), artifactRoutes(artifactId, () => way, void 0)),
|
|
11575
|
+
upgrade: socketUpgrade(artifactId, () => way, void 0),
|
|
10519
11576
|
...options.traceRequests ? { traceRequests: true } : {}
|
|
10520
11577
|
});
|
|
10521
11578
|
port = await addressing.listen(listener.server, {
|
|
@@ -10559,16 +11616,39 @@ function createGateway(options) {
|
|
|
10559
11616
|
const fail = (refused) => {
|
|
10560
11617
|
throw new RpcError(refused.diagnostic);
|
|
10561
11618
|
};
|
|
11619
|
+
/** Opens the faces a host gave before a restart, so their links work before it answers again. */
|
|
11620
|
+
const restoreBases = async () => {
|
|
11621
|
+
for (const row of keptBases()) {
|
|
11622
|
+
if (row.artifact_id === null) continue;
|
|
11623
|
+
try {
|
|
11624
|
+
artifacts.get({ artifactId: row.artifact_id });
|
|
11625
|
+
} catch {
|
|
11626
|
+
continue;
|
|
11627
|
+
}
|
|
11628
|
+
try {
|
|
11629
|
+
const entry = await openFace(hostSpec(row.artifact_id, row.listener, row.mode ?? void 0), row.origin);
|
|
11630
|
+
entry.origin = row.origin;
|
|
11631
|
+
} catch (error) {
|
|
11632
|
+
log.warn("gateway.face_restore_failed", {
|
|
11633
|
+
key: row.key,
|
|
11634
|
+
error: error.message
|
|
11635
|
+
});
|
|
11636
|
+
}
|
|
11637
|
+
}
|
|
11638
|
+
};
|
|
10562
11639
|
return {
|
|
10563
11640
|
shellOrigin,
|
|
10564
11641
|
async start() {
|
|
10565
11642
|
const pruned = capabilities.prune();
|
|
10566
11643
|
if (pruned > 0) log.info("gateway.sessions_pruned", { count: pruned });
|
|
10567
11644
|
shellListener = createListener({
|
|
10568
|
-
policy: () =>
|
|
11645
|
+
policy: () => ({
|
|
11646
|
+
origin: shellOrigin(),
|
|
11647
|
+
hosts: addressing.hosts(shellPort ?? 0)
|
|
11648
|
+
}),
|
|
10569
11649
|
log,
|
|
10570
11650
|
frameAncestors: () => "'none'",
|
|
10571
|
-
configure: (app) => mount(app, shellChecks, shellRoutes),
|
|
11651
|
+
configure: (app) => mount(app, shellChecks(() => loopbackShell), shellRoutes(() => loopbackShell, void 0)),
|
|
10572
11652
|
...options.traceRequests ? { traceRequests: true } : {}
|
|
10573
11653
|
});
|
|
10574
11654
|
shellPort = await addressing.listen(shellListener.server, {
|
|
@@ -10590,9 +11670,11 @@ function createGateway(options) {
|
|
|
10590
11670
|
}
|
|
10591
11671
|
await openArtifact(lease.owner);
|
|
10592
11672
|
}
|
|
11673
|
+
await restoreBases();
|
|
10593
11674
|
},
|
|
10594
|
-
defaultLink(artifactId) {
|
|
10595
|
-
const
|
|
11675
|
+
async defaultLink(artifactId) {
|
|
11676
|
+
const base = await linkBase(artifactId);
|
|
11677
|
+
const { url, tokenId } = link(capabilities.defaultLink(artifactId, base));
|
|
10596
11678
|
return {
|
|
10597
11679
|
url,
|
|
10598
11680
|
tokenId
|
|
@@ -10604,23 +11686,53 @@ function createGateway(options) {
|
|
|
10604
11686
|
...input.version !== void 0 ? { pinnedVersion: input.version } : {}
|
|
10605
11687
|
})).url;
|
|
10606
11688
|
},
|
|
11689
|
+
mintAt(input, within) {
|
|
11690
|
+
return link(capabilities.mint({
|
|
11691
|
+
artifactId: input.artifactId,
|
|
11692
|
+
scopes: input.scopes,
|
|
11693
|
+
ttlMs: input.ttlMs,
|
|
11694
|
+
viewerId: input.viewerId,
|
|
11695
|
+
shellOrigin: input.shellOrigin
|
|
11696
|
+
}, within));
|
|
11697
|
+
},
|
|
11698
|
+
reveal(tokenId) {
|
|
11699
|
+
const shown = capabilities.reveal(tokenId);
|
|
11700
|
+
return shown ? link(shown).url : void 0;
|
|
11701
|
+
},
|
|
11702
|
+
async openFace(spec) {
|
|
11703
|
+
return handleOf(await openFace(spec));
|
|
11704
|
+
},
|
|
11705
|
+
face(key) {
|
|
11706
|
+
const entry = faces.get(key);
|
|
11707
|
+
return entry ? handleOf(entry) : void 0;
|
|
11708
|
+
},
|
|
11709
|
+
closeFace,
|
|
11710
|
+
faces: () => [...faces.values()].filter((entry) => entry.origin !== void 0).map((entry) => ({
|
|
11711
|
+
origin: entry.origin,
|
|
11712
|
+
local: addressing.faceLocal(entry.port),
|
|
11713
|
+
listener: entry.spec.listener,
|
|
11714
|
+
...entry.spec.artifactId !== void 0 ? { artifactId: entry.spec.artifactId } : {},
|
|
11715
|
+
by: entry.spec.by
|
|
11716
|
+
})),
|
|
10607
11717
|
methods: () => [
|
|
10608
|
-
handler(viewUrlMethod, (params) => {
|
|
11718
|
+
handler(viewUrlMethod, async (params) => {
|
|
10609
11719
|
const detail = artifacts.get(params.artifact);
|
|
10610
11720
|
const version = versionOf(detail, params.version);
|
|
10611
11721
|
if (!version) throw new RpcError(createDiagnostic("MOSTRA_ARTIFACT_VERSION_NOT_FOUND", { message: params.version === void 0 ? `The artifact ${detail.id} has no published version.` : `The artifact ${detail.id} has no version ${params.version}.` }));
|
|
10612
11722
|
if (version.collected !== void 0) throw new RpcError(collectedDiagnostic(version.number));
|
|
11723
|
+
const base = await linkBase(detail.id);
|
|
10613
11724
|
return recorded(requestKey("view/url", params), (db) => capabilities.mint({
|
|
10614
11725
|
artifactId: detail.id,
|
|
10615
11726
|
scopes: params.scopes,
|
|
10616
11727
|
ttlMs: params.ttl === void 0 ? void 0 : durationMs(params.ttl),
|
|
10617
11728
|
pinnedVersion: params.version === void 0 ? void 0 : version.number,
|
|
10618
|
-
viewerId: params.viewer === void 0 ? void 0 : interaction.viewerForSpec(db, params.viewer)
|
|
11729
|
+
viewerId: params.viewer === void 0 ? void 0 : interaction.viewerForSpec(db, params.viewer),
|
|
11730
|
+
shellOrigin: base
|
|
10619
11731
|
}, db));
|
|
10620
11732
|
}),
|
|
10621
|
-
handler(viewDefaultMethod, (params) => {
|
|
11733
|
+
handler(viewDefaultMethod, async (params) => {
|
|
10622
11734
|
const detail = artifacts.get(params.artifact);
|
|
10623
|
-
return link(capabilities.defaultLink(detail.id));
|
|
11735
|
+
return link(capabilities.defaultLink(detail.id, await linkBase(detail.id)));
|
|
10624
11736
|
}),
|
|
10625
11737
|
handler(viewLaunchMethod, (params) => {
|
|
10626
11738
|
const minted = capabilities.mintLaunch(params.tokenId);
|
|
@@ -10628,7 +11740,7 @@ function createGateway(options) {
|
|
|
10628
11740
|
if (minted === "dead") return fail(refusal("MOSTRA_HYGIENE_TOKEN_REVOKED", `The token ${params.tokenId} was revoked, has expired, or was made for another address.`));
|
|
10629
11741
|
const { grant } = minted;
|
|
10630
11742
|
return {
|
|
10631
|
-
url: `${shellOrigin
|
|
11743
|
+
url: `${grant.shellOrigin}/a/${grant.artifactId}${grant.pinnedVersion !== void 0 ? `/v/${grant.pinnedVersion}` : ""}#l=${minted.ticket}`,
|
|
10632
11744
|
expiresAt: minted.expiresAt
|
|
10633
11745
|
};
|
|
10634
11746
|
}),
|
|
@@ -10647,9 +11759,16 @@ function createGateway(options) {
|
|
|
10647
11759
|
],
|
|
10648
11760
|
artifactOrigins: () => new Map([...artifactListeners].map(([artifactId, entry]) => [artifactId, addressing.origin(entry.port)])),
|
|
10649
11761
|
async close() {
|
|
10650
|
-
await Promise.allSettled([...opening.values()]);
|
|
10651
|
-
await Promise.all([
|
|
10652
|
-
|
|
11762
|
+
await Promise.allSettled([...opening.values(), ...openingFaces.values()]);
|
|
11763
|
+
await Promise.all([
|
|
11764
|
+
shellListener?.close(),
|
|
11765
|
+
...[...artifactListeners.values()].map((entry) => entry.listener.close()),
|
|
11766
|
+
...[...faces.values()].map((entry) => entry.listener.close()),
|
|
11767
|
+
...[...lingering.keys()].map((key) => endLingering(key))
|
|
11768
|
+
]);
|
|
11769
|
+
faces.clear();
|
|
11770
|
+
},
|
|
11771
|
+
servesShell
|
|
10653
11772
|
};
|
|
10654
11773
|
}
|
|
10655
11774
|
/** The answer for a version `mostra gc` collected (D140 item 14). */
|
|
@@ -14215,7 +15334,7 @@ function artifactMethods(options) {
|
|
|
14215
15334
|
options.published?.(receipt.artifactId);
|
|
14216
15335
|
return options.link ? {
|
|
14217
15336
|
...receipt,
|
|
14218
|
-
...options.link(receipt.artifactId)
|
|
15337
|
+
...await options.link(receipt.artifactId)
|
|
14219
15338
|
} : receipt;
|
|
14220
15339
|
}),
|
|
14221
15340
|
handler(depsAddMethod, async (params) => {
|
|
@@ -15341,7 +16460,7 @@ function markHostConfigured(home, client, at = /* @__PURE__ */ new Date()) {
|
|
|
15341
16460
|
*/
|
|
15342
16461
|
const HOME_SCOPE = "home";
|
|
15343
16462
|
const ARTIFACT_SCOPE = /^art_[0-9A-HJKMNP-TV-Z]{26}$/;
|
|
15344
|
-
function missing(name, detail) {
|
|
16463
|
+
function missing$1(name, detail) {
|
|
15345
16464
|
return new RpcError(createDiagnostic("MOSTRA_SECRET_MISSING", {
|
|
15346
16465
|
message: `No secret named ${name} is set${detail ? ` (${detail})` : ""}.`,
|
|
15347
16466
|
hint: `Set it with \`mostra secret set ${name}\`, reading the value from stdin.`
|
|
@@ -15428,7 +16547,7 @@ function openSecrets(options) {
|
|
|
15428
16547
|
return true;
|
|
15429
16548
|
},
|
|
15430
16549
|
async resolve(artifactId, name) {
|
|
15431
|
-
if (!SECRET_NAME_PATTERN.test(name)) throw missing(name, "not a secret name");
|
|
16550
|
+
if (!SECRET_NAME_PATTERN.test(name)) throw missing$1(name, "not a secret name");
|
|
15432
16551
|
const port = options.port?.();
|
|
15433
16552
|
if (port) {
|
|
15434
16553
|
let value;
|
|
@@ -15442,7 +16561,7 @@ function openSecrets(options) {
|
|
|
15442
16561
|
name,
|
|
15443
16562
|
error: String(error?.message ?? error)
|
|
15444
16563
|
});
|
|
15445
|
-
throw missing(name, "the host's secrets port didn't answer");
|
|
16564
|
+
throw missing$1(name, "the host's secrets port didn't answer");
|
|
15446
16565
|
}
|
|
15447
16566
|
if (typeof value === "string") {
|
|
15448
16567
|
options.redactor.protectSecret(value);
|
|
@@ -15453,7 +16572,7 @@ function openSecrets(options) {
|
|
|
15453
16572
|
kind: "artifact",
|
|
15454
16573
|
artifactId
|
|
15455
16574
|
}), name) ?? read(dirOf({ kind: "home" }), name);
|
|
15456
|
-
if (value === void 0) throw missing(name);
|
|
16575
|
+
if (value === void 0) throw missing$1(name);
|
|
15457
16576
|
options.redactor.protectSecret(value);
|
|
15458
16577
|
return value;
|
|
15459
16578
|
}
|
|
@@ -15947,65 +17066,987 @@ async function shutDownInstance(home, client) {
|
|
|
15947
17066
|
name: "mostra-service",
|
|
15948
17067
|
version: "0"
|
|
15949
17068
|
});
|
|
15950
|
-
await session.client.peer.call(mostraShutdownMethod, {}, { timeoutMs: 1e4 }).catch(() => void 0);
|
|
15951
|
-
session.client.close();
|
|
15952
|
-
} catch {
|
|
15953
|
-
return;
|
|
17069
|
+
await session.client.peer.call(mostraShutdownMethod, {}, { timeoutMs: 1e4 }).catch(() => void 0);
|
|
17070
|
+
session.client.close();
|
|
17071
|
+
} catch {
|
|
17072
|
+
return;
|
|
17073
|
+
}
|
|
17074
|
+
const deadline = Date.now() + 2e4;
|
|
17075
|
+
while (Date.now() < deadline && await isSameProcess(record.pid, record.startTime)) await new Promise((resolve) => setTimeout(resolve, 100));
|
|
17076
|
+
}
|
|
17077
|
+
/** Whether Task Scheduler holds the home's task. */
|
|
17078
|
+
function taskRegistered(status) {
|
|
17079
|
+
try {
|
|
17080
|
+
run("schtasks", [
|
|
17081
|
+
"/Query",
|
|
17082
|
+
"/TN",
|
|
17083
|
+
status.name
|
|
17084
|
+
]);
|
|
17085
|
+
return true;
|
|
17086
|
+
} catch {
|
|
17087
|
+
return false;
|
|
17088
|
+
}
|
|
17089
|
+
}
|
|
17090
|
+
/**
|
|
17091
|
+
* Stops and removes the home's login service; a home without one is left as it is. On Windows a
|
|
17092
|
+
* task Task Scheduler still holds is removed though the home lost its definition (restored from a
|
|
17093
|
+
* backup, removed by hand), or the task would keep starting the daemon at every logon (Opus review
|
|
17094
|
+
* of WP-W2, finding 5).
|
|
17095
|
+
*/
|
|
17096
|
+
async function uninstallService(spec, options = {}) {
|
|
17097
|
+
const status = serviceFor(spec);
|
|
17098
|
+
const orphaned = !status.installed && status.manager === "task-scheduler" && !options.noStart && taskRegistered(status);
|
|
17099
|
+
if (!status.installed && !orphaned) return status;
|
|
17100
|
+
if (!options.noStart) await stopService(status, spec.home, options);
|
|
17101
|
+
rmSync(status.file, { force: true });
|
|
17102
|
+
if (!options.noStart && status.manager === "systemd") try {
|
|
17103
|
+
run("systemctl", ["--user", "daemon-reload"]);
|
|
17104
|
+
} catch {}
|
|
17105
|
+
return {
|
|
17106
|
+
...status,
|
|
17107
|
+
installed: false
|
|
17108
|
+
};
|
|
17109
|
+
}
|
|
17110
|
+
/**
|
|
17111
|
+
* Whether the home has a login service whose file runs this home's daemon (`mostra doctor`); on
|
|
17112
|
+
* Windows also whether Task Scheduler holds its task (`registered`).
|
|
17113
|
+
*/
|
|
17114
|
+
function serviceStatus(spec) {
|
|
17115
|
+
const status = serviceFor(spec);
|
|
17116
|
+
const registered = status.manager === "task-scheduler" ? { registered: taskRegistered(status) } : {};
|
|
17117
|
+
if (!status.installed) return {
|
|
17118
|
+
...status,
|
|
17119
|
+
current: false,
|
|
17120
|
+
...registered
|
|
17121
|
+
};
|
|
17122
|
+
return {
|
|
17123
|
+
...status,
|
|
17124
|
+
current: readDefinition(status) === serviceFile(spec, status),
|
|
17125
|
+
...registered
|
|
17126
|
+
};
|
|
17127
|
+
}
|
|
17128
|
+
//#endregion
|
|
17129
|
+
//#region src/share/tunnel.ts
|
|
17130
|
+
/**
|
|
17131
|
+
* A tunnel tool's process (D158 item 4): `tailscale serve`, `tailscale funnel` or `cloudflared`,
|
|
17132
|
+
* started through the process manager (recorded, gated, reaped after a crash, RT-09), its output
|
|
17133
|
+
* read line by line until it says it serves, fails, or runs out of time. A tunnel that serves
|
|
17134
|
+
* keeps running until it is stopped; `ended` says when it ends by itself.
|
|
17135
|
+
*/
|
|
17136
|
+
const TAIL = 20;
|
|
17137
|
+
/** Starts a tunnel tool and resolves once it serves; rejects with a `MOSTRA_SHARE_*` RpcError. */
|
|
17138
|
+
async function runTunnel(options) {
|
|
17139
|
+
const lines = [];
|
|
17140
|
+
let origin = options.origin;
|
|
17141
|
+
let settle;
|
|
17142
|
+
const settled = new Promise((resolve) => {
|
|
17143
|
+
settle = resolve;
|
|
17144
|
+
});
|
|
17145
|
+
let serving = false;
|
|
17146
|
+
const onLine = (line) => {
|
|
17147
|
+
lines.push(line);
|
|
17148
|
+
if (lines.length > TAIL) lines.shift();
|
|
17149
|
+
if (serving) return;
|
|
17150
|
+
const verdict = options.read(line);
|
|
17151
|
+
if (verdict === void 0) return;
|
|
17152
|
+
if (verdict.kind === "origin") {
|
|
17153
|
+
origin = verdict.origin;
|
|
17154
|
+
return;
|
|
17155
|
+
}
|
|
17156
|
+
if (verdict.kind === "failed") {
|
|
17157
|
+
settle?.({
|
|
17158
|
+
ok: false,
|
|
17159
|
+
diagnostic: verdict.diagnostic
|
|
17160
|
+
});
|
|
17161
|
+
return;
|
|
17162
|
+
}
|
|
17163
|
+
if (verdict.origin !== void 0) origin = verdict.origin;
|
|
17164
|
+
if (origin !== void 0) {
|
|
17165
|
+
serving = true;
|
|
17166
|
+
settle?.({ ok: true });
|
|
17167
|
+
}
|
|
17168
|
+
};
|
|
17169
|
+
let child;
|
|
17170
|
+
try {
|
|
17171
|
+
child = await options.processes.spawn({
|
|
17172
|
+
kind: options.kind,
|
|
17173
|
+
ownerRef: options.ownerRef,
|
|
17174
|
+
command: options.command,
|
|
17175
|
+
args: options.args,
|
|
17176
|
+
env: options.env,
|
|
17177
|
+
onStdout: onLine,
|
|
17178
|
+
onStderr: onLine
|
|
17179
|
+
});
|
|
17180
|
+
} catch (error) {
|
|
17181
|
+
throw new RpcError(createDiagnostic("MOSTRA_SHARE_TOOL_NOT_READY", { message: `${options.label} couldn't start: ${error.message}` }));
|
|
17182
|
+
}
|
|
17183
|
+
let stopping = false;
|
|
17184
|
+
const exited = child.exited.then((exit) => {
|
|
17185
|
+
if (!serving) settle?.({
|
|
17186
|
+
ok: false,
|
|
17187
|
+
diagnostic: createDiagnostic("MOSTRA_SHARE_TUNNEL_FAILED", { message: `${options.label} ended before it served (exit ${exit.code ?? exit.signal}): ${lastWords(lines)}` })
|
|
17188
|
+
});
|
|
17189
|
+
return exit;
|
|
17190
|
+
});
|
|
17191
|
+
const timer = setTimeout(() => {
|
|
17192
|
+
settle?.({
|
|
17193
|
+
ok: false,
|
|
17194
|
+
diagnostic: createDiagnostic("MOSTRA_SHARE_TUNNEL_FAILED", { message: `${options.label} didn't serve within ${Math.round(options.timeoutMs / 1e3)} s: ${lastWords(lines)}` })
|
|
17195
|
+
});
|
|
17196
|
+
}, options.timeoutMs);
|
|
17197
|
+
const outcome = await settled;
|
|
17198
|
+
clearTimeout(timer);
|
|
17199
|
+
if (!outcome.ok) {
|
|
17200
|
+
stopping = true;
|
|
17201
|
+
await child.stop(3e3).catch(() => void 0);
|
|
17202
|
+
throw new RpcError(outcome.diagnostic);
|
|
17203
|
+
}
|
|
17204
|
+
options.log.info("share.tunnel_serving", {
|
|
17205
|
+
kind: options.kind,
|
|
17206
|
+
owner: options.ownerRef,
|
|
17207
|
+
origin
|
|
17208
|
+
});
|
|
17209
|
+
const ended = exited.then((exit) => new Promise((resolve) => {
|
|
17210
|
+
if (!stopping) resolve({
|
|
17211
|
+
code: exit.code,
|
|
17212
|
+
lines: [...lines]
|
|
17213
|
+
});
|
|
17214
|
+
}));
|
|
17215
|
+
return {
|
|
17216
|
+
origin,
|
|
17217
|
+
ended,
|
|
17218
|
+
async stop() {
|
|
17219
|
+
stopping = true;
|
|
17220
|
+
await child.stop(3e3).catch(() => void 0);
|
|
17221
|
+
}
|
|
17222
|
+
};
|
|
17223
|
+
}
|
|
17224
|
+
/** The last meaningful lines of a tool's output, for a message. */
|
|
17225
|
+
function lastWords(lines) {
|
|
17226
|
+
const meaningful = lines.filter((line) => line.trim() !== "").slice(-3);
|
|
17227
|
+
return meaningful.length === 0 ? "it said nothing" : meaningful.join(" / ").slice(0, 600);
|
|
17228
|
+
}
|
|
17229
|
+
/**
|
|
17230
|
+
* Runs a tool to its end and resolves with its standard output (a status query), or rejects with
|
|
17231
|
+
* `MOSTRA_SHARE_TOOL_NOT_READY` naming what it said.
|
|
17232
|
+
*/
|
|
17233
|
+
async function runToCompletion(options) {
|
|
17234
|
+
const stdout = [];
|
|
17235
|
+
const stderr = [];
|
|
17236
|
+
let child;
|
|
17237
|
+
try {
|
|
17238
|
+
child = await options.processes.spawn({
|
|
17239
|
+
kind: options.kind,
|
|
17240
|
+
ownerRef: options.ownerRef,
|
|
17241
|
+
command: options.command,
|
|
17242
|
+
args: options.args,
|
|
17243
|
+
env: options.env,
|
|
17244
|
+
onStdout: (line) => stdout.push(line),
|
|
17245
|
+
onStderr: (line) => stderr.push(line)
|
|
17246
|
+
});
|
|
17247
|
+
} catch (error) {
|
|
17248
|
+
throw new RpcError(createDiagnostic("MOSTRA_SHARE_TOOL_NOT_READY", { message: `${options.label} couldn't start: ${error.message}` }));
|
|
15954
17249
|
}
|
|
15955
|
-
const
|
|
15956
|
-
|
|
17250
|
+
const timer = setTimeout(() => void child.stop(1e3), options.timeoutMs);
|
|
17251
|
+
const exit = await child.exited;
|
|
17252
|
+
clearTimeout(timer);
|
|
17253
|
+
return {
|
|
17254
|
+
code: exit.code,
|
|
17255
|
+
stdout: stdout.join("\n"),
|
|
17256
|
+
stderr: stderr.join("\n")
|
|
17257
|
+
};
|
|
15957
17258
|
}
|
|
15958
|
-
|
|
15959
|
-
|
|
17259
|
+
//#endregion
|
|
17260
|
+
//#region src/share/cloudflare.ts
|
|
17261
|
+
/**
|
|
17262
|
+
* The Cloudflare driver (D158 item 4): a Cloudflare quick tunnel per face, `cloudflared tunnel
|
|
17263
|
+
* --url http://127.0.0.1:<port>`, which needs no account and gets a random `trycloudflare.com`
|
|
17264
|
+
* hostname. Each hostname is its own site (`trycloudflare.com` is a public suffix), so a share's
|
|
17265
|
+
* shell and artifact are cross-site and its frames use worker mode (D70). Quick tunnels hold every
|
|
17266
|
+
* response back until it ends, so pages long-poll (VERIFIED_FACTS, WP-13). A quick tunnel's
|
|
17267
|
+
* hostname dies with its process, so a Cloudflare share ends with its tunnel.
|
|
17268
|
+
*/
|
|
17269
|
+
/** How long a quick tunnel may take to serve: registering and the hostname's first answer. */
|
|
17270
|
+
const QUICK_TUNNEL_TIMEOUT_MS = 6e4;
|
|
17271
|
+
/** How `cloudflared` runs, or `MOSTRA_SHARE_TOOL_MISSING`. */
|
|
17272
|
+
function cloudflared(context) {
|
|
17273
|
+
const tool = toolCommand("cloudflared", context.env);
|
|
17274
|
+
if (!tool) throw new RpcError(createDiagnostic("MOSTRA_SHARE_TOOL_MISSING", { message: `cloudflared isn't installed on this machine. ${installHint("cloudflared")}` }));
|
|
17275
|
+
return tool;
|
|
17276
|
+
}
|
|
17277
|
+
/**
|
|
17278
|
+
* Reads `cloudflared`'s log: it names the quick tunnel's address in a banner, and serves once a
|
|
17279
|
+
* connection to Cloudflare's edge is registered.
|
|
17280
|
+
*/
|
|
17281
|
+
function quickTunnelReader(fake) {
|
|
17282
|
+
return (line) => {
|
|
17283
|
+
const local = fake ? /\b(http:\/\/[a-z0-9-]+\.localhost:\d+)\b/.exec(line) : null;
|
|
17284
|
+
if (local) return {
|
|
17285
|
+
kind: "origin",
|
|
17286
|
+
origin: local[1].toLowerCase()
|
|
17287
|
+
};
|
|
17288
|
+
const address = /https:\/\/([a-z0-9-]+\.trycloudflare\.com)\b/i.exec(line);
|
|
17289
|
+
if (address) return {
|
|
17290
|
+
kind: "origin",
|
|
17291
|
+
origin: `https://${address[1].toLowerCase()}`
|
|
17292
|
+
};
|
|
17293
|
+
if (/Registered tunnel connection/i.test(line)) return { kind: "serving" };
|
|
17294
|
+
if (/failed to (request|create) quick tunnel|error unmarshaling QuickTunnel|429 Too Many Requests/i.test(line)) return {
|
|
17295
|
+
kind: "failed",
|
|
17296
|
+
diagnostic: createDiagnostic("MOSTRA_SHARE_TUNNEL_FAILED", { message: `Cloudflare didn't open a quick tunnel: ${line.trim().slice(0, 300)}` })
|
|
17297
|
+
};
|
|
17298
|
+
};
|
|
17299
|
+
}
|
|
17300
|
+
/**
|
|
17301
|
+
* Opens a quick tunnel to `local`. It never reads the user's own `cloudflared` configuration (a
|
|
17302
|
+
* file with ingress rules would turn the quick tunnel off): it runs with an empty one of its own.
|
|
17303
|
+
*/
|
|
17304
|
+
function quickTunnel(context, input) {
|
|
17305
|
+
const tool = cloudflared(context);
|
|
17306
|
+
mkdirSync(context.cacheDir, {
|
|
17307
|
+
recursive: true,
|
|
17308
|
+
mode: 448
|
|
17309
|
+
});
|
|
17310
|
+
const config = join(context.cacheDir, "cloudflared.yml");
|
|
17311
|
+
writeFileSync(config, "# Mostra's quick tunnels read no other configuration.\nno-autoupdate: true\n", { mode: 384 });
|
|
17312
|
+
return runTunnel({
|
|
17313
|
+
processes: context.processes,
|
|
17314
|
+
log: context.log,
|
|
17315
|
+
kind: "tunnel-cloudflare",
|
|
17316
|
+
ownerRef: input.ownerRef,
|
|
17317
|
+
command: tool.command,
|
|
17318
|
+
args: [
|
|
17319
|
+
...tool.args,
|
|
17320
|
+
"tunnel",
|
|
17321
|
+
"--config",
|
|
17322
|
+
config,
|
|
17323
|
+
"--no-autoupdate",
|
|
17324
|
+
"--metrics",
|
|
17325
|
+
"127.0.0.1:0",
|
|
17326
|
+
"--management-diagnostics=false",
|
|
17327
|
+
"--url",
|
|
17328
|
+
input.local
|
|
17329
|
+
],
|
|
17330
|
+
env: context.env,
|
|
17331
|
+
read: quickTunnelReader(tool.fake),
|
|
17332
|
+
timeoutMs: QUICK_TUNNEL_TIMEOUT_MS,
|
|
17333
|
+
label: "A Cloudflare quick tunnel"
|
|
17334
|
+
});
|
|
17335
|
+
}
|
|
17336
|
+
/**
|
|
17337
|
+
* Waits until a quick tunnel's hostname resolves at Cloudflare's own resolvers (1.1.1.1 and
|
|
17338
|
+
* 1.0.0.1), asked directly, past this machine's cache. A new `trycloudflare.com` name takes a few
|
|
17339
|
+
* seconds to appear, and a resolver that is asked too early caches the miss for many minutes
|
|
17340
|
+
* (observed: the link never opened on this machine after an early probe, WP-13), so neither this
|
|
17341
|
+
* machine nor a viewer's phone may ask before the name exists. Resolves `false` when the budget
|
|
17342
|
+
* runs out (a network that blocks outside resolvers): the share goes on, since a viewer's
|
|
17343
|
+
* resolver may still answer.
|
|
17344
|
+
*/
|
|
17345
|
+
async function hostnameResolves(hostname, budgetMs) {
|
|
17346
|
+
const resolver = new Resolver({
|
|
17347
|
+
timeout: 2e3,
|
|
17348
|
+
tries: 1
|
|
17349
|
+
});
|
|
17350
|
+
resolver.setServers(["1.1.1.1", "1.0.0.1"]);
|
|
17351
|
+
const until = Date.now() + budgetMs;
|
|
17352
|
+
while (Date.now() < until) {
|
|
17353
|
+
try {
|
|
17354
|
+
if ((await resolver.resolve4(hostname)).length > 0) return true;
|
|
17355
|
+
} catch {}
|
|
17356
|
+
await new Promise((resolve) => setTimeout(resolve, 1e3));
|
|
17357
|
+
}
|
|
17358
|
+
return false;
|
|
17359
|
+
}
|
|
17360
|
+
//#endregion
|
|
17361
|
+
//#region src/share/tailscale.ts
|
|
17362
|
+
/**
|
|
17363
|
+
* The Tailscale driver (D158 item 4): Tailscale Serve for tailnet shares and Funnel for public
|
|
17364
|
+
* ones, through foreground `tailscale serve` and `tailscale funnel` children, one per address.
|
|
17365
|
+
* A foreground configuration lives as long as its command, so a stopped or crashed share leaves
|
|
17366
|
+
* nothing exposed. The device's name comes from `tailscale status --json`; a port this device's
|
|
17367
|
+
* own configuration already uses is never taken over.
|
|
17368
|
+
*/
|
|
17369
|
+
const FUNNEL_ARTIFACT_PORTS = [8443, 1e4];
|
|
17370
|
+
/** How long `tailscale serve` or `funnel` may take to serve. */
|
|
17371
|
+
const SERVE_TIMEOUT_MS = 3e4;
|
|
17372
|
+
const missing = () => new RpcError(createDiagnostic("MOSTRA_SHARE_TOOL_MISSING", { message: `Tailscale isn't installed on this machine (no \`tailscale\` found). ${installHint("tailscale")}` }));
|
|
17373
|
+
/** Finds Tailscale and this device, or explains what is missing. */
|
|
17374
|
+
async function tailnetDevice(context) {
|
|
17375
|
+
const tool = toolCommand("tailscale", context.env);
|
|
17376
|
+
if (!tool) throw missing();
|
|
17377
|
+
const status = await runToCompletion({
|
|
17378
|
+
processes: context.processes,
|
|
17379
|
+
kind: "tunnel-query",
|
|
17380
|
+
ownerRef: "tailscale",
|
|
17381
|
+
command: tool.command,
|
|
17382
|
+
args: [
|
|
17383
|
+
...tool.args,
|
|
17384
|
+
"status",
|
|
17385
|
+
"--json"
|
|
17386
|
+
],
|
|
17387
|
+
env: context.env,
|
|
17388
|
+
timeoutMs: 15e3,
|
|
17389
|
+
label: "Tailscale"
|
|
17390
|
+
});
|
|
17391
|
+
let parsed;
|
|
15960
17392
|
try {
|
|
15961
|
-
|
|
15962
|
-
"/Query",
|
|
15963
|
-
"/TN",
|
|
15964
|
-
status.name
|
|
15965
|
-
]);
|
|
15966
|
-
return true;
|
|
17393
|
+
parsed = JSON.parse(status.stdout);
|
|
15967
17394
|
} catch {
|
|
15968
|
-
|
|
17395
|
+
throw new RpcError(createDiagnostic("MOSTRA_SHARE_TOOL_NOT_READY", { message: `Tailscale didn't report its status: ${(status.stderr || status.stdout).trim().slice(0, 400) || `exit ${status.code}`}. Start Tailscale and sign in (\`tailscale up\`).` }));
|
|
15969
17396
|
}
|
|
17397
|
+
if (parsed.BackendState !== "Running") throw new RpcError(createDiagnostic("MOSTRA_SHARE_TOOL_NOT_READY", { message: `Tailscale is ${parsed.BackendState ?? "not running"} on this machine. Start it and sign in (\`tailscale up\`).` }));
|
|
17398
|
+
const dns = parsed.Self?.DNSName?.replace(/\.$/, "").toLowerCase();
|
|
17399
|
+
if (!dns || parsed.CurrentTailnet?.MagicDNSEnabled === false) throw new RpcError(createDiagnostic("MOSTRA_SHARE_NOT_ENABLED", { message: "This tailnet has MagicDNS off, which Tailscale Serve and Funnel need for the device's name. Turn it on in the tailnet's DNS settings (https://login.tailscale.com/admin/dns)." }));
|
|
17400
|
+
return {
|
|
17401
|
+
tool,
|
|
17402
|
+
hostname: dns,
|
|
17403
|
+
served: await servedPorts(context, tool)
|
|
17404
|
+
};
|
|
17405
|
+
}
|
|
17406
|
+
/** The ports this device's Serve and Funnel configuration uses now. */
|
|
17407
|
+
async function servedPorts(context, tool) {
|
|
17408
|
+
const status = await runToCompletion({
|
|
17409
|
+
processes: context.processes,
|
|
17410
|
+
kind: "tunnel-query",
|
|
17411
|
+
ownerRef: "tailscale",
|
|
17412
|
+
command: tool.command,
|
|
17413
|
+
args: [
|
|
17414
|
+
...tool.args,
|
|
17415
|
+
"serve",
|
|
17416
|
+
"status",
|
|
17417
|
+
"--json"
|
|
17418
|
+
],
|
|
17419
|
+
env: context.env,
|
|
17420
|
+
timeoutMs: 15e3,
|
|
17421
|
+
label: "Tailscale"
|
|
17422
|
+
});
|
|
17423
|
+
const ports = /* @__PURE__ */ new Set();
|
|
17424
|
+
try {
|
|
17425
|
+
const config = JSON.parse(status.stdout || "{}");
|
|
17426
|
+
for (const key of Object.keys(config.TCP ?? {})) ports.add(Number(key));
|
|
17427
|
+
for (const session of Object.values(config.Foreground ?? {})) for (const key of Object.keys(session.TCP ?? {})) ports.add(Number(key));
|
|
17428
|
+
} catch {}
|
|
17429
|
+
return ports;
|
|
15970
17430
|
}
|
|
15971
17431
|
/**
|
|
15972
|
-
*
|
|
15973
|
-
*
|
|
15974
|
-
* backup, removed by hand), or the task would keep starting the daemon at every logon (Opus review
|
|
15975
|
-
* of WP-W2, finding 5).
|
|
17432
|
+
* Reads `tailscale serve` and `funnel` output: they serve once they print where; a tailnet
|
|
17433
|
+
* without the feature prints the address where an admin turns it on, which the share reports.
|
|
15976
17434
|
*/
|
|
15977
|
-
|
|
15978
|
-
|
|
15979
|
-
const
|
|
15980
|
-
|
|
15981
|
-
|
|
15982
|
-
|
|
15983
|
-
|
|
15984
|
-
|
|
15985
|
-
|
|
15986
|
-
|
|
15987
|
-
|
|
15988
|
-
|
|
17435
|
+
function serveReader(feature, device, port) {
|
|
17436
|
+
let notEnabled = false;
|
|
17437
|
+
const expected = tailnetOrigin(device.hostname, port);
|
|
17438
|
+
return (line) => {
|
|
17439
|
+
const text = line.trim();
|
|
17440
|
+
const printed = /^(https?:\/\/\S+?)\/?$/.exec(text)?.[1]?.toLowerCase();
|
|
17441
|
+
if (printed !== void 0 && (printed === expected || device.tool.fake && /^http:\/\/(\[::1\]|127\.0\.0\.1|localhost):\d+$/.test(printed))) return {
|
|
17442
|
+
kind: "origin",
|
|
17443
|
+
origin: printed
|
|
17444
|
+
};
|
|
17445
|
+
if (/not enabled on your tailnet|isn't enabled|is not enabled/i.test(text)) {
|
|
17446
|
+
notEnabled = true;
|
|
17447
|
+
return;
|
|
17448
|
+
}
|
|
17449
|
+
const consent = /https:\/\/login\.tailscale\.com\/\S+/.exec(text);
|
|
17450
|
+
if (consent && notEnabled) return {
|
|
17451
|
+
kind: "failed",
|
|
17452
|
+
diagnostic: createDiagnostic("MOSTRA_SHARE_NOT_ENABLED", { message: `Tailscale ${feature} isn't enabled for this device's tailnet. An admin of the tailnet turns it on at ${consent[0]}` })
|
|
17453
|
+
};
|
|
17454
|
+
if (/^Available (within your tailnet|on the internet)/i.test(text) || /Press Ctrl\+C to exit/i.test(text)) return { kind: "serving" };
|
|
17455
|
+
if (/already|in use|conflict/i.test(text) && /port|serve|listen/i.test(text)) return {
|
|
17456
|
+
kind: "failed",
|
|
17457
|
+
diagnostic: createDiagnostic("MOSTRA_SHARE_PORTS_EXHAUSTED", { message: `Tailscale refused the port: ${text.slice(0, 300)}` })
|
|
17458
|
+
};
|
|
17459
|
+
if (/^(error|failed)|permission denied|access denied/i.test(text)) return {
|
|
17460
|
+
kind: "failed",
|
|
17461
|
+
diagnostic: createDiagnostic("MOSTRA_SHARE_TOOL_NOT_READY", { message: `Tailscale ${feature} refused the share: ${text.slice(0, 300)}` })
|
|
17462
|
+
};
|
|
15989
17463
|
};
|
|
15990
17464
|
}
|
|
15991
17465
|
/**
|
|
15992
|
-
*
|
|
15993
|
-
*
|
|
17466
|
+
* Serves `local` at `https://<device>:<port>` on the tailnet (`serve`) or on the internet
|
|
17467
|
+
* (`funnel`), until the tunnel is stopped.
|
|
15994
17468
|
*/
|
|
15995
|
-
function
|
|
15996
|
-
const
|
|
15997
|
-
|
|
15998
|
-
|
|
15999
|
-
|
|
16000
|
-
|
|
16001
|
-
|
|
17469
|
+
function expose(context, device, input) {
|
|
17470
|
+
const label = input.feature === "serve" ? "Tailscale Serve" : "Tailscale Funnel";
|
|
17471
|
+
return runTunnel({
|
|
17472
|
+
processes: context.processes,
|
|
17473
|
+
log: context.log,
|
|
17474
|
+
kind: `tunnel-${input.feature}`,
|
|
17475
|
+
ownerRef: input.ownerRef,
|
|
17476
|
+
command: device.tool.command,
|
|
17477
|
+
args: [
|
|
17478
|
+
...device.tool.args,
|
|
17479
|
+
input.feature,
|
|
17480
|
+
`--https=${input.port}`,
|
|
17481
|
+
input.local
|
|
17482
|
+
],
|
|
17483
|
+
env: context.env,
|
|
17484
|
+
read: serveReader(input.feature === "serve" ? "Serve" : "Funnel", device, input.port),
|
|
17485
|
+
...device.tool.fake ? {} : { origin: tailnetOrigin(device.hostname, input.port) },
|
|
17486
|
+
timeoutMs: SERVE_TIMEOUT_MS,
|
|
17487
|
+
label
|
|
17488
|
+
});
|
|
17489
|
+
}
|
|
17490
|
+
/** `https://<device>` with the port only when it isn't 443, as a browser writes the origin. */
|
|
17491
|
+
function tailnetOrigin(hostname, port) {
|
|
17492
|
+
return port === 443 ? `https://${hostname}` : `https://${hostname}:${port}`;
|
|
17493
|
+
}
|
|
17494
|
+
//#endregion
|
|
17495
|
+
//#region src/share/index.ts
|
|
17496
|
+
/**
|
|
17497
|
+
* Shares (HY-04, HY-05, D158): an artifact opened to viewers beyond this machine through a tunnel
|
|
17498
|
+
* the instance drives. A share opens the gateway's faces for its tunnel (D158 item 1), the tunnel
|
|
17499
|
+
* tool's processes that forward to them, and a link of its own at the tunnel's shell address
|
|
17500
|
+
* (D97 item 10); it ends at its TTL, on `share/stop`, when its link is revoked, or when its tunnel
|
|
17501
|
+
* can't continue, and every end revokes its link and stops what only it used.
|
|
17502
|
+
*
|
|
17503
|
+
* - **Tailnet** (Tailscale Serve): the shell's and each artifact's face keep leased ports, served
|
|
17504
|
+
* on the device's name at the same port numbers, so tailnet links survive restarts. Requests
|
|
17505
|
+
* carry the tailnet person, who becomes the viewer (D158 item 2).
|
|
17506
|
+
* - **Funnel**: the shell on 443 and two artifacts on 8443 and 10000 (D158 item 4), public.
|
|
17507
|
+
* - **Cloudflare** quick tunnels: one per face, each a site of its own, so worker-mode frames
|
|
17508
|
+
* (D70), and pages long-poll, since quick tunnels hold responses back. A quick tunnel's address
|
|
17509
|
+
* dies with its process, so its share ends with it, a restart included.
|
|
17510
|
+
*
|
|
17511
|
+
* ```ts
|
|
17512
|
+
* const shares = createShares({ ledger, log, gateway, capabilities, interaction, artifacts, … });
|
|
17513
|
+
* const share = await shares.start({ artifact: { artifactId }, via: "cloudflare", ttl: "1h" });
|
|
17514
|
+
* share.url; // https://<random>.trycloudflare.com/a/art_…#t=…
|
|
17515
|
+
* ```
|
|
17516
|
+
*/
|
|
17517
|
+
/** How often active shares are checked for an expired or revoked link. */
|
|
17518
|
+
const SWEEP_MS = 3e4;
|
|
17519
|
+
/** How a tailnet or Funnel tunnel that ended by itself is set up again: after 1, 4 and 16 s. */
|
|
17520
|
+
const RESTART_DELAYS_MS = [
|
|
17521
|
+
1e3,
|
|
17522
|
+
4e3,
|
|
17523
|
+
16e3
|
|
17524
|
+
];
|
|
17525
|
+
/** How long a restart keeps trying to set a share up again before ending it (Tailscale starting). */
|
|
17526
|
+
const RECOVERY_DELAYS_MS = [
|
|
17527
|
+
0,
|
|
17528
|
+
5e3,
|
|
17529
|
+
15e3,
|
|
17530
|
+
3e4,
|
|
17531
|
+
6e4
|
|
17532
|
+
];
|
|
17533
|
+
/** How long a quick tunnel's name may take to appear before its link is handed out anyway. */
|
|
17534
|
+
const PROBE_MS = 3e4;
|
|
17535
|
+
/** Creates the shares of one instance. */
|
|
17536
|
+
function createShares(options) {
|
|
17537
|
+
const { ledger, log, gateway, capabilities, interaction } = options;
|
|
17538
|
+
const exposures = /* @__PURE__ */ new Map();
|
|
17539
|
+
const timers = /* @__PURE__ */ new Map();
|
|
17540
|
+
const inflight = new InflightRequests();
|
|
17541
|
+
let closed = false;
|
|
17542
|
+
let chain = Promise.resolve();
|
|
17543
|
+
/** Share starts and stops run one at a time, so refcounts and port plans never race. */
|
|
17544
|
+
const serial = (task) => {
|
|
17545
|
+
const run = chain.then(task, task);
|
|
17546
|
+
chain = run.catch(() => void 0);
|
|
17547
|
+
return run;
|
|
17548
|
+
};
|
|
17549
|
+
const toolContext = {
|
|
17550
|
+
processes: options.processes,
|
|
17551
|
+
log,
|
|
17552
|
+
env: {
|
|
17553
|
+
...options.toolEnvironment,
|
|
17554
|
+
...pick(options.environment)
|
|
17555
|
+
}
|
|
17556
|
+
};
|
|
17557
|
+
const iso = (ms) => new Date(ms).toISOString();
|
|
17558
|
+
const row = (shareId) => ledger.read((db) => db.get("SELECT * FROM share WHERE id = ?", shareId));
|
|
17559
|
+
const toShare = (found) => {
|
|
17560
|
+
const tokenId = capabilities.current(found.token_id);
|
|
17561
|
+
const url = found.stopped_at === null ? gateway.reveal(tokenId) : void 0;
|
|
17562
|
+
const artifactKey = JSON.parse(found.plan_json).faces.find((face) => face.listener === "artifact")?.key;
|
|
17563
|
+
const artifactOrigin = found.stopped_at === null && artifactKey !== void 0 ? gateway.face(artifactKey)?.origin() : void 0;
|
|
17564
|
+
return {
|
|
17565
|
+
shareId: found.id,
|
|
17566
|
+
artifactId: found.artifact_id,
|
|
17567
|
+
via: found.via,
|
|
17568
|
+
...url !== void 0 ? { url } : {},
|
|
17569
|
+
hostname: found.hostname,
|
|
17570
|
+
...artifactOrigin !== void 0 ? { artifactOrigin } : {},
|
|
17571
|
+
mode: found.mode,
|
|
17572
|
+
tokenId,
|
|
17573
|
+
startedAt: found.started_at,
|
|
17574
|
+
...found.expires_at !== null ? { expiresAt: found.expires_at } : {},
|
|
17575
|
+
state: found.stopped_at === null ? "active" : "stopped",
|
|
17576
|
+
...found.stopped_at !== null ? { stoppedAt: found.stopped_at } : {},
|
|
17577
|
+
...found.stop_reason !== null ? { stopReason: found.stop_reason } : {}
|
|
17578
|
+
};
|
|
17579
|
+
};
|
|
17580
|
+
const activeRows = () => ledger.read((db) => db.all("SELECT * FROM share WHERE stopped_at IS NULL ORDER BY started_at DESC"));
|
|
17581
|
+
/**
|
|
17582
|
+
* The tunnel of a face, started for `shareId` or joined when it runs already. A tunnel that
|
|
17583
|
+
* ends by itself is set up again (Tailscale, whose address is the device's) or ends every share
|
|
17584
|
+
* that used it (Cloudflare, whose address died with it).
|
|
17585
|
+
*/
|
|
17586
|
+
const acquire = async (key, shareId, via, start) => {
|
|
17587
|
+
const running = exposures.get(key);
|
|
17588
|
+
if (running?.restarting) throw new RpcError(createDiagnostic("MOSTRA_SHARE_TUNNEL_FAILED", { message: "This share's tunnel stopped a moment ago and is being started again; try again in a few seconds." }));
|
|
17589
|
+
if (running) {
|
|
17590
|
+
running.refs.add(shareId);
|
|
17591
|
+
return running.tunnel;
|
|
17592
|
+
}
|
|
17593
|
+
const tunnel = await start();
|
|
17594
|
+
const exposure = {
|
|
17595
|
+
tunnel,
|
|
17596
|
+
refs: /* @__PURE__ */ new Set([shareId]),
|
|
17597
|
+
start,
|
|
17598
|
+
via,
|
|
17599
|
+
restarting: false
|
|
17600
|
+
};
|
|
17601
|
+
exposures.set(key, exposure);
|
|
17602
|
+
watch(key, exposure);
|
|
17603
|
+
return tunnel;
|
|
17604
|
+
};
|
|
17605
|
+
const watch = (key, exposure) => {
|
|
17606
|
+
const current = exposure.tunnel;
|
|
17607
|
+
current.ended.then(async (end) => {
|
|
17608
|
+
if (closed || exposures.get(key) !== exposure || exposure.tunnel !== current) return;
|
|
17609
|
+
log.warn("share.tunnel_dropped", {
|
|
17610
|
+
key,
|
|
17611
|
+
code: end.code,
|
|
17612
|
+
lines: end.lines.slice(-3)
|
|
17613
|
+
});
|
|
17614
|
+
if (exposure.via !== "cloudflare") {
|
|
17615
|
+
exposure.restarting = true;
|
|
17616
|
+
for (const delay of RESTART_DELAYS_MS) {
|
|
17617
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
17618
|
+
if (closed || exposures.get(key) !== exposure) return;
|
|
17619
|
+
try {
|
|
17620
|
+
if (!await serial(async () => {
|
|
17621
|
+
if (closed || exposures.get(key) !== exposure) return false;
|
|
17622
|
+
const tunnel = await exposure.start();
|
|
17623
|
+
if (closed || exposures.get(key) !== exposure) {
|
|
17624
|
+
await tunnel.stop();
|
|
17625
|
+
return false;
|
|
17626
|
+
}
|
|
17627
|
+
exposure.tunnel = tunnel;
|
|
17628
|
+
return true;
|
|
17629
|
+
})) return;
|
|
17630
|
+
exposure.restarting = false;
|
|
17631
|
+
log.info("share.tunnel_restored", { key });
|
|
17632
|
+
watch(key, exposure);
|
|
17633
|
+
return;
|
|
17634
|
+
} catch (error) {
|
|
17635
|
+
log.warn("share.tunnel_restart_failed", {
|
|
17636
|
+
key,
|
|
17637
|
+
error: error.message
|
|
17638
|
+
});
|
|
17639
|
+
}
|
|
17640
|
+
}
|
|
17641
|
+
}
|
|
17642
|
+
for (const shareId of [...exposure.refs]) await serial(() => stop(shareId, "tunnel")).catch((error) => log.error("share.stop_failed", {
|
|
17643
|
+
shareId,
|
|
17644
|
+
error
|
|
17645
|
+
}));
|
|
17646
|
+
});
|
|
17647
|
+
};
|
|
17648
|
+
/** Drops a share's hold on a face's tunnel, stopping it and closing the face when unused. */
|
|
17649
|
+
const release = async (key, shareId) => {
|
|
17650
|
+
const exposure = exposures.get(key);
|
|
17651
|
+
if (exposure) {
|
|
17652
|
+
exposure.refs.delete(shareId);
|
|
17653
|
+
if (exposure.refs.size > 0) return;
|
|
17654
|
+
exposures.delete(key);
|
|
17655
|
+
await exposure.tunnel.stop();
|
|
17656
|
+
}
|
|
17657
|
+
externalPorts.delete(key);
|
|
17658
|
+
await gateway.closeFace(key, !key.startsWith("tailnet:"));
|
|
17659
|
+
};
|
|
17660
|
+
/** The ttl a share's link gets: public shares 1 hour by default and at most 7 days (D158). */
|
|
17661
|
+
const lifetime = (via, ttl) => {
|
|
17662
|
+
if (via === "tailnet") return ttl === void 0 ? void 0 : durationMs(ttl);
|
|
17663
|
+
const ms = durationMs(ttl ?? PUBLIC_SHARE_DEFAULT_TTL);
|
|
17664
|
+
if (ms > PUBLIC_SHARE_MAX_TTL_MS) throw new RpcError(createDiagnostic("MOSTRA_SHARE_TTL_INVALID", { message: `A public share lasts at most 7 days; ${ttl} is longer.` }));
|
|
17665
|
+
return ms;
|
|
17666
|
+
};
|
|
17667
|
+
/** Opens a face and its tunnel for a share, or joins the ones that run already. */
|
|
17668
|
+
const faceFor = async (spec, shareId, tunnel, held) => {
|
|
17669
|
+
const face = await gateway.openFace(spec);
|
|
17670
|
+
held.push(face.key);
|
|
17671
|
+
const running = await acquire(face.key, shareId, spec.by, () => tunnel(face));
|
|
17672
|
+
face.setOrigin(running.origin);
|
|
17673
|
+
return face;
|
|
17674
|
+
};
|
|
17675
|
+
/** Sets up a share's faces and tunnels; on failure releases what it took. */
|
|
17676
|
+
const setUp = async (shareId, artifactId, via, planned) => {
|
|
17677
|
+
const held = [];
|
|
17678
|
+
try {
|
|
17679
|
+
if (via === "cloudflare") {
|
|
17680
|
+
const group = `cloudflare:${shareId}`;
|
|
17681
|
+
const context = {
|
|
17682
|
+
...toolContext,
|
|
17683
|
+
cacheDir: options.cacheDir
|
|
17684
|
+
};
|
|
17685
|
+
const spec = (listener) => ({
|
|
17686
|
+
by: "cloudflare",
|
|
17687
|
+
group,
|
|
17688
|
+
listener,
|
|
17689
|
+
...listener === "artifact" ? {
|
|
17690
|
+
artifactId,
|
|
17691
|
+
mode: "worker"
|
|
17692
|
+
} : {},
|
|
17693
|
+
via: "token",
|
|
17694
|
+
lease: false,
|
|
17695
|
+
streams: false
|
|
17696
|
+
});
|
|
17697
|
+
const settled = await Promise.allSettled([faceFor(spec("shell"), shareId, (face) => quickTunnel(context, {
|
|
17698
|
+
local: face.local,
|
|
17699
|
+
ownerRef: face.key
|
|
17700
|
+
}), held), faceFor(spec("artifact"), shareId, (face) => quickTunnel(context, {
|
|
17701
|
+
local: face.local,
|
|
17702
|
+
ownerRef: face.key
|
|
17703
|
+
}), held)]);
|
|
17704
|
+
const failed = settled.find((outcome) => outcome.status === "rejected");
|
|
17705
|
+
if (failed) throw failed.reason;
|
|
17706
|
+
const [shell, artifact] = settled.map((outcome) => outcome.value);
|
|
17707
|
+
await Promise.all([probe(shell.origin()), probe(artifact.origin())]);
|
|
17708
|
+
return {
|
|
17709
|
+
shell,
|
|
17710
|
+
artifact,
|
|
17711
|
+
plan: { faces: [{
|
|
17712
|
+
key: shell.key,
|
|
17713
|
+
listener: "shell"
|
|
17714
|
+
}, {
|
|
17715
|
+
key: artifact.key,
|
|
17716
|
+
listener: "artifact"
|
|
17717
|
+
}] },
|
|
17718
|
+
hostname: new URL(shell.origin()).hostname
|
|
17719
|
+
};
|
|
17720
|
+
}
|
|
17721
|
+
const device = await tailnetDevice(toolContext);
|
|
17722
|
+
const ours = (port) => [...exposures.entries()].some(([key, exposure]) => exposure.via !== "cloudflare" && planPort(key) === port);
|
|
17723
|
+
const free = (port) => !device.served.has(port) || ours(port);
|
|
17724
|
+
if (via === "tailnet") {
|
|
17725
|
+
const spec = (listener) => ({
|
|
17726
|
+
by: "tailnet",
|
|
17727
|
+
group: "tailnet",
|
|
17728
|
+
listener,
|
|
17729
|
+
...listener === "artifact" ? { artifactId } : {},
|
|
17730
|
+
via: "tailnet",
|
|
17731
|
+
lease: true
|
|
17732
|
+
});
|
|
17733
|
+
const serveAt = (face) => {
|
|
17734
|
+
if (!free(face.port)) throw portTaken(face.port, "Serve");
|
|
17735
|
+
return tailnetTunnel(device, "serve", face.port, face);
|
|
17736
|
+
};
|
|
17737
|
+
const shell = await faceFor(spec("shell"), shareId, serveAt, held);
|
|
17738
|
+
const artifact = await faceFor(spec("artifact"), shareId, serveAt, held);
|
|
17739
|
+
return {
|
|
17740
|
+
shell,
|
|
17741
|
+
artifact,
|
|
17742
|
+
plan: { faces: [{
|
|
17743
|
+
key: shell.key,
|
|
17744
|
+
listener: "shell",
|
|
17745
|
+
external: shell.port
|
|
17746
|
+
}, {
|
|
17747
|
+
key: artifact.key,
|
|
17748
|
+
listener: "artifact",
|
|
17749
|
+
external: artifact.port
|
|
17750
|
+
}] },
|
|
17751
|
+
hostname: device.hostname
|
|
17752
|
+
};
|
|
17753
|
+
}
|
|
17754
|
+
const spec = (listener) => ({
|
|
17755
|
+
by: "funnel",
|
|
17756
|
+
group: "funnel",
|
|
17757
|
+
listener,
|
|
17758
|
+
...listener === "artifact" ? { artifactId } : {},
|
|
17759
|
+
via: "token",
|
|
17760
|
+
lease: true
|
|
17761
|
+
});
|
|
17762
|
+
const shellKey = faceKey("funnel", "shell");
|
|
17763
|
+
if (!exposures.has(shellKey) && !free(443)) throw portTaken(443, "Funnel");
|
|
17764
|
+
const shell = await faceFor(spec("shell"), shareId, (face) => tailnetTunnel(device, "funnel", 443, face), held);
|
|
17765
|
+
const artifactKey = faceKey("funnel", "artifact", artifactId);
|
|
17766
|
+
const plannedPort = planned?.faces.find((face) => face.key === artifactKey)?.external;
|
|
17767
|
+
const port = planPort(artifactKey) ?? [plannedPort, ...FUNNEL_ARTIFACT_PORTS].find((candidate) => candidate !== void 0 && free(candidate) && ![...externalPorts].some(([key, taken]) => key !== artifactKey && taken === candidate));
|
|
17768
|
+
if (port === void 0) throw new RpcError(createDiagnostic("MOSTRA_SHARE_PORTS_EXHAUSTED", { message: `Tailscale Funnel's ports for artifacts (${FUNNEL_ARTIFACT_PORTS.join(" and ")}) are in use: two artifacts are shared through Funnel already, or this device's own configuration uses them.` }));
|
|
17769
|
+
const artifact = await faceFor(spec("artifact"), shareId, (face) => tailnetTunnel(device, "funnel", port, face), held);
|
|
17770
|
+
return {
|
|
17771
|
+
shell,
|
|
17772
|
+
artifact,
|
|
17773
|
+
plan: { faces: [{
|
|
17774
|
+
key: shell.key,
|
|
17775
|
+
listener: "shell",
|
|
17776
|
+
external: 443
|
|
17777
|
+
}, {
|
|
17778
|
+
key: artifact.key,
|
|
17779
|
+
listener: "artifact",
|
|
17780
|
+
external: port
|
|
17781
|
+
}] },
|
|
17782
|
+
hostname: device.hostname
|
|
17783
|
+
};
|
|
17784
|
+
} catch (error) {
|
|
17785
|
+
for (const key of held) await release(key, shareId).catch(() => void 0);
|
|
17786
|
+
throw error;
|
|
17787
|
+
}
|
|
17788
|
+
};
|
|
17789
|
+
/** The external ports of running Tailscale tunnels, by face key. */
|
|
17790
|
+
const externalPorts = /* @__PURE__ */ new Map();
|
|
17791
|
+
const planPort = (key) => externalPorts.get(key);
|
|
17792
|
+
const tailnetTunnel = async (device, feature, port, face) => {
|
|
17793
|
+
const tunnel = await expose(toolContext, device, {
|
|
17794
|
+
feature,
|
|
17795
|
+
port,
|
|
17796
|
+
local: face.local,
|
|
17797
|
+
ownerRef: face.key
|
|
17798
|
+
});
|
|
17799
|
+
externalPorts.set(face.key, port);
|
|
17800
|
+
return tunnel;
|
|
17801
|
+
};
|
|
17802
|
+
const portTaken = (port, feature) => new RpcError(createDiagnostic("MOSTRA_SHARE_PORTS_EXHAUSTED", { message: `Port ${port} of this device is in use by its own Tailscale ${feature} configuration, which Mostra never takes over.` }));
|
|
17803
|
+
/**
|
|
17804
|
+
* Waits until a quick tunnel's name exists at Cloudflare's resolvers, so the link never meets a
|
|
17805
|
+
* cached miss on this machine or a viewer's phone; nothing here resolves it before then.
|
|
17806
|
+
*/
|
|
17807
|
+
const probe = async (origin) => {
|
|
17808
|
+
const budget = options.probeMs ?? PROBE_MS;
|
|
17809
|
+
if (origin === void 0 || budget <= 0) return;
|
|
17810
|
+
const hostname = new URL(origin).hostname;
|
|
17811
|
+
if (!hostname.endsWith(".trycloudflare.com")) return;
|
|
17812
|
+
if (!await hostnameResolves(hostname, budget)) log.warn("share.name_unresolved", {
|
|
17813
|
+
hostname,
|
|
17814
|
+
budgetMs: budget
|
|
17815
|
+
});
|
|
17816
|
+
};
|
|
17817
|
+
const start = async (params) => {
|
|
17818
|
+
const detail = options.artifacts.get(params.artifact);
|
|
17819
|
+
if (!detail.latestVersion && detail.versions.length === 0) throw new RpcError(createDiagnostic("MOSTRA_ARTIFACT_VERSION_NOT_FOUND", { message: `The artifact ${detail.id} has no published version to share.` }));
|
|
17820
|
+
const key = requestKey("share/start", params);
|
|
17821
|
+
if (key !== void 0) {
|
|
17822
|
+
const replay = ledger.read((db) => recordedResult(db, key));
|
|
17823
|
+
const found = replay ? row(replay.shareId) : void 0;
|
|
17824
|
+
if (found) return withUrl(toShare(found));
|
|
17825
|
+
}
|
|
17826
|
+
const ttlMs = lifetime(params.via, params.ttl);
|
|
17827
|
+
const shareId = ShareId.create();
|
|
17828
|
+
const { shell, artifact, plan, hostname } = await setUp(shareId, detail.id, params.via, void 0);
|
|
17829
|
+
const shellOrigin = shell.origin();
|
|
17830
|
+
const startedAt = options.now();
|
|
17831
|
+
const record = () => ledger.write((db) => {
|
|
17832
|
+
const viewerId = params.viewer === void 0 ? void 0 : interaction.viewerForSpec(db, params.viewer);
|
|
17833
|
+
const link = gateway.mintAt({
|
|
17834
|
+
artifactId: detail.id,
|
|
17835
|
+
shellOrigin,
|
|
17836
|
+
scopes: params.scopes,
|
|
17837
|
+
ttlMs,
|
|
17838
|
+
viewerId
|
|
17839
|
+
}, db);
|
|
17840
|
+
db.run("INSERT INTO share (id, artifact_id, via, hostname, token_id, mode, plan_json, started_at, expires_at, stopped_at, stop_reason) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL)", shareId, detail.id, params.via, hostname, link.tokenId, params.via === "cloudflare" ? "worker" : "cookie", JSON.stringify(plan), iso(startedAt), link.expiresAt ?? null);
|
|
17841
|
+
appendEvent(db, {
|
|
17842
|
+
artifactId: detail.id,
|
|
17843
|
+
type: "share.started",
|
|
17844
|
+
payload: {
|
|
17845
|
+
shareId,
|
|
17846
|
+
via: params.via,
|
|
17847
|
+
hostname,
|
|
17848
|
+
artifactOrigin: artifact.origin()
|
|
17849
|
+
}
|
|
17850
|
+
});
|
|
17851
|
+
if (key !== void 0) recordResult(db, key, { shareId });
|
|
17852
|
+
return link;
|
|
17853
|
+
});
|
|
17854
|
+
let minted;
|
|
17855
|
+
try {
|
|
17856
|
+
minted = record();
|
|
17857
|
+
} catch (error) {
|
|
17858
|
+
for (const face of plan.faces) await release(face.key, shareId).catch(() => void 0);
|
|
17859
|
+
throw error;
|
|
17860
|
+
}
|
|
17861
|
+
schedule(shareId, minted.expiresAt);
|
|
17862
|
+
log.info("share.started", {
|
|
17863
|
+
shareId,
|
|
17864
|
+
artifactId: detail.id,
|
|
17865
|
+
via: params.via,
|
|
17866
|
+
hostname
|
|
17867
|
+
});
|
|
17868
|
+
const started = row(shareId);
|
|
17869
|
+
return {
|
|
17870
|
+
...toShare(started),
|
|
17871
|
+
url: minted.url
|
|
17872
|
+
};
|
|
17873
|
+
};
|
|
17874
|
+
const withUrl = (share) => ({
|
|
17875
|
+
...share,
|
|
17876
|
+
url: share.url ?? gateway.reveal(share.tokenId) ?? ""
|
|
17877
|
+
});
|
|
17878
|
+
const schedule = (shareId, expiresAt) => {
|
|
17879
|
+
if (expiresAt === void 0) return;
|
|
17880
|
+
const delay = Math.max(0, Date.parse(expiresAt) - options.now());
|
|
17881
|
+
if (delay > 2 ** 31 - 1) return;
|
|
17882
|
+
const timer = setTimeout(() => {
|
|
17883
|
+
timers.delete(shareId);
|
|
17884
|
+
serial(() => stop(shareId, "expired")).catch((error) => log.error("share.stop_failed", {
|
|
17885
|
+
shareId,
|
|
17886
|
+
error
|
|
17887
|
+
}));
|
|
17888
|
+
}, delay);
|
|
17889
|
+
timer.unref?.();
|
|
17890
|
+
timers.set(shareId, timer);
|
|
17891
|
+
};
|
|
17892
|
+
/**
|
|
17893
|
+
* Ends a share once: its link is revoked (unless it expired or was revoked already), the
|
|
17894
|
+
* ledger records why, and its faces' tunnels stop when no other share uses them.
|
|
17895
|
+
*/
|
|
17896
|
+
const stop = async (shareId, reason) => {
|
|
17897
|
+
const found = row(shareId);
|
|
17898
|
+
if (!found || found.stopped_at !== null) return void 0;
|
|
17899
|
+
const at = options.now();
|
|
17900
|
+
ledger.write((db) => {
|
|
17901
|
+
db.run("UPDATE share SET stopped_at = ?, stop_reason = ? WHERE id = ?", iso(at), reason, shareId);
|
|
17902
|
+
if (reason !== "expired" && reason !== "revoked") capabilities.revoke(capabilities.current(found.token_id), db);
|
|
17903
|
+
appendEvent(db, {
|
|
17904
|
+
artifactId: found.artifact_id,
|
|
17905
|
+
type: "share.stopped",
|
|
17906
|
+
payload: {
|
|
17907
|
+
shareId,
|
|
17908
|
+
via: found.via,
|
|
17909
|
+
hostname: found.hostname,
|
|
17910
|
+
reason
|
|
17911
|
+
}
|
|
17912
|
+
});
|
|
17913
|
+
});
|
|
17914
|
+
const timer = timers.get(shareId);
|
|
17915
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
17916
|
+
timers.delete(shareId);
|
|
17917
|
+
const plan = JSON.parse(found.plan_json);
|
|
17918
|
+
for (const face of plan.faces) await release(face.key, shareId);
|
|
17919
|
+
log.info("share.stopped", {
|
|
17920
|
+
shareId,
|
|
17921
|
+
via: found.via,
|
|
17922
|
+
reason
|
|
17923
|
+
});
|
|
17924
|
+
return toShare(row(shareId));
|
|
17925
|
+
};
|
|
17926
|
+
/** Ends shares whose link expired or was revoked since (`view/revoke` of a share's link). */
|
|
17927
|
+
const sweep = async () => {
|
|
17928
|
+
for (const found of activeRows()) {
|
|
17929
|
+
if (capabilities.grant(capabilities.current(found.token_id))?.live) continue;
|
|
17930
|
+
const expired = found.expires_at !== null && Date.parse(found.expires_at) <= options.now();
|
|
17931
|
+
await serial(() => stop(found.id, expired ? "expired" : "revoked"));
|
|
17932
|
+
}
|
|
17933
|
+
};
|
|
17934
|
+
const sweeper = setInterval(() => {
|
|
17935
|
+
sweep().catch((error) => log.error("share.sweep_failed", { error }));
|
|
17936
|
+
}, options.sweepMs ?? SWEEP_MS);
|
|
17937
|
+
sweeper.unref?.();
|
|
17938
|
+
const restore = async (found) => {
|
|
17939
|
+
const plan = JSON.parse(found.plan_json);
|
|
17940
|
+
let last;
|
|
17941
|
+
for (const delay of RECOVERY_DELAYS_MS) {
|
|
17942
|
+
if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay));
|
|
17943
|
+
if (closed) return;
|
|
17944
|
+
try {
|
|
17945
|
+
if (!await serial(async () => {
|
|
17946
|
+
const current = row(found.id);
|
|
17947
|
+
if (closed || !current || current.stopped_at !== null) return false;
|
|
17948
|
+
await setUp(found.id, found.artifact_id, found.via, plan);
|
|
17949
|
+
return true;
|
|
17950
|
+
})) return;
|
|
17951
|
+
schedule(found.id, found.expires_at ?? void 0);
|
|
17952
|
+
log.info("share.restored", {
|
|
17953
|
+
shareId: found.id,
|
|
17954
|
+
via: found.via
|
|
17955
|
+
});
|
|
17956
|
+
return;
|
|
17957
|
+
} catch (error) {
|
|
17958
|
+
last = error;
|
|
17959
|
+
log.warn("share.restore_failed", {
|
|
17960
|
+
shareId: found.id,
|
|
17961
|
+
error: error.message
|
|
17962
|
+
});
|
|
17963
|
+
}
|
|
17964
|
+
}
|
|
17965
|
+
log.warn("share.restore_gave_up", {
|
|
17966
|
+
shareId: found.id,
|
|
17967
|
+
error: last instanceof Error ? last.message : String(last)
|
|
17968
|
+
});
|
|
17969
|
+
await serial(() => stop(found.id, "tunnel"));
|
|
16002
17970
|
};
|
|
16003
17971
|
return {
|
|
16004
|
-
|
|
16005
|
-
|
|
16006
|
-
|
|
17972
|
+
methods: () => [
|
|
17973
|
+
handler(shareStartMethod, (params) => {
|
|
17974
|
+
const key = requestKey("share/start", params);
|
|
17975
|
+
const run = () => serial(() => start(params));
|
|
17976
|
+
return key === void 0 ? run() : inflight.run(key, run);
|
|
17977
|
+
}),
|
|
17978
|
+
handler(shareStopMethod, (params) => serial(async () => {
|
|
17979
|
+
if (params.shareId === void 0 === (params.artifact === void 0)) throw new RpcError(createDiagnostic("MOSTRA_HOST_INVALID_PARAMS", { message: "share/stop names either `shareId` or `artifact`, not both or neither." }), -32602);
|
|
17980
|
+
let ids;
|
|
17981
|
+
if (params.shareId !== void 0) {
|
|
17982
|
+
if (!row(params.shareId)) throw new RpcError(createDiagnostic("MOSTRA_SHARE_NOT_FOUND", { message: `No share ${params.shareId} exists in this home.` }));
|
|
17983
|
+
ids = [params.shareId];
|
|
17984
|
+
} else {
|
|
17985
|
+
const artifactId = options.artifacts.get(params.artifact).id;
|
|
17986
|
+
ids = activeRows().filter((found) => found.artifact_id === artifactId).map((found) => found.id);
|
|
17987
|
+
}
|
|
17988
|
+
const stopped = [];
|
|
17989
|
+
for (const id of ids) {
|
|
17990
|
+
const ended = await stop(id, "stopped");
|
|
17991
|
+
if (ended) stopped.push(ended);
|
|
17992
|
+
}
|
|
17993
|
+
return { stopped };
|
|
17994
|
+
})),
|
|
17995
|
+
handler(shareListMethod, (params) => {
|
|
17996
|
+
const artifactId = params.artifact === void 0 ? void 0 : options.artifacts.get(params.artifact).id;
|
|
17997
|
+
return { shares: ledger.read((db) => db.all(params.all === true ? "SELECT * FROM share ORDER BY stopped_at IS NOT NULL, started_at DESC" : "SELECT * FROM share WHERE stopped_at IS NULL ORDER BY started_at DESC")).filter((found) => artifactId === void 0 || found.artifact_id === artifactId).map(toShare) };
|
|
17998
|
+
})
|
|
17999
|
+
],
|
|
18000
|
+
count: () => ledger.read((db) => db.get("SELECT COUNT(*) AS count FROM share WHERE stopped_at IS NULL")?.count ?? 0),
|
|
18001
|
+
active: () => activeRows().map((found) => {
|
|
18002
|
+
const { url: _url, ...rest } = toShare(found);
|
|
18003
|
+
return rest;
|
|
18004
|
+
}),
|
|
18005
|
+
async recover() {
|
|
18006
|
+
const pending = [];
|
|
18007
|
+
for (const found of activeRows()) {
|
|
18008
|
+
const grant = capabilities.grant(capabilities.current(found.token_id));
|
|
18009
|
+
const expired = found.expires_at !== null && Date.parse(found.expires_at) <= options.now();
|
|
18010
|
+
if (expired || !grant?.live) await serial(() => stop(found.id, expired ? "expired" : "revoked"));
|
|
18011
|
+
else if (found.via === "cloudflare") await serial(() => stop(found.id, "restart"));
|
|
18012
|
+
else pending.push(restore(found));
|
|
18013
|
+
}
|
|
18014
|
+
await Promise.all(pending);
|
|
18015
|
+
},
|
|
18016
|
+
async close() {
|
|
18017
|
+
closed = true;
|
|
18018
|
+
clearInterval(sweeper);
|
|
18019
|
+
for (const timer of timers.values()) clearTimeout(timer);
|
|
18020
|
+
timers.clear();
|
|
18021
|
+
const running = [...exposures.values()];
|
|
18022
|
+
exposures.clear();
|
|
18023
|
+
await Promise.all(running.map((exposure) => exposure.tunnel.stop()));
|
|
18024
|
+
}
|
|
16007
18025
|
};
|
|
16008
18026
|
}
|
|
18027
|
+
/** The variables that name the tools outright, passed to the lookup from the instance's own. */
|
|
18028
|
+
function pick(env) {
|
|
18029
|
+
const out = {};
|
|
18030
|
+
if (env["MOSTRA_TEST_TUNNELS"]) {
|
|
18031
|
+
for (const [name, value] of Object.entries(env)) if ((name === "MOSTRA_TEST_TUNNELS" || name.startsWith("MOSTRA_FAKE_")) && value !== void 0) out[name] = value;
|
|
18032
|
+
}
|
|
18033
|
+
for (const name of [
|
|
18034
|
+
"MOSTRA_TAILSCALE",
|
|
18035
|
+
"MOSTRA_CLOUDFLARED",
|
|
18036
|
+
"PATH",
|
|
18037
|
+
"Path",
|
|
18038
|
+
"ProgramFiles",
|
|
18039
|
+
"ProgramFiles(x86)"
|
|
18040
|
+
]) {
|
|
18041
|
+
const value = env[name];
|
|
18042
|
+
if (value !== void 0) out[name] = value;
|
|
18043
|
+
}
|
|
18044
|
+
return out;
|
|
18045
|
+
}
|
|
18046
|
+
/** The directory of a home's share files (the quick tunnel's empty configuration). */
|
|
18047
|
+
function shareCacheDir(home) {
|
|
18048
|
+
return join(home, "cache", "share");
|
|
18049
|
+
}
|
|
16009
18050
|
//#endregion
|
|
16010
18051
|
//#region src/instance/index.ts
|
|
16011
18052
|
/**
|
|
@@ -16047,8 +18088,11 @@ const SUPPORTED_PORTS = [
|
|
|
16047
18088
|
"submissions",
|
|
16048
18089
|
"drafts",
|
|
16049
18090
|
"trustedControls",
|
|
16050
|
-
"secrets"
|
|
18091
|
+
"secrets",
|
|
18092
|
+
"addressing"
|
|
16051
18093
|
];
|
|
18094
|
+
/** How long a host's `addressing` port has to answer: a page or a minted link waits (D158). */
|
|
18095
|
+
const ADDRESSING_TIMEOUT_MS = 5e3;
|
|
16052
18096
|
/**
|
|
16053
18097
|
* Starts an instance for a home (RT-06): the platform gate, then the home's lock, migrations,
|
|
16054
18098
|
* reaping, the socket and `instance.json`. A daemon starter that finds the home owned attaches
|
|
@@ -16239,7 +18283,8 @@ async function assemble(home, options) {
|
|
|
16239
18283
|
log,
|
|
16240
18284
|
key: capabilityKey(home.path, log),
|
|
16241
18285
|
now: () => Date.now() + clockOffset,
|
|
16242
|
-
shellOrigin: () => gateway.shellOrigin()
|
|
18286
|
+
shellOrigin: () => gateway.shellOrigin(),
|
|
18287
|
+
servesShell: (origin) => gateway.servesShell(origin)
|
|
16243
18288
|
});
|
|
16244
18289
|
const interaction = createInteraction({
|
|
16245
18290
|
ledger: home.ledger,
|
|
@@ -16398,6 +18443,7 @@ async function assemble(home, options) {
|
|
|
16398
18443
|
if (shellDir === void 0) log.warn("gateway.shell_missing", { code: "MOSTRA_ENV_SHELL_MISSING" });
|
|
16399
18444
|
const traceRequests = Boolean(environment["MOSTRA_TEST_REQUEST_LOG"]);
|
|
16400
18445
|
if (traceRequests) log.warn("instance.test_request_log", {});
|
|
18446
|
+
if (environment["MOSTRA_TEST_TUNNELS"]) log.warn("instance.test_tunnels", {});
|
|
16401
18447
|
const gateway = createGateway({
|
|
16402
18448
|
ledger: home.ledger,
|
|
16403
18449
|
log,
|
|
@@ -16434,6 +18480,36 @@ async function assemble(home, options) {
|
|
|
16434
18480
|
registrant: () => server.registrants("identity").at(-1),
|
|
16435
18481
|
call: (session, params) => server.callSession(session, portIdentityResolveMethod.method, params, IDENTITY_TIMEOUT_MS)
|
|
16436
18482
|
}),
|
|
18483
|
+
externalBase: {
|
|
18484
|
+
registered: () => server.registrants("addressing").length > 0,
|
|
18485
|
+
ask: async (input) => {
|
|
18486
|
+
const registrant = server.registrants("addressing").at(-1);
|
|
18487
|
+
if (!registrant) return { kind: "away" };
|
|
18488
|
+
try {
|
|
18489
|
+
const answer = await server.callSession(registrant.session, portAddressingExternalBaseMethod.method, input, ADDRESSING_TIMEOUT_MS);
|
|
18490
|
+
const parsed = portAddressingExternalBaseMethod.result.safeParse(answer);
|
|
18491
|
+
if (!parsed.success) {
|
|
18492
|
+
log.warn("gateway.addressing_invalid", {
|
|
18493
|
+
owner: registrant.owner,
|
|
18494
|
+
artifactId: input.artifactId
|
|
18495
|
+
});
|
|
18496
|
+
return { kind: "failed" };
|
|
18497
|
+
}
|
|
18498
|
+
return parsed.data === null ? { kind: "none" } : {
|
|
18499
|
+
kind: "base",
|
|
18500
|
+
base: parsed.data,
|
|
18501
|
+
owner: registrant.owner
|
|
18502
|
+
};
|
|
18503
|
+
} catch (error) {
|
|
18504
|
+
log.warn("gateway.addressing_failed", {
|
|
18505
|
+
owner: registrant.owner,
|
|
18506
|
+
artifactId: input.artifactId,
|
|
18507
|
+
error: error.message
|
|
18508
|
+
});
|
|
18509
|
+
return { kind: "failed" };
|
|
18510
|
+
}
|
|
18511
|
+
}
|
|
18512
|
+
},
|
|
16437
18513
|
activated: (event) => {
|
|
16438
18514
|
for (const registrant of server.registrants("trustedControls")) {
|
|
16439
18515
|
const params = {
|
|
@@ -16450,6 +18526,21 @@ async function assemble(home, options) {
|
|
|
16450
18526
|
}
|
|
16451
18527
|
}
|
|
16452
18528
|
});
|
|
18529
|
+
const shares = createShares({
|
|
18530
|
+
ledger: home.ledger,
|
|
18531
|
+
log,
|
|
18532
|
+
gateway,
|
|
18533
|
+
capabilities,
|
|
18534
|
+
interaction,
|
|
18535
|
+
artifacts: { get: (ref) => registry.get(canonicalRef(ref)) },
|
|
18536
|
+
processes: manager,
|
|
18537
|
+
environment,
|
|
18538
|
+
toolEnvironment: artifactEnvironment(environment),
|
|
18539
|
+
cacheDir: shareCacheDir(home.path),
|
|
18540
|
+
now: () => Date.now() + clockOffset,
|
|
18541
|
+
...environment["MOSTRA_TEST_SHARE_PROBE_MS"] !== void 0 ? { probeMs: Number(environment["MOSTRA_TEST_SHARE_PROBE_MS"]) } : {},
|
|
18542
|
+
...environment["MOSTRA_TEST_SHARE_SWEEP_MS"] !== void 0 ? { sweepMs: Number(environment["MOSTRA_TEST_SHARE_SWEEP_MS"]) } : {}
|
|
18543
|
+
});
|
|
16453
18544
|
let gatewayStarted = false;
|
|
16454
18545
|
let idle;
|
|
16455
18546
|
const info = {
|
|
@@ -16530,6 +18621,7 @@ async function assemble(home, options) {
|
|
|
16530
18621
|
}),
|
|
16531
18622
|
...dev.methods(),
|
|
16532
18623
|
...gateway.methods(),
|
|
18624
|
+
...shares.methods(),
|
|
16533
18625
|
...interaction.methods(),
|
|
16534
18626
|
...secretMethods(secrets, (ref) => registry.get(canonicalRef(ref)).id),
|
|
16535
18627
|
...gcMethods(createGc({
|
|
@@ -16556,8 +18648,10 @@ async function assemble(home, options) {
|
|
|
16556
18648
|
artifacts: [...gateway.artifactOrigins()].map(([artifactId, origin]) => ({
|
|
16557
18649
|
artifactId,
|
|
16558
18650
|
origin
|
|
16559
|
-
}))
|
|
18651
|
+
})),
|
|
18652
|
+
faces: [...gateway.faces()]
|
|
16560
18653
|
} : void 0,
|
|
18654
|
+
shares: () => shares.active(),
|
|
16561
18655
|
deliveries: () => interaction.deliveries(),
|
|
16562
18656
|
workers: () => pool.status(),
|
|
16563
18657
|
idleExitAt: () => idle?.exitAt(),
|
|
@@ -16593,6 +18687,7 @@ async function assemble(home, options) {
|
|
|
16593
18687
|
interaction.stop();
|
|
16594
18688
|
await server.close();
|
|
16595
18689
|
await dev.stopAll();
|
|
18690
|
+
await shares.close();
|
|
16596
18691
|
await gateway.close();
|
|
16597
18692
|
await pool.stopAll();
|
|
16598
18693
|
await runner?.close();
|
|
@@ -16650,6 +18745,7 @@ async function assemble(home, options) {
|
|
|
16650
18745
|
});
|
|
16651
18746
|
interaction.start();
|
|
16652
18747
|
live.start();
|
|
18748
|
+
shares.recover().catch((error) => log.error("share.recover_failed", { error }));
|
|
16653
18749
|
home.publish(options.mode, server.socketPath ?? home.socketPath);
|
|
16654
18750
|
if (options.mode === "host" && markHostConfigured(home.path, "mostra-runtime host")) log.info("home.host_configured", { client: "mostra-runtime host" });
|
|
16655
18751
|
} catch (error) {
|
|
@@ -16675,6 +18771,7 @@ async function assemble(home, options) {
|
|
|
16675
18771
|
producers: live.activity(),
|
|
16676
18772
|
subscriptions: interaction.subscriptionCount(),
|
|
16677
18773
|
devSessions: dev.count(),
|
|
18774
|
+
shares: shares.count(),
|
|
16678
18775
|
loginService: hasLoginService(home.path, environment) ? 1 : 0
|
|
16679
18776
|
}),
|
|
16680
18777
|
onIdle: () => {
|
|
@@ -16747,4 +18844,4 @@ function sourceDirectory(path) {
|
|
|
16747
18844
|
//#endregion
|
|
16748
18845
|
export { uninstallService as a, serviceStatus as i, startInstance as n, checkPlatform as o, installService as r, resolveHomePath as s, runtimeVersion as t };
|
|
16749
18846
|
|
|
16750
|
-
//# sourceMappingURL=instance-
|
|
18847
|
+
//# sourceMappingURL=instance-CYPYPCIb.js.map
|