@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.
package/src/auth.mjs CHANGED
@@ -465,31 +465,9 @@ export async function podId(publicKeyRaw) {
465
465
  return base64urlEncode(new Uint8Array(hash));
466
466
  }
467
467
 
468
- /**
469
- * Convert a hex fingerprint to a base64url pod ID.
470
- * @param {string} hexFingerprint - 64-char hex fingerprint
471
- * @returns {string} base64url pod ID
472
- */
473
- export function fingerprintToPodId(hexFingerprint) {
474
- if (typeof hexFingerprint !== 'string' || !/^(?:[0-9a-fA-F]{2})+$/.test(hexFingerprint)) {
475
- throw new TypeError('fingerprintToPodId: expected a hex fingerprint');
476
- }
477
- const bytes = new Uint8Array(hexFingerprint.length / 2);
478
- for (let i = 0; i < bytes.length; i++) {
479
- bytes[i] = parseInt(hexFingerprint.slice(i * 2, i * 2 + 2), 16);
480
- }
481
- return base64urlEncode(bytes);
482
- }
483
-
484
- /**
485
- * Convert a base64url pod ID to a hex fingerprint.
486
- * @param {string} podIdStr - base64url pod ID
487
- * @returns {string} hex fingerprint
488
- */
489
- export function podIdToFingerprint(podIdStr) {
490
- const bytes = base64urlDecode(podIdStr);
491
- return hexEncode(bytes);
492
- }
468
+ // The two conversions between a fingerprint and a pod id live in `key-names.mjs` (pure, no crypto), so that the object and MCP layers
469
+ // can use them without this file; they are the same functions, and strict: exactly a 32-byte hash, in its canonical spelling.
470
+ export { fingerprintToPodId, podIdToFingerprint } from './key-names.mjs';
493
471
 
