@arcblock/did-noise 0.0.0-stage → 1.30.26

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 (44) hide show
  1. package/LICENSE +13 -0
  2. package/esm/chacha20poly1305.d.mts +18 -0
  3. package/esm/chacha20poly1305.mjs +152 -0
  4. package/esm/chain-node-mesh.d.mts +79 -0
  5. package/esm/chain-node-mesh.mjs +187 -0
  6. package/esm/http-transport.d.mts +72 -0
  7. package/esm/http-transport.mjs +216 -0
  8. package/esm/index.d.mts +6 -0
  9. package/esm/index.mjs +7 -0
  10. package/esm/mesh-tunnel.d.mts +165 -0
  11. package/esm/mesh-tunnel.mjs +350 -0
  12. package/esm/noise-session.d.mts +157 -0
  13. package/esm/noise-session.mjs +491 -0
  14. package/lib/_vendor/@noble/curves/LICENSE +21 -0
  15. package/lib/_vendor/@noble/curves/abstract/curve.cjs +338 -0
  16. package/lib/_vendor/@noble/curves/abstract/edwards.cjs +542 -0
  17. package/lib/_vendor/@noble/curves/abstract/hash-to-curve.cjs +72 -0
  18. package/lib/_vendor/@noble/curves/abstract/modular.cjs +557 -0
  19. package/lib/_vendor/@noble/curves/abstract/montgomery.cjs +149 -0
  20. package/lib/_vendor/@noble/curves/ed25519.cjs +302 -0
  21. package/lib/_vendor/@noble/curves/utils.cjs +436 -0
  22. package/lib/_vendor/@noble/hashes/LICENSE +21 -0
  23. package/lib/_vendor/@noble/hashes/_blake.cjs +300 -0
  24. package/lib/_vendor/@noble/hashes/_md.cjs +194 -0
  25. package/lib/_vendor/@noble/hashes/_u64.cjs +60 -0
  26. package/lib/_vendor/@noble/hashes/blake2.cjs +291 -0
  27. package/lib/_vendor/@noble/hashes/hkdf.cjs +104 -0
  28. package/lib/_vendor/@noble/hashes/hmac.cjs +86 -0
  29. package/lib/_vendor/@noble/hashes/sha2.cjs +417 -0
  30. package/lib/_vendor/@noble/hashes/utils.cjs +422 -0
  31. package/lib/chacha20poly1305.cjs +153 -0
  32. package/lib/chacha20poly1305.d.cts +18 -0
  33. package/lib/chain-node-mesh.cjs +189 -0
  34. package/lib/chain-node-mesh.d.cts +79 -0
  35. package/lib/http-transport.cjs +219 -0
  36. package/lib/http-transport.d.cts +72 -0
  37. package/lib/index.cjs +31 -0
  38. package/lib/index.d.cts +6 -0
  39. package/lib/mesh-tunnel.cjs +354 -0
  40. package/lib/mesh-tunnel.d.cts +165 -0
  41. package/lib/noise-session.cjs +503 -0
  42. package/lib/noise-session.d.cts +157 -0
  43. package/package.json +80 -4
  44. package/README.md +0 -3
