leviathan-crypto 1.3.1 → 2.0.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/CLAUDE.md +129 -76
- package/README.md +166 -221
- package/SECURITY.md +89 -37
- package/dist/chacha20/cipher-suite.d.ts +4 -0
- package/dist/chacha20/cipher-suite.js +78 -0
- package/dist/chacha20/embedded.d.ts +1 -0
- package/dist/chacha20/embedded.js +27 -0
- package/dist/chacha20/index.d.ts +20 -7
- package/dist/chacha20/index.js +41 -14
- package/dist/chacha20/ops.d.ts +1 -1
- package/dist/chacha20/ops.js +19 -18
- package/dist/chacha20/pool-worker.js +77 -0
- package/dist/ct-wasm.d.ts +1 -0
- package/dist/ct-wasm.js +3 -0
- package/dist/ct.wasm +0 -0
- package/dist/docs/aead.md +320 -0
- package/dist/docs/architecture.md +419 -285
- package/dist/docs/argon2id.md +42 -30
- package/dist/docs/chacha20.md +218 -150
- package/dist/docs/exports.md +241 -0
- package/dist/docs/fortuna.md +65 -74
- package/dist/docs/init.md +172 -178
- package/dist/docs/loader.md +87 -132
- package/dist/docs/serpent.md +134 -565
- package/dist/docs/sha2.md +91 -103
- package/dist/docs/sha3.md +70 -36
- package/dist/docs/types.md +93 -16
- package/dist/docs/utils.md +114 -41
- package/dist/embedded/chacha20.d.ts +1 -1
- package/dist/embedded/chacha20.js +2 -1
- package/dist/embedded/kyber.d.ts +1 -0
- package/dist/embedded/kyber.js +3 -0
- package/dist/embedded/serpent.d.ts +1 -1
- package/dist/embedded/serpent.js +2 -1
- package/dist/embedded/sha2.d.ts +1 -1
- package/dist/embedded/sha2.js +2 -1
- package/dist/embedded/sha3.d.ts +1 -1
- package/dist/embedded/sha3.js +2 -1
- package/dist/errors.d.ts +10 -0
- package/dist/{serpent/seal.js → errors.js} +14 -46
- package/dist/fortuna.d.ts +2 -8
- package/dist/fortuna.js +11 -9
- package/dist/index.d.ts +25 -9
- package/dist/index.js +36 -7
- package/dist/init.d.ts +3 -7
- package/dist/init.js +18 -35
- package/dist/keccak/embedded.d.ts +1 -0
- package/dist/keccak/embedded.js +27 -0
- package/dist/keccak/index.d.ts +4 -0
- package/dist/keccak/index.js +31 -0
- package/dist/kyber/embedded.d.ts +1 -0
- package/dist/kyber/embedded.js +27 -0
- package/dist/kyber/indcpa.d.ts +49 -0
- package/dist/kyber/indcpa.js +352 -0
- package/dist/kyber/index.d.ts +38 -0
- package/dist/kyber/index.js +150 -0
- package/dist/kyber/kem.d.ts +21 -0
- package/dist/kyber/kem.js +160 -0
- package/dist/kyber/params.d.ts +14 -0
- package/dist/kyber/params.js +37 -0
- package/dist/kyber/suite.d.ts +13 -0
- package/dist/kyber/suite.js +93 -0
- package/dist/kyber/types.d.ts +98 -0
- package/dist/kyber/types.js +25 -0
- package/dist/kyber/validate.d.ts +19 -0
- package/dist/kyber/validate.js +68 -0
- package/dist/kyber.wasm +0 -0
- package/dist/loader.d.ts +19 -4
- package/dist/loader.js +91 -25
- package/dist/serpent/cipher-suite.d.ts +4 -0
- package/dist/serpent/cipher-suite.js +121 -0
- package/dist/serpent/embedded.d.ts +1 -0
- package/dist/serpent/embedded.js +27 -0
- package/dist/serpent/index.d.ts +6 -37
- package/dist/serpent/index.js +9 -118
- package/dist/serpent/pool-worker.d.ts +1 -0
- package/dist/serpent/pool-worker.js +202 -0
- package/dist/serpent/serpent-cbc.d.ts +30 -0
- package/dist/serpent/serpent-cbc.js +136 -0
- package/dist/sha2/embedded.d.ts +1 -0
- package/dist/sha2/embedded.js +27 -0
- package/dist/sha2/hkdf.js +6 -2
- package/dist/sha2/index.d.ts +3 -2
- package/dist/sha2/index.js +3 -4
- package/dist/sha3/embedded.d.ts +1 -0
- package/dist/sha3/embedded.js +27 -0
- package/dist/sha3/index.d.ts +3 -2
- package/dist/sha3/index.js +3 -4
- package/dist/stream/constants.d.ts +6 -0
- package/dist/stream/constants.js +30 -0
- package/dist/stream/header.d.ts +9 -0
- package/dist/stream/header.js +77 -0
- package/dist/stream/index.d.ts +7 -0
- package/dist/stream/index.js +27 -0
- package/dist/stream/open-stream.d.ts +21 -0
- package/dist/stream/open-stream.js +146 -0
- package/dist/stream/seal-stream-pool.d.ts +38 -0
- package/dist/stream/seal-stream-pool.js +391 -0
- package/dist/stream/seal-stream.d.ts +20 -0
- package/dist/stream/seal-stream.js +142 -0
- package/dist/stream/seal.d.ts +9 -0
- package/dist/stream/seal.js +75 -0
- package/dist/stream/types.d.ts +24 -0
- package/dist/stream/types.js +26 -0
- package/dist/utils.d.ts +12 -7
- package/dist/utils.js +75 -19
- package/dist/wasm-source.d.ts +12 -0
- package/dist/wasm-source.js +26 -0
- package/package.json +13 -5
- package/dist/chacha20/pool.d.ts +0 -52
- package/dist/chacha20/pool.js +0 -188
- package/dist/chacha20/pool.worker.js +0 -37
- package/dist/docs/chacha20_pool.md +0 -309
- package/dist/docs/wasm.md +0 -194
- package/dist/serpent/seal.d.ts +0 -8
- package/dist/serpent/stream-pool.d.ts +0 -48
- package/dist/serpent/stream-pool.js +0 -285
- package/dist/serpent/stream-sealer.d.ts +0 -50
- package/dist/serpent/stream-sealer.js +0 -341
- package/dist/serpent/stream.d.ts +0 -28
- package/dist/serpent/stream.js +0 -205
- package/dist/serpent/stream.worker.d.ts +0 -32
- package/dist/serpent/stream.worker.js +0 -117
- /package/dist/chacha20/{pool.worker.d.ts → pool-worker.d.ts} +0 -0
package/dist/docs/wasm.md
DELETED
|
@@ -1,194 +0,0 @@
|
|
|
1
|
-
# WebAssembly Primer
|
|
2
|
-
|
|
3
|
-
> [!NOTE]
|
|
4
|
-
> - A short introduction to WebAssembly concepts as they apply to the leviathan-crypto library.
|
|
5
|
-
> - If you already understand WASM, skip to [Project-Specific Concepts](#project-specific-concepts).
|
|
6
|
-
> - WebAssembly specification and documentation: [webassembly.org](https://webassembly.org/)
|
|
7
|
-
|
|
8
|
-
## What is WebAssembly?
|
|
9
|
-
|
|
10
|
-
WebAssembly (WASM) is a binary instruction format that runs in browsers and
|
|
11
|
-
server-side runtimes alongside JavaScript. Rather than a programming language
|
|
12
|
-
one writes by hand, it serves as a compilation target. Code is written in a higher-level
|
|
13
|
-
language, compiled to `.wasm`, and then executed by the browser.
|
|
14
|
-
|
|
15
|
-
Consider it a small, fast virtual machine built into every modern browser.
|
|
16
|
-
JavaScript can load a `.wasm` binary, call its exported functions, and read
|
|
17
|
-
its results. The WASM code runs in its own sandboxed memory space, and thus cannot
|
|
18
|
-
touch the DOM, access JavaScript variables, or reach the network. It computes
|
|
19
|
-
and returns values, and that is its sole function.
|
|
20
|
-
|
|
21
|
-
---
|
|
22
|
-
|
|
23
|
-
## How It Runs
|
|
24
|
-
|
|
25
|
-
When a browser encounters a `.wasm` binary, it performs two steps:
|
|
26
|
-
|
|
27
|
-
1. Compilation: The binary is validated and compiled into native machine code.
|
|
28
|
-
This is fast because WASM is already a low-level format, requiring less
|
|
29
|
-
work for the compiler compared to parsing and optimizing JavaScript.
|
|
30
|
-
|
|
31
|
-
2. Instantiation: The compiled module is paired with its imports, such as a
|
|
32
|
-
memory object, to create a live instance. The instance's exported functions
|
|
33
|
-
are then callable from JavaScript.
|
|
34
|
-
|
|
35
|
-
Once instantiated, calling a WASM function is similar to calling any JavaScript
|
|
36
|
-
function: you pass arguments, it runs, and it returns a result. The key difference
|
|
37
|
-
lies in how it runs. WASM execution is deterministic and not subject to the
|
|
38
|
-
JIT compiler's speculative optimizations. Unlike JavaScript, the browser does not rewrite, inline,
|
|
39
|
-
or de-optimize WASM code paths based on runtime profiling.
|
|
40
|
-
|
|
41
|
-
---
|
|
42
|
-
|
|
43
|
-
## Why We Use It
|
|
44
|
-
|
|
45
|
-
Leviathan performs all cryptographic computations in WASM because JavaScript
|
|
46
|
-
engines offer no formal constant-time guarantees for arbitrary code. The JIT
|
|
47
|
-
compiler can introduce timing variations that leak information about secret
|
|
48
|
-
data; WASM execution avoids this class of problem.
|
|
49
|
-
|
|
50
|
-
For architectural details and security rationale, see [architecture.md](./architecture.md).
|
|
51
|
-
|
|
52
|
-
**TLDR:** _TypeScript handles the API, and WASM handles the math._
|
|
53
|
-
|
|
54
|
-
---
|
|
55
|
-
|
|
56
|
-
## Core Concepts
|
|
57
|
-
|
|
58
|
-
### Module
|
|
59
|
-
|
|
60
|
-
A `WebAssembly.Module` is a compiled `.wasm` binary and a stateless
|
|
61
|
-
template for creating instances. You can compile a module once and create
|
|
62
|
-
multiple instances from it. For example, [XChaCha20Poly1305Pool](./chacha20_pool.md)
|
|
63
|
-
uses one compiled module to create many worker instances.
|
|
64
|
-
|
|
65
|
-
---
|
|
66
|
-
|
|
67
|
-
### Instance
|
|
68
|
-
|
|
69
|
-
A WebAssembly.Instance is a live, runnable copy of a module, complete with
|
|
70
|
-
its own memory and state. When you call `init('serpent')`, the library
|
|
71
|
-
compiles the Serpent WASM binary and creates a single instance. All
|
|
72
|
-
Serpent classes (`Serpent`, `SerpentCtr`, `SerpentCbc`) share this instance.
|
|
73
|
-
|
|
74
|
-
---
|
|
75
|
-
|
|
76
|
-
### Memory
|
|
77
|
-
|
|
78
|
-
A `WebAssembly.Memory` is a contiguous block of bytes, essentially a
|
|
79
|
-
`Uint8Array` that WASM functions can read and write, also known as **linear
|
|
80
|
-
memory**. Each of our WASM modules gets its own memory (3 pages = 192 KB).
|
|
81
|
-
|
|
82
|
-
The TypeScript layer communicates with WASM by writing inputs to specific offsets
|
|
83
|
-
in this memory, calling a WASM function, and then reading the outputs from other
|
|
84
|
-
offsets. There is no other communication channel, no function arguments for
|
|
85
|
-
large data, and no return values beyond a single number. Memory is the data bus.
|
|
86
|
-
|
|
87
|
-
---
|
|
88
|
-
|
|
89
|
-
### Exports
|
|
90
|
-
|
|
91
|
-
A WASM instance exposes exports: functions and memory that JavaScript can
|
|
92
|
-
access. In leviathan-crypto, every WASM module exports:
|
|
93
|
-
|
|
94
|
-
- **Getter functions** like getKeyOffset() and getChunkPtOffset(): these
|
|
95
|
-
return the memory offsets where the TypeScript layer should write inputs
|
|
96
|
-
or read outputs.
|
|
97
|
-
- **Operation functions** like chachaEncryptChunk() and sha256Final():
|
|
98
|
-
these perform the actual cryptographic computation on data already in memory.
|
|
99
|
-
- **wipeBuffers():** this zeros all sensitive regions of memory and is called
|
|
100
|
-
by every class's dispose() method.
|
|
101
|
-
- **memory:** the linear memory object itself, which allows the TypeScript
|
|
102
|
-
layer to create Uint8Array views over it.
|
|
103
|
-
|
|
104
|
-
---
|
|
105
|
-
|
|
106
|
-
### Imports
|
|
107
|
-
|
|
108
|
-
When instantiating a module, you can pass **imports:** objects the WASM code
|
|
109
|
-
needs from the host. Our modules import only one thing: the Memory object.
|
|
110
|
-
We create the memory on the JavaScript side and pass it in, giving us
|
|
111
|
-
control over its size and lifecycle.
|
|
112
|
-
|
|
113
|
-
---
|
|
114
|
-
|
|
115
|
-
## Project-Specific Concepts
|
|
116
|
-
|
|
117
|
-
### AssemblyScript
|
|
118
|
-
|
|
119
|
-
The WASM binaries in this project are written in [AssemblyScript](https://www.assemblyscript.org/):
|
|
120
|
-
a TypeScript-like language that compiles to WebAssembly. It resembles
|
|
121
|
-
TypeScript but targets WASM instead of JavaScript. The source code
|
|
122
|
-
resides in `src/asm/` and compiles into `.wasm` binaries in `build/`.
|
|
123
|
-
|
|
124
|
-
AssemblyScript was selected because its syntax is familiar to TypeScript
|
|
125
|
-
developers. It produces small binaries and grants low-level control over
|
|
126
|
-
memory layout without requiring C, C++, or Rust.
|
|
127
|
-
|
|
128
|
-
---
|
|
129
|
-
|
|
130
|
-
### Thunks
|
|
131
|
-
|
|
132
|
-
In this project, a **thunk** is a base64-encoded WASM binary embedded directly
|
|
133
|
-
within a TypeScript file. The files in `src/ts/embedded/`
|
|
134
|
-
(such as chacha20.ts and serpent.ts) each export a single constant:
|
|
135
|
-
|
|
136
|
-
```typescript
|
|
137
|
-
export const WASM_BASE64 = 'AGFzbQEAAAAB...'
|
|
138
|
-
```
|
|
139
|
-
|
|
140
|
-
This represents the entire compiled .wasm binary, encoded as a base64 string. When
|
|
141
|
-
you call init('chacha20') in embedded mode (the default), the library
|
|
142
|
-
imports this string, decodes it back into bytes, and compiles it into a
|
|
143
|
-
`WebAssembly.Module`.
|
|
144
|
-
|
|
145
|
-
Why embed the binary as a string? This approach enables the library to function with zero
|
|
146
|
-
configuration. There's no need to serve .wasm files from a CDN, configure MIME
|
|
147
|
-
types, or establish a build plugin to manage binary imports. Simply npm install and
|
|
148
|
-
import. The tradeoff is bundle size, as base64 encoding increases the size by
|
|
149
|
-
approximately 33% compared to the raw binary. For production deployments where bundle size is
|
|
150
|
-
critical, the library also supports [streaming and manual loading modes](./loader.md).
|
|
151
|
-
|
|
152
|
-
**TLDR:** Thunks are build artifacts generated by `scripts/embed-wasm.ts`.
|
|
153
|
-
They are gitignored and regenerated during each build. Avoid manual edits.
|
|
154
|
-
|
|
155
|
-
---
|
|
156
|
-
|
|
157
|
-
### Buffer Layout
|
|
158
|
-
|
|
159
|
-
Each WASM module divides its linear memory into fixed regions at known offsets.
|
|
160
|
-
For example, the ChaCha20 module has a region for the key, a region for the
|
|
161
|
-
nonce, a region for plaintext input, a region for ciphertext output, and so on.
|
|
162
|
-
These offsets are defined in `src/asm/*/buffers.ts` and never change at runtime.
|
|
163
|
-
The TypeScript layer calls getter functions (like `getKeyOffset()`) to
|
|
164
|
-
determine where each region starts, then reads and writes `Uint8Array` slices at those
|
|
165
|
-
positions. This is the only way data moves between TypeScript and
|
|
166
|
-
WASM. There is no serialization, no copying to intermediate buffers, and no function call
|
|
167
|
-
overhead for large data. Data is transferred via direct byte writes to shared memory.
|
|
168
|
-
|
|
169
|
-
The buffer layouts for each module are documented in [architecture.md](./architecture.md).
|
|
170
|
-
|
|
171
|
-
---
|
|
172
|
-
|
|
173
|
-
### The `init()` Gate
|
|
174
|
-
|
|
175
|
-
WASM modules must be compiled and instantiated before use. Because compilation
|
|
176
|
-
returns a Promise, this is an asynchronous operation. Rather than hiding this
|
|
177
|
-
behind lazy auto-initialization, which would make every cryptographic call
|
|
178
|
-
implicitly asynchronous and create race conditions, the library requires an explicit
|
|
179
|
-
`init()` call up front. If you forget, every class immediately throws an error message
|
|
180
|
-
indicating which `init(init()` call is missing. _This is deliberate._
|
|
181
|
-
|
|
182
|
-
See [init.md](./init.md) for the full API.
|
|
183
|
-
|
|
184
|
-
---
|
|
185
|
-
|
|
186
|
-
> ## Cross-References
|
|
187
|
-
>
|
|
188
|
-
> - [index](./README.md) — Project Documentation index
|
|
189
|
-
> - [architecture](./architecture.md) — architecture overview, module relationships, buffer layouts, and build pipeline
|
|
190
|
-
> - [serpent_simd_bench](./serpent_simd_bench.md) Serpent-256 SIMD benchmark results: CTR and CBC-decrypt inter-block 4-wide, scalar vs SIMD across V8, SpiderMonkey, and JSC
|
|
191
|
-
> - [chacha_simd_bench](./chacha_simd_bench.md) ChaCha20 SIMD benchmark results: 4-wide inter-block parallelism, scalar vs SIMD across V8, SpiderMonkey, and JSC. Includes documented negative result for intra-block approach
|
|
192
|
-
> - [init](./init.md) — `init()` API and the three loading modes
|
|
193
|
-
> - [loader](./loader.md) — how WASM binaries are loaded and instantiated
|
|
194
|
-
> - [chacha20_pool](./chacha20_pool.md) — example of one compiled module spawning many instances across workers
|
package/dist/serpent/seal.d.ts
DELETED
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
export interface StreamPoolOpts {
|
|
2
|
-
/** Number of workers. Default: navigator.hardwareConcurrency ?? 4 */
|
|
3
|
-
workers?: number;
|
|
4
|
-
}
|
|
5
|
-
/**
|
|
6
|
-
* Parallel worker pool for SerpentStream chunked authenticated encryption.
|
|
7
|
-
*
|
|
8
|
-
* Each worker owns its own `serpent.wasm` and `sha2.wasm` instances with
|
|
9
|
-
* isolated linear memory. Key derivation happens on the main thread; workers
|
|
10
|
-
* receive pre-derived encKey/macKey per chunk.
|
|
11
|
-
*
|
|
12
|
-
* Produces the same wire format as `SerpentStream` -- either can decrypt
|
|
13
|
-
* the other's output.
|
|
14
|
-
*/
|
|
15
|
-
export declare class SerpentStreamPool {
|
|
16
|
-
private readonly _workers;
|
|
17
|
-
private readonly _idle;
|
|
18
|
-
private readonly _queue;
|
|
19
|
-
private readonly _pending;
|
|
20
|
-
private readonly _hkdf;
|
|
21
|
-
private _nextId;
|
|
22
|
-
private _disposed;
|
|
23
|
-
private constructor();
|
|
24
|
-
/**
|
|
25
|
-
* Create a new pool. Requires `init(['serpent', 'sha2'])` to have been called.
|
|
26
|
-
* Compiles both WASM modules once and distributes them to all workers.
|
|
27
|
-
*/
|
|
28
|
-
static create(opts?: StreamPoolOpts): Promise<SerpentStreamPool>;
|
|
29
|
-
/**
|
|
30
|
-
* Encrypt plaintext with SerpentStream chunked authenticated encryption.
|
|
31
|
-
* Returns the complete wire format (header + encrypted chunks).
|
|
32
|
-
*/
|
|
33
|
-
seal(key: Uint8Array, plaintext: Uint8Array, chunkSize?: number): Promise<Uint8Array>;
|
|
34
|
-
/**
|
|
35
|
-
* Decrypt SerpentStream wire format.
|
|
36
|
-
* If any chunk fails authentication, rejects immediately -- no partial plaintext.
|
|
37
|
-
*/
|
|
38
|
-
open(key: Uint8Array, ciphertext: Uint8Array): Promise<Uint8Array>;
|
|
39
|
-
/** Terminates all workers. Rejects all pending and queued jobs. */
|
|
40
|
-
dispose(): void;
|
|
41
|
-
/** Number of workers in the pool. */
|
|
42
|
-
get size(): number;
|
|
43
|
-
/** Number of jobs currently queued (waiting for a free worker). */
|
|
44
|
-
get queueDepth(): number;
|
|
45
|
-
private _dispatch;
|
|
46
|
-
private _send;
|
|
47
|
-
private _onMessage;
|
|
48
|
-
}
|
|
@@ -1,285 +0,0 @@
|
|
|
1
|
-
// ▄▄▄▄▄▄▄▄▄▄
|
|
2
|
-
// ▄████████████████████▄▄ ▒ ▄▀▀ ▒ ▒ █ ▄▀▄ ▀█▀ █ ▒ ▄▀▄ █▀▄
|
|
3
|
-
// ▄██████████████████████ ▀████▄ ▓ ▓▀ ▓ ▓ ▓ ▓▄▓ ▓ ▓▀▓ ▓▄▓ ▓ ▓
|
|
4
|
-
// ▄█████████▀▀▀ ▀███████▄▄███████▌ ▀▄ ▀▄▄ ▀▄▀ ▒ ▒ ▒ ▒ ▒ █ ▒ ▒ ▒ █
|
|
5
|
-
// ▐████████▀ ▄▄▄▄ ▀████████▀██▀█▌
|
|
6
|
-
// ████████ ███▀▀ ████▀ █▀ █▀ Leviathan Crypto Library
|
|
7
|
-
// ███████▌ ▀██▀ ███
|
|
8
|
-
// ███████ ▀███ ▀██ ▀█▄ Repository & Mirror:
|
|
9
|
-
// ▀██████ ▄▄██ ▀▀ ██▄ github.com/xero/leviathan-crypto
|
|
10
|
-
// ▀█████▄ ▄██▄ ▄▀▄▀ unpkg.com/leviathan-crypto
|
|
11
|
-
// ▀████▄ ▄██▄
|
|
12
|
-
// ▐████ ▐███ Author: xero (https://x-e.ro)
|
|
13
|
-
// ▄▄██████████ ▐███ ▄▄ License: MIT
|
|
14
|
-
// ▄██▀▀▀▀▀▀▀▀▀▀ ▄████ ▄██▀
|
|
15
|
-
// ▄▀ ▄▄█████████▄▄ ▀▀▀▀▀ ▄███ This file is provided completely
|
|
16
|
-
// ▄██████▀▀▀▀▀▀██████▄ ▀▄▄▄▄████▀ free, "as is", and without
|
|
17
|
-
// ████▀ ▄▄▄▄▄▄▄ ▀████▄ ▀█████▀ ▄▄▄▄ warranty of any kind. The author
|
|
18
|
-
// █████▄▄█████▀▀▀▀▀▀▄ ▀███▄ ▄████ assumes absolutely no liability
|
|
19
|
-
// ▀██████▀ ▀████▄▄▄████▀ for its {ab,mis,}use.
|
|
20
|
-
// ▀█████▀▀
|
|
21
|
-
//
|
|
22
|
-
// src/ts/serpent/stream-pool.ts
|
|
23
|
-
//
|
|
24
|
-
// SerpentStreamPool — parallel worker pool for SerpentStream.
|
|
25
|
-
// Dispatches chunk-level seal/open jobs across Web Workers, each
|
|
26
|
-
// with its own serpent.wasm and sha2.wasm instances.
|
|
27
|
-
import { isInitialized } from '../init.js';
|
|
28
|
-
import { HKDF_SHA256 } from '../sha2/index.js';
|
|
29
|
-
import { u32be, u64be, deriveChunkKeys } from './stream.js';
|
|
30
|
-
// ── Constants ─────────────────────────────────────────────────────────────────
|
|
31
|
-
const CHUNK_MIN = 1024;
|
|
32
|
-
const CHUNK_MAX = 65536;
|
|
33
|
-
const CHUNK_DEF = 65536;
|
|
34
|
-
// ── Module-private base64 decoder ─────────────────────────────────────────────
|
|
35
|
-
function base64ToBytes(b64) {
|
|
36
|
-
if (typeof atob === 'function') {
|
|
37
|
-
const raw = atob(b64);
|
|
38
|
-
const out = new Uint8Array(raw.length);
|
|
39
|
-
for (let i = 0; i < raw.length; i++)
|
|
40
|
-
out[i] = raw.charCodeAt(i);
|
|
41
|
-
return out;
|
|
42
|
-
}
|
|
43
|
-
return new Uint8Array(Buffer.from(b64, 'base64'));
|
|
44
|
-
}
|
|
45
|
-
// ── WASM module singletons ──────────────────────────────────────────────────
|
|
46
|
-
let _serpentModule;
|
|
47
|
-
let _sha2Module;
|
|
48
|
-
async function getSerpentModule() {
|
|
49
|
-
if (_serpentModule)
|
|
50
|
-
return _serpentModule;
|
|
51
|
-
const { WASM_BASE64 } = await import('../embedded/serpent.js');
|
|
52
|
-
const bytes = base64ToBytes(WASM_BASE64);
|
|
53
|
-
_serpentModule = await WebAssembly.compile(bytes.buffer);
|
|
54
|
-
return _serpentModule;
|
|
55
|
-
}
|
|
56
|
-
async function getSha2Module() {
|
|
57
|
-
if (_sha2Module)
|
|
58
|
-
return _sha2Module;
|
|
59
|
-
const { WASM_BASE64 } = await import('../embedded/sha2.js');
|
|
60
|
-
const bytes = base64ToBytes(WASM_BASE64);
|
|
61
|
-
_sha2Module = await WebAssembly.compile(bytes.buffer);
|
|
62
|
-
return _sha2Module;
|
|
63
|
-
}
|
|
64
|
-
// ── Worker spawning ──────────────────────────────────────────────────────────
|
|
65
|
-
function spawnWorker(serpentMod, sha2Mod) {
|
|
66
|
-
return new Promise((resolve, reject) => {
|
|
67
|
-
const worker = new Worker(new URL('./stream.worker.js', import.meta.url), { type: 'module' });
|
|
68
|
-
const onMessage = (e) => {
|
|
69
|
-
cleanup();
|
|
70
|
-
if (e.data.type === 'ready') {
|
|
71
|
-
resolve(worker);
|
|
72
|
-
}
|
|
73
|
-
else {
|
|
74
|
-
worker.terminate();
|
|
75
|
-
reject(new Error(`leviathan-crypto: worker init failed: ${e.data.message}`));
|
|
76
|
-
}
|
|
77
|
-
};
|
|
78
|
-
const onError = (e) => {
|
|
79
|
-
cleanup();
|
|
80
|
-
worker.terminate();
|
|
81
|
-
reject(new Error(`leviathan-crypto: worker init failed: ${e.message}`));
|
|
82
|
-
};
|
|
83
|
-
const cleanup = () => {
|
|
84
|
-
worker.removeEventListener('message', onMessage);
|
|
85
|
-
worker.removeEventListener('error', onError);
|
|
86
|
-
};
|
|
87
|
-
worker.addEventListener('message', onMessage);
|
|
88
|
-
worker.addEventListener('error', onError);
|
|
89
|
-
worker.postMessage({ type: 'init', serpentModule: serpentMod, sha2Module: sha2Mod });
|
|
90
|
-
});
|
|
91
|
-
}
|
|
92
|
-
// ── Pool class ───────────────────────────────────────────────────────────────
|
|
93
|
-
/**
|
|
94
|
-
* Parallel worker pool for SerpentStream chunked authenticated encryption.
|
|
95
|
-
*
|
|
96
|
-
* Each worker owns its own `serpent.wasm` and `sha2.wasm` instances with
|
|
97
|
-
* isolated linear memory. Key derivation happens on the main thread; workers
|
|
98
|
-
* receive pre-derived encKey/macKey per chunk.
|
|
99
|
-
*
|
|
100
|
-
* Produces the same wire format as `SerpentStream` -- either can decrypt
|
|
101
|
-
* the other's output.
|
|
102
|
-
*/
|
|
103
|
-
export class SerpentStreamPool {
|
|
104
|
-
_workers;
|
|
105
|
-
_idle;
|
|
106
|
-
_queue;
|
|
107
|
-
_pending;
|
|
108
|
-
_hkdf;
|
|
109
|
-
_nextId;
|
|
110
|
-
_disposed;
|
|
111
|
-
constructor(workers, hkdf) {
|
|
112
|
-
this._workers = workers;
|
|
113
|
-
this._idle = [...workers];
|
|
114
|
-
this._queue = [];
|
|
115
|
-
this._pending = new Map();
|
|
116
|
-
this._hkdf = hkdf;
|
|
117
|
-
this._nextId = 0;
|
|
118
|
-
this._disposed = false;
|
|
119
|
-
for (const w of workers) {
|
|
120
|
-
w.onmessage = (e) => this._onMessage(w, e);
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
/**
|
|
124
|
-
* Create a new pool. Requires `init(['serpent', 'sha2'])` to have been called.
|
|
125
|
-
* Compiles both WASM modules once and distributes them to all workers.
|
|
126
|
-
*/
|
|
127
|
-
static async create(opts) {
|
|
128
|
-
if (!isInitialized('serpent') || !isInitialized('sha2'))
|
|
129
|
-
throw new Error('leviathan-crypto: call init([\'serpent\', \'sha2\']) before using SerpentStreamPool');
|
|
130
|
-
const n = opts?.workers ?? (typeof navigator !== 'undefined' ? navigator.hardwareConcurrency : undefined) ?? 4;
|
|
131
|
-
const [serpentMod, sha2Mod] = await Promise.all([getSerpentModule(), getSha2Module()]);
|
|
132
|
-
// Sequential spawn — compatible with inline-worker test environments
|
|
133
|
-
const workers = [];
|
|
134
|
-
for (let i = 0; i < n; i++)
|
|
135
|
-
workers.push(await spawnWorker(serpentMod, sha2Mod));
|
|
136
|
-
const hkdf = new HKDF_SHA256();
|
|
137
|
-
return new SerpentStreamPool(workers, hkdf);
|
|
138
|
-
}
|
|
139
|
-
/**
|
|
140
|
-
* Encrypt plaintext with SerpentStream chunked authenticated encryption.
|
|
141
|
-
* Returns the complete wire format (header + encrypted chunks).
|
|
142
|
-
*/
|
|
143
|
-
async seal(key, plaintext, chunkSize) {
|
|
144
|
-
if (this._disposed)
|
|
145
|
-
throw new Error('leviathan-crypto: pool is disposed');
|
|
146
|
-
if (key.length !== 32)
|
|
147
|
-
throw new RangeError(`SerpentStream key must be 32 bytes (got ${key.length})`);
|
|
148
|
-
const cs = chunkSize ?? CHUNK_DEF;
|
|
149
|
-
if (cs < CHUNK_MIN || cs > CHUNK_MAX)
|
|
150
|
-
throw new RangeError(`SerpentStream chunkSize must be ${CHUNK_MIN}..${CHUNK_MAX} (got ${cs})`);
|
|
151
|
-
const streamNonce = new Uint8Array(16);
|
|
152
|
-
crypto.getRandomValues(streamNonce);
|
|
153
|
-
const chunkCount = plaintext.length === 0 ? 1 : Math.ceil(plaintext.length / cs);
|
|
154
|
-
// Dispatch all chunk jobs in parallel
|
|
155
|
-
const chunkPromises = [];
|
|
156
|
-
for (let i = 0; i < chunkCount; i++) {
|
|
157
|
-
const start = i * cs;
|
|
158
|
-
const end = Math.min(start + cs, plaintext.length);
|
|
159
|
-
const slice = plaintext.slice(start, end);
|
|
160
|
-
const isLast = i === chunkCount - 1;
|
|
161
|
-
const { encKey, macKey } = deriveChunkKeys(this._hkdf, key, streamNonce, cs, chunkCount, i, isLast);
|
|
162
|
-
chunkPromises.push(this._dispatch('seal', encKey, macKey, slice));
|
|
163
|
-
}
|
|
164
|
-
const chunkResults = await Promise.all(chunkPromises);
|
|
165
|
-
// Compute total output size
|
|
166
|
-
let totalWire = 28;
|
|
167
|
-
for (const c of chunkResults)
|
|
168
|
-
totalWire += c.length;
|
|
169
|
-
const out = new Uint8Array(totalWire);
|
|
170
|
-
// Write header
|
|
171
|
-
out.set(streamNonce, 0);
|
|
172
|
-
out.set(u32be(cs), 16);
|
|
173
|
-
out.set(u64be(chunkCount), 20);
|
|
174
|
-
let pos = 28;
|
|
175
|
-
for (const c of chunkResults) {
|
|
176
|
-
out.set(c, pos);
|
|
177
|
-
pos += c.length;
|
|
178
|
-
}
|
|
179
|
-
return out;
|
|
180
|
-
}
|
|
181
|
-
/**
|
|
182
|
-
* Decrypt SerpentStream wire format.
|
|
183
|
-
* If any chunk fails authentication, rejects immediately -- no partial plaintext.
|
|
184
|
-
*/
|
|
185
|
-
async open(key, ciphertext) {
|
|
186
|
-
if (this._disposed)
|
|
187
|
-
throw new Error('leviathan-crypto: pool is disposed');
|
|
188
|
-
if (key.length !== 32)
|
|
189
|
-
throw new RangeError(`SerpentStream key must be 32 bytes (got ${key.length})`);
|
|
190
|
-
if (ciphertext.length < 28 + 32)
|
|
191
|
-
throw new RangeError('SerpentStream: ciphertext too short');
|
|
192
|
-
// Parse header
|
|
193
|
-
const streamNonce = ciphertext.subarray(0, 16);
|
|
194
|
-
const csView = ciphertext.subarray(16, 20);
|
|
195
|
-
const cs = (csView[0] << 24) | (csView[1] << 16) | (csView[2] << 8) | csView[3];
|
|
196
|
-
const ccView = ciphertext.subarray(20, 28);
|
|
197
|
-
let chunkCount = 0;
|
|
198
|
-
for (let i = 0; i < 8; i++)
|
|
199
|
-
chunkCount = chunkCount * 256 + ccView[i];
|
|
200
|
-
// Dispatch all chunk jobs
|
|
201
|
-
const chunkPromises = [];
|
|
202
|
-
let pos = 28;
|
|
203
|
-
for (let i = 0; i < chunkCount; i++) {
|
|
204
|
-
const isLast = i === chunkCount - 1;
|
|
205
|
-
const wireLen = isLast ? ciphertext.length - pos : cs + 32;
|
|
206
|
-
const wireSlice = ciphertext.slice(pos, pos + wireLen);
|
|
207
|
-
const { encKey, macKey } = deriveChunkKeys(this._hkdf, key, streamNonce, cs, chunkCount, i, isLast);
|
|
208
|
-
chunkPromises.push(this._dispatch('open', encKey, macKey, wireSlice));
|
|
209
|
-
pos += wireLen;
|
|
210
|
-
}
|
|
211
|
-
// Await all — Promise.all rejects on first failure
|
|
212
|
-
const results = await Promise.all(chunkPromises);
|
|
213
|
-
// Reassemble plaintext
|
|
214
|
-
let totalPt = 0;
|
|
215
|
-
for (const r of results)
|
|
216
|
-
totalPt += r.length;
|
|
217
|
-
const plaintext = new Uint8Array(totalPt);
|
|
218
|
-
let ptPos = 0;
|
|
219
|
-
for (const r of results) {
|
|
220
|
-
plaintext.set(r, ptPos);
|
|
221
|
-
ptPos += r.length;
|
|
222
|
-
}
|
|
223
|
-
return plaintext;
|
|
224
|
-
}
|
|
225
|
-
/** Terminates all workers. Rejects all pending and queued jobs. */
|
|
226
|
-
dispose() {
|
|
227
|
-
if (this._disposed)
|
|
228
|
-
return;
|
|
229
|
-
this._disposed = true;
|
|
230
|
-
for (const w of this._workers)
|
|
231
|
-
w.terminate();
|
|
232
|
-
const err = new Error('leviathan-crypto: pool disposed');
|
|
233
|
-
for (const { reject } of this._pending.values())
|
|
234
|
-
reject(err);
|
|
235
|
-
for (const job of this._queue)
|
|
236
|
-
this._pending.get(job.id)?.reject(err);
|
|
237
|
-
this._pending.clear();
|
|
238
|
-
this._queue.length = 0;
|
|
239
|
-
this._hkdf.dispose();
|
|
240
|
-
}
|
|
241
|
-
/** Number of workers in the pool. */
|
|
242
|
-
get size() {
|
|
243
|
-
return this._workers.length;
|
|
244
|
-
}
|
|
245
|
-
/** Number of jobs currently queued (waiting for a free worker). */
|
|
246
|
-
get queueDepth() {
|
|
247
|
-
return this._queue.length;
|
|
248
|
-
}
|
|
249
|
-
// ── Internals ────────────────────────────────────────────────────────────
|
|
250
|
-
_dispatch(op, encKey, macKey, data) {
|
|
251
|
-
return new Promise((resolve, reject) => {
|
|
252
|
-
const id = this._nextId++;
|
|
253
|
-
const job = { id, op, encKey, macKey, data };
|
|
254
|
-
this._pending.set(id, { resolve, reject });
|
|
255
|
-
const worker = this._idle.pop();
|
|
256
|
-
if (worker)
|
|
257
|
-
this._send(worker, job);
|
|
258
|
-
else
|
|
259
|
-
this._queue.push(job);
|
|
260
|
-
});
|
|
261
|
-
}
|
|
262
|
-
_send(worker, job) {
|
|
263
|
-
// No transfer list: @vitest/web-worker (same-thread fake worker used in
|
|
264
|
-
// Vitest test environment) silently drops postMessage calls that include a
|
|
265
|
-
// non-empty Transferable array. encKey/macKey/data are already .slice()
|
|
266
|
-
// copies — neutering was never part of SerpentStreamPool's public contract.
|
|
267
|
-
worker.postMessage({ type: 'job', ...job });
|
|
268
|
-
}
|
|
269
|
-
_onMessage(worker, e) {
|
|
270
|
-
const msg = e.data;
|
|
271
|
-
const job = this._pending.get(msg.id);
|
|
272
|
-
if (!job)
|
|
273
|
-
return;
|
|
274
|
-
this._pending.delete(msg.id);
|
|
275
|
-
if (msg.type === 'result')
|
|
276
|
-
job.resolve(msg.data);
|
|
277
|
-
else
|
|
278
|
-
job.reject(new Error(msg.message));
|
|
279
|
-
const next = this._queue.shift();
|
|
280
|
-
if (next)
|
|
281
|
-
this._send(worker, next);
|
|
282
|
-
else
|
|
283
|
-
this._idle.push(worker);
|
|
284
|
-
}
|
|
285
|
-
}
|
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
export declare class SerpentStreamSealer {
|
|
2
|
-
private readonly _key;
|
|
3
|
-
private readonly _cs;
|
|
4
|
-
private readonly _nonce;
|
|
5
|
-
private readonly _cbc;
|
|
6
|
-
private readonly _hmac;
|
|
7
|
-
private readonly _hkdf;
|
|
8
|
-
private readonly _framed;
|
|
9
|
-
private readonly _ivs;
|
|
10
|
-
private _ivIdx;
|
|
11
|
-
private _index;
|
|
12
|
-
private _state;
|
|
13
|
-
/** Public: consumers use this 3-param form. */
|
|
14
|
-
constructor(key: Uint8Array, chunkSize?: number, opts?: {
|
|
15
|
-
framed?: boolean;
|
|
16
|
-
});
|
|
17
|
-
/** @internal Test-only overload to inject fixed nonce/IVs for deterministic KAT vectors. */
|
|
18
|
-
constructor(key: Uint8Array, chunkSize: number | undefined, opts: {
|
|
19
|
-
framed?: boolean;
|
|
20
|
-
} | undefined, _nonce: Uint8Array, _ivs?: Uint8Array[]);
|
|
21
|
-
header(): Uint8Array;
|
|
22
|
-
seal(plaintext: Uint8Array): Uint8Array;
|
|
23
|
-
final(plaintext: Uint8Array): Uint8Array;
|
|
24
|
-
private _sealChunk;
|
|
25
|
-
private _wipe;
|
|
26
|
-
dispose(): void;
|
|
27
|
-
}
|
|
28
|
-
export declare class SerpentStreamOpener {
|
|
29
|
-
private readonly _key;
|
|
30
|
-
private readonly _cs;
|
|
31
|
-
private readonly _nonce;
|
|
32
|
-
private readonly _cbc;
|
|
33
|
-
private readonly _hmac;
|
|
34
|
-
private readonly _hkdf;
|
|
35
|
-
private readonly _framed;
|
|
36
|
-
private readonly _buf;
|
|
37
|
-
private readonly _maxFrame;
|
|
38
|
-
private _bufLen;
|
|
39
|
-
private _index;
|
|
40
|
-
private _dead;
|
|
41
|
-
constructor(key: Uint8Array, header: Uint8Array, opts?: {
|
|
42
|
-
framed?: boolean;
|
|
43
|
-
});
|
|
44
|
-
get closed(): boolean;
|
|
45
|
-
open(chunk: Uint8Array): Uint8Array;
|
|
46
|
-
private _openRaw;
|
|
47
|
-
feed(bytes: Uint8Array): Uint8Array[];
|
|
48
|
-
private _wipe;
|
|
49
|
-
dispose(): void;
|
|
50
|
-
}
|