@johnhenry/wsh 0.48.0 → 0.50.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.
@@ -0,0 +1,194 @@
1
+ /**
2
+ * `@johnhenry/wsh/identity` -- a key's identity in its spellings, in one stable, browser-safe module (no Node import).
3
+ *
4
+ * One Ed25519 public key has these names:
5
+ *
6
+ * raw key the 32 bytes (`Uint8Array`), what WebCrypto exports as `'raw'`
7
+ * OpenSSH line `ssh-ed25519 AAAAC3Nza... comment`: what `authorized_keys` and `ssh-keygen` write
8
+ * fingerprint the SHA-256 of the raw key, 64 lower-case hex digits: what wsh logs, pins and passes to `authorize()`
9
+ * pod id the same 32 bytes of SHA-256, as 43 characters of base64url: what BrowserMesh calls a pod
10
+ *
11
+ * The fingerprint and the pod id are two spellings of one hash (so they convert in both directions without the key), and both are
12
+ * derived from the raw key (so they cannot be turned back into it). The OpenSSH line and the raw key are one value in two spellings.
13
+ *
14
+ * ```js
15
+ * import { identityOf, authorizedKeyLine } from '@johnhenry/wsh/identity';
16
+ * const { fingerprint, podId } = await identityOf('ssh-ed25519 AAAAC3Nza...');
17
+ * const line = authorizedKeyLine(rawKey, { capabilities: ['objects:window:get'], expires: '2030-01-01T00:00:00Z', comment: 'mesh peer' });
18
+ * ```
19
+ *
20
+ * Everything here refuses what is not exactly what it names (a key that is not 32 bytes, a fingerprint that is not a SHA-256, a line
21
+ * that carries options or a second line) rather than convert it into something else.
22
+ */
23
+
24
+ import { fingerprint, podId, exportPublicKeyRaw, base64Decode } from './auth.mjs';
25
+ import { fingerprintToPodId, podIdToFingerprint, normalizeIdentity } from './key-names.mjs';
26
+ import { grantPermissions, parseAuthorizedKeyLine, parseRfc3339 } from './key-options.mjs';
27
+
28
+ export { fingerprint, podId, fingerprintToPodId, podIdToFingerprint, normalizeIdentity };
29
+
30
+ const KEY_TYPE = 'ssh-ed25519';
31
+ const TYPE_BYTES = new TextEncoder().encode(KEY_TYPE);
32
+ const WIRE_LENGTH = 4 + TYPE_BYTES.length + 4 + 32;
33
+ // Anything that could end a line or start another: C0 and C1 controls, DEL, and the Unicode line and paragraph separators
34
+ // (written with their code points, so that no separator character sits in the source of a regular expression).
35
+ const LINE_BREAKING = new RegExp(`[\\u0000-\\u001f\\u007f-\\u009f${String.fromCharCode(0x2028)}${String.fromCharCode(0x2029)}]`);
36
+
37
+ const isRawKey = (raw) => raw instanceof Uint8Array && raw.byteLength === 32;
38
+
39
+ function base64(bytes) {
40
+ let binary = '';
41
+ for (const b of bytes) binary += String.fromCharCode(b);
42
+ return btoa(binary);
43
+ }
44
+
45
+ function checkComment(comment, who) {
46
+ if (comment === undefined || comment === '') return '';
47
+ if (typeof comment !== 'string') throw new TypeError(`${who}: the comment must be a string`);
48
+ if (LINE_BREAKING.test(comment)) throw new TypeError(`${who}: the comment may not contain a control character or a line break (it could start another line)`);
49
+ return comment;
50
+ }
51
+
52
+ /**
53
+ * The OpenSSH `ssh-ed25519` line of a raw public key.
54
+ * @param {Uint8Array} raw exactly 32 bytes
55
+ * @param {string} [comment] appended after the key; no control character or line break
56
+ * @returns {string}
57
+ */
58
+ export function rawKeyToOpenSsh(raw, comment) {
59
+ if (!isRawKey(raw)) throw new TypeError('rawKeyToOpenSsh: expected a Uint8Array of exactly 32 bytes (an Ed25519 public key)');
60
+ const note = checkComment(comment, 'rawKeyToOpenSsh');
61
+ const wire = new Uint8Array(WIRE_LENGTH);
62
+ const view = new DataView(wire.buffer);
63
+ view.setUint32(0, TYPE_BYTES.length);
64
+ wire.set(TYPE_BYTES, 4);
65
+ view.setUint32(4 + TYPE_BYTES.length, 32);
66
+ wire.set(raw, 8 + TYPE_BYTES.length);
67
+ return `${KEY_TYPE} ${base64(wire)}${note ? ` ${note}` : ''}`;
68
+ }
69
+
70
+ /**
71
+ * The OpenSSH line of a public `CryptoKey`.
72
+ * @param {CryptoKey} publicKey an extractable Ed25519 public key
73
+ * @param {string} [comment]
74
+ * @returns {Promise<string>}
75
+ */
76
+ export async function publicKeyToOpenSsh(publicKey, comment) {
77
+ return rawKeyToOpenSsh(await exportPublicKeyRaw(publicKey), comment);
78
+ }
79
+
80
+ /**
81
+ * Read an OpenSSH `ssh-ed25519` public key line: the raw key and the comment. Only a plain key is read: no options in front (those are
82
+ * `authorized_keys` syntax, see `parseAuthorizedKeyLine`), no other key type, nothing after the 32 bytes of the key inside, one line.
83
+ * @param {string} line `ssh-ed25519 <base64> [comment]`
84
+ * @returns {{ raw: Uint8Array, comment: string }}
85
+ */
86
+ export function parseOpenSshKey(line) {
87
+ if (typeof line !== 'string') throw new TypeError('parseOpenSshKey: expected an ssh-ed25519 line');
88
+ const text = line.endsWith('\n') ? line.slice(0, -1) : line;
89
+ if (LINE_BREAKING.test(text)) throw new TypeError('parseOpenSshKey: expected one line with no control character');
90
+ const m = /^ssh-ed25519 ([A-Za-z0-9+/]+={0,2})(?: (.*))?$/.exec(text);
91
+ if (!m) throw new TypeError('parseOpenSshKey: expected "ssh-ed25519 <base64> [comment]" (a key with options in front is an authorized_keys line, not a key)');
92
+ let wire;
93
+ try { wire = base64Decode(m[1]); } catch { throw new TypeError('parseOpenSshKey: the key is not base64'); }
94
+ if (base64(wire) !== m[1]) throw new TypeError('parseOpenSshKey: the key is not in the canonical base64 spelling');
95
+ if (wire.byteLength !== WIRE_LENGTH) throw new TypeError('parseOpenSshKey: not an Ed25519 key (the wire form of one is exactly 51 bytes)');
96
+ const view = new DataView(wire.buffer, wire.byteOffset, wire.byteLength);
97
+ const typeLength = view.getUint32(0);
98
+ const typeOk = typeLength === TYPE_BYTES.length && TYPE_BYTES.every((b, i) => wire[4 + i] === b);
99
+ if (!typeOk || view.getUint32(4 + TYPE_BYTES.length) !== 32) throw new TypeError('parseOpenSshKey: the key inside the line is not an ssh-ed25519 key');
100
+ return { raw: wire.slice(8 + TYPE_BYTES.length), comment: m[2] ?? '' };
101
+ }
102
+
103
+ /**
104
+ * The raw 32-byte public key of an OpenSSH `ssh-ed25519` line (what `parseOpenSshKey` reads; the comment is dropped).
105
+ * @param {string} line
106
+ * @returns {Uint8Array}
107
+ */
108
+ export function openSshToRawKey(line) {
109
+ return parseOpenSshKey(line).raw;
110
+ }
111
+
112
+ /**
113
+ * One key in every spelling: `{ raw, fingerprint, podId, openssh }`.
114
+ * @param {Uint8Array | string | CryptoKey} key a raw 32-byte key, an OpenSSH `ssh-ed25519` line, or a public `CryptoKey`
115
+ * @returns {Promise<{ raw: Uint8Array, fingerprint: string, podId: string, openssh: string }>}
116
+ */
117
+ export async function identityOf(key) {
118
+ let raw;
119
+ if (typeof key === 'string') raw = openSshToRawKey(key);
120
+ else if (isRawKey(key)) raw = key.slice();
121
+ else if (typeof CryptoKey !== 'undefined' && key instanceof CryptoKey) raw = await exportPublicKeyRaw(key);
122
+ else throw new TypeError('identityOf: expected a raw 32-byte key, an ssh-ed25519 line or a public CryptoKey');
123
+ const fp = await fingerprint(raw);
124
+ return { raw, fingerprint: fp, podId: fingerprintToPodId(fp), openssh: rawKeyToOpenSsh(raw) };
125
+ }
126
+
127
+ const LINE_OPTIONS = new Set(['capabilities', 'expires', 'comment', 'allowFullAccess']);
128
+
129
+ /** `Date | epoch milliseconds | RFC 3339 string` as the canonical `YYYY-MM-DDTHH:MM:SSZ`, or a TypeError. */
130
+ function canonicalExpiry(expires) {
131
+ let seconds = null;
132
+ if (typeof expires === 'string') seconds = parseRfc3339(expires);
133
+ else if (expires instanceof Date) seconds = Number.isFinite(expires.getTime()) ? Math.floor(expires.getTime() / 1000) : null;
134
+ else if (typeof expires === 'number') seconds = Number.isFinite(expires) ? Math.floor(expires / 1000) : null;
135
+ // The grammar starts in 1970, and the text of a timestamp holds four digits of year
136
+ if (seconds === null || seconds < 0 || seconds > 253402300799) {
137
+ throw new TypeError('authorizedKeyLine: expires must be an RFC 3339 timestamp such as 2030-01-01T00:00:00Z, a Date, or epoch milliseconds, between 1970 and 9999');
138
+ }
139
+ return new Date(seconds * 1000).toISOString().replace('.000Z', 'Z');
140
+ }
141
+
142
+ /**
143
+ * A line for an `authorized_keys` file: `capabilities="..."[,expires="..."] ssh-ed25519 <key> [comment]`. Only what it is asked for
144
+ * is written, and it refuses what could grant more:
145
+ *
146
+ * - `capabilities` is required: a line with no limits at all is a key that may do everything, so that is `allowFullAccess: true`
147
+ * said out loud (and then `capabilities` must not be given). `[]` is a key that may do nothing.
148
+ * - every capability must be one this package's notation knows (`spec/capabilities.md`): an entry it does not understand, or one that
149
+ * carries a quote, a comma or whitespace, is refused, naming it, instead of being written for a host to refuse or misread;
150
+ * - `expires` must be a timestamp and is written in UTC, `Z`;
151
+ * - the key must be a plain Ed25519 key (raw bytes or a plain OpenSSH line; the options and the comment of an input line are not
152
+ * carried over); the comment may not hold a control character or line break;
153
+ * - what it wrote is read back through the same parser a host uses, and must give the same capabilities, the same expiry and no other
154
+ * option; if not, it throws.
155
+ *
156
+ * @param {Uint8Array | string} key a raw 32-byte public key, or an OpenSSH `ssh-ed25519` line (use `publicKeyToOpenSsh` for a `CryptoKey`)
157
+ * @param {{ capabilities?: string[] | string, expires?: string | Date | number, comment?: string, allowFullAccess?: boolean }} options
158
+ * @returns {string} one line, no trailing newline
159
+ */
160
+ export function authorizedKeyLine(key, options) {
161
+ if (options === null || typeof options !== 'object') throw new TypeError('authorizedKeyLine: options { capabilities, expires, comment } are required');
162
+ for (const name of Object.keys(options)) {
163
+ if (!LINE_OPTIONS.has(name)) throw new TypeError(`authorizedKeyLine: unknown option ${JSON.stringify(name)} (this builder writes capabilities, expires and a comment)`);
164
+ }
165
+ const { capabilities, expires, comment, allowFullAccess = false } = options;
166
+ if (allowFullAccess !== true && allowFullAccess !== false) throw new TypeError('authorizedKeyLine: allowFullAccess must be true or false');
167
+ if (capabilities === undefined && !allowFullAccess) {
168
+ throw new TypeError('authorizedKeyLine: capabilities are required (a key line with none may do everything): pass the list, [] for a key that may do nothing, or allowFullAccess: true');
169
+ }
170
+ if (capabilities !== undefined && allowFullAccess) throw new TypeError('authorizedKeyLine: allowFullAccess: true and a capabilities list contradict each other');
171
+ const raw = isRawKey(key) ? key : (typeof key === 'string' ? parseOpenSshKey(key).raw : null);
172
+ if (raw === null) throw new TypeError('authorizedKeyLine: key must be a raw 32-byte Ed25519 key or an ssh-ed25519 line');
173
+ const note = checkComment(comment, 'authorizedKeyLine');
174
+ const written = [];
175
+ let list = null;
176
+ if (capabilities !== undefined) {
177
+ const granted = grantPermissions({ capabilities });
178
+ if (!granted.ok) throw new TypeError(`authorizedKeyLine: ${granted.reason}`);
179
+ list = granted.permissions.capabilities;
180
+ written.push(`capabilities="${list.join(',')}"`);
181
+ }
182
+ const until = expires === undefined ? null : canonicalExpiry(expires);
183
+ if (until !== null) written.push(`expires="${until}"`);
184
+ const line = `${written.length ? `${written.join(',')} ` : ''}${rawKeyToOpenSsh(raw, note)}`;
185
+ // Read it back as a host would.
186
+ const back = parseAuthorizedKeyLine(line);
187
+ const ok = back.permissions
188
+ && back.key.byteLength === 32 && back.key.every((b, i) => b === raw[i])
189
+ && JSON.stringify(back.permissions.capabilities) === JSON.stringify(list)
190
+ && back.permissions.expires === (until === null ? null : parseRfc3339(until))
191
+ && back.permissions.forcedCommand === null && back.permissions.maxSessions === null;
192
+ if (!ok) throw new TypeError('authorizedKeyLine: the line it built does not read back as the grant that was asked for; refusing to write it');
193
+ return line;
194
+ }
package/src/index.d.ts CHANGED
@@ -2251,6 +2251,17 @@ export const GATEWAY_DATAGRAM_FEATURE: 'gateway-datagram';
2251
2251
  /** A GatewayFail / ListenFail as an Error: `code` 4 = refused by the host's policy, 7 = too many connections, 1 = refused by the target. */
