@johnhenry/wsh 0.34.1 → 0.35.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -3
- package/package.json +1 -1
- package/src/memory-host.d.ts +32 -1
- package/src/memory-host.mjs +45 -4
- package/src/server/sessions.mjs +10 -230
- package/src/session-registry.mjs +255 -0
package/README.md
CHANGED
|
@@ -274,8 +274,23 @@ session.onData = (d) => console.log(new TextDecoder().decode(d)); // "ran hi"
|
|
|
274
274
|
|
|
275
275
|
It is the real connection handler speaking QMux over an in-memory socket pair, so the client code you test is the code
|
|
276
276
|
you ship. `host.createClient()` / `host.WebSocket` / `host.accept(socket)` / `createSocketPair()` are the lower-level pieces.
|
|
277
|
-
Supported: `auth`, `exec` (a function; there is no shell), `mcp`, `extensions
|
|
278
|
-
`
|
|
277
|
+
Supported: `auth`, `exec` (a function; there is no shell), `mcp`, `extensions`, `rpc` and `sessions` (below). Not
|
|
278
|
+
available in memory: `pty`, `fs`, `gateway`, `relay`, `hostKey`, WebTransport and the `wsh-host` / `wsh-fs` rpc
|
|
279
|
+
built-ins (use `@johnhenry/wsh/server`).
|
|
280
|
+
|
|
281
|
+
**`rpc`** takes handler functions only, `rpc: { calc: (channel, ctx) => channel.onRequest('add', ({ a, b }) => a + b) }`
|
|
282
|
+
(the `RpcChannel` is the one `@johnhenry/wsh/server` hands its handlers), with `rpcMaxMessageBytes` (default 1 MiB) and
|
|
283
|
+
`rpcMaxInflight` (default 64). Clients use `client.openRpc('calc')` unchanged.
|
|
284
|
+
|
|
285
|
+
**`sessions`** (`true` or `{ detachTtlMs, maxDetached, ringBytes }`) keeps *exec* sessions alive across a dropped link
|
|
286
|
+
or `client.detach()`, so `resumeSession()` / `attachSession()` work unchanged: the same Attach / Resume / Detach
|
|
287
|
+
messages, `seq` counted in output bytes, and the same errors (unknown or expired session, bad token, `last_seq` ahead
|
|
288
|
+
of the session, an output gap). The limits and defaults are the server's: 300000 ms detached before a session is
|
|
289
|
+
dropped, at most 16 detached sessions (the longest-detached is dropped first), 1 MiB of replayable output per session
|
|
290
|
+
(a resume older than the ring is refused as a gap; `attachSession` gets the retained tail). The session list lives in
|
|
291
|
+
the page's memory, so it ends with the page or `host.close()`. Differences from the server: no `pty`, no
|
|
292
|
+
`sessionSecret` (tokens are random per session instead of HMAC-signed, so they cannot be checked across restarts), and
|
|
293
|
+
the host still runs no command by itself: sessions only wrap whatever `exec` function you pass.
|
|
279
294
|
|
|
280
295
|
### Signing with a page-held signer
|
|
281
296
|
|
|
@@ -618,7 +633,9 @@ const pty = client.getSession(client.listSessions()[0].channelId); // live sessi
|
|
|
618
633
|
```
|
|
619
634
|
|
|
620
635
|
An aborted upload writes nothing (the server writes the file only when the last chunk arrives). An aborted `callTool`
|
|
621
|
-
also sends `McpCancel` to a host advertising `mcp-cancel`, so the tool handler's `ctx.signal` fires.
|
|
636
|
+
also sends `McpCancel` to a host advertising `mcp-cancel`, so the tool handler's `ctx.signal` fires. The Rust `wsh-server`
|
|
637
|
+
advertises it from `rust-v0.6.0`: it drops the call's task and kills the tool's process group, and offers CLI tools
|
|
638
|
+
from `[[mcp.tools]]` entries in its `config.toml`.
|
|
622
639
|
|
|
623
640
|
### MCP tools
|
|
624
641
|
|
package/package.json
CHANGED
package/src/memory-host.d.ts
CHANGED
|
@@ -1,10 +1,30 @@
|
|
|
1
|
-
import type { WshClient } from './index.js';
|
|
1
|
+
import type { WshClient, RpcChannel } from './index.js';
|
|
2
2
|
import type { WshSigner } from './index.js';
|
|
3
3
|
import type {
|
|
4
4
|
WshServerAuthOptions, WshServerPrincipal, WshServerMcpOptions, WshExecRunner, WshServerOptions,
|
|
5
5
|
WshAcceptableSocket, WshAcceptOptions,
|
|
6
6
|
} from './server/index.js';
|
|
7
7
|
|
|
8
|
+
export interface WshMemorySessionsOptions {
|
|
9
|
+
/** How long a session nobody is attached to keeps running (default 300000; 0 = kill at once). */
|
|
10
|
+
detachTtlMs?: number;
|
|
11
|
+
/** Unattended sessions kept at once (default 16); beyond that the longest-detached is killed. */
|
|
12
|
+
maxDetached?: number;
|
|
13
|
+
/** Output history kept per session, i.e. what a resume can replay (default 1048576 bytes). */
|
|
14
|
+
ringBytes?: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** What an rpc handler is told about its channel. */
|
|
18
|
+
export interface WshMemoryRpcContext {
|
|
19
|
+
protocol: string;
|
|
20
|
+
channelId: number;
|
|
21
|
+
user: string | null;
|
|
22
|
+
fingerprint: string | null;
|
|
23
|
+
features: string[];
|
|
24
|
+
log(line: string): void;
|
|
25
|
+
[key: string]: unknown;
|
|
26
|
+
}
|
|
27
|
+
|
|
8
28
|
export interface WshMemoryHostOptions {
|
|
9
29
|
/** As for `createWshServer`. Omitted = refuse everyone. */
|
|
10
30
|
auth?: WshServerAuthOptions | ((who: WshServerPrincipal) => boolean | Promise<boolean>);
|
|
@@ -12,6 +32,17 @@ export interface WshMemoryHostOptions {
|
|
|
12
32
|
exec?: WshExecRunner | { run: WshExecRunner; timeoutMs?: number; clientEnv?: boolean };
|
|
13
33
|
mcp?: WshServerMcpOptions;
|
|
14
34
|
extensions?: WshServerOptions['extensions'];
|
|
35
|
+
/** Typed RPC channels: one handler per protocol, called once per opened channel to register methods. Handler functions only (the `wsh-host` / `wsh-fs` built-ins need Node). Off unless given. */
|
|
36
|
+
rpc?: Record<string, ((channel: RpcChannel, ctx: WshMemoryRpcContext) => void | Promise<void>) | false | null | undefined>;
|
|
37
|
+
/** Largest single rpc message (default 1048576; at least 256). */
|
|
38
|
+
rpcMaxMessageBytes?: number;
|
|
39
|
+
/** Concurrent requests per rpc channel before `-32002` (default 64). */
|
|
40
|
+
rpcMaxInflight?: number;
|
|
41
|
+
/**
|
|
42
|
+
* Keep exec sessions alive across disconnects so `resumeSession()` / `attachSession()` work, with the same
|
|
43
|
+
* defaults as `createWshServer`. `true` for the defaults. Off unless given.
|
|
44
|
+
*/
|
|
45
|
+
sessions?: true | false | null | WshMemorySessionsOptions;
|
|
15
46
|
bindTimeoutMs?: number;
|
|
16
47
|
onLog?: (line: string) => void;
|
|
17
48
|
}
|
package/src/memory-host.mjs
CHANGED
|
@@ -6,8 +6,10 @@
|
|
|
6
6
|
* It is the real protocol end to end -- the same connection handler `createWshServer` runs (handshake, Ed25519 or
|
|
7
7
|
* password auth, exec channels, MCP tools, extensions), speaking QMux over a pair of in-memory WebSocket-like
|
|
8
8
|
* sockets -- so what a client does here is what it does against a server. It serves what a browser can: `exec` as a
|
|
9
|
-
* function you provide (there is no shell), `mcp` tools, `extensions
|
|
10
|
-
* `sessions
|
|
9
|
+
* function you provide (there is no shell), `mcp` tools, `extensions`, typed `rpc` channels (handler functions you
|
|
10
|
+
* provide) and `sessions` (detach / attach / resume of exec sessions, output replayed from an in-memory ring buffer).
|
|
11
|
+
* Not available: `pty`, `fs`, `gateway`, `relay`, `hostKey`, WebTransport, the `wsh-host` / `wsh-fs` rpc built-ins
|
|
12
|
+
* (they need Node; use `@johnhenry/wsh/server`).
|
|
11
13
|
*
|
|
12
14
|
* ```js
|
|
13
15
|
* import { createMemoryHost } from '@johnhenry/wsh/memory';
|
|
@@ -25,6 +27,8 @@ import { createConnectionFactory } from './server/connection.mjs';
|
|
|
25
27
|
import { buildAuthorizer, authMethods, FailureLimiter } from './server/auth.mjs';
|
|
26
28
|
import { createMcpHost } from './server/mcp.mjs';
|
|
27
29
|
import { bindSocket } from './server/socket.mjs';
|
|
30
|
+
import { RPC_PROTOCOL_NAME_RE, RPC_DEFAULT_MAX_MESSAGE } from './rpc.mjs';
|
|
31
|
+
import { SessionRegistry, DEFAULT_RING_BYTES, DEFAULT_DETACH_TTL_MS, DEFAULT_MAX_DETACHED } from './session-registry.mjs';
|
|
28
32
|
|
|
29
33
|
const CONNECTING = 0;
|
|
30
34
|
const OPEN = 1;
|
|
@@ -90,6 +94,31 @@ export function createSocketPair() {
|
|
|
90
94
|
return [a, b];
|
|
91
95
|
}
|
|
92
96
|
|
|
97
|
+
/** Validate the `rpc` option into the table the connection handler reads (`createRpcHost` in `server/rpc.mjs` minus the Node-only built-ins). */
|
|
98
|
+
function createRpcTable(rpc, maxMessageBytes, maxInflight) {
|
|
99
|
+
if (typeof rpc !== 'object' || Array.isArray(rpc)) throw new TypeError('createMemoryHost: rpc must be an object of { [protocol]: handler }');
|
|
100
|
+
if (!(maxMessageBytes >= 256)) throw new TypeError('createMemoryHost: rpcMaxMessageBytes must be at least 256');
|
|
101
|
+
if (!Number.isSafeInteger(maxInflight) || maxInflight < 1) throw new TypeError('createMemoryHost: rpcMaxInflight must be a positive integer');
|
|
102
|
+
const protocols = new Map();
|
|
103
|
+
for (const [name, handler] of Object.entries(rpc)) {
|
|
104
|
+
if (handler === undefined || handler === false || handler === null) continue;
|
|
105
|
+
if (!RPC_PROTOCOL_NAME_RE.test(name)) throw new TypeError(`createMemoryHost: rpc protocol name ${JSON.stringify(name)} is not allowed (letters, digits, ".", "_", "-")`);
|
|
106
|
+
if (typeof handler !== 'function') throw new TypeError(`createMemoryHost: rpc[${JSON.stringify(name)}] needs a handler function (channel, ctx) => void (the wsh-host / wsh-fs built-ins need Node; use @johnhenry/wsh/server)`);
|
|
107
|
+
protocols.set(name, handler);
|
|
108
|
+
}
|
|
109
|
+
return { protocols, maxMessageBytes, maxInflight };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function createRegistry(sessions, log) {
|
|
113
|
+
const o = sessions === true ? {} : sessions;
|
|
114
|
+
if (typeof o !== 'object' || Array.isArray(o)) throw new TypeError('createMemoryHost: sessions must be true or { detachTtlMs, maxDetached, ringBytes }');
|
|
115
|
+
const { detachTtlMs = DEFAULT_DETACH_TTL_MS, maxDetached = DEFAULT_MAX_DETACHED, ringBytes = DEFAULT_RING_BYTES } = o;
|
|
116
|
+
if (!(Number.isFinite(detachTtlMs) && detachTtlMs >= 0)) throw new TypeError('createMemoryHost: sessions.detachTtlMs must be a non-negative number');
|
|
117
|
+
if (!Number.isSafeInteger(maxDetached) || maxDetached < 0) throw new TypeError('createMemoryHost: sessions.maxDetached must be a non-negative integer');
|
|
118
|
+
if (!Number.isSafeInteger(ringBytes) || ringBytes < 1) throw new TypeError('createMemoryHost: sessions.ringBytes must be a positive integer');
|
|
119
|
+
return new SessionRegistry({ detachTtlMs, maxDetached, ringBytes, log });
|
|
120
|
+
}
|
|
121
|
+
|
|
93
122
|
/**
|
|
94
123
|
* @param {object} [options]
|
|
95
124
|
* @param {object | Function} [options.auth] - As for `createWshServer`. Omitted = refuse everyone.
|
|
@@ -97,15 +126,26 @@ export function createSocketPair() {
|
|
|
97
126
|
* `run(command, io) => Promise<exitCode>` (see `ExecIo` in `server/exec.mjs`): the host has no shell, so there is no `true`.
|
|
98
127
|
* @param {{ tools?: object[] | object, client?: object, authorize?: Function, maxConcurrent?: number, timeoutMs?: number }} [options.mcp]
|
|
99
128
|
* @param {Record<string, Function>} [options.extensions] - Handlers for application-defined messages, as for `createWshServer`.
|
|
129
|
+
* @param {Record<string, Function>} [options.rpc] - Typed RPC channels: `{ [protocol]: (channel, ctx) => void | Promise<void> }`,
|
|
130
|
+
* a handler per protocol that registers methods on an `RpcChannel`. Off unless given. Handler functions only (no built-ins).
|
|
131
|
+
* @param {number} [options.rpcMaxMessageBytes=1048576] - Largest single rpc message (advertised as `rpc-max-message:<n>`; at least 256).
|
|
132
|
+
* @param {number} [options.rpcMaxInflight=64] - Concurrent requests per rpc channel before `-32002`.
|
|
133
|
+
* @param {true | { detachTtlMs?: number, maxDetached?: number, ringBytes?: number }} [options.sessions]
|
|
134
|
+
* Keep exec sessions alive across disconnects so a client can `resumeSession()` / `attachSession()`: as for
|
|
135
|
+
* `createWshServer`, with the same defaults (300000 ms detached, 16 detached sessions, 1 MiB of replayable output
|
|
136
|
+
* per session). Off unless given: sessions then die with their connection. There is no `sessionSecret`: session
|
|
137
|
+
* tokens are random per session.
|
|
100
138
|
* @param {number} [options.bindTimeoutMs=3000]
|
|
101
139
|
* @param {(line: string) => void} [options.onLog]
|
|
102
140
|
*/
|
|
103
|
-
export function createMemoryHost({ auth, exec, mcp, extensions, bindTimeoutMs = 3000, onLog = () => {} } = {}) {
|
|
141
|
+
export function createMemoryHost({ auth, exec, mcp, extensions, rpc, rpcMaxMessageBytes = RPC_DEFAULT_MAX_MESSAGE, rpcMaxInflight = 64, sessions, bindTimeoutMs = 3000, onLog = () => {} } = {}) {
|
|
104
142
|
if (exec === true) throw new TypeError('createMemoryHost: exec must be a function (run(command, io)); there is no shell to run `true` with');
|
|
105
143
|
if (exec !== undefined && typeof exec !== 'function' && typeof exec?.run !== 'function') {
|
|
106
144
|
throw new TypeError('createMemoryHost: exec must be a function or { run }');
|
|
107
145
|
}
|
|
108
146
|
if (extensions !== undefined && (extensions === null || typeof extensions !== 'object')) throw new TypeError('createMemoryHost: extensions must be an object of handlers');
|
|
147
|
+
const rpcHost = rpc === undefined || rpc === null ? null : createRpcTable(rpc, rpcMaxMessageBytes, rpcMaxInflight);
|
|
148
|
+
const registry = sessions === undefined || sessions === null || sessions === false ? null : createRegistry(sessions, onLog);
|
|
109
149
|
const execOptions = typeof exec === 'function' || !exec ? {} : exec;
|
|
110
150
|
const execRunner = typeof exec === 'function' ? exec : exec?.run ?? null;
|
|
111
151
|
const rl = auth?.rateLimit ?? {};
|
|
@@ -119,7 +159,7 @@ export function createMemoryHost({ auth, exec, mcp, extensions, bindTimeoutMs =
|
|
|
119
159
|
|
|
120
160
|
const ready = buildAuthorizer(auth).then((authorize) => createConnectionFactory({
|
|
121
161
|
authorize, execRunner, execOptions, pty: null, files: null, bindTimeoutMs, log: onLog,
|
|
122
|
-
methods, hostKey: null, rateLimit, extensions, mcp: mcpHost, rpc:
|
|
162
|
+
methods, hostKey: null, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, gateway: null, sessions: registry, relay: null,
|
|
123
163
|
}));
|
|
124
164
|
ready.catch(() => {});
|
|
125
165
|
|
|
@@ -169,6 +209,7 @@ export function createMemoryHost({ auth, exec, mcp, extensions, bindTimeoutMs =
|
|
|
169
209
|
closed = true;
|
|
170
210
|
for (const handle of accepted) handle.close();
|
|
171
211
|
accepted.clear();
|
|
212
|
+
registry?.closeAll();
|
|
172
213
|
},
|
|
173
214
|
};
|
|
174
215
|
return host;
|
package/src/server/sessions.mjs
CHANGED
|
@@ -2,81 +2,17 @@
|
|
|
2
2
|
* Session registry for `@johnhenry/wsh/server`: what lets an exec/pty session
|
|
3
3
|
* outlive the connection that opened it (`createWshServer({ sessions })`).
|
|
4
4
|
*
|
|
5
|
-
* The
|
|
6
|
-
*
|
|
7
|
-
* appended to the session's ring buffer and fanned out to every attachment,
|
|
8
|
-
* so when a socket drops the process keeps running and its newest output keeps
|
|
9
|
-
* accumulating until `detachTtlMs` elapses or a client resumes.
|
|
10
|
-
*
|
|
11
|
-
* `seq` -- the one design question the wire does not answer -- is defined as
|
|
12
|
-
* the cumulative count of output BYTES the host has produced for a session.
|
|
13
|
-
* A client counts what it has received (it sees every byte), passes that as
|
|
14
|
-
* `Resume.last_seq`, and the host replays `ring[last_seq - ringStart ..]`.
|
|
15
|
-
* See spec/wsh-v1.yaml (`Resume`, `AttachmentInfo`).
|
|
5
|
+
* The store itself (ring buffer, attachments, TTL, eviction) lives in `../session-registry.mjs`, which has no Node
|
|
6
|
+
* dependency so the in-memory host can use it too. This file adds HMAC-signed session tokens (`node:crypto`).
|
|
16
7
|
*/
|
|
17
8
|
|
|
18
|
-
import { createHmac, randomBytes,
|
|
9
|
+
import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
10
|
+
import { SessionRegistry as CoreSessionRegistry } from '../session-registry.mjs';
|
|
19
11
|
|
|
20
|
-
export
|
|
21
|
-
export const DEFAULT_DETACH_TTL_MS = 300_000;
|
|
22
|
-
export const DEFAULT_MAX_DETACHED = 16;
|
|
23
|
-
import { MAX_ATTACHMENTS } from './constants.mjs';
|
|
24
|
-
export { MAX_ATTACHMENTS };
|
|
12
|
+
export { ByteRing, HostedSession, DEFAULT_RING_BYTES, DEFAULT_DETACH_TTL_MS, DEFAULT_MAX_DETACHED, MAX_ATTACHMENTS } from '../session-registry.mjs';
|
|
25
13
|
|
|
26
14
|
const NO_EXPIRY = Buffer.alloc(8, 0xff);
|
|
27
15
|
|
|
28
|
-
/**
|
|
29
|
-
* A bounded byte history addressed by absolute stream position.
|
|
30
|
-
* `start` is the seq of the oldest retained byte, `end` the seq one past the newest.
|
|
31
|
-
*/
|
|
32
|
-
export class ByteRing {
|
|
33
|
-
#chunks = [];
|
|
34
|
-
#size = 0;
|
|
35
|
-
start = 0;
|
|
36
|
-
end = 0;
|
|
37
|
-
|
|
38
|
-
constructor(maxBytes) {
|
|
39
|
-
this.max = maxBytes;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
push(bytes) {
|
|
43
|
-
if (!bytes.byteLength) return;
|
|
44
|
-
this.#chunks.push(Uint8Array.from(bytes));
|
|
45
|
-
this.#size += bytes.byteLength;
|
|
46
|
-
this.end += bytes.byteLength;
|
|
47
|
-
while (this.#size > this.max) {
|
|
48
|
-
const excess = this.#size - this.max;
|
|
49
|
-
const first = this.#chunks[0];
|
|
50
|
-
if (first.byteLength <= excess) {
|
|
51
|
-
this.#chunks.shift();
|
|
52
|
-
this.#size -= first.byteLength;
|
|
53
|
-
this.start += first.byteLength;
|
|
54
|
-
} else {
|
|
55
|
-
this.#chunks[0] = first.subarray(excess);
|
|
56
|
-
this.#size -= excess;
|
|
57
|
-
this.start += excess;
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
/** Bytes from absolute position `from` (clamped to `start`) to the end. */
|
|
63
|
-
read(from = this.start) {
|
|
64
|
-
const skip = Math.max(0, from - this.start);
|
|
65
|
-
const out = new Uint8Array(Math.max(0, this.#size - skip));
|
|
66
|
-
let at = 0;
|
|
67
|
-
let seen = 0;
|
|
68
|
-
for (const c of this.#chunks) {
|
|
69
|
-
if (seen + c.byteLength > skip) {
|
|
70
|
-
const part = c.subarray(Math.max(0, skip - seen));
|
|
71
|
-
out.set(part, at);
|
|
72
|
-
at += part.byteLength;
|
|
73
|
-
}
|
|
74
|
-
seen += c.byteLength;
|
|
75
|
-
}
|
|
76
|
-
return out;
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
|
|
80
16
|
/**
|
|
81
17
|
* Mint a session token in the spec's format: `[8B expiry][32B HMAC-SHA256(secret, session_id || expiry)]`.
|
|
82
18
|
* A session's lifetime is governed by `detachTtlMs`, not by its token, so the expiry is the maximum.
|
|
@@ -96,169 +32,13 @@ export function verifyToken(secret, sessionId, token) {
|
|
|
96
32
|
return timingSafeEqual(want, buf.subarray(8));
|
|
97
33
|
}
|
|
98
34
|
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
* @property {number} connId
|
|
103
|
-
* @property {number} channelId
|
|
104
|
-
* @property {'control' | 'readonly'} mode
|
|
105
|
-
* @property {string} username
|
|
106
|
-
* @property {string} principal - who this connection authenticated as (see `principalKey`)
|
|
107
|
-
* @property {(bytes: Uint8Array) => unknown} write - live output
|
|
108
|
-
* @property {(msg: object) => unknown} notify - an ordered control message (e.g. Presence)
|
|
109
|
-
* @property {(code: number) => unknown} exit - the session ended
|
|
110
|
-
*/
|
|
111
|
-
|
|
112
|
-
export class HostedSession {
|
|
113
|
-
/** @type {Set<Attachment>} */
|
|
114
|
-
attachments = new Set();
|
|
115
|
-
state = 'attached';
|
|
116
|
-
exitCode = null;
|
|
117
|
-
createdAt = Date.now();
|
|
118
|
-
lastActivity = Date.now();
|
|
119
|
-
detachedAt = 0;
|
|
120
|
-
name;
|
|
121
|
-
#timer = null;
|
|
122
|
-
|
|
123
|
-
constructor(registry, { id, token, owner, kind, command, ringBytes }) {
|
|
124
|
-
this.registry = registry;
|
|
125
|
-
this.id = id;
|
|
126
|
-
this.token = token;
|
|
127
|
-
this.owner = owner;
|
|
128
|
-
this.kind = kind;
|
|
129
|
-
this.command = command;
|
|
130
|
-
this.ring = new ByteRing(ringBytes);
|
|
131
|
-
/** Set by the connection once the process exists: `{ input, inputEnd, resize, signal, kill }`. */
|
|
132
|
-
this.handlers = {};
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
/** Output from the process: retained in the ring, delivered to every attachment. */
|
|
136
|
-
push(bytes) {
|
|
137
|
-
this.lastActivity = Date.now();
|
|
138
|
-
this.ring.push(bytes);
|
|
139
|
-
for (const a of this.attachments) a.write(bytes);
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
attach(att) {
|
|
143
|
-
this.attachments.add(att);
|
|
144
|
-
this.state = 'attached';
|
|
145
|
-
this.#clearTimer();
|
|
146
|
-
this.broadcastPresence(att);
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
detach(att) {
|
|
150
|
-
if (!this.attachments.delete(att)) return;
|
|
151
|
-
this.broadcastPresence();
|
|
152
|
-
if (this.attachments.size === 0) this.#markDetached();
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
roster() {
|
|
156
|
-
return [...this.attachments].map((a) => ({ session_id: this.id, mode: a.mode, username: a.username }));
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
/** Tell every attachment (except `except`) who is attached now. */
|
|
160
|
-
broadcastPresence(except) {
|
|
161
|
-
if (this.attachments.size === 0) return;
|
|
162
|
-
const msg = { attachments: this.roster() };
|
|
163
|
-
for (const a of this.attachments) if (a !== except) a.notify(msg);
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
/** The process ended. Everyone attached hears Exit + Close; the record lingers for late resumes. */
|
|
167
|
-
finish(code) {
|
|
168
|
-
if (this.state === 'exited') return;
|
|
169
|
-
this.exitCode = code;
|
|
170
|
-
this.state = 'exited';
|
|
171
|
-
const att = [...this.attachments];
|
|
172
|
-
this.attachments.clear();
|
|
173
|
-
for (const a of att) a.exit(code);
|
|
174
|
-
this.#markDetached();
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
kill() {
|
|
178
|
-
try { this.handlers.kill?.(); } catch { /* already gone */ }
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
/** Forget the session (and stop it if it is still running). */
|
|
182
|
-
dispose() {
|
|
183
|
-
this.#clearTimer();
|
|
184
|
-
this.registry._forget(this);
|
|
185
|
-
if (this.state !== 'exited') {
|
|
186
|
-
this.kill();
|
|
187
|
-
this.state = 'exited';
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
#markDetached() {
|
|
192
|
-
this.detachedAt = Date.now();
|
|
193
|
-
if (this.state !== 'exited') this.state = 'detached';
|
|
194
|
-
this.#clearTimer();
|
|
195
|
-
const ttl = this.registry.detachTtlMs;
|
|
196
|
-
if (ttl <= 0) { this.dispose(); return; }
|
|
197
|
-
this.#timer = setTimeout(() => {
|
|
198
|
-
this.registry.log(`session ${this.id} expired after ${ttl}ms detached`);
|
|
199
|
-
this.dispose();
|
|
200
|
-
}, ttl);
|
|
201
|
-
this.#timer.unref?.();
|
|
202
|
-
this.registry._enforceMaxDetached(this);
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
#clearTimer() {
|
|
206
|
-
clearTimeout(this.#timer);
|
|
207
|
-
this.#timer = null;
|
|
208
|
-
}
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
export class SessionRegistry {
|
|
212
|
-
/** @type {Map<string, HostedSession>} */
|
|
213
|
-
#sessions = new Map();
|
|
214
|
-
|
|
215
|
-
constructor({ secret, detachTtlMs = DEFAULT_DETACH_TTL_MS, maxDetached = DEFAULT_MAX_DETACHED, ringBytes = DEFAULT_RING_BYTES, log = () => {} } = {}) {
|
|
35
|
+
export class SessionRegistry extends CoreSessionRegistry {
|
|
36
|
+
constructor({ secret, ...rest } = {}) {
|
|
37
|
+
super(rest);
|
|
216
38
|
this.secret = secret ?? randomBytes(32);
|
|
217
|
-
this.detachTtlMs = detachTtlMs;
|
|
218
|
-
this.maxDetached = maxDetached;
|
|
219
|
-
this.ringBytes = ringBytes;
|
|
220
|
-
this.log = log;
|
|
221
39
|
}
|
|
222
40
|
|
|
223
|
-
|
|
224
|
-
create({ owner, kind, command }) {
|
|
225
|
-
const id = randomUUID();
|
|
226
|
-
const s = new HostedSession(this, { id, token: mintToken(this.secret, id), owner, kind, command, ringBytes: this.ringBytes });
|
|
227
|
-
this.#sessions.set(id, s);
|
|
228
|
-
return s;
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
get(id) {
|
|
232
|
-
return typeof id === 'string' ? this.#sessions.get(id) : undefined;
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
checkToken(session, token) {
|
|
236
|
-
return verifyToken(this.secret, session.id, token);
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
/** Sessions this principal owns. */
|
|
240
|
-
listFor(principal) {
|
|
241
|
-
return [...this.#sessions.values()].filter((s) => s.owner.principal === principal);
|
|
242
|
-
}
|
|
41
|
+
mintToken(sessionId) { return mintToken(this.secret, sessionId); }
|
|
243
42
|
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
/** Kill everything (server shutdown). */
|
|
247
|
-
closeAll() {
|
|
248
|
-
for (const s of [...this.#sessions.values()]) s.dispose();
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
_forget(session) {
|
|
252
|
-
this.#sessions.delete(session.id);
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
/** Keep at most `maxDetached` unattended sessions: the longest-detached are killed first. */
|
|
256
|
-
_enforceMaxDetached() {
|
|
257
|
-
const detached = [...this.#sessions.values()].filter((s) => s.attachments.size === 0).sort((a, b) => a.detachedAt - b.detachedAt);
|
|
258
|
-
while (detached.length > this.maxDetached) {
|
|
259
|
-
const victim = detached.shift();
|
|
260
|
-
this.log(`session ${victim.id} evicted (more than ${this.maxDetached} detached)`);
|
|
261
|
-
victim.dispose();
|
|
262
|
-
}
|
|
263
|
-
}
|
|
43
|
+
checkToken(session, token) { return verifyToken(this.secret, session.id, token); }
|
|
264
44
|
}
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The session store behind `createWshServer({ sessions })` and `createMemoryHost({ sessions })`: what lets an exec/pty
|
|
3
|
+
* session outlive the connection that opened it. Imports nothing from `node:*` (a test keeps `src/memory-host.mjs`
|
|
4
|
+
* honest), so a browser frame can host sessions too. `server/sessions.mjs` adds the Node-only part: HMAC session tokens.
|
|
5
|
+
*
|
|
6
|
+
* The registry is per host and holds a `HostedSession` for every session. A connection's channel is an *attachment*
|
|
7
|
+
* to one: output is appended to the session's ring buffer and fanned out to every attachment, so when a socket drops
|
|
8
|
+
* the process keeps running and its newest output keeps accumulating until `detachTtlMs` elapses or a client resumes.
|
|
9
|
+
*
|
|
10
|
+
* `seq` -- the one design question the wire does not answer -- is the cumulative count of output BYTES the host has
|
|
11
|
+
* produced for a session. A client counts what it has received, passes that as `Resume.last_seq`, and the host replays
|
|
12
|
+
* `ring[last_seq - ringStart ..]`. See spec/wsh-v1.yaml (`Resume`, `AttachmentInfo`).
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export const DEFAULT_RING_BYTES = 1024 * 1024;
|
|
16
|
+
export const DEFAULT_DETACH_TTL_MS = 300_000;
|
|
17
|
+
export const DEFAULT_MAX_DETACHED = 16;
|
|
18
|
+
import { MAX_ATTACHMENTS } from './server/constants.mjs';
|
|
19
|
+
export { MAX_ATTACHMENTS };
|
|
20
|
+
|
|
21
|
+
const NO_EXPIRY = new Uint8Array(8).fill(0xff);
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* A bounded byte history addressed by absolute stream position.
|
|
25
|
+
* `start` is the seq of the oldest retained byte, `end` the seq one past the newest.
|
|
26
|
+
*/
|
|
27
|
+
export class ByteRing {
|
|
28
|
+
#chunks = [];
|
|
29
|
+
#size = 0;
|
|
30
|
+
start = 0;
|
|
31
|
+
end = 0;
|
|
32
|
+
|
|
33
|
+
constructor(maxBytes) {
|
|
34
|
+
this.max = maxBytes;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
push(bytes) {
|
|
38
|
+
if (!bytes.byteLength) return;
|
|
39
|
+
this.#chunks.push(Uint8Array.from(bytes));
|
|
40
|
+
this.#size += bytes.byteLength;
|
|
41
|
+
this.end += bytes.byteLength;
|
|
42
|
+
while (this.#size > this.max) {
|
|
43
|
+
const excess = this.#size - this.max;
|
|
44
|
+
const first = this.#chunks[0];
|
|
45
|
+
if (first.byteLength <= excess) {
|
|
46
|
+
this.#chunks.shift();
|
|
47
|
+
this.#size -= first.byteLength;
|
|
48
|
+
this.start += first.byteLength;
|
|
49
|
+
} else {
|
|
50
|
+
this.#chunks[0] = first.subarray(excess);
|
|
51
|
+
this.#size -= excess;
|
|
52
|
+
this.start += excess;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Bytes from absolute position `from` (clamped to `start`) to the end. */
|
|
58
|
+
read(from = this.start) {
|
|
59
|
+
const skip = Math.max(0, from - this.start);
|
|
60
|
+
const out = new Uint8Array(Math.max(0, this.#size - skip));
|
|
61
|
+
let at = 0;
|
|
62
|
+
let seen = 0;
|
|
63
|
+
for (const c of this.#chunks) {
|
|
64
|
+
if (seen + c.byteLength > skip) {
|
|
65
|
+
const part = c.subarray(Math.max(0, skip - seen));
|
|
66
|
+
out.set(part, at);
|
|
67
|
+
at += part.byteLength;
|
|
68
|
+
}
|
|
69
|
+
seen += c.byteLength;
|
|
70
|
+
}
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* One attached connection's view of a session; `connection.mjs` builds them.
|
|
77
|
+
* @typedef {object} Attachment
|
|
78
|
+
* @property {number} connId
|
|
79
|
+
* @property {number} channelId
|
|
80
|
+
* @property {'control' | 'readonly'} mode
|
|
81
|
+
* @property {string} username
|
|
82
|
+
* @property {string} principal - who this connection authenticated as (see `principalKey`)
|
|
83
|
+
* @property {(bytes: Uint8Array) => unknown} write - live output
|
|
84
|
+
* @property {(msg: object) => unknown} notify - an ordered control message (e.g. Presence)
|
|
85
|
+
* @property {(code: number) => unknown} exit - the session ended
|
|
86
|
+
*/
|
|
87
|
+
|
|
88
|
+
export class HostedSession {
|
|
89
|
+
/** @type {Set<Attachment>} */
|
|
90
|
+
attachments = new Set();
|
|
91
|
+
state = 'attached';
|
|
92
|
+
/** Set by `dispose()`: a disposed session never arms a timer again. */
|
|
93
|
+
disposed = false;
|
|
94
|
+
exitCode = null;
|
|
95
|
+
createdAt = Date.now();
|
|
96
|
+
lastActivity = Date.now();
|
|
97
|
+
detachedAt = 0;
|
|
98
|
+
name;
|
|
99
|
+
#timer = null;
|
|
100
|
+
|
|
101
|
+
constructor(registry, { id, token, owner, kind, command, ringBytes }) {
|
|
102
|
+
this.registry = registry;
|
|
103
|
+
this.id = id;
|
|
104
|
+
this.token = token;
|
|
105
|
+
this.owner = owner;
|
|
106
|
+
this.kind = kind;
|
|
107
|
+
this.command = command;
|
|
108
|
+
this.ring = new ByteRing(ringBytes);
|
|
109
|
+
/** Set by the connection once the process exists: `{ input, inputEnd, resize, signal, kill }`. */
|
|
110
|
+
this.handlers = {};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Output from the process: retained in the ring, delivered to every attachment. */
|
|
114
|
+
push(bytes) {
|
|
115
|
+
this.lastActivity = Date.now();
|
|
116
|
+
this.ring.push(bytes);
|
|
117
|
+
for (const a of this.attachments) a.write(bytes);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
attach(att) {
|
|
121
|
+
this.attachments.add(att);
|
|
122
|
+
this.state = 'attached';
|
|
123
|
+
this.#clearTimer();
|
|
124
|
+
this.broadcastPresence(att);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
detach(att) {
|
|
128
|
+
if (!this.attachments.delete(att)) return;
|
|
129
|
+
this.broadcastPresence();
|
|
130
|
+
if (this.attachments.size === 0) this.#markDetached();
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
roster() {
|
|
134
|
+
return [...this.attachments].map((a) => ({ session_id: this.id, mode: a.mode, username: a.username }));
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Tell every attachment (except `except`) who is attached now. */
|
|
138
|
+
broadcastPresence(except) {
|
|
139
|
+
if (this.attachments.size === 0) return;
|
|
140
|
+
const msg = { attachments: this.roster() };
|
|
141
|
+
for (const a of this.attachments) if (a !== except) a.notify(msg);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** The process ended. Everyone attached hears Exit + Close; the record lingers for late resumes. */
|
|
145
|
+
finish(code) {
|
|
146
|
+
if (this.state === 'exited') return;
|
|
147
|
+
this.exitCode = code;
|
|
148
|
+
this.state = 'exited';
|
|
149
|
+
const att = [...this.attachments];
|
|
150
|
+
this.attachments.clear();
|
|
151
|
+
for (const a of att) a.exit(code);
|
|
152
|
+
this.#markDetached();
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
kill() {
|
|
156
|
+
try { this.handlers.kill?.(); } catch { /* already gone */ }
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Forget the session (and stop it if it is still running). */
|
|
160
|
+
dispose() {
|
|
161
|
+
this.disposed = true;
|
|
162
|
+
this.#clearTimer();
|
|
163
|
+
this.registry._forget(this);
|
|
164
|
+
if (this.state !== 'exited') {
|
|
165
|
+
this.kill();
|
|
166
|
+
this.state = 'exited';
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
#markDetached() {
|
|
171
|
+
if (this.disposed) return;
|
|
172
|
+
this.detachedAt = Date.now();
|
|
173
|
+
if (this.state !== 'exited') this.state = 'detached';
|
|
174
|
+
this.#clearTimer();
|
|
175
|
+
const ttl = this.registry.detachTtlMs;
|
|
176
|
+
if (ttl <= 0) { this.dispose(); return; }
|
|
177
|
+
this.#timer = setTimeout(() => {
|
|
178
|
+
this.registry.log(`session ${this.id} expired after ${ttl}ms detached`);
|
|
179
|
+
this.dispose();
|
|
180
|
+
}, ttl);
|
|
181
|
+
this.#timer.unref?.();
|
|
182
|
+
this.registry._enforceMaxDetached(this);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
#clearTimer() {
|
|
186
|
+
clearTimeout(this.#timer);
|
|
187
|
+
this.#timer = null;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export class SessionRegistry {
|
|
192
|
+
/** @type {Map<string, HostedSession>} */
|
|
193
|
+
#sessions = new Map();
|
|
194
|
+
|
|
195
|
+
constructor({ detachTtlMs = DEFAULT_DETACH_TTL_MS, maxDetached = DEFAULT_MAX_DETACHED, ringBytes = DEFAULT_RING_BYTES, log = () => {} } = {}) {
|
|
196
|
+
this.detachTtlMs = detachTtlMs;
|
|
197
|
+
this.maxDetached = maxDetached;
|
|
198
|
+
this.ringBytes = ringBytes;
|
|
199
|
+
this.log = log;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** @param {{ owner: { username: string, principal: string, fingerprint: string | null }, kind: 'pty' | 'exec', command?: string }} spec */
|
|
203
|
+
create({ owner, kind, command }) {
|
|
204
|
+
const id = globalThis.crypto.randomUUID();
|
|
205
|
+
const s = new HostedSession(this, { id, token: this.mintToken(id), owner, kind, command, ringBytes: this.ringBytes });
|
|
206
|
+
this.#sessions.set(id, s);
|
|
207
|
+
return s;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
get(id) {
|
|
211
|
+
return typeof id === 'string' ? this.#sessions.get(id) : undefined;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** A session token in the spec's format: `[8B expiry][32B secret]` (expiry is the maximum: `detachTtlMs` governs life). */
|
|
215
|
+
mintToken(_sessionId) {
|
|
216
|
+
const token = new Uint8Array(40);
|
|
217
|
+
token.set(NO_EXPIRY, 0);
|
|
218
|
+
globalThis.crypto.getRandomValues(token.subarray(8));
|
|
219
|
+
return token;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Constant-time check of a presented token against the one minted for this session. */
|
|
223
|
+
checkToken(session, token) {
|
|
224
|
+
if (!(token instanceof Uint8Array) || token.byteLength !== 40 || session.token.byteLength !== 40) return false;
|
|
225
|
+
let diff = 0;
|
|
226
|
+
for (let i = 0; i < 40; i++) diff |= token[i] ^ session.token[i];
|
|
227
|
+
return diff === 0;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** Sessions this principal owns. */
|
|
231
|
+
listFor(principal) {
|
|
232
|
+
return [...this.#sessions.values()].filter((s) => s.owner.principal === principal);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
get size() { return this.#sessions.size; }
|
|
236
|
+
|
|
237
|
+
/** Kill everything (server shutdown). */
|
|
238
|
+
closeAll() {
|
|
239
|
+
for (const s of [...this.#sessions.values()]) s.dispose();
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
_forget(session) {
|
|
243
|
+
this.#sessions.delete(session.id);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Keep at most `maxDetached` unattended sessions: the longest-detached are killed first. */
|
|
247
|
+
_enforceMaxDetached() {
|
|
248
|
+
const detached = [...this.#sessions.values()].filter((s) => s.attachments.size === 0).sort((a, b) => a.detachedAt - b.detachedAt);
|
|
249
|
+
while (detached.length > this.maxDetached) {
|
|
250
|
+
const victim = detached.shift();
|
|
251
|
+
this.log(`session ${victim.id} evicted (more than ${this.maxDetached} detached)`);
|
|
252
|
+
victim.dispose();
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|