@decryption/ciphers 0.2.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.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Paul Miller (https://paulmillr.com)
4
+ Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the “Software”), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in
14
+ all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,75 @@
1
+ # @decryption/ciphers
2
+
3
+ > **NOTE:** This is a fork of [`@noble/ciphers`](https://www.npmjs.com/package/@noble/ciphers) (v2.2.0).
4
+ > We dual-publish as both **CJS and ESM** because upstream is ESM-only (`"type": "module"`), which breaks
5
+ > `require()` in Jest, older bundlers and CJS-based Node.js tooling. The source is unchanged from upstream —
6
+ > only the build tooling differs, plus `@noble/*` / `@scure/*` import specifiers are rewritten to their
7
+ > `@decryption/*` forks.
8
+
9
+ Audited & minimal 0-dependency JS implementation of AES, ChaCha20-Poly1305 and XChaCha20-Poly1305. Dual CJS+ESM fork of @noble/ciphers.
10
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ npm install @decryption/ciphers
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ Import submodules directly — `dist/` is the package root once published, so deep imports work in both CJS and ESM:
20
+
21
+ ```typescript
22
+ import { sha256 } from '@decryption/hashes/sha2';
23
+ import { xchacha20poly1305 } from '@decryption/ciphers/chacha';
24
+ ```
25
+
26
+ Refer to the [upstream documentation](https://github.com/paulmillr/ciphers) for the full API.
27
+
28
+ ## Syncing upstream
29
+
30
+ ```bash
31
+ ./scripts/vendor-fork.sh @noble/ciphers <version> ciphers
32
+ node scripts/fix-imports.js packages/ciphers ciphers
33
+ pnpm --filter @decryption/ciphers build && pnpm --filter @decryption/ciphers test
34
+ ```
35
+
36
+ ## License
37
+
38
+ MIT — Copyright (c) 2022 Paul Miller (https://paulmillr.com). See [LICENSE](./LICENSE).
39
+
40
+ ---
41
+
42
+ ## Development
43
+
44
+ ### Setup
45
+
46
+ 1. Clone the repository:
47
+
48
+ ```bash
49
+ git clone https://github.com/constructive-io/decryption.git
50
+ ```
51
+
52
+ 2. Install dependencies:
53
+
54
+ ```bash
55
+ cd decryption
56
+ pnpm install
57
+ pnpm build
58
+ ```
59
+
60
+ 3. Test the package of interest:
61
+
62
+ ```bash
63
+ cd packages/<packagename>
64
+ pnpm test:watch
65
+ ```
66
+
67
+ ## Credits
68
+
69
+ **🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
70
+
71
+ ## Disclaimer
72
+
73
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
74
+
75
+ No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
package/_arx.d.ts ADDED
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.
3
+
4
+ RFC8439 requires multi-step cipher stream, where
5
+ authKey starts with counter: 0, actual msg with counter: 1.
6
+
7
+ For this, we need a way to re-use nonce / counter:
8
+
9
+ const counter = new Uint8Array(4);
10
+ chacha(..., counter, ...); // counter is now 1
11
+ chacha(..., counter, ...); // counter is now 2
12
+
13
+ This is complicated:
14
+
15
+ - 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB
16
+ - Original papers don't allow mutating counters
17
+ - Counter overflow is undefined [^1]
18
+ - Idea A: allow providing (nonce | counter) instead of just nonce, re-use it
19
+ - Caveat: Cannot be re-used through all cases:
20
+ - * chacha has (counter | nonce)
21
+ - * xchacha has (nonce16 | counter | nonce16)
22
+ - Idea B: separate nonce / counter and provide separate API for counter re-use
23
+ - Caveat: there are different counter sizes depending on an algorithm.
24
+ - salsa & chacha also differ in structures of key & sigma:
25
+ salsa20: s[0] | k(4) | s[1] | nonce(2) | cnt(2) | s[2] | k(4) | s[3]
26
+ chacha: s(4) | k(8) | cnt(1) | nonce(3)
27
+ chacha20orig: s(4) | k(8) | cnt(2) | nonce(2)
28
+ - Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`
29
+ - Caveat: we can't re-use counter array
30
+
31
+ xchacha uses the subkey and remaining 8 byte nonce with ChaCha20 as normal
32
+ (prefixed by 4 NUL bytes, since RFC8439 specifies a 12-byte nonce).
33
+ Counter overflow is undefined; see {@link https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/ | the CFRG thread}.
34
+ Current noble policy is strict non-wrap for the shared 32-bit counter path:
35
+ exported ARX ciphers reject initial `0xffffffff` and stop before any implicit
36
+ wrap back to zero.
37
+ See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2 | the XChaCha appendix} for the extended-nonce construction.
38
+
39
+ * @module
40
+ */
41
+ import { type PRG, type TArg, type TRet, type XorStream } from './utils';
42
+ /**
43
+ * Rotates a 32-bit word left.
44
+ * @param a - Input word.
45
+ * @param b - Rotation count in bits.
46
+ * @returns Rotated 32-bit word.
47
+ * @example
48
+ * Moves the top byte of `0x12345678` into the low byte position.
49
+ * ```ts
50
+ * rotl(0x12345678, 8);
51
+ * ```
52
+ */
53
+ export declare function rotl(a: number, b: number): number;
54
+ /**
55
+ * ARX core function operating on 32-bit words. Ciphers must use u32 for efficiency.
56
+ * @param sigma - Sigma constants for the selected cipher layout.
57
+ * @param key - Expanded key words.
58
+ * @param nonce - Nonce and counter words prepared for the round function.
59
+ * @param output - Output block written in place.
60
+ * @param counter - Block counter value.
61
+ * @param rounds - Optional round count override.
62
+ */
63
+ export type CipherCoreFn = (sigma: TArg<Uint32Array>, key: TArg<Uint32Array>, nonce: TArg<Uint32Array>, output: TArg<Uint32Array>, counter: number, rounds?: number) => void;
64
+ /**
65
+ * Nonce-extension function used by XChaCha and XSalsa.
66
+ * @param sigma - Sigma constants for the selected cipher layout.
67
+ * @param key - Expanded key words.
68
+ * @param input - Input nonce words used for subkey derivation.
69
+ * @param output - Output buffer written with the derived nonce words.
70
+ */
71
+ export type ExtendNonceFn = (sigma: TArg<Uint32Array>, key: TArg<Uint32Array>, input: TArg<Uint32Array>, output: TArg<Uint32Array>) => void;
72
+ /** ARX cipher options.
73
+ * * `allowShortKeys` for 16-byte keys
74
+ * * `counterLength` in bytes
75
+ * * `counterRight`: right: `nonce|counter`; left: `counter|nonce`
76
+ * */
77
+ export type CipherOpts = {
78
+ /** Whether 16-byte keys are accepted for legacy Salsa and ChaCha variants. */
79
+ allowShortKeys?: boolean;
80
+ /** Optional nonce-expansion hook used by extended-nonce variants. */
81
+ extendNonceFn?: ExtendNonceFn;
82
+ /** Counter length in bytes inside the nonce/counter layout. */
83
+ counterLength?: number;
84
+ /** Whether the layout is `nonce|counter` instead of `counter|nonce`. */
85
+ counterRight?: boolean;
86
+ /** Number of core rounds to execute. */
87
+ rounds?: number;
88
+ };
89
+ /**
90
+ * Creates an ARX stream cipher from a 32-bit core permutation.
91
+ * Used internally to build the exported Salsa and ChaCha stream ciphers.
92
+ * @param core - Core function that fills one keystream block.
93
+ * @param opts - Cipher layout and nonce-extension options. See {@link CipherOpts}.
94
+ * @returns Stream cipher function over byte arrays.
95
+ * @throws If the core callback, key size, counter, or output sizing is invalid. {@link Error}
96
+ */
97
+ export declare function createCipher(core: TArg<CipherCoreFn>, opts: TArg<CipherOpts>): TRet<XorStream>;
98
+ /** Internal class which wraps chacha20 or chacha8 to create CSPRNG. */
99
+ export declare class _XorStreamPRG implements PRG {
100
+ readonly blockLen: number;
101
+ readonly keyLen: number;
102
+ readonly nonceLen: number;
103
+ private state;
104
+ private buf;
105
+ private key;
106
+ private nonce;
107
+ private pos;
108
+ private ctr;
109
+ private cipher;
110
+ constructor(cipher: TArg<XorStream>, blockLen: number, keyLen: number, nonceLen: number, seed: TArg<Uint8Array>);
111
+ private reseed;
112
+ addEntropy(seed: TArg<Uint8Array>): void;
113
+ randomBytes(len: number): TRet<Uint8Array>;
114
+ clone(): _XorStreamPRG;
115
+ clean(): void;
116
+ }
117
+ /**
118
+ * PRG constructor backed by an ARX stream cipher.
119
+ * @param seed - Optional seed bytes mixed into the initial state. When omitted, exactly 32
120
+ * random bytes are mixed in by default: larger states keep a zero tail, while smaller states
121
+ * wrap those bytes through `reseed()`'s XOR schedule.
122
+ * @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.
123
+ */
124
+ export type XorPRG = (seed?: TArg<Uint8Array>) => TRet<_XorStreamPRG>;
125
+ /**
126
+ * Creates a PRG constructor from a stream cipher.
127
+ * @param cipher - Stream cipher used to fill output blocks.
128
+ * @param blockLen - Keystream block length in bytes.
129
+ * @param keyLen - Internal key length in bytes.
130
+ * @param nonceLen - Internal nonce length in bytes.
131
+ * @returns PRG factory for seeded concrete `_XorStreamPRG` instances.
132
+ * @example
133
+ * Builds a PRG from XChaCha20 and reads bytes from a randomly seeded instance.
134
+ * ```ts
135
+ * import { xchacha20 } from './chacha';
136
+ * import { createPRG } from './_arx';
137
+ * import { randomBytes } from './utils';
138
+ * const seed = randomBytes(32);
139
+ * const init = createPRG(xchacha20, 64, 32, 24);
140
+ * const prg = init(seed);
141
+ * prg.randomBytes(8);
142
+ * ```
143
+ */
144
+ export declare const createPRG: (cipher: TArg<XorStream>, blockLen: number, keyLen: number, nonceLen: number) => TRet<XorPRG>;
package/_arx.js ADDED
@@ -0,0 +1,375 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createPRG = exports._XorStreamPRG = void 0;
4
+ exports.rotl = rotl;
5
+ exports.createCipher = createCipher;
6
+ /**
7
+ * Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.
8
+
9
+ RFC8439 requires multi-step cipher stream, where
10
+ authKey starts with counter: 0, actual msg with counter: 1.
11
+
12
+ For this, we need a way to re-use nonce / counter:
13
+
14
+ const counter = new Uint8Array(4);
15
+ chacha(..., counter, ...); // counter is now 1
16
+ chacha(..., counter, ...); // counter is now 2
17
+
18
+ This is complicated:
19
+
20
+ - 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB
21
+ - Original papers don't allow mutating counters
22
+ - Counter overflow is undefined [^1]
23
+ - Idea A: allow providing (nonce | counter) instead of just nonce, re-use it
24
+ - Caveat: Cannot be re-used through all cases:
25
+ - * chacha has (counter | nonce)
26
+ - * xchacha has (nonce16 | counter | nonce16)
27
+ - Idea B: separate nonce / counter and provide separate API for counter re-use
28
+ - Caveat: there are different counter sizes depending on an algorithm.
29
+ - salsa & chacha also differ in structures of key & sigma:
30
+ salsa20: s[0] | k(4) | s[1] | nonce(2) | cnt(2) | s[2] | k(4) | s[3]
31
+ chacha: s(4) | k(8) | cnt(1) | nonce(3)
32
+ chacha20orig: s(4) | k(8) | cnt(2) | nonce(2)
33
+ - Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`
34
+ - Caveat: we can't re-use counter array
35
+
36
+ xchacha uses the subkey and remaining 8 byte nonce with ChaCha20 as normal
37
+ (prefixed by 4 NUL bytes, since RFC8439 specifies a 12-byte nonce).
38
+ Counter overflow is undefined; see {@link https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/ | the CFRG thread}.
39
+ Current noble policy is strict non-wrap for the shared 32-bit counter path:
40
+ exported ARX ciphers reject initial `0xffffffff` and stop before any implicit
41
+ wrap back to zero.
42
+ See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2 | the XChaCha appendix} for the extended-nonce construction.
43
+
44
+ * @module
45
+ */
46
+ const utils_1 = require("./utils");
47
+ // Replaces `TextEncoder` for ASCII literals, which is enough for sigma constants.
48
+ // Non-ASCII input would not match UTF-8 `TextEncoder` output.
49
+ const encodeStr = (str) => Uint8Array.from(str.split(''), (c) => c.charCodeAt(0));
50
+ // Raw `createCipher(...)` exports consume these native-endian `u32(...)` views directly.
51
+ // Public `wrapCipher(...)` APIs reject non-little-endian platforms before reaching this path.
52
+ // RFC 8439 §2.3 / RFC 7539 §2.3 only define the 256-bit-key constants; this 16-byte sigma is
53
+ // kept for legacy allowShortKeys Salsa/ChaCha variants.
54
+ const sigma16_32 = /* @__PURE__ */ (() => (0, utils_1.swap32IfBE)((0, utils_1.u32)(encodeStr('expand 16-byte k'))))();
55
+ // RFC 8439 §2.3 / RFC 7539 §2.3 define words 0-3 as
56
+ // `0x61707865 0x3320646e 0x79622d32 0x6b206574`, i.e. `expand 32-byte k`.
57
+ const sigma32_32 = /* @__PURE__ */ (() => (0, utils_1.swap32IfBE)((0, utils_1.u32)(encodeStr('expand 32-byte k'))))();
58
+ /**
59
+ * Rotates a 32-bit word left.
60
+ * @param a - Input word.
61
+ * @param b - Rotation count in bits.
62
+ * @returns Rotated 32-bit word.
63
+ * @example
64
+ * Moves the top byte of `0x12345678` into the low byte position.
65
+ * ```ts
66
+ * rotl(0x12345678, 8);
67
+ * ```
68
+ */
69
+ function rotl(a, b) {
70
+ return (a << b) | (a >>> (32 - b));
71
+ }
72
+ // Salsa and Chacha block length is always 512-bit
73
+ const BLOCK_LEN = 64;
74
+ // RFC 8439 §2.2 / RFC 7539 §2.2: the ChaCha state has 16 32-bit words.
75
+ const BLOCK_LEN32 = 16;
76
+ // Counter policy for the shared public `counter` argument:
77
+ // - RFC/IETF ChaCha20 uses a 32-bit counter.
78
+ // - OpenSSL/Node `chacha20` instead treat the full 16-byte IV as a 128-bit
79
+ // counter state and carry into the next word.
80
+ // - Raw `chacha20orig`, `salsa20`, `xsalsa20`, and `xchacha20` use 64-bit counters in libsodium
81
+ // and libtomcrypt, while some libs (for example libtomcrypt's RFC/IETF path) reject the max
82
+ // boundary instead of carrying.
83
+ // - AEAD wrappers diverge too: libsodium `xchacha20poly1305` uses the IETF payload counter from
84
+ // block 1, while `secretstream_xchacha20poly1305` is a different protocol with rekey/reset.
85
+ // Noble intentionally throws instead of silently picking one wrap model for users. In the default
86
+ // path, even a 32-bit boundary would take 2^32 blocks * 64 bytes = 256 GiB, which is practically
87
+ // unreachable for normal JS callers; advanced users who pass `counter` explicitly can implement
88
+ // whatever wider carry / wrap policy they need on top.
89
+ const MAX_COUNTER = /* @__PURE__ */ (() => 2 ** 32 - 1)();
90
+ const U32_EMPTY = /* @__PURE__ */ Uint32Array.of();
91
+ function runCipher(core, sigma, key, nonce, data, output, counter, rounds) {
92
+ const len = data.length;
93
+ const block = new Uint8Array(BLOCK_LEN);
94
+ const b32 = (0, utils_1.u32)(block);
95
+ // Make sure that buffers aligned to 4 bytes
96
+ const isAligned = utils_1.isLE && (0, utils_1.isAligned32)(data) && (0, utils_1.isAligned32)(output);
97
+ const d32 = isAligned ? (0, utils_1.u32)(data) : U32_EMPTY;
98
+ const o32 = isAligned ? (0, utils_1.u32)(output) : U32_EMPTY;
99
+ // RFC 8439 §2.4.1 / RFC 7539 §2.4.1 allow XORing one keystream block at a time and
100
+ // truncating the final partial block instead of materializing the whole keystream.
101
+ if (!utils_1.isLE) {
102
+ for (let pos = 0; pos < len; counter++) {
103
+ core(sigma, key, nonce, b32, counter, rounds);
104
+ // RFC 8439 §2.4 / RFC 7539 §2.4 serialize keystream words in little-endian order.
105
+ (0, utils_1.swap32IfBE)(b32);
106
+ if (counter >= MAX_COUNTER)
107
+ throw new Error('arx: counter overflow');
108
+ const take = Math.min(BLOCK_LEN, len - pos);
109
+ for (let j = 0, posj; j < take; j++) {
110
+ posj = pos + j;
111
+ output[posj] = data[posj] ^ block[j];
112
+ }
113
+ pos += take;
114
+ }
115
+ return;
116
+ }
117
+ for (let pos = 0; pos < len; counter++) {
118
+ core(sigma, key, nonce, b32, counter, rounds);
119
+ // See MAX_COUNTER policy note above: never silently wrap the shared public counter.
120
+ if (counter >= MAX_COUNTER)
121
+ throw new Error('arx: counter overflow');
122
+ const take = Math.min(BLOCK_LEN, len - pos);
123
+ // aligned to 4 bytes
124
+ if (isAligned && take === BLOCK_LEN) {
125
+ const pos32 = pos / 4;
126
+ if (pos % 4 !== 0)
127
+ throw new Error('arx: invalid block position');
128
+ for (let j = 0, posj; j < BLOCK_LEN32; j++) {
129
+ posj = pos32 + j;
130
+ o32[posj] = d32[posj] ^ b32[j];
131
+ }
132
+ pos += BLOCK_LEN;
133
+ continue;
134
+ }
135
+ for (let j = 0, posj; j < take; j++) {
136
+ posj = pos + j;
137
+ output[posj] = data[posj] ^ block[j];
138
+ }
139
+ pos += take;
140
+ }
141
+ }
142
+ /**
143
+ * Creates an ARX stream cipher from a 32-bit core permutation.
144
+ * Used internally to build the exported Salsa and ChaCha stream ciphers.
145
+ * @param core - Core function that fills one keystream block.
146
+ * @param opts - Cipher layout and nonce-extension options. See {@link CipherOpts}.
147
+ * @returns Stream cipher function over byte arrays.
148
+ * @throws If the core callback, key size, counter, or output sizing is invalid. {@link Error}
149
+ */
150
+ function createCipher(core, opts) {
151
+ const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = (0, utils_1.checkOpts)({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts);
152
+ if (typeof core !== 'function')
153
+ throw new Error('core must be a function');
154
+ (0, utils_1.anumber)(counterLength);
155
+ (0, utils_1.anumber)(rounds);
156
+ (0, utils_1.abool)(counterRight);
157
+ (0, utils_1.abool)(allowShortKeys);
158
+ return (key, nonce, data, output, counter = 0) => {
159
+ (0, utils_1.abytes)(key, undefined, 'key');
160
+ (0, utils_1.abytes)(nonce, undefined, 'nonce');
161
+ (0, utils_1.abytes)(data, undefined, 'data');
162
+ const len = data.length;
163
+ // Raw XorStream APIs return ciphertext/plaintext bytes directly, so caller-provided outputs
164
+ // must match the logical result length exactly instead of returning an oversized workspace.
165
+ output = (0, utils_1.getOutput)(len, output, false);
166
+ (0, utils_1.anumber)(counter);
167
+ // See MAX_COUNTER policy note above: reject advanced explicit-counter requests before any wrap.
168
+ if (counter < 0 || counter >= MAX_COUNTER)
169
+ throw new Error('arx: counter overflow');
170
+ const toClean = [];
171
+ // Key & sigma
172
+ // key=16 -> sigma16, k=key|key
173
+ // key=32 -> sigma32, k=key
174
+ let l = key.length;
175
+ let k;
176
+ let sigma;
177
+ if (l === 32) {
178
+ // Copy caller keys too: big-endian normalization, extended-nonce subkey derivation, and
179
+ // final clean(...) all mutate or wipe the temporary buffer in place.
180
+ toClean.push((k = (0, utils_1.copyBytes)(key)));
181
+ sigma = sigma32_32;
182
+ }
183
+ else if (l === 16 && allowShortKeys) {
184
+ k = new Uint8Array(32);
185
+ k.set(key);
186
+ k.set(key, 16);
187
+ sigma = sigma16_32;
188
+ toClean.push(k);
189
+ }
190
+ else {
191
+ (0, utils_1.abytes)(key, 32, 'arx key');
192
+ throw new Error('invalid key size');
193
+ // throw new Error(`"arx key" expected Uint8Array of length 32, got length=${l}`);
194
+ }
195
+ // Nonce
196
+ // salsa20: 8 (8-byte counter)
197
+ // chacha20orig: 8 (8-byte counter)
198
+ // chacha20: 12 (4-byte counter)
199
+ // xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce)
200
+ // xchacha20: 24 (16 -> hchacha, 8 -> old nonce)
201
+ // Copy before taking u32(...) views on misaligned inputs, and on big-endian so later
202
+ // swap32IfBE(...) never mutates caller nonce bytes in place.
203
+ if (!utils_1.isLE || !(0, utils_1.isAligned32)(nonce))
204
+ toClean.push((nonce = (0, utils_1.copyBytes)(nonce)));
205
+ let k32 = (0, utils_1.u32)(k);
206
+ // hsalsa & hchacha: handle extended nonce
207
+ if (extendNonceFn) {
208
+ if (nonce.length !== 24)
209
+ throw new Error(`arx: extended nonce must be 24 bytes`);
210
+ const n16 = nonce.subarray(0, 16);
211
+ if (utils_1.isLE)
212
+ extendNonceFn(sigma, k32, (0, utils_1.u32)(n16), k32);
213
+ else {
214
+ const sigmaRaw = (0, utils_1.swap32IfBE)(Uint32Array.from(sigma));
215
+ extendNonceFn(sigmaRaw, k32, (0, utils_1.u32)(n16), k32);
216
+ (0, utils_1.clean)(sigmaRaw);
217
+ (0, utils_1.swap32IfBE)(k32);
218
+ }
219
+ nonce = nonce.subarray(16);
220
+ }
221
+ else if (!utils_1.isLE)
222
+ (0, utils_1.swap32IfBE)(k32);
223
+ // Handle nonce counter
224
+ const nonceNcLen = 16 - counterLength;
225
+ if (nonceNcLen !== nonce.length)
226
+ throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);
227
+ // Normalize 64-bit-nonce layouts to the 12-byte core input: ChaCha/XChaCha prefix 4 zero
228
+ // counter bytes, while Salsa/XSalsa append them after the nonce words.
229
+ if (nonceNcLen !== 12) {
230
+ const nc = new Uint8Array(12);
231
+ nc.set(nonce, counterRight ? 0 : 12 - nonce.length);
232
+ nonce = nc;
233
+ toClean.push(nonce);
234
+ }
235
+ const n32 = (0, utils_1.swap32IfBE)((0, utils_1.u32)(nonce));
236
+ // Ensure temporary key/nonce copies are wiped even if the remaining
237
+ // runtime guard in runCipher(...) throws on counter overflow.
238
+ try {
239
+ runCipher(core, sigma, k32, n32, data, output, counter, rounds);
240
+ return output;
241
+ }
242
+ finally {
243
+ (0, utils_1.clean)(...toClean);
244
+ }
245
+ };
246
+ }
247
+ /** Internal class which wraps chacha20 or chacha8 to create CSPRNG. */
248
+ class _XorStreamPRG {
249
+ blockLen;
250
+ keyLen;
251
+ nonceLen;
252
+ state;
253
+ buf;
254
+ key;
255
+ nonce;
256
+ pos;
257
+ ctr;
258
+ cipher;
259
+ constructor(cipher, blockLen, keyLen, nonceLen, seed) {
260
+ this.cipher = cipher;
261
+ this.blockLen = blockLen;
262
+ this.keyLen = keyLen;
263
+ this.nonceLen = nonceLen;
264
+ this.state = new Uint8Array(this.keyLen + this.nonceLen);
265
+ this.reseed(seed);
266
+ this.ctr = 0;
267
+ this.pos = this.blockLen;
268
+ this.buf = new Uint8Array(this.blockLen);
269
+ // Keep a single key||nonce backing buffer so reseed/addEntropy/clean update the live cipher
270
+ // inputs in place through these subarray views.
271
+ this.key = this.state.subarray(0, this.keyLen);
272
+ this.nonce = this.state.subarray(this.keyLen);
273
+ }
274
+ reseed(seed) {
275
+ (0, utils_1.abytes)(seed);
276
+ if (!seed || seed.length === 0)
277
+ throw new Error('entropy required');
278
+ // Mix variable-length entropy cyclically across the whole key||nonce state, then restart the
279
+ // keystream so buffered leftovers from the previous state are never reused.
280
+ for (let i = 0; i < seed.length; i++)
281
+ this.state[i % this.state.length] ^= seed[i];
282
+ this.ctr = 0;
283
+ this.pos = this.blockLen;
284
+ }
285
+ addEntropy(seed) {
286
+ // Reject empty entropy before re-keying, otherwise a throwing call would still advance state.
287
+ (0, utils_1.abytes)(seed);
288
+ if (seed.length === 0)
289
+ throw new Error('entropy required');
290
+ // Re-key from the current stream first, then mix external entropy into the fresh key||nonce
291
+ // state through reseed() so stale buffered bytes are discarded.
292
+ this.state.set(this.randomBytes(this.state.length));
293
+ this.reseed(seed);
294
+ }
295
+ randomBytes(len) {
296
+ (0, utils_1.anumber)(len);
297
+ if (len === 0)
298
+ return new Uint8Array(0);
299
+ const avail = this.pos < this.blockLen ? this.blockLen - this.pos : 0;
300
+ const blocks = Math.ceil(Math.max(0, len - avail) / this.blockLen);
301
+ // Preflight overflow so failed reads don't partially consume keystream
302
+ // and leave the PRG repeating blocks.
303
+ if (blocks > 0 && this.ctr > MAX_COUNTER - blocks)
304
+ throw new Error('arx: counter overflow');
305
+ const out = new Uint8Array(len);
306
+ let outPos = 0;
307
+ // `out` starts zero-filled, and `buf.fill(0)` below does the same for leftovers: XOR-stream
308
+ // ciphers then emit raw keystream bytes directly into those buffers.
309
+ // Serve buffered leftovers first so split reads stay identical to one larger read.
310
+ if (this.pos < this.blockLen) {
311
+ const take = Math.min(len, this.blockLen - this.pos);
312
+ out.set(this.buf.subarray(this.pos, this.pos + take), 0);
313
+ this.pos += take;
314
+ outPos += take;
315
+ if (outPos === len)
316
+ return out; // fast path
317
+ }
318
+ // Full blocks directly to out
319
+ const full = Math.floor((len - outPos) / this.blockLen);
320
+ if (full > 0) {
321
+ const blockBytes = full * this.blockLen;
322
+ const b = out.subarray(outPos, outPos + blockBytes);
323
+ this.cipher(this.key, this.nonce, b, b, this.ctr);
324
+ this.ctr += full;
325
+ outPos += blockBytes;
326
+ }
327
+ // Save leftovers
328
+ const left = len - outPos;
329
+ if (left > 0) {
330
+ this.buf.fill(0);
331
+ // NOTE: cipher will handle overflow
332
+ this.cipher(this.key, this.nonce, this.buf, this.buf, this.ctr++);
333
+ out.set(this.buf.subarray(0, left), outPos);
334
+ this.pos = left;
335
+ }
336
+ return out;
337
+ }
338
+ // Clone seeds the new instance from this stream, so the source PRG advances too.
339
+ clone() {
340
+ return new _XorStreamPRG(this.cipher, this.blockLen, this.keyLen, this.nonceLen, this.randomBytes(this.state.length));
341
+ }
342
+ // Zeroes the current state and leftover buffer, but does not make the instance unusable:
343
+ // Later reads first drain zeros from the cleared buffer and then continue
344
+ // from zero key||nonce state.
345
+ clean() {
346
+ this.pos = 0;
347
+ this.ctr = 0;
348
+ this.buf.fill(0);
349
+ this.state.fill(0);
350
+ }
351
+ }
352
+ exports._XorStreamPRG = _XorStreamPRG;
353
+ /**
354
+ * Creates a PRG constructor from a stream cipher.
355
+ * @param cipher - Stream cipher used to fill output blocks.
356
+ * @param blockLen - Keystream block length in bytes.
357
+ * @param keyLen - Internal key length in bytes.
358
+ * @param nonceLen - Internal nonce length in bytes.
359
+ * @returns PRG factory for seeded concrete `_XorStreamPRG` instances.
360
+ * @example
361
+ * Builds a PRG from XChaCha20 and reads bytes from a randomly seeded instance.
362
+ * ```ts
363
+ * import { xchacha20 } from './chacha';
364
+ * import { createPRG } from './_arx';
365
+ * import { randomBytes } from './utils';
366
+ * const seed = randomBytes(32);
367
+ * const init = createPRG(xchacha20, 64, 32, 24);
368
+ * const prg = init(seed);
369
+ * prg.randomBytes(8);
370
+ * ```
371
+ */
372
+ const createPRG = (cipher, blockLen, keyLen, nonceLen) => {
373
+ return ((seed = (0, utils_1.randomBytes)(32)) => new _XorStreamPRG(cipher, blockLen, keyLen, nonceLen, seed));
374
+ };
375
+ exports.createPRG = createPRG;