@johnhenry/wsh 0.39.0 → 0.41.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.
@@ -23,6 +23,8 @@ 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';
27
+ import { refusalNotifier, validateOnRefused } from './refusal.mjs';
26
28
 
27
29
  const BACKOFF_START_MS = 500;
28
30
  const BACKOFF_MAX_MS = 30_000;
@@ -67,6 +69,12 @@ const BACKOFF_MAX_MS = 30_000;
67
69
  * plain message (it could inject an `Open`). Needs `e2e` (on by default) and `reportFeatures`. Without this option the
68
70
  * proof is requested when it can be and reported as `proven`, and the bridge is sealed only if the operator asks.
69
71
  * @param {number} [options.proofTimeoutMs=5000] - How long an operator has to answer the challenge.
72
+ * @param {(name: string, fs: object, who: { username: string | null, fingerprint: string | null }) => void | Promise<void>} [options.onShare]
73
+ * Folders an operator offers (`ShareOffer`, #159), once per share, as an object of async file operations. The Rust CLI
74
+ * offers shares on a direct or pipe-relayed session (`wsh --share`), not over `wsh reverse-connect` yet.
75
+ * @param {(refusal: { reason: string, who: { username?: string, fingerprint?: string, address?: string }, detail: string }) => void} [options.onRefused]
76
+ * #163: called when this host turns an operator away (`unauthorized` when `accept` says no, `busy`, `proof-required`,
77
+ * `proof-failed`, `not-sealed`, `seal-failed`; see `REFUSAL_REASONS`), with what is known of `who` and a human `detail`.
70
78
  * @param {(line: string) => void} [options.onLog]
71
79
  */
