@johnhenry/wsh 0.36.0 → 0.38.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.
@@ -0,0 +1,77 @@
1
+ /**
2
+ * A sealed bridge (wsh #117): everything two endpoints say to each other across a relay, sealed under a key they
3
+ * agreed with a signed `KeyExchange` whose `session_id` is the bridge's, so the relay carries ciphertext it cannot
4
+ * read, forge, replay or reorder -- and, because a relay can stamp any `from_fingerprint` on a PLAIN message, cannot
5
+ * make a peer act for an operator that is not there.
6
+ *
7
+ * Each message that would cross the bridge is CBOR-encoded and sealed with the same AES-256-GCM framing as session
8
+ * data (`e2e-frame.mjs`: a strict send counter, a role tag per direction, `session_id` as AAD) into an
9
+ * `EncryptedFrame` with `channel_id` 0 (real channels start at 1). The receiver opens it and handles the inner
10
+ * message as if it had arrived plain; a plain message on a sealed bridge is dropped.
11
+ *
12
+ * Browser-safe: Web Crypto and the CBOR codec only.
13
+ */
14
+
15
+ import { sealFrame, openFrame, ROLE_TAGS } from './e2e-frame.mjs';
16
+ import { cborEncode, cborDecode } from './cbor.mjs';
17
+ import { encryptedFrame, MSG, isRelayForwardable } from './messages.gen.mjs';
18
+
19
+ /** `EncryptedFrame.channel_id` of a bridge-level frame. */
20
+ export const BRIDGE_CHANNEL_ID = 0;
21
+
22
+ export class SealedBridge {
23
+ #key;
24
+ #sessionId;
25
+ #sendTag;
26
+ #recvTag;
27
+ #sendCounter = 0;
28
+ #recvCounter = 0;
29
+ #outChain = Promise.resolve();
30
+ #inChain = Promise.resolve();
31
+
32
+ /**
33
+ * @param {{ key: CryptoKey, sessionId: string, role: 'initiator' | 'responder' }} p - `initiator` is the operator
34
+ */
35
+ constructor({ key, sessionId, role }) {
36
+ if (role !== 'initiator' && role !== 'responder') throw new TypeError("SealedBridge: role must be 'initiator' or 'responder'");
37
+ this.#key = key;
38
+ this.#sessionId = sessionId;
39
+ this.#sendTag = ROLE_TAGS[role];
40
+ this.#recvTag = ROLE_TAGS[role === 'initiator' ? 'responder' : 'initiator'];
41
+ }
42
+
43
+ get sessionId() { return this.#sessionId; }
44
+
45
+ /** Is `msg` a bridge-level frame of this bridge? */
46
+ isFrame(msg) {
47
+ return msg?.type === MSG.ENCRYPTED_FRAME && msg.channel_id === BRIDGE_CHANNEL_ID && msg.session_id === this.#sessionId;
48
+ }
49
+
50
+ /** Seal one message; calls are sealed (and so must be sent) in call order. @returns {Promise<object>} an `EncryptedFrame` */
51
+ seal(msg) {
52
+ const counter = this.#sendCounter++;
53
+ const run = this.#outChain.then(async () => {
54
+ const { nonce, ciphertext } = await sealFrame(this.#key, this.#sessionId, this.#sendTag, counter, cborEncode(msg));
55
+ return encryptedFrame({ channelId: BRIDGE_CHANNEL_ID, nonce, ciphertext, sessionId: this.#sessionId });
56
+ });
57
+ this.#outChain = run.catch(() => {});
58
+ return run;
59
+ }
60
+
61
+ /**
62
+ * Open one frame. A replayed, reordered, forged or foreign frame throws and does not consume a counter.
63
+ * @returns {Promise<object>} the inner message, which is always one a relay may forward
64
+ */
65
+ open(frame) {
66
+ const run = this.#inChain.then(async () => {
67
+ if (!this.isFrame(frame)) throw new Error('not a frame of this bridge');
68
+ const plain = await openFrame(this.#key, this.#sessionId, this.#recvCounter, { nonce: frame.nonce, ciphertext: frame.ciphertext, expectedRoleTag: this.#recvTag });
69
+ this.#recvCounter += 1;
70
+ const inner = cborDecode(plain);
71
+ if (!inner || typeof inner.type !== 'number' || inner.type === MSG.RELAY_FORWARD || !isRelayForwardable(inner.type)) throw new Error('sealed message of a type that may not cross a bridge');
72
+ return inner;
73
+ });
74
+ this.#inChain = run.catch(() => {});
75
+ return run;
76
+ }
77
+ }
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Channel binding for the wsh authentication transcript (wsh #119).
3
+ *
4
+ * `buildTranscript()` has always had a `channel_binding` slot; nothing filled it, so a client's signature said
5
+ * nothing about WHICH connection it was made over. An intermediary that terminates the client's connection and
6
+ * opens its own to the host could pass a genuine challenge through and get the client's signature back
7
+ * (the same limit the README states for host keys on `ws://`).
8
+ *
9
+ * The binding is a SHA-256 over what the two ends of the connection both know, each part tagged with its kind:
10
+ *
11
+ * binding = SHA-256( "wsh-channel-binding-v1\0" || for each present kind, in the order below: lp(kind) || lp(value) )
12
+ *
13
+ * kind value who can supply it
14
+ * cert-hash the 32-byte SHA-256 of the WebTransport certificate pinned client with exactly one
15
+ * through `serverCertificateHashes` `serverCertificateHashes` entry; host
16
+ * host the raw 32-byte Ed25519 host key the client saw prove client that verified the host's
17
+ * possession (so a relay presenting its own key binds to THAT) key proof; host with a `hostKey`
18
+ * tls-exporter 32 bytes of TLS keying material, label Node on both ends over TLS (the
19
+ * "EXPORTER-wsh-channel-binding", empty context (RFC 5705/8446) `ws` package); never a browser
20
+ *
21
+ * With no kind present the binding is the EMPTY byte string -- exactly what the transcript carried before, so a
22
+ * peer that knows nothing of this still interoperates.
23
+ *
24
+ * Negotiation, all by feature string (no new wire field):
25
+ * - a host that can bind a kind lists `channel-binding:<kind>` in `ServerHello.features`; a host that REQUIRES a
26
+ * binding also lists `channel-binding-required`;
27
+ * - the client binds every kind that the host offers and it can supply, and signs that;
28
+ * - the host recomputes the binding over each non-empty combination of the kinds it offers (the client may lack
29
+ * one, a browser lacks `tls-exporter`) and accepts the signature if one matches -- the empty binding only if the
30
+ * host does not require one. A host that requires a binding also requires its named kinds, when it names any.
31
+ * - a client that must not authenticate unbound (`requireChannelBinding`) refuses when it ends up with none, which
32
+ * also defeats an intermediary that strips the host's `channel-binding:*` features.
33
+ */
34
+
35
+ const enc = new TextEncoder();
36
+ const LABEL = enc.encode('wsh-channel-binding-v1\0');
37
+
38
+ export const CHANNEL_BINDING_PREFIX = 'channel-binding:';
39
+ export const CHANNEL_BINDING_REQUIRED_FEATURE = 'channel-binding-required';
40
+ /** TLS exporter label (RFC 5705 / RFC 8446 section 7.5) and length. */
41
+ export const TLS_EXPORTER_LABEL = 'EXPORTER-wsh-channel-binding';
42
+ export const TLS_EXPORTER_LENGTH = 32;
43
+ /** Canonical order of the kinds inside the hash. */
44
+ export const CHANNEL_BINDING_KINDS = Object.freeze(['cert-hash', 'host', 'tls-exporter']);
45
+
46
+ const lp = (bytes) => {
47
+ const out = new Uint8Array(4 + bytes.length);
48
+ new DataView(out.buffer).setUint32(0, bytes.length);
49
+ out.set(bytes, 4);
50
+ return out;
51
+ };
52
+
53
+ /**
54
+ * @param {Record<string, Uint8Array>} values - kind -> value; unknown kinds and absent ones are ignored
55
+ * @returns {Promise<Uint8Array>} 32 bytes, or an empty array when no kind is present
56
+ */
57
+ export async function computeChannelBinding(values) {
58
+ const parts = [LABEL];
59
+ for (const kind of CHANNEL_BINDING_KINDS) {
60
+ const v = values?.[kind];
61
+ if (v instanceof Uint8Array && v.length) parts.push(lp(enc.encode(kind)), lp(v));
62
+ }
63
+ if (parts.length === 1) return new Uint8Array(0);
64
+ const all = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
65
+ let off = 0;
66
+ for (const p of parts) { all.set(p, off); off += p.length; }
67
+ return new Uint8Array(await crypto.subtle.digest('SHA-256', all));
68
+ }
69
+
70
+ /** The kinds a `ServerHello.features` list offers, in canonical order. */
71
+ export function offeredKinds(features) {
72
+ const set = new Set();
73
+ for (const f of features ?? []) if (typeof f === 'string' && f.startsWith(CHANNEL_BINDING_PREFIX)) set.add(f.slice(CHANNEL_BINDING_PREFIX.length));
74
+ return CHANNEL_BINDING_KINDS.filter((k) => set.has(k));
75
+ }
76
+
77
+ /** Does `features` say the host requires a channel binding? */
78
+ export const requiresBinding = (features) => (features ?? []).includes(CHANNEL_BINDING_REQUIRED_FEATURE);
79
+
80
+ /** The `ServerHello` feature strings for what a host can bind (and, optionally, that it requires one). */
81
+ export function bindingFeatures(kinds, { required = false } = {}) {
82
+ return [...kinds.map((k) => CHANNEL_BINDING_PREFIX + k), ...(required ? [CHANNEL_BINDING_REQUIRED_FEATURE] : [])];
83
+ }
84
+
85
+ /**
86
+ * The client side: bind everything offered that this client can supply.
87
+ * @param {string[]} serverFeatures
88
+ * @param {Record<string, Uint8Array | null | undefined>} available - what the client holds, by kind
89
+ * @returns {Promise<{ binding: Uint8Array, kinds: string[] }>}
90
+ */
91
+ export async function clientChannelBinding(serverFeatures, available) {
92
+ const kinds = offeredKinds(serverFeatures).filter((k) => available?.[k] instanceof Uint8Array && available[k].length);
93
+ const values = {};
94
+ for (const k of kinds) values[k] = available[k];
95
+ return { binding: await computeChannelBinding(values), kinds };
96
+ }
97
+
98
+ /**
99
+ * The host side: every binding a client might legitimately have signed, as `{ binding, kinds }`.
100
+ * @param {Record<string, Uint8Array[]>} held - the kinds this host can compute, each with its (usually one) value;
101
+ * several for `cert-hash` while a certificate rotates
102
+ * @param {{ required: false | true | string[] }} policy - `true`: a non-empty binding; an array: those kinds too
103
+ * @returns {Promise<{ binding: Uint8Array, kinds: string[] }[]>}
104
+ */
105
+ export async function acceptableBindings(held, { required = false } = {}) {
106
+ const kinds = CHANNEL_BINDING_KINDS.filter((k) => held[k]?.length);
107
+ const must = Array.isArray(required) ? required : [];
108
+ const out = [];
109
+ const subsets = [];
110
+ for (let mask = 0; mask < (1 << kinds.length); mask++) subsets.push(kinds.filter((_, i) => mask & (1 << i)));
111
+ for (const subset of subsets) {
112
+ if (subset.length === 0 && required) continue;
113
+ if (!must.every((k) => subset.includes(k))) continue;
114
+ // Expand alternatives (a rotating certificate has two hashes).
115
+ let combos = [{}];
116
+ for (const k of subset) combos = combos.flatMap((c) => held[k].map((v) => ({ ...c, [k]: v })));
117
+ for (const values of combos) out.push({ binding: await computeChannelBinding(values), kinds: subset });
118
+ }
119
+ return out;
120
+ }
121
+
122
+ const eq = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);
123
+ /** @returns {boolean} whether `binding` is one of `acceptable` */
124
+ export const bindingAcceptable = (acceptable, binding) => acceptable.some((a) => eq(a.binding, binding));