@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.
- package/LICENSE +13 -0
- package/esm/chacha20poly1305.d.mts +18 -0
- package/esm/chacha20poly1305.mjs +152 -0
- package/esm/chain-node-mesh.d.mts +79 -0
- package/esm/chain-node-mesh.mjs +187 -0
- package/esm/http-transport.d.mts +72 -0
- package/esm/http-transport.mjs +216 -0
- package/esm/index.d.mts +6 -0
- package/esm/index.mjs +7 -0
- package/esm/mesh-tunnel.d.mts +165 -0
- package/esm/mesh-tunnel.mjs +350 -0
- package/esm/noise-session.d.mts +157 -0
- package/esm/noise-session.mjs +491 -0
- package/lib/_vendor/@noble/curves/LICENSE +21 -0
- package/lib/_vendor/@noble/curves/abstract/curve.cjs +338 -0
- package/lib/_vendor/@noble/curves/abstract/edwards.cjs +542 -0
- package/lib/_vendor/@noble/curves/abstract/hash-to-curve.cjs +72 -0
- package/lib/_vendor/@noble/curves/abstract/modular.cjs +557 -0
- package/lib/_vendor/@noble/curves/abstract/montgomery.cjs +149 -0
- package/lib/_vendor/@noble/curves/ed25519.cjs +302 -0
- package/lib/_vendor/@noble/curves/utils.cjs +436 -0
- package/lib/_vendor/@noble/hashes/LICENSE +21 -0
- package/lib/_vendor/@noble/hashes/_blake.cjs +300 -0
- package/lib/_vendor/@noble/hashes/_md.cjs +194 -0
- package/lib/_vendor/@noble/hashes/_u64.cjs +60 -0
- package/lib/_vendor/@noble/hashes/blake2.cjs +291 -0
- package/lib/_vendor/@noble/hashes/hkdf.cjs +104 -0
- package/lib/_vendor/@noble/hashes/hmac.cjs +86 -0
- package/lib/_vendor/@noble/hashes/sha2.cjs +417 -0
- package/lib/_vendor/@noble/hashes/utils.cjs +422 -0
- package/lib/chacha20poly1305.cjs +153 -0
- package/lib/chacha20poly1305.d.cts +18 -0
- package/lib/chain-node-mesh.cjs +189 -0
- package/lib/chain-node-mesh.d.cts +79 -0
- package/lib/http-transport.cjs +219 -0
- package/lib/http-transport.d.cts +72 -0
- package/lib/index.cjs +31 -0
- package/lib/index.d.cts +6 -0
- package/lib/mesh-tunnel.cjs +354 -0
- package/lib/mesh-tunnel.d.cts +165 -0
- package/lib/noise-session.cjs +503 -0
- package/lib/noise-session.d.cts +157 -0
- package/package.json +80 -4
- package/README.md +0 -3
|
@@ -0,0 +1,491 @@
|
|
|
1
|
+
import { chacha20poly1305 } from "./chacha20poly1305.mjs";
|
|
2
|
+
import { ed25519, x25519 } from "@noble/curves/ed25519.js";
|
|
3
|
+
import { sha512 } from "@noble/hashes/sha2.js";
|
|
4
|
+
import { fromPublicKey, isFromPublicKey } from "@arcblock/did";
|
|
5
|
+
import { blake2s } from "@noble/hashes/blake2.js";
|
|
6
|
+
import { hkdf } from "@noble/hashes/hkdf.js";
|
|
7
|
+
import { toDid } from "@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 toDid(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 = 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 : ed25519.utils.randomSecretKey();
|
|
109
|
+
const publicKey = 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 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 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 = 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 = blake2s(combined);
|
|
200
|
+
}
|
|
201
|
+
mixKey(inputKeyMaterial) {
|
|
202
|
+
const derived = hkdf(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 = hkdf(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 = 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 = 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(hkdf(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 && !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 = x25519.utils.randomSecretKey();
|
|
357
|
+
const ePub = x25519.getPublicKey(ePriv);
|
|
358
|
+
ss.mixHash(ePub);
|
|
359
|
+
const esShared = x25519.getSharedSecret(ePriv, remoteXPub);
|
|
360
|
+
ss.mixKey(esShared);
|
|
361
|
+
const encryptedS = ss.encryptAndHash(localXPub);
|
|
362
|
+
const ssShared = 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 = x25519.getSharedSecret(ePriv, rePub);
|
|
382
|
+
ss.mixKey(eeShared);
|
|
383
|
+
const seShared = 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 = x25519.getSharedSecret(localXPriv, iePub);
|
|
413
|
+
ss.mixKey(esShared);
|
|
414
|
+
const encryptedS = msg1.subarray(32, 80);
|
|
415
|
+
const isXPub = ss.decryptAndHash(encryptedS);
|
|
416
|
+
const ssShared = 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 = x25519.utils.randomSecretKey();
|
|
431
|
+
const ePub = x25519.getPublicKey(ePriv);
|
|
432
|
+
ss.mixHash(ePub);
|
|
433
|
+
const eeShared = x25519.getSharedSecret(ePriv, iePub);
|
|
434
|
+
ss.mixKey(eeShared);
|
|
435
|
+
const seShared = 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
|
+
export { KEY_SIZE, NONCE_SIZE, NoiseReplayError, NoiseSession, NoiseStealthDropError, ReplayWindow, TAG_SIZE, createNoiseIdentity, didFromPublicKey, edToX25519Priv, edToX25519Pub, fromHex, toHex };
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2022 Paul Miller (https://paulmillr.com)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the “Software”), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
|
13
|
+
all copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
21
|
+
THE SOFTWARE.
|