@tik-choco/mistlib-mcp 0.0.0-stage → 0.1.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.
Files changed (52) hide show
  1. package/LICENSE +373 -0
  2. package/README.md +128 -2
  3. package/dist/index.d.ts +3 -0
  4. package/dist/index.js +3 -0
  5. package/dist/mcp/index.d.ts +3 -0
  6. package/dist/mcp/index.js +1 -0
  7. package/dist/mcp/schema.d.ts +6 -0
  8. package/dist/mcp/schema.js +29 -0
  9. package/dist/mcp/server.d.ts +100 -0
  10. package/dist/mcp/server.js +303 -0
  11. package/dist/provider/identity.d.ts +4 -0
  12. package/dist/provider/identity.js +57 -0
  13. package/dist/provider/index.d.ts +4 -0
  14. package/dist/provider/index.js +3 -0
  15. package/dist/provider/mistseed.d.ts +16 -0
  16. package/dist/provider/mistseed.js +91 -0
  17. package/dist/provider/protocol.d.ts +49 -0
  18. package/dist/provider/protocol.js +139 -0
  19. package/dist/provider/provider.d.ts +3 -0
  20. package/dist/provider/provider.js +430 -0
  21. package/dist/provider/shared-node.d.ts +23 -0
  22. package/dist/provider/shared-node.js +78 -0
  23. package/dist/provider/types.d.ts +31 -0
  24. package/dist/provider/types.js +1 -0
  25. package/dist/wire/credentials.d.ts +47 -0
  26. package/dist/wire/credentials.js +79 -0
  27. package/dist/wire/encoding.d.ts +7 -0
  28. package/dist/wire/encoding.js +23 -0
  29. package/dist/wire/errors.d.ts +27 -0
  30. package/dist/wire/errors.js +19 -0
  31. package/dist/wire/framing.d.ts +40 -0
  32. package/dist/wire/framing.js +166 -0
  33. package/dist/wire/index.d.ts +8 -0
  34. package/dist/wire/index.js +8 -0
  35. package/dist/wire/json.d.ts +13 -0
  36. package/dist/wire/json.js +73 -0
  37. package/dist/wire/messages.d.ts +68 -0
  38. package/dist/wire/messages.js +89 -0
  39. package/dist/wire/names.d.ts +4 -0
  40. package/dist/wire/names.js +14 -0
  41. package/dist/wire/noise-session.d.ts +135 -0
  42. package/dist/wire/noise-session.js +432 -0
  43. package/noise-wasm/README.md +59 -0
  44. package/noise-wasm/pkg/noise_wasm.d.ts +101 -0
  45. package/noise-wasm/pkg/noise_wasm.js +699 -0
  46. package/noise-wasm/pkg/noise_wasm_bg.wasm +0 -0
  47. package/noise-wasm/pkg/noise_wasm_bg.wasm.d.ts +30 -0
  48. package/package.json +70 -4
  49. package/spec/provider-runtime-v1.md +100 -0
  50. package/spec/secure-channel-v1.md +213 -0
  51. package/spec/wire-v1.md +355 -0
  52. package/vectors/wire-v1.json +117 -0
