@johnhenry/wsh 0.44.1 → 0.46.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 +382 -39
- package/bin/wsh-mcp.mjs +3 -1
- package/package.json +13 -1
- package/src/cbor.mjs +40 -7
- package/src/client.mjs +79 -20
- package/src/errors.mjs +90 -0
- package/src/host-backends.mjs +23 -0
- package/src/host.d.ts +1 -1
- package/src/index.d.ts +68 -0
- package/src/index.mjs +5 -0
- package/src/key-options.mjs +3 -1
- package/src/mcp-stdio.d.ts +2 -0
- package/src/mcp-stdio.mjs +4 -2
- package/src/memory-host.d.ts +12 -1
- package/src/memory-host.mjs +8 -21
- package/src/messages.gen.mjs +1 -0
- package/src/objects-core.mjs +805 -0
- package/src/objects.d.ts +152 -0
- package/src/objects.mjs +97 -0
- package/src/page-host.d.ts +213 -0
- package/src/page-host.mjs +381 -0
- package/src/pipe-relay-node.mjs +43 -0
- package/src/pipe-relay.d.ts +19 -4
- package/src/pipe-relay.mjs +108 -39
- package/src/reverse-host.d.ts +4 -0
- package/src/reverse-host.mjs +14 -4
- package/src/rpc-virtual.mjs +127 -0
- package/src/rpc.mjs +34 -2
- package/src/server/connection.mjs +70 -10
- package/src/server/index.d.ts +41 -2
- package/src/server/index.mjs +5 -2
- package/src/server/password.mjs +142 -0
- package/src/server/reverse-host.mjs +7 -2
- package/src/server/username.mjs +57 -0
- package/src/session.mjs +2 -1
- package/src/testing.d.ts +50 -0
- package/src/testing.mjs +27 -0
- package/src/webmcp.mjs +694 -0
|
@@ -19,7 +19,7 @@ import {
|
|
|
19
19
|
MSG, serverHello, challenge, authOk, authFail, openOk, openFail, sessionData,
|
|
20
20
|
exit as exitMsg, close as closeMsg, encryptedFrame as encryptedFrameMsg, pong, fileResult, fileChunk, mcpTools, mcpResult,
|
|
21
21
|
presence as presenceMsg, error as errorMsg, sessionList, detachOk, detachFail, reversePeers, reverseReject,
|
|
22
|
-
targetList as targetListMsg, gatewayFail, listenFail,
|
|
22
|
+
targetList as targetListMsg, gatewayFail, listenFail, gatewayCredit,
|
|
23
23
|
} from '../messages.gen.mjs';
|
|
24
24
|
import {
|
|
25
25
|
generateNonce, verifyChallenge, fingerprint, importPublicKeyRaw,
|
|
@@ -27,7 +27,8 @@ import {
|
|
|
27
27
|
import { FILE_CHUNK_BYTES, MAX_ATTACHMENTS } from './constants.mjs';
|
|
28
28
|
import { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, SESSION_SEAL_FEATURE, SESSION_SEAL_REQUIRED_FEATURE, TARGETS_FEATURE } from '../features.mjs';
|
|
29
29
|
import { TARGET_NAME_RE } from '../host-backends.mjs';
|
|
30
|
-
import { RpcChannel, RPC_FEATURE, RPC_MAX_MESSAGE_PREFIX, rpcProtocolFeature } from '../rpc.mjs';
|
|
30
|
+
import { RpcChannel, RPC_FEATURE, RPC_VIRTUAL_FEATURE, RPC_MAX_MESSAGE_PREFIX, rpcProtocolFeature } from '../rpc.mjs';
|
|
31
|
+
import { RpcCreditLink, rpcChannelOfCredit, rpcCreditId } from '../rpc-virtual.mjs';
|
|
31
32
|
import { sealFrame, openFrame, ROLE_TAGS } from '../e2e-frame.mjs';
|
|
32
33
|
import { E2EResponder, E2E_FEATURE, E2E_SIGN_FEATURE } from '../e2e-exchange.mjs';
|
|
33
34
|
import { MULTI_OPERATOR_FEATURE } from './relay.mjs';
|
|
@@ -40,6 +41,7 @@ import { SealedBridge } from '../bridge-seal.mjs';
|
|
|
40
41
|
import { refusalNotifier, validateOnRefused } from '../refusal.mjs';
|
|
41
42
|
import { HOST_KEY_PREFIX, HOST_KEY_SIG_PREFIX, findClientNonce, hostKeyProofMessage, toHex } from '../host-key.mjs';
|
|
42
43
|
import { checkKeyRequest } from '../key-options.mjs';
|
|
44
|
+
import { resolveUsernamePattern, usernameAllowed } from './username.mjs';
|
|
43
45
|
import { SHARES_FEATURE, createShareSession } from '../shares.mjs';
|
|
44
46
|
|
|
45
47
|
export const STREAM_ANNOUNCE = 'stream-announce';
|
|
@@ -48,7 +50,7 @@ export { SESSION_SEAL_FEATURE, SESSION_SEAL_REQUIRED_FEATURE };
|
|
|
48
50
|
/**
|
|
49
51
|
* The features a host built from `cfg` advertises (`ServerHello.features`, minus the host-key proof).
|
|
50
52
|
* Over a relay bridge (`dataStreams: false`) there are no client-opened streams, so the
|
|
51
|
-
*
|
|
53
|
+
* `stream-announce` is not offered and rpc is stated as `rpc-virtual` (#191) instead of `rpc`; a reverse host reports this
|
|
52
54
|
* list to the operator in `ReverseAccept.features`.
|
|
53
55
|
*/
|
|
54
56
|
export function hostFeatures(cfg, { dataStreams = true } = {}) {
|
|
@@ -74,8 +76,10 @@ export function hostFeatures(cfg, { dataStreams = true } = {}) {
|
|
|
74
76
|
if (cfg.e2e && !dataStreams) features.push(E2E_FEATURE, ...(cfg.e2e.signKey ? [E2E_SIGN_FEATURE] : []));
|
|
75
77
|
// A sealed session (#155) needs the host's identity to sign its half, and no client-opened streams (their bytes are not frames).
|
|
76
78
|
if (cfg.sealSession && cfg.hostKey && !dataStreams) features.push(SESSION_SEAL_FEATURE, ...(cfg.sealSession === 'require' ? [SESSION_SEAL_REQUIRED_FEATURE] : []));
|
|
77
|
-
|
|
78
|
-
|
|
79
|
+
// rpc (#85) rides a client-opened data stream; where there is none (a relay bridge, a sealed session) it rides the control
|
|
80
|
+
// plane (#191). A host states one form per connection: a peer that only knows `rpc` never opens a channel it cannot carry.
|
|
81
|
+
if (cfg.rpc && cfg.rpc.protocols.size) {
|
|
82
|
+
features.push(dataStreams ? RPC_FEATURE : RPC_VIRTUAL_FEATURE, ...[...cfg.rpc.protocols.keys()].map(rpcProtocolFeature), RPC_MAX_MESSAGE_PREFIX + cfg.rpc.maxMessageBytes);
|
|
79
83
|
}
|
|
80
84
|
return features;
|
|
81
85
|
}
|
|
@@ -85,7 +89,6 @@ const WRITE_IDLE_MS = 30_000;
|
|
|
85
89
|
|
|
86
90
|
const MAX_CHANNELS = 64;
|
|
87
91
|
const REPLAY_CHUNK_BYTES = 32 * 1024;
|
|
88
|
-
const USERNAME_RE = /^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/;
|
|
89
92
|
const enc = new TextEncoder();
|
|
90
93
|
|
|
91
94
|
const randomUUID = () => crypto.randomUUID();
|
|
@@ -130,6 +133,7 @@ export function createConnectionFactory(cfg) {
|
|
|
130
133
|
methods: cfg.methods ?? { pubkey: true, password: null },
|
|
131
134
|
bindTimeoutMs: cfg.bindTimeoutMs ?? 3000,
|
|
132
135
|
log: cfg.log ?? (() => {}),
|
|
136
|
+
usernamePattern: resolveUsernamePattern(cfg.usernamePattern, 'createConnectionFactory'),
|
|
133
137
|
};
|
|
134
138
|
validateOnRefused(cfg.onRefused, 'createConnectionFactory');
|
|
135
139
|
const notifyRefused = refusalNotifier(cfg.onRefused, cfg.log);
|
|
@@ -213,6 +217,13 @@ export function createConnectionFactory(cfg) {
|
|
|
213
217
|
const keyRefusal = (req) => refusalOf(req, false);
|
|
214
218
|
/** Whether this request would be allowed, without saying anything about it (what a discovery answer lists). */
|
|
215
219
|
const keyAllows = (req) => refusalOf(req, true) === null;
|
|
220
|
+
/**
|
|
221
|
+
* What an rpc handler is told of the key it serves (additive): the capability list of the key (`null` for a key with none), and
|
|
222
|
+
* `permits(request, { now })`, whether the key's options and capabilities allow a request such as `{ kind: 'mcp-tool', tool }`,
|
|
223
|
+
* asked afresh each time (an expiry is honoured), without a refusal being reported. `permits` is the authority; the list is for display.
|
|
224
|
+
*/
|
|
225
|
+
const keyCapabilities = () => { for (const p of permissionSets()) if (Array.isArray(p.capabilities)) return p.capabilities.slice(); return null; };
|
|
226
|
+
const permits = (req, { now } = {}) => permissionSets().every((perms) => !checkKeyRequest(perms, req, { now }));
|
|
216
227
|
/** The reply that refuses a gateway message the key's capabilities do not cover (`GatewayFail` / `ListenFail`), or null. */
|
|
217
228
|
function gatewayRefusal(m) {
|
|
218
229
|
let req; let listener = false;
|
|
@@ -392,6 +403,11 @@ export function createConnectionFactory(cfg) {
|
|
|
392
403
|
m = inner;
|
|
393
404
|
}
|
|
394
405
|
if (await handleRelay(m)) return;
|
|
406
|
+
// Credit for a virtual-mode rpc channel (#191) is a GatewayCredit in a number space of its own; it is never the gateway's.
|
|
407
|
+
if (m.type === MSG.GATEWAY_CREDIT && rpcChannelOfCredit(m.gateway_id) !== undefined) {
|
|
408
|
+
channels.get(rpcChannelOfCredit(m.gateway_id))?.credit?.(m.bytes);
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
395
411
|
if (gateway) {
|
|
396
412
|
// What the key's capabilities allow of the gateway (#122), before the gateway's own policy is asked.
|
|
397
413
|
const refusal = gatewayRefusal(m);
|
|
@@ -495,7 +511,7 @@ export function createConnectionFactory(cfg) {
|
|
|
495
511
|
async function handleAuth(m) {
|
|
496
512
|
if (m.type === MSG.HELLO) {
|
|
497
513
|
const user = String(m.username ?? '');
|
|
498
|
-
if (!
|
|
514
|
+
if (!usernameAllowed(cfg.usernamePattern, user)) return refuse(`bad username ${JSON.stringify(user)}`);
|
|
499
515
|
const method = m.auth_method || 'pubkey';
|
|
500
516
|
if (method === 'password') {
|
|
501
517
|
if (!cfg.methods.password) return refuse('password auth is not enabled on this host', 'method-disabled', { username: user });
|
|
@@ -844,7 +860,8 @@ export function createConnectionFactory(cfg) {
|
|
|
844
860
|
if (target !== undefined) return send(openFail({ reason: 'rpc channels do not take a target' }));
|
|
845
861
|
if (requireTarget) return send(openFail({ reason: 'a target is required' }));
|
|
846
862
|
{
|
|
847
|
-
const
|
|
863
|
+
const protocol = typeof m.command === 'string' ? m.command : '';
|
|
864
|
+
const refusal = keyRefusal({ kind: 'open', channel: 'rpc', protocol, scoped: cfg.rpc?.protocols.get(protocol)?.capabilityScoped === true });
|
|
848
865
|
if (refusal) return send(openFail({ reason: refusal.reason }));
|
|
849
866
|
}
|
|
850
867
|
return openRpc(m);
|
|
@@ -1119,10 +1136,11 @@ export function createConnectionFactory(cfg) {
|
|
|
1119
1136
|
const rpc = cfg.rpc;
|
|
1120
1137
|
const protocol = typeof m.command === 'string' ? m.command : '';
|
|
1121
1138
|
const handler = rpc?.protocols.get(protocol);
|
|
1122
|
-
if (!rpc || !
|
|
1123
|
-
const why = !rpc
|
|
1139
|
+
if (!rpc || !handler) {
|
|
1140
|
+
const why = !rpc ? 'rpc is not enabled on this server' : `protocol "${protocol}" is not supported by this server`;
|
|
1124
1141
|
return send(openFail({ reason: `UNSUPPORTED_PROTOCOL: ${why}` }));
|
|
1125
1142
|
}
|
|
1143
|
+
if (!dataStreams) return openRpcVirtual(m, protocol, handler, rpc);
|
|
1126
1144
|
const channelId = ++state.nextChannel;
|
|
1127
1145
|
let chan = null;
|
|
1128
1146
|
let stream = null;
|
|
@@ -1148,6 +1166,7 @@ export function createConnectionFactory(cfg) {
|
|
|
1148
1166
|
const ctx = {
|
|
1149
1167
|
protocol, channelId, user: state.username, fingerprint: state.fingerprint, remote,
|
|
1150
1168
|
features: state.features ?? [], hostFingerprint: state.hostFingerprint,
|
|
1169
|
+
capabilities: keyCapabilities(), permits,
|
|
1151
1170
|
log: (line) => log(`rpc ${protocol} channel ${channelId}: ${line}`),
|
|
1152
1171
|
};
|
|
1153
1172
|
// Inbound messages wait until the handler (possibly async) has registered its methods.
|
|
@@ -1166,6 +1185,47 @@ export function createConnectionFactory(cfg) {
|
|
|
1166
1185
|
log(`rpc channel ${channelId}: ${protocol}`);
|
|
1167
1186
|
}
|
|
1168
1187
|
|
|
1188
|
+
// An rpc channel in virtual data mode (#191): the same CBOR sequence of JSON-RPC messages, carried as SessionData (and so
|
|
1189
|
+
// inside EncryptedFrame on a sealed session) and metered by credit, because the control plane has no flow control of its own.
|
|
1190
|
+
async function openRpcVirtual(m, protocol, handler, rpc) {
|
|
1191
|
+
const channelId = ++state.nextChannel;
|
|
1192
|
+
let chan = null;
|
|
1193
|
+
const link = new RpcCreditLink({
|
|
1194
|
+
sendData: (bytes) => send(sessionData({ channelId, data: bytes })),
|
|
1195
|
+
sendCredit: (n) => send(gatewayCredit({ gatewayId: rpcCreditId(channelId), bytes: n })),
|
|
1196
|
+
onViolation: (why) => { log(`rpc ${protocol} channel ${channelId}: ${why}; closing it`); void chan?.close('credit-violation'); },
|
|
1197
|
+
});
|
|
1198
|
+
chan = new RpcChannel({
|
|
1199
|
+
maxMessageBytes: rpc.maxMessageBytes,
|
|
1200
|
+
maxInflight: rpc.maxInflight,
|
|
1201
|
+
write: (bytes) => link.write(bytes),
|
|
1202
|
+
onConsumed: (n) => link.consumed(n),
|
|
1203
|
+
close: async () => { link.close(); await finishChannel(channelId, 0); },
|
|
1204
|
+
});
|
|
1205
|
+
channels.set(channelId, {
|
|
1206
|
+
kill: () => { channels.delete(channelId); link.close(); chan.handleClose('peer-closed'); },
|
|
1207
|
+
input: (d) => { if (d?.length && link.receive(d.length)) chan.feed(d); },
|
|
1208
|
+
credit: (n) => link.grant(n),
|
|
1209
|
+
});
|
|
1210
|
+
const ctx = {
|
|
1211
|
+
protocol, channelId, user: state.username, fingerprint: state.fingerprint, remote,
|
|
1212
|
+
features: state.features ?? [], hostFingerprint: state.hostFingerprint,
|
|
1213
|
+
capabilities: keyCapabilities(), permits,
|
|
1214
|
+
log: (line) => log(`rpc ${protocol} channel ${channelId}: ${line}`),
|
|
1215
|
+
};
|
|
1216
|
+
// Inbound messages wait until the handler (possibly async) has registered its methods; the handler starts only after
|
|
1217
|
+
// OpenOk is on its way, so nothing it sends can reach a client that does not have the channel yet.
|
|
1218
|
+
chan.hold();
|
|
1219
|
+
await send(openOk({ channelId, dataMode: 'virtual', capabilities: [] }));
|
|
1220
|
+
log(`rpc channel ${channelId}: ${protocol} (virtual)`);
|
|
1221
|
+
let ready;
|
|
1222
|
+
try { ready = Promise.resolve(handler(chan, ctx)); } catch (e) { ready = Promise.reject(e); }
|
|
1223
|
+
ready.then(() => chan.release(), (e) => {
|
|
1224
|
+
log(`rpc ${protocol} channel ${channelId}: handler failed: ${e?.message ?? e}`);
|
|
1225
|
+
void chan.close('handler-error');
|
|
1226
|
+
});
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1169
1229
|
async function openPty(m, b, target) {
|
|
1170
1230
|
if (!b.pty) return send(openFail({ reason: `pty is not enabled ${b.ownHost ? 'on this server' : 'for this target'}` }));
|
|
1171
1231
|
const channelId = ++state.nextChannel;
|
package/src/server/index.d.ts
CHANGED
|
@@ -412,6 +412,23 @@ export interface WshSelfSignedCertificate {
|
|
|
412
412
|
/** A dependency-free self-signed ECDSA P-256 certificate fit for WebTransport's `serverCertificateHashes`. */
|
|
413
413
|
export function generateSelfSignedCertificate(opts?: { hosts?: string[]; validityDays?: number; now?: Date }): WshSelfSignedCertificate;
|
|
414
414
|
|
|
415
|
+
/**
|
|
416
|
+
* Hash a password for `passwordVerifier`: scrypt (`node:crypto`), a random per-user salt, a PHC string
|
|
417
|
+
* (`$scrypt$ln=16,r=8,p=1$<salt>$<hash>`). The default cost is 64 MiB; `ln` is log2 of N (10 to 22, and at most 256 MiB in all).
|
|
418
|
+
*/
|
|
419
|
+
export function hashPassword(password: string, opts?: { ln?: number; r?: number; p?: number }): Promise<string>;
|
|
420
|
+
/** Does `password` match a `hashPassword` value? False for anything else (never throws on the stored value); compared in constant time. */
|
|
421
|
+
export function verifyPassword(password: string, stored: string): Promise<boolean>;
|
|
422
|
+
/**
|
|
423
|
+
* An `auth.password` callback over stored `hashPassword` values: an unknown user costs the same derivation as a wrong password,
|
|
424
|
+
* and an entry that is not a `hashPassword` value is refused with `onWarn` naming the user (default `console.warn`; never the
|
|
425
|
+
* stored value). An old unsalted `sha256:<hex>` entry is refused unless `allowLegacySha256` is set.
|
|
426
|
+
*/
|
|
427
|
+
export function passwordVerifier(
|
|
428
|
+
hashes: Record<string, string> | Map<string, string> | ((username: string) => string | undefined | Promise<string | undefined>),
|
|
429
|
+
opts?: { allowLegacySha256?: boolean; onWarn?: (message: string) => void },
|
|
430
|
+
): (username: string, password: string) => Promise<boolean>;
|
|
431
|
+
|
|
415
432
|
export interface WshServerOptions {
|
|
416
433
|
/** Bind address (default `127.0.0.1`). */
|
|
417
434
|
host?: string;
|
|
@@ -512,6 +529,13 @@ export interface WshServerOptions {
|
|
|
512
529
|
targets?: Record<string, Omit<import('../host.js').WshTargetOptions, 'exec' | 'fs'> & { exec?: true | WshServerExecOptions | WshExecRunner; fs?: WshServerFsOptions | import('../host.js').WshFileBackend }>;
|
|
513
530
|
/** With `targets`: an `Open`, `FileOp` or `OpenEndpoint` that names no target is refused, so nothing runs on the host itself (`rpc` channels too). Does not cover the gateway, MCP or `Attach`. */
|
|
514
531
|
requireTarget?: boolean;
|
|
532
|
+
/**
|
|
533
|
+
* Which login names this host admits (a RegExp, or a pattern string). Default `/^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/`, the shape of an
|
|
534
|
+
* OS account name, because a name reaches `exec` environments and file paths. A host that does not map names to OS accounts can
|
|
535
|
+
* admit its own shape, e.g. `/^[A-Za-z0-9_-]{1,64}$/` for base64url identity hashes. Whatever the pattern, a name is 1 to 256
|
|
536
|
+
* characters with no control character, no `/` and no `\`, and the pattern may not match the empty name.
|
|
537
|
+
*/
|
|
538
|
+
usernamePattern?: RegExp | string;
|
|
515
539
|
onLog?: (line: string) => void;
|
|
516
540
|
}
|
|
517
541
|
|
|
@@ -525,11 +549,22 @@ export interface WshRpcContext {
|
|
|
525
549
|
/** The exact `ServerHello.features` this connection received. */
|
|
526
550
|
features: string[];
|
|
527
551
|
hostFingerprint: string | null;
|
|
552
|
+
/** The capability list of the key this channel serves (`capabilities="..."` in its `authorized_keys` line, or what `authorize` granted), or `null` for a key with none. For display: `permits` decides. */
|
|
553
|
+
capabilities: string[] | null;
|
|
554
|
+
/**
|
|
555
|
+
* Whether the key's options and capabilities allow a request such as `{ kind: 'mcp-tool', tool: 'search' }`, asked afresh each call (an
|
|
556
|
+
* `expires` is honoured; `now` is epoch seconds). Nothing is reported to `onRefused`. A handler that narrows by capability this way
|
|
557
|
+
* sets `capabilityScoped = true` on itself, so that a key which names tools (`mcp:search`) but not `mcp:*` may open the `mcp` channel.
|
|
558
|
+
*/
|
|
559
|
+
permits(request: { kind: string; [field: string]: unknown }, options?: { now?: number }): boolean;
|
|
528
560
|
log(line: string): void;
|
|
529
561
|
}
|
|
530
562
|
|
|
531
|
-
/**
|
|
532
|
-
|
|
563
|
+
/**
|
|
564
|
+
* Runs once per opened channel; register methods on `channel`. Inbound messages wait until the returned promise settles. A handler for
|
|
565
|
+
* `mcp` that filters by `ctx.permits` itself may carry `capabilityScoped: true`.
|
|
566
|
+
*/
|
|
567
|
+
export type WshRpcHandler = ((channel: RpcChannel, ctx: WshRpcContext) => void | Promise<void>) & { capabilityScoped?: boolean };
|
|
533
568
|
|
|
534
569
|
/**
|
|
535
570
|
* Expose an MCP `Server` (`@modelcontextprotocol/sdk`) over an rpc channel: `rpc: { mcp: mcpServerAdapter(server) }`.
|
|
@@ -663,6 +698,10 @@ export interface WshReverseHostOptions {
|
|
|
663
698
|
pty?: WshServerPtyOptions;
|
|
664
699
|
fs?: WshServerFsOptions;
|
|
665
700
|
mcp?: WshServerMcpOptions;
|
|
701
|
+
/** Typed rpc channels (#191), as for `createWshServer` (the `wsh-host` and `wsh-fs` built-ins included), served to the bridged operator in virtual data mode and stated as `rpc-virtual` in `ReverseAccept.features` (so it needs `reportFeatures`). */
|
|
702
|
+
rpc?: Record<string, true | WshServerFsOptions | WshRpcHandler | false | null | undefined>;
|
|
703
|
+
rpcMaxMessageBytes?: number;
|
|
704
|
+
rpcMaxInflight?: number;
|
|
666
705
|
/** Dial again, with backoff, after the relay connection ends -- which a relay does when a bridge does (default true). */
|
|
667
706
|
reconnect?: boolean;
|
|
668
707
|
/** Extra options for the relay connection (`expectHostKey`, `knownHosts`, `trustOnFirstUse`, ...). */
|
package/src/server/index.mjs
CHANGED
|
@@ -20,11 +20,13 @@ import { validateOnRefused } from '../refusal.mjs';
|
|
|
20
20
|
import { normalizeGateway, createGatewaySession } from './gateway.mjs';
|
|
21
21
|
import { createRpcHost, mcpServerAdapter } from './rpc.mjs';
|
|
22
22
|
import { bindSocket } from './socket.mjs';
|
|
23
|
+
import { resolveUsernamePattern } from './username.mjs';
|
|
23
24
|
import { TLS_EXPORTER_LABEL, TLS_EXPORTER_LENGTH, CHANNEL_BINDING_KINDS } from '../channel-binding.mjs';
|
|
24
25
|
|
|
25
26
|
export { parseAuthorizedKeys, parseAuthorizedKeyEntries, STREAM_ANNOUNCE, mcpServerAdapter };
|
|
26
27
|
export { createReverseHost } from './reverse-host.mjs';
|
|
27
28
|
export { generateSelfSignedCertificate } from './self-signed.mjs';
|
|
29
|
+
export { hashPassword, verifyPassword, passwordVerifier } from './password.mjs';
|
|
28
30
|
|
|
29
31
|
/** The TLS exporter of a `wss://` connection as a channel binding (#119); null on a plain socket or a TLS-terminating proxy hop. */
|
|
30
32
|
function tlsChannelBinding(socket) {
|
|
@@ -115,8 +117,9 @@ function tlsChannelBinding(socket) {
|
|
|
115
117
|
*/
|
|
116
118
|
export function createWshServer({
|
|
117
119
|
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 = () => {},
|
|
118
|
-
onShare, onRefused, targets, requireTarget,
|
|
120
|
+
onShare, onRefused, targets, requireTarget, usernamePattern,
|
|
119
121
|
} = {}) {
|
|
122
|
+
resolveUsernamePattern(usernamePattern, 'createWshServer');
|
|
120
123
|
validateOnShare(onShare, 'createWshServer');
|
|
121
124
|
validateOnRefused(onRefused, 'createWshServer');
|
|
122
125
|
if (sealSession !== false && sealSession !== 'offer' && sealSession !== 'require') throw new TypeError("createWshServer: sealSession must be false, 'offer' or 'require'");
|
|
@@ -175,7 +178,7 @@ export function createWshServer({
|
|
|
175
178
|
return createConnectionFactory({
|
|
176
179
|
authorize, execRunner, execOptions, pty: ptyConfig, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, sealSession, log: onLog,
|
|
177
180
|
methods, hostKey: host_, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, gateway: gatewayCfg, createGatewaySession, sessions: registry, relay: hub,
|
|
178
|
-
onShare, onRefused, targets: targetTable, requireTarget: mustHaveTarget,
|
|
181
|
+
onShare, onRefused, targets: targetTable, requireTarget: mustHaveTarget, usernamePattern,
|
|
179
182
|
});
|
|
180
183
|
})();
|
|
181
184
|
ready.catch(() => { ready = null; });
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Password hashing for hosts that serve password logins (`auth.password`), on Node: scrypt from `node:crypto`,
|
|
3
|
+
* stored as a PHC string (`$scrypt$ln=16,r=8,p=1$<salt>$<hash>`, unpadded standard base64) with a random per-user
|
|
4
|
+
* salt, compared with `timingSafeEqual`. scrypt is memory-hard; it is what the Node entry point can do honestly
|
|
5
|
+
* (WebCrypto has no argon2 and no scrypt, so this module is not part of the browser-safe entry points, and a host
|
|
6
|
+
* running in a page keeps its own `auth.password` callback and its own choice of hash).
|
|
7
|
+
*
|
|
8
|
+
* The Rust `wsh-server` stores Argon2id; a hash written by one is not read by the other, and this is not meant to
|
|
9
|
+
* make them interchangeable.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { scrypt as nodeScrypt, createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
13
|
+
|
|
14
|
+
const DEFAULT_PARAMS = Object.freeze({ ln: 16, r: 8, p: 1 });
|
|
15
|
+
const SALT_BYTES = 16;
|
|
16
|
+
const KEY_BYTES = 32;
|
|
17
|
+
/** The most memory a stored hash may ask a login to spend (128 * N * r bytes): a hostile value in a file cannot exhaust the host. */
|
|
18
|
+
const MAX_MEMORY = 2 ** 28;
|
|
19
|
+
|
|
20
|
+
const defaultScrypt = (password, salt, keylen, opts) => new Promise((resolve, reject) => {
|
|
21
|
+
nodeScrypt(password, salt, keylen, opts, (err, key) => (err ? reject(err) : resolve(key)));
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
const b64 = (buf) => Buffer.from(buf).toString('base64').replace(/=+$/, '');
|
|
25
|
+
const B64_RE = /^[A-Za-z0-9+/]+$/;
|
|
26
|
+
const unb64 = (s) => (typeof s === 'string' && B64_RE.test(s) ? Buffer.from(s, 'base64') : null);
|
|
27
|
+
|
|
28
|
+
function memoryFor({ ln, r }) { return 128 * (2 ** ln) * r; }
|
|
29
|
+
|
|
30
|
+
function scryptOptions({ ln, r, p }) {
|
|
31
|
+
return { N: 2 ** ln, r, p, maxmem: memoryFor({ ln, r }) * 2 };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Hash a password for storage.
|
|
36
|
+
* @param {string} password
|
|
37
|
+
* @param {{ ln?: number, r?: number, p?: number, scrypt?: Function }} [opts] cost (`ln` is log2 of N); the default is
|
|
38
|
+
* ln=16, r=8, p=1 (64 MiB). `scrypt` replaces the derivation (tests).
|
|
39
|
+
* @returns {Promise<string>}
|
|
40
|
+
*/
|
|
41
|
+
export async function hashPassword(password, opts = {}) {
|
|
42
|
+
if (typeof password !== 'string' || password === '') throw new TypeError('hashPassword: a non-empty password string is required');
|
|
43
|
+
const params = { ln: opts.ln ?? DEFAULT_PARAMS.ln, r: opts.r ?? DEFAULT_PARAMS.r, p: opts.p ?? DEFAULT_PARAMS.p };
|
|
44
|
+
if (!validParams(params)) throw new RangeError('hashPassword: cost parameters out of range (ln 10-22, r 1-32, p 1-16, at most 256 MiB)');
|
|
45
|
+
const salt = randomBytes(SALT_BYTES);
|
|
46
|
+
const key = await (opts.scrypt ?? defaultScrypt)(password.normalize('NFKC'), salt, KEY_BYTES, scryptOptions(params));
|
|
47
|
+
return `$scrypt$ln=${params.ln},r=${params.r},p=${params.p}$${b64(salt)}$${b64(key)}`;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function validParams({ ln, r, p }) {
|
|
51
|
+
return Number.isInteger(ln) && ln >= 10 && ln <= 22 && Number.isInteger(r) && r >= 1 && r <= 32
|
|
52
|
+
&& Number.isInteger(p) && p >= 1 && p <= 16 && memoryFor({ ln, r }) <= MAX_MEMORY;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** @returns {{ params: {ln:number,r:number,p:number}, salt: Buffer, hash: Buffer } | null} */
|
|
56
|
+
function parseHash(stored) {
|
|
57
|
+
if (typeof stored !== 'string') return null;
|
|
58
|
+
const parts = stored.split('$');
|
|
59
|
+
if (parts.length !== 5 || parts[0] !== '' || parts[1] !== 'scrypt') return null;
|
|
60
|
+
const m = /^ln=(\d{1,2}),r=(\d{1,2}),p=(\d{1,2})$/.exec(parts[2]);
|
|
61
|
+
if (!m) return null;
|
|
62
|
+
const params = { ln: Number(m[1]), r: Number(m[2]), p: Number(m[3]) };
|
|
63
|
+
if (!validParams(params)) return null;
|
|
64
|
+
const salt = unb64(parts[3]);
|
|
65
|
+
const hash = unb64(parts[4]);
|
|
66
|
+
if (!salt || !hash || salt.length < 8 || salt.length > 64 || hash.length !== KEY_BYTES) return null;
|
|
67
|
+
return { params, salt, hash };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Does `password` match a hash made by `hashPassword`? False for anything else, including a malformed or oversized
|
|
72
|
+
* value; it never throws on the stored value.
|
|
73
|
+
* @param {string} password
|
|
74
|
+
* @param {string} stored
|
|
75
|
+
* @param {{ scrypt?: Function }} [opts]
|
|
76
|
+
* @returns {Promise<boolean>}
|
|
77
|
+
*/
|
|
78
|
+
export async function verifyPassword(password, stored, opts = {}) {
|
|
79
|
+
if (typeof password !== 'string') return false;
|
|
80
|
+
const parsed = parseHash(stored);
|
|
81
|
+
if (!parsed) return false;
|
|
82
|
+
const key = await (opts.scrypt ?? defaultScrypt)(password.normalize('NFKC'), parsed.salt, KEY_BYTES, scryptOptions(parsed.params));
|
|
83
|
+
return key.length === parsed.hash.length && timingSafeEqual(key, parsed.hash);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Derived against a password nobody has, with the default cost, for a user the table does not know.
|
|
87
|
+
const DECOY_SALT = Buffer.from('wsh-decoy-salt!!');
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* An `auth.password` callback over a table of stored hashes, in the same shape the Rust `wsh-server` serves: an
|
|
91
|
+
* unknown user costs the same derivation as a wrong password (so neither the answer nor the time says which users
|
|
92
|
+
* exist), the table is not consulted through the prototype chain, and an entry that is not a `hashPassword` hash is
|
|
93
|
+
* refused with a warning that names the user (never the stored value).
|
|
94
|
+
*
|
|
95
|
+
* An old unsalted `sha256:<hex>` entry (one SHA-256 of the password: guessable offline at billions per second) is
|
|
96
|
+
* refused, as the Rust server refuses it, unless `allowLegacySha256` is set; it then verifies, in constant time, with
|
|
97
|
+
* a warning naming the user, and should be replaced with `hashPassword`'s output.
|
|
98
|
+
*
|
|
99
|
+
* @param {Record<string,string> | Map<string,string> | ((username: string) => string | undefined | Promise<string | undefined>)} hashes
|
|
100
|
+
* @param {{ allowLegacySha256?: boolean, onWarn?: (message: string) => void, scrypt?: Function }} [opts]
|
|
101
|
+
* @returns {(username: string, password: string) => Promise<boolean>}
|
|
102
|
+
*/
|
|
103
|
+
export function passwordVerifier(hashes, opts = {}) {
|
|
104
|
+
const { allowLegacySha256 = false, onWarn = (m) => console.warn(m), scrypt = defaultScrypt } = opts;
|
|
105
|
+
const lookup = typeof hashes === 'function' ? hashes
|
|
106
|
+
: hashes instanceof Map ? (u) => hashes.get(u)
|
|
107
|
+
: (u) => (hashes && Object.hasOwn(hashes, u) ? hashes[u] : undefined);
|
|
108
|
+
const warned = new Set();
|
|
109
|
+
const warnOnce = (user, text) => {
|
|
110
|
+
const key = `${user}\0${text}`;
|
|
111
|
+
if (warned.has(key)) return;
|
|
112
|
+
warned.add(key);
|
|
113
|
+
try { onWarn(text); } catch { /* a throwing logger must not decide a login */ }
|
|
114
|
+
};
|
|
115
|
+
const decoy = async (password) => {
|
|
116
|
+
try { await scrypt(password.normalize('NFKC'), DECOY_SALT, KEY_BYTES, scryptOptions(DEFAULT_PARAMS)); } catch { /* the answer is false either way */ }
|
|
117
|
+
return false;
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
return async (username, password) => {
|
|
121
|
+
if (typeof username !== 'string' || typeof password !== 'string') return false;
|
|
122
|
+
let stored;
|
|
123
|
+
try { stored = await lookup(username); } catch { stored = undefined; }
|
|
124
|
+
if (typeof stored !== 'string') return decoy(password);
|
|
125
|
+
|
|
126
|
+
if (stored.startsWith('sha256:')) {
|
|
127
|
+
const want = /^sha256:([0-9a-f]{64})$/i.exec(stored)?.[1];
|
|
128
|
+
if (!allowLegacySha256 || !want) {
|
|
129
|
+
warnOnce(username, `wsh: password hash for user "${username}" is an unsalted sha256 entry and is refused: replace it with the output of hashPassword() (or pass allowLegacySha256: true to passwordVerifier to keep it working for now)`);
|
|
130
|
+
return decoy(password);
|
|
131
|
+
}
|
|
132
|
+
warnOnce(username, `wsh: password hash for user "${username}" is an unsalted sha256 entry; it is accepted because allowLegacySha256 is set. Replace it with the output of hashPassword()`);
|
|
133
|
+
const got = createHash('sha256').update(password).digest();
|
|
134
|
+
return timingSafeEqual(got, Buffer.from(want, 'hex'));
|
|
135
|
+
}
|
|
136
|
+
if (!parseHash(stored)) {
|
|
137
|
+
warnOnce(username, `wsh: password hash for user "${username}" is not a hashPassword() value and is refused`);
|
|
138
|
+
return decoy(password);
|
|
139
|
+
}
|
|
140
|
+
return verifyPassword(password, stored, { scrypt });
|
|
141
|
+
};
|
|
142
|
+
}
|
|
@@ -1,13 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* `createReverseHost` for `@johnhenry/wsh/server`: the browser-safe reverse host (`../reverse-host.mjs`, also
|
|
3
3
|
* `@johnhenry/wsh/reverse`) with the Node-only backends added -- `exec: true` (a shell through child_process)
|
|
4
|
-
* and `fs: { root }` (a directory). The reverse host itself lives in
|
|
4
|
+
* and `fs: { root }` (a directory), and the `wsh-host` / `wsh-fs` rpc built-ins. The reverse host itself lives in
|
|
5
|
+
* `../reverse-host.mjs`.
|
|
5
6
|
*/
|
|
6
7
|
|
|
7
8
|
import { createReverseHostWith } from '../reverse-host.mjs';
|
|
8
9
|
import { buildBackends } from './backends.mjs';
|
|
10
|
+
import { createRpcHost } from './rpc.mjs';
|
|
9
11
|
|
|
10
12
|
/** @param {Parameters<typeof import('../reverse-host.mjs').createReverseHost>[0]} [options] - see `../reverse-host.mjs` */
|
|
11
13
|
export function createReverseHost(options = {}) {
|
|
12
|
-
|
|
14
|
+
const backends = buildBackends(options);
|
|
15
|
+
const rpc = options.rpc === undefined || options.rpc === null ? null
|
|
16
|
+
: createRpcHost(options.rpc, { files: backends.files, maxMessageBytes: options.rpcMaxMessageBytes, maxInflight: options.rpcMaxInflight });
|
|
17
|
+
return createReverseHostWith(options, { ...backends, rpc });
|
|
13
18
|
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which login names a host admits. The default is the shape of an OS account name (a letter or `_`, then letters,
|
|
3
|
+
* digits, `_`, `.`, `-`, up to 64 characters), because a name reaches `exec` environments, file paths and logs of hosts
|
|
4
|
+
* that really do map it to an account. A host that does not (a page, a mesh peer whose name is a base64url identity
|
|
5
|
+
* hash that may start with a digit or `-`) can say what it admits with `usernamePattern`.
|
|
6
|
+
*
|
|
7
|
+
* What a pattern cannot loosen: the name is a string of 1 to 256 characters with no control character (C0, DEL, C1,
|
|
8
|
+
* line or paragraph separators), no slash and no backslash, and is not `.` or `..`. The pattern narrows further; it does not get to admit those.
|
|
9
|
+
*
|
|
10
|
+
* Pure JavaScript, browser-safe (the memory host imports it).
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export const DEFAULT_USERNAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/;
|
|
14
|
+
|
|
15
|
+
const MAX_USERNAME_LENGTH = 256;
|
|
16
|
+
|
|
17
|
+
/** A control character (C0, DEL, C1), a line or paragraph separator (code points 0x2028, 0x2029), `/` (0x2f) or `\` (0x5c). */
|
|
18
|
+
function forbiddenCode(c) {
|
|
19
|
+
return c <= 0x1f || (c >= 0x7f && c <= 0x9f) || c === 0x2028 || c === 0x2029 || c === 0x2f || c === 0x5c;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function hasForbidden(s) {
|
|
23
|
+
for (let i = 0; i < s.length; i++) if (forbiddenCode(s.charCodeAt(i))) return true;
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Validate a `usernamePattern` option and return the RegExp to test names with (never global or sticky, so `test()`
|
|
29
|
+
* keeps no state between logins).
|
|
30
|
+
* @param {RegExp | string | undefined | null} value
|
|
31
|
+
* @param {string} label `createWshServer` etc., for the error message
|
|
32
|
+
* @returns {RegExp}
|
|
33
|
+
*/
|
|
34
|
+
export function resolveUsernamePattern(value, label) {
|
|
35
|
+
if (value === undefined || value === null) return DEFAULT_USERNAME_PATTERN;
|
|
36
|
+
let re;
|
|
37
|
+
try {
|
|
38
|
+
if (value instanceof RegExp) re = new RegExp(value.source, value.flags.replace(/[gy]/g, ''));
|
|
39
|
+
else if (typeof value === 'string') re = new RegExp(value);
|
|
40
|
+
} catch (e) {
|
|
41
|
+
throw new TypeError(`${label}: usernamePattern is not a valid pattern (${e.message})`);
|
|
42
|
+
}
|
|
43
|
+
if (!re) throw new TypeError(`${label}: usernamePattern must be a RegExp or a pattern string`);
|
|
44
|
+
if (re.test('')) throw new TypeError(`${label}: usernamePattern must not match the empty name`);
|
|
45
|
+
return re;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* May this login name be admitted under `pattern`?
|
|
50
|
+
* @param {RegExp} pattern from `resolveUsernamePattern`
|
|
51
|
+
* @param {unknown} name
|
|
52
|
+
*/
|
|
53
|
+
export function usernameAllowed(pattern, name) {
|
|
54
|
+
if (typeof name !== 'string' || name.length === 0 || name.length > MAX_USERNAME_LENGTH || hasForbidden(name)) return false;
|
|
55
|
+
if (name === '.' || name === '..') return false; // a path component, whatever the pattern says
|
|
56
|
+
return pattern.test(name);
|
|
57
|
+
}
|
package/src/session.mjs
CHANGED
|
@@ -755,7 +755,8 @@ export class WshSession {
|
|
|
755
755
|
break;
|
|
756
756
|
}
|
|
757
757
|
if (msg.data && msg.data.byteLength > 0) {
|
|
758
|
-
|
|
758
|
+
// An rpc channel is read through `onData` only (its credit window bounds what is in flight): nothing is queued for read().
|
|
759
|
+
if (this.kind !== 'rpc') this.#virtualBackend?.pushData(msg.data);
|
|
759
760
|
try {
|
|
760
761
|
this.#seq += msg.data.byteLength;
|
|
761
762
|
this.onData?.(msg.data);
|
package/src/testing.d.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@johnhenry/wsh/testing`: the QMux record and frame codec primitives, for tests that look inside a connection, change it and
|
|
3
|
+
* re-wrap it.
|
|
4
|
+
*
|
|
5
|
+
* @experimental This entry point is not part of the stable API: a release may rename, change or remove anything in it, and the
|
|
6
|
+
* compatibility policy does not cover it. Application code should use the other entry points.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** QUIC variable-length integer (RFC 9000 section 16), as bytes. */
|
|
10
|
+
export function encodeVarint(value: number | bigint): Uint8Array;
|
|
11
|
+
export function decodeVarint(data: Uint8Array, offset?: number): { value: number | bigint; length: number };
|
|
12
|
+
export function varintLength(value: number | bigint): number;
|
|
13
|
+
|
|
14
|
+
export const FRAME_TYPE: Readonly<Record<string, number>>;
|
|
15
|
+
export const QX_TRANSPORT_PARAMETERS_TYPE: bigint;
|
|
16
|
+
export const QMUX_ERROR_CODE: Readonly<Record<string, number>>;
|
|
17
|
+
export const TRANSPORT_PARAM_ID: Readonly<Record<string, number>>;
|
|
18
|
+
|
|
19
|
+
/** One QMux Record: a varint size, then the frames. */
|
|
20
|
+
export function encodeRecord(framesBytes: Uint8Array): Uint8Array;
|
|
21
|
+
/** Accumulates transport bytes and yields the Frames payload of each complete record. */
|
|
22
|
+
export class RecordDecoder {
|
|
23
|
+
feed(chunk: Uint8Array): Uint8Array[];
|
|
24
|
+
reset(): void;
|
|
25
|
+
}
|
|
26
|
+
/** Decode every frame in a Frames payload; throws a `QMuxProtocolError` on a malformed one. */
|
|
27
|
+
export function decodeFrames(data: Uint8Array): Array<{ frameType: string; [field: string]: unknown }>;
|
|
28
|
+
|
|
29
|
+
export function encodePadding(length: number): Uint8Array;
|
|
30
|
+
/** A STREAM frame with Offset and Length always present. */
|
|
31
|
+
export function encodeStream(frame: { streamId: number | bigint; offset: number | bigint; data: Uint8Array; fin?: boolean }): Uint8Array;
|
|
32
|
+
export function encodeResetStream(frame: { streamId: number | bigint; errorCode: number | bigint; finalSize: number | bigint }): Uint8Array;
|
|
33
|
+
export function encodeResetStreamAt(frame: { streamId: number | bigint; errorCode: number | bigint; finalSize: number | bigint; reliableSize: number | bigint }): Uint8Array;
|
|
34
|
+
export function encodeStopSending(frame: { streamId: number | bigint; errorCode: number | bigint }): Uint8Array;
|
|
35
|
+
export function encodeMaxData(maxData: number | bigint): Uint8Array;
|
|
36
|
+
export function encodeMaxStreamData(frame: { streamId: number | bigint; maxStreamData: number | bigint }): Uint8Array;
|
|
37
|
+
export function encodeMaxStreams(frame: { unidirectional: boolean; maxStreams: number | bigint }): Uint8Array;
|
|
38
|
+
export function encodeDataBlocked(dataLimit: number | bigint): Uint8Array;
|
|
39
|
+
export function encodeStreamDataBlocked(frame: { streamId: number | bigint; streamDataLimit: number | bigint }): Uint8Array;
|
|
40
|
+
export function encodeStreamsBlocked(frame: { unidirectional: boolean; streamLimit: number | bigint }): Uint8Array;
|
|
41
|
+
export function encodeConnectionClose(frame: { application?: boolean; errorCode: number | bigint; frameType?: number | bigint; reason?: string }): Uint8Array;
|
|
42
|
+
export function encodeDatagram(data: Uint8Array): Uint8Array;
|
|
43
|
+
export function encodeTransportParameters(params: Record<string, unknown>): Uint8Array;
|
|
44
|
+
|
|
45
|
+
export class QMuxProtocolError extends Error {
|
|
46
|
+
readonly errorCode: number;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Machine-readable form of the notice: `stable` is `false`. */
|
|
50
|
+
export const QMUX_TESTING_API: Readonly<{ stable: false; notice: string }>;
|
package/src/testing.mjs
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@johnhenry/wsh/testing` -- the QMux record and frame codec primitives a test needs to look inside what travels on a connection,
|
|
3
|
+
* change it and put it back (re-wrap a STREAM frame around altered bytes, build a malformed frame, split a record at a chosen
|
|
4
|
+
* byte). They are the same functions `QMuxConnection` uses.
|
|
5
|
+
*
|
|
6
|
+
* NOT PART OF THE STABLE API. This entry point exists for tests of code that embeds the package (a transport, a relay, an
|
|
7
|
+
* alternate host); a release may rename, change or remove anything here, and it is not covered by the compatibility policy
|
|
8
|
+
* the rest of the package follows. Application code should use `WshClient`, `createWshServer` and the other entry points.
|
|
9
|
+
*
|
|
10
|
+
* Pure JavaScript, no Node built-in: it bundles for a browser like the rest.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export {
|
|
14
|
+
encodeVarint, decodeVarint, varintLength,
|
|
15
|
+
FRAME_TYPE, QX_TRANSPORT_PARAMETERS_TYPE, ERROR_CODE as QMUX_ERROR_CODE,
|
|
16
|
+
encodeRecord, RecordDecoder, decodeFrames,
|
|
17
|
+
encodePadding, encodeStream, encodeResetStream, encodeResetStreamAt, encodeStopSending,
|
|
18
|
+
encodeMaxData, encodeMaxStreamData, encodeMaxStreams, encodeDataBlocked, encodeStreamDataBlocked, encodeStreamsBlocked,
|
|
19
|
+
encodeConnectionClose, encodeDatagram, encodeTransportParameters, TRANSPORT_PARAM_ID,
|
|
20
|
+
QMuxProtocolError,
|
|
21
|
+
} from './qmux.mjs';
|
|
22
|
+
|
|
23
|
+
/** Machine-readable form of the notice above, so a test (or a reader) can check what it imported. */
|
|
24
|
+
export const QMUX_TESTING_API = Object.freeze({
|
|
25
|
+
stable: false,
|
|
26
|
+
notice: 'The primitives of @johnhenry/wsh/testing are not part of the stable API: they may change or disappear in any release.',
|
|
27
|
+
});
|