@johnhenry/wsh 0.35.0 → 0.37.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 +453 -21
- package/package.json +18 -1
- package/src/bridge-seal.mjs +77 -0
- package/src/channel-binding.mjs +124 -0
- package/src/client.mjs +351 -62
- package/src/e2e-exchange.mjs +51 -1
- package/src/features.mjs +28 -0
- package/src/forward-node.mjs +118 -0
- package/src/gateway-channel.mjs +250 -0
- package/src/gateway-client.mjs +252 -0
- package/src/host-backends.mjs +100 -0
- package/src/host.d.ts +146 -0
- package/src/host.mjs +30 -0
- package/src/index.d.ts +114 -0
- package/src/index.mjs +13 -0
- package/src/memory-host.d.ts +34 -3
- package/src/memory-host.mjs +57 -13
- package/src/messages.gen.mjs +59 -7
- package/src/operator-proof.mjs +135 -0
- package/src/pipe-relay.d.ts +49 -0
- package/src/pipe-relay.mjs +274 -0
- package/src/reverse-host.d.ts +25 -0
- package/src/reverse-host.mjs +339 -0
- package/src/server/address-guard.mjs +164 -0
- package/src/server/backends.mjs +10 -16
- package/src/server/client-env.mjs +60 -0
- package/src/server/connection.mjs +100 -23
- package/src/server/constants.mjs +3 -0
- package/src/server/fs.mjs +2 -3
- package/src/server/gateway-core.mjs +188 -0
- package/src/server/gateway.mjs +483 -80
- package/src/server/index.d.ts +103 -5
- package/src/server/index.mjs +25 -4
- package/src/server/pty.mjs +1 -0
- package/src/server/relay.mjs +45 -2
- package/src/server/reverse-host.mjs +7 -213
- package/src/server/socket.mjs +25 -4
- package/src/server/unix-policy.mjs +120 -0
- package/src/server/webtransport.mjs +2 -0
- package/src/transport-ws.mjs +16 -0
- package/src/transport.mjs +11 -0
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The client half of gateway forwarding: `openUnix`, `openEndpoint`, `openTcp` and `listenUnix` on `WshClient`.
|
|
3
|
+
* Browser-safe (no `node:*`): the connections are web streams with backpressure (see `gateway-channel.mjs`);
|
|
4
|
+
* `forward-node.mjs` builds the Node helper `client.forwardUnix()` on top.
|
|
5
|
+
*
|
|
6
|
+
* gateway_ids and listener_ids this client allocates start at 0x40000000, so they cannot collide with the small
|
|
7
|
+
* ids an application that drives the raw gateway messages itself (netway's `GatewayBackend`) hands out; messages for
|
|
8
|
+
* ids this class does not own go on to `client.onGatewayMessage`.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import {
|
|
12
|
+
MSG, openTcp as openTcpMsg, openUdp as openUdpMsg, openUnix as openUnixMsg, openEndpoint as openEndpointMsg, listenUnix as listenUnixMsg,
|
|
13
|
+
listenClose as listenCloseMsg, inboundAccept as inboundAcceptMsg, inboundReject as inboundRejectMsg,
|
|
14
|
+
gatewayData as gatewayDataMsg, gatewayCredit as gatewayCreditMsg, gatewayClose as gatewayCloseMsg,
|
|
15
|
+
} from './messages.mjs';
|
|
16
|
+
import { GatewayChannel, GATEWAY_CREDIT_FEATURE } from './gateway-channel.mjs';
|
|
17
|
+
|
|
18
|
+
const ID_BASE = 0x40000000;
|
|
19
|
+
const ID_LIMIT = 0xffffffff;
|
|
20
|
+
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
21
|
+
const CLIENT_GRACE_MS = 5_000;
|
|
22
|
+
|
|
23
|
+
/** An Error from a GatewayFail / ListenFail: `.code` is the GatewayFail code (4 = refused by policy), `.reason` the host's text. */
|
|
24
|
+
export class GatewayError extends Error {
|
|
25
|
+
constructor(message, code) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.name = 'GatewayError';
|
|
28
|
+
this.code = code;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* @typedef {object} GatewayDuplex
|
|
34
|
+
* @property {ReadableStream<Uint8Array>} readable what the peer sends; read it to keep the peer's credit coming
|
|
35
|
+
* @property {WritableStream<Uint8Array>} writable what you send; each write waits for credit
|
|
36
|
+
* @property {(reason?: string) => void} close half-close: nothing more will be written
|
|
37
|
+
* @property {(reason?: string) => void} destroy tear the connection down now
|
|
38
|
+
* @property {Promise<string | undefined>} closed settles when the connection is over
|
|
39
|
+
*/
|
|
40
|
+
|
|
41
|
+
export class GatewayConnections {
|
|
42
|
+
#send;
|
|
43
|
+
#hasFeature;
|
|
44
|
+
#nextId = ID_BASE;
|
|
45
|
+
/** @type {Map<number, GatewayChannel>} */
|
|
46
|
+
#channels = new Map();
|
|
47
|
+
/** @type {Map<number, { channel: GatewayChannel, resolve: Function, reject: Function, timer: any }>} */
|
|
48
|
+
#opening = new Map();
|
|
49
|
+
/** @type {Map<number, { onConnection: Function, resolve?: Function, reject?: Function, timer?: any, path: string, closed: boolean }>} */
|
|
50
|
+
#listeners = new Map();
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* @param {object} o
|
|
54
|
+
* @param {(msg: object) => Promise<void>} o.send
|
|
55
|
+
* @param {(feature: string) => boolean} o.hasFeature
|
|
56
|
+
*/
|
|
57
|
+
constructor({ send, hasFeature }) {
|
|
58
|
+
this.#send = send;
|
|
59
|
+
this.#hasFeature = hasFeature;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
#id() {
|
|
63
|
+
if (this.#nextId >= ID_LIMIT) throw new Error('gateway ids exhausted on this connection');
|
|
64
|
+
return this.#nextId++;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
#need(feature, what) {
|
|
68
|
+
if (!this.#hasFeature(feature)) throw new GatewayError(`this host does not support ${what} (it did not advertise "${feature}")`, 0);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** @param {{ datagram?: boolean }} [kind] a datagram flow has no half-close: the peer's close ends it */
|
|
72
|
+
#makeChannel(id, { datagram = false } = {}) {
|
|
73
|
+
const channel = new GatewayChannel({
|
|
74
|
+
id,
|
|
75
|
+
credit: this.#hasFeature(GATEWAY_CREDIT_FEATURE),
|
|
76
|
+
// After the peer's GatewayClose the application has this long to finish writing (a half-open connection) before
|
|
77
|
+
// our side closes too, so a connection nobody closes does not stay in the table forever.
|
|
78
|
+
graceMs: CLIENT_GRACE_MS,
|
|
79
|
+
onRemoteClose: datagram ? () => channel.destroy() : undefined,
|
|
80
|
+
sendData: (data) => this.#send(gatewayDataMsg({ gatewayId: id, data })),
|
|
81
|
+
sendCredit: (n) => this.#send(gatewayCreditMsg({ gatewayId: id, bytes: n })),
|
|
82
|
+
sendClose: (reason) => this.#send(gatewayCloseMsg({ gatewayId: id, reason })),
|
|
83
|
+
onClose: () => { this.#channels.delete(id); },
|
|
84
|
+
});
|
|
85
|
+
this.#channels.set(id, channel);
|
|
86
|
+
return channel;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
#duplex(channel) {
|
|
90
|
+
const { readable, writable } = channel.streams();
|
|
91
|
+
return { readable, writable, close: (r) => channel.end(r), destroy: (r) => channel.destroy(r), closed: channel.closedPromise };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async #open(build, { timeoutMs = DEFAULT_TIMEOUT_MS, signal } = {}, kind) {
|
|
95
|
+
if (signal?.aborted) throw signal.reason ?? new DOMException('aborted', 'AbortError');
|
|
96
|
+
const id = this.#id();
|
|
97
|
+
const channel = this.#makeChannel(id, kind);
|
|
98
|
+
const done = new Promise((resolve, reject) => {
|
|
99
|
+
const timer = setTimeout(() => { this.#opening.delete(id); channel.abandon(); reject(new GatewayError('the host did not answer the open request in time', 5)); }, timeoutMs);
|
|
100
|
+
timer.unref?.();
|
|
101
|
+
this.#opening.set(id, { channel, resolve, reject, timer });
|
|
102
|
+
});
|
|
103
|
+
const onAbort = () => {
|
|
104
|
+
const o = this.#opening.get(id);
|
|
105
|
+
if (!o) return;
|
|
106
|
+
this.#opening.delete(id); clearTimeout(o.timer);
|
|
107
|
+
channel.destroy(); // the host's Ok, if it comes, finds nothing; its connection is closed by this GatewayClose
|
|
108
|
+
o.reject(signal.reason ?? new DOMException('aborted', 'AbortError'));
|
|
109
|
+
};
|
|
110
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
111
|
+
try {
|
|
112
|
+
await this.#send(build(id));
|
|
113
|
+
} catch (e) {
|
|
114
|
+
const o = this.#opening.get(id);
|
|
115
|
+
if (o) { clearTimeout(o.timer); this.#opening.delete(id); }
|
|
116
|
+
channel.abandon();
|
|
117
|
+
throw e;
|
|
118
|
+
}
|
|
119
|
+
try { return await done; } finally { signal?.removeEventListener('abort', onAbort); }
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Connect to a unix-domain socket on the HOST. */
|
|
123
|
+
async openUnix(path, opts) {
|
|
124
|
+
this.#need('gateway-unix', 'unix-domain socket forwarding');
|
|
125
|
+
if (typeof path !== 'string' || !path) throw new TypeError('openUnix: path must be a non-empty string');
|
|
126
|
+
return this.#open((id) => openUnixMsg({ gatewayId: id, path }), opts);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Open a named virtual endpoint of the host. */
|
|
130
|
+
async openEndpoint(name, opts) {
|
|
131
|
+
this.#need('gateway-endpoints', 'named endpoints');
|
|
132
|
+
if (typeof name !== 'string' || !name) throw new TypeError('openEndpoint: name must be a non-empty string');
|
|
133
|
+
return this.#open((id) => openEndpointMsg({ gatewayId: id, name }), opts);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Connect to host:port FROM THE HOST (the gateway's TCP egress, subject to the host's allow list). */
|
|
137
|
+
async openTcp(host, port, opts) {
|
|
138
|
+
this.#need('gateway', 'TCP egress');
|
|
139
|
+
if (typeof host !== 'string' || !host || !Number.isInteger(port)) throw new TypeError('openTcp: host and port are required');
|
|
140
|
+
return this.#open((id) => openTcpMsg({ gatewayId: id, host, port }), opts);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* A UDP "connection" to host:port FROM THE HOST: each chunk written is one datagram, each chunk read is one datagram
|
|
145
|
+
* (at most 65507 bytes). It rides the reliable control stream, so it is ordered and retransmitted; datagrams the
|
|
146
|
+
* receiving side cannot keep up with are dropped by the host. Same destination policy as TCP.
|
|
147
|
+
*/
|
|
148
|
+
async openUdp(host, port, opts) {
|
|
149
|
+
this.#need('gateway', 'UDP egress');
|
|
150
|
+
if (typeof host !== 'string' || !host || !Number.isInteger(port)) throw new TypeError('openUdp: host and port are required');
|
|
151
|
+
return this.#open((id) => openUdpMsg({ gatewayId: id, host, port }), opts, { datagram: true });
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Ask the host to listen on a unix-domain socket and hand each connection to `onConnection(duplex)`.
|
|
156
|
+
* @param {string} path
|
|
157
|
+
* @param {{ replace?: boolean, onConnection: (duplex: GatewayDuplex) => void, timeoutMs?: number }} opts
|
|
158
|
+
* @returns {Promise<{ path: string, close: () => Promise<void> }>}
|
|
159
|
+
*/
|
|
160
|
+
async listenUnix(path, { replace, onConnection, timeoutMs = DEFAULT_TIMEOUT_MS } = {}) {
|
|
161
|
+
this.#need('gateway-unix', 'unix-domain socket forwarding');
|
|
162
|
+
if (typeof path !== 'string' || !path) throw new TypeError('listenUnix: path must be a non-empty string');
|
|
163
|
+
if (typeof onConnection !== 'function') throw new TypeError('listenUnix: onConnection is required');
|
|
164
|
+
const id = this.#id();
|
|
165
|
+
const entry = { onConnection, path, closed: false };
|
|
166
|
+
const answered = new Promise((resolve, reject) => {
|
|
167
|
+
entry.resolve = resolve; entry.reject = reject;
|
|
168
|
+
entry.timer = setTimeout(() => { this.#listeners.delete(id); reject(new GatewayError('the host did not answer the listen request in time', 5)); }, timeoutMs);
|
|
169
|
+
entry.timer.unref?.();
|
|
170
|
+
});
|
|
171
|
+
this.#listeners.set(id, entry);
|
|
172
|
+
try {
|
|
173
|
+
await this.#send(listenUnixMsg({ listenerId: id, path, replace: replace === true ? true : undefined }));
|
|
174
|
+
await answered;
|
|
175
|
+
} catch (e) { this.#listeners.delete(id); throw e; }
|
|
176
|
+
return {
|
|
177
|
+
path,
|
|
178
|
+
close: async () => {
|
|
179
|
+
if (entry.closed) return;
|
|
180
|
+
entry.closed = true;
|
|
181
|
+
this.#listeners.delete(id);
|
|
182
|
+
await this.#send(listenCloseMsg({ listenerId: id })).catch(() => {});
|
|
183
|
+
},
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Feed a control message in. Returns true when it belonged to a connection or listener this object owns. */
|
|
188
|
+
handle(m) {
|
|
189
|
+
switch (m.type) {
|
|
190
|
+
case MSG.GATEWAY_OK: {
|
|
191
|
+
const o = this.#opening.get(m.gateway_id);
|
|
192
|
+
if (!o) return this.#channels.has(m.gateway_id);
|
|
193
|
+
this.#opening.delete(m.gateway_id);
|
|
194
|
+
clearTimeout(o.timer);
|
|
195
|
+
o.resolve(this.#duplex(o.channel));
|
|
196
|
+
return true;
|
|
197
|
+
}
|
|
198
|
+
case MSG.GATEWAY_FAIL: {
|
|
199
|
+
const o = this.#opening.get(m.gateway_id);
|
|
200
|
+
if (!o) return false;
|
|
201
|
+
this.#opening.delete(m.gateway_id);
|
|
202
|
+
clearTimeout(o.timer);
|
|
203
|
+
o.channel.abandon();
|
|
204
|
+
o.reject(new GatewayError(m.message || 'refused by the host', m.code));
|
|
205
|
+
return true;
|
|
206
|
+
}
|
|
207
|
+
case MSG.GATEWAY_DATA: { const c = this.#channels.get(m.gateway_id); if (!c) return false; c.receive(m.data); return true; }
|
|
208
|
+
case MSG.GATEWAY_CREDIT: { const c = this.#channels.get(m.gateway_id); if (!c) return false; c.grant(m.bytes); return true; }
|
|
209
|
+
case MSG.GATEWAY_CLOSE: {
|
|
210
|
+
const c = this.#channels.get(m.gateway_id);
|
|
211
|
+
if (!c) return false;
|
|
212
|
+
const o = this.#opening.get(m.gateway_id);
|
|
213
|
+
if (o) { this.#opening.delete(m.gateway_id); clearTimeout(o.timer); c.abandon(); o.reject(new GatewayError('closed by the host', 6)); return true; }
|
|
214
|
+
c.remoteClosed(m.reason);
|
|
215
|
+
return true;
|
|
216
|
+
}
|
|
217
|
+
case MSG.LISTEN_OK: { const l = this.#listeners.get(m.listener_id); if (!l?.resolve) return false; clearTimeout(l.timer); l.resolve(); l.resolve = undefined; return true; }
|
|
218
|
+
case MSG.LISTEN_FAIL: {
|
|
219
|
+
const l = this.#listeners.get(m.listener_id);
|
|
220
|
+
if (!l?.reject) return false;
|
|
221
|
+
clearTimeout(l.timer);
|
|
222
|
+
this.#listeners.delete(m.listener_id);
|
|
223
|
+
l.reject(new GatewayError(m.reason || 'refused by the host', 4));
|
|
224
|
+
return true;
|
|
225
|
+
}
|
|
226
|
+
case MSG.INBOUND_OPEN: {
|
|
227
|
+
const l = this.#listeners.get(m.listener_id);
|
|
228
|
+
if (!l) return false;
|
|
229
|
+
if (l.closed) { void this.#send(inboundRejectMsg({ channelId: m.channel_id, reason: 'listener closed' })).catch(() => {}); return true; }
|
|
230
|
+
let id;
|
|
231
|
+
try { id = this.#id(); } catch { void this.#send(inboundRejectMsg({ channelId: m.channel_id, reason: 'out of ids' })).catch(() => {}); return true; }
|
|
232
|
+
const channel = this.#makeChannel(id);
|
|
233
|
+
const duplex = this.#duplex(channel);
|
|
234
|
+
void this.#send(inboundAcceptMsg({ channelId: m.channel_id, gatewayId: id })).then(() => {
|
|
235
|
+
try { l.onConnection(duplex, { peer: m.peer_addr }); } catch { channel.destroy('handler error'); }
|
|
236
|
+
}, () => channel.abandon());
|
|
237
|
+
return true;
|
|
238
|
+
}
|
|
239
|
+
default: return false;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** The connection is gone: every open connection ends, every pending open fails. */
|
|
244
|
+
abandonAll(reason = 'connection closed') {
|
|
245
|
+
for (const o of this.#opening.values()) { clearTimeout(o.timer); o.reject(new GatewayError(reason, 6)); }
|
|
246
|
+
this.#opening.clear();
|
|
247
|
+
for (const l of this.#listeners.values()) { clearTimeout(l.timer); l.reject?.(new GatewayError(reason, 6)); }
|
|
248
|
+
this.#listeners.clear();
|
|
249
|
+
for (const c of [...this.#channels.values()]) c.abandon(reason);
|
|
250
|
+
this.#channels.clear();
|
|
251
|
+
}
|
|
252
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a host serves, built from injected parts only: no shell to spawn and no directory to read, so nothing here
|
|
3
|
+
* imports from `node:*` and a browser host (`@johnhenry/wsh/memory`, `/reverse`, `/host`) can use it. The Node
|
|
4
|
+
* server wraps it (`server/backends.mjs`) with the two backends that need Node: `exec: true` and `fs: { root }`.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { normalizePty } from './server/pty.mjs';
|
|
8
|
+
import { createMcpHost } from './server/mcp.mjs';
|
|
9
|
+
import { DEFAULT_MAX_FILE_BYTES } from './server/constants.mjs';
|
|
10
|
+
import { generateKeyPair, resolveSigner, fingerprint, exportPublicKeySSH, importPublicKeyRaw } from './auth.mjs';
|
|
11
|
+
|
|
12
|
+
/** The operations a file backend must have (`openRange` is optional: only the `wsh-fs` rpc built-in, which needs Node, reads it). */
|
|
13
|
+
const FILE_OPERATIONS = ['operate', 'readWhole', 'writeWhole', 'writeAt'];
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Validate a file backend: an object of operations, as `createFileAccess` (`@johnhenry/wsh/server`, confined to a
|
|
17
|
+
* root directory) returns one. Paths arrive exactly as the client sent them -- confining them is the backend's job.
|
|
18
|
+
*
|
|
19
|
+
* - `operate(op, path, { offset, length, newPath, data })` -> `{ metadata?, entries? }`, for the FileOp requests
|
|
20
|
+
* `list`, `stat`, `read`, `write`, `rename`, `mkdir`, `remove`
|
|
21
|
+
* - `readWhole(path)` -> `Uint8Array` (a `download:` channel)
|
|
22
|
+
* - `writeWhole(path, bytes)` (an `upload:` channel)
|
|
23
|
+
* - `writeAt(path, bytes, offset?, { mkdirs? })`
|
|
24
|
+
* - `maxFileBytes` (default 64 MiB)
|
|
25
|
+
*
|
|
26
|
+
* Throw an `Error` with `wsh: true` to have its message sent to the client as is; any other error is reported by its message too.
|
|
27
|
+
*
|
|
28
|
+
* @param {object} fs
|
|
29
|
+
* @param {string} [who] - the option's name in error messages
|
|
30
|
+
*/
|
|
31
|
+
export function normalizeFileBackend(fs, who = 'fs') {
|
|
32
|
+
if (!fs || typeof fs !== 'object') throw new TypeError(`${who} must be an object of file operations`);
|
|
33
|
+
if (typeof fs.root === 'string' && typeof fs.operate !== 'function') {
|
|
34
|
+
throw new TypeError(`${who}.root names a directory, which needs Node: use @johnhenry/wsh/server, or give ${who} as an object of operations ({ operate, readWhole, writeWhole, writeAt })`);
|
|
35
|
+
}
|
|
36
|
+
for (const name of FILE_OPERATIONS) {
|
|
37
|
+
if (typeof fs[name] !== 'function') throw new TypeError(`${who}.${name} must be a function`);
|
|
38
|
+
}
|
|
39
|
+
if (fs.openRange !== undefined && typeof fs.openRange !== 'function') throw new TypeError(`${who}.openRange must be a function`);
|
|
40
|
+
const maxFileBytes = fs.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES;
|
|
41
|
+
if (!Number.isSafeInteger(maxFileBytes) || maxFileBytes < 1) throw new TypeError(`${who}.maxFileBytes must be a positive integer`);
|
|
42
|
+
// Call through `fs` so a backend written with `this` keeps working.
|
|
43
|
+
const files = {
|
|
44
|
+
maxFileBytes,
|
|
45
|
+
operate: (...a) => fs.operate(...a),
|
|
46
|
+
readWhole: (...a) => fs.readWhole(...a),
|
|
47
|
+
writeWhole: (...a) => fs.writeWhole(...a),
|
|
48
|
+
writeAt: (...a) => fs.writeAt(...a),
|
|
49
|
+
};
|
|
50
|
+
if (fs.openRange) files.openRange = (...a) => fs.openRange(...a);
|
|
51
|
+
return files;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* @param {{ exec?: Function | { run: Function }, pty?: { spawn: Function }, fs?: object, mcp?: object }} options
|
|
56
|
+
* @returns {{ execRunner: Function | null, execOptions: object, pty: object | null, files: object | null, mcp: object | null }}
|
|
57
|
+
*/
|
|
58
|
+
export function resolveBackends({ exec, pty, fs, mcp } = {}) {
|
|
59
|
+
let execRunner = null;
|
|
60
|
+
let execOptions = {};
|
|
61
|
+
if (typeof exec === 'function') {
|
|
62
|
+
execRunner = exec;
|
|
63
|
+
} else if (exec !== undefined && exec !== null && exec !== false) {
|
|
64
|
+
if (typeof exec !== 'object' || typeof exec.run !== 'function') {
|
|
65
|
+
throw new TypeError('exec must be a function run(command, io) or { run }: there is no shell to run `true` with here (use @johnhenry/wsh/server for that)');
|
|
66
|
+
}
|
|
67
|
+
execOptions = exec;
|
|
68
|
+
execRunner = exec.run;
|
|
69
|
+
}
|
|
70
|
+
return {
|
|
71
|
+
execRunner,
|
|
72
|
+
execOptions,
|
|
73
|
+
pty: pty ? normalizePty(pty) : null,
|
|
74
|
+
files: fs ? normalizeFileBackend(fs) : null,
|
|
75
|
+
mcp: mcp ? createMcpHost(mcp) : null,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* The host's own identity (`ServerHello.host_fingerprint` and the host-key proof; see `host-key.mjs`), from what a page
|
|
81
|
+
* can hold: a `CryptoKeyPair` (generate it with `generateKeyPair(false)` and the private key never leaves the browser),
|
|
82
|
+
* or a signer `{ publicKey, sign(data) }` (`WshSigner`) when the key lives elsewhere (a hardware key, a Worker, an
|
|
83
|
+
* HSM). `true` makes a fresh non-extractable key for this host (TOFU clients see "changed" next time: demos and tests).
|
|
84
|
+
* The Node server's `hostKey` also takes `{ file }`.
|
|
85
|
+
*
|
|
86
|
+
* @returns {Promise<{ publicKey: Uint8Array, fingerprint: string, openssh: string, sign(data: Uint8Array): Promise<Uint8Array> }>}
|
|
87
|
+
*/
|
|
88
|
+
export async function resolveHostKey(option, who = 'hostKey') {
|
|
89
|
+
if (option === true) option = await generateKeyPair(false);
|
|
90
|
+
const isPair = option && typeof option === 'object' && option.privateKey && option.publicKey;
|
|
91
|
+
const isSigner = option && typeof option === 'object' && typeof option.sign === 'function' && option.publicKey;
|
|
92
|
+
if (!isPair && !isSigner) throw new TypeError(`${who} must be true, a CryptoKeyPair, or a signer { publicKey, sign(data) }`);
|
|
93
|
+
const resolved = await resolveSigner(isPair ? { keyPair: option } : { signer: option });
|
|
94
|
+
return {
|
|
95
|
+
publicKey: resolved.publicKeyRaw,
|
|
96
|
+
fingerprint: await fingerprint(resolved.publicKeyRaw),
|
|
97
|
+
openssh: await exportPublicKeySSH(await importPublicKeyRaw(resolved.publicKeyRaw)),
|
|
98
|
+
sign: resolved.sign,
|
|
99
|
+
};
|
|
100
|
+
}
|
package/src/host.d.ts
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import type { WshSigner } from './index.js';
|
|
2
|
+
import type {
|
|
3
|
+
WshExecRunner, WshServerPtyOptions, WshServerMcpOptions, WshServerAuthOptions, WshServerPrincipal, WshAcceptableSocket, WshAcceptOptions, WshClientEnv,
|
|
4
|
+
} from './server/index.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* File operations a host serves `FileOp` requests and `upload:` / `download:` channels from. An object of
|
|
8
|
+
* operations, not a root path: confining client paths to what the host may expose is the backend's job.
|
|
9
|
+
* (`createWshServer({ fs: { root } })` builds one of these over a directory.)
|
|
10
|
+
*/
|
|
11
|
+
export interface WshFileBackend {
|
|
12
|
+
/**
|
|
13
|
+
* `list` -> `{ entries, metadata: { path } }`; `stat` -> `{ metadata: { name, size, modified, type } }`;
|
|
14
|
+
* `read` (`offset`, `length`) -> `{ metadata: { data, size } }`; `write` (`offset`, `data`) -> `{ metadata: { written } }`;
|
|
15
|
+
* `rename` (`newPath`); `mkdir`; `remove`. Anything else should throw.
|
|
16
|
+
*/
|
|
17
|
+
operate(op: string, path: string, args?: { offset?: number; length?: number; newPath?: string; data?: Uint8Array }): Promise<{ metadata?: Record<string, unknown>; entries?: Array<Record<string, unknown>> }>;
|
|
18
|
+
/** The whole file, for a `download:` channel. Throw if it is larger than `maxFileBytes`. */
|
|
19
|
+
readWhole(path: string): Promise<Uint8Array>;
|
|
20
|
+
/** Create or replace a file (creating its directories), for an `upload:` channel. */
|
|
21
|
+
writeWhole(path: string, data: Uint8Array): Promise<void>;
|
|
22
|
+
/** Write `data` at `offset` (omitted = replace the file), without truncating when an offset is given. */
|
|
23
|
+
writeAt(path: string, data: Uint8Array, offset?: number, options?: { mkdirs?: boolean }): Promise<void>;
|
|
24
|
+
/** A byte range as chunks; only the `wsh-fs` rpc built-in (Node) reads it. */
|
|
25
|
+
openRange?(path: string, options?: { offset?: number; length?: number; chunkBytes?: number }): Promise<{ size: number; offset: number; length: number; chunks: AsyncIterable<Uint8Array> }>;
|
|
26
|
+
/** Largest file read or written whole, in bytes (default 64 MiB). */
|
|
27
|
+
maxFileBytes?: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** A host's own identity: a key pair (the private key may be non-extractable) or a signer for a key held elsewhere. */
|
|
31
|
+
export type WshHostKeyOption = true | CryptoKeyPair | WshSigner;
|
|
32
|
+
|
|
33
|
+
/** The identity `resolveHostKey` makes of a `WshHostKeyOption`. */
|
|
34
|
+
export interface WshResolvedHostKey {
|
|
35
|
+
/** Raw 32-byte Ed25519 public key. */
|
|
36
|
+
publicKey: Uint8Array;
|
|
37
|
+
fingerprint: string;
|
|
38
|
+
openssh: string;
|
|
39
|
+
sign(data: Uint8Array): Promise<Uint8Array>;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface WshResolvedBackends {
|
|
43
|
+
execRunner: WshExecRunner | null;
|
|
44
|
+
execOptions: { timeoutMs?: number; clientEnv?: WshClientEnv };
|
|
45
|
+
pty: { spawn: WshServerPtyOptions['spawn']; shell: string; cwd?: string; env?: Record<string, string | undefined>; term: string } | null;
|
|
46
|
+
files: Required<Pick<WshFileBackend, 'operate' | 'readWhole' | 'writeWhole' | 'writeAt' | 'maxFileBytes'>> & Pick<WshFileBackend, 'openRange'> | null;
|
|
47
|
+
mcp: object | null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Validate injected backends (no shell, no directory: `exec` is a function or `{ run }`, `fs` an object of operations). */
|
|
51
|
+
export function resolveBackends(options?: {
|
|
52
|
+
exec?: WshExecRunner | { run: WshExecRunner; timeoutMs?: number; clientEnv?: WshClientEnv };
|
|
53
|
+
pty?: WshServerPtyOptions;
|
|
54
|
+
fs?: WshFileBackend;
|
|
55
|
+
mcp?: WshServerMcpOptions;
|
|
56
|
+
}): WshResolvedBackends;
|
|
57
|
+
|
|
58
|
+
/** Validate a file backend (see {@link WshFileBackend}). */
|
|
59
|
+
export function normalizeFileBackend(fs: WshFileBackend, who?: string): NonNullable<WshResolvedBackends['files']>;
|
|
60
|
+
|
|
61
|
+
/** Make the identity a host presents from a `CryptoKeyPair`, a signer, or `true` (a fresh non-extractable key). */
|
|
62
|
+
export function resolveHostKey(option: WshHostKeyOption, who?: string): Promise<WshResolvedHostKey>;
|
|
63
|
+
|
|
64
|
+
/** The `authorize(who)` function for a host's `auth` option (as `createWshServer` reads it). */
|
|
65
|
+
export function buildAuthorizer(auth: WshServerAuthOptions | ((who: WshServerPrincipal) => boolean | Promise<boolean>) | undefined): Promise<(who: { username: string; fingerprint: string; publicKey: Uint8Array }) => Promise<boolean>>;
|
|
66
|
+
|
|
67
|
+
/** Which auth methods an `auth` option turns on. */
|
|
68
|
+
export function authMethods(auth: WshServerAuthOptions | ((who: WshServerPrincipal) => boolean | Promise<boolean>) | undefined): { pubkey: boolean; password: ((user: string, pass: string) => boolean | Promise<boolean>) | null };
|
|
69
|
+
|
|
70
|
+
/** What the connection handler is given. Everything but `authorize` is optional. */
|
|
71
|
+
export interface WshConnectionConfig extends Partial<WshResolvedBackends> {
|
|
72
|
+
/** Required: decides who is let in. A host with no authorizer would let everyone in, so there is no default. */
|
|
73
|
+
authorize(who: { username: string; fingerprint?: string; publicKey?: Uint8Array }): Promise<boolean>;
|
|
74
|
+
/** Auth methods on (default: pubkey only). */
|
|
75
|
+
methods?: { pubkey: boolean; password: ((user: string, pass: string) => boolean | Promise<boolean>) | null };
|
|
76
|
+
hostKey?: WshResolvedHostKey | null;
|
|
77
|
+
/** Handlers for application-defined (string-typed) messages. */
|
|
78
|
+
extensions?: Record<string, (message: any, ctx: { username: string | null; fingerprint: string | null; send(message: object): Promise<void> }) => unknown>;
|
|
79
|
+
/** A `SessionRegistry` (see `src/session-registry.mjs`): detach / attach / resume. Null = sessions die with their connection. */
|
|
80
|
+
sessions?: object | null;
|
|
81
|
+
/** End-to-end encryption for a message-framed (relay-bridged) connection. */
|
|
82
|
+
e2e?: { signKey: CryptoKey | null; hybrid?: boolean } | null;
|
|
83
|
+
/** How long exec output waits for the client-opened data stream (default 3000). */
|
|
84
|
+
bindTimeoutMs?: number;
|
|
85
|
+
log?: (line: string) => void;
|
|
86
|
+
[key: string]: unknown;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** One connection over a byte pipe. */
|
|
90
|
+
export interface WshConnectionPipe {
|
|
91
|
+
/** Send these bytes to the peer. */
|
|
92
|
+
send(bytes: Uint8Array): void;
|
|
93
|
+
remote?: { address?: string; headers?: Record<string, unknown> };
|
|
94
|
+
/** End the underlying transport (the host ends the connection: a refused login, say). */
|
|
95
|
+
closeTransport?(): void;
|
|
96
|
+
/**
|
|
97
|
+
* Serve the connection without client-opened QMux streams: exec output rides `SessionData` (`data_mode: 'virtual'`) and
|
|
98
|
+
* `stream-announce` / `rpc` are not offered. Default `true`. Needed for a peer that cannot open streams (#132).
|
|
99
|
+
*/
|
|
100
|
+
dataStreams?: boolean;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** One connection over messages (a transport that does its own framing, e.g. a relay bridge). */
|
|
104
|
+
export interface WshConnectionMessages {
|
|
105
|
+
sendMessage(message: object): unknown;
|
|
106
|
+
/** The identity something else already authenticated: skips the handshake. */
|
|
107
|
+
authenticated?: { username: string; fingerprint: string } | null;
|
|
108
|
+
dataStreams?: boolean;
|
|
109
|
+
e2e?: { signKey: CryptoKey | null; hybrid?: boolean } | null;
|
|
110
|
+
remote?: { address?: string; headers?: Record<string, unknown> };
|
|
111
|
+
closeTransport?(): void;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export interface WshConnection {
|
|
115
|
+
/** Bytes from the peer (byte-pipe form). */
|
|
116
|
+
receive(bytes: Uint8Array): void;
|
|
117
|
+
/** One decoded message from the peer (message form). */
|
|
118
|
+
receiveMessage(message: object): void;
|
|
119
|
+
/** A QMux-style stream opened by the peer (message form, when it has them). */
|
|
120
|
+
bindStream?(stream: object): void;
|
|
121
|
+
close(): void;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export type WshConnectionAttach = (pipe: WshConnectionPipe | WshConnectionMessages) => WshConnection;
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* The connection handler every wsh host runs. Returns `attach`, called once per connection. Over a WebSocket-like
|
|
128
|
+
* duplex use {@link bindSocket} rather than calling it by hand.
|
|
129
|
+
*/
|
|
130
|
+
export function createConnectionFactory(config: WshConnectionConfig): WshConnectionAttach;
|
|
131
|
+
|
|
132
|
+
/** The features a host built from `config` advertises in `ServerHello` (minus the host-key proof). */
|
|
133
|
+
export function hostFeatures(config: Partial<WshConnectionConfig>, options?: { dataStreams?: boolean }): string[];
|
|
134
|
+
|
|
135
|
+
/** ServerHello feature: the host discovers client-opened exec data streams itself (no primer byte). */
|
|
136
|
+
export const STREAM_ANNOUNCE: 'stream-announce';
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Serve a pre-upgraded WebSocket-like duplex (`send`, `close`, `readyState`, and `addEventListener` or `on`) with the
|
|
140
|
+
* connection handler `ready` resolves to. Resolves once attached; the handle's `close()` drops the connection.
|
|
141
|
+
*/
|
|
142
|
+
export function bindSocket(
|
|
143
|
+
socket: WshAcceptableSocket,
|
|
144
|
+
ready: Promise<WshConnectionAttach>,
|
|
145
|
+
options?: WshAcceptOptions,
|
|
146
|
+
): Promise<{ close(): void }>;
|
package/src/host.mjs
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@johnhenry/wsh/host` -- the building blocks of a wsh host that runs anywhere JavaScript does (a page, a Worker,
|
|
3
|
+
* Deno, Bun, Node), for an embedder that brings its own transport. No `node:*` import and no `Buffer` is reachable
|
|
4
|
+
* from here (a test bundles this entry point for the browser and fails if one is), and it does not import the client.
|
|
5
|
+
*
|
|
6
|
+
* - `createConnectionFactory(cfg)` -- the connection handler `createWshServer`, `createMemoryHost` and
|
|
7
|
+
* `createReverseHost` all run: handshake, auth, exec / pty / file / MCP channels, sessions, end-to-end encryption.
|
|
8
|
+
* `attach(...)` is called once per connection, over a byte pipe (QMux framing, what a WebSocket carries) or, for a
|
|
9
|
+
* transport that frames messages itself, over messages.
|
|
10
|
+
* - `bindSocket(socket, ready, options)` -- the byte-pipe side for a WebSocket-like duplex.
|
|
11
|
+
* - `resolveBackends({ exec, pty, fs, mcp })`, `resolveHostKey(key)`, `buildAuthorizer(auth)`, `authMethods(auth)` --
|
|
12
|
+
* turn the options a host takes into what the factory wants.
|
|
13
|
+
*
|
|
14
|
+
* ```js
|
|
15
|
+
* import { createConnectionFactory, resolveBackends, buildAuthorizer, authMethods, bindSocket } from '@johnhenry/wsh/host';
|
|
16
|
+
*
|
|
17
|
+
* const auth = { authorizedKeys: [rawPublicKey] };
|
|
18
|
+
* const backends = resolveBackends({ exec: async (command, io) => { await io.write('hi\n'); return 0; } });
|
|
19
|
+
* const attach = createConnectionFactory({
|
|
20
|
+
* authorize: await buildAuthorizer(auth), methods: authMethods(auth), ...backends,
|
|
21
|
+
* });
|
|
22
|
+
* // `attach` is what `bindSocket` wants, as a promise:
|
|
23
|
+
* await bindSocket(upgradedSocket, Promise.resolve(attach), { dataStreams: false });
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
export { createConnectionFactory, hostFeatures, STREAM_ANNOUNCE } from './server/connection.mjs';
|
|
28
|
+
export { bindSocket } from './server/socket.mjs';
|
|
29
|
+
export { resolveBackends, resolveHostKey, normalizeFileBackend } from './host-backends.mjs';
|
|
30
|
+
export { buildAuthorizer, authMethods } from './server/auth.mjs';
|