@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,422 @@
1
+
2
+ //#region ../../node_modules/@noble/hashes/utils.js
3
+ /**
4
+ * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
5
+ * @param a - value to test
6
+ * @returns `true` when the value is a Uint8Array-compatible view.
7
+ * @example
8
+ * Check whether a value is a Uint8Array-compatible view.
9
+ * ```ts
10
+ * isBytes(new Uint8Array([1, 2, 3]));
11
+ * ```
12
+ */
13
+ function isBytes(a) {
14
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
15
+ }
16
+ /**
17
+ * Asserts something is a non-negative integer.
18
+ * @param n - number to validate
19
+ * @param title - label included in thrown errors
20
+ * @throws On wrong argument types. {@link TypeError}
21
+ * @throws On wrong argument ranges or values. {@link RangeError}
22
+ * @example
23
+ * Validate a non-negative integer option.
24
+ * ```ts
25
+ * anumber(32, 'length');
26
+ * ```
27
+ */
28
+ function anumber(n, title = "") {
29
+ if (typeof n !== "number") {
30
+ const prefix = title && `"${title}" `;
31
+ throw new TypeError(`${prefix}expected number, got ${typeof n}`);
32
+ }
33
+ if (!Number.isSafeInteger(n) || n < 0) {
34
+ const prefix = title && `"${title}" `;
35
+ throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);
36
+ }
37
+ }
38
+ /**
39
+ * Asserts something is Uint8Array.
40
+ * @param value - value to validate
41
+ * @param length - optional exact length constraint
42
+ * @param title - label included in thrown errors
43
+ * @returns The validated byte array.
44
+ * @throws On wrong argument types. {@link TypeError}
45
+ * @throws On wrong argument ranges or values. {@link RangeError}
46
+ * @example
47
+ * Validate that a value is a byte array.
48
+ * ```ts
49
+ * abytes(new Uint8Array([1, 2, 3]));
50
+ * ```
51
+ */
52
+ function abytes(value, length, title = "") {
53
+ const bytes = isBytes(value);
54
+ const len = value?.length;
55
+ const needsLen = length !== void 0;
56
+ if (!bytes || needsLen && len !== length) {
57
+ const prefix = title && `"${title}" `;
58
+ const ofLen = needsLen ? ` of length ${length}` : "";
59
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
60
+ const message = prefix + "expected Uint8Array" + ofLen + ", got " + got;
61
+ if (!bytes) throw new TypeError(message);
62
+ throw new RangeError(message);
63
+ }
64
+ return value;
65
+ }
66
+ /**
67
+ * Asserts something is a wrapped hash constructor.
68
+ * @param h - hash constructor to validate
69
+ * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}
70
+ * @throws On invalid hash metadata ranges or values. {@link RangeError}
71
+ * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}
72
+ * @example
73
+ * Validate a callable hash wrapper.
74
+ * ```ts
75
+ * import { ahash } from '@noble/hashes/utils.js';
76
+ * import { sha256 } from '@noble/hashes/sha2.js';
77
+ * ahash(sha256);
78
+ * ```
79
+ */
80
+ function ahash(h) {
81
+ if (typeof h !== "function" || typeof h.create !== "function") throw new TypeError("Hash must wrapped by utils.createHasher");
82
+ anumber(h.outputLen);
83
+ anumber(h.blockLen);
84
+ if (h.outputLen < 1) throw new Error("\"outputLen\" must be >= 1");
85
+ if (h.blockLen < 1) throw new Error("\"blockLen\" must be >= 1");
86
+ }
87
+ /**
88
+ * Asserts a hash instance has not been destroyed or finished.
89
+ * @param instance - hash instance to validate
90
+ * @param checkFinished - whether to reject finalized instances
91
+ * @throws If the hash instance has already been destroyed or finalized. {@link Error}
92
+ * @example
93
+ * Validate that a hash instance is still usable.
94
+ * ```ts
95
+ * import { aexists } from '@noble/hashes/utils.js';
96
+ * import { sha256 } from '@noble/hashes/sha2.js';
97
+ * const hash = sha256.create();
98
+ * aexists(hash);
99
+ * ```
100
+ */
101
+ function aexists(instance, checkFinished = true) {
102
+ if (instance.destroyed) throw new Error("Hash instance has been destroyed");
103
+ if (checkFinished && instance.finished) throw new Error("Hash#digest() has already been called");
104
+ }
105
+ /**
106
+ * Asserts output is a sufficiently-sized byte array.
107
+ * @param out - destination buffer
108
+ * @param instance - hash instance providing output length
109
+ * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.
110
+ * @throws On wrong argument types. {@link TypeError}
111
+ * @throws On wrong argument ranges or values. {@link RangeError}
112
+ * @example
113
+ * Validate a caller-provided digest buffer.
114
+ * ```ts
115
+ * import { aoutput } from '@noble/hashes/utils.js';
116
+ * import { sha256 } from '@noble/hashes/sha2.js';
117
+ * const hash = sha256.create();
118
+ * aoutput(new Uint8Array(hash.outputLen), hash);
119
+ * ```
120
+ */
121
+ function aoutput(out, instance) {
122
+ abytes(out, void 0, "digestInto() output");
123
+ const min = instance.outputLen;
124
+ if (out.length < min) throw new RangeError("\"digestInto() output\" expected to be of length >=" + min);
125
+ }
126
+ /**
127
+ * Casts a typed array view to Uint32Array.
128
+ * `arr.byteOffset` must already be 4-byte aligned or the platform
129
+ * Uint32Array constructor will throw.
130
+ * @param arr - source typed array
131
+ * @returns Uint32Array view over the same buffer.
132
+ * @example
133
+ * Reinterpret a byte array as 32-bit words.
134
+ * ```ts
135
+ * u32(new Uint8Array(8));
136
+ * ```
137
+ */
138
+ function u32(arr) {
139
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
140
+ }
141
+ /**
142
+ * Zeroizes typed arrays in place. Warning: JS provides no guarantees.
143
+ * @param arrays - arrays to overwrite with zeros
144
+ * @example
145
+ * Zeroize sensitive buffers in place.
146
+ * ```ts
147
+ * clean(new Uint8Array([1, 2, 3]));
148
+ * ```
149
+ */
150
+ function clean(...arrays) {
151
+ for (let i = 0; i < arrays.length; i++) arrays[i].fill(0);
152
+ }
153
+ /**
154
+ * Creates a DataView for byte-level manipulation.
155
+ * @param arr - source typed array
156
+ * @returns DataView over the same buffer region.
157
+ * @example
158
+ * Create a DataView over an existing buffer.
159
+ * ```ts
160
+ * createView(new Uint8Array(4));
161
+ * ```
162
+ */
163
+ function createView(arr) {
164
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
165
+ }
166
+ /**
167
+ * Rotate-right operation for uint32 values.
168
+ * @param word - source word
169
+ * @param shift - shift amount in bits
170
+ * @returns Rotated word.
171
+ * @example
172
+ * Rotate a 32-bit word to the right.
173
+ * ```ts
174
+ * rotr(0x12345678, 8);
175
+ * ```
176
+ */
177
+ function rotr(word, shift) {
178
+ return word << 32 - shift | word >>> shift;
179
+ }
180
+ /** Whether the current platform is little-endian. */
181
+ const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
182
+ /**
183
+ * Byte-swap operation for uint32 values.
184
+ * @param word - source word
185
+ * @returns Word with reversed byte order.
186
+ * @example
187
+ * Reverse the byte order of a 32-bit word.
188
+ * ```ts
189
+ * byteSwap(0x11223344);
190
+ * ```
191
+ */
192
+ function byteSwap(word) {
193
+ return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
194
+ }
195
+ /**
196
+ * Conditionally byte-swaps one 32-bit word on big-endian platforms.
197
+ * @param n - source word
198
+ * @returns Original or byte-swapped word depending on platform endianness.
199
+ * @example
200
+ * Normalize a 32-bit word for host endianness.
201
+ * ```ts
202
+ * swap8IfBE(0x11223344);
203
+ * ```
204
+ */
205
+ const swap8IfBE = isLE ? (n) => n : (n) => byteSwap(n) >>> 0;
206
+ /**
207
+ * Byte-swaps every word of a Uint32Array in place.
208
+ * @param arr - array to mutate
209
+ * @returns The same array after mutation; callers pass live state arrays here.
210
+ * @example
211
+ * Reverse the byte order of every word in place.
212
+ * ```ts
213
+ * byteSwap32(new Uint32Array([0x11223344]));
214
+ * ```
215
+ */
216
+ function byteSwap32(arr) {
217
+ for (let i = 0; i < arr.length; i++) arr[i] = byteSwap(arr[i]);
218
+ return arr;
219
+ }
220
+ /**
221
+ * Conditionally byte-swaps a Uint32Array on big-endian platforms.
222
+ * @param u - array to normalize for host endianness
223
+ * @returns Original or byte-swapped array depending on platform endianness.
224
+ * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.
225
+ * @example
226
+ * Normalize a word array for host endianness.
227
+ * ```ts
228
+ * swap32IfBE(new Uint32Array([0x11223344]));
229
+ * ```
230
+ */
231
+ const swap32IfBE = isLE ? (u) => u : byteSwap32;
232
+ const hasHexBuiltin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function")();
233
+ const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
234
+ /**
235
+ * Convert byte array to hex string.
236
+ * Uses the built-in function when available and assumes it matches the tested
237
+ * fallback semantics.
238
+ * @param bytes - bytes to encode
239
+ * @returns Lowercase hexadecimal string.
240
+ * @throws On wrong argument types. {@link TypeError}
241
+ * @example
242
+ * Convert bytes to lowercase hexadecimal.
243
+ * ```ts
244
+ * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'
245
+ * ```
246
+ */
247
+ function bytesToHex(bytes) {
248
+ abytes(bytes);
249
+ if (hasHexBuiltin) return bytes.toHex();
250
+ let hex = "";
251
+ for (let i = 0; i < bytes.length; i++) hex += hexes[bytes[i]];
252
+ return hex;
253
+ }
254
+ const asciis = {
255
+ _0: 48,
256
+ _9: 57,
257
+ A: 65,
258
+ F: 70,
259
+ a: 97,
260
+ f: 102
261
+ };
262
+ function asciiToBase16(ch) {
263
+ if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0;
264
+ if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10);
265
+ if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10);
266
+ }
267
+ /**
268
+ * Convert hex string to byte array. Uses built-in function, when available.
269
+ * @param hex - hexadecimal string to decode
270
+ * @returns Decoded bytes.
271
+ * @throws On wrong argument types. {@link TypeError}
272
+ * @throws On wrong argument ranges or values. {@link RangeError}
273
+ * @example
274
+ * Decode lowercase hexadecimal into bytes.
275
+ * ```ts
276
+ * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
277
+ * ```
278
+ */
279
+ function hexToBytes(hex) {
280
+ if (typeof hex !== "string") throw new TypeError("hex string expected, got " + typeof hex);
281
+ if (hasHexBuiltin) try {
282
+ return Uint8Array.fromHex(hex);
283
+ } catch (error) {
284
+ if (error instanceof SyntaxError) throw new RangeError(error.message);
285
+ throw error;
286
+ }
287
+ const hl = hex.length;
288
+ const al = hl / 2;
289
+ if (hl % 2) throw new RangeError("hex string expected, got unpadded hex of length " + hl);
290
+ const array = new Uint8Array(al);
291
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
292
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
293
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
294
+ if (n1 === void 0 || n2 === void 0) {
295
+ const char = hex[hi] + hex[hi + 1];
296
+ throw new RangeError("hex string expected, got non-hex character \"" + char + "\" at index " + hi);
297
+ }
298
+ array[ai] = n1 * 16 + n2;
299
+ }
300
+ return array;
301
+ }
302
+ /**
303
+ * Copies several Uint8Arrays into one.
304
+ * @param arrays - arrays to concatenate
305
+ * @returns Concatenated byte array.
306
+ * @throws On wrong argument types. {@link TypeError}
307
+ * @example
308
+ * Concatenate multiple byte arrays.
309
+ * ```ts
310
+ * concatBytes(new Uint8Array([1]), new Uint8Array([2]));
311
+ * ```
312
+ */
313
+ function concatBytes(...arrays) {
314
+ let sum = 0;
315
+ for (let i = 0; i < arrays.length; i++) {
316
+ const a = arrays[i];
317
+ abytes(a);
318
+ sum += a.length;
319
+ }
320
+ const res = new Uint8Array(sum);
321
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
322
+ const a = arrays[i];
323
+ res.set(a, pad);
324
+ pad += a.length;
325
+ }
326
+ return res;
327
+ }
328
+ /**
329
+ * Creates a callable hash function from a stateful class constructor.
330
+ * @param hashCons - hash constructor or factory
331
+ * @param info - optional metadata such as DER OID
332
+ * @returns Frozen callable hash wrapper with `.create()`.
333
+ * Wrapper construction eagerly calls `hashCons(undefined)` once to read
334
+ * `outputLen` / `blockLen`, so constructor side effects happen at module
335
+ * init time.
336
+ * @example
337
+ * Wrap a stateful hash constructor into a callable helper.
338
+ * ```ts
339
+ * import { createHasher } from '@noble/hashes/utils.js';
340
+ * import { sha256 } from '@noble/hashes/sha2.js';
341
+ * const wrapped = createHasher(sha256.create, { oid: sha256.oid });
342
+ * wrapped(new Uint8Array([1]));
343
+ * ```
344
+ */
345
+ function createHasher(hashCons, info = {}) {
346
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
347
+ const tmp = hashCons(void 0);
348
+ hashC.outputLen = tmp.outputLen;
349
+ hashC.blockLen = tmp.blockLen;
350
+ hashC.canXOF = tmp.canXOF;
351
+ hashC.create = (opts) => hashCons(opts);
352
+ Object.assign(hashC, info);
353
+ return Object.freeze(hashC);
354
+ }
355
+ /**
356
+ * Cryptographically secure PRNG backed by `crypto.getRandomValues`.
357
+ * @param bytesLength - number of random bytes to generate
358
+ * @returns Random bytes.
359
+ * The platform `getRandomValues()` implementation still defines any
360
+ * single-call length cap, and this helper rejects oversize requests
361
+ * with a stable library `RangeError` instead of host-specific errors.
362
+ * @throws On wrong argument types. {@link TypeError}
363
+ * @throws On wrong argument ranges or values. {@link RangeError}
364
+ * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}
365
+ * @example
366
+ * Generate a fresh random key or nonce.
367
+ * ```ts
368
+ * const key = randomBytes(16);
369
+ * ```
370
+ */
371
+ function randomBytes(bytesLength = 32) {
372
+ anumber(bytesLength, "bytesLength");
373
+ const cr = typeof globalThis === "object" ? globalThis.crypto : null;
374
+ if (typeof cr?.getRandomValues !== "function") throw new Error("crypto.getRandomValues must be defined");
375
+ if (bytesLength > 65536) throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
376
+ return cr.getRandomValues(new Uint8Array(bytesLength));
377
+ }
378
+ /**
379
+ * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.
380
+ * @param suffix - final OID byte for the selected hash.
381
+ * The helper accepts any byte even though only the documented NIST hash
382
+ * suffixes are meaningful downstream.
383
+ * @returns Object containing the DER-encoded OID.
384
+ * @example
385
+ * Build OID metadata for a NIST hash.
386
+ * ```ts
387
+ * oidNist(0x01);
388
+ * ```
389
+ */
390
+ const oidNist = (suffix) => ({ oid: Uint8Array.from([
391
+ 6,
392
+ 9,
393
+ 96,
394
+ 134,
395
+ 72,
396
+ 1,
397
+ 101,
398
+ 3,
399
+ 4,
400
+ 2,
401
+ suffix
402
+ ]) });
403
+
404
+ //#endregion
405
+ exports.abytes = abytes;
406
+ exports.aexists = aexists;
407
+ exports.ahash = ahash;
408
+ exports.anumber = anumber;
409
+ exports.aoutput = aoutput;
410
+ exports.bytesToHex = bytesToHex;
411
+ exports.clean = clean;
412
+ exports.concatBytes = concatBytes;
413
+ exports.createHasher = createHasher;
414
+ exports.createView = createView;
415
+ exports.hexToBytes = hexToBytes;
416
+ exports.isBytes = isBytes;
417
+ exports.oidNist = oidNist;
418
+ exports.randomBytes = randomBytes;
419
+ exports.rotr = rotr;
420
+ exports.swap32IfBE = swap32IfBE;
421
+ exports.swap8IfBE = swap8IfBE;
422
+ exports.u32 = u32;
@@ -0,0 +1,153 @@
1
+
2
+ //#region src/chacha20poly1305.ts
3
+ /**
4
+ * RFC 8439 ChaCha20-Poly1305 AEAD implementation.
5
+ *
6
+ * Self-contained, zero external cipher dependency, constant-time tag verification,
7
+ * byte-for-byte compatible with `@noble/ciphers/chacha.js` (`chacha20poly1305`).
8
+ */
9
+ function rotl32(v, n) {
10
+ return (v << n | v >>> 32 - n) >>> 0;
11
+ }
12
+ function readU32LE(buf, offset) {
13
+ return (buf[offset] | buf[offset + 1] << 8 | buf[offset + 2] << 16 | buf[offset + 3] << 24) >>> 0;
14
+ }
15
+ function writeU32LE(buf, offset, val) {
16
+ buf[offset] = val & 255;
17
+ buf[offset + 1] = val >>> 8 & 255;
18
+ buf[offset + 2] = val >>> 16 & 255;
19
+ buf[offset + 3] = val >>> 24 & 255;
20
+ }
21
+ function writeU64LE(buf, offset, len) {
22
+ const lo = len >>> 0;
23
+ const hi = Math.floor(len / 4294967296) >>> 0;
24
+ writeU32LE(buf, offset, lo);
25
+ writeU32LE(buf, offset + 4, hi);
26
+ }
27
+ function quarterRound(s, a, b, c, d) {
28
+ s[a] = s[a] + s[b] >>> 0;
29
+ s[d] = rotl32(s[d] ^ s[a], 16);
30
+ s[c] = s[c] + s[d] >>> 0;
31
+ s[b] = rotl32(s[b] ^ s[c], 12);
32
+ s[a] = s[a] + s[b] >>> 0;
33
+ s[d] = rotl32(s[d] ^ s[a], 8);
34
+ s[c] = s[c] + s[d] >>> 0;
35
+ s[b] = rotl32(s[b] ^ s[c], 7);
36
+ }
37
+ function chacha20Block(key, counter, nonce) {
38
+ const state = new Uint32Array(16);
39
+ state[0] = 1634760805;
40
+ state[1] = 857760878;
41
+ state[2] = 2036477234;
42
+ state[3] = 1797285236;
43
+ for (let i = 0; i < 8; i++) state[4 + i] = readU32LE(key, i * 4);
44
+ state[12] = counter >>> 0;
45
+ state[13] = readU32LE(nonce, 0);
46
+ state[14] = readU32LE(nonce, 4);
47
+ state[15] = readU32LE(nonce, 8);
48
+ const working = new Uint32Array(state);
49
+ for (let i = 0; i < 10; i++) {
50
+ quarterRound(working, 0, 4, 8, 12);
51
+ quarterRound(working, 1, 5, 9, 13);
52
+ quarterRound(working, 2, 6, 10, 14);
53
+ quarterRound(working, 3, 7, 11, 15);
54
+ quarterRound(working, 0, 5, 10, 15);
55
+ quarterRound(working, 1, 6, 11, 12);
56
+ quarterRound(working, 2, 7, 8, 13);
57
+ quarterRound(working, 3, 4, 9, 14);
58
+ }
59
+ const out = new Uint8Array(64);
60
+ for (let i = 0; i < 16; i++) writeU32LE(out, i * 4, working[i] + state[i] >>> 0);
61
+ return out;
62
+ }
63
+ function chacha20Xor(key, initialCounter, nonce, input) {
64
+ const out = new Uint8Array(input.length);
65
+ let counter = initialCounter;
66
+ for (let offset = 0; offset < input.length; offset += 64) {
67
+ const block = chacha20Block(key, counter++, nonce);
68
+ const chunkLen = Math.min(64, input.length - offset);
69
+ for (let i = 0; i < chunkLen; i++) out[offset + i] = input[offset + i] ^ block[i];
70
+ }
71
+ return out;
72
+ }
73
+ const POLY1305_P = (1n << 130n) - 5n;
74
+ function bytesToBigIntLE(bytes) {
75
+ let result = 0n;
76
+ for (let i = bytes.length - 1; i >= 0; i--) result = result << 8n | BigInt(bytes[i]);
77
+ return result;
78
+ }
79
+ function poly1305Mac(msg, otk) {
80
+ const rBytes = new Uint8Array(otk.subarray(0, 16));
81
+ rBytes[3] &= 15;
82
+ rBytes[7] &= 15;
83
+ rBytes[11] &= 15;
84
+ rBytes[15] &= 15;
85
+ rBytes[4] &= 252;
86
+ rBytes[8] &= 252;
87
+ rBytes[12] &= 252;
88
+ const r = bytesToBigIntLE(rBytes);
89
+ const s = bytesToBigIntLE(otk.subarray(16, 32));
90
+ let acc = 0n;
91
+ for (let offset = 0; offset < msg.length; offset += 16) {
92
+ const slice = msg.subarray(offset, Math.min(offset + 16, msg.length));
93
+ const n = bytesToBigIntLE(slice) | 1n << BigInt(slice.length * 8);
94
+ acc = (acc + n) * r % POLY1305_P;
95
+ }
96
+ acc = acc + s & (1n << 128n) - 1n;
97
+ const tag = new Uint8Array(16);
98
+ for (let i = 0; i < 16; i++) {
99
+ tag[i] = Number(acc & 255n);
100
+ acc >>= 8n;
101
+ }
102
+ return tag;
103
+ }
104
+ function buildPoly1305Input(aad, ciphertext) {
105
+ const aadPad = (16 - aad.length % 16) % 16;
106
+ const ctPad = (16 - ciphertext.length % 16) % 16;
107
+ const totalLen = aad.length + aadPad + ciphertext.length + ctPad + 16;
108
+ const buf = new Uint8Array(totalLen);
109
+ let pos = 0;
110
+ buf.set(aad, pos);
111
+ pos += aad.length + aadPad;
112
+ buf.set(ciphertext, pos);
113
+ pos += ciphertext.length + ctPad;
114
+ writeU64LE(buf, pos, aad.length);
115
+ writeU64LE(buf, pos + 8, ciphertext.length);
116
+ return buf;
117
+ }
118
+ function constantTimeEqual(a, b) {
119
+ if (a.length !== b.length) return false;
120
+ let diff = 0;
121
+ for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
122
+ return diff === 0;
123
+ }
124
+ /**
125
+ * Create an RFC 8439 ChaCha20-Poly1305 AEAD cipher instance.
126
+ * Drop-in compatible with `@noble/ciphers/chacha.js` `chacha20poly1305(key, nonce, aad)`.
127
+ */
128
+ function chacha20poly1305(key, nonce, aad = new Uint8Array(0)) {
129
+ if (key.length !== 32) throw new Error(`Invalid ChaCha20-Poly1305 key length: expected 32, got ${key.length}`);
130
+ if (nonce.length !== 12) throw new Error(`Invalid ChaCha20-Poly1305 nonce length: expected 12, got ${nonce.length}`);
131
+ return {
132
+ encrypt(plaintext) {
133
+ const otk = chacha20Block(key, 0, nonce).subarray(0, 32);
134
+ const ciphertext = chacha20Xor(key, 1, nonce, plaintext);
135
+ const tag = poly1305Mac(buildPoly1305Input(aad, ciphertext), otk);
136
+ const out = new Uint8Array(ciphertext.length + 16);
137
+ out.set(ciphertext, 0);
138
+ out.set(tag, ciphertext.length);
139
+ return out;
140
+ },
141
+ decrypt(ciphertextWithTag) {
142
+ if (ciphertextWithTag.length < 16) throw new Error("ChaCha20-Poly1305 decryption failed: ciphertext too short");
143
+ const ciphertext = ciphertextWithTag.subarray(0, ciphertextWithTag.length - 16);
144
+ const receivedTag = ciphertextWithTag.subarray(ciphertextWithTag.length - 16);
145
+ const otk = chacha20Block(key, 0, nonce).subarray(0, 32);
146
+ if (!constantTimeEqual(receivedTag, poly1305Mac(buildPoly1305Input(aad, ciphertext), otk))) throw new Error("ChaCha20-Poly1305 authentication tag mismatch");
147
+ return chacha20Xor(key, 1, nonce, ciphertext);
148
+ }
149
+ };
150
+ }
151
+
152
+ //#endregion
153
+ exports.chacha20poly1305 = chacha20poly1305;
@@ -0,0 +1,18 @@
1
+ //#region src/chacha20poly1305.d.ts
2
+ /**
3
+ * RFC 8439 ChaCha20-Poly1305 AEAD implementation.
4
+ *
5
+ * Self-contained, zero external cipher dependency, constant-time tag verification,
6
+ * byte-for-byte compatible with `@noble/ciphers/chacha.js` (`chacha20poly1305`).
7
+ */
8
+ interface ChaCha20Poly1305Cipher {
9
+ encrypt(plaintext: Uint8Array): Uint8Array;
10
+ decrypt(ciphertextWithTag: Uint8Array): Uint8Array;
11
+ }
12
+ /**
13
+ * Create an RFC 8439 ChaCha20-Poly1305 AEAD cipher instance.
14
+ * Drop-in compatible with `@noble/ciphers/chacha.js` `chacha20poly1305(key, nonce, aad)`.
15
+ */
16
+ declare function chacha20poly1305(key: Uint8Array, nonce: Uint8Array, aad?: Uint8Array): ChaCha20Poly1305Cipher;
17
+ //#endregion
18
+ export { ChaCha20Poly1305Cipher, chacha20poly1305 };