@johnhenry/wsh 0.49.0 → 0.50.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +41 -7
- package/package.json +5 -1
- package/spec/capabilities.md +1 -0
- package/spec/duplex-binding.md +86 -0
- package/spec/wsh-v1.yaml +9 -1
- package/src/duplex.d.ts +69 -0
- package/src/duplex.mjs +208 -0
- package/src/key-options.mjs +3 -0
- package/src/server/connection.mjs +11 -6
- package/src/server/socket.mjs +5 -2
package/README.md
CHANGED
|
@@ -666,6 +666,7 @@ bundler drop what you do not use.
|
|
|
666
666
|
| `@johnhenry/wsh/reverse` | `createReverseHost()` for a page or Worker: dial out to a relay and serve the operator it bridges. The same function `@johnhenry/wsh/server` exports, minus `exec: true` and `fs: { root }` |
|
|
667
667
|
| `@johnhenry/wsh/testing` | the QMux record and frame codec (`encodeStream`, `encodeRecord`, `RecordDecoder`, `decodeFrames`, the varint and the other frame encoders), for a test that reads, alters and re-wraps what travels on a connection; and two test doubles for code that embeds wsh: `createInProcessPipeRelay({ tap })` (the real pipe relay in this process, with a `WebSocket` that dials it, a record of every message it copied, and a `tap` that may change, drop, repeat or add to what it writes, like a hostile relay) and `createMemoryPair({ host, username })` (a memory host and a client already logged in to it). **Experimental: not part of the stable API**; it may change or disappear in any release. Importing only the codec costs under 1 kB: the doubles are separate exports a bundler drops |
|
|
668
668
|
| `@johnhenry/wsh/identity` | a key in its four spellings, and `authorized_keys` lines: `fingerprint` and `podId` of a raw key, `fingerprintToPodId` / `podIdToFingerprint`, `rawKeyToOpenSsh` / `openSshToRawKey` / `parseOpenSshKey` / `publicKeyToOpenSsh`, `identityOf`, `normalizeIdentity`, `authorizedKeyLine`. Stable; see [Identity and capabilities for other implementations](#identity-and-capabilities-for-other-implementations-220) |
|
|
669
|
+
| `@johnhenry/wsh/duplex` | a full wsh session over a duplex of messages another library provides: `serveWshOverDuplex(host, { send })`, `connectWshOverDuplex({ send }, credentials)`, `createDuplexSocket`. Sealed by default; see [wsh over a duplex](#wsh-over-a-duplex-220) |
|
|
669
670
|
| `@johnhenry/wsh/capabilities` | `permits(capabilities, request)`: the notation of key capabilities as a pure function, the one `@johnhenry/wsh/server` and the memory host evaluate. Stable; same section |
|
|
670
671
|
| `@johnhenry/wsh/spec/*.json`, `*.md`, `wsh-v1.yaml` | the data files of the specification: `capabilities.md`, `capabilities.vectors.json`, `key-options.vectors.json`, the wire spec |
|
|
671
672
|
| `@johnhenry/wsh/server` | Node only |
|
|
@@ -692,19 +693,20 @@ optional ML-KEM backend, is left out of the measurement. What a page ships is wh
|
|
|
692
693
|
| browser bundle | minified | gzip |
|
|
693
694
|
| --- | ---: | ---: |
|
|
694
695
|
| `@johnhenry/wsh` (whole entry point) | 165.8 kB | 50.3 kB |
|
|
695
|
-
| `@johnhenry/wsh/memory` (whole entry point) |
|
|
696
|
-
| `@johnhenry/wsh/host` (whole entry point) | 127.
|
|
697
|
-
| `@johnhenry/wsh/reverse` (whole entry point) | 221.
|
|
696
|
+
| `@johnhenry/wsh/memory` (whole entry point) | 233.4 kB | 72.9 kB |
|
|
697
|
+
| `@johnhenry/wsh/host` (whole entry point) | 127.9 kB | 42.1 kB |
|
|
698
|
+
| `@johnhenry/wsh/reverse` (whole entry point) | 221.7 kB | 68.6 kB |
|
|
698
699
|
| `@johnhenry/wsh/pipe-relay` (whole entry point) | 7.0 kB | 3.0 kB |
|
|
699
|
-
| `@johnhenry/wsh/testing` (whole entry point) |
|
|
700
|
-
| `@johnhenry/wsh/page` (whole entry point) |
|
|
700
|
+
| `@johnhenry/wsh/testing` (whole entry point) | 241.2 kB | 76.0 kB |
|
|
701
|
+
| `@johnhenry/wsh/page` (whole entry point) | 302.4 kB | 96.0 kB |
|
|
701
702
|
| `@johnhenry/wsh/objects` (whole entry point) | 177.4 kB | 54.4 kB |
|
|
702
|
-
| `@johnhenry/wsh/capabilities` (whole entry point) | 10.
|
|
703
|
+
| `@johnhenry/wsh/capabilities` (whole entry point) | 10.6 kB | 3.8 kB |
|
|
703
704
|
| `@johnhenry/wsh/identity` (whole entry point) | 15.7 kB | 5.7 kB |
|
|
705
|
+
| `@johnhenry/wsh/duplex` (whole entry point) | 140.1 kB | 42.4 kB |
|
|
704
706
|
| `import { encodeRecord } from '@johnhenry/wsh/testing'` | 1.8 kB | 0.9 kB |
|
|
705
707
|
| `import { generateKeyPair } from '@johnhenry/wsh'` | 0.4 kB | 0.3 kB |
|
|
706
708
|
| `import { WshClient } from '@johnhenry/wsh'` | 135.9 kB | 40.8 kB |
|
|
707
|
-
| `import { createConnectionFactory } from '@johnhenry/wsh/host'` | 104.
|
|
709
|
+
| `import { createConnectionFactory } from '@johnhenry/wsh/host'` | 104.6 kB | 34.2 kB |
|
|
708
710
|
<!-- bundle-size:end -->
|
|
709
711
|
|
|
710
712
|
### Signing with a page-held signer
|
|
@@ -2341,6 +2343,7 @@ than left to be found.
|
|
|
2341
2343
|
| `clientEnv` allow-list (#126) | default `TERM`, `COLORTERM`, `LANG`, `LANGUAGE`, `LC_*` | `wsh-server`: the same default; `[server] client_env = true` (everything, the old behaviour), `false` (nothing) or a list of names / `PREFIX*` (replaces the default) | **Both hosts**; wire unchanged. **Breaking default in the Rust server**, see the CHANGELOG |
|
|
2342
2344
|
| `authorized_keys` options (#122): `restrict`, `permit-*`, `no-pty`, `command=`, `max-sessions=` | `auth.authorizedKeys` lines with options on `createWshServer` / `createMemoryHost`; `parseAuthorizedKeyEntries()` | `wsh-server` reads `~/.wsh/authorized_keys` (then `~/.ssh/authorized_keys`) | **Same rules and the same vectors on both hosts** (`spec/key-options.vectors.json`, run by the JS suite and a Rust test); an option that is not understood keeps the key out, on both. See [Authorized-key options](#authorized-key-options-122) for the per-host column |
|
|
2343
2345
|
| Per-key capabilities and expiry (#122): `capabilities="..."`, `expires="..."`; `authorize()` may return a set | every entry the host has: `Open` kinds, `FileOp` read vs write, gateway TCP/UDP/unix/endpoint open and listen, MCP discovery and calls, targets, rpc channels, relay; refusals through `onRefused` (`not-permitted`, `key-expired`) | the same, except **no endpoints and no targets** (`endpoint:` / `target:` parse and grant nothing; such requests are refused); refusals are logged, there is no callback; no `authorize` | **Same grammar, same vectors, same refusal codes on both hosts**; default-deny only for a key whose line has `capabilities`. Neither covers sessions already open, see [Security model](#security-model). The notation is written in `spec/capabilities.md` and its vectors (`spec/capabilities.vectors.json`, `version` 1) ship in the npm package and are run by both; the Rust server's subset is stated by refusal: a key line with an `objects:` capability is refused at load (`unknown-capability`) |
|
|
2346
|
+
| A session over a caller-supplied duplex (#220): `serveWshOverDuplex`, `connectWshOverDuplex` from `@johnhenry/wsh/duplex` | exported, browser-safe; sealed by default | none: the Rust server and client dial a WebSocket, TLS or a pipe relay (a pipe relay carries the same bytes) | **Unified on the wire** (nothing new); the binding is the JS implementation's |
|
|
2344
2347
|
| `permits(capabilities, request)`, `@johnhenry/wsh/identity` (fingerprint, pod id, OpenSSH line, `authorized_keys` line builder), the `GATEWAY_FAIL` table, `serveMcpOverDuplex`, `createDuplexPeer({ who, permit })` (#220) | exported pure functions and seams of the JS package, browser-safe | none: the Rust server and CLI export no library function of these; the Rust server sends the same `GatewayFail` numbers, with `5` meaning "gateway disabled" where the Node gateway sends it for a timeout | **Notation unified by vectors**; the functions are the JS implementation's and are not a wire feature |
|
|
2345
2348
|
| Session recording/replay | `SessionRecorder`/`SessionPlayer` (asciicast-v2-shaped JSON) | none | **JS-only** -- no current Rust consumer needs playback; the vocabulary is asciicast v2's, so a Rust port could share it |
|
|
2346
2349
|
| Self-signed cert pinning | `serverCertificateHashes` (WebTransport option) | `--cert-hash <sha256>` (repeatable) and `ConnectConfig.cert_hash`/`cert_hashes`, with the same rules (SHA-256, ECDSA P-256, at most 14 days); `wsh-server` prints its certificate hash at start-up. Without a pin the certificate is validated against the system trust store; `--insecure-skip-cert-verification` is the development-only opt-out | **Not a wire concept**; a default changed in the Rust client, see the CHANGELOG |
|
|
@@ -2875,6 +2878,37 @@ browsermesh** (a test of the pod id derivation uses `@johnhenry/browsermesh-prim
|
|
|
2875
2878
|
`serveMcpOverDuplex` for MCP, the identity object `{ username, fingerprint, podId }`, and `permits()` of the
|
|
2876
2879
|
[capability notation](#identity-and-capabilities-for-other-implementations-220), which the mesh's own grants run the same vectors against.
|
|
2877
2880
|
|
|
2881
|
+
#### wsh over a duplex (#220)
|
|
2882
|
+
|
|
2883
|
+
`@johnhenry/wsh/duplex` runs a whole wsh session (login, host-key proof, sealed session, channels) over a duplex of messages that another library
|
|
2884
|
+
provides, so a browser with no relay can be reached by hopping through a mesh peer, and a pod can reach a wsh host without a relay. The transport
|
|
2885
|
+
is the one wsh already runs over a WebSocket; `createDuplexSocket` is a WebSocket-shaped object whose messages are the duplex's.
|
|
2886
|
+
|
|
2887
|
+
```js
|
|
2888
|
+
// host (a page, a pod): a host with a host key
|
|
2889
|
+
const host = createMemoryHost({ auth: { authorizedKeys }, hostKey: true, dataStreams: false, exec });
|
|
2890
|
+
const served = serveWshOverDuplex(host, { send: (bytes) => channel.send(bytes) });
|
|
2891
|
+
channel.onmessage = (bytes) => served.receive(bytes);
|
|
2892
|
+
// client: it names the host key it expects (over a mesh: podIdToFingerprint(peerPodId))
|
|
2893
|
+
const link = connectWshOverDuplex({ send: (bytes) => channel.send(bytes) }, { username, keyPair, expectHostKey });
|
|
2894
|
+
channel.onmessage = (bytes) => link.receive(bytes);
|
|
2895
|
+
const client = await link.connected;
|
|
2896
|
+
```
|
|
2897
|
+
|
|
2898
|
+
**The duplex must** deliver messages of bytes reliably and in order, with a maximum size both ends know (`maxMessageBytes`, default 64 KiB; a larger
|
|
2899
|
+
write is cut, a larger incoming message ends the link), and apply backpressure by `send` returning a promise (what waits is bounded by
|
|
2900
|
+
`maxBufferedBytes`, default 4 MiB). One duplex carries one session. The full statement is [`spec/duplex-binding.md`](spec/duplex-binding.md).
|
|
2901
|
+
|
|
2902
|
+
**Channel binding here is not TLS's.** There is none of `cert-hash` or `tls-exporter`. The authentication is carried by the host-key proof (the client
|
|
2903
|
+
compares the key with the one it named), the login bound to that key (`requireChannelBinding: ['host']`, the default) and the sealed session. So a hop on
|
|
2904
|
+
the duplex cannot read or change a command, an output or a credential after login, cannot replay one, and cannot answer as the host to a client that named
|
|
2905
|
+
its key. It can see that a session exists, its timing and sizes, and the plain handshake (the host key, the username, the client's public key); it can
|
|
2906
|
+
drop or delay (the session stalls) or end the link. It is **not** protected against: a client that does not name the host key (`trustOnFirstUse: true` is
|
|
2907
|
+
said out loud: the first answer is trusted), a **password** login (sent before the seal; refused unless `allowUnsealed: true`), or what the host's own
|
|
2908
|
+
`auth` and capabilities allow. **Unsealed is refused by default**: the host serves a duplex only sealed (it needs a host key; `sealSession: 'require'`
|
|
2909
|
+
can now be asked of one connection, `host.accept(socket, { sealSession: 'require' })`, and only strengthens the host's setting), and the client
|
|
2910
|
+
refuses a host that cannot seal. `allowUnsealed: true` on either lifts it, and then a hop can read and change everything.
|
|
2911
|
+
|
|
2878
2912
|
**What is deliberately not shared**
|
|
2879
2913
|
|
|
2880
2914
|
- **Sealing.** A wsh session is sealed once, after a signed key exchange, and everything after login travels in authenticated frames; the
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@johnhenry/wsh",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.50.0",
|
|
4
4
|
"description": "Web Shell \u2014 browser-native remote command execution over WebTransport and WebSocket with Ed25519 authentication",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.mjs",
|
|
@@ -49,6 +49,10 @@
|
|
|
49
49
|
"types": "./src/capabilities.d.ts",
|
|
50
50
|
"import": "./src/capabilities.mjs"
|
|
51
51
|
},
|
|
52
|
+
"./duplex": {
|
|
53
|
+
"types": "./src/duplex.d.ts",
|
|
54
|
+
"import": "./src/duplex.mjs"
|
|
55
|
+
},
|
|
52
56
|
"./identity": {
|
|
53
57
|
"types": "./src/identity.d.ts",
|
|
54
58
|
"import": "./src/identity.mjs"
|
package/spec/capabilities.md
CHANGED
|
@@ -96,6 +96,7 @@ A request is an object with a `kind`. The capability needed (the name a refusal
|
|
|
96
96
|
| `{ kind: 'open', channel: 'rpc', protocol: 'mcp' }` | `mcp:*` (an `mcp:TOOL` key opens it only through a handler that narrows by tool itself, `scoped: true`) |
|
|
97
97
|
| `{ kind: 'open', channel: 'rpc', protocol: 'wsh-objects', scoped: true }` | `rpc:wsh-objects` or any `objects:` entry |
|
|
98
98
|
| `{ kind: 'open', channel: 'rpc', protocol: P }` | `rpc:P` |
|
|
99
|
+
| `{ kind: 'open', channel: 'rpc', protocol: P, authorizesItself: true }` | nothing from the list: a handler that asks the host's own `permits` for every call (`handler.authorizesItself = true`) is opened by any key the options and expiry let in; its own checks decide |
|
|
99
100
|
| `{ kind: 'file-op', op }` | `fs:read` for `stat`, `list`, `read`; `fs:write` for every other `op` |
|
|
100
101
|
| `{ kind: 'mcp' }` (discovery) | any `mcp:` entry |
|
|
101
102
|
| `{ kind: 'mcp-call' | 'mcp-tool', tool }` | `mcp:TOOL` or `mcp:*` |
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
# wsh over a caller-supplied duplex
|
|
2
|
+
|
|
3
|
+
Status: implemented in `@johnhenry/wsh/duplex` (`createDuplexSocket`, `serveWshOverDuplex`, `connectWshOverDuplex`). Nothing is added to the wire.
|
|
4
|
+
|
|
5
|
+
## What this is for
|
|
6
|
+
|
|
7
|
+
A full wsh session (login, host-key proof, the sealed session, channels) over a duplex of messages that another library provides: a browsermesh
|
|
8
|
+
channel between two pods, a `MessagePort`, a data channel. Two things it makes possible: a browser with no relay can be reached by hopping
|
|
9
|
+
through a mesh peer, and a pod can reach a wsh host without a relay. wsh knows nothing of the library that provides the duplex.
|
|
10
|
+
|
|
11
|
+
## What already existed, and what this adds
|
|
12
|
+
|
|
13
|
+
The transport wsh runs over a WebSocket is QMux records on a stream of binary messages (`src/transport-ws.mjs`), and a host serves any
|
|
14
|
+
WebSocket-shaped object it is handed (`host.accept(socket)`, `bindSocket`). So the session needs no new protocol: only a WebSocket-shaped object
|
|
15
|
+
whose messages are the duplex's. That is `createDuplexSocket`. The rest is policy, because a duplex somebody else carries is not a TLS connection:
|
|
16
|
+
|
|
17
|
+
- the session over it is **sealed** unless said otherwise (the host serves nothing until it is; the client refuses a host that cannot);
|
|
18
|
+
- the client must **name the host key** it expects;
|
|
19
|
+
- `sealSession: 'require'` can now be asked for per connection (`bindSocket(..., { sealSession: 'require' })`, `host.accept(socket, { sealSession: 'require' })`):
|
|
20
|
+
it can only strengthen the host's own setting, and a host that cannot seal (no host key, or data streams) refuses to attach the connection at all.
|
|
21
|
+
|
|
22
|
+
## What the duplex must guarantee
|
|
23
|
+
|
|
24
|
+
1. **Reliable, in order, no duplicates.** The bytes of a QMux record and of a sealed frame arrive in the order sent, none lost, none twice. (A
|
|
25
|
+
hop may do worse; see below: what it can do is limited to ending or stalling the session, not changing it.)
|
|
26
|
+
2. **Messages of bytes.** Each message is a `Uint8Array` / `ArrayBuffer`. Text is refused (the link ends).
|
|
27
|
+
3. **A maximum message size** that both ends know (`maxMessageBytes`, default 64 KiB). A write larger than it is cut into messages of at most
|
|
28
|
+
that size and a message larger than it ends the link. Where the cuts fall does not matter: the transport above reads a byte stream and
|
|
29
|
+
reassembles records. (A mesh channel with a smaller limit sets it smaller; a pipe relay carries 4 MiB.)
|
|
30
|
+
4. **Backpressure by a returned promise.** `send` may be asynchronous; the next message is not written until it settles, and what waits is bounded
|
|
31
|
+
(`maxBufferedBytes`, default 4 MiB): over it the link is ended rather than buffered without bound. A `send` that throws or rejects ends the link.
|
|
32
|
+
Inbound, what arrives before anyone listens is held, bounded by the same figure.
|
|
33
|
+
5. **One connection per duplex.** A duplex carries one session. When it ends (the peer left, the channel closed) the caller calls `end()`; when
|
|
34
|
+
the session ends it calls the duplex's `close`.
|
|
35
|
+
6. **Open before use.** The host speaks first (its transport handshake). The caller must have wired `receive` before the far side can send, or hold
|
|
36
|
+
what arrives until it has: a message for an end that does not exist yet is the caller's to keep (a mesh adapter has the channel before the client).
|
|
37
|
+
|
|
38
|
+
Ordering matters more than delivery: a duplex that reorders, or repeats, a record corrupts the byte stream and the session ends; one that drops
|
|
39
|
+
a message stalls it until a timeout. Neither lets anything through that was not sent.
|
|
40
|
+
|
|
41
|
+
## Channel binding: what there is, and what there is not
|
|
42
|
+
|
|
43
|
+
There is **no TLS** on this transport, so there is no `cert-hash` and no `tls-exporter` binding to the connection. What carries the
|
|
44
|
+
authentication instead:
|
|
45
|
+
|
|
46
|
+
- **The host-key proof.** The host signs a challenge that names this session and the client's nonce with its host key; the client checks the
|
|
47
|
+
signature and compares the key with the one it expects (`expectHostKey`, or a `known_hosts` entry; over a mesh, the peer's pod id is the key's hash,
|
|
48
|
+
so `expectHostKey: podIdToFingerprint(peer)`). A hop that answers as the host would have to hold that key.
|
|
49
|
+
- **The login bound to the host key.** `requireChannelBinding: ['host']` (the one binding a memory host has): the client's signature covers the host
|
|
50
|
+
key it proved, so a hop that relays a genuine login to a different host, or the host's challenge to a different client, produces a signature
|
|
51
|
+
the real host rejects. This is the default of `connectWshOverDuplex`.
|
|
52
|
+
- **The sealed session.** After login a signed key exchange (X25519 and ML-KEM-768, both halves signed by the login key and the host key) keys an
|
|
53
|
+
authenticated encryption of every message but the keepalive, with a role tag and a counter: a frame that does not open ends the session, a
|
|
54
|
+
replayed, reflected or reordered one does not open, and an unsealed message after sealing is dropped.
|
|
55
|
+
|
|
56
|
+
## What a hop on the duplex can and cannot do
|
|
57
|
+
|
|
58
|
+
It **cannot**: read a command, an output, a file, a credential, a tool call or an object value after login; change one without the session
|
|
59
|
+
ending (or the message being dropped: nothing altered is delivered); replay a message so that it runs twice; log in as the client or serve as the
|
|
60
|
+
host to a client that named the host key; make a client that required sealing talk unsealed, or make a host that requires it serve a plain client.
|
|
61
|
+
|
|
62
|
+
It **can**: see that a session exists, when it starts and ends, and the size and timing of messages; drop or delay messages (the session
|
|
63
|
+
stalls; there is no integrity of availability); end the link; refuse to carry it. It reads the **handshake**, which is plain before the seal: the
|
|
64
|
+
host's key (public), the client's username, the client's public key and the features each side states.
|
|
65
|
+
|
|
66
|
+
It is **not protected against**: a client that does not name the host key (it trusts the first host that answers, `trustOnFirstUse: true`,
|
|
67
|
+
said out loud, and that is the one moment a hop can answer as the host); a **password** login (the password is sent before the session is sealed,
|
|
68
|
+
so `connectWshOverDuplex` refuses one unless `allowUnsealed: true`); the host's own configuration (what the key may do is the host's `auth`,
|
|
69
|
+
capabilities and allow-lists, not the duplex's); an endpoint that is itself hostile (sealing protects from the hop, not from the peer).
|
|
70
|
+
|
|
71
|
+
## Unsealed
|
|
72
|
+
|
|
73
|
+
`allowUnsealed: true` on either function lifts the seal requirement and the default binding. Nothing a hop does is then caught: it can read and change
|
|
74
|
+
everything. It is for a duplex that is already protected by something else, and it is said in the call.
|
|
75
|
+
|
|
76
|
+
## Not covered here
|
|
77
|
+
|
|
78
|
+
Discovery, and who the peer is (the mesh's business: it must give the key to expect); relaying through several hops (each hop is another
|
|
79
|
+
duplex, and the session is end to end); reconnecting a session over a new duplex (a `resume` of an exec session works as over any connection;
|
|
80
|
+
the duplex itself is one connection).
|
|
81
|
+
|
|
82
|
+
## Compatibility
|
|
83
|
+
|
|
84
|
+
No message, field or feature string is new. A released peer on the other end of a duplex is an ordinary wsh peer: a 0.48.0 client or host
|
|
85
|
+
interoperates (it seals as it always did); the Rust client and server are not bound to a duplex by this change (the Rust CLI dials a pipe
|
|
86
|
+
relay, which carries bytes the same way, with `--via`, and `wsh --sealed`).
|
package/spec/wsh-v1.yaml
CHANGED
|
@@ -1273,7 +1273,15 @@ messages:
|
|
|
1273
1273
|
description: >
|
|
1274
1274
|
Machine-readable failure reason. Known values:
|
|
1275
1275
|
1=CONNECTION_REFUSED, 2=HOST_UNREACHABLE, 3=DNS_FAILED,
|
|
1276
|
-
4=POLICY_DENIED, 5=GATEWAY_DISABLED.
|
|
1276
|
+
4=POLICY_DENIED, 5=GATEWAY_DISABLED, 6=CLOSED, 7=QUEUE_FULL.
|
|
1277
|
+
KNOWN INCONSISTENCY (documentation only, behaviour unchanged):
|
|
1278
|
+
the Rust wsh-server sends 5 for a disabled gateway, while the
|
|
1279
|
+
Node gateway (@johnhenry/wsh/server, the page and memory hosts)
|
|
1280
|
+
sends 5 for a timeout (TIMEOUT), and @johnhenry/browsermesh-netway
|
|
1281
|
+
names 5 TIMEOUT. A client that reads 5 should treat it as "timed
|
|
1282
|
+
out or disabled". 6 and 7 are sent by the Node gateway (the Rust
|
|
1283
|
+
server sends 7 for a full queue). The table is exported as data
|
|
1284
|
+
from @johnhenry/wsh (GATEWAY_FAIL_TABLE).
|
|
1277
1285
|
message:
|
|
1278
1286
|
type: string
|
|
1279
1287
|
required: true
|
package/src/duplex.d.ts
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@johnhenry/wsh/duplex`: a full wsh session over a duplex of messages that another library provides (a mesh channel, a `MessagePort`).
|
|
3
|
+
* Browser-safe. See `spec/duplex-binding.md` for what the duplex must guarantee and what a hop can and cannot do.
|
|
4
|
+
*/
|
|
5
|
+
import type { WshClient } from './index.js';
|
|
6
|
+
|
|
7
|
+
export const DUPLEX_DEFAULT_MAX_MESSAGE_BYTES: 65536;
|
|
8
|
+
export const DUPLEX_DEFAULT_MAX_BUFFERED_BYTES: 4194304;
|
|
9
|
+
|
|
10
|
+
export interface WshDuplexOptions {
|
|
11
|
+
/** Writes ONE message to the far side (reliable, in order). May be asynchronous: the next message waits for it. A throw or rejection ends the link. */
|
|
12
|
+
send(bytes: Uint8Array): void | Promise<void>;
|
|
13
|
+
/** Ends the underlying duplex (called when the session ends; not called after `end()`). */
|
|
14
|
+
close?(reason?: string): void;
|
|
15
|
+
/** Default 65536. A bigger write is cut into messages of at most this size; a bigger incoming message ends the link. */
|
|
16
|
+
maxMessageBytes?: number;
|
|
17
|
+
/** Default 4194304. Bytes waiting for `send` (or for a listener) before the link is ended. */
|
|
18
|
+
maxBufferedBytes?: number;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** What `createDuplexSocket` makes: a WebSocket-shaped object the transport and `host.accept` take, and the two calls that feed it. */
|
|
22
|
+
export function createDuplexSocket(options: WshDuplexOptions): {
|
|
23
|
+
socket: object;
|
|
24
|
+
/** One message from the far side. */
|
|
25
|
+
receive(data: Uint8Array | ArrayBuffer): void;
|
|
26
|
+
/** The duplex ended on its own. */
|
|
27
|
+
end(reason?: string): void;
|
|
28
|
+
readonly closed: boolean;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Serve a host's session over a duplex, SEALED (the host serves nothing until the session is sealed, whatever its own `sealSession`). The host needs a
|
|
33
|
+
* host key; with none `ready` rejects. `allowUnsealed: true` lifts it.
|
|
34
|
+
*/
|
|
35
|
+
export function serveWshOverDuplex(
|
|
36
|
+
host: { accept(socket: object, options?: object): Promise<{ close(): void }> },
|
|
37
|
+
options: WshDuplexOptions & { allowUnsealed?: boolean; remote?: { address?: string } },
|
|
38
|
+
): {
|
|
39
|
+
receive(data: Uint8Array | ArrayBuffer): void;
|
|
40
|
+
end(reason?: string): void;
|
|
41
|
+
ready: Promise<{ close(): void }>;
|
|
42
|
+
close(): void;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Connect a client over a duplex: key login, sealed, bound to the host key, and the host key must be named (`expectHostKey`, `knownHosts`, or
|
|
47
|
+
* `trustOnFirstUse: true`). `allowUnsealed: true` lifts the seal and the binding; a password login needs it.
|
|
48
|
+
*/
|
|
49
|
+
export function connectWshOverDuplex(
|
|
50
|
+
duplex: WshDuplexOptions,
|
|
51
|
+
credentials: {
|
|
52
|
+
username: string;
|
|
53
|
+
keyPair?: CryptoKeyPair;
|
|
54
|
+
signer?: { publicKey: Uint8Array | CryptoKey; sign(data: Uint8Array): Promise<Uint8Array> | Uint8Array };
|
|
55
|
+
password?: string;
|
|
56
|
+
expectHostKey?: string;
|
|
57
|
+
knownHosts?: object;
|
|
58
|
+
trustOnFirstUse?: boolean;
|
|
59
|
+
allowUnsealed?: boolean;
|
|
60
|
+
timeout?: number;
|
|
61
|
+
[option: string]: unknown;
|
|
62
|
+
},
|
|
63
|
+
): {
|
|
64
|
+
receive(data: Uint8Array | ArrayBuffer): void;
|
|
65
|
+
end(reason?: string): void;
|
|
66
|
+
client: WshClient;
|
|
67
|
+
connected: Promise<WshClient>;
|
|
68
|
+
close(): Promise<void>;
|
|
69
|
+
};
|
package/src/duplex.mjs
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@johnhenry/wsh/duplex` -- a full wsh session over a duplex that someone else provides (#220): a mesh channel, a `MessagePort`, a data
|
|
3
|
+
* channel, anything that can carry bytes in order. Browser-safe. The specification, with what the duplex must guarantee and what a hop on it can
|
|
4
|
+
* and cannot do, is `spec/duplex-binding.md`; this file is the binding.
|
|
5
|
+
*
|
|
6
|
+
* ```js
|
|
7
|
+
* // the host side (a page, a pod): a memory host with a host key, served over the link
|
|
8
|
+
* const host = createMemoryHost({ auth: { authorizedKeys }, hostKey: true, dataStreams: false, exec });
|
|
9
|
+
* const served = serveWshOverDuplex(host, { send: (bytes) => channel.send(bytes) });
|
|
10
|
+
* channel.onmessage = (bytes) => served.receive(bytes);
|
|
11
|
+
*
|
|
12
|
+
* // the client side: pinned to the host key it expects (a mesh knows the peer's key), sealed
|
|
13
|
+
* const link = connectWshOverDuplex({ send: (bytes) => channel.send(bytes) }, { username: 'alice', keyPair, expectHostKey });
|
|
14
|
+
* channel.onmessage = (bytes) => link.receive(bytes);
|
|
15
|
+
* const client = await link.connected;
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* Nothing new is on the wire: the duplex carries what a WebSocket would (QMux records), and `createDuplexSocket` is the WebSocket-shaped
|
|
19
|
+
* object the existing transport and `host.accept` already take. A session over it is SEALED unless you say `allowUnsealed: true` out loud.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import { WshClient } from './client.mjs';
|
|
23
|
+
import { WebSocketTransport } from './transport-ws.mjs';
|
|
24
|
+
|
|
25
|
+
const CONNECTING = 0;
|
|
26
|
+
const OPEN = 1;
|
|
27
|
+
const CLOSING = 2;
|
|
28
|
+
const CLOSED = 3;
|
|
29
|
+
|
|
30
|
+
/** Largest message handed to `send` unless the duplex says otherwise: what the pipe relay carries by default is 4 MiB; a mesh channel is far smaller. */
|
|
31
|
+
export const DUPLEX_DEFAULT_MAX_MESSAGE_BYTES = 64 * 1024;
|
|
32
|
+
/** Bytes held for a duplex whose `send` has not finished before the link is dropped (a peer that does not read). */
|
|
33
|
+
export const DUPLEX_DEFAULT_MAX_BUFFERED_BYTES = 4 * 1024 * 1024;
|
|
34
|
+
|
|
35
|
+
const toBytes = (data) => {
|
|
36
|
+
if (data instanceof Uint8Array) return data;
|
|
37
|
+
if (data instanceof ArrayBuffer) return new Uint8Array(data);
|
|
38
|
+
if (ArrayBuffer.isView(data)) return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
39
|
+
return null;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
class DuplexEvent extends Event {
|
|
43
|
+
constructor(type, init = {}) { super(type); Object.assign(this, init); }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The WebSocket-shaped object over a duplex of messages.
|
|
48
|
+
*
|
|
49
|
+
* @param {object} options
|
|
50
|
+
* @param {(bytes: Uint8Array) => void | Promise<void>} options.send writes ONE message to the far side. Messages must arrive reliably and in order. It may be
|
|
51
|
+
* asynchronous (it is waited for before the next is written, which is the backpressure) and a rejection or throw ends the link.
|
|
52
|
+
* @param {(reason?: string) => void} [options.close] ends the underlying duplex
|
|
53
|
+
* @param {number} [options.maxMessageBytes=65536] the largest message `send` is given (a bigger write is cut into messages of at most this size: the
|
|
54
|
+
* transport above reads a byte stream, so where the cuts fall does not matter) and the largest message `receive` accepts (a bigger one ends the link)
|
|
55
|
+
* @param {number} [options.maxBufferedBytes=4194304] bytes waiting for `send`; over it the link is ended (a peer that does not read is not buffered for without bound)
|
|
56
|
+
* @returns {{ socket: object, receive(data: Uint8Array | ArrayBuffer): void, end(reason?: string): void, readonly closed: boolean }}
|
|
57
|
+
*/
|
|
58
|
+
export function createDuplexSocket({ send, close, maxMessageBytes = DUPLEX_DEFAULT_MAX_MESSAGE_BYTES, maxBufferedBytes = DUPLEX_DEFAULT_MAX_BUFFERED_BYTES } = {}) {
|
|
59
|
+
if (typeof send !== 'function') throw new TypeError('createDuplexSocket: send(bytes) is required');
|
|
60
|
+
if (close !== undefined && typeof close !== 'function') throw new TypeError('createDuplexSocket: close must be a function');
|
|
61
|
+
if (!Number.isSafeInteger(maxMessageBytes) || maxMessageBytes < 256) throw new TypeError('createDuplexSocket: maxMessageBytes must be a whole number of at least 256');
|
|
62
|
+
if (!Number.isSafeInteger(maxBufferedBytes) || maxBufferedBytes < maxMessageBytes) throw new TypeError('createDuplexSocket: maxBufferedBytes must be a whole number of at least maxMessageBytes');
|
|
63
|
+
|
|
64
|
+
const events = new EventTarget();
|
|
65
|
+
let buffered = 0;
|
|
66
|
+
let pending = Promise.resolve();
|
|
67
|
+
let finished = false;
|
|
68
|
+
|
|
69
|
+
const finish = (code, reason, { callClose = true } = {}) => {
|
|
70
|
+
if (finished) return;
|
|
71
|
+
finished = true;
|
|
72
|
+
socket.readyState = CLOSED;
|
|
73
|
+
if (callClose) { try { close?.(reason); } catch { /* the duplex is already gone */ } }
|
|
74
|
+
events.dispatchEvent(new DuplexEvent('close', { code, reason, wasClean: code === 1000 }));
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
// A duplex is already up when the socket is made, but whoever uses the socket attaches its listeners a moment later (a client builds its
|
|
78
|
+
// transport after some asynchronous steps). So `open` is told to a listener that arrives after it, and messages wait, in order, for the
|
|
79
|
+
// first listener of `message`: nothing the far side said first (the host speaks first) is lost.
|
|
80
|
+
let opened = false;
|
|
81
|
+
let messageListeners = 0;
|
|
82
|
+
const incoming = [];
|
|
83
|
+
const flush = () => {
|
|
84
|
+
if (!opened || messageListeners === 0) return;
|
|
85
|
+
while (incoming.length && !finished) events.dispatchEvent(new DuplexEvent('message', { data: incoming.shift() }));
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
const socket = {
|
|
89
|
+
CONNECTING, OPEN, CLOSING, CLOSED,
|
|
90
|
+
readyState: CONNECTING,
|
|
91
|
+
binaryType: 'arraybuffer',
|
|
92
|
+
get bufferedAmount() { return buffered; },
|
|
93
|
+
addEventListener: (type, fn, options) => {
|
|
94
|
+
events.addEventListener(type, fn, options);
|
|
95
|
+
if (type === 'open' && opened && !finished) queueMicrotask(() => { if (!finished) fn(new DuplexEvent('open')); });
|
|
96
|
+
if (type === 'message') { messageListeners++; queueMicrotask(flush); }
|
|
97
|
+
},
|
|
98
|
+
removeEventListener: (type, fn) => events.removeEventListener(type, fn),
|
|
99
|
+
send(data) {
|
|
100
|
+
if (socket.readyState !== OPEN) throw new Error('WebSocket is not open');
|
|
101
|
+
const bytes = toBytes(data);
|
|
102
|
+
if (!bytes) return; // wsh frames are binary
|
|
103
|
+
for (let at = 0; at < bytes.byteLength; at += maxMessageBytes) {
|
|
104
|
+
const part = bytes.slice(at, at + maxMessageBytes);
|
|
105
|
+
if (buffered + part.byteLength > maxBufferedBytes) { finish(1013, 'the duplex does not take what is written to it'); return; }
|
|
106
|
+
buffered += part.byteLength;
|
|
107
|
+
pending = pending.then(async () => {
|
|
108
|
+
if (finished) return;
|
|
109
|
+
try { await send(part); } catch { finish(1011, 'the duplex failed to send'); } finally { buffered -= part.byteLength; }
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
},
|
|
113
|
+
close(code = 1000, reason = '') { finish(code, reason); },
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
queueMicrotask(() => { if (finished) return; socket.readyState = OPEN; opened = true; events.dispatchEvent(new DuplexEvent('open')); flush(); });
|
|
117
|
+
|
|
118
|
+
return {
|
|
119
|
+
socket,
|
|
120
|
+
/** One message from the far side. A message that is not bytes, or is larger than `maxMessageBytes`, ends the link. */
|
|
121
|
+
receive(data) {
|
|
122
|
+
if (finished) return;
|
|
123
|
+
const bytes = toBytes(data);
|
|
124
|
+
if (!bytes) { finish(1003, 'a message that is not bytes'); return; }
|
|
125
|
+
if (bytes.byteLength > maxMessageBytes) { finish(1009, 'a message larger than maxMessageBytes'); return; }
|
|
126
|
+
if (incoming.reduce((n, b) => n + b.byteLength, 0) + bytes.byteLength > maxBufferedBytes) { finish(1013, 'more arrived than the receiver takes'); return; }
|
|
127
|
+
incoming.push(bytes.slice().buffer);
|
|
128
|
+
queueMicrotask(flush); // in order, after `open`, once something listens
|
|
129
|
+
},
|
|
130
|
+
/** The duplex ended on its own (the peer left, the channel closed): the socket closes, `close` is not called back. */
|
|
131
|
+
end(reason = 'the duplex ended') { finish(1006, reason, { callClose: false }); },
|
|
132
|
+
get closed() { return finished; },
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Serve a host's wsh session over a duplex: `host.accept(socket)` with `dataStreams: false` and the session SEALED, whatever the host's own
|
|
138
|
+
* `sealSession` says (it can only be strengthened). The host needs a host key (`hostKey: ...`): with none it cannot seal, so it cannot serve a
|
|
139
|
+
* duplex, and `ready` rejects. `host` is anything with `accept(socket, options)`: `createMemoryHost()`, `createWshServer()`.
|
|
140
|
+
*
|
|
141
|
+
* @param {{ accept(socket: object, options?: object): Promise<{ close(): void }> }} host
|
|
142
|
+
* @param {object} options as `createDuplexSocket` (`send`, `close`, `maxMessageBytes`, `maxBufferedBytes`), and
|
|
143
|
+
* @param {boolean} [options.allowUnsealed=false] serve a client that does not seal: nothing a hop does is then caught. Refused by default.
|
|
144
|
+
* @param {object} [options.remote] what the host knows of the far side (`{ address }`, for its rate limiting of password failures)
|
|
145
|
+
* @returns {{ receive(data: Uint8Array | ArrayBuffer): void, end(reason?: string): void, ready: Promise<{ close(): void }>, close(): void }}
|
|
146
|
+
*/
|
|
147
|
+
export function serveWshOverDuplex(host, { allowUnsealed = false, remote, ...duplexOptions } = {}) {
|
|
148
|
+
if (typeof host?.accept !== 'function') throw new TypeError('serveWshOverDuplex: host must have accept(socket, options) (createMemoryHost(), createWshServer())');
|
|
149
|
+
if (typeof allowUnsealed !== 'boolean') throw new TypeError('serveWshOverDuplex: allowUnsealed must be true or false');
|
|
150
|
+
const link = createDuplexSocket(duplexOptions);
|
|
151
|
+
const ready = Promise.resolve().then(() => host.accept(link.socket, {
|
|
152
|
+
dataStreams: false,
|
|
153
|
+
...(allowUnsealed ? {} : { sealSession: 'require' }),
|
|
154
|
+
...(remote ? { remote } : {}),
|
|
155
|
+
})).catch((e) => { link.socket.close(1011, 'this host cannot serve this duplex'); throw e; });
|
|
156
|
+
ready.catch(() => {});
|
|
157
|
+
return {
|
|
158
|
+
receive: link.receive,
|
|
159
|
+
end: link.end,
|
|
160
|
+
ready,
|
|
161
|
+
close() { link.socket.close(1000, 'closed'); },
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Connect a wsh client over a duplex: the login is a key login, the session is SEALED, the login is bound to the host's key, and the host's key
|
|
167
|
+
* must be named: a hop on the duplex that answers as a host of its own would otherwise be trusted on first use. Name it with `expectHostKey` (the
|
|
168
|
+
* hex fingerprint; over a mesh it is the peer's pod id, `podIdToFingerprint(peer)`), or `knownHosts`, or say `trustOnFirstUse: true`.
|
|
169
|
+
*
|
|
170
|
+
* @param {object} duplex as `createDuplexSocket` (`send`, `close`, `maxMessageBytes`, `maxBufferedBytes`)
|
|
171
|
+
* @param {object} credentials `{ username, keyPair | signer, expectHostKey | knownHosts | trustOnFirstUse, timeout, allowUnsealed }` and the other options of
|
|
172
|
+
* `WshClient.connect`; `allowUnsealed: true` (and `sealSession`, `requireChannelBinding`) set the guarantees down, out loud
|
|
173
|
+
* @returns {{ receive(data: Uint8Array | ArrayBuffer): void, end(reason?: string): void, client: WshClient, connected: Promise<WshClient>, close(): Promise<void> }}
|
|
174
|
+
*/
|
|
175
|
+
export function connectWshOverDuplex(duplex, { allowUnsealed = false, ...credentials } = {}) {
|
|
176
|
+
if (typeof allowUnsealed !== 'boolean') throw new TypeError('connectWshOverDuplex: allowUnsealed must be true or false');
|
|
177
|
+
if (credentials.password !== undefined && !allowUnsealed) throw new TypeError('connectWshOverDuplex: a password login cannot be sealed (a hop would read it): use a key, or say allowUnsealed: true');
|
|
178
|
+
if (credentials.expectHostKey === undefined && credentials.knownHosts === undefined && credentials.trustOnFirstUse !== true && credentials.onHostKey === undefined) {
|
|
179
|
+
throw new TypeError('connectWshOverDuplex: name the host key you expect (expectHostKey: its hex fingerprint, over a mesh the peer\'s pod id converted with podIdToFingerprint), or knownHosts, or say trustOnFirstUse: true (a hop on the duplex could answer as the host)');
|
|
180
|
+
}
|
|
181
|
+
const link = createDuplexSocket(duplex);
|
|
182
|
+
let used = false;
|
|
183
|
+
// One duplex serves one connection: the constructor the transport calls hands back the socket made for it, once.
|
|
184
|
+
function LinkSocket() {
|
|
185
|
+
if (used) throw new Error('this duplex carries one connection and it is in use');
|
|
186
|
+
used = true;
|
|
187
|
+
return link.socket;
|
|
188
|
+
}
|
|
189
|
+
const client = new WshClient({
|
|
190
|
+
transportFactories: {
|
|
191
|
+
ws: () => new WebSocketTransport({ WebSocket: LinkSocket }),
|
|
192
|
+
wt: () => { throw new Error('connectWshOverDuplex: a duplex is not WebTransport'); },
|
|
193
|
+
},
|
|
194
|
+
});
|
|
195
|
+
const connected = client.connect('ws://duplex.invalid/', {
|
|
196
|
+
transport: 'ws',
|
|
197
|
+
...(allowUnsealed ? {} : { sealSession: true, requireChannelBinding: ['host'] }),
|
|
198
|
+
...credentials,
|
|
199
|
+
}).then(() => client);
|
|
200
|
+
connected.catch(() => {});
|
|
201
|
+
return {
|
|
202
|
+
receive: link.receive,
|
|
203
|
+
end: link.end,
|
|
204
|
+
client,
|
|
205
|
+
connected,
|
|
206
|
+
close: () => client.disconnect(),
|
|
207
|
+
};
|
|
208
|
+
}
|
package/src/key-options.mjs
CHANGED
|
@@ -347,6 +347,9 @@ function capabilityRefusal(p, req) {
|
|
|
347
347
|
else if (req.channel === 'file') { const need_ = req.direction === 'download' ? 'fs:read' : 'fs:write'; r = need(need_, has(need_)); }
|
|
348
348
|
else if (req.channel === 'rpc') {
|
|
349
349
|
const proto = req.protocol;
|
|
350
|
+
// A handler that says it authorizes for itself (`authorizesItself`: it asks the host's own `permits` for every call) is opened by any key the
|
|
351
|
+
// options let in: the list does not have to name its protocol. The options and the expiry were checked before this; only the `rpc:`/`mcp:` entry is deferred.
|
|
352
|
+
if (req.authorizesItself === true) return req.target === undefined || req.target === null ? null : target();
|
|
350
353
|
// The file rpc has read and write methods on one channel: a key without both is refused it (a client falls back to
|
|
351
354
|
// FileOp and the file channels, which are checked per operation).
|
|
352
355
|
if (proto === 'wsh-fs') r = need('fs:read', has('fs:read')) ?? need('fs:write', has('fs:write'));
|
|
@@ -164,7 +164,7 @@ export function createConnectionFactory(cfg) {
|
|
|
164
164
|
* `dataStreams: false` means there are no client-opened streams to bind, so exec output rides SessionData.
|
|
165
165
|
* `e2e` overrides `cfg.e2e` for this connection.
|
|
166
166
|
*/
|
|
167
|
-
return function attach({ send: sendBytes, sendMessage = null, remote = {}, authenticated = null, dataStreams = true, closeTransport = null, e2e: e2eOverride, channelBinding = null, datagrams = null }) {
|
|
167
|
+
return function attach({ send: sendBytes, sendMessage = null, remote = {}, authenticated = null, dataStreams = true, closeTransport = null, e2e: e2eOverride, channelBinding = null, datagrams = null, sealSession: sealOverride }) {
|
|
168
168
|
const cid = ++counter;
|
|
169
169
|
const log = (m) => cfg.log(`[conn ${cid}] ${m}`);
|
|
170
170
|
const state = {
|
|
@@ -260,8 +260,13 @@ export function createConnectionFactory(cfg) {
|
|
|
260
260
|
|
|
261
261
|
// A sealed session (#155): after login, a signed KeyExchange for this connection's session id seals everything
|
|
262
262
|
// that follows (control messages, gateway and endpoint data included) as EncryptedFrames on channel 0.
|
|
263
|
-
|
|
264
|
-
|
|
263
|
+
// `sealSession: 'require'` in the options of this connection may only STRENGTHEN the host's setting (a transport that cannot vouch for itself,
|
|
264
|
+
// a duplex someone else carries, asks for it); a host that cannot seal (no host key, or client-opened data streams) then cannot serve it at all.
|
|
265
|
+
if (sealOverride !== undefined && sealOverride !== 'require') throw new TypeError("attach: sealSession can only be 'require' for one connection");
|
|
266
|
+
if (sealOverride === 'require' && (!cfg.hostKey || dataStreams)) throw new Error('this connection must be sealed, and this host cannot seal it (it needs a host key and dataStreams: false)');
|
|
267
|
+
const sealMode = sealOverride === 'require' ? 'require' : cfg.sealSession;
|
|
268
|
+
const sealOn = !!sealMode && !!cfg.hostKey && !dataStreams;
|
|
269
|
+
const sealRequired = sealOn && sealMode === 'require';
|
|
265
270
|
/** @type {{ bridge: SealedBridge | null, responder: E2EResponder | null }} */
|
|
266
271
|
const sealed = { bridge: null, responder: null };
|
|
267
272
|
|
|
@@ -520,11 +525,11 @@ export function createConnectionFactory(cfg) {
|
|
|
520
525
|
} else {
|
|
521
526
|
return refuse(`unsupported auth method ${JSON.stringify(method)}`, 'bad-request', { username: user });
|
|
522
527
|
}
|
|
523
|
-
if (
|
|
528
|
+
if (sealRequired && method !== 'pubkey') return refuse('this host requires a sealed session, which needs a key login', 'not-sealed', { username: user });
|
|
524
529
|
state.username = user;
|
|
525
530
|
state.method = method;
|
|
526
531
|
gateway?.setPeerFeatures(m.features);
|
|
527
|
-
const features = hostFeatures(cfg, { dataStreams });
|
|
532
|
+
const features = hostFeatures(sealMode === cfg.sealSession ? cfg : { ...cfg, sealSession: sealMode }, { dataStreams });
|
|
528
533
|
// UDP over datagrams only where this transport has them and the gateway serves (and allows) UDP.
|
|
529
534
|
if (datagrams && cfg.gateway?.tcp && cfg.gateway.udp?.datagrams) features.push(GATEWAY_DATAGRAM_FEATURE);
|
|
530
535
|
let hostFingerprint;
|
|
@@ -864,7 +869,7 @@ export function createConnectionFactory(cfg) {
|
|
|
864
869
|
if (requireTarget) return send(openFail({ reason: 'a target is required' }));
|
|
865
870
|
{
|
|
866
871
|
const protocol = typeof m.command === 'string' ? m.command : '';
|
|
867
|
-
const refusal = keyRefusal({ kind: 'open', channel: 'rpc', protocol, scoped: cfg.rpc?.protocols.get(protocol)?.capabilityScoped === true });
|
|
872
|
+
const refusal = keyRefusal({ kind: 'open', channel: 'rpc', protocol, scoped: cfg.rpc?.protocols.get(protocol)?.capabilityScoped === true, authorizesItself: cfg.rpc?.protocols.get(protocol)?.authorizesItself === true });
|
|
868
873
|
if (refusal) return send(openFail({ reason: refusal.reason }));
|
|
869
874
|
}
|
|
870
875
|
return openRpc(m);
|
package/src/server/socket.mjs
CHANGED
|
@@ -35,10 +35,12 @@ async function toBytes(data) {
|
|
|
35
35
|
* @param {{ remote?: { address?: string, headers?: object }, dataStreams?: boolean }} [options] - what the host knows about the peer
|
|
36
36
|
* (`address` keys the password-failure throttle; the default key is shared by every socket without one).
|
|
37
37
|
* `dataStreams: false` serves this connection without client-opened data streams (exec output rides SessionData), for a
|
|
38
|
-
* client that cannot open them (the Rust client over WebSocket, #132).
|
|
38
|
+
* client that cannot open them (the Rust client over WebSocket, #132). `sealSession: 'require'` makes THIS connection serve nothing
|
|
39
|
+
* until it is sealed, whatever the host's own setting (it can only strengthen it; a host with no host key, or with data streams, refuses to
|
|
40
|
+
* attach it: `ready` rejects). It is what `@johnhenry/wsh/duplex` asks of a transport it cannot vouch for.
|
|
39
41
|
* @returns {Promise<{ close(): void }>} resolves once the connection is attached; `close()` drops it
|
|
40
42
|
*/
|
|
41
|
-
export function bindSocket(socket, ready, { remote = {}, dataStreams } = {}) {
|
|
43
|
+
export function bindSocket(socket, ready, { remote = {}, dataStreams, sealSession } = {}) {
|
|
42
44
|
if (!socket || typeof socket.send !== 'function' || typeof socket.close !== 'function') {
|
|
43
45
|
throw new TypeError('accept: socket must be a WebSocket-like duplex with send() and close()');
|
|
44
46
|
}
|
|
@@ -74,6 +76,7 @@ export function bindSocket(socket, ready, { remote = {}, dataStreams } = {}) {
|
|
|
74
76
|
send: write,
|
|
75
77
|
remote: { address: remote.address, headers: remote.headers ?? {} },
|
|
76
78
|
dataStreams,
|
|
79
|
+
...(sealSession !== undefined ? { sealSession } : {}),
|
|
77
80
|
closeTransport: () => { try { socket.close(1000); } catch { /* already closed */ } },
|
|
78
81
|
});
|
|
79
82
|
});
|