@johnhenry/wsh 0.39.0 → 0.40.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 +86 -6
- package/package.json +1 -1
- package/src/host.d.ts +75 -0
- package/src/host.mjs +1 -0
- package/src/memory-host.d.ts +8 -1
- package/src/memory-host.mjs +10 -2
- package/src/messages.gen.mjs +41 -0
- package/src/reverse-host.mjs +8 -3
- package/src/server/connection.mjs +9 -0
- package/src/server/index.d.ts +7 -0
- package/src/server/index.mjs +7 -0
- package/src/shares.mjs +425 -0
package/README.md
CHANGED
|
@@ -66,7 +66,7 @@ Or via CDN:
|
|
|
66
66
|
- **MCP bridge** -- discover and invoke remote MCP tools through the control channel
|
|
67
67
|
- **Session recording** -- own JSON schema (asciicast-v2-shaped, not a playable asciicast file -- see note below) recording and playback with seek/pause/resume
|
|
68
68
|
- **Key management** -- IndexedDB storage with OPFS encrypted backup (PBKDF2 + AES-256-GCM)
|
|
69
|
-
- **
|
|
69
|
+
- **108 message types** -- handshake, channel, gateway, guest sharing, compression negotiation, copilot, policy, authorized-key management, and more
|
|
70
70
|
|
|
71
71
|
> **Session recording is asciicast-v2-shaped, but not an asciicast file.**
|
|
72
72
|
> The JS `SessionRecorder.toJSON()` export borrows asciicast v2's vocabulary --
|
|
@@ -904,8 +904,10 @@ host whichever relay carried it and a different host behind that name is refused
|
|
|
904
904
|
command is sent. A plain URL target (`wsh alice@wss://relay/r/<id> ...`) also dials but is recorded under the URL's
|
|
905
905
|
authority, which is the relay's, so prefer `--via`. `--via` works with `wsh [user@]host`, `connect`, `scp`, `ls`, `sftp`
|
|
906
906
|
and `copy-id`; it is an error elsewhere, and cannot be combined with a URL target. A pipe relay is WebSocket only: no
|
|
907
|
-
fallback, and `--transport` does not apply. The rendezvous id is not written to `last_session.json
|
|
908
|
-
|
|
907
|
+
fallback, and `--transport` does not apply. The rendezvous id is not written to `last_session.json`, and the CLI never
|
|
908
|
+
prints it: errors and `--verbose` logs show the relay's host and the id shortened to its first characters
|
|
909
|
+
(`wss://relay/r/AbCd...`). The Rust client verifies the host-key proof and binds the login to it, as on a direct
|
|
910
|
+
connection; what it does not do (seal the pipe-relayed session) is listed under the Security model. The host side
|
|
909
911
|
is any process that can open a WebSocket to `pipeUrl(..., 'host')` and hand it to `accept`.
|
|
910
912
|
|
|
911
913
|
### Sessions: attach / resume / detach
|
|
@@ -1458,7 +1460,7 @@ so options the platform gains later need no change here.
|
|
|
1458
1460
|
|
|
1459
1461
|
| Export | Description |
|
|
1460
1462
|
|--------|-------------|
|
|
1461
|
-
| `MSG` |
|
|
1463
|
+
| `MSG` | 108 message type constants (hex opcodes) |
|
|
1462
1464
|
| `CHANNEL_KIND` | Channel types: `pty`, `exec`, `meta`, `file`, `tcp`, `udp`, `job` |
|
|
1463
1465
|
| `AUTH_METHOD` | Auth methods: `pubkey`, `password` |
|
|
1464
1466
|
| `cborEncode` / `cborDecode` | CBOR codec (maps, arrays, strings, ints, bytes, bools, null, floats) |
|
|
@@ -1482,7 +1484,7 @@ instead of dragging its own toolchain and CI job into an unrelated
|
|
|
1482
1484
|
browser-app repo. It was previously deleted from clawser by accident
|
|
1483
1485
|
(2026-03-14) and restored (2026-07-05) before this move.
|
|
1484
1486
|
|
|
1485
|
-
Four crates, workspace-versioned (currently `0.
|
|
1487
|
+
Four crates, workspace-versioned (currently `0.11.0`):
|
|
1486
1488
|
|
|
1487
1489
|
| Crate | Kind | Description |
|
|
1488
1490
|
|-------|------|--------------|
|
|
@@ -1537,6 +1539,69 @@ cannot do what a forward needs says so (`this host does not offer unix-socket fo
|
|
|
1537
1539
|
the gateway policy`); a malformed spec exits with status 2 before anything is dialled. Up to 128 forwarded connections are
|
|
1538
1540
|
open at once. `-L`/`-R`/`-N` apply to `wsh [user@]host [command...]` and `wsh connect` only.
|
|
1539
1541
|
|
|
1542
|
+
### Sharing a directory with the host: `wsh --share` (#159)
|
|
1543
|
+
|
|
1544
|
+
A host with no disk of its own (a browser tab) sometimes needs files that live on the OPERATOR's machine: `docker run -v
|
|
1545
|
+
$PWD:/app` through `wsh -L /tmp/docker.sock:endpoint=docker` is the case that asked for this. `--share` offers a directory of
|
|
1546
|
+
THIS machine to the host for the life of the session; the CLI serves file operations on it, and nothing else.
|
|
1547
|
+
|
|
1548
|
+
```bash
|
|
1549
|
+
wsh -N --share src=/home/me/project --share out=/home/me/build:rw --via wss://relay/r/<id> alice@tab.example
|
|
1550
|
+
wsh -N -L /tmp/docker.sock:endpoint=docker --share app=$PWD alice@tab.example # one connection, both
|
|
1551
|
+
```
|
|
1552
|
+
|
|
1553
|
+
`--share NAME=/abs/dir[:ro|:rw]`, repeatable (at most 16; `NAME`: letters, digits, `.`, `_`, `-`, at most 64). **Read-only unless
|
|
1554
|
+
`:rw`.** The path must be absolute and an existing directory, or the CLI exits with status 2 before dialling. It says once, on
|
|
1555
|
+
stderr, what it shares and how (`wsh: sharing "src" = /home/me/project (read-only)`). It works with `-N`, `-L`, `--via` and a
|
|
1556
|
+
command, applies to `wsh [user@]host [command...]` and `wsh connect` only (`scp`, `ls`, `sftp`, `copy-id` refuse it), and fails
|
|
1557
|
+
with a sentence when the host does not say it can use shares: a share that silently does not exist is worse than none. Unix only.
|
|
1558
|
+
|
|
1559
|
+
**What the host can do.** Stat and lstat, readdir (every entry WITH its attributes, in pages), readlink, open and read (ranges; a
|
|
1560
|
+
small file's content rides the open, so reading it is one message), write, create, mkdir, rename, unlink, rmdir, setattr (mode,
|
|
1561
|
+
times, truncate) and close, each a bounded `ShareRequest` the host sends and the CLI answers with an errno-like code. At most 16
|
|
1562
|
+
requests are in flight (the rest are refused `EAGAIN` at once), no data in a request or reply exceeds 256 KiB, a stalled host
|
|
1563
|
+
cannot make the CLI queue more than a few replies, at most 64 files are open at once, and the session's total read-plus-write rate
|
|
1564
|
+
is capped (256 MiB/s after a 32 MiB burst). The host's own API is [`onShare(name, fs, who)`](#serving-the-operators-files-from-a-host-onshare).
|
|
1565
|
+
|
|
1566
|
+
**What it will not do, whatever the host sends** (each rule has a test that fails when it is broken; see the Security model):
|
|
1567
|
+
the share exists only because it was named on the command line (nothing a host sends adds or widens one); every path is resolved
|
|
1568
|
+
component by component from a directory descriptor opened at start-up, with `O_NOFOLLOW` on each step, so a symlink in the middle
|
|
1569
|
+
of a path is `ELOOP` and one swapped in between a check and its use is never followed; `..` is refused; a symlink is only ever
|
|
1570
|
+
seen as a symlink; sockets, devices and FIFOs do not exist (and a FIFO cannot hang the CLI); names that are not valid UTF-8 are
|
|
1571
|
+
skipped; another file system mounted inside the tree is not entered; the root's device and inode are re-checked before every
|
|
1572
|
+
request, so a root that was moved or replaced answers `ESTALE`; a file with more than one hard link is never opened for writing,
|
|
1573
|
+
truncated or chmod'ed; a created file or directory gets the requested mode limited to `0755`'s bits (never setuid, never
|
|
1574
|
+
group- or other-writable), created with `O_EXCL` so a link planted in its place is never written through; there is no operation
|
|
1575
|
+
that makes a link. Case-insensitive file systems (the macOS default) cannot be used to reach outside: confinement is by
|
|
1576
|
+
descriptor, never by comparing names, so `LINK` is the same symlink as `link` and is refused like it.
|
|
1577
|
+
|
|
1578
|
+
**Not done:** change notification (the host re-reads; nothing is cached on the CLI's side), Windows (`--share` is unix-only), a
|
|
1579
|
+
Rust host that uses shares (the JS host does), and sharing over `wsh reverse-connect` (a direct or pipe-relayed session only).
|
|
1580
|
+
|
|
1581
|
+
#### Serving the operator's files from a host: `onShare`
|
|
1582
|
+
|
|
1583
|
+
```js
|
|
1584
|
+
const host = createMemoryHost({
|
|
1585
|
+
auth, hostKey: true, dataStreams: false, // a page host, reached through a pipe relay
|
|
1586
|
+
onShare: async (name, fs, who) => { // once per share the operator's CLI offers
|
|
1587
|
+
if (name !== 'app') return;
|
|
1588
|
+
const entries = await fs.readdir('/'); // [{ name, type, size, mode, mtimeMs, ... }] -- attributes included
|
|
1589
|
+
const pkg = JSON.parse(new TextDecoder().decode(await fs.readFile('/package.json')));
|
|
1590
|
+
if (fs.writable) await fs.writeFile('/out/built.txt', new TextEncoder().encode('done'));
|
|
1591
|
+
},
|
|
1592
|
+
});
|
|
1593
|
+
```
|
|
1594
|
+
|
|
1595
|
+
`createMemoryHost`, `createWshServer` and `createReverseHost` take `onShare`; listing it makes the host state the feature
|
|
1596
|
+
`shares`, and a host without it never hears an offer. `fs` is an object of async operations (`stat`, `lstat`, `readlink`,
|
|
1597
|
+
`readdir`, `open` / `create` returning a file with `read(offset, length)` / `write` / `setattr` / `close`, `readFile`,
|
|
1598
|
+
`writeFile`, `mkdir`, `rename`, `unlink`, `rmdir`, `setattr`, `truncate`, `chmod`, `utimes`), `fs.writable`, `fs.signal`
|
|
1599
|
+
(aborted when the operator goes), `fs.stats` (requests, replies, bytes: the evidence that batching works), and the
|
|
1600
|
+
`operate` / `readWhole` / `writeWhole` / `writeAt` shape of an injected [`fs` backend](#in-memory-host-johnhenrywshmemory), so a share can be served on.
|
|
1601
|
+
Errors are `ShareError`s with `.code` (`ENOENT`, `EROFS`, `ELOOP`, `EPERM`, `EEXIST`, ...). The host keeps to the window the
|
|
1602
|
+
CLI offered, gives every request a deadline (30 s), treats a reply that is too big or the wrong shape as `EIO`, and rejects every
|
|
1603
|
+
pending call when the connection ends. Browser-safe: `src/shares.mjs` imports nothing from `node:*`.
|
|
1604
|
+
|
|
1540
1605
|
### Capability matrix: JS SDK vs Rust CLI/client
|
|
1541
1606
|
|
|
1542
1607
|
Two implementations of one protocol will always have *some* asymmetry --
|
|
@@ -1567,8 +1632,9 @@ than left to be found.
|
|
|
1567
1632
|
| Gateway destination policy by resolved address | `@johnhenry/wsh/server` `gateway`: resolved address checked, `allowPrivate` | fixed in the Rust release after `rust-v0.6.0`: a loopback/private/link-local/ULA/CGNAT/unspecified/multicast address is refused after resolution unless a rule names it, and the server connects to the address it checked | **Same rule on both sides** (a Rust server released before that still has the name-only check) |
|
|
1568
1633
|
| Operator proof to the peer, sealed bridge, signed initiator half (#117) | `reverseConnect(.., { sealed, requirePeerProof })`; host `createReverseHost({ requireOperatorProof })`; relay lists `operator-proof` | **Operator proof: yes.** The Rust relay lists `operator-proof` and carries `ReverseChallenge`/`ReverseProof`/`ReverseConnect.features`; `wsh reverse-connect` answers a challenge (`--operator-proof` / `--no-operator-proof`; by default only for a peer that registered the `operator-proof` capability, because a released Rust host cannot decode the field); `wsh reverse` / `wsh agent run` challenge, verify BEFORE accepting, and take `--require-operator-proof` and `--allow-operator`. **Sealed bridge and both signed `KeyExchange` halves: yes** (`wsh reverse-connect --sealed`; a host with an identity states `e2e` / `e2e-sign` / `e2e-sealed` in its `ReverseAccept` once it has proven the operator). The exchange is byte-identical to JS (transcripts compared against vectors printed by the JS code), hybrid X25519+ML-KEM-768 negotiated exactly as JS does, X25519 when the peer lists no ML-KEM key. A host started with `--require-operator-proof` REQUIRES the sealed bridge (the JS rule): until the key exists it hears and sends nothing but the key exchange, and drops a bridge that has not sealed in 10 s; an operator that does not seal gets no answer to its plain messages. Every message that would cross the relay travels as an `EncryptedFrame` on channel 0; a plain message (wrapped or not) is dropped; **a frame that does not open (tampered, replayed, reordered) closes the bridge** (stricter than the JS host, which drops the frame and ignores the rest). Not covered: a direct or pipe-relayed connection, and `GatewayData` outside a reverse bridge (#155) | **Wire-unified, negotiated** (`ReverseConnect.features`, `operator-proof`, `e2e-sealed`); both implementations seal a reverse bridge |
|
|
1569
1634
|
| Channel binding of the login signature (#119) | `requireChannelBinding` (client and server); kinds `host`, `cert-hash`, `tls-exporter` | Kind `host`: the client binds to the proven host key (`--require-channel-binding`, and it honours `channel-binding-required`), and `wsh-server` offers it and can require it (`[server] require_channel_binding`, needs `host_key`). `cert-hash` and `tls-exporter`: not in Rust (the Rust WebTransport client has no certificate-hash pinning; `ConnectConfig.cert_hash` binds it if a caller supplies one) | **Wire-unified, negotiated** (`channel-binding:<kind>` features); verified against the spec's test vectors |
|
|
1635
|
+
| Pipe relay (#118) | `@johnhenry/wsh/pipe-relay` | operator side only (#145): `wsh --via wss://relay/r/<id> user@host command...` (also `connect`, `scp`, `ls`, `sftp`, `copy-id`), or the URL as the target. The host side of a pipe is not implemented in Rust. As on a direct connection the Rust client verifies the host-key proof (`host-key` / `host-key-sig` over its own nonce) before sending a credential, pins only a proven key, and binds the login to it (channel binding `host`; `test/rust/wsh-cli-identity.test.mjs`); the pipe-relayed session itself is not sealed (see Security model). `wsh -N -L` exits non-zero when the host drops the session (#156), and the error lines show the relay and a shortened id, never the whole rendezvous id | **Deliberately a relay without wsh parsing** -- nothing to unify on the wire. `--via` keeps `user@host` as the identity: its key is recorded in `known_hosts` under `host:port` (what a direct connection uses), never under the relay's address; a URL target is recorded under the URL's own authority, i.e. the relay's. The URL is not saved to `last_session.json` (the id is a capability) |
|
|
1636
|
+
| Operator-side shared folders (`--share`, #159) | host side: `onShare(name, fs, who)` on `createMemoryHost` / `createWshServer` / `createReverseHost` (the host *uses* the operator's directories; `fs` is an object of async file operations, also shaped like an `fs` backend). The JS client does not offer shares | CLI side: `wsh --share NAME=/abs/dir[:ro\|:rw]` offers them (`wsh_client::share`, `wsh-cli`'s `sharefs`: descriptor-relative, never follows a link, see [Sharing a directory](#sharing-a-directory-with-the-host-wsh---share-159)); unix only. **A Rust host that uses shares: not built** (`wsh-server` does not state `shares`) | **Wire-unified, negotiated**: the host states the feature `shares`; the client sends one `ShareOffer` after login (opcodes `0xa8` `ShareOffer`, `0xa9` `ShareRequest`, host to client, `0xaa` `ShareReply`). No change notification, no sharing over `reverse-connect` |
|
|
1570
1637
|
| Sealed session: any authenticated connection incl. gateway/endpoint data (#155) | host `sealSession: 'offer' \| 'require'` (stage b); the JS client does not seal yet | `wsh --sealed ...` (or automatic against `e2e-session-required`) seals a direct or pipe-relayed session; `wsh-server` does not offer it yet | **Wire-unified, negotiated** (`e2e-session`, `e2e-session-required`, `KeyExchange` for the connection's session id, `EncryptedFrame` channel 0) |
|
|
1571
|
-
| Pipe relay (#118) | `@johnhenry/wsh/pipe-relay` | operator side only (#145): `wsh --via wss://relay/r/<id> user@host command...` (also `connect`, `scp`, `ls`, `sftp`, `copy-id`), or the URL as the target. The host side of a pipe is not implemented in Rust, and the Rust client does not yet verify the host-key proof or bind the login to the host (see Security model) | **Deliberately a relay without wsh parsing** -- nothing to unify on the wire. `--via` keeps `user@host` as the identity: its key is recorded in `known_hosts` under `host:port` (what a direct connection uses), never under the relay's address; a URL target is recorded under the URL's own authority, i.e. the relay's. The URL is not saved to `last_session.json` (the id is a capability) |
|
|
1572
1638
|
| `AuthOk.ttl` enforced, `token` opaque (#125) | `connectionTtlMs`; `client.authTtl` | `wsh-server` sends `ttl: 0` (no lifetime promised; `session_ttl` is the lifetime of a *detached* session) and an HMAC token that nothing accepts back | **Wire-compatible**: both fields are still sent (released peers require them). **Changed in the Rust server after `rust-v0.6.0`**: it used to send `session_ttl` (86400), which nothing enforced. The Rust client ignores `ttl` |
|
|
1573
1639
|
| `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 |
|
|
1574
1640
|
| 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 |
|
|
@@ -1840,6 +1906,20 @@ What this does **not** protect against:
|
|
|
1840
1906
|
`bind_addr` of `0.0.0.0` (the CLI warns) hands the forward to the network, and a local unix socket is `0600` only against
|
|
1841
1907
|
other users, not against your own processes. A forwarded connection is as private as the wsh connection under it (a pipe
|
|
1842
1908
|
relay sees it unless the legs are TLS). The Rust host binds a created socket inside a private `0700` directory and links it into place, so it is never visible with a looser mode and the process umask is not touched.
|
|
1909
|
+
- **`wsh --share` hands a host a directory of YOUR machine, and the host is not trusted (#159).** What the host can do is
|
|
1910
|
+
exactly what the command line named: list and read everything under the directory (a read-only share still exposes every
|
|
1911
|
+
file in it, secrets included: share a directory made for the purpose, not `$HOME`), and with `:rw` change and delete all of it
|
|
1912
|
+
and fill the disk (the CLI bounds a file at 1 TiB and the read-plus-write rate, not the disk). What it cannot do is leave the
|
|
1913
|
+
directory: paths are resolved by descriptor with `O_NOFOLLOW` on every component (a link swapped in after a check is not
|
|
1914
|
+
followed), `..` is refused, a file with other hard links is never written, special files do not exist, a root that was
|
|
1915
|
+
replaced is refused (`ESTALE`), and nothing the host sends adds or widens a share. **Not covered:** a link that already
|
|
1916
|
+
exists inside the tree and points outside is simply not followed (so it appears broken to the host, but its name and target
|
|
1917
|
+
are listed); a local user who can write inside the shared tree is outside this model (they can race a rename, though never
|
|
1918
|
+
out of the root); the file *names and sizes* of everything under the share are visible to the host and to a relay that is not
|
|
1919
|
+
sealed (a share travels inside the session: a pipe relay sees it unless the legs are TLS and it is trusted, or the session
|
|
1920
|
+
is sealed, #155); a host that is itself malicious software on a page can read what the page's other code can ask for. The
|
|
1921
|
+
JS side treats the CLI as untrusted too (window, size, shape and deadline of every reply are checked), but an embedder
|
|
1922
|
+
that mounts `fs` is responsible for what it does with the files.
|
|
1843
1923
|
- **Rust `wsh-server`'s `AuthOk.ttl` is 0 and its `token` is opaque** (as the
|
|
1844
1924
|
JS host's, above): nothing is promised or enforced at connection level; do not
|
|
1845
1925
|
treat the token as a credential.
|
package/package.json
CHANGED
package/src/host.d.ts
CHANGED
|
@@ -82,10 +82,15 @@ export interface WshConnectionConfig extends Partial<WshResolvedBackends> {
|
|
|
82
82
|
e2e?: { signKey: CryptoKey | null; hybrid?: boolean } | null;
|
|
83
83
|
/** How long exec output waits for the client-opened data stream (default 3000). */
|
|
84
84
|
bindTimeoutMs?: number;
|
|
85
|
+
/** Folders the operator offers (`wsh --share`, #159): called once per share; listing it makes the host state `shares`. */
|
|
86
|
+
onShare?: WshOnShare;
|
|
85
87
|
log?: (line: string) => void;
|
|
86
88
|
[key: string]: unknown;
|
|
87
89
|
}
|
|
88
90
|
|
|
91
|
+
/** The `ServerHello` feature of a host that can use shares (#159). */
|
|
92
|
+
export const SHARES_FEATURE: 'shares';
|
|
93
|
+
|
|
89
94
|
/** One connection over a byte pipe. */
|
|
90
95
|
export interface WshConnectionPipe {
|
|
91
96
|
/** Send these bytes to the peer. */
|
|
@@ -144,3 +149,73 @@ export function bindSocket(
|
|
|
144
149
|
ready: Promise<WshConnectionAttach>,
|
|
145
150
|
options?: WshAcceptOptions,
|
|
146
151
|
): Promise<{ close(): void }>;
|
|
152
|
+
|
|
153
|
+
/** A file's attributes on the operator's machine (`wsh --share`, #159). Times are milliseconds since the epoch. */
|
|
154
|
+
export interface WshShareAttr {
|
|
155
|
+
type: 'file' | 'directory' | 'symlink';
|
|
156
|
+
size: number;
|
|
157
|
+
/** Permission bits only (`0o777` at most). */
|
|
158
|
+
mode: number;
|
|
159
|
+
mtimeMs: number;
|
|
160
|
+
atimeMs: number;
|
|
161
|
+
ctimeMs: number;
|
|
162
|
+
nlink: number;
|
|
163
|
+
ino: number;
|
|
164
|
+
isFile(): boolean;
|
|
165
|
+
isDirectory(): boolean;
|
|
166
|
+
isSymbolicLink(): boolean;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** An entry of {@link WshShareFs.readdir}: attributes included, so listing a directory needs no `stat` per entry. */
|
|
170
|
+
export interface WshShareEntry extends WshShareAttr { name: string; /** A symlink's target. A link is never followed. */ target?: string }
|
|
171
|
+
|
|
172
|
+
/** An open file of a share. */
|
|
173
|
+
export interface WshShareFile {
|
|
174
|
+
readonly attr: WshShareAttr;
|
|
175
|
+
read(offset: number, length: number): Promise<{ data: Uint8Array; eof: boolean }>;
|
|
176
|
+
write(offset: number, data: Uint8Array): Promise<number>;
|
|
177
|
+
setattr(changes: WshShareChanges): Promise<WshShareAttr>;
|
|
178
|
+
truncate(size: number): Promise<WshShareAttr>;
|
|
179
|
+
close(): Promise<void>;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export interface WshShareChanges { mode?: number; atimeMs?: number; mtimeMs?: number; size?: number }
|
|
183
|
+
|
|
184
|
+
/** An errno-like failure answered by the operator's client (`code`: `ENOENT`, `EROFS`, `EEXIST`, `ELOOP`, `EPERM`, ...). */
|
|
185
|
+
export class ShareError extends Error { readonly errno: string; readonly code: string }
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* One folder the operator shares with this host (`wsh --share NAME=/abs/dir[:ro|:rw]`, #159): async file operations
|
|
189
|
+
* answered by the operator's client, which confines every path to the folder. Paths are relative to the folder root.
|
|
190
|
+
* It also has the shape of a {@link WshFileBackend} (`operate`, `readWhole`, `writeWhole`, `writeAt`), so it can be served on.
|
|
191
|
+
*/
|
|
192
|
+
export interface WshShareFs extends WshFileBackend {
|
|
193
|
+
readonly name: string;
|
|
194
|
+
/** Whether the operator offered writes (`:rw`). A change on a read-only share fails with `EROFS`. */
|
|
195
|
+
readonly writable: boolean;
|
|
196
|
+
/** Aborted when the connection to the operator ends; every later call fails with `EIO`. */
|
|
197
|
+
readonly signal: AbortSignal;
|
|
198
|
+
/** Requests, replies, errors, bytes each way and timeouts on this connection so far. */
|
|
199
|
+
readonly stats: { requests: number; replies: number; errors: number; bytesDown: number; bytesUp: number; timeouts: number };
|
|
200
|
+
stat(path: string): Promise<WshShareAttr>;
|
|
201
|
+
lstat(path: string): Promise<WshShareAttr>;
|
|
202
|
+
readlink(path: string): Promise<string>;
|
|
203
|
+
/** The whole directory with attributes, sorted by name, in as few messages as the operator's page size allows. */
|
|
204
|
+
readdir(path: string): Promise<WshShareEntry[]>;
|
|
205
|
+
open(path: string, flags?: Array<'read' | 'write' | 'create' | 'excl' | 'trunc'>, options?: { mode?: number; inlineBytes?: number }): Promise<WshShareFile>;
|
|
206
|
+
create(path: string, options?: { mode?: number }): Promise<WshShareFile>;
|
|
207
|
+
/** A small file arrives with the open (one round trip). */
|
|
208
|
+
readFile(path: string, options?: { maxBytes?: number }): Promise<Uint8Array>;
|
|
209
|
+
writeFile(path: string, data: Uint8Array, options?: { mode?: number; truncate?: boolean }): Promise<number>;
|
|
210
|
+
mkdir(path: string, options?: { mode?: number }): Promise<WshShareAttr>;
|
|
211
|
+
unlink(path: string): Promise<void>;
|
|
212
|
+
rmdir(path: string): Promise<void>;
|
|
213
|
+
rename(from: string, to: string): Promise<void>;
|
|
214
|
+
setattr(path: string, changes: WshShareChanges): Promise<WshShareAttr>;
|
|
215
|
+
truncate(path: string, size: number): Promise<WshShareAttr>;
|
|
216
|
+
chmod(path: string, mode: number): Promise<WshShareAttr>;
|
|
217
|
+
utimes(path: string, atimeMs: number, mtimeMs: number): Promise<WshShareAttr>;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Called once per share the operator offers (#159). Mount `fs` where you like; `who` is the authenticated operator. */
|
|
221
|
+
export type WshOnShare = (name: string, fs: WshShareFs, who: { username: string | null; fingerprint: string | null }) => void | Promise<void>;
|
package/src/host.mjs
CHANGED
|
@@ -28,3 +28,4 @@ export { createConnectionFactory, hostFeatures, STREAM_ANNOUNCE } from './server
|
|
|
28
28
|
export { bindSocket } from './server/socket.mjs';
|
|
29
29
|
export { resolveBackends, resolveHostKey, normalizeFileBackend } from './host-backends.mjs';
|
|
30
30
|
export { buildAuthorizer, authMethods } from './server/auth.mjs';
|
|
31
|
+
export { ShareError, SHARES_FEATURE } from './shares.mjs';
|
package/src/memory-host.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
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
|
+
import type { WshFileBackend, WshHostKeyOption, WshOnShare } from './host.js';
|
|
4
4
|
import type {
|
|
5
5
|
WshServerAuthOptions, WshServerPrincipal, WshServerMcpOptions, WshExecRunner, WshServerOptions, WshServerPtyOptions, WshClientEnv,
|
|
6
6
|
WshAcceptableSocket, WshAcceptOptions, WshGatewayEndpointHandler as WshMemoryEndpointHandler,
|
|
@@ -75,6 +75,13 @@ export interface WshMemoryHostOptions {
|
|
|
75
75
|
* Needs `hostKey`; a client older than 0.36 cannot satisfy it.
|
|
76
76
|
*/
|
|
77
77
|
requireChannelBinding?: boolean | Array<'host'>;
|
|
78
|
+
/**
|
|
79
|
+
* Folders of the OPERATOR's machine (#159): `wsh --share NAME=/abs/dir[:ro|:rw]` offers them after login, and this is
|
|
80
|
+
* called once per share with an object of async file operations the page can mount (a host with no disk of its own
|
|
81
|
+
* can then serve `docker run -v $PWD:/app`). Listing it makes the host state the `shares` feature; a host without it
|
|
82
|
+
* never hears a share offer. See `WshShareFs`.
|
|
83
|
+
*/
|
|
84
|
+
onShare?: WshOnShare;
|
|
78
85
|
/** #155: seal the whole session end to end (needs `hostKey`; offered where `dataStreams` is false). `'require'` serves nothing unsealed. */
|
|
79
86
|
sealSession?: false | 'offer' | 'require';
|
|
80
87
|
onLog?: (line: string) => void;
|
package/src/memory-host.mjs
CHANGED
|
@@ -38,6 +38,7 @@ import { normalizeEndpointGateway, createEndpointGatewaySession } from './server
|
|
|
38
38
|
import { CHANNEL_BINDING_KINDS } from './channel-binding.mjs';
|
|
39
39
|
import { RPC_PROTOCOL_NAME_RE, RPC_DEFAULT_MAX_MESSAGE } from './rpc.mjs';
|
|
40
40
|
import { SessionRegistry, DEFAULT_RING_BYTES, DEFAULT_DETACH_TTL_MS, DEFAULT_MAX_DETACHED } from './session-registry.mjs';
|
|
41
|
+
import { validateOnShare } from './shares.mjs';
|
|
41
42
|
|
|
42
43
|
const CONNECTING = 0;
|
|
43
44
|
const OPEN = 1;
|
|
@@ -176,9 +177,16 @@ function createRegistry(sessions, log) {
|
|
|
176
177
|
* @param {boolean | string[]} [options.requireChannelBinding=false] - Accept a key login only when its signature is bound
|
|
177
178
|
* to this host's key (#119). A memory host can bind only `host` (it has no TLS of its own), so this needs `hostKey`;
|
|
178
179
|
* `true` or `['host']`.
|
|
180
|
+
* @param {(name: string, fs: object, who: { username: string | null, fingerprint: string | null }) => void | Promise<void>} [options.onShare]
|
|
181
|
+
* Folders of the OPERATOR's machine (#159): the operator's `wsh --share NAME=/abs/dir[:ro|:rw]` offers them after login and
|
|
182
|
+
* this is called once per share with an object of async file operations (`stat`, `readdir` with attributes, `readFile`,
|
|
183
|
+
* `open`, `writeFile`, `mkdir`, `rename`, `unlink`, ... and the `operate` / `readWhole` / `writeWhole` / `writeAt` shape of
|
|
184
|
+
* an `fs` backend) that the embedder can mount. Listing it makes the host state the `shares` feature. See `shares.mjs`.
|
|
179
185
|
* @param {(line: string) => void} [options.onLog]
|
|
180
186
|
*/
|
|
181
|
-
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, sealSession = false, onLog = () => {}
|
|
187
|
+
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, sealSession = false, onLog = () => {},
|
|
188
|
+
onShare } = {}) {
|
|
189
|
+
validateOnShare(onShare, 'createMemoryHost');
|
|
182
190
|
if (!Number.isFinite(connectionTtlMs) || connectionTtlMs < 0) throw new TypeError('createMemoryHost: connectionTtlMs must be a non-negative number');
|
|
183
191
|
if (requireChannelBinding !== false && requireChannelBinding !== true && !(Array.isArray(requireChannelBinding) && requireChannelBinding.every((k) => CHANNEL_BINDING_KINDS.includes(k)))) {
|
|
184
192
|
throw new TypeError(`createMemoryHost: requireChannelBinding must be true, false or an array of kinds (${CHANNEL_BINDING_KINDS.join(', ')})`);
|
|
@@ -210,7 +218,7 @@ export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions
|
|
|
210
218
|
|
|
211
219
|
const ready = Promise.all([buildAuthorizer(auth), hostKeyReady]).then(([authorize, hostKeyResolved]) => createConnectionFactory({
|
|
212
220
|
authorize, execRunner, execOptions, pty: ptyBackend, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, sealSession, log: onLog,
|
|
213
|
-
methods, hostKey: hostKeyResolved, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost,
|
|
221
|
+
methods, hostKey: hostKeyResolved, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, onShare,
|
|
214
222
|
gateway: gatewayCfg, createGatewaySession: gatewayCfg ? createEndpointGatewaySession : undefined, sessions: registry, relay: null,
|
|
215
223
|
}));
|
|
216
224
|
ready.catch(() => {});
|
package/src/messages.gen.mjs
CHANGED
|
@@ -157,6 +157,11 @@ export const MSG = Object.freeze({
|
|
|
157
157
|
// Keys
|
|
158
158
|
AUTHORIZED_KEY_ADD: 0x9f,
|
|
159
159
|
AUTHORIZED_KEY_RESULT: 0xa0,
|
|
160
|
+
|
|
161
|
+
// Shares
|
|
162
|
+
SHARE_OFFER: 0xa8,
|
|
163
|
+
SHARE_REQUEST: 0xa9,
|
|
164
|
+
SHARE_REPLY: 0xaa,
|
|
160
165
|
});
|
|
161
166
|
|
|
162
167
|
// Reverse lookup: number → name
|
|
@@ -986,6 +991,42 @@ export function authorizedKeyResult({ success, added = false, errorMessage } = {
|
|
|
986
991
|
return msg;
|
|
987
992
|
}
|
|
988
993
|
|
|
994
|
+
export function shareOffer({ shares, writable = [], maxInflight, maxBytes } = {}) {
|
|
995
|
+
return {
|
|
996
|
+
type: MSG.SHARE_OFFER,
|
|
997
|
+
shares,
|
|
998
|
+
writable,
|
|
999
|
+
max_inflight: maxInflight,
|
|
1000
|
+
max_bytes: maxBytes,
|
|
1001
|
+
};
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
export function shareRequest({ requestId, share, op, path, to, handle, offset, length, mode, flags = [], cursor, attr = {}, data } = {}) {
|
|
1005
|
+
const msg = { type: MSG.SHARE_REQUEST, request_id: requestId, share, op, flags, attr };
|
|
1006
|
+
if (path !== undefined) msg.path = path;
|
|
1007
|
+
if (to !== undefined) msg.to = to;
|
|
1008
|
+
if (handle !== undefined) msg.handle = handle;
|
|
1009
|
+
if (offset !== undefined) msg.offset = offset;
|
|
1010
|
+
if (length !== undefined) msg.length = length;
|
|
1011
|
+
if (mode !== undefined) msg.mode = mode;
|
|
1012
|
+
if (cursor !== undefined) msg.cursor = cursor;
|
|
1013
|
+
if (data !== undefined) msg.data = data;
|
|
1014
|
+
return msg;
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
export function shareReply({ requestId, ok, errno, message, attr = {}, entries = [], cursor, handle, data, eof, written, target } = {}) {
|
|
1018
|
+
const msg = { type: MSG.SHARE_REPLY, request_id: requestId, ok, attr, entries };
|
|
1019
|
+
if (errno !== undefined) msg.errno = errno;
|
|
1020
|
+
if (message !== undefined) msg.message = message;
|
|
1021
|
+
if (cursor !== undefined) msg.cursor = cursor;
|
|
1022
|
+
if (handle !== undefined) msg.handle = handle;
|
|
1023
|
+
if (data !== undefined) msg.data = data;
|
|
1024
|
+
if (eof !== undefined) msg.eof = eof;
|
|
1025
|
+
if (written !== undefined) msg.written = written;
|
|
1026
|
+
if (target !== undefined) msg.target = target;
|
|
1027
|
+
return msg;
|
|
1028
|
+
}
|
|
1029
|
+
|
|
989
1030
|
// ── Relay forwarding ─────────────────────────────────────────────────
|
|
990
1031
|
|
|
991
1032
|
// Message types a relay may forward inside a RelayForward wrapper.
|
package/src/reverse-host.mjs
CHANGED
|
@@ -23,6 +23,7 @@ import { OPERATOR_PROOF_FEATURE, E2E_SEALED_FEATURE, createReverseChallenge, ver
|
|
|
23
23
|
import { SealedBridge } from './bridge-seal.mjs';
|
|
24
24
|
import { resolveBackends } from './host-backends.mjs';
|
|
25
25
|
import { createConnectionFactory, hostFeatures } from './server/connection.mjs';
|
|
26
|
+
import { validateOnShare } from './shares.mjs';
|
|
26
27
|
|
|
27
28
|
const BACKOFF_START_MS = 500;
|
|
28
29
|
const BACKOFF_MAX_MS = 30_000;
|
|
@@ -67,6 +68,9 @@ const BACKOFF_MAX_MS = 30_000;
|
|
|
67
68
|
* plain message (it could inject an `Open`). Needs `e2e` (on by default) and `reportFeatures`. Without this option the
|
|
68
69
|
* proof is requested when it can be and reported as `proven`, and the bridge is sealed only if the operator asks.
|
|
69
70
|
* @param {number} [options.proofTimeoutMs=5000] - How long an operator has to answer the challenge.
|
|
71
|
+
* @param {(name: string, fs: object, who: { username: string | null, fingerprint: string | null }) => void | Promise<void>} [options.onShare]
|
|
72
|
+
* Folders an operator offers (`ShareOffer`, #159), once per share, as an object of async file operations. The Rust CLI
|
|
73
|
+
* offers shares on a direct or pipe-relayed session (`wsh --share`), not over `wsh reverse-connect` yet.
|
|
70
74
|
* @param {(line: string) => void} [options.onLog]
|
|
71
75
|
*/
|
|
72
76
|
export function createReverseHost(options = {}) {
|
|
@@ -81,8 +85,9 @@ export function createReverseHost(options = {}) {
|
|
|
81
85
|
*/
|
|
82
86
|
export function createReverseHostWith({
|
|
83
87
|
url, username, keyPair, accept, reconnect = true, connect = {}, peerType = 'host', reportFeatures = true, maxOperators = 1, e2e = {},
|
|
84
|
-
requireOperatorProof = false, proofTimeoutMs = 5000, onLog = () => {},
|
|
88
|
+
requireOperatorProof = false, proofTimeoutMs = 5000, onLog = () => {}, onShare,
|
|
85
89
|
} = {}, backends) {
|
|
90
|
+
validateOnShare(onShare, 'createReverseHost');
|
|
86
91
|
if (typeof requireOperatorProof !== 'boolean') throw new TypeError('createReverseHost: requireOperatorProof must be a boolean');
|
|
87
92
|
if (requireOperatorProof && e2e === false) throw new TypeError('createReverseHost: requireOperatorProof seals the bridge, which needs e2e (do not set e2e: false)');
|
|
88
93
|
if (requireOperatorProof && !reportFeatures) throw new TypeError('createReverseHost: requireOperatorProof needs reportFeatures (the operator learns "e2e-sealed" from ReverseAccept.features)');
|
|
@@ -109,13 +114,13 @@ export function createReverseHostWith({
|
|
|
109
114
|
});
|
|
110
115
|
/** Features for `ReverseAccept` on this relay connection. */
|
|
111
116
|
const bridgeFeatures = (c, e2eConfig, manyOperators) => [
|
|
112
|
-
...hostFeatures({ mcp: backends.mcp, files: backends.files, e2e: e2eConfig }, { dataStreams: false }),
|
|
117
|
+
...hostFeatures({ mcp: backends.mcp, files: backends.files, e2e: e2eConfig, onShare }, { dataStreams: false }),
|
|
113
118
|
...(manyOperators ? [MULTI_OPERATOR_FEATURE] : []),
|
|
114
119
|
];
|
|
115
120
|
const factory = createConnectionFactory({
|
|
116
121
|
authorize: async () => false, methods: { pubkey: false, password: null }, hostKey: null, rateLimit: null,
|
|
117
122
|
execRunner: backends.execRunner, execOptions: backends.execOptions, pty: backends.pty, files: backends.files, mcp: backends.mcp,
|
|
118
|
-
sessions: null, relay: null, e2e: null, bindTimeoutMs: 3000, log: (l) => onLog(`[reverse] ${l}`),
|
|
123
|
+
sessions: null, relay: null, e2e: null, bindTimeoutMs: 3000, log: (l) => onLog(`[reverse] ${l}`), onShare,
|
|
119
124
|
});
|
|
120
125
|
|
|
121
126
|
let client = null;
|
|
@@ -36,6 +36,7 @@ import { clientEnvFilter } from './client-env.mjs';
|
|
|
36
36
|
import { acceptableBindings, bindingFeatures } from '../channel-binding.mjs';
|
|
37
37
|
import { SealedBridge } from '../bridge-seal.mjs';
|
|
38
38
|
import { HOST_KEY_PREFIX, HOST_KEY_SIG_PREFIX, findClientNonce, hostKeyProofMessage, toHex } from '../host-key.mjs';
|
|
39
|
+
import { SHARES_FEATURE, createShareSession } from '../shares.mjs';
|
|
39
40
|
|
|
40
41
|
export const STREAM_ANNOUNCE = 'stream-announce';
|
|
41
42
|
/** Host feature (#155): this host seals the whole session end to end when asked (a signed `KeyExchange` for the connection's session id). */
|
|
@@ -54,6 +55,7 @@ export function hostFeatures(cfg, { dataStreams = true } = {}) {
|
|
|
54
55
|
if (cfg.mcp) features.push(MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE);
|
|
55
56
|
if (cfg.gateway) features.push(...gatewayFeatures(cfg.gateway));
|
|
56
57
|
if (cfg.files) features.push('file-transfer', 'file-write', 'file-rename');
|
|
58
|
+
if (cfg.onShare) features.push(SHARES_FEATURE); // #159: this host can use folders the operator's client offers
|
|
57
59
|
// End-to-end encryption (#90) is the virtual-mode EncryptedFrame layer, so it is offered where there are no
|
|
58
60
|
// client-opened streams: over a relay bridge.
|
|
59
61
|
// A relay carries a signed KeyExchange untouched, and (when configured) several operators per peer: peers read
|
|
@@ -177,6 +179,11 @@ export function createConnectionFactory(cfg) {
|
|
|
177
179
|
? cfg.createGatewaySession(cfg.gateway, (m) => send(m), log, { who: () => ({ username: state.username, fingerprint: state.fingerprint }), datagrams })
|
|
178
180
|
: null;
|
|
179
181
|
|
|
182
|
+
// Operator-side shared folders (#159): created with the connection, used only after the client's ShareOffer.
|
|
183
|
+
const shares = cfg.onShare
|
|
184
|
+
? createShareSession({ send: (m) => send(m), onShare: cfg.onShare, who: () => ({ username: state.username, fingerprint: state.fingerprint }), log, timeoutMs: cfg.shareTimeoutMs })
|
|
185
|
+
: null;
|
|
186
|
+
|
|
180
187
|
const qmux = sendMessage ? null : new QMuxConnection({ isClient: false, send: (b) => { if (!state.closed) sendBytes(b); } });
|
|
181
188
|
|
|
182
189
|
// ── End-to-end encryption (#90) ──────────────────────────────────
|
|
@@ -240,6 +247,7 @@ export function createConnectionFactory(cfg) {
|
|
|
240
247
|
channels.clear();
|
|
241
248
|
responder?.close();
|
|
242
249
|
gateway?.close();
|
|
250
|
+
shares?.close();
|
|
243
251
|
e2eSessions.clear();
|
|
244
252
|
for (const c of mcpCalls) c.abort(new Error('connection closed'));
|
|
245
253
|
mcpCalls.clear();
|
|
@@ -295,6 +303,7 @@ export function createConnectionFactory(cfg) {
|
|
|
295
303
|
}
|
|
296
304
|
if (await handleRelay(m)) return;
|
|
297
305
|
if (gateway && await gateway.handle(m)) return;
|
|
306
|
+
if (shares && shares.handle(m)) return;
|
|
298
307
|
switch (m.type) {
|
|
299
308
|
case MSG.PING: return send(pong({ id: m.id }));
|
|
300
309
|
case MSG.OPEN: return handleOpen(m);
|
package/src/server/index.d.ts
CHANGED
|
@@ -480,6 +480,11 @@ export interface WshServerOptions {
|
|
|
480
480
|
* TLS-terminating proxy; `cert-hash` needs WebTransport with `selfSigned`). Clients older than 0.36 cannot satisfy it.
|
|
481
481
|
*/
|
|
482
482
|
requireChannelBinding?: boolean | Array<'cert-hash' | 'host' | 'tls-exporter'>;
|
|
483
|
+
/**
|
|
484
|
+
* Folders the operator's `wsh --share NAME=/abs/dir[:ro|:rw]` offers (#159): called once per share with an object of
|
|
485
|
+
* async file operations to mount. Listing it makes the host state the `shares` feature.
|
|
486
|
+
*/
|
|
487
|
+
onShare?: import('../host.js').WshOnShare;
|
|
483
488
|
onLog?: (line: string) => void;
|
|
484
489
|
}
|
|
485
490
|
|
|
@@ -628,6 +633,8 @@ export interface WshReverseHostOptions {
|
|
|
628
633
|
requireOperatorProof?: boolean;
|
|
629
634
|
/** How long an operator has to answer the challenge (default 5000). */
|
|
630
635
|
proofTimeoutMs?: number;
|
|
636
|
+
/** Folders an operator offers over a bridge (#159), once per share, as an object of async file operations. */
|
|
637
|
+
onShare?: import('../host.js').WshOnShare;
|
|
631
638
|
onLog?: (line: string) => void;
|
|
632
639
|
}
|
|
633
640
|
|
package/src/server/index.mjs
CHANGED
|
@@ -15,6 +15,7 @@ import { SessionRegistry } from './sessions.mjs';
|
|
|
15
15
|
import { RelayHub } from './relay.mjs';
|
|
16
16
|
import { startWebTransport } from './webtransport.mjs';
|
|
17
17
|
import { createConnectionFactory, STREAM_ANNOUNCE } from './connection.mjs';
|
|
18
|
+
import { validateOnShare } from '../shares.mjs';
|
|
18
19
|
import { normalizeGateway, createGatewaySession } from './gateway.mjs';
|
|
19
20
|
import { createRpcHost, mcpServerAdapter } from './rpc.mjs';
|
|
20
21
|
import { bindSocket } from './socket.mjs';
|
|
@@ -93,12 +94,17 @@ function tlsChannelBinding(socket) {
|
|
|
93
94
|
* this connection (#119): `true` needs any binding kind, an array names kinds that must all be bound (`host` needs
|
|
94
95
|
* `hostKey`; `tls-exporter` needs `wss://` served by this process, not a TLS-terminating proxy; `cert-hash` needs
|
|
95
96
|
* WebTransport with `selfSigned`). Clients older than 0.36 cannot satisfy it. Off by default.
|
|
97
|
+
* @param {(name: string, fs: object, who: { username: string | null, fingerprint: string | null }) => void | Promise<void>} [options.onShare]
|
|
98
|
+
* Folders of the operator's machine (`wsh --share`, #159), once per share, as an object of async file operations to mount;
|
|
99
|
+
* listing it makes the host state the `shares` feature. As for `createMemoryHost`.
|
|
96
100
|
* @param {(line: string) => void} [options.onLog]
|
|
97
101
|
* @returns {{ listen(): Promise<{address: string, port: number}>, accept(socket: object, options?: object): Promise<{ close(): void }>, close(): Promise<void>, address(): ({address: string, port: number} | null) }}
|
|
98
102
|
*/
|
|
99
103
|
export function createWshServer({
|
|
100
104
|
host = '127.0.0.1', port = 0, tls, auth, exec, pty, fs, hostKey, mcp, rpc, rpcMaxMessageBytes, rpcMaxInflight, sessions, sessionSecret, relay, extensions, gateway, webTransport, bindTimeoutMs = 3000, connectionTtlMs = 0, requireChannelBinding = false, sealSession = false, onLog = () => {},
|
|
105
|
+
onShare,
|
|
101
106
|
} = {}) {
|
|
107
|
+
validateOnShare(onShare, 'createWshServer');
|
|
102
108
|
if (sealSession !== false && sealSession !== 'offer' && sealSession !== 'require') throw new TypeError("createWshServer: sealSession must be false, 'offer' or 'require'");
|
|
103
109
|
if (sealSession && !hostKey) throw new TypeError('createWshServer: sealSession needs a hostKey (the host signs its half of the key exchange with it)');
|
|
104
110
|
if (requireChannelBinding !== false && requireChannelBinding !== true && !(Array.isArray(requireChannelBinding) && requireChannelBinding.every((k) => CHANNEL_BINDING_KINDS.includes(k)))) {
|
|
@@ -152,6 +158,7 @@ export function createWshServer({
|
|
|
152
158
|
return createConnectionFactory({
|
|
153
159
|
authorize, execRunner, execOptions, pty: ptyConfig, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, sealSession, log: onLog,
|
|
154
160
|
methods, hostKey: host_, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, gateway: gatewayCfg, createGatewaySession, sessions: registry, relay: hub,
|
|
161
|
+
onShare,
|
|
155
162
|
});
|
|
156
163
|
})();
|
|
157
164
|
ready.catch(() => { ready = null; });
|
package/src/shares.mjs
ADDED
|
@@ -0,0 +1,425 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Operator-side shared folders, the HOST half (#159). Browser-safe: it imports nothing from `node:*`.
|
|
3
|
+
*
|
|
4
|
+
* A host that has no disk of its own (a tab) can use directories that live on the OPERATOR's machine for the life of
|
|
5
|
+
* a session: the operator's `wsh --share NAME=/abs/dir[:ro|:rw]` offers them (`ShareOffer`), and this module hands the
|
|
6
|
+
* embedder an object of async file operations per share -- `onShare(name, fs, who)` -- that it can mount. Every
|
|
7
|
+
* operation is a bounded `ShareRequest` this host sends and the operator's client answers (`ShareReply`).
|
|
8
|
+
*
|
|
9
|
+
* The client is the file server and enforces confinement; this side enforces what a host can: the request window the
|
|
10
|
+
* offer promised (`max_inflight`), a per-request deadline, the size of a reply, the shape of what comes back (a client
|
|
11
|
+
* that answers nonsense gets an `EIO`, never a thrown TypeError in the embedder's code), and that nothing is asked
|
|
12
|
+
* before an offer. Share names, counts and limits from the offer are validated and clamped.
|
|
13
|
+
*
|
|
14
|
+
* Negotiation: a host that passes `onShare` lists the feature `shares` in `ServerHello.features`. A client with shares
|
|
15
|
+
* to offer sends ONE `ShareOffer` after login (inside whatever sealing the session has, so a sealed session protects
|
|
16
|
+
* file data with no extra crypto here). A host without `onShare` never lists the feature and ignores an offer.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { MSG, shareRequest } from './messages.gen.mjs';
|
|
20
|
+
|
|
21
|
+
/** The `ServerHello` feature of a host that can use shares. */
|
|
22
|
+
export const SHARES_FEATURE = 'shares';
|
|
23
|
+
|
|
24
|
+
const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
25
|
+
const ERRNOS = new Set(['ENOENT', 'EEXIST', 'ENOTDIR', 'EISDIR', 'ENOTEMPTY', 'EACCES', 'EPERM', 'EROFS', 'EINVAL', 'EBADF', 'ELOOP',
|
|
26
|
+
'ENAMETOOLONG', 'ENOSPC', 'EMFILE', 'EBUSY', 'EAGAIN', 'EXDEV', 'EFBIG', 'ENOTSUP', 'ESTALE', 'EIO']);
|
|
27
|
+
const MAX_SHARES = 16;
|
|
28
|
+
const MAX_INFLIGHT = 64;
|
|
29
|
+
const MIN_BYTES = 4096;
|
|
30
|
+
const MAX_BYTES = 4 * 1024 * 1024;
|
|
31
|
+
/** Requests waiting for a slot of the window, per connection; beyond that a call fails with `EAGAIN` at once. */
|
|
32
|
+
const QUEUE_LIMIT = 4096;
|
|
33
|
+
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
34
|
+
const DEFAULT_MAX_FILE_BYTES = 64 * 1024 * 1024;
|
|
35
|
+
const MAX_LIST_ENTRIES = 2_000_000;
|
|
36
|
+
|
|
37
|
+
/** An error from the operator's side of a share, with the errno-like code the wire carries (`error.code === error.errno`). */
|
|
38
|
+
export class ShareError extends Error {
|
|
39
|
+
constructor(errno, message) {
|
|
40
|
+
super(`${errno}: ${message}`);
|
|
41
|
+
this.name = 'ShareError';
|
|
42
|
+
this.errno = errno;
|
|
43
|
+
this.code = errno;
|
|
44
|
+
this.wsh = true;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const clampInt = (v, lo, hi) => Math.min(hi, Math.max(lo, Number.isFinite(v) ? Math.trunc(v) : lo));
|
|
49
|
+
const text = (v, max = 200) => (typeof v === 'string' ? v.replace(/[\u0000-\u001f\u007f]/g, ' ').slice(0, max) : '');
|
|
50
|
+
|
|
51
|
+
/** An attribute map from the wire, as a plain object a caller can rely on. */
|
|
52
|
+
function toAttr(a) {
|
|
53
|
+
if (!a || typeof a !== 'object') throw new ShareError('EIO', 'the operator sent no attributes');
|
|
54
|
+
const type = a.type === 'file' || a.type === 'directory' || a.type === 'symlink' ? a.type : null;
|
|
55
|
+
if (!type) throw new ShareError('EIO', 'the operator sent an unknown file type');
|
|
56
|
+
const n = (v) => (Number.isFinite(v) ? Number(v) : 0);
|
|
57
|
+
return {
|
|
58
|
+
type, size: n(a.size), mode: n(a.mode) & 0o777, mtimeMs: n(a.mtime_ms), atimeMs: n(a.atime_ms), ctimeMs: n(a.ctime_ms), nlink: n(a.nlink), ino: n(a.ino),
|
|
59
|
+
isFile: () => type === 'file', isDirectory: () => type === 'directory', isSymbolicLink: () => type === 'symlink',
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const toBytes = (v, what) => {
|
|
64
|
+
if (v instanceof Uint8Array) return v;
|
|
65
|
+
if (v === undefined || v === null) return new Uint8Array(0);
|
|
66
|
+
throw new ShareError('EIO', `the operator sent ${what} that is not bytes`);
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* The per-connection engine: one request window shared by every share of the connection.
|
|
71
|
+
* @param {{ send: (m: object) => unknown, log?: (line: string) => void, timeoutMs?: number }} io
|
|
72
|
+
*/
|
|
73
|
+
function createCore({ send, log = () => {}, timeoutMs = DEFAULT_TIMEOUT_MS }) {
|
|
74
|
+
let window = 1;
|
|
75
|
+
let maxBytes = MIN_BYTES;
|
|
76
|
+
let nextId = 1;
|
|
77
|
+
let closed = false;
|
|
78
|
+
const inflight = new Map(); // id -> { job, abandoned }
|
|
79
|
+
const queue = [];
|
|
80
|
+
const stats = { requests: 0, replies: 0, errors: 0, bytesDown: 0, bytesUp: 0, timeouts: 0 };
|
|
81
|
+
|
|
82
|
+
function pump() {
|
|
83
|
+
while (!closed && inflight.size < window && queue.length) start(queue.shift());
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function start(job) {
|
|
87
|
+
if (job.done) return;
|
|
88
|
+
let id = nextId;
|
|
89
|
+
for (let i = 0; inflight.has(id); i += 1) { id = (id % 0xffffffff) + 1; if (i > 0xffff) { finish(job, new ShareError('EAGAIN', 'no request id free')); return; } }
|
|
90
|
+
nextId = (id % 0xffffffff) + 1;
|
|
91
|
+
job.id = id;
|
|
92
|
+
inflight.set(id, { job, abandoned: false });
|
|
93
|
+
stats.requests += 1;
|
|
94
|
+
if (job.fields.data) stats.bytesUp += job.fields.data.byteLength;
|
|
95
|
+
try {
|
|
96
|
+
Promise.resolve(send(shareRequest({ requestId: id, share: job.share, op: job.op, ...job.fields }))).catch(() => {});
|
|
97
|
+
} catch (e) { inflight.delete(id); finish(job, new ShareError('EIO', `could not send: ${e.message}`)); }
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function finish(job, err, value) {
|
|
101
|
+
if (job.done) return;
|
|
102
|
+
job.done = true;
|
|
103
|
+
clearTimeout(job.timer);
|
|
104
|
+
if (err) job.reject(err); else job.resolve(value);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
return {
|
|
108
|
+
stats,
|
|
109
|
+
get maxBytes() { return maxBytes; },
|
|
110
|
+
configure(offer) { window = offer.maxInflight; maxBytes = offer.maxBytes; pump(); },
|
|
111
|
+
/** Send one request and resolve with the (validated-as-ok) reply. */
|
|
112
|
+
call(share, op, fields = {}) {
|
|
113
|
+
return new Promise((resolve, reject) => {
|
|
114
|
+
if (closed) { reject(new ShareError('EIO', 'the connection to the operator is gone')); return; }
|
|
115
|
+
const job = { share, op, fields, resolve, reject, done: false, id: 0, timer: null };
|
|
116
|
+
if (queue.length >= QUEUE_LIMIT) { reject(new ShareError('EAGAIN', 'too many share requests are waiting')); return; }
|
|
117
|
+
job.timer = setTimeout(() => {
|
|
118
|
+
stats.timeouts += 1;
|
|
119
|
+
const q = queue.indexOf(job);
|
|
120
|
+
if (q >= 0) queue.splice(q, 1);
|
|
121
|
+
// A request already sent keeps its slot until the operator answers (or the connection ends): the window
|
|
122
|
+
// the offer promised is not exceeded because one answer is slow.
|
|
123
|
+
const entry = inflight.get(job.id);
|
|
124
|
+
if (entry) entry.abandoned = true;
|
|
125
|
+
finish(job, new ShareError('EIO', `the operator did not answer ${op} within ${timeoutMs} ms`));
|
|
126
|
+
}, timeoutMs);
|
|
127
|
+
job.timer.unref?.();
|
|
128
|
+
queue.push(job);
|
|
129
|
+
pump();
|
|
130
|
+
});
|
|
131
|
+
},
|
|
132
|
+
reply(m) {
|
|
133
|
+
const entry = inflight.get(m.request_id);
|
|
134
|
+
if (!entry) return; // unknown or already answered: ignored
|
|
135
|
+
inflight.delete(m.request_id);
|
|
136
|
+
stats.replies += 1;
|
|
137
|
+
const { job, abandoned } = entry;
|
|
138
|
+
if (!abandoned) {
|
|
139
|
+
if (m.ok === true) {
|
|
140
|
+
const data = m.data;
|
|
141
|
+
if (data instanceof Uint8Array) {
|
|
142
|
+
stats.bytesDown += data.byteLength;
|
|
143
|
+
if (data.byteLength > maxBytes) { stats.errors += 1; finish(job, new ShareError('EIO', 'the operator sent more data than it offered')); pump(); return; }
|
|
144
|
+
}
|
|
145
|
+
finish(job, null, m);
|
|
146
|
+
} else {
|
|
147
|
+
stats.errors += 1;
|
|
148
|
+
const errno = ERRNOS.has(m.errno) ? m.errno : 'EIO';
|
|
149
|
+
finish(job, new ShareError(errno, text(m.message) || errno));
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
pump();
|
|
153
|
+
},
|
|
154
|
+
close() {
|
|
155
|
+
if (closed) return;
|
|
156
|
+
closed = true;
|
|
157
|
+
const gone = () => new ShareError('EIO', 'the connection to the operator is gone');
|
|
158
|
+
for (const { job } of inflight.values()) finish(job, gone());
|
|
159
|
+
inflight.clear();
|
|
160
|
+
for (const job of queue.splice(0)) finish(job, gone());
|
|
161
|
+
},
|
|
162
|
+
get closed() { return closed; },
|
|
163
|
+
log,
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** An open file on the operator's machine. */
|
|
168
|
+
class ShareFile {
|
|
169
|
+
#core; #share; #handle; #inline; #writable; #closed = false;
|
|
170
|
+
constructor(core, share, handle, attr, { inline = null, writable = false } = {}) {
|
|
171
|
+
this.#core = core; this.#share = share; this.#handle = handle; this.#inline = inline; this.#writable = writable;
|
|
172
|
+
this.attr = attr;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Read up to `length` bytes at `offset`: `{ data, eof }`. */
|
|
176
|
+
async read(offset, length) {
|
|
177
|
+
if (this.#closed) throw new ShareError('EBADF', 'the file is closed');
|
|
178
|
+
if (!(Number.isSafeInteger(offset) && offset >= 0) || !(Number.isSafeInteger(length) && length >= 0)) throw new ShareError('EINVAL', 'read needs a non-negative offset and length');
|
|
179
|
+
if (this.#inline) {
|
|
180
|
+
const data = this.#inline.subarray(offset, offset + length);
|
|
181
|
+
return { data, eof: offset + length >= this.#inline.byteLength };
|
|
182
|
+
}
|
|
183
|
+
const n = Math.min(length, this.#core.maxBytes);
|
|
184
|
+
const r = await this.#core.call(this.#share, 'read', { handle: this.#handle, offset, length: n });
|
|
185
|
+
return { data: toBytes(r.data, 'read data'), eof: r.eof === true };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Write `data` at `offset` (a share offered `:rw`); resolves with the bytes written. */
|
|
189
|
+
async write(offset, data) {
|
|
190
|
+
if (this.#closed) throw new ShareError('EBADF', 'the file is closed');
|
|
191
|
+
if (!this.#writable) throw new ShareError('EBADF', 'the file is not open for writing');
|
|
192
|
+
let done = 0;
|
|
193
|
+
while (done < data.byteLength) {
|
|
194
|
+
const chunk = data.subarray(done, done + this.#core.maxBytes);
|
|
195
|
+
const r = await this.#core.call(this.#share, 'write', { handle: this.#handle, offset: offset + done, data: chunk });
|
|
196
|
+
const w = Number(r.written);
|
|
197
|
+
if (!Number.isSafeInteger(w) || w < 0 || w > chunk.byteLength) throw new ShareError('EIO', 'the operator reported a bad write size');
|
|
198
|
+
done += w;
|
|
199
|
+
if (w === 0) break;
|
|
200
|
+
}
|
|
201
|
+
return done;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async setattr(changes) {
|
|
205
|
+
if (this.#closed) throw new ShareError('EBADF', 'the file is closed');
|
|
206
|
+
if (!this.#handle) throw new ShareError('EBADF', 'this file is read-only and complete: use fs.setattr(path, ...)');
|
|
207
|
+
const r = await this.#core.call(this.#share, 'setattr', { handle: this.#handle, attr: wireAttr(changes) });
|
|
208
|
+
return toAttr(r.attr);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async truncate(size) { return this.setattr({ size }); }
|
|
212
|
+
|
|
213
|
+
async close() {
|
|
214
|
+
if (this.#closed) return;
|
|
215
|
+
this.#closed = true;
|
|
216
|
+
if (this.#handle) await this.#core.call(this.#share, 'close', { handle: this.#handle }).catch(() => {});
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function wireAttr(c = {}) {
|
|
221
|
+
const out = {};
|
|
222
|
+
if (c.mode !== undefined) out.mode = c.mode;
|
|
223
|
+
if (c.atimeMs !== undefined) out.atime_ms = c.atimeMs;
|
|
224
|
+
if (c.mtimeMs !== undefined) out.mtime_ms = c.mtimeMs;
|
|
225
|
+
if (c.size !== undefined) out.size = c.size;
|
|
226
|
+
return out;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* The object an embedder mounts: async file operations on one share. Paths are relative to the share root
|
|
231
|
+
* ("/"-separated; a leading "/" means the root); `..` is refused by the operator's client. Errors are `ShareError`s
|
|
232
|
+
* with `.code` an errno-like string (`ENOENT`, `EROFS`, ...).
|
|
233
|
+
*/
|
|
234
|
+
function createShareFs(core, name, writable, signal) {
|
|
235
|
+
const call = (op, fields) => core.call(name, op, fields);
|
|
236
|
+
const norm = (p) => { if (typeof p !== 'string') throw new ShareError('EINVAL', 'a path must be a string'); return p; };
|
|
237
|
+
const maxFileBytes = DEFAULT_MAX_FILE_BYTES;
|
|
238
|
+
|
|
239
|
+
const fs = {
|
|
240
|
+
name,
|
|
241
|
+
/** Whether the operator offered writes. */
|
|
242
|
+
writable,
|
|
243
|
+
maxFileBytes,
|
|
244
|
+
/** Aborted when the connection to the operator ends. */
|
|
245
|
+
signal,
|
|
246
|
+
/** Counters for this connection (requests, replies, errors, bytes each way): the evidence that batching works. */
|
|
247
|
+
get stats() { return { ...core.stats }; },
|
|
248
|
+
|
|
249
|
+
async stat(path) { return toAttr((await call('stat', { path: norm(path) })).attr); },
|
|
250
|
+
async lstat(path) { return toAttr((await call('lstat', { path: norm(path) })).attr); },
|
|
251
|
+
async readlink(path) {
|
|
252
|
+
const r = await call('readlink', { path: norm(path) });
|
|
253
|
+
if (typeof r.target !== 'string') throw new ShareError('EIO', 'the operator sent no link target');
|
|
254
|
+
return r.target;
|
|
255
|
+
},
|
|
256
|
+
|
|
257
|
+
/** Every entry of a directory WITH its attributes, sorted by name (the pages are followed): `[{ name, type, size, mode, mtimeMs, ..., target? }]`. */
|
|
258
|
+
async readdir(path) {
|
|
259
|
+
const out = [];
|
|
260
|
+
let cursor;
|
|
261
|
+
for (;;) {
|
|
262
|
+
const r = await call('readdir', { path: norm(path), ...(cursor !== undefined ? { cursor } : {}) });
|
|
263
|
+
if (!Array.isArray(r.entries)) throw new ShareError('EIO', 'the operator sent no entries');
|
|
264
|
+
for (const e of r.entries) {
|
|
265
|
+
if (!e || typeof e.name !== 'string' || !e.name || e.name.includes('/') || e.name.includes('\0') || e.name === '.' || e.name === '..') throw new ShareError('EIO', 'the operator sent a bad directory entry');
|
|
266
|
+
const entry = { name: e.name, ...toAttr(e) };
|
|
267
|
+
if (typeof e.target === 'string') entry.target = e.target;
|
|
268
|
+
out.push(entry);
|
|
269
|
+
}
|
|
270
|
+
if (out.length > MAX_LIST_ENTRIES) throw new ShareError('EFBIG', 'directory has too many entries');
|
|
271
|
+
if (r.cursor === undefined || r.cursor === null) break;
|
|
272
|
+
if (typeof r.cursor !== 'string' || (cursor !== undefined && r.cursor <= cursor)) throw new ShareError('EIO', 'the operator\'s directory cursor did not advance');
|
|
273
|
+
cursor = r.cursor;
|
|
274
|
+
}
|
|
275
|
+
return out;
|
|
276
|
+
},
|
|
277
|
+
|
|
278
|
+
/** Open a file. `flags`: any of `read`, `write`, `create`, `excl`, `trunc`. */
|
|
279
|
+
async open(path, flags = ['read'], { mode, inlineBytes } = {}) {
|
|
280
|
+
const f = [...flags];
|
|
281
|
+
const wantsWrite = f.includes('write') || f.includes('create') || f.includes('trunc');
|
|
282
|
+
const r = await call('open', { path: norm(path), flags: f, ...(mode !== undefined ? { mode } : {}), ...(inlineBytes !== undefined ? { length: inlineBytes } : {}) });
|
|
283
|
+
const attr = toAttr(r.attr);
|
|
284
|
+
if (r.handle === undefined || r.handle === null) {
|
|
285
|
+
// Whole file, read-only, no handle: it came with the open.
|
|
286
|
+
if (wantsWrite || r.eof !== true || !(r.data instanceof Uint8Array)) throw new ShareError('EIO', 'the operator sent no file handle');
|
|
287
|
+
return new ShareFile(core, name, 0, attr, { inline: r.data });
|
|
288
|
+
}
|
|
289
|
+
if (!Number.isSafeInteger(r.handle) || r.handle <= 0) throw new ShareError('EIO', 'the operator sent a bad handle');
|
|
290
|
+
return new ShareFile(core, name, r.handle, attr, { writable: wantsWrite, inline: r.eof === true && r.data instanceof Uint8Array && !wantsWrite ? r.data : null });
|
|
291
|
+
},
|
|
292
|
+
|
|
293
|
+
/** Create a NEW file (`EEXIST` if the name is taken, a link included) and open it for writing. */
|
|
294
|
+
async create(path, { mode } = {}) {
|
|
295
|
+
const r = await call('create', { path: norm(path), ...(mode !== undefined ? { mode } : {}) });
|
|
296
|
+
if (!Number.isSafeInteger(r.handle) || r.handle <= 0) throw new ShareError('EIO', 'the operator sent a bad handle');
|
|
297
|
+
return new ShareFile(core, name, r.handle, toAttr(r.attr), { writable: true });
|
|
298
|
+
},
|
|
299
|
+
|
|
300
|
+
/** The whole content of a file: one round trip when it is small (it rides the open), else ranges of the offered size. */
|
|
301
|
+
async readFile(path, { maxBytes = maxFileBytes } = {}) {
|
|
302
|
+
const file = await fs.open(path, ['read'], { inlineBytes: core.maxBytes });
|
|
303
|
+
try {
|
|
304
|
+
if (file.attr.size > maxBytes) throw new ShareError('EFBIG', `the file is ${file.attr.size} bytes, more than ${maxBytes}`);
|
|
305
|
+
const parts = [];
|
|
306
|
+
let offset = 0;
|
|
307
|
+
for (;;) {
|
|
308
|
+
const { data, eof } = await file.read(offset, core.maxBytes);
|
|
309
|
+
if (data.byteLength) parts.push(data);
|
|
310
|
+
offset += data.byteLength;
|
|
311
|
+
if (offset > maxBytes) throw new ShareError('EFBIG', `the file is bigger than ${maxBytes} bytes`);
|
|
312
|
+
if (eof || data.byteLength === 0) break;
|
|
313
|
+
}
|
|
314
|
+
if (parts.length === 1) return parts[0];
|
|
315
|
+
const all = new Uint8Array(offset);
|
|
316
|
+
let at = 0;
|
|
317
|
+
for (const p of parts) { all.set(p, at); at += p.byteLength; }
|
|
318
|
+
return all;
|
|
319
|
+
} finally { await file.close(); }
|
|
320
|
+
},
|
|
321
|
+
|
|
322
|
+
/** Replace (or create) a file with `data`. Needs `:rw`. */
|
|
323
|
+
async writeFile(path, data, { mode, truncate = true } = {}) {
|
|
324
|
+
const file = await fs.open(path, ['write', 'create', ...(truncate ? ['trunc'] : [])], { mode });
|
|
325
|
+
try { return await file.write(0, data); } finally { await file.close(); }
|
|
326
|
+
},
|
|
327
|
+
|
|
328
|
+
async mkdir(path, { mode } = {}) { return toAttr((await call('mkdir', { path: norm(path), ...(mode !== undefined ? { mode } : {}) })).attr); },
|
|
329
|
+
async unlink(path) { await call('unlink', { path: norm(path) }); },
|
|
330
|
+
async rmdir(path) { await call('rmdir', { path: norm(path) }); },
|
|
331
|
+
async rename(from, to) { await call('rename', { path: norm(from), to: norm(to) }); },
|
|
332
|
+
/** `changes`: any of `mode`, `atimeMs`, `mtimeMs`, `size` (a new size is a truncate). */
|
|
333
|
+
async setattr(path, changes) { return toAttr((await call('setattr', { path: norm(path), attr: wireAttr(changes) })).attr); },
|
|
334
|
+
async truncate(path, size) { return fs.setattr(path, { size }); },
|
|
335
|
+
async chmod(path, mode) { return fs.setattr(path, { mode }); },
|
|
336
|
+
async utimes(path, atimeMs, mtimeMs) { return fs.setattr(path, { atimeMs, mtimeMs }); },
|
|
337
|
+
|
|
338
|
+
// ── the shape of an injected `fs` backend (`createMemoryHost({ fs })`, `createWshServer({ fs })`) ───────────────
|
|
339
|
+
// A share can be served onward as a host's own file backend: `createMemoryHost({ fs: share })`.
|
|
340
|
+
async operate(op, clientPath, { offset, length, newPath, data } = {}) {
|
|
341
|
+
const entry = (e, nameOf) => ({ name: nameOf, size: e.size, modified: Math.floor(e.mtimeMs / 1000), type: e.type, ...(e.target !== undefined ? { symlink_target: e.target } : {}) });
|
|
342
|
+
switch (op) {
|
|
343
|
+
case 'list': return { entries: (await fs.readdir(clientPath || '/')).map((e) => entry(e, e.name)), metadata: { path: clientPath || '/' } };
|
|
344
|
+
case 'stat': { const a = await fs.lstat(clientPath); return { metadata: entry(a, String(clientPath).split('/').filter(Boolean).pop() ?? '') }; }
|
|
345
|
+
case 'read': {
|
|
346
|
+
const file = await fs.open(clientPath, ['read']);
|
|
347
|
+
try {
|
|
348
|
+
const want = Math.min(Number(length ?? core.maxBytes), core.maxBytes);
|
|
349
|
+
const { data: bytes } = await file.read(Math.max(0, Number(offset ?? 0)), want);
|
|
350
|
+
return { metadata: { data: bytes, size: file.attr.size } };
|
|
351
|
+
} finally { await file.close(); }
|
|
352
|
+
}
|
|
353
|
+
case 'write': { await fs.writeAt(clientPath, data, offset); return { metadata: { written: data.byteLength } }; }
|
|
354
|
+
case 'mkdir': await fs.mkdir(clientPath); return { metadata: {} };
|
|
355
|
+
case 'remove': { const a = await fs.lstat(clientPath); await (a.isDirectory() ? fs.rmdir(clientPath) : fs.unlink(clientPath)); return { metadata: { removed: clientPath } }; }
|
|
356
|
+
case 'rename': await fs.rename(clientPath, newPath); return { metadata: { renamed: clientPath, to: newPath } };
|
|
357
|
+
default: throw new ShareError('ENOTSUP', `"${op}" is not offered (list, stat, read, write, rename, mkdir, remove)`);
|
|
358
|
+
}
|
|
359
|
+
},
|
|
360
|
+
async readWhole(clientPath) { return fs.readFile(clientPath); },
|
|
361
|
+
async writeWhole(clientPath, bytes) { await fs.writeFile(clientPath, bytes); },
|
|
362
|
+
async writeAt(clientPath, bytes, offset = 0) {
|
|
363
|
+
const file = await fs.open(clientPath, ['write', 'create']);
|
|
364
|
+
try { await file.write(Number(offset), bytes); } finally { await file.close(); }
|
|
365
|
+
},
|
|
366
|
+
};
|
|
367
|
+
return fs;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* The shares of ONE connection. `handle(m)` takes the messages that are about shares; `close()` ends everything.
|
|
372
|
+
* @param {object} io
|
|
373
|
+
* @param {(m: object) => unknown} io.send - send a message to the operator (through the connection's sealing, if any)
|
|
374
|
+
* @param {(name: string, fs: object, who: { username: string | null, fingerprint: string | null }) => unknown} io.onShare
|
|
375
|
+
* @param {() => { username: string | null, fingerprint: string | null }} io.who
|
|
376
|
+
* @param {(line: string) => void} [io.log]
|
|
377
|
+
* @param {number} [io.timeoutMs]
|
|
378
|
+
*/
|
|
379
|
+
export function createShareSession({ send, onShare, who, log = () => {}, timeoutMs }) {
|
|
380
|
+
const core = createCore({ send, log, timeoutMs });
|
|
381
|
+
const abort = new AbortController();
|
|
382
|
+
let offered = false;
|
|
383
|
+
const shares = new Map();
|
|
384
|
+
|
|
385
|
+
function offer(m) {
|
|
386
|
+
if (offered) { log('ignored a second ShareOffer'); return; }
|
|
387
|
+
offered = true;
|
|
388
|
+
const names = Array.isArray(m.shares) ? m.shares : [];
|
|
389
|
+
if (!names.length || names.length > MAX_SHARES || names.some((n) => typeof n !== 'string' || !NAME_RE.test(n)) || new Set(names).size !== names.length) {
|
|
390
|
+
log('ignored a ShareOffer with bad share names');
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
const writable = new Set(Array.isArray(m.writable) ? m.writable.filter((n) => names.includes(n)) : []);
|
|
394
|
+
core.configure({ maxInflight: clampInt(m.max_inflight, 1, MAX_INFLIGHT), maxBytes: clampInt(m.max_bytes, MIN_BYTES, MAX_BYTES) });
|
|
395
|
+
for (const name of names) {
|
|
396
|
+
const fs = createShareFs(core, name, writable.has(name), abort.signal);
|
|
397
|
+
shares.set(name, fs);
|
|
398
|
+
Promise.resolve()
|
|
399
|
+
.then(() => onShare(name, fs, who()))
|
|
400
|
+
.catch((e) => log(`onShare(${JSON.stringify(name)}) threw: ${e?.message ?? e}`));
|
|
401
|
+
}
|
|
402
|
+
log(`shares offered: ${names.map((n) => `${n}${writable.has(n) ? ' (rw)' : ''}`).join(', ')}`);
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
return {
|
|
406
|
+
/** The shares offered so far, by name. */
|
|
407
|
+
shares,
|
|
408
|
+
stats: core.stats,
|
|
409
|
+
/** @returns {boolean} whether `m` was about shares (and has been dealt with). */
|
|
410
|
+
handle(m) {
|
|
411
|
+
switch (m.type) {
|
|
412
|
+
case MSG.SHARE_OFFER: offer(m); return true;
|
|
413
|
+
case MSG.SHARE_REPLY: core.reply(m); return true;
|
|
414
|
+
case MSG.SHARE_REQUEST: log('ignored a ShareRequest from the operator (only the host asks)'); return true;
|
|
415
|
+
default: return false;
|
|
416
|
+
}
|
|
417
|
+
},
|
|
418
|
+
close() { abort.abort(); core.close(); },
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/** Validate an `onShare` option (a function, or absent). */
|
|
423
|
+
export function validateOnShare(onShare, who) {
|
|
424
|
+
if (onShare !== undefined && onShare !== null && typeof onShare !== 'function') throw new TypeError(`${who}: onShare must be a function (name, fs, who) => void`);
|
|
425
|
+
}
|