72
80
  export function createReverseHost(options = {}) {
@@ -81,8 +89,11 @@ export function createReverseHost(options = {}) {
81
89
  */
82
90
  export function createReverseHostWith({
83
91
  url, username, keyPair, accept, reconnect = true, connect = {}, peerType = 'host', reportFeatures = true, maxOperators = 1, e2e = {},
84
- requireOperatorProof = false, proofTimeoutMs = 5000, onLog = () => {},
92
+ requireOperatorProof = false, proofTimeoutMs = 5000, onLog = () => {}, onShare, onRefused,
85
93
  } = {}, backends) {
94
+ validateOnShare(onShare, 'createReverseHost');
95
+ validateOnRefused(onRefused, 'createReverseHost');
96
+ const notifyRefused = refusalNotifier(onRefused, onLog);
86
97
  if (typeof requireOperatorProof !== 'boolean') throw new TypeError('createReverseHost: requireOperatorProof must be a boolean');
87
98
  if (requireOperatorProof && e2e === false) throw new TypeError('createReverseHost: requireOperatorProof seals the bridge, which needs e2e (do not set e2e: false)');
88
99
  if (requireOperatorProof && !reportFeatures) throw new TypeError('createReverseHost: requireOperatorProof needs reportFeatures (the operator learns "e2e-sealed" from ReverseAccept.features)');
@@ -109,13 +120,13 @@ export function createReverseHostWith({
109
120
  });
110
121
  /** Features for `ReverseAccept` on this relay connection. */
111
122
  const bridgeFeatures = (c, e2eConfig, manyOperators) => [
112
- ...hostFeatures({ mcp: backends.mcp, files: backends.files, e2e: e2eConfig }, { dataStreams: false }),
123
+ ...hostFeatures({ mcp: backends.mcp, files: backends.files, e2e: e2eConfig, onShare }, { dataStreams: false }),
113
124
  ...(manyOperators ? [MULTI_OPERATOR_FEATURE] : []),
114
125
  ];
115
126
  const factory = createConnectionFactory({
116
127
  authorize: async () => false, methods: { pubkey: false, password: null }, hostKey: null, rateLimit: null,
117
128
  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}`),
129
+ sessions: null, relay: null, e2e: null, bindTimeoutMs: 3000, log: (l) => onLog(`[reverse] ${l}`), onShare,
119
130
  });
120
131
 
121
132
  let client = null;
@@ -158,8 +169,11 @@ export function createReverseHostWith({
158
169
  c.onReverseConnect = async (req) => {
159
170
  const from = req.from_fingerprint;
160
171
  const answer = (m) => c.sendRelayControl(m).catch(() => {});
161
- const refuse = (reason) => answer(reverseReject({ targetFingerprint: myFingerprint, username, reason }));
162
- if (typeof from !== 'string' || !from) { await refuse('busy: this host is already serving an operator'); return; }
172
+ const refuse = (reason, code = 'busy') => {
173
+ notifyRefused(code, { fingerprint: typeof from === 'string' ? from : undefined, username: req.username }, reason);
174
+ return answer(reverseReject({ targetFingerprint: myFingerprint, username, reason }));
175
+ };
176
+ if (typeof from !== 'string' || !from) { await refuse('busy: this host is already serving an operator', 'bad-request'); return; }
163
177
  if (bridges.has(from) || reserved.has(from)) { await refuse('busy: you already have a bridge with this host'); return; }
164
178
  if (bridges.size + reserved.size >= operatorLimit()) {
165
179
  await refuse(manyOperators() ? `busy: this host is already serving its maximum of ${maxOperators} operators` : 'busy: this host is already serving an operator');
@@ -170,20 +184,21 @@ export function createReverseHostWith({
170
184
  try {
171
185
  // Who is this operator? The relay says (`from`); with proof the operator says so itself (#117).
172
186
  const canProve = c.hasFeature(OPERATOR_PROOF_FEATURE) && Array.isArray(req.features) && req.features.includes(OPERATOR_PROOF_FEATURE);
173
- if (requireOperatorProof && !canProve) { await refuse('operator proof required'); return; }
187
+ if (requireOperatorProof && !canProve) { await refuse('operator proof required', 'proof-required'); return; }
174
188
  let proven = null;
175
189
  let challenge = null;
176
190
  if (canProve) {
177
191
  const outcome = await challengeOperator(c, from);
178
- if (outcome.error) { await refuse(outcome.error); return; }
192
+ if (outcome.error) { await refuse(outcome.error, 'proof-failed'); return; }
179
193
  ({ proven, challenge } = outcome);
180
194
  // The relay's claim and the operator's own must agree: a relay that rewrote from_fingerprint is caught here.
181
- if (proven.fingerprint !== from) { onLog(`[reverse] proof is by ${proven.fingerprint.slice(0, 12)}, the relay said ${from.slice(0, 12)}`); await refuse('operator proof does not match the identity the relay asserted'); return; }
182
- if (proven.username !== String(req.username ?? '')) { await refuse('operator proof names another username than the relay asserted'); return; }
195
+ if (proven.fingerprint !== from) { onLog(`[reverse] proof is by ${proven.fingerprint.slice(0, 12)}, the relay said ${from.slice(0, 12)}`); await refuse('operator proof does not match the identity the relay asserted', 'proof-failed'); return; }
196
+ if (proven.username !== String(req.username ?? '')) { await refuse('operator proof names another username than the relay asserted', 'proof-failed'); return; }
183
197
  }
184
198
  const who = { fingerprint: from, username: String(req.username ?? ''), proven: !!proven, ...(proven ? { publicKey: proven.publicKey } : {}) };
185
199
  try { ok = (await accept?.(who)) === true; } catch (e) { onLog(`[reverse] accept threw: ${e.message}`); }
186
- if (!ok || bridges.size >= operatorLimit()) { await refuse('not accepted'); return; }
200
+ if (!ok) { await refuse('not accepted', 'unauthorized'); return; }
201
+ if (bridges.size >= operatorLimit()) { await refuse('not accepted'); return; }
187
202
  c.trustRelayPeer(from);
188
203
  const bridge = makeBridge(c, from, String(req.username ?? 'operator'), proven, challenge);
189
204
  bridges.set(from, bridge);
@@ -248,7 +263,9 @@ export function createReverseHostWith({
248
263
  });
249
264
  let chain = Promise.resolve();
250
265
  let giveUp = null;
251
- const fail = (why) => { onLog(`[reverse] sealed bridge with ${from.slice(0, 12)} failed: ${why}`); endBridge(from); };
266
+ const who = { fingerprint: from, username: operatorName };
267
+ let unsealedReported = false;
268
+ const fail = (why) => { onLog(`[reverse] sealed bridge with ${from.slice(0, 12)} failed: ${why}`); notifyRefused('seal-failed', who, why); endBridge(from); };
252
269
  if (mustSeal) {
253
270
  giveUp = setTimeout(() => { if (!sealed) fail('no key exchange in time'); }, proofTimeoutMs * 2);
254
271
  giveUp.unref?.();
@@ -271,7 +288,11 @@ export function createReverseHostWith({
271
288
  }).catch((e) => fail(e.message));
272
289
  return;
273
290
  }
274
- if (mustSeal) { onLog(`[reverse] dropped a message that is not sealed (type ${msg.type}) on a bridge that must be`); return; }
291
+ if (mustSeal) {
292
+ onLog(`[reverse] dropped a message that is not sealed (type ${msg.type}) on a bridge that must be`);
293
+ if (!unsealedReported) { unsealedReported = true; notifyRefused('not-sealed', who, `a message that is not sealed (type ${msg.type}) on a bridge that must be`); }
294
+ return;
295
+ }
275
296
  base.receiveMessage(msg);
276
297
  },
277
298
  bindStream: (s) => base.bindStream?.(s),
@@ -35,7 +35,9 @@ import { OPERATOR_PROOF_FEATURE } from '../operator-proof.mjs';
35
35
  import { clientEnvFilter } from './client-env.mjs';
36
36
  import { acceptableBindings, bindingFeatures } from '../channel-binding.mjs';
37
37
  import { SealedBridge } from '../bridge-seal.mjs';
38
+ import { refusalNotifier, validateOnRefused } from '../refusal.mjs';
38
39
  import { HOST_KEY_PREFIX, HOST_KEY_SIG_PREFIX, findClientNonce, hostKeyProofMessage, toHex } from '../host-key.mjs';
40
+ import { SHARES_FEATURE, createShareSession } from '../shares.mjs';
39
41
 
40
42
  export const STREAM_ANNOUNCE = 'stream-announce';
41
43
  /** 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 +56,7 @@ export function hostFeatures(cfg, { dataStreams = true } = {}) {
54
56
  if (cfg.mcp) features.push(MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE);
55
57
  if (cfg.gateway) features.push(...gatewayFeatures(cfg.gateway));
56
58
  if (cfg.files) features.push('file-transfer', 'file-write', 'file-rename');
59
+ if (cfg.onShare) features.push(SHARES_FEATURE); // #159: this host can use folders the operator's client offers
57
60
  // End-to-end encryption (#90) is the virtual-mode EncryptedFrame layer, so it is offered where there are no
58
61
  // client-opened streams: over a relay bridge.
59
62
  // A relay carries a signed KeyExchange untouched, and (when configured) several operators per peer: peers read
@@ -122,6 +125,8 @@ export function createConnectionFactory(cfg) {
122
125
  bindTimeoutMs: cfg.bindTimeoutMs ?? 3000,
123
126
  log: cfg.log ?? (() => {}),
124
127
  };
128
+ validateOnRefused(cfg.onRefused, 'createConnectionFactory');
129
+ const notifyRefused = refusalNotifier(cfg.onRefused, cfg.log);
125
130
  let counter = 0;
126
131
  // What a client may put in `Open.env` (#126): an allow-list unless the host says otherwise.
127
132
  const execEnv = clientEnvFilter(cfg.execOptions?.clientEnv);
@@ -177,6 +182,11 @@ export function createConnectionFactory(cfg) {
177
182
  ? cfg.createGatewaySession(cfg.gateway, (m) => send(m), log, { who: () => ({ username: state.username, fingerprint: state.fingerprint }), datagrams })
178
183
  : null;
179
184
 
185
+ // Operator-side shared folders (#159): created with the connection, used only after the client's ShareOffer.
186
+ const shares = cfg.onShare
187
+ ? createShareSession({ send: (m) => send(m), onShare: cfg.onShare, who: () => ({ username: state.username, fingerprint: state.fingerprint }), log, timeoutMs: cfg.shareTimeoutMs })
188
+ : null;
189
+
180
190
  const qmux = sendMessage ? null : new QMuxConnection({ isClient: false, send: (b) => { if (!state.closed) sendBytes(b); } });
181
191
 
182
192
  // ── End-to-end encryption (#90) ──────────────────────────────────
@@ -240,6 +250,7 @@ export function createConnectionFactory(cfg) {
240
250
  channels.clear();
241
251
  responder?.close();
242
252
  gateway?.close();
253
+ shares?.close();
243
254
  e2eSessions.clear();
244
255
  for (const c of mcpCalls) c.abort(new Error('connection closed'));
245
256
  mcpCalls.clear();
@@ -295,6 +306,7 @@ export function createConnectionFactory(cfg) {
295
306
  }
296
307
  if (await handleRelay(m)) return;
297
308
  if (gateway && await gateway.handle(m)) return;
309
+ if (shares && shares.handle(m)) return;
298
310
  switch (m.type) {
299
311
  case MSG.PING: return send(pong({ id: m.id }));
300
312
  case MSG.OPEN: return handleOpen(m);
@@ -372,8 +384,17 @@ export function createConnectionFactory(cfg) {
372
384
  await send(authOk({ sessionId: state.sessionId, token: randomBytes(16), ttl: Math.ceil(ttlMs / 1000) }));
373
385
  }
374
386
 
375
- async function refuse(reason) {
387
+ /** Tell the embedder (`onRefused`, #163) once per connection that this peer was turned away. */
388
+ let refusalReported = false;
389
+ function reportRefused(code, detail, extra = {}) {
390
+ if (refusalReported) return;
391
+ refusalReported = true;
392
+ notifyRefused(code, { username: state.username, fingerprint: state.fingerprint, address: remote.address, ...extra }, detail);
393
+ }
394
+
395
+ async function refuse(reason, code = 'bad-request', who) {
376
396
  log(`AUTH_FAIL: ${reason}`);
397
+ reportRefused(code, reason, who);
377
398
  await send(authFail({ reason }));
378
399
  setTimeout(() => shutdown('auth failed'), 50);
379
400
  }
@@ -384,13 +405,13 @@ export function createConnectionFactory(cfg) {
384
405
  if (!USERNAME_RE.test(user)) return refuse(`bad username ${JSON.stringify(user)}`);
385
406
  const method = m.auth_method || 'pubkey';
386
407
  if (method === 'password') {
387
- if (!cfg.methods.password) return refuse('password auth is not enabled on this host');
408
+ if (!cfg.methods.password) return refuse('password auth is not enabled on this host', 'method-disabled', { username: user });
388
409
  } else if (method === 'pubkey') {
389
- if (!cfg.methods.pubkey) return refuse('pubkey auth is not enabled on this host');
410
+ if (!cfg.methods.pubkey) return refuse('pubkey auth is not enabled on this host', 'method-disabled', { username: user });
390
411
  } else {
391
- return refuse(`unsupported auth method ${JSON.stringify(method)}`);
412
+ return refuse(`unsupported auth method ${JSON.stringify(method)}`, 'bad-request', { username: user });
392
413
  }
393
- if (cfg.sealSession === 'require' && cfg.hostKey && !dataStreams && method !== 'pubkey') return refuse('this host requires a sealed session, which needs a key login');
414
+ if (cfg.sealSession === 'require' && cfg.hostKey && !dataStreams && method !== 'pubkey') return refuse('this host requires a sealed session, which needs a key login', 'not-sealed', { username: user });
394
415
  state.username = user;
395
416
  state.method = method;
396
417
  gateway?.setPeerFeatures(m.features);
@@ -436,6 +457,7 @@ export function createConnectionFactory(cfg) {
436
457
  fp = await fingerprint(m.public_key);
437
458
  key = await importPublicKeyRaw(m.public_key);
438
459
  } catch { return refuse('malformed public key'); }
460
+ const claimed = { fingerprint: fp };
439
461
  // Verify the signature first: nothing about who is on the allowlist
440
462
  // is revealed to a caller who cannot even prove they hold a key.
441
463
  // The signature may be over the empty binding (a client that knows nothing of #119, or a browser that can
@@ -454,16 +476,16 @@ export function createConnectionFactory(cfg) {
454
476
  if (required) {
455
477
  let unbound = false;
456
478
  try { unbound = await verifyChallenge(key, m.signature, state.sessionId, state.nonce, { username: state.username }); } catch { /* not that either */ }
457
- if (unbound) return refuse('channel binding required: the signature is not bound to this connection');
479
+ if (unbound) return refuse('channel binding required: the signature is not bound to this connection', 'binding-required', claimed);
458
480
  }
459
- return refuse('signature does not verify over the transcript');
481
+ return refuse('signature does not verify over the transcript', 'bad-signature', claimed);
460
482
  }
461
483
  state.channelBinding = boundKinds;
462
484
  let allowed = false;
463
485
  try {
464
486
  allowed = await cfg.authorize({ username: state.username, fingerprint: fp, publicKey: m.public_key });
465
487
  } catch (e) { log(`authorize threw: ${e.message}`); }
466
- if (!allowed) return refuse('key not authorized');
488
+ if (!allowed) return refuse('key not authorized', 'unauthorized', claimed);
467
489
  state.authed = true;
468
490
  state.fingerprint = fp;
469
491
  state.publicKey = m.public_key;
@@ -484,12 +506,13 @@ export function createConnectionFactory(cfg) {
484
506
  if (!sealed.bridge.isFrame(m)) { log(`dropped a plaintext message (type ${m.type}) on a sealed session`); return undefined; }
485
507
  try { return await sealed.bridge.open(m); } catch (e) {
486
508
  log(`a sealed frame did not open (${e.message}): closing the session`);
509
+ reportRefused('seal-failed', `a sealed frame did not open: ${e.message}`);
487
510
  shutdown('sealed frame did not open');
488
511
  return undefined;
489
512
  }
490
513
  }
491
514
  if (m.type === MSG.KEY_EXCHANGE && m.session_id === state.sessionId) {
492
- if (!state.publicKey) { log('sealed session refused: no login key to authenticate the initiator with'); shutdown('sealed session needs a key login'); return undefined; }
515
+ if (!state.publicKey) { log('sealed session refused: no login key to authenticate the initiator with'); reportRefused('seal-failed', 'no login key to authenticate the initiator with'); shutdown('sealed session needs a key login'); return undefined; }
493
516
  sealed.responder ??= new E2EResponder({
494
517
  signKey: cfg.hostKey, hybrid: true, identity: cfg.hostKey.publicKey,
495
518
  initiator: { publicKey: state.publicKey, require: true },
@@ -500,12 +523,13 @@ export function createConnectionFactory(cfg) {
500
523
  sealed.bridge = new SealedBridge({ key: result.key, sessionId: state.sessionId, role: 'responder', scope: 'session' });
501
524
  log(`session sealed${result.hybrid ? ' (hybrid)' : ''}`);
502
525
  }
503
- } catch (e) { log(`sealed session refused: ${e.message}`); shutdown('sealed session key exchange failed'); }
526
+ } catch (e) { log(`sealed session refused: ${e.message}`); reportRefused('seal-failed', `key exchange failed: ${e.message}`); shutdown('sealed session key exchange failed'); }
504
527
  return undefined;
505
528
  }
506
529
  if (m.type === MSG.PING) return m;
507
530
  if (sealRequired) {
508
531
  log(`refused a plaintext message (type ${m.type}): this host requires a sealed session`);
532
+ reportRefused('not-sealed', `a plaintext message (type ${m.type}) on a host that requires a sealed session`);
509
533
  await deliverRaw(errorMsg({ code: 1, message: 'this host requires a sealed session (e2e-session-required)' }));
510
534
  setTimeout(() => shutdown('sealed session required'), 50);
511
535
  return undefined;
@@ -515,20 +539,20 @@ export function createConnectionFactory(cfg) {
515
539
 
516
540
  async function handlePasswordAuth(m) {
517
541
  state.awaitingPassword = false; // one guess per connection
518
- if (m.method !== 'password' || typeof m.password !== 'string') return refuse('expected a password AUTH');
542
+ if (m.method !== 'password' || typeof m.password !== 'string') return refuse('expected a password AUTH', 'bad-request');
519
543
  const rl = cfg.rateLimit;
520
544
  const key = rl.key({ address: remote.address, headers: remote.headers, username: state.username });
521
545
  const locked = rl.limiter.lockedFor(key);
522
546
  if (locked > 0) {
523
547
  // Not even evaluated: a locked-out caller learns nothing and costs nothing.
524
- return refuse(`too many failed attempts; try again in ${Math.ceil(locked / 1000)}s`);
548
+ return refuse(`too many failed attempts; try again in ${Math.ceil(locked / 1000)}s`, 'rate-limited');
525
549
  }
526
550
  let ok = false;
527
551
  try { ok = (await cfg.methods.password(state.username, m.password)) === true; } catch (e) { log(`password check threw: ${e.message}`); }
528
552
  if (!ok) {
529
553
  rl.limiter.fail(key);
530
554
  if (rl.failureDelayMs > 0) await new Promise((r) => setTimeout(r, rl.failureDelayMs));
531
- return refuse('authentication failed');
555
+ return refuse('authentication failed', 'unauthorized');
532
556
  }
533
557
  rl.limiter.succeed(key);
534
558
  state.authed = true;
@@ -480,6 +480,13 @@ 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;
488
+ /** #163: told once per connection this host turned away (an operator, on a reverse host), with a stable reason code (`REFUSAL_REASONS`, from `@johnhenry/wsh/host`). */
489
+ onRefused?: import('../host.js').WshOnRefused;
483
490
  onLog?: (line: string) => void;
484
491
  }
485
492
 
@@ -628,6 +635,10 @@ export interface WshReverseHostOptions {
628
635
  requireOperatorProof?: boolean;
629
636
  /** How long an operator has to answer the challenge (default 5000). */
630
637
  proofTimeoutMs?: number;
638
+ /** Folders an operator offers over a bridge (#159), once per share, as an object of async file operations. */
639
+ onShare?: import('../host.js').WshOnShare;
640
+ /** #163: told once per connection this host turned away (an operator, on a reverse host), with a stable reason code (`REFUSAL_REASONS`, from `@johnhenry/wsh/host`). */
641
+ onRefused?: import('../host.js').WshOnRefused;
631
642
  onLog?: (line: string) => void;
632
643
  }
633
644
 
@@ -15,6 +15,8 @@ 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';
19
+ import { validateOnRefused } from '../refusal.mjs';
18
20
  import { normalizeGateway, createGatewaySession } from './gateway.mjs';
19
21
  import { createRpcHost, mcpServerAdapter } from './rpc.mjs';
20
22
  import { bindSocket } from './socket.mjs';
@@ -93,12 +95,21 @@ function tlsChannelBinding(socket) {
93
95
  * this connection (#119): `true` needs any binding kind, an array names kinds that must all be bound (`host` needs
94
96
  * `hostKey`; `tls-exporter` needs `wss://` served by this process, not a TLS-terminating proxy; `cert-hash` needs
95
97
  * WebTransport with `selfSigned`). Clients older than 0.36 cannot satisfy it. Off by default.
98
+ * @param {(name: string, fs: object, who: { username: string | null, fingerprint: string | null }) => void | Promise<void>} [options.onShare]
99
+ * Folders of the operator's machine (`wsh --share`, #159), once per share, as an object of async file operations to mount;
100
+ * listing it makes the host state the `shares` feature. As for `createMemoryHost`.
101
+ * @param {(refusal: { reason: string, who: { username?: string, fingerprint?: string, address?: string }, detail: string }) => void} [options.onRefused]
102
+ * Called once per connection this host turned away, with a stable `reason` code (`REFUSAL_REASONS`, from
103
+ * `@johnhenry/wsh/host`), what is known of `who` and a human `detail`. As for `createMemoryHost`.
96
104
  * @param {(line: string) => void} [options.onLog]
97
105
  * @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
106
  */
99
107
  export function createWshServer({
100
108
  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 = () => {},
109
+ onShare, onRefused,
101
110
  } = {}) {
111
+ validateOnShare(onShare, 'createWshServer');
112
+ validateOnRefused(onRefused, 'createWshServer');
102
113
  if (sealSession !== false && sealSession !== 'offer' && sealSession !== 'require') throw new TypeError("createWshServer: sealSession must be false, 'offer' or 'require'");
103
114
  if (sealSession && !hostKey) throw new TypeError('createWshServer: sealSession needs a hostKey (the host signs its half of the key exchange with it)');
104
115
  if (requireChannelBinding !== false && requireChannelBinding !== true && !(Array.isArray(requireChannelBinding) && requireChannelBinding.every((k) => CHANNEL_BINDING_KINDS.includes(k)))) {
@@ -152,6 +163,7 @@ export function createWshServer({
152
163
  return createConnectionFactory({
153
164
  authorize, execRunner, execOptions, pty: ptyConfig, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, sealSession, log: onLog,
154
165
  methods, hostKey: host_, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, gateway: gatewayCfg, createGatewaySession, sessions: registry, relay: hub,
166
+ onShare, onRefused,
155
167
  });
156
168
  })();
157
169
  ready.catch(() => { ready = null; });