@johnhenry/wsh 0.34.2 → 0.36.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 +121 -8
- package/package.json +14 -1
- package/src/client.mjs +3 -22
- package/src/features.mjs +28 -0
- package/src/host-backends.mjs +100 -0
- package/src/host.d.ts +146 -0
- package/src/host.mjs +30 -0
- package/src/memory-host.d.ts +50 -2
- package/src/memory-host.mjs +72 -11
- package/src/reverse-host.d.ts +25 -0
- package/src/reverse-host.mjs +228 -0
- package/src/server/backends.mjs +10 -16
- package/src/server/connection.mjs +37 -13
- package/src/server/constants.mjs +3 -0
- package/src/server/fs.mjs +2 -3
- package/src/server/index.d.ts +6 -0
- package/src/server/index.mjs +2 -2
- package/src/server/reverse-host.mjs +7 -213
- package/src/server/sessions.mjs +10 -230
- package/src/server/socket.mjs +25 -4
- package/src/session-registry.mjs +255 -0
|
@@ -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
|
+
}
|