@johnhenry/wsh 0.36.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 +345 -11
- package/package.json +5 -1
- package/src/bridge-seal.mjs +77 -0
- package/src/channel-binding.mjs +124 -0
- package/src/client.mjs +348 -40
- package/src/e2e-exchange.mjs +51 -1
- package/src/forward-node.mjs +118 -0
- package/src/gateway-channel.mjs +250 -0
- package/src/gateway-client.mjs +252 -0
- package/src/host.d.ts +3 -3
- package/src/index.d.ts +114 -0
- package/src/index.mjs +13 -0
- package/src/memory-host.d.ts +17 -3
- package/src/memory-host.mjs +31 -7
- 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 +2 -2
- package/src/reverse-host.mjs +126 -15
- package/src/server/address-guard.mjs +164 -0
- package/src/server/client-env.mjs +60 -0
- package/src/server/connection.mjs +65 -12
- package/src/server/gateway-core.mjs +188 -0
- package/src/server/gateway.mjs +483 -80
- package/src/server/index.d.ts +97 -5
- package/src/server/index.mjs +23 -2
- package/src/server/pty.mjs +1 -0
- package/src/server/relay.mjs +45 -2
- 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
package/src/messages.gen.mjs
CHANGED
|
@@ -65,6 +65,8 @@ export const MSG = Object.freeze({
|
|
|
65
65
|
REVERSE_REJECT: 0x55,
|
|
66
66
|
RELAY_FORWARD: 0x56,
|
|
67
67
|
REVERSE_CLOSE: 0x57,
|
|
68
|
+
REVERSE_CHALLENGE: 0x58,
|
|
69
|
+
REVERSE_PROOF: 0x59,
|
|
68
70
|
|
|
69
71
|
// Session
|
|
70
72
|
SESSION_LIST: 0x5f,
|
|
@@ -73,6 +75,9 @@ export const MSG = Object.freeze({
|
|
|
73
75
|
DETACH_FAIL: 0x62,
|
|
74
76
|
|
|
75
77
|
// Gateway
|
|
78
|
+
OPEN_UNIX: 0x63,
|
|
79
|
+
OPEN_ENDPOINT: 0x64,
|
|
80
|
+
LISTEN_UNIX: 0x65,
|
|
76
81
|
OPEN_TCP: 0x70,
|
|
77
82
|
OPEN_UDP: 0x71,
|
|
78
83
|
RESOLVE_DNS: 0x72,
|
|
@@ -88,6 +93,7 @@ export const MSG = Object.freeze({
|
|
|
88
93
|
LISTEN_FAIL: 0x7c,
|
|
89
94
|
LISTEN_CLOSE: 0x7d,
|
|
90
95
|
GATEWAY_DATA: 0x7e,
|
|
96
|
+
GATEWAY_CREDIT: 0x7f,
|
|
91
97
|
|
|
92
98
|
// Guest
|
|
93
99
|
GUEST_INVITE: 0x80,
|
|
@@ -497,13 +503,10 @@ export function reversePeers({ peers } = {}) {
|
|
|
497
503
|
};
|
|
498
504
|
}
|
|
499
505
|
|
|
500
|
-
export function reverseConnect({ targetFingerprint, username, fromFingerprint } = {}) {
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
username,
|
|
505
|
-
from_fingerprint: fromFingerprint,
|
|
506
|
-
};
|
|
506
|
+
export function reverseConnect({ targetFingerprint, username, fromFingerprint, features } = {}) {
|
|
507
|
+
const msg = { type: MSG.REVERSE_CONNECT, target_fingerprint: targetFingerprint, username, from_fingerprint: fromFingerprint };
|
|
508
|
+
if (features !== undefined) msg.features = features;
|
|
509
|
+
return msg;
|
|
507
510
|
}
|
|
508
511
|
|
|
509
512
|
export function reverseAccept({ targetFingerprint, username, capabilities = [], peerType = "host", shellBackend = "pty", supportsAttach = false, supportsReplay = false, supportsEcho = false, supportsTermSync = false, features } = {}) {
|
|
@@ -533,6 +536,24 @@ export function reverseClose({ targetFingerprint, reason } = {}) {
|
|
|
533
536
|
return msg;
|
|
534
537
|
}
|
|
535
538
|
|
|
539
|
+
export function reverseChallenge({ targetFingerprint, publicKey, operatorFingerprint, nonce, sessionId, signature } = {}) {
|
|
540
|
+
return {
|
|
541
|
+
type: MSG.REVERSE_CHALLENGE,
|
|
542
|
+
target_fingerprint: targetFingerprint,
|
|
543
|
+
public_key: publicKey,
|
|
544
|
+
operator_fingerprint: operatorFingerprint,
|
|
545
|
+
nonce,
|
|
546
|
+
session_id: sessionId,
|
|
547
|
+
signature,
|
|
548
|
+
};
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
export function reverseProof({ targetFingerprint, publicKey, username, nonce, sessionId, signature, fromFingerprint } = {}) {
|
|
552
|
+
const msg = { type: MSG.REVERSE_PROOF, target_fingerprint: targetFingerprint, public_key: publicKey, username, nonce, session_id: sessionId, signature };
|
|
553
|
+
if (fromFingerprint !== undefined) msg.from_fingerprint = fromFingerprint;
|
|
554
|
+
return msg;
|
|
555
|
+
}
|
|
556
|
+
|
|
536
557
|
export function sessionList({ sessions } = {}) {
|
|
537
558
|
return {
|
|
538
559
|
type: MSG.SESSION_LIST,
|
|
@@ -561,6 +582,28 @@ export function detachFail({ reason } = {}) {
|
|
|
561
582
|
};
|
|
562
583
|
}
|
|
563
584
|
|
|
585
|
+
export function openUnix({ gatewayId, path } = {}) {
|
|
586
|
+
return {
|
|
587
|
+
type: MSG.OPEN_UNIX,
|
|
588
|
+
gateway_id: gatewayId,
|
|
589
|
+
path,
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
export function openEndpoint({ gatewayId, name } = {}) {
|
|
594
|
+
return {
|
|
595
|
+
type: MSG.OPEN_ENDPOINT,
|
|
596
|
+
gateway_id: gatewayId,
|
|
597
|
+
name,
|
|
598
|
+
};
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
export function listenUnix({ listenerId, path, replace } = {}) {
|
|
602
|
+
const msg = { type: MSG.LISTEN_UNIX, listener_id: listenerId, path };
|
|
603
|
+
if (replace !== undefined) msg.replace = replace;
|
|
604
|
+
return msg;
|
|
605
|
+
}
|
|
606
|
+
|
|
564
607
|
export function openTcp({ gatewayId, host, port } = {}) {
|
|
565
608
|
return {
|
|
566
609
|
type: MSG.OPEN_TCP,
|
|
@@ -677,6 +720,14 @@ export function gatewayData({ gatewayId, data } = {}) {
|
|
|
677
720
|
};
|
|
678
721
|
}
|
|
679
722
|
|
|
723
|
+
export function gatewayCredit({ gatewayId, bytes } = {}) {
|
|
724
|
+
return {
|
|
725
|
+
type: MSG.GATEWAY_CREDIT,
|
|
726
|
+
gateway_id: gatewayId,
|
|
727
|
+
bytes,
|
|
728
|
+
};
|
|
729
|
+
}
|
|
730
|
+
|
|
680
731
|
export function guestInvite({ sessionId, ttl, permissions = ["read"] } = {}) {
|
|
681
732
|
return {
|
|
682
733
|
type: MSG.GUEST_INVITE,
|
|
@@ -948,6 +999,7 @@ export const RELAY_FORWARDABLE = new Set([
|
|
|
948
999
|
MSG.SIGNAL,
|
|
949
1000
|
MSG.SESSION_DATA,
|
|
950
1001
|
MSG.GATEWAY_DATA,
|
|
1002
|
+
MSG.GATEWAY_CREDIT,
|
|
951
1003
|
MSG.GATEWAY_OK,
|
|
952
1004
|
MSG.GATEWAY_FAIL,
|
|
953
1005
|
MSG.GATEWAY_CLOSE,
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The operator proves its identity to the PEER (wsh #117).
|
|
3
|
+
*
|
|
4
|
+
* In reverse mode the relay authenticates the operator (its login key) and stamps `from_fingerprint` on what it
|
|
5
|
+
* forwards, so a peer that took `accept({ fingerprint })` at face value trusted the relay for authorization. With
|
|
6
|
+
* proof the peer does not have to:
|
|
7
|
+
*
|
|
8
|
+
* operator -> relay -> peer ReverseConnect { features: ['operator-proof'] }
|
|
9
|
+
* peer -> relay -> operator ReverseChallenge { public_key, operator_fingerprint, nonce, session_id, signature }
|
|
10
|
+
* operator -> relay -> peer ReverseProof { public_key, username, nonce, session_id, signature }
|
|
11
|
+
* peer: verifies, THEN runs `accept({ fingerprint, username, proven: true })`
|
|
12
|
+
*
|
|
13
|
+
* Both signatures are Ed25519 over a labelled, length-prefixed byte string (not a hash, so nothing is truncated):
|
|
14
|
+
*
|
|
15
|
+
* challenge = "wsh-reverse-challenge-v1\0" || lp(peer key) || lp(operator fingerprint) || lp(nonce) || lp(session id)
|
|
16
|
+
* proof = "wsh-operator-proof-v1\0" || lp(peer key) || lp(operator key) || lp(username) || lp(nonce) || lp(session id)
|
|
17
|
+
*
|
|
18
|
+
* The peer signs its challenge so the operator knows whom it is proving itself to and that the peer saw the
|
|
19
|
+
* operator's own fingerprint (a relay that rewrote `from_fingerprint` shows). The operator's proof names the peer it
|
|
20
|
+
* is for, the peer's single-use nonce and the bridge's session id: it cannot be replayed to another peer, later, or
|
|
21
|
+
* for another bridge, and a relay that swaps `public_key` cannot sign for the key it put there.
|
|
22
|
+
*
|
|
23
|
+
* What it does NOT do on its own: it proves who was at the other end when the bridge was set up. A relay can still
|
|
24
|
+
* stamp that identity on a plain message afterwards; closing that is the sealed bridge (`bridge-seal.mjs`), which a
|
|
25
|
+
* host that requires operator proof also requires.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
import { verify as verifyBytes, importPublicKeyRaw, fingerprint, resolveSigner } from './auth.mjs';
|
|
29
|
+
|
|
30
|
+
/** `ServerHello.features` of a relay that carries `ReverseChallenge` / `ReverseProof`, and `ReverseConnect.features` of an operator that answers one. */
|
|
31
|
+
export const OPERATOR_PROOF_FEATURE = 'operator-proof';
|
|
32
|
+
/** `ReverseAccept.features` of a peer that takes a signed initiator half and a sealed bridge. */
|
|
33
|
+
export const E2E_SEALED_FEATURE = 'e2e-sealed';
|
|
34
|
+
|
|
35
|
+
const enc = new TextEncoder();
|
|
36
|
+
const CHALLENGE_LABEL = enc.encode('wsh-reverse-challenge-v1\0');
|
|
37
|
+
const PROOF_LABEL = enc.encode('wsh-operator-proof-v1\0');
|
|
38
|
+
export const NONCE_LENGTH = 32;
|
|
39
|
+
|
|
40
|
+
const lp = (bytes) => {
|
|
41
|
+
const out = new Uint8Array(4 + bytes.length);
|
|
42
|
+
new DataView(out.buffer).setUint32(0, bytes.length);
|
|
43
|
+
out.set(bytes, 4);
|
|
44
|
+
return out;
|
|
45
|
+
};
|
|
46
|
+
const concat = (parts) => {
|
|
47
|
+
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
|
48
|
+
let off = 0;
|
|
49
|
+
for (const p of parts) { out.set(p, off); off += p.length; }
|
|
50
|
+
return out;
|
|
51
|
+
};
|
|
52
|
+
const isKey = (v) => v instanceof Uint8Array && v.length === 32;
|
|
53
|
+
const str = (v, max = 256) => typeof v === 'string' && v.length > 0 && v.length <= max;
|
|
54
|
+
|
|
55
|
+
/** The bytes a peer signs in a `ReverseChallenge`. */
|
|
56
|
+
export function challengeTranscript({ peerPublicKey, operatorFingerprint, nonce, sessionId }) {
|
|
57
|
+
return concat([CHALLENGE_LABEL, lp(peerPublicKey), lp(enc.encode(operatorFingerprint)), lp(nonce), lp(enc.encode(sessionId))]);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The bytes an operator signs in a `ReverseProof`. */
|
|
61
|
+
export function proofTranscript({ peerPublicKey, operatorPublicKey, username, nonce, sessionId }) {
|
|
62
|
+
return concat([PROOF_LABEL, lp(peerPublicKey), lp(operatorPublicKey), lp(enc.encode(username)), lp(nonce), lp(enc.encode(sessionId))]);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function verifyWith(rawKey, signature, data) {
|
|
66
|
+
if (!isKey(rawKey) || !(signature instanceof Uint8Array) || signature.length !== 64) return false;
|
|
67
|
+
try { return await verifyBytes(await importPublicKeyRaw(rawKey), signature, data); } catch { return false; }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Peer side: make a challenge for the operator `operatorFingerprint` (as the relay stamped it).
|
|
72
|
+
* @param {{ keyPair?: CryptoKeyPair, signer?: object }} identity - this peer's key
|
|
73
|
+
* @param {string} operatorFingerprint
|
|
74
|
+
* @returns {Promise<{ fields: object, nonce: Uint8Array, sessionId: string, peerPublicKey: Uint8Array }>}
|
|
75
|
+
* `fields` is what goes into `reverseChallenge({ targetFingerprint, ...fields })`
|
|
76
|
+
*/
|
|
77
|
+
export async function createReverseChallenge(identity, operatorFingerprint) {
|
|
78
|
+
const signer = await resolveSigner(identity);
|
|
79
|
+
if (!signer) throw new TypeError('createReverseChallenge: a keyPair or signer is required');
|
|
80
|
+
const nonce = crypto.getRandomValues(new Uint8Array(NONCE_LENGTH));
|
|
81
|
+
const sessionId = crypto.randomUUID();
|
|
82
|
+
const signature = await signer.sign(challengeTranscript({ peerPublicKey: signer.publicKeyRaw, operatorFingerprint, nonce, sessionId }));
|
|
83
|
+
return {
|
|
84
|
+
fields: { publicKey: signer.publicKeyRaw, operatorFingerprint, nonce, sessionId, signature },
|
|
85
|
+
nonce, sessionId, peerPublicKey: signer.publicKeyRaw,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Operator side: check a `ReverseChallenge` and return the peer's identity, or throw.
|
|
91
|
+
* @param {object} msg - the decoded message (snake_case)
|
|
92
|
+
* @param {{ target: string, ownFingerprint: string }} expect - the peer fingerprint (or prefix) asked for; this operator's own
|
|
93
|
+
* @returns {Promise<{ peerPublicKey: Uint8Array, peerFingerprint: string, nonce: Uint8Array, sessionId: string }>}
|
|
94
|
+
*/
|
|
95
|
+
export async function verifyReverseChallenge(msg, { target, ownFingerprint }) {
|
|
96
|
+
const fail = (why) => Object.assign(new Error(`reverse challenge refused: ${why}`), { code: 'REVERSE_CHALLENGE_INVALID' });
|
|
97
|
+
if (!isKey(msg.public_key) || !(msg.nonce instanceof Uint8Array) || msg.nonce.length !== NONCE_LENGTH || !str(msg.session_id) || !str(msg.operator_fingerprint)) throw fail('malformed');
|
|
98
|
+
const peerFingerprint = await fingerprint(msg.public_key);
|
|
99
|
+
if (typeof target !== 'string' || !target || !peerFingerprint.startsWith(target)) throw fail('the key that signed it is not the peer that was asked for');
|
|
100
|
+
if (msg.operator_fingerprint !== ownFingerprint) throw fail('the peer saw a different operator fingerprint than this connection\'s (the relay rewrote it)');
|
|
101
|
+
const ok = await verifyWith(msg.public_key, msg.signature, challengeTranscript({
|
|
102
|
+
peerPublicKey: msg.public_key, operatorFingerprint: msg.operator_fingerprint, nonce: msg.nonce, sessionId: msg.session_id,
|
|
103
|
+
}));
|
|
104
|
+
if (!ok) throw fail('the signature does not verify');
|
|
105
|
+
return { peerPublicKey: msg.public_key, peerFingerprint, nonce: msg.nonce, sessionId: msg.session_id };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Operator side: answer a verified challenge.
|
|
110
|
+
* @param {{ publicKeyRaw: Uint8Array, sign: (d: Uint8Array) => Promise<Uint8Array> }} signer - from `resolveSigner`
|
|
111
|
+
* @returns {Promise<object>} fields for `reverseProof({ targetFingerprint, ...fields })`
|
|
112
|
+
*/
|
|
113
|
+
export async function createOperatorProof(signer, challenge, username) {
|
|
114
|
+
const signature = await signer.sign(proofTranscript({
|
|
115
|
+
peerPublicKey: challenge.peerPublicKey, operatorPublicKey: signer.publicKeyRaw, username, nonce: challenge.nonce, sessionId: challenge.sessionId,
|
|
116
|
+
}));
|
|
117
|
+
return { publicKey: signer.publicKeyRaw, username, nonce: challenge.nonce, sessionId: challenge.sessionId, signature };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Peer side: check a `ReverseProof` against the challenge it issued.
|
|
122
|
+
* @param {object} msg - the decoded message
|
|
123
|
+
* @param {{ nonce: Uint8Array, sessionId: string, peerPublicKey: Uint8Array }} issued
|
|
124
|
+
* @returns {Promise<{ publicKey: Uint8Array, fingerprint: string, username: string } | null>} null when it does not verify
|
|
125
|
+
*/
|
|
126
|
+
export async function verifyOperatorProof(msg, issued) {
|
|
127
|
+
if (!isKey(msg.public_key) || !str(msg.username, 64)) return null;
|
|
128
|
+
const same = (a, b) => a instanceof Uint8Array && a.length === b.length && a.every((x, i) => x === b[i]);
|
|
129
|
+
if (!same(msg.nonce, issued.nonce) || msg.session_id !== issued.sessionId) return null;
|
|
130
|
+
const ok = await verifyWith(msg.public_key, msg.signature, proofTranscript({
|
|
131
|
+
peerPublicKey: issued.peerPublicKey, operatorPublicKey: msg.public_key, username: msg.username, nonce: issued.nonce, sessionId: issued.sessionId,
|
|
132
|
+
}));
|
|
133
|
+
return ok ? { publicKey: msg.public_key, fingerprint: await fingerprint(msg.public_key), username: msg.username } : null;
|
|
134
|
+
}
|
|
135
|
+
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/** A WebSocket-like duplex: the `ws` package's, a browser's, or a Worker's. */
|
|
2
|
+
export interface PipeSocket {
|
|
3
|
+
send(data: Uint8Array | ArrayBuffer): void;
|
|
4
|
+
close(code?: number, reason?: string): void;
|
|
5
|
+
readonly readyState: number;
|
|
6
|
+
readonly bufferedAmount?: number;
|
|
7
|
+
pause?(): void;
|
|
8
|
+
resume?(): void;
|
|
9
|
+
on?(event: string, listener: (...args: any[]) => void): unknown;
|
|
10
|
+
addEventListener?(event: string, listener: (ev: any) => void): unknown;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface PipeRelayOptions {
|
|
14
|
+
/** Halves waiting for a partner, over all ids (default 1024). */
|
|
15
|
+
maxWaiting?: number;
|
|
16
|
+
/** How long a half waits for its partner (default 120000). */
|
|
17
|
+
rendezvousTimeoutMs?: number;
|
|
18
|
+
/** A pipe that carried no byte either way for this long is closed (default 300000). */
|
|
19
|
+
idleTimeoutMs?: number;
|
|
20
|
+
/** A pipe is closed this long after pairing (default 12 hours). */
|
|
21
|
+
maxLifetimeMs?: number;
|
|
22
|
+
/** Total bytes copied per pipe, both directions (default 1 GiB). */
|
|
23
|
+
maxBytes?: number;
|
|
24
|
+
/** Largest single message (default 4 MiB). */
|
|
25
|
+
maxMessageBytes?: number;
|
|
26
|
+
/** What a half may send before its partner arrives (default 64 KiB). */
|
|
27
|
+
earlyBytes?: number;
|
|
28
|
+
/** Outgoing buffer size past which the sender is paused (default 1 MiB). */
|
|
29
|
+
highWaterBytes?: number;
|
|
30
|
+
/** Optional gate before a half may wait or pair; default: anyone holding a well-formed id. */
|
|
31
|
+
authorize?: (who: { id: string; role: 'host' | 'operator'; remote?: object }) => boolean | Promise<boolean>;
|
|
32
|
+
onLog?: (line: string) => void;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface PipeRelay {
|
|
36
|
+
/** Hand the relay one accepted connection; resolves false when it was refused (and closed). */
|
|
37
|
+
accept(socket: PipeSocket, who: { id: string; role?: 'host' | 'operator'; remote?: object }): Promise<boolean>;
|
|
38
|
+
/** Listen for WebSocket upgrades on `<path>/<id>` (default `/r`); `?role=host` is the host side. Needs the `ws` package. */
|
|
39
|
+
listen(options?: { host?: string; port?: number; path?: string; tls?: object }): Promise<{ port: number; address: string; close(): Promise<void> }>;
|
|
40
|
+
close(): Promise<void>;
|
|
41
|
+
stats(): { waiting: number; pipes: number };
|
|
42
|
+
newRendezvousId(): string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function createPipeRelay(options?: PipeRelayOptions): PipeRelay;
|
|
46
|
+
/** A fresh 128-bit rendezvous id, base64url. */
|
|
47
|
+
export function newRendezvousId(): string;
|
|
48
|
+
/** The URL one side dials: `<relay>/r/<id>`, with `?role=host` for the host. */
|
|
49
|
+
export function pipeUrl(relayUrl: string, id: string, role?: 'host' | 'operator'): string;
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A pipe relay (wsh #118): rendezvous and byte copying, nothing else.
|
|
3
|
+
*
|
|
4
|
+
* Two parties that cannot reach each other directly both dial the relay with the same unguessable rendezvous id --
|
|
5
|
+
* the host (`role: 'host'`) and the operator (`role: 'operator'`) -- and the relay joins them and copies WebSocket
|
|
6
|
+
* messages in both directions. It does not parse wsh: it holds no keys, runs nothing, reads no files, and cannot
|
|
7
|
+
* tell who either party is. The host serves its connection with the ordinary `createWshServer().accept(socket)` (or
|
|
8
|
+
* `createMemoryHost().accept`), so it runs the ordinary handshake and verifies the OPERATOR'S OWN signature; the
|
|
9
|
+
* operator connects with the ordinary `WshClient.connect(pipeUrl(...))` and can pin the host key. Compare relay
|
|
10
|
+
* mode (`createWshServer({ relay })`), where the relay authenticates the operator and tells the peer who it is.
|
|
11
|
+
* What a pipe relay can still do is in the README's Security model: it sees metadata and ciphertext-free traffic
|
|
12
|
+
* volume, can drop or delay bytes, and can offer a host or operator to whoever holds the rendezvous id.
|
|
13
|
+
*
|
|
14
|
+
* THIS MODULE IMPORTS NOTHING STATICALLY, and its only dynamic imports are `ws`, `node:http` and `node:https` (in
|
|
15
|
+
* `listen()`, for embedders that do not already run an HTTP server). test/pipe-relay.test.mjs asserts that the
|
|
16
|
+
* module graph reaches nothing that can execute code or read files. That is the point of shipping it as its own
|
|
17
|
+
* entry point (`@johnhenry/wsh/pipe-relay`) rather than a mode of the server.
|
|
18
|
+
*
|
|
19
|
+
* Bounds (every one has a default; 0 turns a limit off only where noted):
|
|
20
|
+
* maxWaiting halves waiting for a partner, over all ids (default 1024); more are refused
|
|
21
|
+
* rendezvousTimeoutMs how long a half waits for its partner (default 120000)
|
|
22
|
+
* idleTimeoutMs a pipe that carried no byte either way for this long is closed (default 300000; wsh clients ping)
|
|
23
|
+
* maxLifetimeMs a pipe is closed this long after pairing (default 12 h)
|
|
24
|
+
* maxBytes total bytes copied per pipe, both directions (default 1 GiB)
|
|
25
|
+
* maxMessageBytes largest single message (default 4 MiB)
|
|
26
|
+
* earlyBytes what a half may send before its partner arrives (default 64 KiB); more closes it
|
|
27
|
+
* highWaterBytes a socket whose outgoing buffer exceeds this is not fed further until it drains (default 1 MiB)
|
|
28
|
+
*
|
|
29
|
+
* Backpressure: when the receiving socket's `bufferedAmount` passes `highWaterBytes`, the sending socket is
|
|
30
|
+
* `pause()`d (the `ws` package's flow control, which stops reading its TCP socket) and resumed once the buffer is
|
|
31
|
+
* below half of it. A socket that cannot pause (a browser's, say) is closed instead of buffered without bound.
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
const OPEN = 1;
|
|
35
|
+
const ID_RE = /^[A-Za-z0-9_-]{22,128}$/;
|
|
36
|
+
const ROLES = new Set(['host', 'operator']);
|
|
37
|
+
const MIN_ID_LENGTH = 22; // 16 random bytes, base64url
|
|
38
|
+
|
|
39
|
+
/** A fresh rendezvous id: 128 bits from the platform CSPRNG, base64url (22 characters). */
|
|
40
|
+
export function newRendezvousId() {
|
|
41
|
+
const bytes = crypto.getRandomValues(new Uint8Array(16));
|
|
42
|
+
let s = '';
|
|
43
|
+
for (const b of bytes) s += String.fromCharCode(b);
|
|
44
|
+
return btoa(s).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The URL one side dials: `<relay>/r/<id>`, with `?role=host` for the host (the operator is the default).
|
|
49
|
+
* @param {string} relayUrl - `ws://` / `wss://` (or `http(s)://`) base of the relay
|
|
50
|
+
* @param {string} id
|
|
51
|
+
* @param {'host' | 'operator'} [role='operator']
|
|
52
|
+
*/
|
|
53
|
+
export function pipeUrl(relayUrl, id, role = 'operator') {
|
|
54
|
+
if (!ID_RE.test(id)) throw new TypeError(`pipeUrl: the rendezvous id must be ${MIN_ID_LENGTH}-128 base64url characters (use newRendezvousId())`);
|
|
55
|
+
if (!ROLES.has(role)) throw new TypeError("pipeUrl: role must be 'host' or 'operator'");
|
|
56
|
+
const u = new URL(relayUrl);
|
|
57
|
+
u.pathname = `${u.pathname.replace(/\/+$/, '')}/r/${id}`;
|
|
58
|
+
u.search = role === 'host' ? '?role=host' : '';
|
|
59
|
+
return u.toString();
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const sane = (code) => (Number.isInteger(code) && code >= 1000 && code <= 4999 && ![1004, 1005, 1006, 1015].includes(code) ? code : 1000);
|
|
63
|
+
|
|
64
|
+
/** Adapt a `ws`-style (`on`) or browser-style (`addEventListener`) socket to message/close callbacks. */
|
|
65
|
+
function listenOn(socket, onMessage, onClose) {
|
|
66
|
+
if (typeof socket.addEventListener === 'function') {
|
|
67
|
+
socket.addEventListener('message', (ev) => onMessage(ev?.data));
|
|
68
|
+
socket.addEventListener('close', (ev) => onClose(ev?.code));
|
|
69
|
+
socket.addEventListener('error', () => {});
|
|
70
|
+
} else if (typeof socket.on === 'function') {
|
|
71
|
+
socket.on('message', (data, isBinary) => onMessage(data, isBinary));
|
|
72
|
+
socket.on('close', (code) => onClose(code));
|
|
73
|
+
socket.on('error', () => {});
|
|
74
|
+
} else {
|
|
75
|
+
throw new TypeError('createPipeRelay: socket must support on() or addEventListener()');
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const sizeOf = (data) => (typeof data === 'string' ? -1
|
|
80
|
+
: Array.isArray(data) ? data.reduce((n, d) => n + d.byteLength, 0)
|
|
81
|
+
: data?.byteLength ?? data?.size ?? -1);
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* @param {object} [options]
|
|
85
|
+
* @param {number} [options.maxWaiting=1024]
|
|
86
|
+
* @param {number} [options.rendezvousTimeoutMs=120000]
|
|
87
|
+
* @param {number} [options.idleTimeoutMs=300000]
|
|
88
|
+
* @param {number} [options.maxLifetimeMs=43200000]
|
|
89
|
+
* @param {number} [options.maxBytes=1073741824]
|
|
90
|
+
* @param {number} [options.maxMessageBytes=4194304]
|
|
91
|
+
* @param {number} [options.earlyBytes=65536]
|
|
92
|
+
* @param {number} [options.highWaterBytes=1048576]
|
|
93
|
+
* @param {(who: { id: string, role: 'host' | 'operator', remote?: object }) => boolean | Promise<boolean>} [options.authorize]
|
|
94
|
+
* Optional gate, called before a half may wait or pair (rate limiting, an allow-list of ids you minted). Default:
|
|
95
|
+
* anyone holding a well-formed id; the id is the capability.
|
|
96
|
+
* @param {(line: string) => void} [options.onLog]
|
|
97
|
+
*/
|
|
98
|
+
export function createPipeRelay({
|
|
99
|
+
maxWaiting = 1024, rendezvousTimeoutMs = 120_000, idleTimeoutMs = 300_000, maxLifetimeMs = 12 * 3600_000,
|
|
100
|
+
maxBytes = 1024 ** 3, maxMessageBytes = 4 * 1024 * 1024, earlyBytes = 64 * 1024, highWaterBytes = 1024 * 1024,
|
|
101
|
+
authorize, onLog = () => {},
|
|
102
|
+
} = {}) {
|
|
103
|
+
for (const [name, v] of Object.entries({ maxWaiting, rendezvousTimeoutMs, idleTimeoutMs, maxLifetimeMs, maxBytes, maxMessageBytes, earlyBytes, highWaterBytes })) {
|
|
104
|
+
if (!Number.isFinite(v) || v < 1) throw new TypeError(`createPipeRelay: ${name} must be a positive number`);
|
|
105
|
+
}
|
|
106
|
+
if (authorize !== undefined && typeof authorize !== 'function') throw new TypeError('createPipeRelay: authorize must be a function');
|
|
107
|
+
|
|
108
|
+
/** id -> the one half waiting for its partner. */
|
|
109
|
+
const waiting = new Map();
|
|
110
|
+
/** Live pipes. */
|
|
111
|
+
const pipes = new Set();
|
|
112
|
+
let closed = false;
|
|
113
|
+
let server = null;
|
|
114
|
+
|
|
115
|
+
const closeSocket = (socket, code = 1000, reason = '') => { try { socket.close(code, reason); } catch { /* gone */ } };
|
|
116
|
+
|
|
117
|
+
function wait(half) {
|
|
118
|
+
half.timer = setTimeout(() => { waiting.delete(half.id); closeSocket(half.socket, 1000, 'no partner arrived'); onLog(`pipe ${half.id.slice(0, 6)}: ${half.role} waited too long`); }, rendezvousTimeoutMs);
|
|
119
|
+
half.timer.unref?.();
|
|
120
|
+
waiting.set(half.id, half);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function pair(first, second) {
|
|
124
|
+
clearTimeout(first.timer);
|
|
125
|
+
waiting.delete(first.id);
|
|
126
|
+
const pipe = { halves: [first, second], bytes: 0, last: Date.now(), timers: [], done: false };
|
|
127
|
+
pipes.add(pipe);
|
|
128
|
+
const end = (code, reason, from) => {
|
|
129
|
+
if (pipe.done) return;
|
|
130
|
+
pipe.done = true;
|
|
131
|
+
pipes.delete(pipe);
|
|
132
|
+
for (const t of pipe.timers) { clearInterval(t); clearTimeout(t); }
|
|
133
|
+
for (const h of pipe.halves) { h.resume?.(); if (h !== from) closeSocket(h.socket, sane(code), reason); }
|
|
134
|
+
onLog(`pipe ${first.id.slice(0, 6)} closed (${reason || code}) after ${pipe.bytes} bytes`);
|
|
135
|
+
};
|
|
136
|
+
pipe.end = end;
|
|
137
|
+
const life = setTimeout(() => end(1000, 'maximum lifetime reached'), maxLifetimeMs);
|
|
138
|
+
const idle = setInterval(() => { if (Date.now() - pipe.last > idleTimeoutMs) end(1000, 'idle'); }, Math.max(1000, Math.min(idleTimeoutMs / 4, 30_000)));
|
|
139
|
+
for (const t of [life, idle]) t.unref?.();
|
|
140
|
+
pipe.timers.push(life, idle);
|
|
141
|
+
|
|
142
|
+
const [a, b] = pipe.halves;
|
|
143
|
+
for (const [from, to] of [[a, b], [b, a]]) {
|
|
144
|
+
from.forward = (data, isBinary) => {
|
|
145
|
+
if (pipe.done) return;
|
|
146
|
+
const n = sizeOf(data);
|
|
147
|
+
if (n < 0 || isBinary === false) return end(1003, 'binary messages only', null);
|
|
148
|
+
if (n > maxMessageBytes) return end(1009, 'message too large', null);
|
|
149
|
+
pipe.bytes += n;
|
|
150
|
+
pipe.last = Date.now();
|
|
151
|
+
if (pipe.bytes > maxBytes) return end(1008, 'byte limit reached', null);
|
|
152
|
+
if (to.socket.readyState !== OPEN) return;
|
|
153
|
+
try { to.socket.send(data); } catch { return end(1011, 'send failed', null); }
|
|
154
|
+
if ((to.socket.bufferedAmount ?? 0) > highWaterBytes) throttle(from, to, pipe);
|
|
155
|
+
};
|
|
156
|
+
// Whatever it said before its partner arrived.
|
|
157
|
+
for (const m of from.early.splice(0)) from.forward(m.data, m.isBinary);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function throttle(from, to, pipe) {
|
|
162
|
+
if (from.paused) return;
|
|
163
|
+
if (typeof from.socket.pause !== 'function' || typeof from.socket.resume !== 'function') return pipe.end(1013, 'receiver too slow', null);
|
|
164
|
+
from.paused = true;
|
|
165
|
+
from.socket.pause();
|
|
166
|
+
from.resume = () => { if (from.paused) { from.paused = false; try { from.socket.resume(); } catch { /* gone */ } } };
|
|
167
|
+
const poll = setInterval(() => {
|
|
168
|
+
if (pipe.done) return clearInterval(poll);
|
|
169
|
+
if ((to.socket.bufferedAmount ?? 0) < highWaterBytes / 2) { clearInterval(poll); from.resume(); }
|
|
170
|
+
}, 10);
|
|
171
|
+
poll.unref?.();
|
|
172
|
+
pipe.timers.push(poll);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Hand the relay one accepted connection.
|
|
177
|
+
* @param {object} socket - a WebSocket-like duplex (`send`, `close`, `readyState`, `on` or `addEventListener`)
|
|
178
|
+
* @param {{ id: string, role?: 'host' | 'operator', remote?: object }} who
|
|
179
|
+
* @returns {Promise<boolean>} whether the connection is now waiting or paired (false: it was refused and closed)
|
|
180
|
+
*/
|
|
181
|
+
async function accept(socket, { id, role = 'operator', remote } = {}) {
|
|
182
|
+
if (!socket || typeof socket.send !== 'function' || typeof socket.close !== 'function') throw new TypeError('createPipeRelay.accept: socket must be a WebSocket-like duplex');
|
|
183
|
+
const refuse = (code, reason) => { closeSocket(socket, code, reason); return false; };
|
|
184
|
+
if (closed) return refuse(1001, 'relay is shutting down');
|
|
185
|
+
if (typeof id !== 'string' || !ID_RE.test(id)) return refuse(1008, 'bad rendezvous id');
|
|
186
|
+
if (!ROLES.has(role)) return refuse(1008, 'bad role');
|
|
187
|
+
|
|
188
|
+
// Listeners first, so nothing the peer says while we decide is lost; it is held (bounded) until it can be passed on.
|
|
189
|
+
const half = { id, role, socket, early: [], earlyBytes: 0, timer: null, forward: null, paused: false, resume: null };
|
|
190
|
+
let pipeRef = null;
|
|
191
|
+
listenOn(socket, (data, isBinary) => {
|
|
192
|
+
if (half.forward) return half.forward(data, isBinary);
|
|
193
|
+
const n = sizeOf(data);
|
|
194
|
+
half.earlyBytes += Math.max(n, 0);
|
|
195
|
+
if (n < 0 || isBinary === false || half.earlyBytes > earlyBytes) {
|
|
196
|
+
waiting.get(id) === half && (clearTimeout(half.timer), waiting.delete(id));
|
|
197
|
+
return closeSocket(socket, n < 0 || isBinary === false ? 1003 : 1009, 'too much before the partner arrived');
|
|
198
|
+
}
|
|
199
|
+
half.early.push({ data, isBinary });
|
|
200
|
+
}, (code) => {
|
|
201
|
+
if (waiting.get(id) === half) { clearTimeout(half.timer); waiting.delete(id); }
|
|
202
|
+
for (const p of pipes) if (p.halves.includes(half)) { pipeRef = p; break; }
|
|
203
|
+
pipeRef?.end(code, 'peer closed', half);
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
if (authorize) {
|
|
207
|
+
let ok = false;
|
|
208
|
+
try { ok = (await authorize({ id, role, remote })) === true; } catch (e) { onLog(`authorize threw: ${e.message}`); }
|
|
209
|
+
if (!ok) return refuse(1008, 'not permitted');
|
|
210
|
+
if (closed || socket.readyState !== OPEN) return false;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const other = waiting.get(id);
|
|
214
|
+
if (!other) {
|
|
215
|
+
if (waiting.size >= maxWaiting) return refuse(1013, 'too many waiting connections');
|
|
216
|
+
wait(half);
|
|
217
|
+
return true;
|
|
218
|
+
}
|
|
219
|
+
if (other.role === role) return refuse(1008, 'rendezvous id in use');
|
|
220
|
+
pair(other, half);
|
|
221
|
+
onLog(`pipe ${id.slice(0, 6)}: paired`);
|
|
222
|
+
return true;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Listen for WebSocket upgrades on `<path>/<id>` (default path `/r`), `?role=host` for the host side.
|
|
227
|
+
* Convenience for embedders without an HTTP server; needs the `ws` package. `tls` is the options of `https.createServer`.
|
|
228
|
+
* @returns {Promise<{ port: number, address: string, close(): Promise<void> }>}
|
|
229
|
+
*/
|
|
230
|
+
async function listen({ host = '127.0.0.1', port = 0, path = '/r', tls } = {}) {
|
|
231
|
+
if (server) throw new Error('createPipeRelay: already listening');
|
|
232
|
+
const { WebSocketServer } = await import('ws');
|
|
233
|
+
const http = tls ? await import('node:https') : await import('node:http');
|
|
234
|
+
const wss = new WebSocketServer({ noServer: true, maxPayload: maxMessageBytes });
|
|
235
|
+
const srv = tls ? http.createServer(tls) : http.createServer();
|
|
236
|
+
srv.on('request', (_req, res) => { res.statusCode = 426; res.end('WebSocket only'); });
|
|
237
|
+
srv.on('upgrade', (req, sock, head) => {
|
|
238
|
+
let url;
|
|
239
|
+
try { url = new URL(req.url, 'http://x'); } catch { sock.destroy(); return; }
|
|
240
|
+
const m = url.pathname.startsWith(`${path}/`) ? url.pathname.slice(path.length + 1) : null;
|
|
241
|
+
const role = url.searchParams.get('role') ?? 'operator';
|
|
242
|
+
if (!m || !ID_RE.test(m) || !ROLES.has(role)) { sock.write('HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n'); sock.destroy(); return; }
|
|
243
|
+
wss.handleUpgrade(req, sock, head, (ws) => { accept(ws, { id: m, role, remote: { address: req.socket.remoteAddress, headers: req.headers } }).catch(() => closeSocket(ws, 1011, 'error')); });
|
|
244
|
+
});
|
|
245
|
+
await new Promise((resolve, reject) => { srv.once('error', reject); srv.listen(port, host, () => { srv.off('error', reject); resolve(); }); });
|
|
246
|
+
server = { srv, wss };
|
|
247
|
+
const addr = srv.address();
|
|
248
|
+
return {
|
|
249
|
+
port: addr.port, address: addr.address,
|
|
250
|
+
close: () => close(),
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
async function close() {
|
|
255
|
+
closed = true;
|
|
256
|
+
for (const h of waiting.values()) { clearTimeout(h.timer); closeSocket(h.socket, 1001, 'relay is shutting down'); }
|
|
257
|
+
waiting.clear();
|
|
258
|
+
for (const p of [...pipes]) p.end(1001, 'relay is shutting down', null);
|
|
259
|
+
if (server) {
|
|
260
|
+
const { srv, wss } = server;
|
|
261
|
+
server = null;
|
|
262
|
+
for (const c of wss.clients) c.terminate();
|
|
263
|
+
await new Promise((r) => wss.close(r));
|
|
264
|
+
await new Promise((r) => { srv.close(() => r()); srv.closeAllConnections?.(); });
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
return {
|
|
269
|
+
accept, listen, close,
|
|
270
|
+
/** `{ waiting, pipes }` right now. */
|
|
271
|
+
stats: () => ({ waiting: waiting.size, pipes: pipes.size }),
|
|
272
|
+
newRendezvousId,
|
|
273
|
+
};
|
|
274
|
+
}
|
package/src/reverse-host.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { WshExecRunner, WshServerPtyOptions, WshServerMcpOptions, WshReverseHostOptions, WshReverseHost } from './server/index.js';
|
|
1
|
+
import type { WshExecRunner, WshServerPtyOptions, WshServerMcpOptions, WshReverseHostOptions, WshReverseHost, WshClientEnv } from './server/index.js';
|
|
2
2
|
import type { WshFileBackend } from './host.js';
|
|
3
3
|
|
|
4
4
|
export type { WshReverseHost } from './server/index.js';
|
|
@@ -9,7 +9,7 @@ export type { WshReverseHost } from './server/index.js';
|
|
|
9
9
|
*/
|
|
10
10
|
export interface WshBrowserReverseHostOptions extends Omit<WshReverseHostOptions, 'exec' | 'fs' | 'pty' | 'mcp'> {
|
|
11
11
|
/** `run(command, io)` or `{ run }`: there is no shell in a browser to run `true` with. */
|
|
12
|
-
exec?: WshExecRunner | { run: WshExecRunner; timeoutMs?: number; clientEnv?:
|
|
12
|
+
exec?: WshExecRunner | { run: WshExecRunner; timeoutMs?: number; clientEnv?: WshClientEnv };
|
|
13
13
|
/** `node-pty`-shaped `{ spawn }`, injected. Input arrives at `write` as a `Uint8Array`. */
|
|
14
14
|
pty?: WshServerPtyOptions;
|
|
15
15
|
/** An object of file operations, not a root path. */
|