494
472
  /**
495
473
  * Get the shortest unique prefix of a fingerprint within a set.
@@ -529,15 +507,6 @@ function base64urlEncode(bytes) {
529
507
  return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
530
508
  }
531
509
 
532
- function base64urlDecode(str) {
533
- let b64 = str.replace(/-/g, '+').replace(/_/g, '/');
534
- while (b64.length % 4) b64 += '=';
535
- const binary = atob(b64);
536
- const bytes = new Uint8Array(binary.length);
537
- for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
538
- return bytes;
539
- }
540
-
541
510
  function base64Encode(bytes) {
542
511
  let binary = '';
543
512
  for (const b of bytes) binary += String.fromCharCode(b);
@@ -0,0 +1,53 @@
1
+ /**
2
+ * `@johnhenry/wsh/capabilities`: the notation of key capabilities as a pure function. The notation is written in
3
+ * `spec/capabilities.md` and its vectors in `spec/capabilities.vectors.json` (both in the package, under `@johnhenry/wsh/spec/`).
4
+ * Browser-safe (no Node import); a stable entry point.
5
+ */
6
+
7
+ /** A request a capability list is asked about; the kinds, and what each needs, are in `spec/capabilities.md`. */
8
+ export type CapabilityRequest =
9
+ | { kind: 'login' }
10
+ | { kind: 'open'; channel: 'pty' | 'exec'; target?: string }
11
+ | { kind: 'open'; channel: 'file'; direction: 'upload' | 'download'; target?: string }
12
+ | { kind: 'open'; channel: 'rpc'; protocol: string; scoped?: boolean; target?: string }
13
+ | { kind: 'file-op'; op: string; target?: string }
14
+ | { kind: 'mcp' }
15
+ | { kind: 'mcp-call' | 'mcp-tool'; tool: string }
16
+ | { kind: 'objects'; root: string; op: 'get' | 'call' | 'set' | 'on' | 'walk' }
17
+ | { kind: 'relay' }
18
+ | { kind: 'key-admin' }
19
+ | { kind: 'tcp' | 'udp'; host: string; port: number }
20
+ | { kind: 'dns'; name: string }
21
+ | { kind: 'listen-tcp'; port: number }
22
+ | { kind: 'unix' | 'listen-unix'; path: string }
23
+ | { kind: 'endpoint'; name: string; target?: string }
24
+ | { kind: 'target'; name: string };
25
+
26
+ export interface CapabilityRefusal {
27
+ /** `capability-missing` (see `capability`), `key-expired`, `key-admin-not-permitted`, or `unknown-capability` / `bad-capability` for a list with an entry that is not understood (the whole list is refused). */
28
+ code: string;
29
+ reason: string;
30
+ /** The capability that was needed, for `capability-missing`. */
31
+ capability?: string;
32
+ }
33
+
34
+ export interface CapabilityOptions {
35
+ /** An RFC 3339 string, a `Date` or epoch milliseconds: the instant from which the list is refused. */
36
+ expires?: string | Date | number;
37
+ /** A `Date` or epoch milliseconds (default: the present). */
38
+ now?: Date | number;
39
+ }
40
+
41
+ /** The revision of the notation implemented here: the `version` of `spec/capabilities.vectors.json`. */
42
+ export const CAPABILITIES_NOTATION_VERSION: 1;
43
+
44
+ /** Parse a capability list; `{ ok: false, code, reason }` for an entry that is unknown or malformed. */
45
+ export function parseCapabilityList(list: string | string[]):
46
+ | { ok: true; capabilities: string[]; parsed: object[] }
47
+ | { ok: false; code: string; reason: string };
48
+
49
+ /** `null` when a holder of `capabilities` may make `request`, else why not. Fails closed. */
50
+ export function checkCapabilities(capabilities: string[] | string, request: CapabilityRequest, options?: CapabilityOptions): CapabilityRefusal | null;
51
+
52
+ /** Whether a holder of `capabilities` may make `request`. A list with an entry that is not understood, no list, or an unknown request kind permits nothing. */
53
+ export function permits(capabilities: string[] | string, request: CapabilityRequest, options?: CapabilityOptions): boolean;
@@ -0,0 +1,69 @@
1
+ /**
2
+ * `@johnhenry/wsh/capabilities` -- the notation of key capabilities, as a pure function (browser-safe, no Node import).
3
+ *
4
+ * import { permits } from '@johnhenry/wsh/capabilities';
5
+ * permits(['exec', 'gateway:tcp:*.example.com:443', 'objects:window:get'], { kind: 'tcp', host: 'api.example.com', port: 443 }); // true
6
+ *
7
+ * What a list means (the grammar, what each wildcard matches, the request kinds and what each needs, and what an
8
+ * implementation does with something it does not understand) is written in `spec/capabilities.md`, and
9
+ * `spec/capabilities.vectors.json` holds the vectors that the JS evaluation and the Rust `wsh-server` both run. Both files are
10
+ * published in the package (`@johnhenry/wsh/spec/capabilities.md`, `@johnhenry/wsh/spec/capabilities.vectors.json`), so another
11
+ * implementation can run the same vectors.
12
+ *
13
+ * This is the same evaluation `@johnhenry/wsh/server`, the memory host and the page host run for a key's `capabilities="..."`;
14
+ * it is exported so a registry of grants in another system (a mesh peer's) can use it instead of keeping a second reading
15
+ * of the notation.
16
+ */
17
+
18
+ import { grantPermissions, checkKeyRequest, parseCapabilityList } from './key-options.mjs';
19
+
20
+ /** The revision of the notation these functions implement: the `version` of `spec/capabilities.vectors.json`. */
21
+ export const CAPABILITIES_NOTATION_VERSION = 1;
22
+
23
+ export { parseCapabilityList };
24
+
25
+ /** `Date | epoch milliseconds | RFC 3339 string | undefined` as epoch seconds, or `undefined`. */
26
+ function toSeconds(now) {
27
+ if (now === undefined || now === null) return undefined;
28
+ const ms = now instanceof Date ? now.getTime() : now;
29
+ if (typeof ms !== 'number' || !Number.isFinite(ms)) throw new TypeError('now must be a Date or epoch milliseconds');
30
+ return Math.floor(ms / 1000);
31
+ }
32
+
33
+ /**
34
+ * Whether a holder of `capabilities` may make `request`, with the reason when not: `null` when permitted, else `{ code, reason,
35
+ * capability? }`. `code` is `capability-missing` (`capability` names what was needed) or `key-expired`; a list that has an entry
36
+ * this implementation does not understand is refused whole, with its `unknown-capability` or `bad-capability` code (the list
37
+ * permits nothing). `capabilities` that is not an array of strings (including `null` and `undefined`: no list is no grant) is refused
38
+ * as `bad-capability`.
39
+ *
40
+ * @param {string[] | string} capabilities a list of capability strings (a comma separated string is read the same way as `capabilities="..."`)
41
+ * @param {{ kind: string, [field: string]: unknown }} request what is asked; the kinds are in `spec/capabilities.md`
42
+ * @param {{ expires?: string | Date | number, now?: Date | number }} [options] `expires`: an RFC 3339 string, a `Date` or epoch
43
+ * milliseconds, the instant from which the list is refused; `now`: a `Date` or epoch milliseconds (default: the present)
44
+ * @returns {null | { code: string, reason: string, capability?: string }}
45
+ */
46
+ export function checkCapabilities(capabilities, request, { expires, now } = {}) {
47
+ if (!(Array.isArray(capabilities) || typeof capabilities === 'string')) {
48
+ return { code: 'bad-capability', reason: 'a capability list is an array of strings' };
49
+ }
50
+ if (request === null || typeof request !== 'object' || typeof request.kind !== 'string') {
51
+ return { code: 'capability-missing', reason: 'a request is an object with a kind' };
52
+ }
53
+ const granted = grantPermissions({ capabilities, ...(expires !== undefined ? { expires } : {}) });
54
+ if (!granted.ok) return { code: granted.code, reason: granted.reason };
55
+ return checkKeyRequest(granted.permissions, request, { now: toSeconds(now) });
56
+ }
57
+
58
+ /**
59
+ * Whether a holder of `capabilities` may make `request`. Fails closed: a list with an entry this implementation does not
60
+ * understand, a missing list, or a request of a kind it does not know permits nothing. See `checkCapabilities` for the reason.
61
+ *
62
+ * @param {string[] | string} capabilities
63
+ * @param {{ kind: string, [field: string]: unknown }} request
64
+ * @param {{ expires?: string | Date | number, now?: Date | number }} [options]
65
+ * @returns {boolean}
66
+ */
67
+ export function permits(capabilities, request, options) {
68
+ return checkCapabilities(capabilities, request, options) === null;
69
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * `@johnhenry/wsh/duplex`: a full wsh session over a duplex of messages that another library provides (a mesh channel, a `MessagePort`).
3
+ * Browser-safe. See `spec/duplex-binding.md` for what the duplex must guarantee and what a hop can and cannot do.
4
+ */
5
+ import type { WshClient } from './index.js';
6
+
7
+ export const DUPLEX_DEFAULT_MAX_MESSAGE_BYTES: 65536;
8
+ export const DUPLEX_DEFAULT_MAX_BUFFERED_BYTES: 4194304;
9
+
10
+ export interface WshDuplexOptions {
11
+ /** Writes ONE message to the far side (reliable, in order). May be asynchronous: the next message waits for it. A throw or rejection ends the link. */
12
+ send(bytes: Uint8Array): void | Promise<void>;
13
+ /** Ends the underlying duplex (called when the session ends; not called after `end()`). */
14
+ close?(reason?: string): void;
15
+ /** Default 65536. A bigger write is cut into messages of at most this size; a bigger incoming message ends the link. */
16
+ maxMessageBytes?: number;
17
+ /** Default 4194304. Bytes waiting for `send` (or for a listener) before the link is ended. */
18
+ maxBufferedBytes?: number;
19
+ }
20
+
21
+ /** What `createDuplexSocket` makes: a WebSocket-shaped object the transport and `host.accept` take, and the two calls that feed it. */
22
+ export function createDuplexSocket(options: WshDuplexOptions): {
23
+ socket: object;
24
+ /** One message from the far side. */
25
+ receive(data: Uint8Array | ArrayBuffer): void;
26
+ /** The duplex ended on its own. */
27
+ end(reason?: string): void;
28
+ readonly closed: boolean;
29
+ };
30
+
31
+ /**
32
+ * Serve a host's session over a duplex, SEALED (the host serves nothing until the session is sealed, whatever its own `sealSession`). The host needs a
33
+ * host key; with none `ready` rejects. `allowUnsealed: true` lifts it.
34
+ */
35
+ export function serveWshOverDuplex(
36
+ host: { accept(socket: object, options?: object): Promise<{ close(): void }> },
37
+ options: WshDuplexOptions & { allowUnsealed?: boolean; remote?: { address?: string } },
38
+ ): {
39
+ receive(data: Uint8Array | ArrayBuffer): void;
40
+ end(reason?: string): void;
41
+ ready: Promise<{ close(): void }>;
42
+ close(): void;
43
+ };
44
+
45
+ /**
46
+ * Connect a client over a duplex: key login, sealed, bound to the host key, and the host key must be named (`expectHostKey`, `knownHosts`, or
47
+ * `trustOnFirstUse: true`). `allowUnsealed: true` lifts the seal and the binding; a password login needs it.
48
+ */
49
+ export function connectWshOverDuplex(
50
+ duplex: WshDuplexOptions,
51
+ credentials: {
52
+ username: string;
53
+ keyPair?: CryptoKeyPair;
54
+ signer?: { publicKey: Uint8Array | CryptoKey; sign(data: Uint8Array): Promise<Uint8Array> | Uint8Array };
55
+ password?: string;
56
+ expectHostKey?: string;
57
+ knownHosts?: object;
58
+ trustOnFirstUse?: boolean;
59
+ allowUnsealed?: boolean;
60
+ timeout?: number;
61
+ [option: string]: unknown;
62
+ },
63
+ ): {
64
+ receive(data: Uint8Array | ArrayBuffer): void;
65
+ end(reason?: string): void;
66
+ client: WshClient;
67
+ connected: Promise<WshClient>;
68
+ close(): Promise<void>;
69
+ };
package/src/duplex.mjs ADDED
@@ -0,0 +1,208 @@
1
+ /**
2
+ * `@johnhenry/wsh/duplex` -- a full wsh session over a duplex that someone else provides (#220): a mesh channel, a `MessagePort`, a data
3
+ * channel, anything that can carry bytes in order. Browser-safe. The specification, with what the duplex must guarantee and what a hop on it can
4
+ * and cannot do, is `spec/duplex-binding.md`; this file is the binding.
5
+ *
6
+ * ```js
7
+ * // the host side (a page, a pod): a memory host with a host key, served over the link
8
+ * const host = createMemoryHost({ auth: { authorizedKeys }, hostKey: true, dataStreams: false, exec });
9
+ * const served = serveWshOverDuplex(host, { send: (bytes) => channel.send(bytes) });
10
+ * channel.onmessage = (bytes) => served.receive(bytes);
11
+ *
12
+ * // the client side: pinned to the host key it expects (a mesh knows the peer's key), sealed
13
+ * const link = connectWshOverDuplex({ send: (bytes) => channel.send(bytes) }, { username: 'alice', keyPair, expectHostKey });
14
+ * channel.onmessage = (bytes) => link.receive(bytes);
15
+ * const client = await link.connected;
16
+ * ```
17
+ *
18
+ * Nothing new is on the wire: the duplex carries what a WebSocket would (QMux records), and `createDuplexSocket` is the WebSocket-shaped
19
+ * object the existing transport and `host.accept` already take. A session over it is SEALED unless you say `allowUnsealed: true` out loud.
20
+ */
21
+
22
+ import { WshClient } from './client.mjs';
23
+ import { WebSocketTransport } from './transport-ws.mjs';
24
+
25
+ const CONNECTING = 0;
26
+ const OPEN = 1;
27
+ const CLOSING = 2;
28
+ const CLOSED = 3;
29
+
30
+ /** Largest message handed to `send` unless the duplex says otherwise: what the pipe relay carries by default is 4 MiB; a mesh channel is far smaller. */
31
+ export const DUPLEX_DEFAULT_MAX_MESSAGE_BYTES = 64 * 1024;
32
+ /** Bytes held for a duplex whose `send` has not finished before the link is dropped (a peer that does not read). */
33
+ export const DUPLEX_DEFAULT_MAX_BUFFERED_BYTES = 4 * 1024 * 1024;
34
+
35
+ const toBytes = (data) => {
36
+ if (data instanceof Uint8Array) return data;
37
+ if (data instanceof ArrayBuffer) return new Uint8Array(data);
38
+ if (ArrayBuffer.isView(data)) return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
39
+ return null;
40
+ };
41
+
42
+ class DuplexEvent extends Event {
43
+ constructor(type, init = {}) { super(type); Object.assign(this, init); }
44
+ }
45
+
46
+ /**
47
+ * The WebSocket-shaped object over a duplex of messages.
48
+ *
49
+ * @param {object} options
50
+ * @param {(bytes: Uint8Array) => void | Promise<void>} options.send writes ONE message to the far side. Messages must arrive reliably and in order. It may be
51
+ * asynchronous (it is waited for before the next is written, which is the backpressure) and a rejection or throw ends the link.
52
+ * @param {(reason?: string) => void} [options.close] ends the underlying duplex
53
+ * @param {number} [options.maxMessageBytes=65536] the largest message `send` is given (a bigger write is cut into messages of at most this size: the
54
+ * transport above reads a byte stream, so where the cuts fall does not matter) and the largest message `receive` accepts (a bigger one ends the link)
55
+ * @param {number} [options.maxBufferedBytes=4194304] bytes waiting for `send`; over it the link is ended (a peer that does not read is not buffered for without bound)
56
+ * @returns {{ socket: object, receive(data: Uint8Array | ArrayBuffer): void, end(reason?: string): void, readonly closed: boolean }}
57
+ */
58
+ export function createDuplexSocket({ send, close, maxMessageBytes = DUPLEX_DEFAULT_MAX_MESSAGE_BYTES, maxBufferedBytes = DUPLEX_DEFAULT_MAX_BUFFERED_BYTES } = {}) {
59
+ if (typeof send !== 'function') throw new TypeError('createDuplexSocket: send(bytes) is required');
60
+ if (close !== undefined && typeof close !== 'function') throw new TypeError('createDuplexSocket: close must be a function');
61
+ if (!Number.isSafeInteger(maxMessageBytes) || maxMessageBytes < 256) throw new TypeError('createDuplexSocket: maxMessageBytes must be a whole number of at least 256');
62
+ if (!Number.isSafeInteger(maxBufferedBytes) || maxBufferedBytes < maxMessageBytes) throw new TypeError('createDuplexSocket: maxBufferedBytes must be a whole number of at least maxMessageBytes');
63
+
64
+ const events = new EventTarget();
65
+ let buffered = 0;
66
+ let pending = Promise.resolve();
67
+ let finished = false;
68
+
69
+ const finish = (code, reason, { callClose = true } = {}) => {
70
+ if (finished) return;
71
+ finished = true;
72
+ socket.readyState = CLOSED;
73
+ if (callClose) { try { close?.(reason); } catch { /* the duplex is already gone */ } }
74
+ events.dispatchEvent(new DuplexEvent('close', { code, reason, wasClean: code === 1000 }));
75
+ };
76
+
77
+ // A duplex is already up when the socket is made, but whoever uses the socket attaches its listeners a moment later (a client builds its
78
+ // transport after some asynchronous steps). So `open` is told to a listener that arrives after it, and messages wait, in order, for the
79
+ // first listener of `message`: nothing the far side said first (the host speaks first) is lost.
80
+ let opened = false;
81
+ let messageListeners = 0;
82
+ const incoming = [];
83
+ const flush = () => {
84
+ if (!opened || messageListeners === 0) return;
85
+ while (incoming.length && !finished) events.dispatchEvent(new DuplexEvent('message', { data: incoming.shift() }));
86
+ };
87
+
88
+ const socket = {
89
+ CONNECTING, OPEN, CLOSING, CLOSED,
90
+ readyState: CONNECTING,
91
+ binaryType: 'arraybuffer',
92
+ get bufferedAmount() { return buffered; },
93
+ addEventListener: (type, fn, options) => {
94
+ events.addEventListener(type, fn, options);
95
+ if (type === 'open' && opened && !finished) queueMicrotask(() => { if (!finished) fn(new DuplexEvent('open')); });
96
+ if (type === 'message') { messageListeners++; queueMicrotask(flush); }
97
+ },
98
+ removeEventListener: (type, fn) => events.removeEventListener(type, fn),
99
+ send(data) {
100
+ if (socket.readyState !== OPEN) throw new Error('WebSocket is not open');
101
+ const bytes = toBytes(data);
102
+ if (!bytes) return; // wsh frames are binary
103
+ for (let at = 0; at < bytes.byteLength; at += maxMessageBytes) {
104
+ const part = bytes.slice(at, at + maxMessageBytes);
105
+ if (buffered + part.byteLength > maxBufferedBytes) { finish(1013, 'the duplex does not take what is written to it'); return; }
106
+ buffered += part.byteLength;
107
+ pending = pending.then(async () => {
108
+ if (finished) return;
109
+ try { await send(part); } catch { finish(1011, 'the duplex failed to send'); } finally { buffered -= part.byteLength; }
110
+ });
111
+ }
112
+ },
113
+ close(code = 1000, reason = '') { finish(code, reason); },
114
+ };
115
+
116
+ queueMicrotask(() => { if (finished) return; socket.readyState = OPEN; opened = true; events.dispatchEvent(new DuplexEvent('open')); flush(); });
117
+
118
+ return {
119
+ socket,
120
+ /** One message from the far side. A message that is not bytes, or is larger than `maxMessageBytes`, ends the link. */
121
+ receive(data) {
122
+ if (finished) return;
123
+ const bytes = toBytes(data);
124
+ if (!bytes) { finish(1003, 'a message that is not bytes'); return; }
125
+ if (bytes.byteLength > maxMessageBytes) { finish(1009, 'a message larger than maxMessageBytes'); return; }
126
+ if (incoming.reduce((n, b) => n + b.byteLength, 0) + bytes.byteLength > maxBufferedBytes) { finish(1013, 'more arrived than the receiver takes'); return; }
127
+ incoming.push(bytes.slice().buffer);
128
+ queueMicrotask(flush); // in order, after `open`, once something listens
129
+ },
130
+ /** The duplex ended on its own (the peer left, the channel closed): the socket closes, `close` is not called back. */
131
+ end(reason = 'the duplex ended') { finish(1006, reason, { callClose: false }); },
132
+ get closed() { return finished; },
133
+ };
134
+ }
135
+
136
+ /**
137
+ * Serve a host's wsh session over a duplex: `host.accept(socket)` with `dataStreams: false` and the session SEALED, whatever the host's own
138
+ * `sealSession` says (it can only be strengthened). The host needs a host key (`hostKey: ...`): with none it cannot seal, so it cannot serve a
139
+ * duplex, and `ready` rejects. `host` is anything with `accept(socket, options)`: `createMemoryHost()`, `createWshServer()`.
140
+ *
141
+ * @param {{ accept(socket: object, options?: object): Promise<{ close(): void }> }} host
142
+ * @param {object} options as `createDuplexSocket` (`send`, `close`, `maxMessageBytes`, `maxBufferedBytes`), and
143
+ * @param {boolean} [options.allowUnsealed=false] serve a client that does not seal: nothing a hop does is then caught. Refused by default.
144
+ * @param {object} [options.remote] what the host knows of the far side (`{ address }`, for its rate limiting of password failures)
145
+ * @returns {{ receive(data: Uint8Array | ArrayBuffer): void, end(reason?: string): void, ready: Promise<{ close(): void }>, close(): void }}
146
+ */
147
+ export function serveWshOverDuplex(host, { allowUnsealed = false, remote, ...duplexOptions } = {}) {
148
+ if (typeof host?.accept !== 'function') throw new TypeError('serveWshOverDuplex: host must have accept(socket, options) (createMemoryHost(), createWshServer())');
149
+ if (typeof allowUnsealed !== 'boolean') throw new TypeError('serveWshOverDuplex: allowUnsealed must be true or false');
150
+ const link = createDuplexSocket(duplexOptions);
151
+ const ready = Promise.resolve().then(() => host.accept(link.socket, {
152
+ dataStreams: false,
153
+ ...(allowUnsealed ? {} : { sealSession: 'require' }),
154
+ ...(remote ? { remote } : {}),
155
+ })).catch((e) => { link.socket.close(1011, 'this host cannot serve this duplex'); throw e; });
156
+ ready.catch(() => {});
157
+ return {
158
+ receive: link.receive,
159
+ end: link.end,
160
+ ready,
161
+ close() { link.socket.close(1000, 'closed'); },
162
+ };
163
+ }
164
+
165
+ /**
166
+ * Connect a wsh client over a duplex: the login is a key login, the session is SEALED, the login is bound to the host's key, and the host's key
167
+ * must be named: a hop on the duplex that answers as a host of its own would otherwise be trusted on first use. Name it with `expectHostKey` (the
168
+ * hex fingerprint; over a mesh it is the peer's pod id, `podIdToFingerprint(peer)`), or `knownHosts`, or say `trustOnFirstUse: true`.
169
+ *
170
+ * @param {object} duplex as `createDuplexSocket` (`send`, `close`, `maxMessageBytes`, `maxBufferedBytes`)
171
+ * @param {object} credentials `{ username, keyPair | signer, expectHostKey | knownHosts | trustOnFirstUse, timeout, allowUnsealed }` and the other options of
172
+ * `WshClient.connect`; `allowUnsealed: true` (and `sealSession`, `requireChannelBinding`) set the guarantees down, out loud
173
+ * @returns {{ receive(data: Uint8Array | ArrayBuffer): void, end(reason?: string): void, client: WshClient, connected: Promise<WshClient>, close(): Promise<void> }}
174
+ */
175
+ export function connectWshOverDuplex(duplex, { allowUnsealed = false, ...credentials } = {}) {
176
+ if (typeof allowUnsealed !== 'boolean') throw new TypeError('connectWshOverDuplex: allowUnsealed must be true or false');
177
+ if (credentials.password !== undefined && !allowUnsealed) throw new TypeError('connectWshOverDuplex: a password login cannot be sealed (a hop would read it): use a key, or say allowUnsealed: true');
178
+ if (credentials.expectHostKey === undefined && credentials.knownHosts === undefined && credentials.trustOnFirstUse !== true && credentials.onHostKey === undefined) {
179
+ throw new TypeError('connectWshOverDuplex: name the host key you expect (expectHostKey: its hex fingerprint, over a mesh the peer\'s pod id converted with podIdToFingerprint), or knownHosts, or say trustOnFirstUse: true (a hop on the duplex could answer as the host)');
180
+ }
181
+ const link = createDuplexSocket(duplex);
182
+ let used = false;
183
+ // One duplex serves one connection: the constructor the transport calls hands back the socket made for it, once.
184
+ function LinkSocket() {
185
+ if (used) throw new Error('this duplex carries one connection and it is in use');
186
+ used = true;
187
+ return link.socket;
188
+ }
189
+ const client = new WshClient({
190
+ transportFactories: {
191
+ ws: () => new WebSocketTransport({ WebSocket: LinkSocket }),
192
+ wt: () => { throw new Error('connectWshOverDuplex: a duplex is not WebTransport'); },
193
+ },
194
+ });
195
+ const connected = client.connect('ws://duplex.invalid/', {
196
+ transport: 'ws',
197
+ ...(allowUnsealed ? {} : { sealSession: true, requireChannelBinding: ['host'] }),
198
+ ...credentials,
199
+ }).then(() => client);
200
+ connected.catch(() => {});
201
+ return {
202
+ receive: link.receive,
203
+ end: link.end,
204
+ client,
205
+ connected,
206
+ close: () => client.disconnect(),
207
+ };
208
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * The codes of `GatewayFail` as data, in one place (browser-safe, no Node import). A host puts one of these numbers in `GatewayFail.code`
3
+ * when a gateway request (`OpenTcp`, `OpenUdp`, `ResolveDns`, `OpenEndpoint`, `OpenUnix`) fails; a client reads it back as
4
+ * `GatewayError.code`. The Node gateway, the page host and the memory host send them from this table, and `@johnhenry/browsermesh-netway`
5
+ * decodes them (it keeps a copy by hand: it can import this one instead, the names and numbers are the same).
6
+ *
7
+ * The table is a contract: a code is never reused for something else and a number is never renumbered. A new code is added at the end.
8
+ */
9
+
10
+ /** Wire codes of `GatewayFail`, by name. */
11
+ export const GATEWAY_FAIL = Object.freeze({
12
+ CONNECTION_REFUSED: 1, HOST_UNREACHABLE: 2, DNS_FAILED: 3, POLICY_DENIED: 4, TIMEOUT: 5, CLOSED: 6, QUEUE_FULL: 7,
13
+ });
14
+
15
+ /**
16
+ * The same codes with their meaning. `alsoSentAs` lists a second name a different implementation gives the same number: the Rust
17
+ * `wsh-server` sends `5` for "gateway disabled" (and `spec/wsh-v1.yaml` lists `5=GATEWAY_DISABLED`), where the Node gateway sends it for a
18
+ * timeout. A client that reads `5` therefore should say "timed out or disabled" rather than only one of the two.
19
+ */
20
+ export const GATEWAY_FAIL_TABLE = Object.freeze([
21
+ Object.freeze({ name: 'CONNECTION_REFUSED', code: 1, meaning: 'The destination actively refused the connection (nothing listens there).' }),
22
+ Object.freeze({ name: 'HOST_UNREACHABLE', code: 2, meaning: 'The destination could not be reached on the network (no route, connect failed, socket error).' }),
23
+ Object.freeze({ name: 'DNS_FAILED', code: 3, meaning: 'The name did not resolve, or is not a valid name.' }),
24
+ Object.freeze({ name: 'POLICY_DENIED', code: 4, meaning: 'The host refused by policy: the key lacks the capability, the address is not allowed, the endpoint or target does not exist or is not for this caller, or the request was malformed or reused an id.' }),
25
+ Object.freeze({ name: 'TIMEOUT', code: 5, alsoSentAs: Object.freeze(['GATEWAY_DISABLED']), meaning: 'The host did not finish in time. The Rust wsh-server sends this number when its gateway is disabled.' }),
26
+ Object.freeze({ name: 'CLOSED', code: 6, meaning: 'The gateway connection was closed before the operation finished.' }),
27
+ Object.freeze({ name: 'QUEUE_FULL', code: 7, meaning: 'The host holds too many gateway connections or too much unsent data, and takes no more for now.' }),
28
+ ]);
29
+
30
+ /**
31
+ * Codes a client gives its own `GatewayError` when it never asked the host: they are not on the wire, and a host never sends them.
32
+ * `UNSUPPORTED`: the host did not advertise the feature the call needs.
33
+ */
34
+ export const GATEWAY_FAIL_LOCAL = Object.freeze({ UNSUPPORTED: 0 });
35
+
36
+ /**
37
+ * The name of a code (wire or client-local), or `null` for a number that is not in the table.
38
+ * @param {number} code
39
+ * @returns {string | null}
40
+ */
41
+ export function gatewayFailName(code) {
42
+ for (const row of GATEWAY_FAIL_TABLE) if (row.code === code) return row.name;
43
+ for (const [name, value] of Object.entries(GATEWAY_FAIL_LOCAL)) if (value === code) return name;
44
+ return null;
45
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * `@johnhenry/wsh/identity`: a key's identity in its spellings (raw 32-byte key, OpenSSH `ssh-ed25519` line, hex fingerprint, base64url
3
+ * pod id), and a builder of `authorized_keys` lines that refuses unsafe input. Browser-safe (no Node import); a stable entry point.
4
+ */
5
+
6
+ /** Who a call is from, whatever carried it: a login name and a key (over wsh), or a pod id (over a mesh). The key's two names are one hash. */
7
+ export interface WshIdentity {
8
+ username: string | null;
9
+ /** 64 lower-case hex digits: the SHA-256 of the caller's raw public key. `null` for a caller with no key. */
10
+ fingerprint: string | null;
11
+ /** 43 base64url characters: the same hash. Derived from `fingerprint` when only that is known, and the other way round. */
12
+ podId: string | null;
13
+ }
14
+
15
+ /** SHA-256 of a raw Ed25519 public key, as 64 lower-case hex digits. */
16
+ export function fingerprint(publicKeyRaw: Uint8Array): Promise<string>;
17
+ /** SHA-256 of a raw Ed25519 public key, as 43 base64url characters (BrowserMesh's pod id). */
18
+ export function podId(publicKeyRaw: Uint8Array): Promise<string>;
19
+ /** Convert a fingerprint (exactly 64 hex digits, either case) to a pod id. Throws a `TypeError` for anything else. */
20
+ export function fingerprintToPodId(hexFingerprint: string): string;
21
+ /** Convert a pod id (exactly 43 base64url characters, canonical spelling) to a fingerprint. Throws a `TypeError` for anything else. */
22
+ export function podIdToFingerprint(podIdStr: string): string;
23
+
24
+ /** The OpenSSH `ssh-ed25519` line of a raw 32-byte public key (`comment`: no control character or line break). */
25
+ export function rawKeyToOpenSsh(raw: Uint8Array, comment?: string): string;
26
+ /** The OpenSSH `ssh-ed25519` line of a public `CryptoKey`. */
27
+ export function publicKeyToOpenSsh(publicKey: CryptoKey, comment?: string): Promise<string>;
28
+ /** Read a plain `ssh-ed25519 <base64> [comment]` line. Refuses options in front, other key types, trailing bytes, more than one line. */
29
+ export function parseOpenSshKey(line: string): { raw: Uint8Array; comment: string };
30
+ /** The raw 32-byte public key of an OpenSSH `ssh-ed25519` line. */
31
+ export function openSshToRawKey(line: string): Uint8Array;
32
+
33
+ /** One key in every spelling. */
34
+ export function identityOf(key: Uint8Array | string | CryptoKey): Promise<{ raw: Uint8Array; fingerprint: string; podId: string; openssh: string }>;
35
+
36
+ /**
37
+ * An identity as `{ username, fingerprint, podId }`: whichever of `fingerprint` and `podId` is given, the other is derived. Throws a
38
+ * `TypeError` for an identity that names two keys or is malformed (`strict: false` keeps a `fingerprint` that is not a key hash).
39
+ */
40
+ export function normalizeIdentity(
41
+ who: { username?: string | null; fingerprint?: string | null; podId?: string | null } | null | undefined,
42
+ options?: { strict?: boolean },
43
+ ): WshIdentity;
44
+
45
+ export interface AuthorizedKeyLineOptions {
46
+ /** The capabilities the key holds (`spec/capabilities.md`); `[]` for a key that may do nothing. Required unless `allowFullAccess`. */
47
+ capabilities?: string[] | string;
48
+ /** When the key stops working: an RFC 3339 string, a `Date` or epoch milliseconds. Written in UTC. */
49
+ expires?: string | Date | number;
50
+ /** Written after the key; no control character or line break. */
51
+ comment?: string;
52
+ /** Say it out loud: a line with no capability list is a key that may do everything. Contradicts `capabilities`. */
53
+ allowFullAccess?: boolean;
54
+ }
55
+
56
+ /**
57
+ * A line for an `authorized_keys` file, read back through the host's own parser before it is returned. Throws a `TypeError` for a
58
+ * capability that is not in the notation, a malformed expiry, a comment that could start another line, a key that is not a plain
59
+ * Ed25519 key, or an option it does not write.
60
+ */
61
+ export function authorizedKeyLine(key: Uint8Array | string, options: AuthorizedKeyLineOptions): string;