@niscorp/moss 0.3.2 → 0.4.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/CHANGELOG.md +155 -0
- package/DESIGN.md +84 -19
- package/DOCS.md +170 -35
- package/README.md +2 -2
- package/dist/{chunk-J72N3EMJ.js → chunk-4T6KAXBP.js} +45 -27
- package/dist/chunk-4T6KAXBP.js.map +1 -0
- package/dist/{chunk-ZOEUEMDX.js → chunk-HOZID4EM.js} +131 -16
- package/dist/chunk-HOZID4EM.js.map +1 -0
- package/dist/{chunk-ZP3C53AC.js → chunk-R3QMJ3JF.js} +744 -661
- package/dist/chunk-R3QMJ3JF.js.map +1 -0
- package/dist/chunk-U3UR5AOQ.js +103 -0
- package/dist/chunk-U3UR5AOQ.js.map +1 -0
- package/dist/client/node.cjs +1 -1
- package/dist/client/node.cjs.map +1 -1
- package/dist/client/node.js +1 -1
- package/dist/client/node.js.map +1 -1
- package/dist/client.cjs +60 -26
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +6 -1
- package/dist/client.d.ts +6 -1
- package/dist/client.js +2 -2
- package/dist/{document-D9khv9jI.d.cts → document-DhWxieUc.d.cts} +22 -3
- package/dist/{document-D9khv9jI.d.ts → document-DhWxieUc.d.ts} +22 -3
- package/dist/index.cjs +786 -583
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +19 -3
- package/dist/index.d.ts +19 -3
- package/dist/index.js +2 -2
- package/dist/node.cjs +379 -230
- package/dist/node.cjs.map +1 -1
- package/dist/node.d.cts +2 -1
- package/dist/node.d.ts +2 -1
- package/dist/node.js +3 -3
- package/dist/terminal/index.cjs +60 -26
- package/dist/terminal/index.cjs.map +1 -1
- package/dist/terminal/index.js +2 -2
- package/dist/vite.cjs +103 -28
- package/dist/vite.cjs.map +1 -1
- package/dist/vite.d.cts +1 -1
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +14 -9
- package/dist/vite.js.map +1 -1
- package/package.json +12 -12
- package/dist/chunk-J72N3EMJ.js.map +0 -1
- package/dist/chunk-SUVDISEG.js +0 -64
- package/dist/chunk-SUVDISEG.js.map +0 -1
- package/dist/chunk-ZOEUEMDX.js.map +0 -1
- package/dist/chunk-ZP3C53AC.js.map +0 -1
package/README.md
CHANGED
|
@@ -83,7 +83,7 @@ server.get('*', async (c) => {
|
|
|
83
83
|
```typescript
|
|
84
84
|
// the browser's entry
|
|
85
85
|
const drawn = readDocumentSnapshot();
|
|
86
|
-
createWire({ env: browserEnv(
|
|
86
|
+
createWire({ env: browserEnv(), ...(drawn ? { initial: drawn } : {}) });
|
|
87
87
|
```
|
|
88
88
|
|
|
89
89
|
Who may keep the page follows from who asked: drawn for nobody it is the same
|
|
@@ -158,7 +158,7 @@ never in moss core.
|
|
|
158
158
|
|
|
159
159
|
- **`/catalog`** — the application, resolved for you (granted action ids + a version token).
|
|
160
160
|
- **`/api/vex`, `/api/<resource>/vex`** — reads and writes, locked (replay-only), scoped per principal. The model never writes SQL; the policy it can't see enforces access.
|
|
161
|
-
- **the socket** — the authority channel: the served frame and per-canvas `RenderNode` trees down, `NovaEvent`s up. Session lifecycle (sign-in grant, sign-out revoke) rides it. Two optional reductions sit under it, both invisible to an app: `permessage-deflate` (on by default) and frame deltas (`shellFrameDelta`, off) — a changed canvas sent as a checksummed delta against the frame the terminal already holds, 1–4% of the frame on an in-place change. See [DOCS.md § Wire size](DOCS.md#wire-size).
|
|
161
|
+
- **the socket** — the authority channel: the served frame and per-canvas `RenderNode` trees down, `NovaEvent`s up (a message a terminal sends is at most 256 KB). Session lifecycle (sign-in grant, sign-out revoke) rides it. Two optional reductions sit under it, both invisible to an app: `permessage-deflate` (on by default) and frame deltas (`shellFrameDelta`, off) — a changed canvas sent as a checksummed delta against the frame the terminal already holds, 1–4% of the frame on an in-place change. See [DOCS.md § Wire size](DOCS.md#wire-size).
|
|
162
162
|
|
|
163
163
|
## Tables and documents, versioned
|
|
164
164
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { applyDelta, frameHash, PROTOCOL_MIN,
|
|
1
|
+
import { heldCookieName, PROTOCOL, offerToken, applyDelta, frameHash, PROTOCOL_MIN, CLOSE_PROTOCOL_MISMATCH, CLOSE_SIGNED_OUT, CLOSE_INVALID_TOKEN } from './chunk-HOZID4EM.js';
|
|
2
2
|
|
|
3
3
|
// src/client/index.ts
|
|
4
4
|
var SNAPSHOT_ELEMENT_ID = "nisc-snapshot";
|
|
@@ -25,21 +25,11 @@ var readDocumentSnapshot = (doc = document) => {
|
|
|
25
25
|
var EMPTY = { frame: [], trees: /* @__PURE__ */ new Map() };
|
|
26
26
|
var browserEnv = (config = {}) => {
|
|
27
27
|
const tokenKey = config.tokenKey ?? "nisc.token";
|
|
28
|
-
const mirror = (token) => {
|
|
29
|
-
if (config.cookie !== true) return;
|
|
30
|
-
try {
|
|
31
|
-
const secure = window.location.protocol === "https:" ? "; Secure" : "";
|
|
32
|
-
document.cookie = token === null ? `${encodeURIComponent(tokenKey)}=; Path=/; Max-Age=0; SameSite=Lax${secure}` : `${encodeURIComponent(tokenKey)}=${encodeURIComponent(token)}; Path=/; SameSite=Lax${secure}`;
|
|
33
|
-
} catch {
|
|
34
|
-
}
|
|
35
|
-
};
|
|
36
28
|
return {
|
|
37
29
|
tokens: {
|
|
38
30
|
load: () => {
|
|
39
31
|
try {
|
|
40
|
-
|
|
41
|
-
mirror(token);
|
|
42
|
-
return token;
|
|
32
|
+
return window.localStorage.getItem(tokenKey);
|
|
43
33
|
} catch {
|
|
44
34
|
return null;
|
|
45
35
|
}
|
|
@@ -49,17 +39,27 @@ var browserEnv = (config = {}) => {
|
|
|
49
39
|
window.localStorage.setItem(tokenKey, token);
|
|
50
40
|
} catch {
|
|
51
41
|
}
|
|
52
|
-
mirror(token);
|
|
53
42
|
},
|
|
54
43
|
clear: () => {
|
|
55
44
|
try {
|
|
56
45
|
window.localStorage.removeItem(tokenKey);
|
|
57
46
|
} catch {
|
|
58
47
|
}
|
|
59
|
-
|
|
60
|
-
|
|
48
|
+
try {
|
|
49
|
+
document.cookie = `${encodeURIComponent(tokenKey)}=; Path=/; Max-Age=0; SameSite=Lax${window.location.protocol === "https:" ? "; Secure" : ""}`;
|
|
50
|
+
} catch {
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
held: () => {
|
|
54
|
+
try {
|
|
55
|
+
return document.cookie.split("; ").includes(`${heldCookieName(tokenKey, window.location.port)}=1`);
|
|
56
|
+
} catch {
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
},
|
|
60
|
+
...config.tokenKey !== void 0 ? { key: tokenKey } : {}
|
|
61
61
|
},
|
|
62
|
-
socket: (url) => new WebSocket(url),
|
|
62
|
+
socket: ({ url, offered }) => new WebSocket(url, offered),
|
|
63
63
|
defaultUrl: () => {
|
|
64
64
|
const scheme = window.location.protocol === "https:" ? "wss" : "ws";
|
|
65
65
|
return `${scheme}://${window.location.host}/socket`;
|
|
@@ -69,12 +69,15 @@ var browserEnv = (config = {}) => {
|
|
|
69
69
|
var createWire = (config = {}) => {
|
|
70
70
|
const env = config.env ?? browserEnv();
|
|
71
71
|
let token = env.tokens.load();
|
|
72
|
-
const initial = config.initial !== void 0 && config.initial.principal === (token !== null) ? config.initial : void 0;
|
|
72
|
+
const initial = config.initial !== void 0 && config.initial.principal === (token !== null || env.tokens.held?.() === true) ? config.initial : void 0;
|
|
73
73
|
let snapshot = initial === void 0 ? EMPTY : { frame: initial.frame, trees: new Map(Object.entries(initial.trees)) };
|
|
74
74
|
let seed = initial?.seed;
|
|
75
75
|
const path = config.path ?? config.initial?.path;
|
|
76
76
|
let status = "connecting";
|
|
77
77
|
let incompatible = false;
|
|
78
|
+
let leaving = false;
|
|
79
|
+
let sealed = null;
|
|
80
|
+
let unsealed = false;
|
|
78
81
|
let socket = null;
|
|
79
82
|
let retry;
|
|
80
83
|
let attempts = 0;
|
|
@@ -99,14 +102,15 @@ var createWire = (config = {}) => {
|
|
|
99
102
|
if (disposed) return;
|
|
100
103
|
setStatus("connecting");
|
|
101
104
|
bases.clear();
|
|
102
|
-
const params = [];
|
|
103
|
-
if (
|
|
104
|
-
params.push(
|
|
105
|
+
const params = [`protocol=${PROTOCOL}`];
|
|
106
|
+
if (env.tokens.key !== void 0) params.push(`key=${encodeURIComponent(env.tokens.key)}`);
|
|
107
|
+
if (leaving) params.push("leave=1");
|
|
108
|
+
if (env.tokens.held !== void 0 && !unsealed) params.push("sealed=1");
|
|
105
109
|
if (config.delta === true) params.push("delta=1");
|
|
106
110
|
if (seed !== void 0) params.push(`seed=${encodeURIComponent(seed)}`);
|
|
107
111
|
seed = void 0;
|
|
108
112
|
if (path !== void 0) params.push(`path=${encodeURIComponent(path)}`);
|
|
109
|
-
const ws = env.socket(`${url()}
|
|
113
|
+
const ws = env.socket({ url: `${url()}?${params.join("&")}`, offered: offerToken(token, sealed) });
|
|
110
114
|
socket = ws;
|
|
111
115
|
ws.onopen = () => {
|
|
112
116
|
attempts = 0;
|
|
@@ -142,13 +146,25 @@ var createWire = (config = {}) => {
|
|
|
142
146
|
publishSnapshot({ ...snapshot, frame: data.tree });
|
|
143
147
|
} else if (data.type === "session" && typeof data.token === "string") {
|
|
144
148
|
become(data.token);
|
|
149
|
+
} else if (data.type === "session" && typeof data.sealed === "string") {
|
|
150
|
+
become(null, data.sealed);
|
|
145
151
|
} else if (data.type === "error") {
|
|
152
|
+
if (data.code === "seal_not_kept") unsealed = true;
|
|
146
153
|
console.warn(`[moss/wire] server error${data.code !== void 0 ? ` (${data.code})` : ""}: ${data.message ?? ""}`);
|
|
147
154
|
} else if (data.type === "hello" && (data.protocol ?? 1) < PROTOCOL_MIN) {
|
|
148
155
|
console.error(`[moss/wire] the server speaks protocol ${data.protocol ?? 1}; this terminal needs ${PROTOCOL_MIN}\u2013${PROTOCOL}. The server has not been updated yet.`);
|
|
149
156
|
incompatible = true;
|
|
150
157
|
ws.close();
|
|
151
|
-
} else if (data.type
|
|
158
|
+
} else if (data.type === "hello") {
|
|
159
|
+
leaving = false;
|
|
160
|
+
sealed = null;
|
|
161
|
+
if (token !== null && env.tokens.held !== void 0) {
|
|
162
|
+
if (env.tokens.held()) {
|
|
163
|
+
env.tokens.clear();
|
|
164
|
+
token = null;
|
|
165
|
+
} else env.tokens.save(token);
|
|
166
|
+
}
|
|
167
|
+
} else if (data.type !== "catalog") {
|
|
152
168
|
console.warn(`[moss/wire] unhandled server message: ${data.type}`);
|
|
153
169
|
}
|
|
154
170
|
};
|
|
@@ -160,6 +176,7 @@ var createWire = (config = {}) => {
|
|
|
160
176
|
}
|
|
161
177
|
setStatus("closed");
|
|
162
178
|
if (e.code === CLOSE_SIGNED_OUT || e.code === CLOSE_INVALID_TOKEN) {
|
|
179
|
+
leaving = e.code === CLOSE_SIGNED_OUT;
|
|
163
180
|
become(null);
|
|
164
181
|
return;
|
|
165
182
|
}
|
|
@@ -173,9 +190,10 @@ var createWire = (config = {}) => {
|
|
|
173
190
|
const delay = ceiling / 2 + Math.random() * (ceiling / 2);
|
|
174
191
|
retry = setTimeout(connect, delay);
|
|
175
192
|
};
|
|
176
|
-
const become = (next) => {
|
|
177
|
-
|
|
178
|
-
else env.tokens.
|
|
193
|
+
const become = (next, handedSealed = null) => {
|
|
194
|
+
sealed = handedSealed;
|
|
195
|
+
if (handedSealed !== null) ; else if (next === null) env.tokens.clear();
|
|
196
|
+
else if (env.tokens.held === void 0) env.tokens.save(next);
|
|
179
197
|
token = next;
|
|
180
198
|
clearTimeout(retry);
|
|
181
199
|
attempts = 0;
|
|
@@ -234,5 +252,5 @@ var createWire = (config = {}) => {
|
|
|
234
252
|
};
|
|
235
253
|
|
|
236
254
|
export { SNAPSHOT_ELEMENT_ID, browserEnv, createWire, readDocumentSnapshot };
|
|
237
|
-
//# sourceMappingURL=chunk-
|
|
238
|
-
//# sourceMappingURL=chunk-
|
|
255
|
+
//# sourceMappingURL=chunk-4T6KAXBP.js.map
|
|
256
|
+
//# sourceMappingURL=chunk-4T6KAXBP.js.map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AAAA,IACA,SAAS,MAAM;AACb,MAAA,QAAA,GAAW,IAAA;AACX,MAAA,MAAA,GAAS,QAAA;AACT,MAAA,YAAA,CAAa,KAAK,CAAA;AAClB,MAAA,MAAA,EAAQ,KAAA,EAAM;AAAA,IAChB;AAAA,GACF;AACF","file":"chunk-4T6KAXBP.js","sourcesContent":["import type { NovaEvent, RenderNode } from '@niscorp/nova';\nimport { CLOSE_INVALID_TOKEN, CLOSE_PROTOCOL_MISMATCH, CLOSE_SIGNED_OUT, PROTOCOL, PROTOCOL_MIN, offerToken } from '../socket';\nimport { applyDelta, frameHash } from '../delta';\nimport type { DeltaOp } from '../delta';\nimport { heldCookieName } from '../session-cookie';\n\n// ═══════════════════════════════════════════════════════════════\n// The wire — moss's protocol client, the other end of ../socket. Plain\n// code: a token slot, a websocket with reconnect, and session lifecycle —\n// a `session` message (login redeemed server-side) stores the token and\n// reconnects authenticated; a 4403 close clears it and reconnects\n// anonymous (the lock screen is the anonymous principal's application,\n// served like everything else). Rendering the snapshot is the app's\n// (framework's) business; nothing framework-shaped lives here.\n//\n// The wire never reaches for globals: everything host-shaped — where the\n// token lives, how a socket is constructed, what url \"here\" means — comes\n// in as a `WireEnv`. `browserEnv` (the default) is localStorage + location;\n// `./node` ships `nodeEnv` (a token file, an explicit url). The socket API\n// itself is WHATWG-standard in every host (browser, Node ≥22, Bun), so an\n// env only constructs it.\n// ═══════════════════════════════════════════════════════════════\n\n// Where the session token lives between connects.\nexport type WireTokenStore = {\n load: () => string | null;\n save: (token: string) => void;\n clear: () => void;\n // A host whose BROWSER may keep the session itself, in a cookie the page\n // cannot read (../session-cookie.ts): whether it does, right now. Asked\n // after an upgrade is answered — if it does, the wire lets go of the token\n // it offered and nothing is stored; if not, the token is stored as ever. A\n // host without this (a process) always keeps its own.\n held?: () => boolean;\n // Which of the browser's sessions this terminal is, when not the default one\n // — a seat. Named in the socket's address; it is the cookie's name.\n key?: string;\n};\n\n// The host seam: what the wire would otherwise take from globals.\nexport type WireEnv = {\n tokens: WireTokenStore;\n // Construct a socket for this url, offering these subprotocols —\n // `new WebSocket(url, offered)` in every host. What is offered is who the\n // terminal is (socket.ts): a host that drops it connects as nobody.\n socket: (upgrade: { url: string; offered: string[] }) => WebSocket;\n // the socket url when `config.url` is absent\n defaultUrl: () => string;\n};\n\nexport type WireConfig = {\n // The socket url; default: `env.defaultUrl()`.\n url?: string;\n // The host environment; default: `browserEnv()`.\n env?: WireEnv;\n // Accept canvas frames as DELTAS against the last frame received (default:\n // off). Both ends have to want it: this tells the server the terminal can\n // rebuild them, and the server sends them only if `runtime.shellFrameDelta`\n // is on and the delta is decisively smaller. Nothing else about the terminal\n // changes — the snapshot it renders is identical either way. See DOCS.md\n // § Frame deltas.\n delta?: boolean;\n // The screen the page already shows — the snapshot a server-rendered\n // document carries (`readDocumentSnapshot`). The wire starts from it instead\n // of from nothing, so the first render matches the HTML and the first frames\n // off the socket confirm it rather than paint it. Absent, or made for\n // somebody else (see `DocumentSnapshot.principal`): the wire starts empty, as\n // it always has.\n initial?: DocumentSnapshot;\n // The path this terminal is on, named on the socket so the server can tell a\n // page's terminal from the app's (a page is served a shell of its own, for\n // this connection alone). Default: the path the page's snapshot was drawn\n // for; a page that was not drawn on the server passes `location.pathname`.\n path?: string;\n};\n\n// What a server-rendered document carries beside its HTML.\nexport type DocumentSnapshot = {\n frame: RenderNode[];\n trees: Record<string, RenderNode[]>;\n // The id seed an anonymous page's shell was built under; named on the first\n // connect so the socket's shell mints the same instance ids.\n seed?: string;\n // Whether the page was rendered for a signed-in principal. A page rendered\n // for nobody is not this terminal's screen if it holds a token, and the other\n // way round — the wire then starts empty rather than from the wrong screen.\n principal: boolean;\n // The path it was drawn for.\n path?: string;\n // False when nothing on the drawn screen can still happen: the trees are the\n // whole of it, and the wire opens no socket at all (status `static`). Absent\n // is live — a page that does not say is not concluded finished.\n live?: boolean;\n};\n\n// The id of the element a document carries its snapshot in.\nexport const SNAPSHOT_ELEMENT_ID = 'nisc-snapshot';\n\n// Read the snapshot out of the page, if it has one. Never throws: a page\n// without one, or with one that does not parse, is a page that was not\n// server-rendered, and the terminal starts the way it always has.\nexport const readDocumentSnapshot = (doc: Pick<Document, 'getElementById'> = document): DocumentSnapshot | undefined => {\n try {\n const text = doc.getElementById(SNAPSHOT_ELEMENT_ID)?.textContent;\n if (text === undefined || text === null || text === '') return undefined;\n const parsed: unknown = JSON.parse(text);\n if (parsed === null || typeof parsed !== 'object') return undefined;\n const { frame, trees, seed, principal, path, live } = parsed as Record<string, unknown>;\n if (!Array.isArray(frame) || trees === null || typeof trees !== 'object' || typeof principal !== 'boolean') return undefined;\n return {\n frame: frame as RenderNode[],\n trees: trees as Record<string, RenderNode[]>,\n principal,\n ...(typeof seed === 'string' ? { seed } : {}),\n ...(typeof path === 'string' ? { path } : {}),\n ...(typeof live === 'boolean' ? { live } : {}),\n };\n } catch {\n return undefined;\n }\n};\n\nexport type WireSnapshot = {\n // the frame: the canvas ARRANGEMENT — a served layout whose CanvasSlot\n // markers resolve against `trees`\n frame: RenderNode[];\n // the current tree per canvas id\n trees: ReadonlyMap<string, RenderNode[]>;\n};\n\n// The socket's health, as a renderer needs it: `connecting` (a connect is in\n// flight or scheduled), `open`, `closed` (lost; a retry will flip it back to\n// connecting). Status changes notify subscribers like snapshot changes do —\n// a terminal that renders nothing on a dead socket is indistinguishable from\n// a working terminal rendering an empty app, so the state must be readable.\n// `incompatible`: this terminal and the server speak protocols the other\n// cannot (see PROTOCOL in ../socket). Terminal state — the wire stops retrying,\n// because every retry would speak the same protocol again.\n// `static`: the page was drawn on the server and nothing on it can still\n// happen, so no socket was opened. Not a fault and not a wait — `reset` (or a\n// token arriving) connects after all.\nexport type WireStatus = 'connecting' | 'open' | 'closed' | 'incompatible' | 'static';\n\nexport type Wire = {\n subscribe: (listener: () => void) => () => void;\n snapshot: () => WireSnapshot;\n status: () => WireStatus;\n // an event from inside a canvas, tagged with the canvas it came from\n dispatch: (canvasId: string, event: NovaEvent) => void;\n publish: (channel: string, payload?: unknown) => void;\n // Ask the server to throw this session's shell away and serve a fresh one —\n // the escape from a wedged shell, and the only one that can work. The shell\n // is SERVER state keyed by principal: dropping the token here would just\n // hand us a throwaway anonymous shell, and signing back in would reattach\n // to the same wreck. On a dead socket this reconnects instead, which is the\n // same recovery one layer down.\n reset: () => void;\n // Undo the shell's last navigation. Fire-and-forget by design: what comes\n // back is whatever canvases moved, over the same stream every other change\n // arrives on — the terminal never holds a location to keep in step.\n back: () => void;\n // Jump to an ancestor already on a canvas's stack — one message the shell\n // executes atomically, rather than N back gestures racing each other.\n popTo: (canvas: string, instance: string) => void;\n dispose: () => void;\n};\n\ntype ClientMessage =\n | { type: 'event'; canvas: string; event: Record<string, unknown> }\n | { type: 'publish'; channel: string; payload?: unknown }\n | { type: 'resync' }\n | { type: 'reset' }\n | { type: 'back' }\n | { type: 'popTo'; canvas: string; instance: string };\n\nconst EMPTY: WireSnapshot = { frame: [], trees: new Map() };\n\n// The browser host: url derived from location, the page's WebSocket, and the\n// session wherever this page can have it kept.\n//\n// SERVED BY THE APP IT TALKS TO, the page does not keep it: the browser does,\n// in a cookie the page cannot read, which the server writes in its answer to\n// the upgrade (../session-cookie.ts). `held` is all the page sees of it. A\n// token this page is handed is offered once and let go of; nothing is stored.\n//\n// ANYWHERE ELSE — another origin, a browser that refuses cookies — the token\n// is in localStorage, as it always was. The try/catches keep a storage-less\n// context (private mode, sandboxed iframe) alive: the session then lives for\n// this page only.\n//\n// `cookie` did one thing — keep a script-readable copy of the token for the\n// server to draw the page from — and is no longer needed: the page is drawn\n// from the browser's own cookie. It is accepted and does nothing.\nexport const browserEnv = (config: { tokenKey?: string; cookie?: boolean } = {}): WireEnv => {\n const tokenKey = config.tokenKey ?? 'nisc.token';\n return {\n tokens: {\n load: () => {\n try {\n return window.localStorage.getItem(tokenKey);\n } catch {\n return null;\n }\n },\n save: (token) => {\n try {\n window.localStorage.setItem(tokenKey, token);\n } catch {\n /* storage unavailable — the session lives for this page only */\n }\n },\n clear: () => {\n try {\n window.localStorage.removeItem(tokenKey);\n } catch {\n /* nothing stored, nothing to clear */\n }\n // the copy an earlier build kept beside it, where script could read it\n try {\n document.cookie = `${encodeURIComponent(tokenKey)}=; Path=/; Max-Age=0; SameSite=Lax${window.location.protocol === 'https:' ? '; Secure' : ''}`;\n } catch {\n /* no document, or cookies refused */\n }\n },\n held: () => {\n try {\n return document.cookie.split('; ').includes(`${heldCookieName(tokenKey, window.location.port)}=1`);\n } catch {\n return false;\n }\n },\n ...(config.tokenKey !== undefined ? { key: tokenKey } : {}),\n },\n socket: ({ url, offered }) => new WebSocket(url, offered),\n defaultUrl: () => {\n const scheme = window.location.protocol === 'https:' ? 'wss' : 'ws';\n return `${scheme}://${window.location.host}/socket`;\n },\n };\n};\n\nexport const createWire = (config: WireConfig = {}): Wire => {\n const env = config.env ?? browserEnv();\n\n let token = env.tokens.load();\n // The page's own snapshot, when it was rendered for who this terminal is —\n // signed in (holding a token, or its browser a session), or neither.\n // Anything else is somebody else's screen and is not started from.\n const initial = config.initial !== undefined && config.initial.principal === (token !== null || env.tokens.held?.() === true) ? config.initial : undefined;\n let snapshot: WireSnapshot = initial === undefined ? EMPTY : { frame: initial.frame, trees: new Map(Object.entries(initial.trees)) };\n // Named on the FIRST connect only: it belongs to the page's own shell, and a\n // later connect (a retry, another principal) is not that shell.\n let seed = initial?.seed;\n const path = config.path ?? config.initial?.path;\n let status: WireStatus = 'connecting';\n // Set by a protocol mismatch in either direction; ends the reconnect loop.\n let incompatible = false;\n // Signed out, and not yet heard by the server: the next upgrade says so,\n // because what the browser holds may be a token that still resolves.\n let leaving = false;\n // A sign-in handed to this terminal SEALED: its browser keeps the session,\n // so the page is given something it can carry to the next upgrade and cannot\n // open. Offered until an upgrade is answered. `unsealed`: this browser turned\n // out not to keep the cookie that opens one, so the terminal stops asking.\n let sealed: string | null = null;\n let unsealed = false;\n let socket: WebSocket | null = null;\n let retry: ReturnType<typeof setTimeout> | undefined;\n // Consecutive failed connects — resets to 0 the moment one opens. Drives the\n // reconnect backoff so a dead server is polled ever more slowly, not every\n // second forever.\n let attempts = 0;\n let disposed = false;\n const listeners = new Set<() => void>();\n const publishSnapshot = (next: WireSnapshot): void => {\n snapshot = next;\n for (const listener of listeners) listener();\n };\n const setStatus = (next: WireStatus): void => {\n if (status === next) return;\n status = next;\n for (const listener of listeners) listener();\n };\n\n const url = (): string => config.url ?? env.defaultUrl();\n\n // Only on an OPEN socket, and never queued — the posture `back` and `popTo`\n // always had, now everybody's. A page rendered server-side is on screen\n // before the socket is, so there is a moment in which something can be\n // pressed with nothing to send it over: that press is dropped, not held. An\n // intention replayed against a screen that may have moved is worse than one\n // lost, and a browser socket that is still connecting throws on `send`.\n const send = (message: ClientMessage): void => {\n if (socket === null || status !== 'open') return;\n socket.send(JSON.stringify(message));\n };\n\n // The last `render` message TEXT per canvas — the base a delta is written\n // against, byte for byte as the server holds it. Only populated when deltas\n // are on; cleared on every connect, because attaching serves whole frames and\n // a base carried across a reconnect is a base the server never assumed.\n const bases = new Map<string, string>();\n\n const connect = (): void => {\n if (disposed) return;\n setStatus('connecting');\n bases.clear();\n // The address says nothing about who this is — it is what every proxy on\n // the way writes down. The token is offered with the socket, below.\n const params: string[] = [`protocol=${PROTOCOL}`];\n if (env.tokens.key !== undefined) params.push(`key=${encodeURIComponent(env.tokens.key)}`);\n if (leaving) params.push('leave=1');\n if (env.tokens.held !== undefined && !unsealed) params.push('sealed=1');\n if (config.delta === true) params.push('delta=1');\n if (seed !== undefined) params.push(`seed=${encodeURIComponent(seed)}`);\n seed = undefined;\n if (path !== undefined) params.push(`path=${encodeURIComponent(path)}`);\n const ws = env.socket({ url: `${url()}?${params.join('&')}`, offered: offerToken(token, sealed) });\n socket = ws;\n // A connection that opens is a healthy connection: forget the backoff.\n ws.onopen = () => {\n attempts = 0;\n setStatus('open');\n };\n ws.onmessage = (e) => {\n const text = String(e.data);\n const data = JSON.parse(text) as {\n type: string;\n canvas?: string;\n tree?: RenderNode[];\n ops?: DeltaOp[];\n hash?: number;\n protocol?: number;\n token?: string;\n sealed?: string;\n code?: string;\n message?: string;\n };\n if (data.type === 'render' && data.canvas !== undefined && data.tree !== undefined) {\n if (config.delta === true) bases.set(data.canvas, text);\n publishSnapshot({ ...snapshot, trees: new Map(snapshot.trees).set(data.canvas, data.tree) });\n } else if (data.type === 'render-delta' && data.canvas !== undefined && data.ops !== undefined && data.hash !== undefined) {\n // Rebuild, then PROVE it. Anything short of the server's own checksum\n // and we would be rendering a frame nobody authored — so every failure\n // here takes the one exit that always works: ask for whole frames.\n // Never a thrown error and never a partial apply; a terminal that goes\n // blank on a bad delta is worse than one that costs a round trip.\n const base = bases.get(data.canvas);\n let rebuilt: string | null = null;\n if (base !== undefined) {\n try {\n const candidate = applyDelta(base, data.ops);\n rebuilt = frameHash(candidate) === data.hash ? candidate : null;\n } catch {\n rebuilt = null;\n }\n }\n if (rebuilt === null) {\n console.warn(`[moss/wire] canvas \"${data.canvas}\": delta did not rebuild the server's frame — resyncing.`);\n bases.delete(data.canvas);\n send({ type: 'resync' });\n return;\n }\n const frame = JSON.parse(rebuilt) as { canvas: string; tree: RenderNode[] };\n bases.set(data.canvas, rebuilt);\n publishSnapshot({ ...snapshot, trees: new Map(snapshot.trees).set(data.canvas, frame.tree) });\n } else if (data.type === 'frame' && data.tree !== undefined) {\n publishSnapshot({ ...snapshot, frame: data.tree });\n } else if (data.type === 'session' && typeof data.token === 'string') {\n // Login redeemed server-side: become that principal.\n become(data.token);\n } else if (data.type === 'session' && typeof data.sealed === 'string') {\n // The same, for a terminal whose browser keeps the session: nothing\n // this page can read — it is carried to the next upgrade as it is.\n become(null, data.sealed);\n } else if (data.type === 'error') {\n if (data.code === 'seal_not_kept') unsealed = true;\n // Diagnostics, not authority — surfaced, never swallowed: a wire that\n // silently stops updating is the worst thing to debug. `invalid_token`\n // arrives here too, from the server's revalidation pass, and it is\n // worth the line: the AUTHORITY is the 4401 close that follows (see\n // onclose), and this is the breadcrumb saying the session expired\n // rather than the network dropping.\n console.warn(`[moss/wire] server error${data.code !== undefined ? ` (${data.code})` : ''}: ${data.message ?? ''}`);\n } else if (data.type === 'hello' && (data.protocol ?? 1) < PROTOCOL_MIN) {\n // The other half of the handshake: the server checked this terminal on\n // the upgrade; this checks the server. One that predates the question\n // sends no `protocol` and speaks 1.\n console.error(`[moss/wire] the server speaks protocol ${data.protocol ?? 1}; this terminal needs ${PROTOCOL_MIN}–${PROTOCOL}. The server has not been updated yet.`);\n incompatible = true;\n ws.close();\n } else if (data.type === 'hello') {\n // The upgrade has been answered, so a browser that keeps the session\n // itself now does: the token this terminal offered is let go of, and\n // the page holds it no longer. One that does not (another origin,\n // cookies refused) leaves it with the terminal, stored as it always was.\n leaving = false;\n sealed = null;\n if (token !== null && env.tokens.held !== undefined) {\n if (env.tokens.held()) {\n env.tokens.clear();\n token = null;\n } else env.tokens.save(token);\n }\n } else if (data.type !== 'catalog') {\n // catalog is known and deliberately ignored (the terminal is\n // grant-blind — it renders what it is served, never what it may do);\n // anything else is protocol drift worth a shout.\n console.warn(`[moss/wire] unhandled server message: ${data.type}`);\n }\n };\n // The socket is ephemeral, the shell is durable: reconnect re-sends\n // current state. Two application close codes are recoveries, not retries —\n // SIGNED_OUT (a deliberate revoke) and INVALID_TOKEN (the stored token went\n // stale; retrying WITH it would loop forever) both drop the token and\n // reconnect anonymous (the served lock screen). Every other close backs off\n // and retries carrying the current token.\n ws.onclose = (e) => {\n if (incompatible || e.code === CLOSE_PROTOCOL_MISMATCH) {\n incompatible = true;\n setStatus('incompatible');\n return;\n }\n setStatus('closed');\n if (e.code === CLOSE_SIGNED_OUT || e.code === CLOSE_INVALID_TOKEN) {\n leaving = e.code === CLOSE_SIGNED_OUT;\n become(null);\n return;\n }\n if (!disposed) scheduleReconnect();\n };\n };\n\n // Exponential backoff with jitter, capped: a dead server is polled ever more\n // slowly (never faster than ~½s, never slower than the cap), and the jitter\n // spreads a thundering herd of terminals reconnecting on the same outage.\n const RECONNECT_CAP_MS = 30_000;\n const scheduleReconnect = (): void => {\n const ceiling = Math.min(RECONNECT_CAP_MS, 1000 * 2 ** attempts);\n attempts += 1;\n const delay = ceiling / 2 + Math.random() * (ceiling / 2);\n retry = setTimeout(connect, delay);\n };\n\n // A different principal — possibly none — is a different application:\n // store the token, blank the screen, reconnect. A host whose browser may\n // keep the session stores nothing yet: the token is offered, and what\n // becomes of it is settled when the upgrade is answered (`hello`, above).\n const become = (next: string | null, handedSealed: string | null = null): void => {\n // whatever was being offered sealed is over: taken, or refused\n sealed = handedSealed;\n if (handedSealed !== null) {\n /* nothing this page can read, so nothing to store */\n } else if (next === null) env.tokens.clear();\n else if (env.tokens.held === undefined) env.tokens.save(next);\n token = next;\n clearTimeout(retry);\n attempts = 0; // a new principal is a fresh session — start backoff clean\n publishSnapshot(EMPTY);\n const old = socket;\n socket = null;\n if (old !== null) {\n old.onclose = null;\n old.close();\n }\n connect();\n };\n\n // A drawn page with nothing left to happen needs no socket. Everything that\n // would later need one — `reset`, a token arriving — connects by itself.\n if (initial?.live === false) status = 'static';\n else connect();\n\n return {\n subscribe: (listener) => {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n snapshot: () => snapshot,\n status: () => status,\n dispatch: (canvasId, event) => send({ type: 'event', canvas: canvasId, event: event as unknown as Record<string, unknown> }),\n publish: (channel, payload) => send(payload === undefined ? { type: 'publish', channel } : { type: 'publish', channel, payload }),\n // Only on an open socket, and deliberately not queued: a back pressed while\n // the connection is down is a gesture about a screen the person is no\n // longer being served, and replaying it on reconnect would move them\n // somewhere they asked to go some seconds and one outage ago.\n back: () => {\n if (socket === null || status !== 'open') return;\n send({ type: 'back' });\n },\n // Same posture as `back`: only on an open socket, never queued. A jump\n // replayed on reconnect would move somebody to where they wanted to be\n // one outage ago.\n popTo: (canvas: string, instance: string) => {\n if (socket === null || status !== 'open') return;\n send({ type: 'popTo', canvas, instance });\n },\n reset: () => {\n if (disposed) return;\n // Open: ask the server, and the fresh frame arrives on this same socket.\n // Asked of our OWN status rather than `readyState`, because the socket\n // is whatever the host env constructed and the status is ours.\n if (socket !== null && status === 'open') {\n send({ type: 'reset' });\n return;\n }\n // Not open: the backoff may have us waiting half a minute for a retry,\n // and somebody pressing reset is telling us they are waiting NOW. Jump\n // the queue — reattaching re-sends the current trees anyway.\n clearTimeout(retry);\n attempts = 0;\n connect();\n },\n dispose: () => {\n disposed = true;\n status = 'closed'; // sync truth for late readers; no notification after dispose\n clearTimeout(retry);\n socket?.close();\n },\n };\n};\n"]}
|
|
@@ -14,8 +14,100 @@ var spanClock = () => {
|
|
|
14
14
|
const t0 = elapsedClock();
|
|
15
15
|
return { startUnixNano, endUnixNano: () => startUnixNano + (elapsedClock() - t0) * 1e6 };
|
|
16
16
|
};
|
|
17
|
-
|
|
18
|
-
|
|
17
|
+
|
|
18
|
+
// src/session-cookie.ts
|
|
19
|
+
var DEFAULT_TOKEN_KEY = "nisc.token";
|
|
20
|
+
var tokenFromCookie = (header, name = DEFAULT_TOKEN_KEY) => {
|
|
21
|
+
if (header === void 0 || header === null) return null;
|
|
22
|
+
const wanted = encodeURIComponent(name);
|
|
23
|
+
for (const part of header.split(";")) {
|
|
24
|
+
const at = part.indexOf("=");
|
|
25
|
+
if (at < 0 || part.slice(0, at).trim() !== wanted) continue;
|
|
26
|
+
try {
|
|
27
|
+
const value = decodeURIComponent(part.slice(at + 1).trim());
|
|
28
|
+
return value === "" ? null : value;
|
|
29
|
+
} catch {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return null;
|
|
34
|
+
};
|
|
35
|
+
var isOwnOrigin = (origin, host, listed = []) => {
|
|
36
|
+
if (origin === void 0 || origin === null || !URL.canParse(origin)) return false;
|
|
37
|
+
const asked = new URL(origin);
|
|
38
|
+
return asked.host === host?.toLowerCase() || listed.some((entry) => URL.canParse(entry) && new URL(entry).origin === asked.origin);
|
|
39
|
+
};
|
|
40
|
+
var nameOf = (key, port) => `${key}${port === "" ? "" : `.${port}`}`;
|
|
41
|
+
var heldCookieName = (key = DEFAULT_TOKEN_KEY, port = "") => encodeURIComponent(`${nameOf(key, port)}.held`);
|
|
42
|
+
var cookiesAt = (where, key, token, lastsMs) => {
|
|
43
|
+
const name = encodeURIComponent(nameOf(key, where.port));
|
|
44
|
+
const life = token === null ? "; Max-Age=0" : typeof lastsMs === "number" ? `; Max-Age=${Math.max(0, Math.floor(lastsMs / 1e3))}` : "";
|
|
45
|
+
const kept = `Path=/; SameSite=Lax${where.secure ? "; Secure" : ""}${life}`;
|
|
46
|
+
return [`${where.secure ? "__Host-" : ""}${name}=${encodeURIComponent(token ?? "")}; HttpOnly; ${kept}`, `${name}.held=${token === null ? "" : "1"}; ${kept}`];
|
|
47
|
+
};
|
|
48
|
+
var originOf = (request) => {
|
|
49
|
+
const said = request.headers.get("origin");
|
|
50
|
+
if (said !== null && URL.canParse(said)) return said;
|
|
51
|
+
const here = new URL(request.url);
|
|
52
|
+
const scheme = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim() || here.protocol.slice(0, -1);
|
|
53
|
+
return `${scheme}://${request.headers.get("host") ?? here.host}`;
|
|
54
|
+
};
|
|
55
|
+
var sessionCookies = (page, token, options = {}) => {
|
|
56
|
+
const at = new URL(typeof page === "string" ? page : originOf(page));
|
|
57
|
+
return cookiesAt({ port: at.port, secure: at.protocol === "https:" }, options.key ?? DEFAULT_TOKEN_KEY, token, options.lastsMs);
|
|
58
|
+
};
|
|
59
|
+
var sessionTokenOf = (cookies, where, key = DEFAULT_TOKEN_KEY) => {
|
|
60
|
+
const name = nameOf(key, where.port);
|
|
61
|
+
for (const secure of where.secure === void 0 ? [true, false] : [where.secure]) {
|
|
62
|
+
const token = tokenFromCookie(cookies, `${secure ? "__Host-" : ""}${name}`);
|
|
63
|
+
if (token !== null) return { token, clear: cookiesAt({ port: where.port, secure }, key, null) };
|
|
64
|
+
}
|
|
65
|
+
return null;
|
|
66
|
+
};
|
|
67
|
+
var SEALED_FOR_MS = 6e4;
|
|
68
|
+
var sealName = (secure) => `${secure ? "__Http-" : ""}nisc.seal`;
|
|
69
|
+
var toBase64Url = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
70
|
+
var fromBase64Url = (text) => Uint8Array.from(atob(text.replace(/-/g, "+").replace(/_/g, "/")), (char) => char.charCodeAt(0));
|
|
71
|
+
var keyOf = async (seal) => crypto.subtle.importKey("raw", await crypto.subtle.digest("SHA-256", new TextEncoder().encode(seal)), "AES-GCM", false, ["encrypt", "decrypt"]);
|
|
72
|
+
var newSeal = () => toBase64Url(crypto.getRandomValues(new Uint8Array(32)));
|
|
73
|
+
var sealOf = (cookies, secure) => tokenFromCookie(cookies, sealName(secure));
|
|
74
|
+
var sealCookie = (seal, where) => `${sealName(where.secure)}=${seal}; HttpOnly; Path=${where.path}; SameSite=Lax${where.secure ? "; Secure" : ""}`;
|
|
75
|
+
var sealSession = async (seal, token, forMs = SEALED_FOR_MS) => {
|
|
76
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
77
|
+
const sealed = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, await keyOf(seal), new TextEncoder().encode(JSON.stringify({ token, until: Date.now() + forMs })));
|
|
78
|
+
return toBase64Url(new Uint8Array([...iv, ...new Uint8Array(sealed)]));
|
|
79
|
+
};
|
|
80
|
+
var openSealed = async (seal, sealed) => {
|
|
81
|
+
try {
|
|
82
|
+
const bytes = fromBase64Url(sealed);
|
|
83
|
+
const opened = await crypto.subtle.decrypt({ name: "AES-GCM", iv: bytes.slice(0, 12) }, await keyOf(seal), bytes.slice(12));
|
|
84
|
+
const { token, until } = JSON.parse(new TextDecoder().decode(opened));
|
|
85
|
+
return typeof token === "string" && typeof until === "number" && until > Date.now() ? token : null;
|
|
86
|
+
} catch {
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
var PROTOCOL = 2;
|
|
91
|
+
var PROTOCOL_MIN = 2;
|
|
92
|
+
var SUBPROTOCOL = "nisc";
|
|
93
|
+
var TOKEN_OFFER = "nisc.token.";
|
|
94
|
+
var SEALED_OFFER = "nisc.sealed.";
|
|
95
|
+
var offerToken = (token, sealed = null) => {
|
|
96
|
+
const offer = sealed === null ? [SUBPROTOCOL] : [SUBPROTOCOL, `${SEALED_OFFER}${sealed}`];
|
|
97
|
+
if (token === null) return offer;
|
|
98
|
+
const bytes = String.fromCharCode(...new TextEncoder().encode(token));
|
|
99
|
+
return [...offer, `${TOKEN_OFFER}${btoa(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")}`];
|
|
100
|
+
};
|
|
101
|
+
var offeredToken = (offered = []) => {
|
|
102
|
+
const offer = offered.find((entry) => entry.startsWith(TOKEN_OFFER));
|
|
103
|
+
if (offer === void 0) return null;
|
|
104
|
+
try {
|
|
105
|
+
const bytes = atob(offer.slice(TOKEN_OFFER.length).replace(/-/g, "+").replace(/_/g, "/"));
|
|
106
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(bytes, (char) => char.charCodeAt(0))) || null;
|
|
107
|
+
} catch {
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
};
|
|
19
111
|
var CLOSE_INVALID_TOKEN = 4401;
|
|
20
112
|
var CLOSE_SIGNED_OUT = 4403;
|
|
21
113
|
var CLOSE_SHELL_FAILED = 4500;
|
|
@@ -31,6 +123,7 @@ var parse = (text) => {
|
|
|
31
123
|
};
|
|
32
124
|
var createSocket = (ctx) => {
|
|
33
125
|
const emit = emitterOf(ctx.telemetry);
|
|
126
|
+
let saidNotOwn = false;
|
|
34
127
|
const live = /* @__PURE__ */ new Map();
|
|
35
128
|
const expire = (connection) => {
|
|
36
129
|
connection.send(JSON.stringify({ type: "error", code: "invalid_token", message: "The session token no longer resolves to this principal." }));
|
|
@@ -87,18 +180,40 @@ var createSocket = (ctx) => {
|
|
|
87
180
|
connection.close(CLOSE_PROTOCOL_MISMATCH, "protocol mismatch");
|
|
88
181
|
return;
|
|
89
182
|
}
|
|
90
|
-
const
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
183
|
+
const upgrade = connection.upgrade;
|
|
184
|
+
const key = /^[\w.-]{1,64}$/.test(params.get("key") ?? "") ? params.get("key") : DEFAULT_TOKEN_KEY;
|
|
185
|
+
const page = upgrade !== void 0 && isOwnOrigin(upgrade.origin, upgrade.host, ctx.origins) ? new URL(upgrade.origin) : void 0;
|
|
186
|
+
const secure = page?.protocol === "https:";
|
|
187
|
+
const held = page === void 0 ? null : sessionTokenOf(upgrade?.cookie, { port: page.port, secure }, key);
|
|
188
|
+
const sealing = page !== void 0 && params.get("sealed") === "1";
|
|
189
|
+
if (page === void 0 && params.get("sealed") === "1" && typeof upgrade?.origin === "string" && !saidNotOwn) {
|
|
190
|
+
saidNotOwn = true;
|
|
191
|
+
console.warn(`[moss] a terminal on ${upgrade.origin} holds its own session token: this server was addressed as ${upgrade.host ?? "nothing"}, so that is not the app\u2019s own page. If the app is served there, behind a proxy that rewrites Host, list it in runtime.origins.`);
|
|
192
|
+
}
|
|
193
|
+
const hadSeal = sealing ? sealOf(upgrade?.cookie, secure) : null;
|
|
194
|
+
const sealedOffer = upgrade?.offered.find((entry) => entry.startsWith(SEALED_OFFER))?.slice(SEALED_OFFER.length) ?? null;
|
|
195
|
+
const sealLost = sealing && sealedOffer !== null && hadSeal === null;
|
|
196
|
+
const seal = !sealing || sealLost ? null : hadSeal ?? (upgrade?.answer === void 0 ? null : newSeal());
|
|
197
|
+
const offered = offeredToken(upgrade?.offered) ?? (sealedOffer === null || hadSeal === null ? null : await openSealed(hadSeal, sealedOffer));
|
|
198
|
+
let token = offered ?? (params.get("leave") === "1" ? null : held?.token ?? null);
|
|
199
|
+
let principal = token === null ? null : await ctx.session(token);
|
|
200
|
+
if (offered !== null && principal === null) {
|
|
201
|
+
if (emit !== void 0 && upClock !== void 0) {
|
|
202
|
+
emit({ name: "socket.upgrade", startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: "refused", attributes: { hasPrincipal: false } });
|
|
101
203
|
}
|
|
204
|
+
send({ type: "error", code: "invalid_token", message: "The session token did not resolve to a principal." });
|
|
205
|
+
connection.close(CLOSE_INVALID_TOKEN, "invalid token");
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
if (principal === null) token = null;
|
|
209
|
+
const answered = [
|
|
210
|
+
...page === void 0 || offered === null && (held?.token ?? null) === token ? [] : token === null ? held?.clear ?? [] : sessionCookies(page.origin, token, { key, lastsMs: await ctx.sessionLastsMs?.(token) ?? null }),
|
|
211
|
+
...seal !== null && hadSeal === null ? [sealCookie(seal, { secure, path: new URL(url, "http://nisc.local").pathname })] : []
|
|
212
|
+
];
|
|
213
|
+
if (answered.length > 0) upgrade?.answer?.(answered);
|
|
214
|
+
if (seal !== null) connection.seal = (granted) => sealSession(seal, granted);
|
|
215
|
+
if (sealLost) {
|
|
216
|
+
send({ type: "error", code: "seal_not_kept", message: "This browser did not keep the cookie a sealed sign-in is opened with. Sign in again: it will be handed over as a token." });
|
|
102
217
|
}
|
|
103
218
|
live.set(connection, token !== null && token !== "" && principal !== null ? { token, principal } : null);
|
|
104
219
|
connection.onClose(() => live.delete(connection));
|
|
@@ -246,6 +361,6 @@ var frameHash = (text) => {
|
|
|
246
361
|
return hash >>> 0;
|
|
247
362
|
};
|
|
248
363
|
|
|
249
|
-
export { CLOSE_INVALID_TOKEN, CLOSE_PROTOCOL_MISMATCH, CLOSE_SHELL_FAILED, CLOSE_SIGNED_OUT, DEFAULT_REVALIDATE_MS, PROTOCOL, PROTOCOL_MIN, applyDelta, createSocket, emitterOf, encodeDelta, frameHash, spanClock };
|
|
250
|
-
//# sourceMappingURL=chunk-
|
|
251
|
-
//# sourceMappingURL=chunk-
|
|
364
|
+
export { CLOSE_INVALID_TOKEN, CLOSE_PROTOCOL_MISMATCH, CLOSE_SHELL_FAILED, CLOSE_SIGNED_OUT, DEFAULT_REVALIDATE_MS, DEFAULT_TOKEN_KEY, PROTOCOL, PROTOCOL_MIN, SUBPROTOCOL, applyDelta, createSocket, emitterOf, encodeDelta, frameHash, heldCookieName, offerToken, sessionCookies, sessionTokenOf, spanClock, tokenFromCookie };
|
|
365
|
+
//# sourceMappingURL=chunk-HOZID4EM.js.map
|
|
366
|
+
//# sourceMappingURL=chunk-HOZID4EM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/telemetry.ts","../src/session-cookie.ts","../src/socket.ts","../src/delta.ts"],"names":[],"mappings":";;;AA0DO,IAAM,YAAY,CAAC,SAAA,KACxB,cAAc,MAAA,GACV,MAAA,GACA,CAAC,IAAA,KAAS;AACR,EAAA,IAAI;AACF,IAAA,SAAA,CAAU,KAAK,IAAI,CAAA;AAAA,EACrB,SAAS,GAAA,EAAK;AACZ,IAAA,OAAA,CAAQ,KAAA,CAAM,oBAAoB,GAAG,CAAA;AAAA,EACvC;AACF;AAON,IAAM,YAAA,GAAe,MAAe,OAAO,WAAA,KAAgB,cAAc,WAAA,CAAY,GAAA,EAAI,GAAI,IAAA,CAAK,GAAA,EAAI;AAE/F,IAAM,YAAY,MAAiB;AACxC,EAAA,MAAM,aAAA,GAAgB,IAAA,CAAK,GAAA,EAAI,GAAI,GAAA;AACnC,EAAA,MAAM,KAAK,YAAA,EAAa;AACxB,EAAA,OAAO,EAAE,eAAe,WAAA,EAAa,MAAM,iBAAiB,YAAA,EAAa,GAAI,MAAM,GAAA,EAAI;AACzF;;;ACpDO,IAAM,iBAAA,GAAoB;AAG1B,IAAM,eAAA,GAAkB,CAAC,MAAA,EAAmC,IAAA,GAAO,iBAAA,KAAqC;AAC7G,EAAA,IAAI,MAAA,KAAW,MAAA,IAAa,MAAA,KAAW,IAAA,EAAM,OAAO,IAAA;AACpD,EAAA,MAAM,MAAA,GAAS,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sBAAA,EAAyB,IAAA,CAAK,MAAM,CAAA,CAAE,CAAA;AAAA,IAC5F;AACA,IAAA,GAAA,IAAO,IAAA,CAAK,KAAA,CAAM,MAAA,EAAQ,MAAA,GAAS,MAAM,CAAA;AAAA,EAC3C;AACA,EAAA,OAAO,GAAA;AACT;AAUO,IAAM,SAAA,GAAY,CAAC,IAAA,KAAyB;AACjD,EAAA,IAAI,IAAA,GAAO,UAAA;AACX,EAAA,KAAA,IAAS,IAAI,CAAA,EAAG,CAAA,GAAI,IAAA,CAAK,MAAA,EAAQ,KAAK,CAAA,EAAG;AACvC,IAAA,IAAA,IAAQ,IAAA,CAAK,WAAW,CAAC,CAAA;AACzB,IAAA,IAAA,GAAO,IAAA,CAAK,IAAA,CAAK,IAAA,EAAM,QAAU,CAAA;AAAA,EACnC;AACA,EAAA,OAAO,IAAA,KAAS,CAAA;AAClB","file":"chunk-HOZID4EM.js","sourcesContent":["// ═══════════════════════════════════════════════════════════════\n// Telemetry — moss's one observability surface, and the SOLE owner of the\n// span shape. Every service a Midas deployment runs is a moss process; moss\n// is the choke point every engine fact passes through, so moss is where a\n// deployment learns how long a vex execution took, which fingerprint is slow,\n// how often a policy refuses, how many shells are resident. Instrumenting here\n// means a service written tomorrow is observed the day it boots, with no code\n// in the service — the same argument the engine boundary makes for queries.\n//\n// The sink is a deployment decision, not an application one, so the hook lives\n// on the runtime (runtime.ts) beside the other operational knobs. Unset, no\n// span is ever built: every emission site guards on `emit !== undefined`, and\n// an optional call short-circuits its argument, so a hot path with no sink\n// allocates nothing.\n//\n// STRUCTURAL FACTS ONLY. A span carries identifiers and measurements — a\n// fingerprint, a duration, a status — never a payload, a context value, a row,\n// or a principal beyond presence (`hasPrincipal`). The stream must be safe to\n// ship to a third-party backend without a privacy review per span. moss builds\n// every span here from what a seam reports; a seam reports facts, moss decides\n// what of them is safe to name.\n// ═══════════════════════════════════════════════════════════════\n\n// The span, shaped after the OpenTelemetry data model — not the SDK, just the\n// shape, so any OTLP backend ingests a JSON mapping of it with no translation.\nexport type TelemetrySpan = {\n // 'vex.execute' | 'fn.call' | 'shell.build' | 'socket.upgrade' |\n // 'socket.close' | 'integration.call' | …\n name: string;\n // Epoch nanoseconds, millisecond-anchored with a sub-millisecond monotonic\n // span between them. JS numbers cannot hold epoch nanos exactly — the low\n // ~8 bits are lossy — which is far below the millisecond scale of what is\n // measured here, and an exporter re-quantises anyway.\n startUnixNano: number;\n endUnixNano: number;\n // 'refused' is a policy/intake NO — a normal outcome, distinct from a fault.\n status: 'ok' | 'error' | 'refused';\n // Identifiers and measurements. Never a payload, name, address, or context\n // value; a principal appears only as `hasPrincipal`.\n attributes: Record<string, string | number | boolean>;\n // Trace stitching — unused in v1 (no cross-process traceparent yet), carried\n // so a sampler and a propagator can arrive without a shape change.\n traceId?: string;\n spanId?: string;\n parentSpanId?: string;\n};\n\n// The runtime hook. `emit` is fire-and-forget: never awaited, and wrapped\n// (`emitterOf`) so a slow or throwing sink costs the request nothing.\nexport type Telemetry = {\n emit: (span: TelemetrySpan) => void;\n};\n\nexport type Emit = (span: TelemetrySpan) => void;\n\n// The one safe emitter every seam derives. `undefined` when no sink is\n// configured — the signal each site guards on to build no span at all. When a\n// sink is present, its throw is contained here, never the caller's.\nexport const emitterOf = (telemetry: Telemetry | undefined): Emit | undefined =>\n telemetry === undefined\n ? undefined\n : (span) => {\n try {\n telemetry.emit(span);\n } catch (err) {\n console.error('[moss:telemetry]', err);\n }\n };\n\n// A span's clock: the start stamped once, elapsed read on demand — so one clock\n// serves both a short handshake span and a whole-connection span from the same\n// origin. Millisecond-anchored start, sub-millisecond monotonic elapsed.\nexport type SpanClock = { startUnixNano: number; endUnixNano: () => number };\n\nconst elapsedClock = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now());\n\nexport const spanClock = (): SpanClock => {\n const startUnixNano = Date.now() * 1e6;\n const t0 = elapsedClock();\n return { startUnixNano, endUnixNano: () => startUnixNano + (elapsedClock() - t0) * 1e6 };\n};\n","// ═══════════════════════════════════════════════════════════════\n// A BROWSER'S SESSION, KEPT WHERE ITS PAGE CANNOT READ IT.\n//\n// A terminal served by the app it talks to does not hold its session: the\n// browser does, in a cookie no script can read, and sends it by itself with\n// the two requests that need to know who is asking — the page, and the\n// upgrade that opens the socket. The server writes it in its answer to that\n// upgrade (socket.ts), or to a sign-in the app answers over HTTP\n// (`sessionCookies`, below). Any other terminal — a process, a page served\n// from somewhere else — holds its own token and offers it, as before.\n//\n// THE NAME is the terminal's token key (`nisc.token`, or a seat's own), so\n// several people can be signed in on one origin, each in a seat. It ends with\n// the port when the page is on one: a browser keeps cookies by host and not by\n// port, and two apps on localhost would otherwise sign each other out. Over\n// https it is `__Host-` prefixed and `Secure`, which a browser lets nothing\n// but this host set.\n//\n// BESIDE IT, `<name>.held=1`, which script CAN read and which says nothing but\n// that the browser holds a session — how a terminal knows to let go of a token\n// it was holding, and that a page drawn for somebody was drawn for it.\n//\n// NO ROUTE ANSWERS TO THIS COOKIE. It is read for a page request, which every\n// site may link to and none can read the answer of, and on an upgrade from the\n// app's own page — never from another origin's, which a browser would send it\n// with all the same.\n// ═══════════════════════════════════════════════════════════════\n\nexport const DEFAULT_TOKEN_KEY = 'nisc.token';\n\n// The token under one name in a `Cookie` header.\nexport const tokenFromCookie = (header: string | null | undefined, name = DEFAULT_TOKEN_KEY): string | null => {\n if (header === undefined || header === null) return null;\n const wanted = encodeURIComponent(name);\n for (const part of header.split(';')) {\n const at = part.indexOf('=');\n if (at < 0 || part.slice(0, at).trim() !== wanted) continue;\n try {\n const value = decodeURIComponent(part.slice(at + 1).trim());\n return value === '' ? null : value;\n } catch {\n return null;\n }\n }\n return null;\n};\n\n// Is this the app's own page asking? Its origin's host is the host the request\n// was addressed to — or one the deployment lists, behind a proxy that rewrites\n// `Host`. A sibling subdomain, another port, an opaque origin: not it.\nexport const isOwnOrigin = (origin: string | null | undefined, host: string | null | undefined, listed: readonly string[] = []): origin is string => {\n if (origin === undefined || origin === null || !URL.canParse(origin)) return false;\n const asked = new URL(origin);\n return asked.host === host?.toLowerCase() || listed.some((entry) => URL.canParse(entry) && new URL(entry).origin === asked.origin);\n};\n\nconst nameOf = (key: string, port: string): string => `${key}${port === '' ? '' : `.${port}`}`;\n\n// The flag's name, as a terminal on `port` reads it out of `document.cookie`.\nexport const heldCookieName = (key = DEFAULT_TOKEN_KEY, port = ''): string => encodeURIComponent(`${nameOf(key, port)}.held`);\n\nconst cookiesAt = (where: { port: string; secure: boolean }, key: string, token: string | null, lastsMs?: number | null): string[] => {\n const name = encodeURIComponent(nameOf(key, where.port));\n const life = token === null ? '; Max-Age=0' : typeof lastsMs === 'number' ? `; Max-Age=${Math.max(0, Math.floor(lastsMs / 1000))}` : '';\n const kept = `Path=/; SameSite=Lax${where.secure ? '; Secure' : ''}${life}`;\n return [`${where.secure ? '__Host-' : ''}${name}=${encodeURIComponent(token ?? '')}; HttpOnly; ${kept}`, `${name}.held=${token === null ? '' : '1'}; ${kept}`];\n};\n\n// The page's origin as its browser sees it: what the request says, else where\n// it was addressed and how a proxy in front says it arrived.\nconst originOf = (request: Request): string => {\n const said = request.headers.get('origin');\n if (said !== null && URL.canParse(said)) return said;\n const here = new URL(request.url);\n const scheme = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim() || here.protocol.slice(0, -1);\n return `${scheme}://${request.headers.get('host') ?? here.host}`;\n};\n\n// THE `Set-Cookie` VALUES that keep `token` in the browser of the page at this\n// origin — or, for `null`, take it back. For a sign-in the app answers over\n// HTTP (a link redeemed, a provider's callback): set these on the response and\n// the page that follows is signed in, having never held the token. `lastsMs`\n// is how long the browser keeps it; left out, until the browser closes.\nexport const sessionCookies = (page: string | Request, token: string | null, options: { key?: string; lastsMs?: number | null } = {}): string[] => {\n const at = new URL(typeof page === 'string' ? page : originOf(page));\n return cookiesAt({ port: at.port, secure: at.protocol === 'https:' }, options.key ?? DEFAULT_TOKEN_KEY, token, options.lastsMs);\n};\n\n// What the browser holds for this key, out of a request's `Cookie` header.\n// `secure` says which of the two names to read; unknown (a page request does\n// not say how it arrived), the one only this host can have set is read first.\nexport const sessionTokenOf = (\n cookies: string | null | undefined,\n where: { port: string; secure?: boolean },\n key = DEFAULT_TOKEN_KEY,\n): { token: string; clear: string[] } | null => {\n const name = nameOf(key, where.port);\n for (const secure of where.secure === undefined ? [true, false] : [where.secure]) {\n const token = tokenFromCookie(cookies, `${secure ? '__Host-' : ''}${name}`);\n if (token !== null) return { token, clear: cookiesAt({ port: where.port, secure }, key, null) };\n }\n return null;\n};\n\n// ═══════════════════════════════════════════════════════════════\n// THE SEAL — how a sign-in made over the socket reaches that cookie.\n//\n// Only an HTTP answer can write a cookie, and a sign-in over the socket is not\n// one: the token has to travel through the page to the next upgrade. It\n// travels SEALED — encrypted with a key the page's browser holds in a second\n// cookie no script can read, set by the answer to its first upgrade. The page\n// can hand it back and cannot open it; neither can anybody it is shown to, on\n// this machine or another. It is good for a minute.\n//\n// The seal rides only the socket's own path: no page request carries it, so a\n// page drawn for nobody is still the same for everybody. It lasts until the\n// browser closes, and is never stored or looked up here — a key, not a name.\n//\n// ITS NAME IS WHAT KEEPS A SCRIPT FROM SUPPLYING IT. A request shows a cookie's\n// name and value and nothing of who set it, so a seal a script planted before\n// the browser's first upgrade would look like one given here — and the script\n// would hold the key. Over https the seal is `__Http-` prefixed: a name a\n// browser lets only an HTTP answer set, never script. A browser that does not\n// know the prefix treats it as any other name, and is where that is still open.\n//\n// WebCrypto, so this is the same on every runtime and nothing here is Node's.\n// ═══════════════════════════════════════════════════════════════\n\nconst SEALED_FOR_MS = 60_000;\nconst sealName = (secure: boolean): string => `${secure ? '__Http-' : ''}nisc.seal`;\nconst toBase64Url = (bytes: Uint8Array): string => btoa(String.fromCharCode(...bytes)).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\nconst fromBase64Url = (text: string): Uint8Array<ArrayBuffer> => Uint8Array.from(atob(text.replace(/-/g, '+').replace(/_/g, '/')), (char) => char.charCodeAt(0));\nconst keyOf = async (seal: string): Promise<CryptoKey> => crypto.subtle.importKey('raw', await crypto.subtle.digest('SHA-256', new TextEncoder().encode(seal)), 'AES-GCM', false, ['encrypt', 'decrypt']);\n\nexport const newSeal = (): string => toBase64Url(crypto.getRandomValues(new Uint8Array(32)));\n\n// The seal a browser sent with an upgrade, and the `Set-Cookie` value that\n// gives it one: for the socket's own `path` only, unreadable to script.\nexport const sealOf = (cookies: string | null | undefined, secure: boolean): string | null => tokenFromCookie(cookies, sealName(secure));\nexport const sealCookie = (seal: string, where: { secure: boolean; path: string }): string => `${sealName(where.secure)}=${seal}; HttpOnly; Path=${where.path}; SameSite=Lax${where.secure ? '; Secure' : ''}`;\n\nexport const sealSession = async (seal: string, token: string, forMs = SEALED_FOR_MS): Promise<string> => {\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const sealed = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, await keyOf(seal), new TextEncoder().encode(JSON.stringify({ token, until: Date.now() + forMs })));\n return toBase64Url(new Uint8Array([...iv, ...new Uint8Array(sealed)]));\n};\n\n// The token in a sealed sign-in — or null: not sealed with this seal, altered, or too old.\nexport const openSealed = async (seal: string, sealed: string): Promise<string | null> => {\n try {\n const bytes = fromBase64Url(sealed);\n const opened = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: bytes.slice(0, 12) }, await keyOf(seal), bytes.slice(12));\n const { token, until } = JSON.parse(new TextDecoder().decode(opened)) as { token?: unknown; until?: unknown };\n return typeof token === 'string' && typeof until === 'number' && until > Date.now() ? token : null;\n } catch {\n return null;\n }\n};\n","import { DefinitionValidationError } from '@niscorp/nova';\nimport type { RenderNode } from '@niscorp/nova';\nimport type { Catalog } from './principal';\nimport type { DeltaOp } from './delta';\nimport type { ShellHost } from './shells';\nimport { emitterOf, spanClock } from './telemetry';\nimport type { Telemetry } from './telemetry';\nimport { DEFAULT_TOKEN_KEY, isOwnOrigin, newSeal, openSealed, sealCookie, sealOf, sealSession, sessionCookies, sessionTokenOf } from './session-cookie';\n\n// ═══════════════════════════════════════════════════════════════\n// The socket — the authority channel (DESIGN.md § The socket), protocol layer.\n//\n// The socket invents nothing: JSON frames, every canvas-bound message\n// carries its canvas id, reconnect just re-sends current state. This\n// module is transport-blind — it speaks through the four-function\n// `Connection` seam; the RFC 6455 plumbing lives with each runtime's\n// entry (`ws` on Node in ./node, Bun-native later) and is never\n// hand-written.\n//\n// What rides it: connection lifecycle, token auth at upgrade, the CATALOG\n// channel (`hello` on connect — the resolved application + its version\n// token; equal hash, equal application), and the canvas streams (`render`\n// down, `event` up) fed by the server shell host. An app whose manifest\n// declares no shell has no streams, and an event envelope aimed at one is\n// answered honestly with `no_shell` rather than silently dropped.\n//\n// Identity is asked twice: once at upgrade, and then on a timer for as long\n// as the connection lives (see DEFAULT_REVALIDATE_MS). The second is what\n// lets a `session` verifier's expiry mean anything here — the HTTP surfaces\n// re-ask on every request, and a socket that asked once would be the hole\n// every long-lived credential leaks through.\n// ═══════════════════════════════════════════════════════════════\n\n// The transport seam — what a runtime's websocket must provide. Four\n// functions, and what the request that opened the connection offered;\n// everything above them is identical on every runtime.\nexport type Connection = {\n send: (text: string) => void;\n close: (code?: number, reason?: string) => void;\n onMessage: (fn: (text: string) => void) => void;\n onClose: (fn: () => void) => void;\n // The upgrade request, as far as it says who is asking: the subprotocols it\n // offered (`Sec-WebSocket-Protocol`, split), and — for a browser's session\n // (session-cookie.ts) — where the page is, where the request was addressed,\n // and the cookies it carried. A transport that leaves this out serves every\n // terminal as nobody.\n //\n // `answer`: a transport that has NOT answered the request yet says so by\n // giving this, and is told — once who is asking is decided, before the\n // connection is used at all — the `Set-Cookie` values its answer is to\n // carry: the one moment a cookie can be written. It answers when the\n // connection is first used.\n // Without it nothing is written, and a browser's terminal goes on holding\n // its own token.\n upgrade?: {\n offered: readonly string[];\n origin?: string | null;\n host?: string | null;\n cookie?: string | null;\n answer?: (cookies: readonly string[]) => void;\n };\n // Set here, not by a transport: how this connection's terminal is handed a\n // session when its browser holds a seal (session-cookie.ts) — sealed, so the\n // page carries it to the next upgrade and cannot open it. Absent, a session\n // is handed over as its token.\n seal?: (token: string) => Promise<string>;\n};\n\n// ── The envelope ──\nexport type ServerMessage =\n | { type: 'hello'; protocol: number; principal: string | null; catalog: { actions: readonly string[]; hash: string } }\n | { type: 'catalog'; actions: readonly string[]; hash: string }\n // the shell's canvas ARRANGEMENT — a rendered layout whose CanvasSlot\n // markers the terminal resolves against its per-canvas trees\n | { type: 'frame'; tree: RenderNode[] }\n | { type: 'render'; canvas: string; tree: RenderNode[] }\n // The same render, as a DELTA against the last frame this connection was\n // sent for this canvas. Only ever sent to a terminal that asked for deltas\n // (`?delta=1` on the upgrade) and only when a previous frame exists, so a\n // terminal that does not understand this never receives one.\n //\n // `hash` is over the rebuilt message text: a terminal that applies the ops\n // and does not land on it has diverged, and asks for a whole frame instead\n // of rendering something the server never meant.\n | { type: 'render-delta'; canvas: string; ops: DeltaOp[]; hash: number }\n // session GRANT (login succeeded server-side): store the token and\n // reconnect authenticated — the twin of the 4403 SIGNED_OUT revoke\n // A sign-in: the terminal comes back as that principal. As the token, for a\n // terminal that keeps its own; SEALED, for one whose browser keeps the\n // session — it offers it on its next upgrade, where its browser's seal opens it.\n | { type: 'session'; token: string }\n | { type: 'session'; sealed: string }\n | { type: 'error'; code: string; message: string; canvas?: string };\n\nexport type ClientMessage =\n | { type: 'event'; canvas: string; event: Record<string, unknown> }\n | { type: 'publish'; channel: string; payload?: unknown }\n // RESYNC: this terminal's frame for a canvas is not what the server thinks\n // it is — a delta failed its checksum, or arrived with no base to apply it\n // to. Answered with whole frames, which is the state both ends can always\n // agree on. Distinct from `reset`: the SHELL is fine, only this connection's\n // copy of it drifted, so nothing is torn down.\n | { type: 'resync' }\n // BACK: undo this session's last navigation. It names no canvas for the same\n // reason `reset` does not — back is one gesture over the whole shell, and the\n // terminal that sends it has no idea which canvas moved last (it is served\n // trees, not stacks). Protocol-level, so a browser's back button, a TUI's\n // Escape and a REPL word are the same message on one wire, and the app has to\n // author nothing to receive it.\n | { type: 'back' }\n // POP TO: jump straight to an ancestor already on a canvas's stack. Back\n // undoes ONE navigation; a breadcrumb that names a screen three levels down\n // is one intention, not three gestures. Sending three `back`s instead raced\n // the browser's own history repair and dropped presses — the shell can walk\n // its own stack atomically, so it should be asked to.\n | { type: 'popTo'; canvas: string; instance: string }\n // RESET: throw this session's shell away and serve its replacement. The one\n // message that names no canvas, deliberately — it is the recovery for a\n // shell whose canvases are the broken thing, so it must not have to travel\n // through one. Protocol-level, not app-level: no action declares it, no\n // charter grants it, and it reaches a terminal whose every surface is dead.\n | { type: 'reset' };\n\n// The wire protocol this server speaks, and the oldest a terminal may speak to\n// it. A terminal says which it speaks on the upgrade (`?protocol=N` — known\n// before the first frame is sent); one that says nothing speaks 1, which is\n// every terminal built before the question existed. Outside the range the\n// connection is refused with a sentence and CLOSE_PROTOCOL_MISMATCH, never\n// served frames it would misread. Bump PROTOCOL when a message changes shape;\n// raise PROTOCOL_MIN only when the server stops speaking an old one.\n//\n// 2: the token left the address. A terminal at 1 put it in `?token=`, and an\n// address is what every proxy on the way writes into its log. A server that\n// went on reading it there would keep that open for as long as anything used\n// it, so 1 is no longer spoken: a terminal built before is told to reload.\nexport const PROTOCOL = 2;\nexport const PROTOCOL_MIN = 2;\n\n// WHO A TERMINAL IS rides the upgrade request, in the one header every host\n// lets a terminal set, a browser included: the subprotocols it offers. It\n// offers `nisc`, and beside it its token when it holds one — base64url,\n// because a subprotocol is an HTTP token and a session token need not be. The\n// server answers `nisc`, never the other. Decided on the request, so no\n// connection is ever open and waiting to be told who it is.\nexport const SUBPROTOCOL = 'nisc';\nconst TOKEN_OFFER = 'nisc.token.';\nconst SEALED_OFFER = 'nisc.sealed.';\n\n// `sealed`: a sign-in the terminal was handed sealed, offered back as it is.\nexport const offerToken = (token: string | null, sealed: string | null = null): string[] => {\n const offer = sealed === null ? [SUBPROTOCOL] : [SUBPROTOCOL, `${SEALED_OFFER}${sealed}`];\n if (token === null) return offer;\n const bytes = String.fromCharCode(...new TextEncoder().encode(token));\n return [...offer, `${TOKEN_OFFER}${btoa(bytes).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')}`];\n};\n\nexport const offeredToken = (offered: readonly string[] = []): string | null => {\n const offer = offered.find((entry) => entry.startsWith(TOKEN_OFFER));\n if (offer === undefined) return null;\n try {\n const bytes = atob(offer.slice(TOKEN_OFFER.length).replace(/-/g, '+').replace(/_/g, '/'));\n return new TextDecoder('utf-8', { fatal: true }).decode(Uint8Array.from(bytes, (char) => char.charCodeAt(0))) || null;\n } catch {\n return null;\n }\n};\n\n// Application close code: the token did not resolve to a principal.\nexport const CLOSE_INVALID_TOKEN = 4401;\n// Application close code: the session ended (sign-out, from any of the\n// principal's terminals) — the terminal clears its token instead of\n// reconnecting.\nexport const CLOSE_SIGNED_OUT = 4403;\n// Application close code: the server could not open a session for THIS\n// connection — commonest cause: a definition failing validation reached the\n// live catalog (a dev edit mid-reload). The refusal is this terminal's alone;\n// the process and every other session stay up, and reconnecting later is\n// reasonable — the next build is attempted fresh.\nexport const CLOSE_SHELL_FAILED = 4500;\n// Application close code: terminal and server speak protocols the other cannot\n// (see PROTOCOL). Not a retry: reconnecting speaks the same protocol again. A\n// browser terminal needs a reload to fetch the current build; the preceding\n// `error` says which side is behind (`client_too_old` / `server_too_old`).\nexport const CLOSE_PROTOCOL_MISMATCH = 4426;\n\nexport type SocketContext = {\n session: (token: string) => string | null | Promise<string | null>;\n catalog: (principal: string | null) => Catalog | Promise<Catalog>;\n // The shell host — when the manifest declares a shell, events route into\n // the session's server shell and render frames flow back.\n shells?: ShellHost;\n // WHICH HOST A PATH LEADS TO. A terminal on a page names the path it is on\n // (`?path=`); this answers with that page's host and the input its path\n // carries, or undefined for a path that is the app's. Absent: every\n // connection is the app's, as before pages existed.\n page?: (path: string) => { host: ShellHost; inputs: Record<string, Record<string, unknown>> } | undefined;\n // How often a LIVE connection's credential is re-verified. Default\n // `DEFAULT_REVALIDATE_MS`; `0` or `Infinity` disables it, and a token\n // checked once at upgrade is then trusted for the life of the connection.\n revalidateMs?: number;\n // The deployment's telemetry sink, if any — a `socket.upgrade` span per\n // connection admitted or refused, and a `socket.close` span carrying the\n // whole connection's lifetime. See telemetry.ts.\n telemetry?: Telemetry;\n // Origins that are this app's own page beside the host a request is\n // addressed to (`runtime.origins`) — a proxy that rewrites `Host`.\n origins?: readonly string[];\n // How much longer a token resolves, when the credential knows — how long a\n // browser is told to keep the cookie that carries it. Unknown: until the\n // browser closes.\n sessionLastsMs?: (token: string) => number | null | Promise<number | null>;\n};\n\n// ── Revalidation ──\n// The HTTP surfaces re-ask \"who is this\" on every request; the socket asked\n// once, at upgrade, and never again. That asymmetry is why an app could not\n// give its tokens an expiry that meant anything: the verifier seam is\n// perfectly able to say a token has died (return null), but on a live socket\n// nobody was listening for the answer.\n//\n// It also failed in a shape worth naming. The server shell's own wire rides\n// the HTTP middleware carrying the session's token, so an expired credential\n// used to leave the socket open and cheerful — frames flowing, screen alive —\n// while every endpoint the shell called came back 401. A live interface whose\n// every load silently fails is strictly worse than a lock screen.\n//\n// The recovery for this already existed and is untouched: a `4401` close is a\n// recovery, not a retry, and the terminal drops its token and reconnects\n// anonymous onto the served lock screen. All that was missing was something\n// asking the question. This is that.\nexport const DEFAULT_REVALIDATE_MS = 60 * 1000;\n\n// One accept per new connection: authenticate (the token rides the upgrade\n// URL — browsers cannot set websocket headers; absent = the anonymous\n// principal, invalid = closed with 4401), then say hello with the resolved\n// catalog and settle into the message loop. `stop` ends revalidation, for\n// hosts that outlive their server (dev checks, embedded tools) — the timer is\n// unref'd, so a plain process needn't call it.\nexport type SocketAccept = ((url: string, connection: Connection) => Promise<void>) & { stop: () => void };\n\nconst parse = (text: string): Record<string, unknown> | null => {\n try {\n const value: unknown = JSON.parse(text);\n return value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : null;\n } catch {\n return null;\n }\n};\n\nexport const createSocket = (ctx: SocketContext): SocketAccept => {\n const emit = emitterOf(ctx.telemetry);\n let saidNotOwn = false;\n // Every live connection, with the credential it authenticated under (null =\n // anonymous, which has nothing that can expire). One structure: the future\n // catalog-push fan-out wants the keys, revalidation wants the values.\n const live = new Map<Connection, { token: string; principal: string } | null>();\n\n const expire = (connection: Connection): void => {\n // Diagnostics before authority, as at upgrade — the close code is what\n // the terminal acts on; this is what a person reads in a log.\n connection.send(JSON.stringify({ type: 'error', code: 'invalid_token', message: 'The session token no longer resolves to this principal.' } satisfies ServerMessage));\n connection.close(CLOSE_INVALID_TOKEN, 'session expired');\n live.delete(connection);\n };\n\n const revalidate = async (): Promise<void> => {\n for (const [connection, credential] of [...live]) {\n if (credential === null) continue; // anonymous — nothing to expire\n let resolved: string | null;\n try {\n resolved = await ctx.session(credential.token);\n } catch {\n // The verifier is unreachable — a database blip, a network hiccup.\n // That is not evidence a session ended, and signing everybody out on\n // it would turn a transient fault into an outage. Ask again next pass.\n continue;\n }\n // Unchanged is the overwhelmingly common answer. A token that stops\n // resolving has expired or been revoked; one that resolves to somebody\n // ELSE is not the session that attached, and both are the same close.\n if (resolved === credential.principal) continue;\n if (!live.has(connection)) continue; // it closed while we were awaiting\n expire(connection);\n }\n };\n\n const revalidateMs = ctx.revalidateMs ?? DEFAULT_REVALIDATE_MS;\n let sweeper: ReturnType<typeof setInterval> | undefined;\n if (revalidateMs > 0 && Number.isFinite(revalidateMs)) {\n sweeper = setInterval(() => void revalidate(), revalidateMs);\n // Revalidation must never be the reason a process stays alive.\n (sweeper as unknown as { unref?: () => void }).unref?.();\n }\n\n // REFUSING ONE SESSION MUST NEVER COST THE OTHERS. Every await in the body\n // below can throw — the verifier on a database blip, the shell build on a\n // definition that fails validation — and the runtime transport calls accept\n // without awaiting it, so an escaped rejection is an unhandled one and Node\n // kills the whole process: one bad definition, every session on the box\n // disconnected. So accept NEVER rejects. A failure to open this session is\n // answered to this terminal — a sentence naming the failing definitions\n // when there are any, then a 4500 close — and logged where somebody can\n // read it. The durable map is only written after a successful build, so a\n // refused terminal poisons nothing: the next connect builds fresh.\n const accept = async (url: string, connection: Connection): Promise<void> => {\n const send = (message: ServerMessage): void => connection.send(JSON.stringify(message));\n try {\n await open(url, connection, send);\n } catch (error) {\n console.error('[moss/socket] refused a session:', error);\n live.delete(connection);\n const failures =\n error instanceof DefinitionValidationError\n ? ((error.context as { failures?: { id: string }[] } | undefined)?.failures ?? []).map((f) => f.id)\n : [];\n const detail = failures.length > 0 ? `${String(error instanceof Error ? error.message : error)}: ${failures.join(', ')}` : String(error);\n try {\n send({ type: 'error', code: 'session_failed', message: `This session could not be opened — ${detail}. The refusal is this terminal's alone; the server is up.` });\n connection.close(CLOSE_SHELL_FAILED, 'session failed');\n } catch {\n // The transport is already gone — there is nobody left to tell.\n }\n }\n };\n\n const open = async (url: string, connection: Connection, send: (message: ServerMessage) => void): Promise<void> => {\n // One clock stamped at the handshake serves both the short `socket.upgrade`\n // span and the whole-connection `socket.close` span from the same origin.\n const upClock = emit === undefined ? undefined : spanClock();\n const params = new URL(url, 'http://nisc.local').searchParams;\n const spoken = Number(params.get('protocol') ?? '1');\n if (!Number.isInteger(spoken) || spoken < PROTOCOL_MIN || spoken > PROTOCOL) {\n const behind = spoken > PROTOCOL ? 'server' : 'client';\n send({\n type: 'error',\n code: `${behind}_too_old`,\n message: `This terminal speaks protocol ${params.get('protocol') ?? '1'}; this server speaks ${PROTOCOL_MIN}–${PROTOCOL}. ${behind === 'client' ? 'Reload the terminal to get the current build.' : 'The server has not been updated yet.'}`,\n });\n connection.close(CLOSE_PROTOCOL_MISMATCH, 'protocol mismatch');\n return;\n }\n const upgrade = connection.upgrade;\n // THE APP'S OWN PAGE does not hold its session: its browser does, in a\n // cookie the page cannot read (session-cookie.ts), and sent it with this\n // request. From any other origin the cookie is not looked at — a browser\n // sends it with a stranger's page all the same. `key` is which of the\n // browser's sessions this terminal is (a seat); a name, not a secret.\n const key = /^[\\w.-]{1,64}$/.test(params.get('key') ?? '') ? (params.get('key') as string) : DEFAULT_TOKEN_KEY;\n const page = upgrade !== undefined && isOwnOrigin(upgrade.origin, upgrade.host, ctx.origins) ? new URL(upgrade.origin) : undefined;\n const secure = page?.protocol === 'https:';\n const held = page === undefined ? null : sessionTokenOf(upgrade?.cookie, { port: page.port, secure }, key);\n // A SIGN-IN OVER THE SOCKET REACHES THAT COOKIE SEALED. A terminal whose\n // browser can keep a session says so (`sealed=1`), and its browser is given\n // a seal — a key in a second cookie no script can read — by the answer to\n // its first upgrade. A sign-in is then handed to the page sealed with it;\n // the page offers it back here, and only this browser's seal opens it.\n const sealing = page !== undefined && params.get('sealed') === '1';\n // A browser terminal that is not on the app's own page works as it always\n // did, holding its own token — which is right for a page served from\n // somewhere else, and is what a proxy that rewrites `Host` looks like too.\n // Said once: nothing else would tell a deployment it is in the second case.\n if (page === undefined && params.get('sealed') === '1' && typeof upgrade?.origin === 'string' && !saidNotOwn) {\n saidNotOwn = true;\n console.warn(`[moss] a terminal on ${upgrade.origin} holds its own session token: this server was addressed as ${upgrade.host ?? 'nothing'}, so that is not the app’s own page. If the app is served there, behind a proxy that rewrites Host, list it in runtime.origins.`);\n }\n const hadSeal = sealing ? sealOf(upgrade?.cookie, secure) : null;\n const sealedOffer = upgrade?.offered.find((entry) => entry.startsWith(SEALED_OFFER))?.slice(SEALED_OFFER.length) ?? null;\n // A sealed sign-in that came back with no seal to open it: this browser\n // does not keep the cookie, and is not handed another sign-in that way.\n const sealLost = sealing && sealedOffer !== null && hadSeal === null;\n const seal = !sealing || sealLost ? null : (hadSeal ?? (upgrade?.answer === undefined ? null : newSeal()));\n const offered = offeredToken(upgrade?.offered) ?? (sealedOffer === null || hadSeal === null ? null : await openSealed(hadSeal, sealedOffer));\n // A token the terminal offers comes first. `leave`: it was signed out, and\n // says so because what its browser holds may be a token that still\n // resolves — an app's own provider's is not moss's to revoke.\n let token = offered ?? (params.get('leave') === '1' ? null : (held?.token ?? null));\n let principal = token === null ? null : await ctx.session(token);\n if (offered !== null && principal === null) {\n if (emit !== undefined && upClock !== undefined) {\n emit({ name: 'socket.upgrade', startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: 'refused', attributes: { hasPrincipal: false } });\n }\n send({ type: 'error', code: 'invalid_token', message: 'The session token did not resolve to a principal.' });\n connection.close(CLOSE_INVALID_TOKEN, 'invalid token');\n return;\n }\n // What the browser held and no longer resolves is nobody — not a refusal:\n // the page cannot read it to drop it, so a 4401 would be one it could\n // never stop getting.\n if (principal === null) token = null;\n // THE ANSWER makes the browser hold who this turned out to be. A token the\n // page offered — left in storage by an earlier build, or just handed to it\n // at sign-in — is moved into the cookie, and that was the last time the\n // page held it; a session that ended is taken back. An offered token is\n // written even when the browser sent the same one: over plain http on the\n // default port the copy an earlier build kept, readable by script, has\n // this cookie's name.\n const answered = [\n ...(page === undefined || (offered === null && (held?.token ?? null) === token) ? [] : token === null ? (held?.clear ?? []) : sessionCookies(page.origin, token, { key, lastsMs: (await ctx.sessionLastsMs?.(token)) ?? null })),\n ...(seal !== null && hadSeal === null ? [sealCookie(seal, { secure, path: new URL(url, 'http://nisc.local').pathname })] : []),\n ];\n if (answered.length > 0) upgrade?.answer?.(answered);\n if (seal !== null) connection.seal = (granted) => sealSession(seal, granted);\n // The terminal is told, and stops asking to be handed sign-ins sealed —\n // the next one reaches it as a token, on this connection already.\n if (sealLost) {\n send({ type: 'error', code: 'seal_not_kept', message: 'This browser did not keep the cookie a sealed sign-in is opened with. Sign in again: it will be handed over as a token.' });\n }\n\n // Remembered WITH its credential — revalidation has to re-ask the same\n // question this connection was admitted on, and the token is not\n // recoverable from anything else here.\n live.set(connection, token !== null && token !== '' && principal !== null ? { token, principal } : null);\n connection.onClose(() => live.delete(connection));\n // The connection's whole life, closed by the same clock — how long\n // terminals stay, and under a principal or anonymous. Registered here so it\n // fires however the connection ends (graceful, expiry, transport drop).\n if (emit !== undefined && upClock !== undefined) {\n const hadPrincipal = principal !== null;\n connection.onClose(() => emit({ name: 'socket.close', startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: 'ok', attributes: { hasPrincipal: hadPrincipal } }));\n }\n\n // The catalog channel: the application, resolved for YOU, on every\n // (re)connect — reconnect re-sends current state, no replay machinery.\n const { ids, hash } = await ctx.catalog(principal);\n send({ type: 'hello', protocol: PROTOCOL, principal, catalog: { actions: ids, hash } });\n\n // The canvas streams: attach to the session's shell (durable per\n // principal — the shell outlives this connection) and it re-sends the\n // current trees; every change fans out to every attached connection.\n // Frame deltas are OPT-IN by the terminal, on the upgrade URL beside the\n // token — browsers cannot set websocket headers, and the capability has to\n // be known before the first frame is sent. A terminal that says nothing is\n // served whole frames forever, which is what every terminal built before\n // this existed does.\n const wantsDelta = params.get('delta') === '1';\n\n // An anonymous terminal whose page was rendered server-side names the id\n // seed that page's shell was built under, so this connection's throwaway\n // shell mints the same instance ids and its first frames match the page.\n // Shape-checked, never trusted further: it only ever names ids inside the\n // caller's own shell.\n const named = params.get('seed');\n const seed = named !== null && /^[0-9a-f]{8,40}$/.test(named) ? named : undefined;\n\n // The path the terminal is on decides which shell it is served: a page's,\n // built for this connection alone, or the app's.\n const path = params.get('path');\n const route = path === null ? undefined : ctx.page?.(path);\n const host = route?.host ?? ctx.shells;\n\n const session = await host?.session(token, principal, { ...(seed === undefined ? {} : { seed }), ...(route === undefined ? {} : { inputs: route.inputs }) });\n if (session !== undefined) {\n session.attach(connection, { delta: wantsDelta });\n connection.onClose(() => session.detach(connection));\n }\n\n // Admitted: the handshake resolved a principal, said hello, and attached a\n // shell. The span measures that, not the connection's life (that is\n // `socket.close`).\n if (emit !== undefined && upClock !== undefined) {\n emit({ name: 'socket.upgrade', startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: 'ok', attributes: { hasPrincipal: principal !== null } });\n }\n\n connection.onMessage((text) => {\n const message = parse(text);\n // Reset first, and answered on its own terms: a wedged session is\n // exactly the one whose other paths cannot be trusted to run.\n if (message !== null && message['type'] === 'reset') {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.reset();\n return;\n }\n // Resync before the ordinary paths, for the reason reset is: a terminal\n // asking for this has already decided it cannot trust what it is holding.\n if (message !== null && message['type'] === 'resync') {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.resync(connection);\n return;\n }\n if (message !== null && message['type'] === 'back') {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.back();\n return;\n }\n if (\n message !== null &&\n message['type'] === 'popTo' &&\n typeof message['canvas'] === 'string' &&\n typeof message['instance'] === 'string'\n ) {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.popTo(message['canvas'], message['instance']);\n return;\n }\n if (message !== null && message['type'] === 'publish' && typeof message['channel'] === 'string') {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.publish(message['channel'], message['payload']);\n return;\n }\n if (message === null || message['type'] !== 'event' || typeof message['canvas'] !== 'string') {\n send({ type: 'error', code: 'invalid_message', message: 'Messages are JSON { type: \"event\", canvas, event }.' });\n return;\n }\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.', canvas: message['canvas'] });\n return;\n }\n const event = message['event'];\n if (event === null || typeof event !== 'object' || Array.isArray(event)) {\n send({ type: 'error', code: 'invalid_message', message: 'The event field must be a NovaEvent object.', canvas: message['canvas'] });\n return;\n }\n session.dispatch(message['canvas'], event as Record<string, unknown>);\n });\n };\n\n return Object.assign(accept, {\n stop: () => {\n if (sweeper !== undefined) clearInterval(sweeper);\n sweeper = undefined;\n },\n });\n};\n","// Frame deltas — send what changed, not the frame.\n//\n// A shell re-sends a whole canvas tree whenever that tree changes. Most changes\n// are small against a large tree (a keystroke filters a list, one badge flips),\n// so the new frame is mostly a rearrangement of bytes the client already holds.\n//\n// This encodes the new frame as COPY runs from the old one plus literal\n// inserts. It is deliberately not a structural diff over the tree: a\n// navigation produces a genuinely different tree, and a path-based diff then\n// costs MORE than the frame it replaces, while a byte matcher still finds the\n// shared vocabulary. It is also not zlib's preset dictionary, which would be\n// two lines here and does not exist in a browser.\n//\n// No dependency, both directions in one file, and small enough to read in\n// full — a delta layer that cannot be audited is a desync you cannot diagnose.\n\n/** A run copied from the base frame: offset, length. */\ntype Copy = [0, number, number];\n/** Bytes that are not in the base at all. */\ntype Insert = [1, string];\nexport type DeltaOp = Copy | Insert;\n\n// Matches shorter than this cost more to describe than to inline. 16 is a\n// compromise: low enough to catch a changed cell inside a row, high enough that\n// the index does not match noise.\nconst BLOCK = 16;\n\n/**\n * Encode `target` as operations against `base`.\n *\n * Greedy and single-pass: at each position look for a block that already exists\n * in the base, extend the match as far as it runs, and emit a copy. Anything\n * unmatched accumulates into a literal. Not optimal — an optimal encoder needs\n * a suffix automaton — but it captures the long shared runs that dominate a\n * render tree, which is where the bytes are.\n */\nexport const encodeDelta = (base: string, target: string): DeltaOp[] => {\n if (base.length < BLOCK) return [[1, target]];\n\n const index = new Map<string, number>();\n for (let i = 0; i + BLOCK <= base.length; i += 1) {\n // First position wins: earlier offsets tend to extend further in a tree\n // whose head is stable chrome.\n const key = base.slice(i, i + BLOCK);\n if (!index.has(key)) index.set(key, i);\n }\n\n const ops: DeltaOp[] = [];\n let literal = '';\n let at = 0;\n\n while (at < target.length) {\n const key = target.slice(at, at + BLOCK);\n const found = key.length === BLOCK ? index.get(key) : undefined;\n if (found === undefined) {\n literal += target[at];\n at += 1;\n continue;\n }\n let length = BLOCK;\n while (found + length < base.length && at + length < target.length && base[found + length] === target[at + length]) {\n length += 1;\n }\n if (literal !== '') {\n ops.push([1, literal]);\n literal = '';\n }\n ops.push([0, found, length]);\n at += length;\n }\n if (literal !== '') ops.push([1, literal]);\n return ops;\n};\n\n/** Rebuild the frame. Throws on a malformed op rather than returning a\n * half-applied string — a silently wrong frame is the failure this whole\n * layer has to not have. */\nexport const applyDelta = (base: string, ops: readonly DeltaOp[]): string => {\n let out = '';\n for (const op of ops) {\n if (op[0] === 1) {\n out += op[1];\n continue;\n }\n const [, offset, length] = op;\n if (offset < 0 || length < 0 || offset + length > base.length) {\n throw new Error(`moss/delta: copy ${offset}+${length} is outside a base of ${base.length}`);\n }\n out += base.slice(offset, offset + length);\n }\n return out;\n};\n\n/**\n * A cheap, order-sensitive checksum of a frame.\n *\n * Carried on every delta so a client can prove it rebuilt the frame the server\n * meant. A delta protocol without this is one dropped message away from a\n * client that is permanently and silently wrong, with no error anywhere — which\n * is strictly worse than sending whole frames forever.\n */\nexport const frameHash = (text: string): number => {\n let hash = 0x811c9dc5;\n for (let i = 0; i < text.length; i += 1) {\n hash ^= text.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return hash >>> 0;\n};\n"]}
|