2252
2252
  export class GatewayError extends Error { code: number }
2253
2253
 
2254
+ /** The codes of `GatewayFail` by name (the one table the Node gateway, the page host and netway share). Frozen; a number is never reused. */
2255
+ export const GATEWAY_FAIL: Readonly<{
2256
+ CONNECTION_REFUSED: 1; HOST_UNREACHABLE: 2; DNS_FAILED: 3; POLICY_DENIED: 4; TIMEOUT: 5; CLOSED: 6; QUEUE_FULL: 7;
2257
+ }>;
2258
+ /** The same codes with their meaning; `alsoSentAs` is a second name another implementation gives the number (the Rust server sends `5` for a disabled gateway). */
2259
+ export const GATEWAY_FAIL_TABLE: ReadonlyArray<Readonly<{ name: keyof typeof GATEWAY_FAIL; code: number; meaning: string; alsoSentAs?: readonly string[] }>>;
2260
+ /** Codes a client gives its own `GatewayError` when it never asked the host (not on the wire): `UNSUPPORTED` is `0`, a feature the host did not advertise. */
2261
+ export const GATEWAY_FAIL_LOCAL: Readonly<{ UNSUPPORTED: 0 }>;
2262
+ /** The name of a wire or client-local code, or `null`. */
2263
+ export function gatewayFailName(code: number): string | null;
2264
+
2254
2265
  /** The feature a client lists in `Hello.features` and a host in `ServerHello.features` to meter gateway data with `GatewayCredit`. */
