@johnhenry/wsh 0.35.0 → 0.37.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +453 -21
- package/package.json +18 -1
- package/src/bridge-seal.mjs +77 -0
- package/src/channel-binding.mjs +124 -0
- package/src/client.mjs +351 -62
- package/src/e2e-exchange.mjs +51 -1
- package/src/features.mjs +28 -0
- package/src/forward-node.mjs +118 -0
- package/src/gateway-channel.mjs +250 -0
- package/src/gateway-client.mjs +252 -0
- package/src/host-backends.mjs +100 -0
- package/src/host.d.ts +146 -0
- package/src/host.mjs +30 -0
- package/src/index.d.ts +114 -0
- package/src/index.mjs +13 -0
- package/src/memory-host.d.ts +34 -3
- package/src/memory-host.mjs +57 -13
- package/src/messages.gen.mjs +59 -7
- package/src/operator-proof.mjs +135 -0
- package/src/pipe-relay.d.ts +49 -0
- package/src/pipe-relay.mjs +274 -0
- package/src/reverse-host.d.ts +25 -0
- package/src/reverse-host.mjs +339 -0
- package/src/server/address-guard.mjs +164 -0
- package/src/server/backends.mjs +10 -16
- package/src/server/client-env.mjs +60 -0
- package/src/server/connection.mjs +100 -23
- package/src/server/constants.mjs +3 -0
- package/src/server/fs.mjs +2 -3
- package/src/server/gateway-core.mjs +188 -0
- package/src/server/gateway.mjs +483 -80
- package/src/server/index.d.ts +103 -5
- package/src/server/index.mjs +25 -4
- package/src/server/pty.mjs +1 -0
- package/src/server/relay.mjs +45 -2
- package/src/server/reverse-host.mjs +7 -213
- package/src/server/socket.mjs +25 -4
- package/src/server/unix-policy.mjs +120 -0
- package/src/server/webtransport.mjs +2 -0
- package/src/transport-ws.mjs +16 -0
- package/src/transport.mjs +11 -0
package/src/index.d.ts
CHANGED
|
@@ -1824,8 +1824,17 @@ export interface WshHostKeyOptions {
|
|
|
1824
1824
|
hostLabel?: string;
|
|
1825
1825
|
/** Sees the verified key before any credential is sent; return `false` (or throw) to refuse. */
|
|
1826
1826
|
onHostKey?: (hostKey: WshHostKey) => boolean | void | Promise<boolean | void>;
|
|
1827
|
+
/**
|
|
1828
|
+
* Refuse to sign the login unless the signature can be bound to this connection (#119): `true` needs at least one
|
|
1829
|
+
* binding kind the host offers and this client can supply (`host`, `cert-hash`, `tls-exporter`), an array names
|
|
1830
|
+
* kinds that must all be bound. Nothing is signed otherwise. Key logins only.
|
|
1831
|
+
*/
|
|
1832
|
+
requireChannelBinding?: boolean | WshChannelBindingKind[];
|
|
1827
1833
|
}
|
|
1828
1834
|
|
|
1835
|
+
/** What a login signature can be bound to (wsh #119). */
|
|
1836
|
+
export type WshChannelBindingKind = 'cert-hash' | 'host' | 'tls-exporter';
|
|
1837
|
+
|
|
1829
1838
|
/** Options for WshClient.connect(). */
|
|
1830
1839
|
export interface WshConnectOptions extends WshHostKeyOptions {
|
|
1831
1840
|
username: string;
|
|
@@ -1921,6 +1930,7 @@ export interface WshConnectReverseOptions {
|
|
|
1921
1930
|
trustOnFirstUse?: boolean;
|
|
1922
1931
|
hostLabel?: string;
|
|
1923
1932
|
onHostKey?: WshHostKeyOptions['onHostKey'];
|
|
1933
|
+
requireChannelBinding?: WshHostKeyOptions['requireChannelBinding'];
|
|
1924
1934
|
expose?: {
|
|
1925
1935
|
shell?: boolean;
|
|
1926
1936
|
exec?: boolean;
|
|
@@ -2010,6 +2020,31 @@ export const E2E_FEATURE: 'e2e';
|
|
|
2010
2020
|
/** Host feature: it signs its `KeyExchange` reply, so `initiateE2E(..., { verifyPeer })` can authenticate it. */
|
|
2011
2021
|
export const E2E_SIGN_FEATURE: 'e2e-sign';
|
|
2012
2022
|
|
|
2023
|
+
/** Relay feature / operator feature: a `ReverseChallenge` / `ReverseProof` crosses the relay (#117). */
|
|
2024
|
+
export const OPERATOR_PROOF_FEATURE: 'operator-proof';
|
|
2025
|
+
/** Host feature (`ReverseAccept.features`): it takes a signed initiator half and a sealed bridge (#117). */
|
|
2026
|
+
export const E2E_SEALED_FEATURE: 'e2e-sealed';
|
|
2027
|
+
export function challengeTranscript(t: { peerPublicKey: Uint8Array; operatorFingerprint: string; nonce: Uint8Array; sessionId: string }): Uint8Array;
|
|
2028
|
+
export function proofTranscript(t: { peerPublicKey: Uint8Array; operatorPublicKey: Uint8Array; username: string; nonce: Uint8Array; sessionId: string }): Uint8Array;
|
|
2029
|
+
/** `EncryptedFrame.channel_id` of a bridge-level frame (real channels start at 1). */
|
|
2030
|
+
export const BRIDGE_CHANNEL_ID: 0;
|
|
2031
|
+
/** A sealed reverse bridge (#117): seals every message that would cross it into an `EncryptedFrame` and opens them. */
|
|
2032
|
+
export class SealedBridge {
|
|
2033
|
+
constructor(p: { key: CryptoKey; sessionId: string; role: 'initiator' | 'responder' });
|
|
2034
|
+
readonly sessionId: string;
|
|
2035
|
+
isFrame(msg: WshMessage): boolean;
|
|
2036
|
+
seal(msg: WshMessage): Promise<WshMessage>;
|
|
2037
|
+
open(frame: WshMessage): Promise<WshMessage>;
|
|
2038
|
+
}
|
|
2039
|
+
/** Operator proof (#117): the peer's signed `ReverseChallenge` fields, and the checks on each side. */
|
|
2040
|
+
export function createReverseChallenge(identity: { keyPair?: CryptoKeyPair; signer?: WshSigner }, operatorFingerprint: string): Promise<{ fields: object; nonce: Uint8Array; sessionId: string; peerPublicKey: Uint8Array }>;
|
|
2041
|
+
export function verifyReverseChallenge(msg: WshMessage, expect: { target: string; ownFingerprint: string }): Promise<{ peerPublicKey: Uint8Array; peerFingerprint: string; nonce: Uint8Array; sessionId: string }>;
|
|
2042
|
+
export function createOperatorProof(signer: { publicKeyRaw: Uint8Array; sign(data: Uint8Array): Promise<Uint8Array> }, challenge: { peerPublicKey: Uint8Array; nonce: Uint8Array; sessionId: string }, username: string): Promise<object>;
|
|
2043
|
+
export function verifyOperatorProof(msg: WshMessage, issued: { nonce: Uint8Array; sessionId: string; peerPublicKey: Uint8Array }): Promise<{ publicKey: Uint8Array; fingerprint: string; username: string } | null>;
|
|
2044
|
+
/** The binding a login signature carries (#119): SHA-256 over the kinds present, or empty when there are none. */
|
|
2045
|
+
export function computeChannelBinding(values: Partial<Record<WshChannelBindingKind, Uint8Array>>): Promise<Uint8Array>;
|
|
2046
|
+
export const CHANNEL_BINDING_KINDS: readonly WshChannelBindingKind[];
|
|
2047
|
+
|
|
2013
2048
|
/** The bytes a responder signs in `KeyExchange.signature`. */
|
|
2014
2049
|
export function keyExchangeTranscript(t: {
|
|
2015
2050
|
sessionId: string;
|
|
@@ -2073,6 +2108,31 @@ export interface WshFileOperationResult {
|
|
|
2073
2108
|
* Supports forward connections (client opens sessions on a remote server) and
|
|
2074
2109
|
* reverse mode (client registers as a peer for incoming connections).
|
|
2075
2110
|
*/
|
|
2111
|
+
/** Options for `openUnix` / `openEndpoint` / `openTcp`. */
|
|
2112
|
+
export interface WshGatewayOpenOptions { signal?: AbortSignal; timeoutMs?: number }
|
|
2113
|
+
|
|
2114
|
+
/** One gateway connection as web streams with backpressure (credit-based flow control when both ends offer `gateway-credit`). */
|
|
2115
|
+
export interface WshGatewayDuplex {
|
|
2116
|
+
/** What the peer sends. Read it to keep credit flowing: a reader that stops reading stops the peer. */
|
|
2117
|
+
readable: ReadableStream<Uint8Array>;
|
|
2118
|
+
/** What you send. Each write waits for credit; closing it half-closes (the peer finishes and closes its side). */
|
|
2119
|
+
writable: WritableStream<Uint8Array>;
|
|
2120
|
+
/** Half-close: nothing more will be written. */
|
|
2121
|
+
close(reason?: string): void;
|
|
2122
|
+
/** Tear the connection down now. */
|
|
2123
|
+
destroy(reason?: string): void;
|
|
2124
|
+
/** Settles once the connection is over. */
|
|
2125
|
+
closed: Promise<string | undefined>;
|
|
2126
|
+
}
|
|
2127
|
+
|
|
2128
|
+
/** A GatewayFail / ListenFail as an Error: `code` 4 = refused by the host's policy, 7 = too many connections, 1 = refused by the target. */
|
|
2129
|
+
export class GatewayError extends Error { code: number }
|
|
2130
|
+
|
|
2131
|
+
/** The feature a client lists in `Hello.features` and a host in `ServerHello.features` to meter gateway data with `GatewayCredit`. */
|
|
2132
|
+
export const GATEWAY_CREDIT_FEATURE: 'gateway-credit';
|
|
2133
|
+
/** Credit, in bytes, each direction of a gateway connection starts with. */
|
|
2134
|
+
export const GATEWAY_CREDIT_WINDOW: 262144;
|
|
2135
|
+
|
|
2076
2136
|
export class WshClient {
|
|
2077
2137
|
/** Current client state. */
|
|
2078
2138
|
readonly state: 'disconnected' | 'connecting' | 'connected' | 'authenticated' | 'closed';
|
|
@@ -2088,6 +2148,9 @@ export class WshClient {
|
|
|
2088
2148
|
*/
|
|
2089
2149
|
readonly authToken: Uint8Array | null;
|
|
2090
2150
|
|
|
2151
|
+
/** Seconds the host said it will keep this connection (`AuthOk.ttl`); 0 = no limit promised. Hosts older than 0.36 sent an unenforced 3600. */
|
|
2152
|
+
readonly authTtl: number;
|
|
2153
|
+
|
|
2091
2154
|
/** Read-only view of active sessions. */
|
|
2092
2155
|
readonly sessions: Map<number, WshSession>;
|
|
2093
2156
|
|
|
@@ -2161,6 +2224,25 @@ export class WshClient {
|
|
|
2161
2224
|
*/
|
|
2162
2225
|
openSession(opts?: WshOpenSessionOptions): Promise<WshSession>;
|
|
2163
2226
|
|
|
2227
|
+
// ── Gateway: unix sockets, named endpoints, TCP egress (#120, #123) ──
|
|
2228
|
+
|
|
2229
|
+
/** Connect to a unix-domain socket on the HOST (needs the host feature `gateway-unix`; refused unless its policy lists the path). */
|
|
2230
|
+
openUnix(path: string, opts?: WshGatewayOpenOptions): Promise<WshGatewayDuplex>;
|
|
2231
|
+
/** Open the host's named virtual endpoint (needs the host feature `gateway-endpoints`). */
|
|
2232
|
+
openEndpoint(name: string, opts?: WshGatewayOpenOptions): Promise<WshGatewayDuplex>;
|
|
2233
|
+
/** Connect to host:port FROM THE HOST (needs the host feature `gateway`; refused unless its `gateway.allow` lists it). */
|
|
2234
|
+
openTcp(host: string, port: number, opts?: WshGatewayOpenOptions): Promise<WshGatewayDuplex>;
|
|
2235
|
+
/** A UDP flow to host:port FROM THE HOST over the reliable control stream: each chunk is one datagram (at most 65507 bytes); the host drops what the receiver cannot keep up with. */
|
|
2236
|
+
openUdp(host: string, port: number, opts?: WshGatewayOpenOptions): Promise<WshGatewayDuplex>;
|
|
2237
|
+
/** Ask the host to listen on a unix-domain socket and hand each connection to `onConnection` (OpenSSH `-R`). */
|
|
2238
|
+
listenUnix(path: string, opts: { replace?: boolean; timeoutMs?: number; onConnection: (duplex: WshGatewayDuplex, info: { peer: string }) => void }): Promise<{ path: string; close(): Promise<void> }>;
|
|
2239
|
+
/**
|
|
2240
|
+
* Node only: forward between a local endpoint and a remote one (`ssh -L` / `-R` with unix sockets and TCP ports mixed).
|
|
2241
|
+
* Each of `local` and `remote` is a socket path (starts with `/`, `./` or `@`) or `host:port`. With `reverse: true` the
|
|
2242
|
+
* HOST listens on `remote` (a unix path) and connections are made to `local` from here.
|
|
2243
|
+
*/
|
|
2244
|
+
forwardUnix(opts: { local: string; remote: string; reverse?: boolean; replace?: boolean; onError?: (err: Error) => void }): Promise<{ local: string; remote: string; address?: { address: string; family: string; port: number } | string | null; close(): Promise<void> }>;
|
|
2245
|
+
|
|
2164
2246
|
/**
|
|
2165
2247
|
* Open a typed (object-mode) RPC channel (wsh #85): JSON-RPC 2.0 over a CBOR sequence on one stream. Sugar over
|
|
2166
2248
|
* `openSession({ type: 'rpc', protocol })`. Throws `RpcError` (`UNSUPPORTED_PROTOCOL`) before sending any bytes
|
|
@@ -2297,6 +2379,34 @@ export class WshClient {
|
|
|
2297
2379
|
*/
|
|
2298
2380
|
reverseConnectTo(targetFingerprint: string, timeout?: number): Promise<void>;
|
|
2299
2381
|
|
|
2382
|
+
/**
|
|
2383
|
+
* Connect to a registered peer and wait for its accept or reject. Against a relay that lists `operator-proof` and a
|
|
2384
|
+
* peer that asks, this operator PROVES its identity to the peer (a signature over the peer's key, a nonce the peer
|
|
2385
|
+
* chose and the bridge's session) instead of leaving the peer to trust the relay's `from_fingerprint` (#117).
|
|
2386
|
+
*/
|
|
2387
|
+
reverseConnect(
|
|
2388
|
+
targetFingerprint: string,
|
|
2389
|
+
timeout?: number,
|
|
2390
|
+
opts?: {
|
|
2391
|
+
/** `'auto'` (default): prove when the relay carries it and the peer asks; `false`: never; `true`: refuse if the relay cannot carry it. */
|
|
2392
|
+
proof?: 'auto' | boolean;
|
|
2393
|
+
/** Refuse the bridge unless the peer signed its challenge (so it proved its key to this operator). */
|
|
2394
|
+
requirePeerProof?: boolean;
|
|
2395
|
+
/**
|
|
2396
|
+
* Seal the bridge: a key exchange both sides sign comes first, and everything after crosses the relay as
|
|
2397
|
+
* `EncryptedFrame`s. Nothing that names a command, a path or a session is sent before the key exists.
|
|
2398
|
+
* The peer must state `e2e-sealed`. `{ hybrid: false }` skips ML-KEM.
|
|
2399
|
+
*/
|
|
2400
|
+
sealed?: boolean | { hybrid?: boolean };
|
|
2401
|
+
},
|
|
2402
|
+
): Promise<WshMessage>;
|
|
2403
|
+
|
|
2404
|
+
/** The binding kinds the last login's signature covered (`[]` = unbound). */
|
|
2405
|
+
readonly channelBinding: WshChannelBindingKind[];
|
|
2406
|
+
|
|
2407
|
+
/** Called with the operator's `ReverseProof` when this peer sent a `ReverseChallenge` (reverse mode). */
|
|
2408
|
+
onReverseProof: ((msg: WshMessage) => void) | null;
|
|
2409
|
+
|
|
2300
2410
|
/**
|
|
2301
2411
|
* Send a control message over the authenticated relay connection.
|
|
2302
2412
|
*/
|
|
@@ -2340,6 +2450,10 @@ export class WshClient {
|
|
|
2340
2450
|
opts?: {
|
|
2341
2451
|
/** The peer's long-term Ed25519 public key; the exchange is refused (`E2E_PEER_UNAUTHENTICATED`) unless it signed its half. */
|
|
2342
2452
|
verifyPeer?: Uint8Array | CryptoKey;
|
|
2453
|
+
/** Sign this (initiator) half with the operator's key; send only to a peer that stated `e2e-sealed`. */
|
|
2454
|
+
signAs?: { sign(data: Uint8Array): Promise<Uint8Array> };
|
|
2455
|
+
/** The responder's raw identity key, bound into the initiator signature (default: `verifyPeer` when raw). */
|
|
2456
|
+
responderIdentity?: Uint8Array;
|
|
2343
2457
|
},
|
|
2344
2458
|
): Promise<WshE2EResult>;
|
|
2345
2459
|
|
package/src/index.mjs
CHANGED
|
@@ -76,10 +76,23 @@ export {
|
|
|
76
76
|
export { WshSession } from './session.mjs';
|
|
77
77
|
export { WshVirtualSessionBackend, normalizeSessionData } from './virtual-session.mjs';
|
|
78
78
|
export { WshClient, MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, STREAM_ANNOUNCE_FEATURE, EXEC_PIPES_FEATURE } from './client.mjs';
|
|
79
|
+
// Gateway forwarding (unix sockets, named endpoints, flow control) -- wsh #120, #123
|
|
80
|
+
export { GatewayError } from './gateway-client.mjs';
|
|
81
|
+
export { GATEWAY_CREDIT_FEATURE, GATEWAY_CREDIT_WINDOW } from './gateway-channel.mjs';
|
|
79
82
|
|
|
80
83
|
// End-to-end key exchange (responder side, feature names, signed transcript) -- wsh #90
|
|
81
84
|
export { E2E_FEATURE, E2E_SIGN_FEATURE, keyExchangeTranscript, verifyKeyExchangeSignature } from './e2e-exchange.mjs';
|
|
82
85
|
|
|
86
|
+
// The operator proves its identity to the peer; sealed bridges -- wsh #117
|
|
87
|
+
export {
|
|
88
|
+
OPERATOR_PROOF_FEATURE, E2E_SEALED_FEATURE, createReverseChallenge, verifyReverseChallenge, createOperatorProof, verifyOperatorProof,
|
|
89
|
+
challengeTranscript, proofTranscript,
|
|
90
|
+
} from './operator-proof.mjs';
|
|
91
|
+
export { SealedBridge, BRIDGE_CHANNEL_ID } from './bridge-seal.mjs';
|
|
92
|
+
|
|
93
|
+
// Channel binding for the login signature -- wsh #119
|
|
94
|
+
export { computeChannelBinding, CHANNEL_BINDING_KINDS } from './channel-binding.mjs';
|
|
95
|
+
|
|
83
96
|
// Key storage
|
|
84
97
|
export { WshKeyStore } from './keystore.mjs';
|
|
85
98
|
|
package/src/memory-host.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import type { WshClient, RpcChannel } from './index.js';
|
|
2
2
|
import type { WshSigner } from './index.js';
|
|
3
|
+
import type { WshFileBackend, WshHostKeyOption } from './host.js';
|
|
3
4
|
import type {
|
|
4
|
-
WshServerAuthOptions, WshServerPrincipal, WshServerMcpOptions, WshExecRunner, WshServerOptions,
|
|
5
|
-
WshAcceptableSocket, WshAcceptOptions,
|
|
5
|
+
WshServerAuthOptions, WshServerPrincipal, WshServerMcpOptions, WshExecRunner, WshServerOptions, WshServerPtyOptions, WshClientEnv,
|
|
6
|
+
WshAcceptableSocket, WshAcceptOptions, WshGatewayEndpointHandler as WshMemoryEndpointHandler,
|
|
6
7
|
} from './server/index.js';
|
|
7
8
|
|
|
8
9
|
export interface WshMemorySessionsOptions {
|
|
@@ -29,7 +30,23 @@ export interface WshMemoryHostOptions {
|
|
|
29
30
|
/** As for `createWshServer`. Omitted = refuse everyone. */
|
|
30
31
|
auth?: WshServerAuthOptions | ((who: WshServerPrincipal) => boolean | Promise<boolean>);
|
|
31
32
|
/** `run(command, io)`; there is no shell in memory, so there is no `true`. */
|
|
32
|
-
exec?: WshExecRunner | { run: WshExecRunner; timeoutMs?: number; clientEnv?:
|
|
33
|
+
exec?: WshExecRunner | { run: WshExecRunner; timeoutMs?: number; clientEnv?: WshClientEnv };
|
|
34
|
+
/** `node-pty`-shaped `{ spawn }`, injected (a browser has no pty of its own). Input arrives at `write` as a `Uint8Array`. Off unless given. */
|
|
35
|
+
pty?: WshServerPtyOptions;
|
|
36
|
+
/** An object of file operations, not a root path (confining paths is the backend's job). Off unless given. */
|
|
37
|
+
fs?: WshFileBackend;
|
|
38
|
+
/**
|
|
39
|
+
* This host's own identity, so clients can pin it: a `CryptoKeyPair` (the private key may be non-extractable), a signer
|
|
40
|
+
* `{ publicKey, sign }` for a key held elsewhere, or `true` for a fresh non-extractable key. Off unless given.
|
|
41
|
+
*/
|
|
42
|
+
hostKey?: WshHostKeyOption;
|
|
43
|
+
/**
|
|
44
|
+
* Offer client-opened QMux data streams (default `true`). `false` serves exec output as `SessionData` instead and
|
|
45
|
+
* offers neither `stream-announce` nor `rpc`: needed for a peer that cannot open streams, the released Rust client over
|
|
46
|
+
* WebSocket (#132). Released clients state nothing a host could choose on, so this is an option, not a negotiation;
|
|
47
|
+
* `accept(socket, { dataStreams })` overrides it for one connection.
|
|
48
|
+
*/
|
|
49
|
+
dataStreams?: boolean;
|
|
33
50
|
mcp?: WshServerMcpOptions;
|
|
34
51
|
extensions?: WshServerOptions['extensions'];
|
|
35
52
|
/** Typed RPC channels: one handler per protocol, called once per opened channel to register methods. Handler functions only (the `wsh-host` / `wsh-fs` built-ins need Node). Off unless given. */
|
|
@@ -43,7 +60,21 @@ export interface WshMemoryHostOptions {
|
|
|
43
60
|
* defaults as `createWshServer`. `true` for the defaults. Off unless given.
|
|
44
61
|
*/
|
|
45
62
|
sessions?: true | false | null | WshMemorySessionsOptions;
|
|
63
|
+
/**
|
|
64
|
+
* Named virtual endpoints: a host with no file system exposes these instead of unix sockets; a client reaches one with
|
|
65
|
+
* `client.openEndpoint(name)`. The handler gets web streams with backpressure and `who` (the authenticated
|
|
66
|
+
* `{ username, fingerprint }`) and refuses by throwing; `{ open, authorize(who) }` authorises per call. Only the
|
|
67
|
+
* names listed exist. Nothing else of the gateway (TCP, DNS, unix sockets) is available in memory.
|
|
68
|
+
*/
|
|
69
|
+
endpoints?: Record<string, WshMemoryEndpointHandler | { open: WshMemoryEndpointHandler; authorize?: (who: { username: string | null; fingerprint: string | null }) => boolean | Promise<boolean> }>;
|
|
46
70
|
bindTimeoutMs?: number;
|
|
71
|
+
/** End each authenticated connection this long after login; advertised as `AuthOk.ttl` in whole seconds. 0 / omitted = never. */
|
|
72
|
+
connectionTtlMs?: number;
|
|
73
|
+
/**
|
|
74
|
+
* Accept a key login only when its signature is bound to this host's key (`host`, the one binding a memory host has).
|
|
75
|
+
* Needs `hostKey`; a client older than 0.36 cannot satisfy it.
|
|
76
|
+
*/
|
|
77
|
+
requireChannelBinding?: boolean | Array<'host'>;
|
|
47
78
|
onLog?: (line: string) => void;
|
|
48
79
|
}
|
|
49
80
|
|
package/src/memory-host.mjs
CHANGED
|
@@ -7,9 +7,16 @@
|
|
|
7
7
|
* password auth, exec channels, MCP tools, extensions), speaking QMux over a pair of in-memory WebSocket-like
|
|
8
8
|
* sockets -- so what a client does here is what it does against a server. It serves what a browser can: `exec` as a
|
|
9
9
|
* function you provide (there is no shell), `mcp` tools, `extensions`, typed `rpc` channels (handler functions you
|
|
10
|
-
* provide)
|
|
11
|
-
*
|
|
12
|
-
*
|
|
10
|
+
* provide), `sessions` (detach / attach / resume of exec sessions, output replayed from an in-memory ring buffer) and
|
|
11
|
+
* `endpoints` (named virtual endpoints, the in-memory stand-in for unix sockets, with flow control).
|
|
12
|
+
* Backends are injected, shaped like the Node host's: `pty` (`{ spawn }`, node-pty shaped), `fs` (an object of file
|
|
13
|
+
* operations, not a root path), `hostKey` (a `CryptoKeyPair`, which may be non-extractable, or a signer
|
|
14
|
+
* `{ publicKey, sign }`).
|
|
15
|
+
* Not available: the TCP, DNS, UDP and unix-socket parts of `gateway` (named `endpoints` are), `relay`, WebTransport,
|
|
16
|
+
* `exec: true` and `fs: { root }` (they need Node), the `wsh-host` / `wsh-fs` rpc built-ins (use `@johnhenry/wsh/server`).
|
|
17
|
+
*
|
|
18
|
+
* To serve a socket someone else upgraded (a WebSocket the page opened to a relay, a byte pipe) use `host.accept(socket)`;
|
|
19
|
+
* a peer that cannot open QMux data streams (the released Rust client over WebSocket) needs `dataStreams: false`.
|
|
13
20
|
*
|
|
14
21
|
* ```js
|
|
15
22
|
* import { createMemoryHost } from '@johnhenry/wsh/memory';
|
|
@@ -25,8 +32,10 @@ import { WshClient } from './client.mjs';
|
|
|
25
32
|
import { WebSocketTransport } from './transport-ws.mjs';
|
|
26
33
|
import { createConnectionFactory } from './server/connection.mjs';
|
|
27
34
|
import { buildAuthorizer, authMethods, FailureLimiter } from './server/auth.mjs';
|
|
28
|
-
import {
|
|
35
|
+
import { resolveBackends, resolveHostKey } from './host-backends.mjs';
|
|
29
36
|
import { bindSocket } from './server/socket.mjs';
|
|
37
|
+
import { normalizeEndpointGateway, createEndpointGatewaySession } from './server/gateway-core.mjs';
|
|
38
|
+
import { CHANNEL_BINDING_KINDS } from './channel-binding.mjs';
|
|
30
39
|
import { RPC_PROTOCOL_NAME_RE, RPC_DEFAULT_MAX_MESSAGE } from './rpc.mjs';
|
|
31
40
|
import { SessionRegistry, DEFAULT_RING_BYTES, DEFAULT_DETACH_TTL_MS, DEFAULT_MAX_DETACHED } from './session-registry.mjs';
|
|
32
41
|
|
|
@@ -122,8 +131,22 @@ function createRegistry(sessions, log) {
|
|
|
122
131
|
/**
|
|
123
132
|
* @param {object} [options]
|
|
124
133
|
* @param {object | Function} [options.auth] - As for `createWshServer`. Omitted = refuse everyone.
|
|
125
|
-
* @param {Function | { run: Function, timeoutMs?: number, clientEnv?: boolean }} [options.exec]
|
|
134
|
+
* @param {Function | { run: Function, timeoutMs?: number, clientEnv?: boolean | string[] | Function }} [options.exec]
|
|
126
135
|
* `run(command, io) => Promise<exitCode>` (see `ExecIo` in `server/exec.mjs`): the host has no shell, so there is no `true`.
|
|
136
|
+
* @param {{ spawn: Function, shell?: string, cwd?: string, env?: object, term?: string }} [options.pty]
|
|
137
|
+
* `pty.spawn(file, args, { name, cols, rows, cwd, env })` as `node-pty`'s `spawn` (or anything shaped like it) returns
|
|
138
|
+
* `{ onData(cb), onExit(cb), write(data), resize(cols, rows), kill(signal?) }`. Input arrives at `write` as a `Uint8Array`.
|
|
139
|
+
* `shell` is the `file` it is called with (default `/bin/sh`: name the program your `spawn` understands).
|
|
140
|
+
* @param {{ operate: Function, readWhole: Function, writeWhole: Function, writeAt: Function, openRange?: Function, maxFileBytes?: number }} [options.fs]
|
|
141
|
+
* File operations, as `createFileAccess` in `@johnhenry/wsh/server` returns them (see `normalizeFileBackend` in
|
|
142
|
+
* `host-backends.mjs`). Not a root path: confining paths is the backend's job.
|
|
143
|
+
* @param {true | CryptoKeyPair | { publicKey: Uint8Array | CryptoKey, sign: Function }} [options.hostKey]
|
|
144
|
+
* This host's own identity, so clients can pin it (TOFU): a `CryptoKeyPair` (non-extractable is fine), a signer
|
|
145
|
+
* `{ publicKey, sign(data) }`, or `true` for a fresh non-extractable key.
|
|
146
|
+
* @param {boolean} [options.dataStreams=true] - Offer client-opened QMux data streams for exec output (`stream-announce`,
|
|
147
|
+
* rpc). Set `false` for a peer that cannot open them -- the released Rust client over WebSocket -- so exec output rides
|
|
148
|
+
* `SessionData` instead (and `rpc` is not offered). The released clients state nothing in their `Hello` that a host could
|
|
149
|
+
* key an automatic choice on, so this is an option; `accept(socket, { dataStreams })` overrides it per connection.
|
|
127
150
|
* @param {{ tools?: object[] | object, client?: object, authorize?: Function, maxConcurrent?: number, timeoutMs?: number }} [options.mcp]
|
|
128
151
|
* @param {Record<string, Function>} [options.extensions] - Handlers for application-defined messages, as for `createWshServer`.
|
|
129
152
|
* @param {Record<string, Function>} [options.rpc] - Typed RPC channels: `{ [protocol]: (channel, ctx) => void | Promise<void> }`,
|
|
@@ -135,19 +158,37 @@ function createRegistry(sessions, log) {
|
|
|
135
158
|
* `createWshServer`, with the same defaults (300000 ms detached, 16 detached sessions, 1 MiB of replayable output
|
|
136
159
|
* per session). Off unless given: sessions then die with their connection. There is no `sessionSecret`: session
|
|
137
160
|
* tokens are random per session.
|
|
161
|
+
* @param {Record<string, ((duplex: object, who: { username: string | null, fingerprint: string | null }) => void | Promise<void>) | { open: Function, authorize?: (who: object) => boolean | Promise<boolean> }>} [options.endpoints]
|
|
162
|
+
* Named virtual endpoints (a host with no file system exposes these instead of unix sockets): a client reaches one with
|
|
163
|
+
* `client.openEndpoint(name)`. `duplex` is `{ readable, writable, close(), destroy(), closed, who }` (web streams with
|
|
164
|
+
* backpressure) and `who` is the authenticated `{ username, fingerprint }`, so the handler can authorise per call:
|
|
165
|
+
* throw synchronously to refuse, or give `{ open, authorize(who) }`. Only the names listed here exist (an allow-list by
|
|
166
|
+
* construction); nothing else of the gateway (TCP, DNS, unix sockets) is on in memory.
|
|
138
167
|
* @param {number} [options.bindTimeoutMs=3000]
|
|
168
|
+
* @param {number} [options.connectionTtlMs=0] - End each authenticated connection this long after login; advertised as
|
|
169
|
+
* `AuthOk.ttl` in whole seconds (#125). 0 = never.
|
|
170
|
+
* @param {boolean | string[]} [options.requireChannelBinding=false] - Accept a key login only when its signature is bound
|
|
171
|
+
* to this host's key (#119). A memory host can bind only `host` (it has no TLS of its own), so this needs `hostKey`;
|
|
172
|
+
* `true` or `['host']`.
|
|
139
173
|
* @param {(line: string) => void} [options.onLog]
|
|
140
174
|
*/
|
|
141
|
-
export function createMemoryHost({ auth, exec, mcp, extensions, rpc, rpcMaxMessageBytes = RPC_DEFAULT_MAX_MESSAGE, rpcMaxInflight = 64, sessions, bindTimeoutMs = 3000, onLog = () => {} } = {}) {
|
|
175
|
+
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, onLog = () => {} } = {}) {
|
|
176
|
+
if (!Number.isFinite(connectionTtlMs) || connectionTtlMs < 0) throw new TypeError('createMemoryHost: connectionTtlMs must be a non-negative number');
|
|
177
|
+
if (requireChannelBinding !== false && requireChannelBinding !== true && !(Array.isArray(requireChannelBinding) && requireChannelBinding.every((k) => CHANNEL_BINDING_KINDS.includes(k)))) {
|
|
178
|
+
throw new TypeError(`createMemoryHost: requireChannelBinding must be true, false or an array of kinds (${CHANNEL_BINDING_KINDS.join(', ')})`);
|
|
179
|
+
}
|
|
180
|
+
if (Array.isArray(requireChannelBinding) && requireChannelBinding.some((k) => k !== 'host')) throw new TypeError('createMemoryHost: requireChannelBinding can name only "host" (a memory host has no TLS connection or certificate to bind)');
|
|
181
|
+
if (requireChannelBinding && !hostKey) throw new TypeError('createMemoryHost: requireChannelBinding needs a hostKey (the only thing a memory host can bind a login to)');
|
|
142
182
|
if (exec === true) throw new TypeError('createMemoryHost: exec must be a function (run(command, io)); there is no shell to run `true` with');
|
|
143
183
|
if (exec !== undefined && typeof exec !== 'function' && typeof exec?.run !== 'function') {
|
|
144
184
|
throw new TypeError('createMemoryHost: exec must be a function or { run }');
|
|
145
185
|
}
|
|
146
186
|
if (extensions !== undefined && (extensions === null || typeof extensions !== 'object')) throw new TypeError('createMemoryHost: extensions must be an object of handlers');
|
|
187
|
+
if (typeof dataStreams !== 'boolean') throw new TypeError('createMemoryHost: dataStreams must be true or false');
|
|
147
188
|
const rpcHost = rpc === undefined || rpc === null ? null : createRpcTable(rpc, rpcMaxMessageBytes, rpcMaxInflight);
|
|
148
189
|
const registry = sessions === undefined || sessions === null || sessions === false ? null : createRegistry(sessions, onLog);
|
|
149
|
-
const execOptions
|
|
150
|
-
const
|
|
190
|
+
const { execRunner, execOptions, pty: ptyBackend, files, mcp: mcpHost } = resolveBackends({ exec, pty, fs, mcp });
|
|
191
|
+
const hostKeyReady = hostKey === undefined || hostKey === null || hostKey === false ? Promise.resolve(null) : resolveHostKey(hostKey, 'createMemoryHost: hostKey');
|
|
151
192
|
const rl = auth?.rateLimit ?? {};
|
|
152
193
|
const rateLimit = {
|
|
153
194
|
limiter: new FailureLimiter(rl),
|
|
@@ -155,11 +196,14 @@ export function createMemoryHost({ auth, exec, mcp, extensions, rpc, rpcMaxMessa
|
|
|
155
196
|
failureDelayMs: rl.failureDelayMs ?? 250,
|
|
156
197
|
};
|
|
157
198
|
const methods = authMethods(auth);
|
|
158
|
-
|
|
199
|
+
// Named virtual endpoints: a gateway with no TCP, DNS or unix sockets that answers only `OpenEndpoint`, built from
|
|
200
|
+
// the browser-safe core (`server/gateway-core.mjs`), so a page can have it.
|
|
201
|
+
const gatewayCfg = endpoints === undefined || endpoints === null ? null : normalizeEndpointGateway({ endpoints });
|
|
159
202
|
|
|
160
|
-
const ready = buildAuthorizer(auth).then((authorize) => createConnectionFactory({
|
|
161
|
-
authorize, execRunner, execOptions, pty:
|
|
162
|
-
methods, hostKey:
|
|
203
|
+
const ready = Promise.all([buildAuthorizer(auth), hostKeyReady]).then(([authorize, hostKeyResolved]) => createConnectionFactory({
|
|
204
|
+
authorize, execRunner, execOptions, pty: ptyBackend, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, log: onLog,
|
|
205
|
+
methods, hostKey: hostKeyResolved, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost,
|
|
206
|
+
gateway: gatewayCfg, createGatewaySession: gatewayCfg ? createEndpointGatewaySession : undefined, sessions: registry, relay: null,
|
|
163
207
|
}));
|
|
164
208
|
ready.catch(() => {});
|
|
165
209
|
|
|
@@ -168,7 +212,7 @@ export function createMemoryHost({ auth, exec, mcp, extensions, rpc, rpcMaxMessa
|
|
|
168
212
|
|
|
169
213
|
async function accept(socket, options) {
|
|
170
214
|
if (closed) throw new Error('createMemoryHost: host is closed');
|
|
171
|
-
const handle = await bindSocket(socket, ready, options);
|
|
215
|
+
const handle = await bindSocket(socket, ready, { dataStreams, ...options });
|
|
172
216
|
accepted.add(handle);
|
|
173
217
|
return handle;
|
|
174
218
|
}
|
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
|
+
|