@@ -0,0 +1,503 @@
1
+ const require_chacha20poly1305 = require('./chacha20poly1305.cjs');
2
+ const require_sha2 = require('./_vendor/@noble/hashes/sha2.cjs');
3
+ const require_ed25519 = require('./_vendor/@noble/curves/ed25519.cjs');
4
+ const require_blake2 = require('./_vendor/@noble/hashes/blake2.cjs');
5
+ const require_hkdf = require('./_vendor/@noble/hashes/hkdf.cjs');
6
+ let _arcblock_did = require("@arcblock/did");
7
+ let _ocap_util = require("@ocap/util");
8
+
9
+ //#region src/noise-session.ts
10
+ /**
11
+ * Noise_IK Session — WireGuard-grade cryptographic transport for DID-Noise Mesh.
12
+ *
13
+ * Implements the Noise_IK handshake pattern (`Noise_IK_25519_ChaChaPoly_BLAKE2s`):
14
+ * - Curve25519 (X25519) for Diffie-Hellman, converted from Ed25519 (`did:abt`) keys
15
+ * - ChaCha20-Poly1305 (RFC 8439) for AEAD encryption
16
+ * - BLAKE2s for hashing and HKDF key derivation
17
+ * - 1-RTT First-Packet Stealth Admission (DID / Mesh VLAN / VC proof verification)
18
+ * - 64-bit sliding window anti-replay protection (WireGuard-style)
19
+ * - Symmetric session rekeying
20
+ */
21
+ const PROTOCOL_NAME = new TextEncoder().encode("Noise_IK_25519_ChaChaPoly_BLAKE2s");
22
+ const NONCE_SIZE = 12;
23
+ const KEY_SIZE = 32;
24
+ const TAG_SIZE = 16;
25
+ const CLAIMS_MAGIC_PREFIX = 123;
26
+ var NoiseStealthDropError = class extends Error {
27
+ constructor(reason) {
28
+ super(`Stealth drop: ${reason}`);
29
+ this.code = "NOISE_STEALTH_DROP";
30
+ this.name = "NoiseStealthDropError";
31
+ }
32
+ };
33
+ var NoiseReplayError = class extends Error {
34
+ constructor(nonce, reason) {
35
+ super(`Replay detected for nonce ${nonce.toString()}: ${reason}`);
36
+ this.code = "NOISE_REPLAY_DETECTED";
37
+ this.name = "NoiseReplayError";
38
+ this.nonce = nonce;
39
+ }
40
+ };
41
+ function toHex(bytes) {
42
+ return Buffer.from(bytes).toString("hex");
43
+ }
44
+ function fromHex(hex) {
45
+ const clean = hex.startsWith("0x") ? hex.slice(2) : hex;
46
+ return new Uint8Array(Buffer.from(clean, "hex"));
47
+ }
48
+ function didFromPublicKey(publicKey) {
49
+ const hex = typeof publicKey === "string" ? publicKey : toHex(publicKey);
50
+ return (0, _ocap_util.toDid)((0, _arcblock_did.fromPublicKey)(hex.startsWith("0x") ? hex : `0x${hex}`));
51
+ }
52
+ const P = 2n ** 255n - 19n;
53
+ function modP(a) {
54
+ const r = a % P;
55
+ return r >= 0n ? r : r + P;
56
+ }
57
+ function modInverse(a) {
58
+ return modPow(modP(a), P - 2n);
59
+ }
60
+ function modPow(base, exp) {
61
+ let result = 1n;
62
+ let b = modP(base);
63
+ let e = exp;
64
+ while (e > 0n) {
65
+ if (e & 1n) result = modP(result * b);
66
+ b = modP(b * b);
67
+ e >>= 1n;
68
+ }
69
+ return result;
70
+ }
71
+ /**
72
+ * Convert an Ed25519 public key (32 bytes) to an X25519 public key (32 bytes).
73
+ * Uses the birational map: u = (1 + y) / (1 - y) mod p, where p = 2^255 - 19.
74
+ */
75
+ function edToX25519Pub(edPub) {
76
+ if (edPub.length !== 32) throw new Error(`Invalid Ed25519 public key length: expected 32, got ${edPub.length}`);
77
+ const bytes = new Uint8Array(edPub);
78
+ bytes[31] &= 127;
79
+ let y = 0n;
80
+ for (let i = 0; i < 32; i++) y |= BigInt(bytes[i]) << BigInt(8 * i);
81
+ const u = modP(modP(1n + y) * modInverse(modP(1n - y)));
82
+ const result = new Uint8Array(32);
83
+ let val = u;
84
+ for (let i = 0; i < 32; i++) {
85
+ result[i] = Number(val & 255n);
86
+ val >>= 8n;
87
+ }
88
+ return result;
89
+ }
90
+ /**
91
+ * Convert an Ed25519 private key seed (first 32 bytes of 64-byte secretKey)
92
+ * to an X25519 private key (32 bytes).
93
+ */
94
+ function edToX25519Priv(edSeed) {
95
+ const seed = edSeed.length === 64 ? edSeed.subarray(0, 32) : edSeed;
96
+ if (seed.length !== 32) throw new Error(`Invalid Ed25519 seed length: expected 32 or 64, got ${edSeed.length}`);
97
+ const h = require_sha2.sha512(seed);
98
+ const x = new Uint8Array(h.subarray(0, 32));
99
+ x[0] &= 248;
100
+ x[31] &= 127;
101
+ x[31] |= 64;
102
+ return x;
103
+ }
104
+ /**
105
+ * Generate a fresh Ed25519-backed NoiseIdentity with its corresponding `did:abt:` identifier.
106
+ */
107
+ function createNoiseIdentity(seed) {
108
+ const privSeed = seed ? seed.length === 64 ? seed.subarray(0, 32) : seed : require_ed25519.ed25519.utils.randomSecretKey();
109
+ const publicKey = require_ed25519.ed25519.getPublicKey(privSeed);
110
+ const secretKey = new Uint8Array(64);
111
+ secretKey.set(privSeed, 0);
112
+ secretKey.set(publicKey, 32);
113
+ return {
114
+ secretKey,
115
+ publicKey,
116
+ pubkeyHex: toHex(publicKey),
117
+ did: didFromPublicKey(publicKey)
118
+ };
119
+ }
120
+ var ReplayWindow = class {
121
+ constructor() {
122
+ this.highestNonce = -1n;
123
+ this.bitmap = 0n;
124
+ this.windowSize = 64n;
125
+ }
126
+ /**
127
+ * Check and record a nonce. Throws `NoiseReplayError` if the nonce is replayed or too old.
128
+ */
129
+ checkAndAccept(nonce) {
130
+ if (nonce < 0n) throw new NoiseReplayError(nonce, "negative nonce");
131
+ if (this.highestNonce === -1n) {
132
+ this.highestNonce = nonce;
133
+ this.bitmap = 1n;
134
+ return;
135
+ }
136
+ if (nonce > this.highestNonce) {
137
+ const shift = nonce - this.highestNonce;
138
+ if (shift >= this.windowSize) this.bitmap = 1n;
139
+ else this.bitmap = (this.bitmap << shift | 1n) & (1n << this.windowSize) - 1n;
140
+ this.highestNonce = nonce;
141
+ return;
142
+ }
143
+ const diff = this.highestNonce - nonce;
144
+ if (diff >= this.windowSize) throw new NoiseReplayError(nonce, "nonce outside sliding replay window");
145
+ const mask = 1n << diff;
146
+ if ((this.bitmap & mask) !== 0n) throw new NoiseReplayError(nonce, "duplicate nonce");
147
+ this.bitmap |= mask;
148
+ }
149
+ reset() {
150
+ this.highestNonce = -1n;
151
+ this.bitmap = 0n;
152
+ }
153
+ };
154
+ function makeNonce(n) {
155
+ const nonce = new Uint8Array(NONCE_SIZE);
156
+ let val = n;
157
+ for (let i = 4; i < 12; i++) {
158
+ nonce[i] = Number(val & 255n);
159
+ val >>= 8n;
160
+ }
161
+ return nonce;
162
+ }
163
+ var CipherState = class {
164
+ constructor() {
165
+ this.k = null;
166
+ this.n = 0n;
167
+ }
168
+ initializeKey(key) {
169
+ this.k = new Uint8Array(key);
170
+ this.n = 0n;
171
+ }
172
+ hasKey() {
173
+ return this.k !== null;
174
+ }
175
+ encryptWithAd(ad, plaintext) {
176
+ if (!this.k) return plaintext;
177
+ const nonce = makeNonce(this.n++);
178
+ return require_chacha20poly1305.chacha20poly1305(this.k, nonce, ad).encrypt(plaintext);
179
+ }
180
+ decryptWithAd(ad, ciphertext) {
181
+ if (!this.k) return ciphertext;
182
+ const nonce = makeNonce(this.n++);
183
+ return require_chacha20poly1305.chacha20poly1305(this.k, nonce, ad).decrypt(ciphertext);
184
+ }
185
+ };
186
+ var SymmetricState = class {
187
+ constructor() {
188
+ this.cipher = new CipherState();
189
+ if (PROTOCOL_NAME.length <= 32) {
190
+ this.h = new Uint8Array(32);
191
+ this.h.set(PROTOCOL_NAME);
192
+ } else this.h = require_blake2.blake2s(PROTOCOL_NAME);
193
+ this.ck = new Uint8Array(this.h);
194
+ }
195
+ mixHash(data) {
196
+ const combined = new Uint8Array(this.h.length + data.length);
197
+ combined.set(this.h);
198
+ combined.set(data, this.h.length);
199
+ this.h = require_blake2.blake2s(combined);
200
+ }
201
+ mixKey(inputKeyMaterial) {
202
+ const derived = require_hkdf.hkdf(require_blake2.blake2s, inputKeyMaterial, this.ck, void 0, 64);
203
+ this.ck = derived.subarray(0, 32);
204
+ const tempK = derived.subarray(32, 64);
205
+ this.cipher.initializeKey(tempK);
206
+ }
207
+ encryptAndHash(plaintext) {
208
+ const ciphertext = this.cipher.encryptWithAd(this.h, plaintext);
209
+ this.mixHash(ciphertext);
210
+ return ciphertext;
211
+ }
212
+ decryptAndHash(ciphertext) {
213
+ const plaintext = this.cipher.decryptWithAd(this.h, ciphertext);
214
+ this.mixHash(ciphertext);
215
+ return plaintext;
216
+ }
217
+ split() {
218
+ const derived = require_hkdf.hkdf(require_blake2.blake2s, new Uint8Array(0), this.ck, void 0, 64);
219
+ return {
220
+ sendKey: new Uint8Array(derived.subarray(0, 32)),
221
+ recvKey: new Uint8Array(derived.subarray(32, 64))
222
+ };
223
+ }
224
+ };
225
+ const REKEY_INFO = new TextEncoder().encode("Noise_IK_Rekey");
226
+ var TransportCipher = class {
227
+ constructor(key) {
228
+ this.nonce = 0n;
229
+ this.messageCount = 0;
230
+ this.createdAt = Date.now();
231
+ this.replayWindow = new ReplayWindow();
232
+ this.key = new Uint8Array(key);
233
+ }
234
+ encrypt(plaintext, aad = new Uint8Array(0)) {
235
+ const n = this.nonce++;
236
+ this.messageCount++;
237
+ const nonce = makeNonce(n);
238
+ const ct = require_chacha20poly1305.chacha20poly1305(this.key, nonce, aad).encrypt(plaintext);
239
+ const out = new Uint8Array(8 + ct.length);
240
+ let val = n;
241
+ for (let i = 0; i < 8; i++) {
242
+ out[i] = Number(val & 255n);
243
+ val >>= 8n;
244
+ }
245
+ out.set(ct, 8);
246
+ return out;
247
+ }
248
+ decrypt(data, aad = new Uint8Array(0), enforceReplayProtection = false) {
249
+ if (data.length < 8 + TAG_SIZE) throw new Error("Ciphertext too short");
250
+ let n = 0n;
251
+ for (let i = 0; i < 8; i++) n |= BigInt(data[i]) << BigInt(8 * i);
252
+ const nonce = makeNonce(n);
253
+ const ct = data.subarray(8);
254
+ const plaintext = require_chacha20poly1305.chacha20poly1305(this.key, nonce, aad).decrypt(ct);
255
+ if (enforceReplayProtection) this.replayWindow.checkAndAccept(n);
256
+ this.messageCount++;
257
+ return plaintext;
258
+ }
259
+ rekey() {
260
+ this.key = new Uint8Array(require_hkdf.hkdf(require_blake2.blake2s, this.key, void 0, REKEY_INFO, 32));
261
+ this.nonce = 0n;
262
+ this.messageCount = 0;
263
+ this.replayWindow.reset();
264
+ }
265
+ get stats() {
266
+ return {
267
+ messageCount: this.messageCount,
268
+ ageMs: Date.now() - this.createdAt,
269
+ currentNonce: this.nonce
270
+ };
271
+ }
272
+ };
273
+ function encodeFirstPacketPayload(edPub, options) {
274
+ if (!(options && (options.meshId !== void 0 || options.membershipProof !== void 0 || options.metadata !== void 0 || options.includeTimestamp))) return edPub;
275
+ const claims = {
276
+ pubkeyHex: toHex(edPub),
277
+ did: didFromPublicKey(edPub),
278
+ ...options.meshId !== void 0 ? { meshId: options.meshId } : {},
279
+ ...options.membershipProof !== void 0 ? { membershipProof: options.membershipProof } : {},
280
+ ...options.includeTimestamp ? { timestamp: Date.now() } : {},
281
+ ...options.metadata !== void 0 ? { metadata: options.metadata } : {}
282
+ };
283
+ return new TextEncoder().encode(JSON.stringify(claims));
284
+ }
285
+ function decodeFirstPacketPayload(payload) {
286
+ if (payload.length === 32 && payload[0] !== CLAIMS_MAGIC_PREFIX) return {
287
+ pubkeyHex: toHex(payload),
288
+ did: didFromPublicKey(payload)
289
+ };
290
+ let parsed;
291
+ try {
292
+ parsed = JSON.parse(new TextDecoder().decode(payload));
293
+ } catch {
294
+ throw new NoiseStealthDropError("Malformed handshake claims payload");
295
+ }
296
+ if (!parsed.pubkeyHex || typeof parsed.pubkeyHex !== "string") throw new NoiseStealthDropError("Missing pubkeyHex in handshake claims");
297
+ const pubBytes = fromHex(parsed.pubkeyHex);
298
+ if (pubBytes.length !== 32) throw new NoiseStealthDropError("Invalid pubkeyHex length in handshake claims");
299
+ const expectedDid = didFromPublicKey(pubBytes);
300
+ if (parsed.did && !(0, _arcblock_did.isFromPublicKey)(parsed.did, `0x${parsed.pubkeyHex}`) && parsed.did !== expectedDid) throw new NoiseStealthDropError("DID does not match public key in handshake claims");
301
+ return {
302
+ pubkeyHex: parsed.pubkeyHex,
303
+ did: parsed.did || expectedDid,
304
+ ...parsed.meshId !== void 0 ? { meshId: parsed.meshId } : {},
305
+ ...parsed.membershipProof !== void 0 ? { membershipProof: parsed.membershipProof } : {},
306
+ ...parsed.timestamp !== void 0 ? { timestamp: parsed.timestamp } : {},
307
+ ...parsed.metadata !== void 0 ? { metadata: parsed.metadata } : {}
308
+ };
309
+ }
310
+ var NoiseSession = class NoiseSession {
311
+ constructor() {
312
+ this.sendCipher = null;
313
+ this.recvCipher = null;
314
+ this._remotePubkeyHex = null;
315
+ this._remoteDid = null;
316
+ this._remoteClaims = null;
317
+ this._ready = false;
318
+ this._replayProtection = false;
319
+ this.handleResponse = () => {
320
+ throw new Error("handleResponse only valid on initiator session");
321
+ };
322
+ }
323
+ /** The authenticated remote peer's Ed25519 pubkey hex (available after handshake). */
324
+ get remotePubkeyHex() {
325
+ return this._remotePubkeyHex;
326
+ }
327
+ /** The authenticated remote peer's `did:abt:...` identifier (available after handshake). */
328
+ get remoteDid() {
329
+ return this._remoteDid;
330
+ }
331
+ /** Full handshake claims presented by the remote peer (available after handshake). */
332
+ get remoteClaims() {
333
+ return this._remoteClaims;
334
+ }
335
+ isReady() {
336
+ return this._ready;
337
+ }
338
+ /**
339
+ * Enable or disable 64-bit sliding window anti-replay enforcement on `decrypt()`.
340
+ */
341
+ setReplayProtection(enabled) {
342
+ this._replayProtection = enabled;
343
+ return this;
344
+ }
345
+ /**
346
+ * Create an initiator session and generate handshake message 1 (`→ e, es, s, ss`).
347
+ */
348
+ static initiator(localIdentity, remoteEdPubHex, options) {
349
+ const session = new NoiseSession();
350
+ const ss = new SymmetricState();
351
+ const localXPriv = edToX25519Priv(localIdentity.secretKey.subarray(0, 32));
352
+ const localXPub = edToX25519Pub(localIdentity.publicKey);
353
+ const remoteEdPub = fromHex(remoteEdPubHex);
354
+ const remoteXPub = edToX25519Pub(remoteEdPub);
355
+ ss.mixHash(remoteXPub);
356
+ const ePriv = require_ed25519.x25519.utils.randomSecretKey();
357
+ const ePub = require_ed25519.x25519.getPublicKey(ePriv);
358
+ ss.mixHash(ePub);
359
+ const esShared = require_ed25519.x25519.getSharedSecret(ePriv, remoteXPub);
360
+ ss.mixKey(esShared);
361
+ const encryptedS = ss.encryptAndHash(localXPub);
362
+ const ssShared = require_ed25519.x25519.getSharedSecret(localXPriv, remoteXPub);
363
+ ss.mixKey(ssShared);
364
+ const payloadBytes = encodeFirstPacketPayload(localIdentity.publicKey, options);
365
+ const encryptedPayload = ss.encryptAndHash(payloadBytes);
366
+ const msg1 = new Uint8Array(32 + encryptedS.length + encryptedPayload.length);
367
+ msg1.set(ePub, 0);
368
+ msg1.set(encryptedS, 32);
369
+ msg1.set(encryptedPayload, 32 + encryptedS.length);
370
+ session._remotePubkeyHex = remoteEdPubHex;
371
+ session._remoteDid = didFromPublicKey(remoteEdPub);
372
+ session._remoteClaims = {
373
+ pubkeyHex: remoteEdPubHex,
374
+ did: session._remoteDid,
375
+ ...options?.meshId !== void 0 ? { meshId: options.meshId } : {}
376
+ };
377
+ const handleResponse = (msg2) => {
378
+ if (msg2.length < 32 + TAG_SIZE) throw new Error("Handshake response too short");
379
+ const rePub = msg2.subarray(0, 32);
380
+ ss.mixHash(rePub);
381
+ const eeShared = require_ed25519.x25519.getSharedSecret(ePriv, rePub);
382
+ ss.mixKey(eeShared);
383
+ const seShared = require_ed25519.x25519.getSharedSecret(localXPriv, rePub);
384
+ ss.mixKey(seShared);
385
+ const encPayload = msg2.subarray(32);
386
+ ss.decryptAndHash(encPayload);
387
+ const { sendKey, recvKey } = ss.split();
388
+ session.sendCipher = new TransportCipher(sendKey);
389
+ session.recvCipher = new TransportCipher(recvKey);
390
+ session._ready = true;
391
+ };
392
+ session.handleResponse = handleResponse;
393
+ return {
394
+ handshakeMsg: msg1,
395
+ session,
396
+ handleResponse
397
+ };
398
+ }
399
+ /**
400
+ * Create a responder session and process handshake message 1 (`← e, ee, se`).
401
+ */
402
+ static responder(localIdentity, options) {
403
+ const session = new NoiseSession();
404
+ const localXPriv = edToX25519Priv(localIdentity.secretKey.subarray(0, 32));
405
+ const localXPub = edToX25519Pub(localIdentity.publicKey);
406
+ const processHandshake = (msg1) => {
407
+ if (msg1.length < 96) throw new NoiseStealthDropError("Handshake message 1 too short");
408
+ const ss = new SymmetricState();
409
+ ss.mixHash(localXPub);
410
+ const iePub = msg1.subarray(0, 32);
411
+ ss.mixHash(iePub);
412
+ const esShared = require_ed25519.x25519.getSharedSecret(localXPriv, iePub);
413
+ ss.mixKey(esShared);
414
+ const encryptedS = msg1.subarray(32, 80);
415
+ const isXPub = ss.decryptAndHash(encryptedS);
416
+ const ssShared = require_ed25519.x25519.getSharedSecret(localXPriv, isXPub);
417
+ ss.mixKey(ssShared);
418
+ const encryptedPayload = msg1.subarray(80);
419
+ const claims = decodeFirstPacketPayload(ss.decryptAndHash(encryptedPayload));
420
+ if (toHex(edToX25519Pub(fromHex(claims.pubkeyHex))) !== toHex(isXPub)) throw new NoiseStealthDropError("Ed25519 public key in payload does not match X25519 static key");
421
+ const maxSkew = options?.maxClockSkewMs ?? 3e5;
422
+ if (claims.timestamp !== void 0 && maxSkew > 0) {
423
+ const skew = Math.abs(Date.now() - claims.timestamp);
424
+ if (skew > maxSkew) throw new NoiseStealthDropError(`Handshake timestamp skew ${skew}ms exceeds ${maxSkew}ms`);
425
+ }
426
+ if (options?.admissionPolicy && !options.admissionPolicy(claims)) throw new NoiseStealthDropError(`Peer ${claims.did} (${claims.pubkeyHex}) rejected by admission policy for mesh ${claims.meshId ?? "default"}`);
427
+ session._remotePubkeyHex = claims.pubkeyHex;
428
+ session._remoteDid = claims.did;
429
+ session._remoteClaims = claims;
430
+ const ePriv = require_ed25519.x25519.utils.randomSecretKey();
431
+ const ePub = require_ed25519.x25519.getPublicKey(ePriv);
432
+ ss.mixHash(ePub);
433
+ const eeShared = require_ed25519.x25519.getSharedSecret(ePriv, iePub);
434
+ ss.mixKey(eeShared);
435
+ const seShared = require_ed25519.x25519.getSharedSecret(ePriv, isXPub);
436
+ ss.mixKey(seShared);
437
+ const encEmpty = ss.encryptAndHash(new Uint8Array(0));
438
+ const { sendKey, recvKey } = ss.split();
439
+ session.sendCipher = new TransportCipher(recvKey);
440
+ session.recvCipher = new TransportCipher(sendKey);
441
+ session._ready = true;
442
+ const msg2 = new Uint8Array(32 + encEmpty.length);
443
+ msg2.set(ePub, 0);
444
+ msg2.set(encEmpty, 32);
445
+ return msg2;
446
+ };
447
+ return {
448
+ session,
449
+ processHandshake
450
+ };
451
+ }
452
+ /**
453
+ * Encrypt a message using the established transport session.
454
+ */
455
+ encrypt(plaintext, aad = new Uint8Array(0)) {
456
+ if (!this._ready || !this.sendCipher) throw new Error("NoiseSession not ready — handshake incomplete");
457
+ return this.sendCipher.encrypt(plaintext, aad);
458
+ }
459
+ /**
460
+ * Decrypt a message using the established transport session.
461
+ */
462
+ decrypt(ciphertext, aad = new Uint8Array(0)) {
463
+ if (!this._ready || !this.recvCipher) throw new Error("NoiseSession not ready — handshake incomplete");
464
+ return this.recvCipher.decrypt(ciphertext, aad, this._replayProtection);
465
+ }
466
+ /**
467
+ * Ratchet the outbound transport key forward (forward-secure rekey).
468
+ */
469
+ rekeySend() {
470
+ if (!this._ready || !this.sendCipher) throw new Error("NoiseSession not ready");
471
+ this.sendCipher.rekey();
472
+ }
473
+ /**
474
+ * Ratchet the inbound transport key forward (must be coordinated with peer's `rekeySend()`).
475
+ */
476
+ rekeyRecv() {
477
+ if (!this._ready || !this.recvCipher) throw new Error("NoiseSession not ready");
478
+ this.recvCipher.rekey();
479
+ }
480
+ /**
481
+ * Check whether the session should be rekeyed based on message count or age.
482
+ */
483
+ needsRekey(maxMessages = 1e6, maxAgeMs = 36e5) {
484
+ if (!this._ready || !this.sendCipher) return false;
485
+ const { messageCount, ageMs } = this.sendCipher.stats;
486
+ return messageCount >= maxMessages || ageMs >= maxAgeMs;
487
+ }
488
+ };
489
+
490
+ //#endregion
491
+ exports.KEY_SIZE = KEY_SIZE;
492
+ exports.NONCE_SIZE = NONCE_SIZE;
493
+ exports.NoiseReplayError = NoiseReplayError;
494
+ exports.NoiseSession = NoiseSession;
495
+ exports.NoiseStealthDropError = NoiseStealthDropError;
496
+ exports.ReplayWindow = ReplayWindow;
497
+ exports.TAG_SIZE = TAG_SIZE;
498
+ exports.createNoiseIdentity = createNoiseIdentity;
499
+ exports.didFromPublicKey = didFromPublicKey;
500
+ exports.edToX25519Priv = edToX25519Priv;
501
+ exports.edToX25519Pub = edToX25519Pub;
502
+ exports.fromHex = fromHex;
503
+ exports.toHex = toHex;
@@ -0,0 +1,157 @@
1
+ //#region src/noise-session.d.ts
2
+ /**
3
+ * Noise_IK Session — WireGuard-grade cryptographic transport for DID-Noise Mesh.
4
+ *
5
+ * Implements the Noise_IK handshake pattern (`Noise_IK_25519_ChaChaPoly_BLAKE2s`):
6
+ * - Curve25519 (X25519) for Diffie-Hellman, converted from Ed25519 (`did:abt`) keys
7
+ * - ChaCha20-Poly1305 (RFC 8439) for AEAD encryption
8
+ * - BLAKE2s for hashing and HKDF key derivation
9
+ * - 1-RTT First-Packet Stealth Admission (DID / Mesh VLAN / VC proof verification)
10
+ * - 64-bit sliding window anti-replay protection (WireGuard-style)
11
+ * - Symmetric session rekeying
12
+ */
13
+ declare const NONCE_SIZE = 12;
14
+ declare const KEY_SIZE = 32;
15
+ declare const TAG_SIZE = 16;
16
+ declare class NoiseStealthDropError extends Error {
17
+ readonly code = "NOISE_STEALTH_DROP";
18
+ constructor(reason: string);
19
+ }
20
+ declare class NoiseReplayError extends Error {
21
+ readonly code = "NOISE_REPLAY_DETECTED";
22
+ readonly nonce: bigint;
23
+ constructor(nonce: bigint, reason: string);
24
+ }
25
+ declare function toHex(bytes: Uint8Array): string;
26
+ declare function fromHex(hex: string): Uint8Array;
27
+ declare function didFromPublicKey(publicKey: Uint8Array | string): string;
28
+ /**
29
+ * Convert an Ed25519 public key (32 bytes) to an X25519 public key (32 bytes).
30
+ * Uses the birational map: u = (1 + y) / (1 - y) mod p, where p = 2^255 - 19.
31
+ */
32
+ declare function edToX25519Pub(edPub: Uint8Array): Uint8Array;
33
+ /**
34
+ * Convert an Ed25519 private key seed (first 32 bytes of 64-byte secretKey)
35
+ * to an X25519 private key (32 bytes).
36
+ */
37
+ declare function edToX25519Priv(edSeed: Uint8Array): Uint8Array;
38
+ interface NoiseIdentity {
39
+ secretKey: Uint8Array;
40
+ publicKey: Uint8Array;
41
+ pubkeyHex: string;
42
+ did?: string;
43
+ }
44
+ /**
45
+ * Generate a fresh Ed25519-backed NoiseIdentity with its corresponding `did:abt:` identifier.
46
+ */
47
+ declare function createNoiseIdentity(seed?: Uint8Array): NoiseIdentity;
48
+ declare class ReplayWindow {
49
+ private highestNonce;
50
+ private bitmap;
51
+ private readonly windowSize;
52
+ /**
53
+ * Check and record a nonce. Throws `NoiseReplayError` if the nonce is replayed or too old.
54
+ */
55
+ checkAndAccept(nonce: bigint): void;
56
+ reset(): void;
57
+ }
58
+ interface NoiseHandshakeClaims {
59
+ /** Initiator's 32-byte Ed25519 public key in hex */
60
+ pubkeyHex: string;
61
+ /** Initiator's derived `did:abt:...` identifier */
62
+ did: string;
63
+ /** Optional virtual LAN / Mesh identifier (e.g. `personal`, `team-core`, `ops-prod`) */
64
+ meshId?: string;
65
+ /** Optional Verifiable Credential (JWT or JSON VC) or delegation proof */
66
+ membershipProof?: string;
67
+ /** Unix timestamp (ms) when handshake was initiated */
68
+ timestamp?: number;
69
+ /** Optional application metadata */
70
+ metadata?: Record<string, unknown>;
71
+ }
72
+ /**
73
+ * Policy callback evaluated inside `readMessage1` after decrypting the initiator's static identity.
74
+ * Return `true` to accept the handshake, or `false` to trigger a silent 1-RTT Stealth Drop.
75
+ */
76
+ type NoiseAdmissionPolicy = (claims: NoiseHandshakeClaims) => boolean;
77
+ interface NoiseInitiatorOptions {
78
+ /** Target virtual LAN / Mesh ID */
79
+ meshId?: string;
80
+ /** Optional VC / delegation token proving membership in `meshId` */
81
+ membershipProof?: string;
82
+ /** Optional metadata included in encrypted first packet */
83
+ metadata?: Record<string, unknown>;
84
+ /** Include timestamp in encrypted first packet */
85
+ includeTimestamp?: boolean;
86
+ }
87
+ interface NoiseResponderOptions {
88
+ /**
89
+ * Optional 1-RTT stealth admission policy.
90
+ * Evaluated before sending any response packet; rejecting throws `NoiseStealthDropError`.
91
+ */
92
+ admissionPolicy?: NoiseAdmissionPolicy;
93
+ /**
94
+ * Maximum allowed clock skew (ms) when `claims.timestamp` is present.
95
+ * Defaults to 5 minutes (300_000 ms) if > 0.
96
+ */
97
+ maxClockSkewMs?: number;
98
+ }
99
+ declare class NoiseSession {
100
+ private sendCipher;
101
+ private recvCipher;
102
+ private _remotePubkeyHex;
103
+ private _remoteDid;
104
+ private _remoteClaims;
105
+ private _ready;
106
+ private _replayProtection;
107
+ /** The authenticated remote peer's Ed25519 pubkey hex (available after handshake). */
108
+ get remotePubkeyHex(): string | null;
109
+ /** The authenticated remote peer's `did:abt:...` identifier (available after handshake). */
110
+ get remoteDid(): string | null;
111
+ /** Full handshake claims presented by the remote peer (available after handshake). */
112
+ get remoteClaims(): NoiseHandshakeClaims | null;
113
+ isReady(): boolean;
114
+ /**
115
+ * Enable or disable 64-bit sliding window anti-replay enforcement on `decrypt()`.
116
+ */
117
+ setReplayProtection(enabled: boolean): this;
118
+ /**
119
+ * Create an initiator session and generate handshake message 1 (`→ e, es, s, ss`).
120
+ */
121
+ static initiator(localIdentity: NoiseIdentity, remoteEdPubHex: string, options?: NoiseInitiatorOptions): {
122
+ handshakeMsg: Uint8Array;
123
+ session: NoiseSession;
124
+ handleResponse: (msg2: Uint8Array) => void;
125
+ };
126
+ /** Complete handshake on initiator side (set by `NoiseSession.initiator()`). */
127
+ handleResponse: (msg2: Uint8Array) => void;
128
+ /**
129
+ * Create a responder session and process handshake message 1 (`← e, ee, se`).
130
+ */
131
+ static responder(localIdentity: NoiseIdentity, options?: NoiseResponderOptions): {
132
+ session: NoiseSession;
133
+ processHandshake: (msg1: Uint8Array) => Uint8Array;
134
+ };
135
+ /**
136
+ * Encrypt a message using the established transport session.
137
+ */
138
+ encrypt(plaintext: Uint8Array, aad?: Uint8Array): Uint8Array;
139
+ /**
140
+ * Decrypt a message using the established transport session.
141
+ */
142
+ decrypt(ciphertext: Uint8Array, aad?: Uint8Array): Uint8Array;
143
+ /**
144
+ * Ratchet the outbound transport key forward (forward-secure rekey).
145
+ */
146
+ rekeySend(): void;
147
+ /**
148
+ * Ratchet the inbound transport key forward (must be coordinated with peer's `rekeySend()`).
149
+ */
150
+ rekeyRecv(): void;
151
+ /**
152
+ * Check whether the session should be rekeyed based on message count or age.
153
+ */
154
+ needsRekey(maxMessages?: number, maxAgeMs?: number): boolean;
155
+ }
156
+ //#endregion
157
+ export { KEY_SIZE, NONCE_SIZE, NoiseAdmissionPolicy, NoiseHandshakeClaims, NoiseIdentity, NoiseInitiatorOptions, NoiseReplayError, NoiseResponderOptions, NoiseSession, NoiseStealthDropError, ReplayWindow, TAG_SIZE, createNoiseIdentity, didFromPublicKey, edToX25519Priv, edToX25519Pub, fromHex, toHex };