2255
2266
  export const GATEWAY_CREDIT_FEATURE: 'gateway-credit';
2256
2267
  /** Credit, in bytes, each direction of a gateway connection starts with. */
package/src/index.mjs CHANGED
@@ -79,6 +79,7 @@ export { WshVirtualSessionBackend, normalizeSessionData } from './virtual-sessio
79
79
  export { WshClient, MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, STREAM_ANNOUNCE_FEATURE, EXEC_PIPES_FEATURE, TARGETS_FEATURE } from './client.mjs';
80
80
  // Gateway forwarding (unix sockets, named endpoints, flow control) -- wsh #120, #123
81
81
  export { GatewayError } from './gateway-client.mjs';
82
+ export { GATEWAY_FAIL, GATEWAY_FAIL_TABLE, GATEWAY_FAIL_LOCAL, gatewayFailName } from './gateway-errors.mjs';
82
83
  export { GATEWAY_CREDIT_FEATURE, GATEWAY_CREDIT_WINDOW } from './gateway-channel.mjs';
83
84
  export { GATEWAY_DATAGRAM_FEATURE } from './gateway-datagram.mjs';
84
85
 
@@ -0,0 +1,115 @@
1
+ /**
2
+ * The two names of a key's hash, and the caller identity built from them. Pure functions of strings: no crypto, no Node import, so the
3
+ * object layer, the MCP layer and `@johnhenry/wsh/identity` can all use them without pulling in the key code.
4
+ *
5
+ * A key is named by the SHA-256 of its raw 32-byte Ed25519 public key. wsh writes the 32 bytes as 64 lower-case hex digits (the
6
+ * "fingerprint"); BrowserMesh writes the same 32 bytes as 43 characters of base64url (the "pod id"). They are one name in two
7
+ * spellings, and these functions convert between them and refuse anything that is not exactly such a hash.
8
+ */
9
+
10
+ const HEX_RE = /^[0-9a-fA-F]{64}$/;
11
+ const B64URL_RE = /^[A-Za-z0-9_-]{43}$/;
12
+ const B64URL_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
13
+
14
+ /** @param {string} hex 64 hex digits @returns {string} the 43-character base64url spelling of the same 32 bytes */
15
+ function hexToBase64url(hex) {
16
+ let out = '';
17
+ let acc = 0;
18
+ let bits = 0;
19
+ for (let i = 0; i < hex.length; i += 2) {
20
+ acc = (acc << 8) | parseInt(hex.slice(i, i + 2), 16);
21
+ bits += 8;
22
+ while (bits >= 6) { bits -= 6; out += B64URL_ALPHABET[(acc >> bits) & 63]; }
23
+ acc &= (1 << bits) - 1;
24
+ }
25
+ if (bits > 0) out += B64URL_ALPHABET[(acc << (6 - bits)) & 63];
26
+ return out;
27
+ }
28
+
29
+ /** @param {string} id 43 base64url characters @returns {string | null} 64 lower-case hex digits, or null when the last character has bits a 32-byte value cannot have */
30
+ function base64urlToHex(id) {
31
+ let hex = '';
32
+ let acc = 0;
33
+ let bits = 0;
34
+ for (const ch of id) {
35
+ acc = (acc << 6) | B64URL_ALPHABET.indexOf(ch);
36
+ bits += 6;
37
+ if (bits >= 8) { bits -= 8; hex += ((acc >> bits) & 255).toString(16).padStart(2, '0'); acc &= (1 << bits) - 1; }
38
+ }
39
+ // 43 characters are 258 bits: the last two must be zero, or two different ids would name the same key
40
+ return acc === 0 ? hex : null;
41
+ }
42
+
43
+ /**
44
+ * Convert a hex fingerprint to a base64url pod id.
45
+ * @param {string} hexFingerprint exactly 64 hex digits (either case): the SHA-256 of a raw public key
46
+ * @returns {string} the 43-character base64url pod id
47
+ */
48
+ export function fingerprintToPodId(hexFingerprint) {
49
+ if (typeof hexFingerprint !== 'string' || !HEX_RE.test(hexFingerprint)) {
50
+ throw new TypeError('fingerprintToPodId: expected a fingerprint of exactly 64 hex digits (the SHA-256 of a public key)');
51
+ }
52
+ return hexToBase64url(hexFingerprint.toLowerCase());
53
+ }
54
+
55
+ /**
56
+ * Convert a base64url pod id to a hex fingerprint.
57
+ * @param {string} podIdStr exactly 43 base64url characters (no padding), in the canonical spelling
58
+ * @returns {string} 64 lower-case hex digits
59
+ */
60
+ export function podIdToFingerprint(podIdStr) {
61
+ const hex = typeof podIdStr === 'string' && B64URL_RE.test(podIdStr) ? base64urlToHex(podIdStr) : null;
62
+ if (hex === null) throw new TypeError('podIdToFingerprint: expected a pod id of exactly 43 base64url characters (the SHA-256 of a public key)');
63
+ return hex;
64
+ }
65
+
66
+ /**
67
+ * Who a call is from, in the one shape every layer of the package uses: `{ username, fingerprint, podId }`. A caller that arrives over
68
+ * wsh has a login name and a key (the hex `fingerprint`); one that arrives over a mesh has a pod id. Both are the hash of the same
69
+ * kind of key, so whichever is given, the other is derived: an `authorize(who, op)` callback written for one world reads the other's
70
+ * callers the same way, and nobody has to put a pod id in a field named `fingerprint`.
71
+ *
72
+ * An identity that names two different keys, or whose `podId` is not a pod id, is refused. A caller with no key (a password login)
73
+ * has `fingerprint: null` and `podId: null`.
74
+ *
75
+ * @param {{ username?: string | null, fingerprint?: string | null, podId?: string | null } | null | undefined} who
76
+ * @param {{ strict?: boolean, derivePodId?: boolean }} [options] `strict: false` keeps a `fingerprint` that is not a key hash as it was
77
+ * given (a host may name its callers some other way) and derives no pod id from it; the default refuses it. `derivePodId: false`
78
+ * derives no pod id from a fingerprint (a `podId` that was given is kept, and always gives the fingerprint): what the object and MCP
79
+ * layers use, so a caller that came in over wsh keeps the `{ username, fingerprint }` it always had.
80
+ * @returns {{ username: string | null, fingerprint: string | null, podId: string | null }}
81
+ */
82
+ export function normalizeIdentity(who, { strict = true, derivePodId = true } = {}) {
83
+ if (who === null || who === undefined) return { username: null, fingerprint: null, podId: null };
84
+ if (typeof who !== 'object' || Array.isArray(who)) throw new TypeError('an identity is an object { username, fingerprint, podId }');
85
+ const { username = null, fingerprint = null, podId = null } = who;
86
+ if (username !== null && typeof username !== 'string') throw new TypeError('identity.username must be a string or null');
87
+ if (fingerprint !== null && typeof fingerprint !== 'string') throw new TypeError('identity.fingerprint must be a string or null');
88
+ if (podId !== null && typeof podId !== 'string') throw new TypeError('identity.podId must be a string or null');
89
+ let fp = fingerprint === null ? null : (HEX_RE.test(fingerprint) ? fingerprint.toLowerCase() : fingerprint);
90
+ if (fp !== null && !HEX_RE.test(fp) && strict) throw new TypeError('identity.fingerprint must be 64 hex digits (the SHA-256 of a public key)');
91
+ let id = podId;
92
+ if (id !== null) {
93
+ const fromId = podIdToFingerprint(id); // throws for something that is not a pod id
94
+ if (fp !== null && HEX_RE.test(fp) && fp !== fromId) throw new TypeError('identity.fingerprint and identity.podId name different keys');
95
+ if (fp !== null && !HEX_RE.test(fp)) throw new TypeError('identity.fingerprint and identity.podId name different keys');
96
+ fp = fromId;
97
+ } else if (derivePodId && fp !== null && HEX_RE.test(fp)) {
98
+ id = fingerprintToPodId(fp);
99
+ }
100
+ return { username, fingerprint: fp, podId: id };
101
+ }
102
+
103
+ /**
104
+ * The identity a layer hands to `authorize(who, op)`, a prompt or an `onCall` callback: what it was given, with `fingerprint` and (when
105
+ * the transport knows it) `podId` agreeing. A caller that arrived over wsh keeps its old shape `{ username, fingerprint }`; one that
106
+ * arrived with only a `podId` (a mesh adapter) also gets the hex `fingerprint`. Extra fields the transport put on it are kept.
107
+ * `undefined` stays `undefined` (no identity given).
108
+ * @param {object | undefined} who
109
+ * @returns {{ username: string | null, fingerprint: string | null, podId?: string } | undefined}
110
+ */
111
+ export function callerIdentity(who) {
112
+ if (who === undefined) return undefined;
113
+ const n = normalizeIdentity(who, { strict: false, derivePodId: false });
114
+ return { ...who, username: n.username, fingerprint: n.fingerprint, ...(n.podId !== null ? { podId: n.podId } : {}) };
115
+ }
@@ -2,6 +2,8 @@
2
2
  * `authorized_keys` options (wsh #122): what a key's leading options mean, parsed the same way by the Node host (this file) and
3
3
  * the Rust `wsh-server` (`crates/wsh-server/src/auth/permissions.rs`). `spec/key-options.vectors.json` holds the shared test
4
4
  * vectors both suites run, so the two cannot drift. Browser-safe (no Node imports): the in-memory host uses it too.
5
+ * The notation of capabilities is written in `spec/capabilities.md`, with `spec/capabilities.vectors.json` run by both hosts, and the
6
+ * pure function over it is `permits()` of `@johnhenry/wsh/capabilities`.
5
7
  *
6
8
  * A line is `[options] ssh-ed25519 <base64> [comment]`. `options` is one token (no whitespace outside double quotes) of
7
9
  * comma-separated items, each `name` or `name=value`, where a value is `"..."` (a `\"` is a quote, any other backslash is
@@ -345,6 +347,9 @@ function capabilityRefusal(p, req) {
345
347
  else if (req.channel === 'file') { const need_ = req.direction === 'download' ? 'fs:read' : 'fs:write'; r = need(need_, has(need_)); }
346
348
  else if (req.channel === 'rpc') {
347
349
  const proto = req.protocol;
350
+ // A handler that says it authorizes for itself (`authorizesItself`: it asks the host's own `permits` for every call) is opened by any key the
351
+ // options let in: the list does not have to name its protocol. The options and the expiry were checked before this; only the `rpc:`/`mcp:` entry is deferred.
352
+ if (req.authorizesItself === true) return req.target === undefined || req.target === null ? null : target();
348
353
  // The file rpc has read and write methods on one channel: a key without both is refused it (a client falls back to
349
354
  // FileOp and the file channels, which are checked per operation).
350
355
  if (proto === 'wsh-fs') r = need('fs:read', has('fs:read')) ?? need('fs:write', has('fs:write'));
@@ -0,0 +1,184 @@
1
+ /**
2
+ * MCP over any duplex (#220). The handler of `webmcpTools` (and any rpc handler of the `mcp` protocol written as `(channel, ctx) => void`)
3
+ * serves MCP on a channel; over wsh that channel is an `RpcChannel` of the `mcp` rpc protocol. `serveMcpOverDuplex` gives the same handler
4
+ * a channel made of nothing but two functions you already have: `send(message)` for what goes to the far side, and `receive(message)` for
5
+ * what comes from it, so a transport that is not wsh at all (a mesh channel, a `MessagePort`, a data channel, a test) can carry it.
6
+ *
7
+ * ```js
8
+ * import { webmcpTools, serveMcpOverDuplex } from '@johnhenry/wsh/page';
9
+ * const handler = webmcpTools({ window, allow: ['search'], approve: 'consequential' });
10
+ * const session = serveMcpOverDuplex(handler, { send: (message) => meshChannel.send(message), who: { podId } });
11
+ * meshChannel.onmessage = (message) => session.receive(message);
12
+ * meshChannel.onclose = () => session.close('the peer left');
13
+ * ```
14
+ *
15
+ * WHAT THE FAR SIDE SPEAKS: plain MCP, that is JSON-RPC 2.0 messages as JavaScript objects (`{ jsonrpc: '2.0', id, method, params }`,
16
+ * `{ jsonrpc: '2.0', id, result }` or `{ jsonrpc: '2.0', id, error: { code, message, data? } }`, and notifications with no `id`): an MCP SDK
17
+ * `Client` can be connected to it through any `Transport` that moves those objects. Encoding them (JSON text, CBOR, structured clone) is the
18
+ * transport's business; this file sees objects. No batches (MCP no longer has them), no ids but strings and integers, one answer per id.
19
+ *
20
+ * WHAT IS THE HANDLER'S, UNCHANGED: the allow-list of tools, the bounds on tools, schemas, arguments and results, the approval of the
21
+ * person at the page (`approve`, `prompt`), the `onCall` events and the labelling of every result as untrusted page content. WHAT THIS
22
+ * ADDS: the bounds of the seam itself (the size of a message in either direction, the requests running at once, one id one request), and
23
+ * the refusal of anything that is not a JSON-RPC 2.0 message from the far side.
24
+ *
25
+ * It does NOT authenticate the far side or seal anything: whoever the transport says is on the other end is `who`, and `permits` is
26
+ * whatever that transport's grants allow. Those are the adapter's to establish and say; they are not in the messages.
27
+ */
28
+
29
+ import { RpcError, RPC_ERROR } from './rpc.mjs';
30
+ import { callerIdentity } from './key-names.mjs';
31
+
32
+ const DEFAULT_MAX_MESSAGE_BYTES = 1024 * 1024;
33
+ const DEFAULT_MAX_INFLIGHT = 64;
34
+ const MAX_ID_CHARS = 256;
35
+
36
+ const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
37
+
38
+ /** UTF-8 length of the JSON of `value` (the size of the message on a JSON transport), or -1 when it has none. */
39
+ function jsonBytes(value) {
40
+ let s;
41
+ try { s = JSON.stringify(value); } catch { return -1; }
42
+ if (typeof s !== 'string') return -1;
43
+ let n = 0;
44
+ for (let i = 0; i < s.length; i++) {
45
+ const c = s.charCodeAt(i);
46
+ if (c < 0x80) n += 1;
47
+ else if (c < 0x800) n += 2;
48
+ else if (c >= 0xd800 && c <= 0xdbff) { n += 4; i++; } else n += 3;
49
+ }
50
+ return n;
51
+ }
52
+
53
+ const validId = (id) => (typeof id === 'string' && id.length >= 1 && id.length <= MAX_ID_CHARS) || (Number.isSafeInteger(id));
54
+
55
+ /**
56
+ * Serve an MCP handler over a duplex.
57
+ *
58
+ * @param {(channel: object, ctx?: object) => void} handler what `webmcpTools(...)` returns, or any handler written for an rpc channel of the `mcp` protocol
59
+ * @param {object} options
60
+ * @param {(message: object) => void | Promise<void>} options.send writes a JSON-RPC 2.0 message to the far side; a throw (or a rejection) ends the session
61
+ * @param {{ username?: string | null, fingerprint?: string | null, podId?: string | null }} [options.who] who is on the far side, as the transport knows
62
+ * it: the handler's prompt, `onCall` events and `closeSessions(reason, fingerprint)` see it (`fingerprint` and `podId` agree, see `callerIdentity`)
63
+ * @param {(request: { kind: string, [field: string]: unknown }) => boolean} [options.permits] the far side's grants, asked afresh for each tool
64
+ * (`{ kind: 'mcp-tool', tool }`); with none, nothing narrows the handler's own allow-list. `@johnhenry/wsh/capabilities`'s `permits` fits: `(req) => permits(caps, req)`
65
+ * @param {number} [options.maxMessageBytes=1048576] the largest message, JSON-encoded, in either direction
66
+ * @param {number} [options.maxInflight=64] requests of the far side being answered at once, of any kind
67
+ * @returns {{ receive(message: unknown): void, close(reason?: string): void, readonly closed: boolean, readonly who: object | undefined }}
68
+ */
69
+ export function serveMcpOverDuplex(handler, options = {}) {
70
+ if (typeof handler !== 'function') throw new TypeError('serveMcpOverDuplex: the handler must be a function (channel, ctx), what webmcpTools() returns');
71
+ const { send, who, permits, maxMessageBytes = DEFAULT_MAX_MESSAGE_BYTES, maxInflight = DEFAULT_MAX_INFLIGHT } = options;
72
+ if (typeof send !== 'function') throw new TypeError('serveMcpOverDuplex: send(message) is required');
73
+ if (permits !== undefined && typeof permits !== 'function') throw new TypeError('serveMcpOverDuplex: permits must be a function');
74
+ if (!Number.isSafeInteger(maxMessageBytes) || maxMessageBytes < 256) throw new TypeError('serveMcpOverDuplex: maxMessageBytes must be a whole number of at least 256');
75
+ if (!Number.isSafeInteger(maxInflight) || maxInflight < 1) throw new TypeError('serveMcpOverDuplex: maxInflight must be a positive whole number');
76
+ const identity = callerIdentity(who);
77
+
78
+ let closed = false;
79
+ const requestHandlers = new Map();
80
+ const notificationHandlers = new Map();
81
+ /** id -> its AbortController, for what is being answered. */
82
+ const inflight = new Map();
83
+
84
+ const fail = (reason) => { try { session.close(reason); } catch { /* already closing */ } };
85
+ /** Write one message; a throw or rejection of the transport ends the session. Resolves when written. */
86
+ async function write(message) {
87
+ if (closed) return;
88
+ const size = jsonBytes(message);
89
+ if (size < 0) throw new TypeError('the message cannot be serialised as JSON');
90
+ if (size > maxMessageBytes) throw new RpcError(RPC_ERROR.INTERNAL, `refused: a message of ${size} bytes is larger than maxMessageBytes (${maxMessageBytes})`, { reason: 'message-too-large' });
91
+ try { await send(message); } catch (e) { fail('the transport failed to send'); throw e; }
92
+ }
93
+ const respond = (id, body) => write({ jsonrpc: '2.0', id, ...body }).catch(() => {});
94
+ const refuse = (id, code, message, data) => respond(id, { error: { code, message, ...(data !== undefined ? { data } : {}) } });
95
+
96
+ /** The channel the handler is given: the part of an `RpcChannel` that an MCP handler uses. */
97
+ const channel = {
98
+ maxMessageBytes,
99
+ onRequest(method, fn) { requestHandlers.set(method, fn); },
100
+ onNotification(method, fn) { notificationHandlers.set(method, fn); },
101
+ notify: (method, params) => write({ jsonrpc: '2.0', method, ...(params !== undefined ? { params } : {}) }),
102
+ request: () => Promise.reject(new RpcError(RPC_ERROR.METHOD_NOT_FOUND, 'this side serves MCP and asks the far side nothing')),
103
+ close: async (reason) => { session.close(reason); },
104
+ onClose: null,
105
+ get closed() { return closed; },
106
+ };
107
+
108
+ async function dispatch(id, method, params) {
109
+ const fn = requestHandlers.get(method);
110
+ if (!fn) { await refuse(id, RPC_ERROR.METHOD_NOT_FOUND, `method not found: ${method}`); return; }
111
+ const ctl = new AbortController();
112
+ inflight.set(id, ctl);
113
+ try {
114
+ const result = await fn(params, { id, signal: ctl.signal });
115
+ // A cancelled request is not answered: the far side said it no longer wants the answer.
116
+ if (!closed && !ctl.signal.aborted) {
117
+ const body = { jsonrpc: '2.0', id, result: result === undefined ? {} : result };
118
+ const size = jsonBytes(body);
119
+ if (size < 0) await refuse(id, RPC_ERROR.INTERNAL, 'the answer cannot be serialised as JSON');
120
+ else if (size > maxMessageBytes) await refuse(id, RPC_ERROR.INTERNAL, `refused: the answer is ${size} bytes, larger than maxMessageBytes (${maxMessageBytes})`, { reason: 'message-too-large' });
121
+ else await write(body).catch(() => {});
122
+ }
123
+ } catch (e) {
124
+ if (!closed && !ctl.signal.aborted) {
125
+ if (e instanceof RpcError) await refuse(id, e.code, e.message, e.toJSON().data);
126
+ else await refuse(id, RPC_ERROR.INTERNAL, String(e?.message ?? e));
127
+ }
128
+ } finally {
129
+ inflight.delete(id);
130
+ }
131
+ }
132
+
133
+ const session = {
134
+ /** Hand over one message from the far side. Never throws: what cannot be answered is refused or dropped. */
135
+ receive(message) {
136
+ if (closed) return;
137
+ if (!isObject(message) || message.jsonrpc !== '2.0') {
138
+ // An id we can read is answered; anything else is dropped (there is no one to tell).
139
+ if (isObject(message) && validId(message.id)) void refuse(message.id, RPC_ERROR.INVALID_REQUEST, 'not a JSON-RPC 2.0 message (batches are not supported)');
140
+ else if (Array.isArray(message) || message === null || typeof message !== 'object') void refuse(null, RPC_ERROR.INVALID_REQUEST, 'not a JSON-RPC 2.0 message (batches are not supported)');
141
+ return;
142
+ }
143
+ const size = jsonBytes(message);
144
+ if (size < 0 || size > maxMessageBytes) {
145
+ void refuse(validId(message.id) ? message.id : null, RPC_ERROR.INVALID_REQUEST, `refused: a message larger than maxMessageBytes (${maxMessageBytes})`, { reason: 'message-too-large' });
146
+ return;
147
+ }
148
+ const hasId = Object.hasOwn(message, 'id');
149
+ if (typeof message.method !== 'string') {
150
+ // A response (or error) of the far side: nothing here asked it anything.
151
+ if (hasId && !('result' in message) && !('error' in message)) void refuse(validId(message.id) ? message.id : null, RPC_ERROR.INVALID_REQUEST, 'a request needs a method');
152
+ return;
153
+ }
154
+ if (message.params !== undefined && !isObject(message.params)) {
155
+ if (hasId) void refuse(validId(message.id) ? message.id : null, RPC_ERROR.INVALID_REQUEST, 'params must be an object');
156
+ return;
157
+ }
158
+ if (!hasId) {
159
+ // A notification. Cancellation is the one the seam knows: it aborts the request the far side names.
160
+ if (message.method === 'notifications/cancelled') inflight.get(message.params?.requestId)?.abort(new Error('cancelled by the caller'));
161
+ try { notificationHandlers.get(message.method)?.(message.params); } catch { /* a notification has no one to tell */ }
162
+ return;
163
+ }
164
+ if (!validId(message.id)) { void refuse(null, RPC_ERROR.INVALID_REQUEST, 'a request id is a string or a whole number'); return; }
165
+ if (inflight.has(message.id)) { void refuse(message.id, RPC_ERROR.INVALID_REQUEST, `request id ${JSON.stringify(message.id)} is still in flight`); return; }
166
+ if (inflight.size >= maxInflight) { void refuse(message.id, RPC_ERROR.STREAM_LIMIT, `refused: maxInflight: more than ${maxInflight} requests at once`, { limit: 'maxInflight' }); return; }
167
+ void dispatch(message.id, message.method, message.params);
168
+ },
169
+
170
+ /** End the session: running calls are aborted, the handler's watchers are removed, nothing more is answered. */
171
+ close(reason = 'closed') {
172
+ if (closed) return;
173
+ closed = true;
174
+ for (const ctl of inflight.values()) ctl.abort(new Error(`the session ended (${reason})`));
175
+ try { channel.onClose?.(reason); } catch { /* the handler's own */ }
176
+ },
177
+
178
+ get closed() { return closed; },
179
+ get who() { return identity; },
180
+ };
181
+
182
+ handler(channel, { ...(identity ? { who: identity, user: identity.username, fingerprint: identity.fingerprint } : {}), ...(permits ? { permits } : {}) });
183
+ return session;
184
+ }
@@ -90,6 +90,11 @@ export interface WshMemoryHostOptions {
90
90
  sealSession?: false | 'offer' | 'require';
91
91
  /** #163: told once per connection this host turned away (a key it does not allow, a plain client on a host that requires a sealed session, ...), with a stable reason code. */
92
92
  onRefused?: WshOnRefused;
93
+ /**
94
+ * Called once per connection when its session has been sealed (after login). With `sealSession: 'require'` a login is not yet a session
95
+ * that can do anything: `auth.authorize(who)` is told `who.sealRequired: true`, and audit or an indicator belongs here instead.
96
+ */
97
+ onSealed?: (who: { username: string | null; fingerprint: string | null }) => void;
93
98
  /**
94
99
  * #121: execution targets, each with its own `exec`, `pty`, `fs` and `endpoints` and an `authorize(who, { target, kind })`.
95
100
  * A client names one in `Open`, `FileOp` or `OpenEndpoint` and lists what it may use with `listTargets()`. Off unless given:
@@ -180,7 +180,8 @@ function createRegistry(sessions, log) {
180
180
  * @param {(line: string) => void} [options.onLog]
181
181
  */
182
182
  export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions, rpc, rpcMaxMessageBytes = RPC_DEFAULT_MAX_MESSAGE, rpcMaxInflight = 64, sessions, endpoints, dataStreams = true, bindTimeoutMs = 3000, connectionTtlMs = 0, requireChannelBinding = false, sealSession = false, onLog = () => {},
183
- onShare, onRefused, targets, requireTarget, usernamePattern } = {}) {
183
+ onShare, onRefused, onSealed, targets, requireTarget, usernamePattern } = {}) {
184
+ if (onSealed !== undefined && typeof onSealed !== 'function') throw new TypeError('createMemoryHost: onSealed must be a function');
184
185
  resolveUsernamePattern(usernamePattern, 'createMemoryHost');
185
186
  validateOnShare(onShare, 'createMemoryHost');
186
187
  validateOnRefused(onRefused, 'createMemoryHost');
@@ -217,7 +218,7 @@ export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions
217
218
 
218
219
  const ready = Promise.all([buildAuthorizer(auth, { log: onLog }), hostKeyReady]).then(([authorize, hostKeyResolved]) => createConnectionFactory({
219
220
  authorize, execRunner, execOptions, pty: ptyBackend, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, sealSession, log: onLog,
220
- methods, hostKey: hostKeyResolved, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, onShare, onRefused,
221
+ methods, hostKey: hostKeyResolved, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, onShare, onRefused, onSealed,
221
222
  targets: targetTable, requireTarget: mustHaveTarget, usernamePattern,
222
223
  gateway: gatewayCfg, createGatewaySession: gatewayCfg ? createEndpointGatewaySession : undefined, sessions: registry, relay: null,
223
224
  }));