@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
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The browser-safe half of the gateway: configuration of the parts that need no Node API (limits, named endpoints,
|
|
3
|
+
* the features a host advertises), and the per-connection core that serves `OpenEndpoint`, `GatewayData`,
|
|
4
|
+
* `GatewayCredit` and `GatewayClose` with flow control (`src/gateway-channel.mjs`). A host in a page
|
|
5
|
+
* (`createMemoryHost({ endpoints })`) is built from this alone; `gateway.mjs` (Node: TCP, DNS, UDP, unix sockets)
|
|
6
|
+
* extends it. Nothing here imports a Node built-in.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { MSG, gatewayOk, gatewayFail, gatewayClose, gatewayData, gatewayCredit, listenFail } from '../messages.gen.mjs';
|
|
10
|
+
import { GatewayChannel, GATEWAY_CREDIT_FEATURE, GATEWAY_CREDIT_WINDOW } from '../gateway-channel.mjs';
|
|
11
|
+
|
|
12
|
+
/** Numeric codes of GatewayFail (the same table `@johnhenry/browsermesh-netway` decodes). */
|
|
13
|
+
export const GATEWAY_FAIL = Object.freeze({
|
|
14
|
+
CONNECTION_REFUSED: 1, HOST_UNREACHABLE: 2, DNS_FAILED: 3, POLICY_DENIED: 4, TIMEOUT: 5, CLOSED: 6, QUEUE_FULL: 7,
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
export const DEFAULT_MAX_CONNECTIONS = 32;
|
|
18
|
+
export const DEFAULT_MAX_BUFFERED = 4 * 1024 * 1024;
|
|
19
|
+
export const DEFAULT_MAX_CLIENT_BUFFERED = 32 * 1024 * 1024;
|
|
20
|
+
export const MAX_DATA_BYTES = 1024 * 1024;
|
|
21
|
+
export const HALF_CLOSE_GRACE_MS = 1000;
|
|
22
|
+
export const ENDPOINT_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
23
|
+
|
|
24
|
+
/** The limits shared by every gateway (validated here so the Node and the in-page host agree). */
|
|
25
|
+
export function normalizeGatewayLimits(opts) {
|
|
26
|
+
const maxConnections = opts.maxConnections ?? DEFAULT_MAX_CONNECTIONS;
|
|
27
|
+
if (!Number.isInteger(maxConnections) || maxConnections < 1) throw new TypeError('gateway.maxConnections must be a positive integer');
|
|
28
|
+
const maxBufferedBytes = opts.maxBufferedBytes ?? DEFAULT_MAX_BUFFERED;
|
|
29
|
+
const maxClientBufferedBytes = opts.maxClientBufferedBytes ?? DEFAULT_MAX_CLIENT_BUFFERED;
|
|
30
|
+
if (!Number.isInteger(maxBufferedBytes) || maxBufferedBytes < GATEWAY_CREDIT_WINDOW) throw new TypeError(`gateway.maxBufferedBytes must be an integer of at least ${GATEWAY_CREDIT_WINDOW}`);
|
|
31
|
+
if (!Number.isInteger(maxClientBufferedBytes) || maxClientBufferedBytes < maxBufferedBytes) throw new TypeError('gateway.maxClientBufferedBytes must be an integer of at least maxBufferedBytes');
|
|
32
|
+
return { maxConnections, maxBufferedBytes, maxClientBufferedBytes };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** `{ name: handler | { open, authorize } }` -> a Map, or null when there are none. */
|
|
36
|
+
export function normalizeEndpoints(endpoints) {
|
|
37
|
+
if (endpoints === undefined || endpoints === null) return null;
|
|
38
|
+
if (typeof endpoints !== 'object' || Array.isArray(endpoints)) throw new TypeError('gateway.endpoints must be an object of { name: handler }');
|
|
39
|
+
const map = new Map();
|
|
40
|
+
for (const [name, h] of Object.entries(endpoints)) {
|
|
41
|
+
if (!ENDPOINT_NAME_RE.test(name)) throw new TypeError(`gateway.endpoints: ${JSON.stringify(name)} is not a valid endpoint name (letters, digits, ".", "_", "-"; at most 64)`);
|
|
42
|
+
const open = typeof h === 'function' ? h : h?.open;
|
|
43
|
+
if (typeof open !== 'function') throw new TypeError(`gateway.endpoints[${JSON.stringify(name)}] needs a handler function (duplex, who) => void, or { open, authorize }`);
|
|
44
|
+
if (h?.authorize !== undefined && typeof h.authorize !== 'function') throw new TypeError(`gateway.endpoints[${JSON.stringify(name)}].authorize must be a function (who) => boolean`);
|
|
45
|
+
map.set(name, { open, authorize: h?.authorize ?? null });
|
|
46
|
+
}
|
|
47
|
+
return map.size === 0 ? null : map;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* The configuration of a gateway that serves named endpoints only (no TCP, DNS or unix sockets): what
|
|
52
|
+
* `createMemoryHost({ endpoints })` passes as `gateway`, with `createEndpointGatewaySession` as the session factory.
|
|
53
|
+
*/
|
|
54
|
+
export function normalizeEndpointGateway(opts = {}) {
|
|
55
|
+
return { ...normalizeGatewayLimits(opts), tcp: false, unix: null, endpoints: normalizeEndpoints(opts.endpoints) };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Which gateway-related features a host with this config advertises (besides what the connection adds). */
|
|
59
|
+
export function gatewayFeatures(cfg) {
|
|
60
|
+
const f = [];
|
|
61
|
+
if (cfg.tcp) f.push('gateway');
|
|
62
|
+
f.push(GATEWAY_CREDIT_FEATURE);
|
|
63
|
+
if (cfg.unix) f.push('gateway-unix');
|
|
64
|
+
if (cfg.endpoints) f.push('gateway-endpoints');
|
|
65
|
+
return f;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The per-connection core: the table of open gateway connections, the per-client byte budget, credit negotiation and
|
|
70
|
+
* the opcodes that need no Node API. `gateway.mjs` builds its socket-backed session on the same object.
|
|
71
|
+
* @param {{ maxConnections: number, maxBufferedBytes: number, maxClientBufferedBytes: number, endpoints: Map<string, object> | null }} cfg
|
|
72
|
+
* @param {(msg: object) => unknown} send
|
|
73
|
+
* @param {(line: string) => void} log
|
|
74
|
+
* @param {{ who?: () => { username: string | null, fingerprint: string | null } }} [ctx]
|
|
75
|
+
*/
|
|
76
|
+
export function createGatewayCore(cfg, send, log = () => {}, ctx = {}) {
|
|
77
|
+
/** @type {Map<number, { channel: GatewayChannel, sock: any }>} */
|
|
78
|
+
const conns = new Map();
|
|
79
|
+
/** gateway_ids whose connect is still in flight (they count against the cap). */
|
|
80
|
+
const pending = new Set();
|
|
81
|
+
let credit = false;
|
|
82
|
+
let closed = false;
|
|
83
|
+
const budget = { used: 0, max: cfg.maxClientBufferedBytes };
|
|
84
|
+
|
|
85
|
+
const reply = (m) => { try { return Promise.resolve(send(m)).catch(() => {}); } catch { return Promise.resolve(); } };
|
|
86
|
+
const fail = (gatewayId, code, message) => reply(gatewayFail({ gatewayId, code, message }));
|
|
87
|
+
const active = () => conns.size + pending.size;
|
|
88
|
+
const idInUse = (id) => conns.has(id) || pending.has(id);
|
|
89
|
+
|
|
90
|
+
/** A channel wired to the wire; `extra` adds the sink (a socket's writer) and the close hooks. */
|
|
91
|
+
function makeChannel(id, extra) {
|
|
92
|
+
return new GatewayChannel({
|
|
93
|
+
id, credit, maxQueued: cfg.maxBufferedBytes, budget,
|
|
94
|
+
sendData: (data) => reply(gatewayData({ gatewayId: id, data })),
|
|
95
|
+
sendCredit: (n) => reply(gatewayCredit({ gatewayId: id, bytes: n })),
|
|
96
|
+
sendClose: (reason) => reply(gatewayClose({ gatewayId: id, reason })),
|
|
97
|
+
...extra,
|
|
98
|
+
onClose: (reason) => { conns.delete(id); extra?.onClose?.(reason); },
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async function openEndpoint(m) {
|
|
103
|
+
const id = m.gateway_id;
|
|
104
|
+
if (!Number.isInteger(id) || typeof m.name !== 'string') return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'malformed OpenEndpoint');
|
|
105
|
+
if (idInUse(id)) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'gateway_id already in use');
|
|
106
|
+
const ep = cfg.endpoints && ENDPOINT_NAME_RE.test(m.name) ? cfg.endpoints.get(m.name) : undefined;
|
|
107
|
+
if (!ep) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'no such endpoint');
|
|
108
|
+
if (active() >= cfg.maxConnections) return fail(id, GATEWAY_FAIL.QUEUE_FULL, 'too many gateway connections');
|
|
109
|
+
const who = ctx.who?.() ?? { username: null, fingerprint: null };
|
|
110
|
+
pending.add(id);
|
|
111
|
+
try {
|
|
112
|
+
if (ep.authorize && !(await ep.authorize(who))) { pending.delete(id); return await fail(id, GATEWAY_FAIL.POLICY_DENIED, 'endpoint refused this caller'); }
|
|
113
|
+
} catch (e) { pending.delete(id); log(`gateway endpoint ${m.name} authorize threw: ${e.message}`); return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'endpoint refused this caller'); }
|
|
114
|
+
pending.delete(id);
|
|
115
|
+
if (closed) return undefined;
|
|
116
|
+
const channel = makeChannel(id, { writeAfterRemoteClose: true, graceMs: HALF_CLOSE_GRACE_MS });
|
|
117
|
+
conns.set(id, { channel, sock: null });
|
|
118
|
+
const { readable, writable } = channel.streams();
|
|
119
|
+
const duplex = {
|
|
120
|
+
readable, writable, who,
|
|
121
|
+
/** Half-close: nothing more will be sent. */
|
|
122
|
+
close: (reason) => channel.end(reason),
|
|
123
|
+
/** Tear the connection down now. */
|
|
124
|
+
destroy: (reason) => channel.destroy(reason),
|
|
125
|
+
closed: channel.closedPromise,
|
|
126
|
+
};
|
|
127
|
+
try {
|
|
128
|
+
const out = ep.open(duplex, who);
|
|
129
|
+
if (out && typeof out.then === 'function') out.then(undefined, (e) => { log(`gateway endpoint ${m.name} failed: ${e?.message}`); channel.destroy('endpoint error'); });
|
|
130
|
+
} catch (e) {
|
|
131
|
+
log(`gateway endpoint ${m.name} threw: ${e.message}`);
|
|
132
|
+
channel.abandon();
|
|
133
|
+
return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'endpoint refused the connection');
|
|
134
|
+
}
|
|
135
|
+
log(`gateway: ${id} -> endpoint ${m.name}`);
|
|
136
|
+
return reply(gatewayOk({ gatewayId: id }));
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
return {
|
|
140
|
+
conns, pending, budget, reply, fail, active, idInUse, makeChannel,
|
|
141
|
+
get closed() { return closed; },
|
|
142
|
+
/** Credit is used on this connection only when the client listed "gateway-credit" in its Hello. */
|
|
143
|
+
setPeerFeatures(features) { credit = Array.isArray(features) && features.includes(GATEWAY_CREDIT_FEATURE); },
|
|
144
|
+
/** @returns {Promise<boolean>} true when the message was a gateway message this session consumed */
|
|
145
|
+
async handle(m) {
|
|
146
|
+
if (closed) return true;
|
|
147
|
+
switch (m.type) {
|
|
148
|
+
case MSG.OPEN_ENDPOINT: await openEndpoint(m); return true;
|
|
149
|
+
case MSG.GATEWAY_DATA: {
|
|
150
|
+
const c = conns.get(m.gateway_id)?.channel;
|
|
151
|
+
const d = m.data;
|
|
152
|
+
if (c && d && d.length <= MAX_DATA_BYTES) c.receive(d);
|
|
153
|
+
return true;
|
|
154
|
+
}
|
|
155
|
+
case MSG.GATEWAY_CREDIT: {
|
|
156
|
+
if (credit && Number.isInteger(m.bytes)) conns.get(m.gateway_id)?.channel.grant(m.bytes);
|
|
157
|
+
return true;
|
|
158
|
+
}
|
|
159
|
+
case MSG.GATEWAY_CLOSE: {
|
|
160
|
+
conns.get(m.gateway_id)?.channel.remoteClosed(m.reason);
|
|
161
|
+
return true;
|
|
162
|
+
}
|
|
163
|
+
// What this host does not serve is refused, not ignored, so the client does not wait for an answer.
|
|
164
|
+
case MSG.OPEN_TCP: case MSG.OPEN_UDP: case MSG.RESOLVE_DNS:
|
|
165
|
+
await fail(m.gateway_id, GATEWAY_FAIL.POLICY_DENIED, 'only named endpoints are available on this host'); return true;
|
|
166
|
+
case MSG.OPEN_UNIX:
|
|
167
|
+
await fail(m.gateway_id, GATEWAY_FAIL.POLICY_DENIED, 'unix sockets are not available on this host'); return true;
|
|
168
|
+
case MSG.LISTEN_REQUEST: case MSG.LISTEN_UNIX:
|
|
169
|
+
await reply(listenFail({ listenerId: m.listener_id, reason: 'listening is not available on this host' })); return true;
|
|
170
|
+
default: return false;
|
|
171
|
+
}
|
|
172
|
+
},
|
|
173
|
+
close() {
|
|
174
|
+
closed = true;
|
|
175
|
+
for (const { channel } of [...conns.values()]) channel.abandon('connection closed');
|
|
176
|
+
conns.clear();
|
|
177
|
+
},
|
|
178
|
+
get size() { return conns.size; },
|
|
179
|
+
/** Bytes received from the client for its origins and not yet taken by them (what the caps bound). */
|
|
180
|
+
get bufferedBytes() { return budget.used; },
|
|
181
|
+
get listenerCount() { return 0; },
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** The session factory of an endpoints-only host (`cfg.createGatewaySession`). */
|
|
186
|
+
export function createEndpointGatewaySession(cfg, send, log, ctx) {
|
|
187
|
+
return createGatewayCore(cfg, send, log, ctx);
|
|
188
|
+
}
|