@@ -0,0 +1,135 @@
1
+ import { Handshake as WasmHandshake } from "../../noise-wasm/pkg/noise_wasm.js";
2
+ import type { FrameCipher as BaseFrameCipher } from "./framing.js";
3
+ export declare const PAIR_PATTERN = "Noise_XXpsk3_25519_ChaChaPoly_SHA256";
4
+ export declare const RECONNECT_PATTERN = "Noise_KK_25519_ChaChaPoly_SHA256";
5
+ export type NoisePattern = typeof PAIR_PATTERN | typeof RECONNECT_PATTERN;
6
+ export type Role = "initiator" | "responder";
7
+ export declare const SECURE_CHANNEL_VERSION = 1;
8
+ /** Max plaintext per transport message: one frame chunk plus its sealed frame header. */
9
+ export declare const MAX_FRAME_PLAINTEXT: number;
10
+ export declare const NOISE_TAG_LEN = 16;
11
+ export declare const MAX_FRAME_SEALED: number;
12
+ export declare const MAX_HANDSHAKE_PAYLOAD = 512;
13
+ export declare const MAX_HANDSHAKE_MESSAGE = 1024;
14
+ export declare const MAX_PROLOGUE_FIELD = 512;
15
+ export declare const MAX_BINDING_PLAINTEXT = 1024;
16
+ export type NoiseWasmSource = BufferSource | WebAssembly.Module | URL | string | Response | Promise<Response>;
17
+ /**
18
+ * Loads the snow wasm once. Browsers/bundlers resolve `noise_wasm_bg.wasm` next to the glue via
19
+ * `import.meta.url`; Node reads the file directly. Pass `source` to override (e.g. a CDN URL).
20
+ */
21
+ export declare function initNoise(source?: NoiseWasmSource): Promise<void>;
22
+ export interface StaticKeypair {
23
+ readonly privateKey: Uint8Array;
24
+ readonly publicKey: Uint8Array;
25
+ }
26
+ /** Fresh X25519 Noise static keypair (snow's resolver RNG). */
27
+ export declare function generateStaticKeypair(): Promise<StaticKeypair>;
28
+ export interface PrologueFields {
29
+ roomId: string;
30
+ initiatorNodeId: string;
31
+ responderNodeId: string;
32
+ }
33
+ /** label || 0x00 || version || lp(room) || lp(initiator) || lp(responder); lp = u16be length || UTF-8. */
34
+ export declare function encodePrologue(p: PrologueFields): Uint8Array;
35
+ export declare const MIN_PAIRING_CODE_CHARS = 26;
36
+ export declare const MAX_PAIRING_CODE_CHARS = 64;
37
+ /** Crockford base32 normalisation: drop spaces/hyphens, uppercase, I/L -> 1, O -> 0. */
38
+ export declare function normalizePairingCode(code: string): string;
39
+ /** PSK = HKDF-SHA256(ikm = ASCII(normalized code), salt = PSK_SALT, info = PSK_INFO, L = 32). */
40
+ export declare function derivePairingPsk(code: string): Promise<Uint8Array>;
41
+ export interface ClosableFrameCipher extends BaseFrameCipher {
42
+ close(): void;
43
+ readonly closed: boolean;
44
+ }
45
+ export interface HandshakeResult {
46
+ readonly pattern: NoisePattern;
47
+ readonly role: Role;
48
+ readonly remoteStatic: Uint8Array;
49
+ readonly handshakeHash: Uint8Array;
50
+ readonly cipher: ClosableFrameCipher;
51
+ }
52
+ /**
53
+ * Stepwise handshake. The caller moves bytes: while `!isFinished`, call `writeMessage()` when
54
+ * `isMyTurn` and send the result, otherwise feed received bytes to `readMessage()`. Then `finish()`.
55
+ * Any error closes the handshake permanently.
56
+ */
57
+ export declare class NoiseHandshake {
58
+ #private;
59
+ readonly pattern: NoisePattern;
60
+ readonly role: Role;
61
+ /** @internal use pairInitiator/pairResponder/reconnectInitiator/reconnectResponder */
62
+ constructor(pattern: NoisePattern, role: Role, hs: WasmHandshake, pinned?: Uint8Array);
63
+ get closed(): boolean;
64
+ get isMyTurn(): boolean;
65
+ get isFinished(): boolean;
66
+ close(): void;
67
+ writeMessage(payload?: Uint8Array): Uint8Array;
68
+ readMessage(message: Uint8Array): Uint8Array;
69
+ /** Converts a finished handshake into the transport. The handshake is consumed either way. */
70
+ finish(): HandshakeResult;
71
+ }
72
+ export interface PairOptions {
73
+ localStatic: StaticKeypair;
74
+ prologue: PrologueFields;
75
+ code: string;
76
+ }
77
+ export interface ReconnectOptions {
78
+ localStatic: StaticKeypair;
79
+ remoteStatic: Uint8Array;
80
+ prologue: PrologueFields;
81
+ }
82
+ /** First pairing, initiator side (Noise_XXpsk3). Learns and returns the peer static key. */
83
+ export declare function pairInitiator(o: PairOptions): Promise<NoiseHandshake>;
84
+ export declare function pairResponder(o: PairOptions): Promise<NoiseHandshake>;
85
+ /** Reconnect with the stored peer static key (Noise_KK). */
86
+ export declare function reconnectInitiator(o: ReconnectOptions): Promise<NoiseHandshake>;
87
+ export declare function reconnectResponder(o: ReconnectOptions): Promise<NoiseHandshake>;
88
+ export interface BindingSigner {
89
+ /** did:key (Ed25519) of the signer. */
90
+ readonly did: string;
91
+ /** Raw 64-byte Ed25519 signature over `message`. */
92
+ sign(message: Uint8Array): Uint8Array | Promise<Uint8Array>;
93
+ }
94
+ export type BindingVerifier = (did: string, message: Uint8Array, signature: Uint8Array) => boolean | Promise<boolean>;
95
+ export interface BindingProof {
96
+ readonly did: string;
97
+ readonly signature: Uint8Array;
98
+ }
99
+ /** UTF-8(BINDING_LABEL + signerRole) || 0x00 || handshakeHash. */
100
+ export declare function bindingMessage(handshakeHash: Uint8Array, signerRole: Role): Uint8Array;
101
+ export declare function signBinding(signer: BindingSigner, handshakeHash: Uint8Array, localRole: Role): Promise<BindingProof>;
102
+ export interface VerifyBindingOptions {
103
+ expectedDid?: string;
104
+ verify?: BindingVerifier;
105
+ }
106
+ /** Throws AUTH_FAILED unless `proof` is a valid signature by `proof.did` for the remote role. */
107
+ export declare function verifyBinding(proof: BindingProof, handshakeHash: Uint8Array, remoteRole: Role, opts?: VerifyBindingOptions): Promise<string>;
108
+ /** Binding plaintext: {"v":1,"did":"did:key:z...","sig":"<base64url>"} (exactly these keys). */
109
+ export declare function encodeBinding(p: BindingProof): Uint8Array;
110
+ export declare function decodeBinding(bytes: Uint8Array): BindingProof;
111
+ export interface SecureSession extends HandshakeResult {
112
+ readonly remoteDid: string;
113
+ }
114
+ export interface BindSessionOptions {
115
+ signer: BindingSigner;
116
+ expectedRemoteDid?: string;
117
+ verify?: BindingVerifier;
118
+ }
119
+ export interface PendingBinding {
120
+ /** Sealed local binding: send it as the first transport message. */
121
+ readonly localBinding: Uint8Array;
122
+ /** Opens and verifies the peer's first transport message. On failure the cipher is closed. */
123
+ accept(sealedRemoteBinding: Uint8Array): Promise<SecureSession>;
124
+ /** Abort: closes the cipher. */
125
+ close(): void;
126
+ }
127
+ /**
128
+ * Binding step over the fresh transport. No application data may be sealed or opened until
129
+ * `accept` resolves; any failure closes the cipher, so no usable session remains.
130
+ */
131
+ export declare function bindSession(result: HandshakeResult, o: BindSessionOptions): Promise<PendingBinding>;
132
+ /** Raw 32-byte Ed25519 key of a `did:key:z6Mk...` (multicodec 0xed01), or undefined. */
133
+ export declare function ed25519PublicKeyFromDidKey(did: unknown): Uint8Array | undefined;
134
+ /** Signer backed by a WebCrypto Ed25519 private key (may be non-extractable). */
135
+ export declare function webCryptoBindingSigner(did: string, privateKey: CryptoKey): BindingSigner;
@@ -0,0 +1,432 @@
1
+ // Secure channel v1 (spec/secure-channel-v1.md): Noise handshakes via the snow crate compiled to wasm,
2
+ // plus the post-handshake Ed25519 DID binding. No primitive is implemented here.
3
+ import initWasm, { initSync, generate_keypair, Handshake as WasmHandshake } from "../../noise-wasm/pkg/noise_wasm.js";
4
+ import { base64url, unbase64url, exactKeys } from "./encoding.js";
5
+ import { WireError } from "./errors.js";
6
+ import { MAX_SEALED_PLAINTEXT } from "./messages.js";
7
+ export const PAIR_PATTERN = "Noise_XXpsk3_25519_ChaChaPoly_SHA256";
8
+ export const RECONNECT_PATTERN = "Noise_KK_25519_ChaChaPoly_SHA256";
9
+ export const SECURE_CHANNEL_VERSION = 1;
10
+ /** Max plaintext per transport message: one frame chunk plus its sealed frame header. */
11
+ export const MAX_FRAME_PLAINTEXT = MAX_SEALED_PLAINTEXT;
12
+ export const NOISE_TAG_LEN = 16;
13
+ export const MAX_FRAME_SEALED = MAX_FRAME_PLAINTEXT + NOISE_TAG_LEN;
14
+ export const MAX_HANDSHAKE_PAYLOAD = 512;
15
+ export const MAX_HANDSHAKE_MESSAGE = 1024;
16
+ export const MAX_PROLOGUE_FIELD = 512;
17
+ export const MAX_BINDING_PLAINTEXT = 1024;
18
+ const te = new TextEncoder();
19
+ const EMPTY = new Uint8Array(0);
20
+ const PSK_POSITION = 3;
21
+ const PROLOGUE_LABEL = "mist-mcp/secure-channel";
22
+ const PSK_SALT = "mist-mcp/secure-channel/v1/pair-psk-salt";
23
+ const PSK_INFO = "mist-mcp/secure-channel/v1/pair-psk|" + PAIR_PATTERN;
24
+ const BINDING_LABEL = "mist-mcp/secure-channel/v1/binding|";
25
+ const fail = (message) => { throw new WireError("AUTH_FAILED", message); };
26
+ const invalid = (message) => { throw new WireError("INVALID_MESSAGE", message); };
27
+ let ready;
28
+ let loaded = false;
29
+ /**
30
+ * Loads the snow wasm once. Browsers/bundlers resolve `noise_wasm_bg.wasm` next to the glue via
31
+ * `import.meta.url`; Node reads the file directly. Pass `source` to override (e.g. a CDN URL).
32
+ */
33
+ export function initNoise(source) {
34
+ ready ??= (async () => {
35
+ const isNode = !!globalThis.process?.versions?.node;
36
+ if (source === undefined && isNode) {
37
+ const spec = "node:fs/promises";
38
+ const { readFile } = await import(/* @vite-ignore */ spec);
39
+ initSync({ module: await readFile(new URL("../../noise-wasm/pkg/noise_wasm_bg.wasm", import.meta.url)) });
40
+ }
41
+ else {
42
+ await initWasm(source === undefined ? undefined : { module_or_path: source });
43
+ }
44
+ loaded = true;
45
+ })();
46
+ ready.catch(() => { ready = undefined; });
47
+ return ready;
48
+ }
49
+ function assertLoaded() { if (!loaded)
50
+ throw new WireError("SESSION_CLOSED", "initNoise() has not completed"); }
51
+ /** Fresh X25519 Noise static keypair (snow's resolver RNG). */
52
+ export async function generateStaticKeypair() {
53
+ await initNoise();
54
+ const kp = generate_keypair();
55
+ return { privateKey: kp.slice(0, 32), publicKey: kp.slice(32, 64) };
56
+ }
57
+ const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
58
+ function field(v, name) {
59
+ if (typeof v !== "string" || v.length === 0 || LONE_SURROGATE.test(v))
60
+ return invalid(`prologue.${name} must be a non-empty well-formed string`);
61
+ const b = te.encode(v);
62
+ if (b.length > MAX_PROLOGUE_FIELD)
63
+ invalid(`prologue.${name} too long`);
64
+ return b;
65
+ }
66
+ /** label || 0x00 || version || lp(room) || lp(initiator) || lp(responder); lp = u16be length || UTF-8. */
67
+ export function encodePrologue(p) {
68
+ const parts = [field(p.roomId, "roomId"), field(p.initiatorNodeId, "initiatorNodeId"), field(p.responderNodeId, "responderNodeId")];
69
+ const label = te.encode(PROLOGUE_LABEL);
70
+ const out = new Uint8Array(label.length + 2 + parts.reduce((n, b) => n + 2 + b.length, 0));
71
+ out.set(label, 0);
72
+ let o = label.length;
73
+ out[o++] = 0;
74
+ out[o++] = SECURE_CHANNEL_VERSION;
75
+ for (const b of parts) {
76
+ out[o++] = b.length >>> 8;
77
+ out[o++] = b.length & 0xff;
78
+ out.set(b, o);
79
+ o += b.length;
80
+ }
81
+ return out;
82
+ }
83
+ const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
84
+ export const MIN_PAIRING_CODE_CHARS = 26; // 26 * 5 = 130 bits >= 128
85
+ export const MAX_PAIRING_CODE_CHARS = 64;
86
+ /** Crockford base32 normalisation: drop spaces/hyphens, uppercase, I/L -> 1, O -> 0. */
87
+ export function normalizePairingCode(code) {
88
+ if (typeof code !== "string")
89
+ return invalid("pairing code must be a string");
90
+ const n = code.replace(/[\s-]/g, "").toUpperCase().replace(/[IL]/g, "1").replace(/O/g, "0");
91
+ if (n.length < MIN_PAIRING_CODE_CHARS || n.length > MAX_PAIRING_CODE_CHARS || [...n].some(c => !CROCKFORD.includes(c)))
92
+ return invalid("invalid pairing code");
93
+ return n;
94
+ }
95
+ /** PSK = HKDF-SHA256(ikm = ASCII(normalized code), salt = PSK_SALT, info = PSK_INFO, L = 32). */
96
+ export async function derivePairingPsk(code) {
97
+ const ikm = te.encode(normalizePairingCode(code));
98
+ const key = await crypto.subtle.importKey("raw", ikm, "HKDF", false, ["deriveBits"]);
99
+ const bits = await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt: te.encode(PSK_SALT), info: te.encode(PSK_INFO) }, key, 256);
100
+ return new Uint8Array(bits);
101
+ }
102
+ class NoiseFrameCipher {
103
+ #t;
104
+ constructor(t) { this.#t = t; }
105
+ get closed() { return this.#t === undefined; }
106
+ close() { const t = this.#t; this.#t = undefined; if (t) {
107
+ try {
108
+ t.close();
109
+ t.free();
110
+ }
111
+ catch { /* already freed */ }
112
+ } }
113
+ #live() { const t = this.#t; if (!t)
114
+ throw new WireError("SESSION_CLOSED"); return t; }
115
+ seal(plain) {
116
+ const t = this.#live();
117
+ if (!(plain instanceof Uint8Array) || plain.length > MAX_FRAME_PLAINTEXT) {
118
+ this.close();
119
+ throw new WireError("LIMIT", "frame plaintext too large");
120
+ }
121
+ try {
122
+ return t.encrypt(plain);
123
+ }
124
+ catch {
125
+ this.close();
126
+ throw new WireError("SESSION_CLOSED", "encrypt failed");
127
+ }
128
+ }
129
+ open(sealed) {
130
+ const t = this.#live();
131
+ if (!(sealed instanceof Uint8Array) || sealed.length < NOISE_TAG_LEN || sealed.length > MAX_FRAME_SEALED) {
132
+ this.close();
133
+ throw new WireError("LIMIT", "sealed frame size out of range");
134
+ }
135
+ try {
136
+ return t.decrypt(sealed);
137
+ }
138
+ catch {
139
+ this.close();
140
+ throw new WireError("AUTH_FAILED", "frame authentication failed");
141
+ }
142
+ }
143
+ }
144
+ /**
145
+ * Stepwise handshake. The caller moves bytes: while `!isFinished`, call `writeMessage()` when
146
+ * `isMyTurn` and send the result, otherwise feed received bytes to `readMessage()`. Then `finish()`.
147
+ * Any error closes the handshake permanently.
148
+ */
149
+ export class NoiseHandshake {
150
+ pattern;
151
+ role;
152
+ #hs;
153
+ #pinned;
154
+ /** @internal use pairInitiator/pairResponder/reconnectInitiator/reconnectResponder */
155
+ constructor(pattern, role, hs, pinned) {
156
+ this.pattern = pattern;
157
+ this.role = role;
158
+ this.#hs = hs;
159
+ this.#pinned = pinned;
160
+ }
161
+ get closed() { return this.#hs === undefined; }
162
+ get isMyTurn() { return !!this.#hs?.is_my_turn(); }
163
+ get isFinished() { return !!this.#hs?.is_finished(); }
164
+ close() { const h = this.#hs; this.#hs = undefined; if (h) {
165
+ try {
166
+ h.close();
167
+ h.free();
168
+ }
169
+ catch { /* already freed */ }
170
+ } }
171
+ #live() { const h = this.#hs; if (!h)
172
+ throw new WireError("SESSION_CLOSED"); return h; }
173
+ writeMessage(payload = EMPTY) {
174
+ const h = this.#live();
175
+ if (!(payload instanceof Uint8Array) || payload.length > MAX_HANDSHAKE_PAYLOAD) {
176
+ this.close();
177
+ throw new WireError("LIMIT", "handshake payload too large");
178
+ }
179
+ if (h.is_finished() || !h.is_my_turn()) {
180
+ this.close();
181
+ return fail("handshake: not our turn");
182
+ }
183
+ try {
184
+ return h.write_message(payload);
185
+ }
186
+ catch {
187
+ this.close();
188
+ return fail("handshake write failed");
189
+ }
190
+ }
191
+ readMessage(message) {
192
+ const h = this.#live();
193
+ if (!(message instanceof Uint8Array) || message.length > MAX_HANDSHAKE_MESSAGE) {
194
+ this.close();
195
+ throw new WireError("LIMIT", "handshake message too large");
196
+ }
197
+ if (h.is_finished() || h.is_my_turn()) {
198
+ this.close();
199
+ return fail("handshake: unexpected message");
200
+ }
201
+ let payload;
202
+ try {
203
+ payload = h.read_message(message);
204
+ }
205
+ catch {
206
+ this.close();
207
+ return fail("handshake failed");
208
+ }
209
+ if (payload.length > MAX_HANDSHAKE_PAYLOAD) {
210
+ this.close();
211
+ throw new WireError("LIMIT", "handshake payload too large");
212
+ }
213
+ return payload;
214
+ }
215
+ /** Converts a finished handshake into the transport. The handshake is consumed either way. */
216
+ finish() {
217
+ const h = this.#live();
218
+ try {
219
+ if (!h.is_finished())
220
+ return fail("handshake not finished");
221
+ const remoteStatic = h.remote_static();
222
+ if (!remoteStatic || remoteStatic.length !== 32)
223
+ return fail("remote static missing");
224
+ if (this.#pinned && !equalBytes(this.#pinned, remoteStatic))
225
+ return fail("remote static mismatch");
226
+ const handshakeHash = h.handshake_hash();
227
+ const cipher = new NoiseFrameCipher(h.into_transport());
228
+ return { pattern: this.pattern, role: this.role, remoteStatic, handshakeHash, cipher };
229
+ }
230
+ catch (e) {
231
+ if (e instanceof WireError)
232
+ throw e;
233
+ return fail("transport setup failed");
234
+ }
235
+ finally {
236
+ this.close();
237
+ }
238
+ }
239
+ }
240
+ function checkKey(k, name) {
241
+ if (!(k instanceof Uint8Array) || k.length !== 32)
242
+ return invalid(`${name} must be 32 bytes`);
243
+ return k;
244
+ }
245
+ async function start(pattern, role, prologue, local, remote, psk) {
246
+ await initNoise();
247
+ assertLoaded();
248
+ const priv = checkKey(local?.privateKey, "localStatic.privateKey");
249
+ const pro = encodePrologue(prologue);
250
+ const pos = psk ? PSK_POSITION : undefined;
251
+ let hs;
252
+ try {
253
+ hs = role === "initiator" ? WasmHandshake.initiator(pattern, pro, priv, remote, psk, pos)
254
+ : WasmHandshake.responder(pattern, pro, priv, remote, psk, pos);
255
+ }
256
+ catch {
257
+ return invalid("invalid handshake parameters");
258
+ }
259
+ finally {
260
+ psk?.fill(0);
261
+ }
262
+ return new NoiseHandshake(pattern, role, hs, remote?.slice());
263
+ }
264
+ /** First pairing, initiator side (Noise_XXpsk3). Learns and returns the peer static key. */
265
+ export async function pairInitiator(o) {
266
+ return start(PAIR_PATTERN, "initiator", o.prologue, o.localStatic, undefined, await derivePairingPsk(o.code));
267
+ }
268
+ export async function pairResponder(o) {
269
+ return start(PAIR_PATTERN, "responder", o.prologue, o.localStatic, undefined, await derivePairingPsk(o.code));
270
+ }
271
+ /** Reconnect with the stored peer static key (Noise_KK). */
272
+ export async function reconnectInitiator(o) {
273
+ return start(RECONNECT_PATTERN, "initiator", o.prologue, o.localStatic, checkKey(o.remoteStatic, "remoteStatic"));
274
+ }
275
+ export async function reconnectResponder(o) {
276
+ return start(RECONNECT_PATTERN, "responder", o.prologue, o.localStatic, checkKey(o.remoteStatic, "remoteStatic"));
277
+ }
278
+ /** UTF-8(BINDING_LABEL + signerRole) || 0x00 || handshakeHash. */
279
+ export function bindingMessage(handshakeHash, signerRole) {
280
+ if (!(handshakeHash instanceof Uint8Array) || handshakeHash.length !== 32)
281
+ return invalid("handshake hash must be 32 bytes");
282
+ if (signerRole !== "initiator" && signerRole !== "responder")
283
+ return invalid("invalid role");
284
+ const label = te.encode(BINDING_LABEL + signerRole);
285
+ const out = new Uint8Array(label.length + 1 + 32);
286
+ out.set(label, 0);
287
+ out.set(handshakeHash, label.length + 1);
288
+ return out;
289
+ }
290
+ export async function signBinding(signer, handshakeHash, localRole) {
291
+ if (!ed25519PublicKeyFromDidKey(signer.did))
292
+ return invalid("signer.did must be an Ed25519 did:key");
293
+ const signature = await signer.sign(bindingMessage(handshakeHash, localRole));
294
+ if (!(signature instanceof Uint8Array) || signature.length !== 64)
295
+ return invalid("signer returned an invalid signature");
296
+ return { did: signer.did, signature: signature.slice() };
297
+ }
298
+ /** Throws AUTH_FAILED unless `proof` is a valid signature by `proof.did` for the remote role. */
299
+ export async function verifyBinding(proof, handshakeHash, remoteRole, opts = {}) {
300
+ const msg = bindingMessage(handshakeHash, remoteRole);
301
+ if (opts.expectedDid !== undefined && proof?.did !== opts.expectedDid)
302
+ fail("binding DID mismatch");
303
+ if (!ed25519PublicKeyFromDidKey(proof?.did) || !(proof.signature instanceof Uint8Array) || proof.signature.length !== 64)
304
+ fail("malformed binding");
305
+ let ok = false;
306
+ try {
307
+ ok = await (opts.verify ?? webCryptoVerify)(proof.did, msg, proof.signature);
308
+ }
309
+ catch {
310
+ ok = false;
311
+ }
312
+ if (ok !== true)
313
+ fail("binding signature invalid");
314
+ return proof.did;
315
+ }
316
+ /** Binding plaintext: {"v":1,"did":"did:key:z...","sig":"<base64url>"} (exactly these keys). */
317
+ export function encodeBinding(p) {
318
+ return te.encode(JSON.stringify({ v: SECURE_CHANNEL_VERSION, did: p.did, sig: base64url(p.signature) }));
319
+ }
320
+ export function decodeBinding(bytes) {
321
+ if (!(bytes instanceof Uint8Array) || bytes.length > MAX_BINDING_PLAINTEXT)
322
+ fail("binding too large");
323
+ let v;
324
+ try {
325
+ v = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
326
+ }
327
+ catch {
328
+ return fail("binding is not JSON");
329
+ }
330
+ if (!v || typeof v !== "object" || Array.isArray(v))
331
+ return fail("binding is not an object");
332
+ const o = v;
333
+ if (!exactKeys(o, ["v", "did", "sig"]) || o.v !== SECURE_CHANNEL_VERSION || typeof o.did !== "string" || typeof o.sig !== "string")
334
+ return fail("malformed binding");
335
+ let signature;
336
+ try {
337
+ signature = unbase64url(o.sig);
338
+ }
339
+ catch {
340
+ return fail("malformed binding signature");
341
+ }
342
+ return { did: o.did, signature };
343
+ }
344
+ /**
345
+ * Binding step over the fresh transport. No application data may be sealed or opened until
346
+ * `accept` resolves; any failure closes the cipher, so no usable session remains.
347
+ */
348
+ export async function bindSession(result, o) {
349
+ const { cipher, handshakeHash, role } = result;
350
+ let localBinding;
351
+ try {
352
+ localBinding = cipher.seal(encodeBinding(await signBinding(o.signer, handshakeHash, role)));
353
+ }
354
+ catch (e) {
355
+ cipher.close();
356
+ throw e;
357
+ }
358
+ let used = false;
359
+ return {
360
+ localBinding,
361
+ close: () => cipher.close(),
362
+ async accept(sealed) {
363
+ try {
364
+ if (used)
365
+ fail("binding already processed");
366
+ used = true;
367
+ const proof = decodeBinding(cipher.open(sealed));
368
+ const remoteDid = await verifyBinding(proof, handshakeHash, role === "initiator" ? "responder" : "initiator", { expectedDid: o.expectedRemoteDid, verify: o.verify });
369
+ if (cipher.closed)
370
+ throw new WireError("SESSION_CLOSED");
371
+ return { ...result, remoteDid };
372
+ }
373
+ catch (e) {
374
+ cipher.close();
375
+ throw e instanceof WireError ? e : new WireError("AUTH_FAILED", "binding failed");
376
+ }
377
+ },
378
+ };
379
+ }
380
+ // ---------------------------------------------------------------- did:key helpers
381
+ const B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
382
+ function base58btcDecode(s) {
383
+ const out = [];
384
+ for (const ch of s) {
385
+ let carry = B58.indexOf(ch);
386
+ if (carry < 0)
387
+ return undefined;
388
+ for (let j = 0; j < out.length; j++) {
389
+ carry += out[j] * 58;
390
+ out[j] = carry & 0xff;
391
+ carry >>= 8;
392
+ }
393
+ while (carry > 0) {
394
+ out.push(carry & 0xff);
395
+ carry >>= 8;
396
+ }
397
+ }
398
+ for (const ch of s) {
399
+ if (ch !== "1")
400
+ break;
401
+ out.push(0);
402
+ }
403
+ return Uint8Array.from(out.reverse());
404
+ }
405
+ /** Raw 32-byte Ed25519 key of a `did:key:z6Mk...` (multicodec 0xed01), or undefined. */
406
+ export function ed25519PublicKeyFromDidKey(did) {
407
+ if (typeof did !== "string" || !did.startsWith("did:key:z") || did.length > 128)
408
+ return undefined;
409
+ const b = base58btcDecode(did.slice("did:key:z".length));
410
+ if (!b || b.length !== 34 || b[0] !== 0xed || b[1] !== 0x01)
411
+ return undefined;
412
+ return b.slice(2);
413
+ }
414
+ async function webCryptoVerify(did, message, signature) {
415
+ const raw = ed25519PublicKeyFromDidKey(did);
416
+ if (!raw)
417
+ return false;
418
+ const key = await crypto.subtle.importKey("raw", raw, { name: "Ed25519" }, false, ["verify"]);
419
+ return crypto.subtle.verify({ name: "Ed25519" }, key, signature, message);
420
+ }
421
+ /** Signer backed by a WebCrypto Ed25519 private key (may be non-extractable). */
422
+ export function webCryptoBindingSigner(did, privateKey) {
423
+ return { did, sign: async (m) => new Uint8Array(await crypto.subtle.sign({ name: "Ed25519" }, privateKey, m)) };
424
+ }
425
+ function equalBytes(a, b) {
426
+ if (a.length !== b.length)
427
+ return false;
428
+ let d = 0;
429
+ for (let i = 0; i < a.length; i++)
430
+ d |= a[i] ^ b[i];
431
+ return d === 0;
432
+ }
@@ -0,0 +1,59 @@
1
+ # noise-wasm
2
+
3
+ Minimal [wasm-bindgen](https://github.com/rustwasm/wasm-bindgen) wrapper over the
4
+ [`snow`](https://github.com/mcginty/snow) Noise Protocol implementation, used by
5
+ `src/wire/noise-session.ts` (secure channel v1, see `../spec/secure-channel-v1.md`).
6
+
7
+ No cryptography is implemented here. The crate only:
8
+
9
+ - accepts exactly `Noise_XXpsk3_25519_ChaChaPoly_SHA256` and `Noise_KK_25519_ChaChaPoly_SHA256`;
10
+ - bounds key/message sizes;
11
+ - drops the snow state on any error, so a failed handshake or transport cannot be reused.
12
+
13
+ The native peer (mistl) must use the **same snow version** (`=0.9.6`, `default-resolver`).
14
+
15
+ ## API (wasm-bindgen exports)
16
+
17
+ | export | notes |
18
+ |---|---|
19
+ | `generate_keypair(): Uint8Array` | 64 bytes: X25519 private (32) ‖ public (32) |
20
+ | `Handshake.initiator / responder(pattern, prologue, local_private, remote_public?, psk?, psk_position?)` | |
21
+ | `hs.write_message(payload)`, `hs.read_message(msg)` | return message / payload |
22
+ | `hs.is_finished()`, `hs.is_my_turn()`, `hs.is_closed()`, `hs.handshake_hash()`, `hs.remote_static()` | |
23
+ | `hs.into_transport(): Transport` | consumes the handshake |
24
+ | `t.encrypt(plain)`, `t.decrypt(sealed)`, `t.close()` | one Noise transport message each, snow's internal nonce |
25
+
26
+ Applications should use the TypeScript wrapper, not these exports directly.
27
+
28
+ ## Prebuilt output
29
+
30
+ `pkg/` is checked in (`noise_wasm.js`, `noise_wasm.d.ts`, `noise_wasm_bg.wasm`,
31
+ `noise_wasm_bg.wasm.d.ts`) so npm consumers do not need Rust. It is built with
32
+ `--target web`: browsers/bundlers fetch `noise_wasm_bg.wasm` via
33
+ `new URL(..., import.meta.url)`; under Node, `initNoise()` reads the file with `node:fs`.
34
+
35
+ ## Rebuilding
36
+
37
+ Requirements: Rust stable, `rustup target add wasm32-unknown-unknown`, `wasm-pack` (it fetches
38
+ `wasm-bindgen-cli` and `wasm-opt`).
39
+
40
+ ```sh
41
+ cd noise-wasm
42
+ wasm-pack build --release --target web --out-dir pkg --out-name noise_wasm --no-pack
43
+ rm -f pkg/.gitignore # wasm-pack writes "*"; pkg/ must be committed
44
+ rm -rf target # optional: drop the build cache
45
+ ```
46
+
47
+ Release profile: `opt-level = "z"`, `lto = true`, `codegen-units = 1`, `panic = "abort"`, `strip`,
48
+ plus `wasm-opt -Oz` (configured in `Cargo.toml`).
49
+
50
+ ## Interop test
51
+
52
+ `interop/` contains a native snow peer and a Node driver that runs the real TypeScript wrapper
53
+ against it over stdin/stdout (XXpsk3 pairing, KK reconnect, DID binding, chunked JSON echo):
54
+
55
+ ```sh
56
+ cargo build --release --manifest-path noise-wasm/interop/Cargo.toml
57
+ node noise-wasm/interop/run.mjs # from the package root; Node >= 22.18 / 24 (type stripping)
58
+ rm -rf noise-wasm/interop/target
59
+ ```