@tupik/password 0.0.0-stage → 1.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/LICENSE +21 -0
- package/README.md +89 -2
- package/dist/index.d.mts +116 -0
- package/dist/index.d.ts +116 -0
- package/dist/index.mjs +210 -0
- package/package.json +61 -3
- package/wasm/argon2.wasm +0 -0
- package/workers.d.ts +1 -0
- package/workers.mjs +9 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Carlos Alberto Barbosa Stenzel / Tupik Contributors
|
|
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 all
|
|
13
|
+
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 THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,90 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @tupik/password
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Argon2id password hashing for **Tupik**, compiled from Rust (RustCrypto `argon2`) to WebAssembly.
|
|
4
|
+
One API on Cloudflare Workers, Node.js and Bun: PHC strings, constant-time verification, `needsRehash`
|
|
5
|
+
and OWASP defaults. Workers only ships PBKDF2 in WebCrypto; this package fills that gap.
|
|
6
|
+
|
|
7
|
+
- `wasm/argon2.wasm`: **34.4 kB** (12.9 kB gzip), no imports, no JS glue. Ships in the package: no Rust needed to install.
|
|
8
|
+
- Zero runtime dependencies.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
npm install @tupik/password
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Usage
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { hashPassword, needsRehash, verifyPassword } from '@tupik/password';
|
|
20
|
+
|
|
21
|
+
const phc = await hashPassword(password); // $argon2id$v=19$m=19456,t=2,p=1$<salt>$<hash>
|
|
22
|
+
await db.saveUser({ email, passwordHash: phc });
|
|
23
|
+
|
|
24
|
+
// Login (inside a route with errors: [Errors.INVALID_CREDENTIALS])
|
|
25
|
+
if (!(await verifyPassword(user.passwordHash, password))) return ctx.fail('INVALID_CREDENTIALS');
|
|
26
|
+
if (needsRehash(user.passwordHash)) await db.updateHash(user.id, await hashPassword(password));
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
### Loading the WebAssembly module
|
|
30
|
+
|
|
31
|
+
| Runtime | How |
|
|
32
|
+
| --- | --- |
|
|
33
|
+
| Node.js 22.12 or later, Bun | Nothing to do: the first call reads `wasm/argon2.wasm` from the package. |
|
|
34
|
+
| Cloudflare Workers (Wrangler) | `import { hashPassword } from '@tupik/password/workers'`. The entry imports the `.wasm` (Wrangler compiles it to a `WebAssembly.Module`) and calls `initPassword` for you. |
|
|
35
|
+
| Workers, manual | `import wasm from '@tupik/password/argon2.wasm'; await initPassword(wasm);` |
|
|
36
|
+
| Anything else | `await initPassword(bytes \| WebAssembly.Module \| Response)` before the first hash. |
|
|
37
|
+
|
|
38
|
+
Workers forbid compiling WebAssembly from bytes at runtime, so there the module must come from a `.wasm` import.
|
|
39
|
+
|
|
40
|
+
## API
|
|
41
|
+
|
|
42
|
+
| Export | Purpose |
|
|
43
|
+
| --- | --- |
|
|
44
|
+
| `hashPassword(password, options?)` | Argon2id with a fresh 16-byte salt (`crypto.getRandomValues`); returns the PHC string |
|
|
45
|
+
| `verifyPassword(phc, password, options?)` | Constant-time check; `false` for a wrong password, throws `TypeError` for a malformed PHC string |
|
|
46
|
+
| `needsRehash(phc, options?)` | `true` when the stored costs/tag length differ from the target (or the string is malformed) |
|
|
47
|
+
| `PROFILES` | `owasp` (m=19456 KiB, t=2, p=1) and `light` (m=4096 KiB, t=1, p=1) |
|
|
48
|
+
| `initPassword(source?)` | Loads the wasm module (see above) |
|
|
49
|
+
| `argon2idRaw(input)` | Raw RFC 9106 Argon2id tag (password, salt, secret, associated data) for test vectors or KDF use |
|
|
50
|
+
| `parsePhc(phc)` | Decodes an Argon2id v1.3 PHC string, `undefined` if malformed |
|
|
51
|
+
|
|
52
|
+
Options: `profile`, `memoryCost` (KiB), `timeCost`, `parallelism`, `hashLength` (32), `saltLength` (16),
|
|
53
|
+
`secret` (pepper, Argon2 `K` input; keep it outside the database), `maxPasswordBytes` (1024; longer passwords
|
|
54
|
+
make `hashPassword` throw and `verifyPassword` answer `false`, so a 1 MB "password" cannot burn CPU) and
|
|
55
|
+
`normalize: 'NFC'` (off by default to stay compatible with other Argon2 libraries; use the same value on both sides).
|
|
56
|
+
|
|
57
|
+
Only Argon2id v1.3 is read and written. Hashes from `argon2`, `@node-rs/argon2`, `argon2-cffi` or PHP verify as is.
|
|
58
|
+
|
|
59
|
+
## Cost and the Workers CPU limit
|
|
60
|
+
|
|
61
|
+
Measured on Node.js 24 (x86-64, this WASM build, one hash at a time; native `@node-rs/argon2` for comparison):
|
|
62
|
+
|
|
63
|
+
| Profile | m / t / p | WASM | Native |
|
|
64
|
+
| --- | --- | --- | --- |
|
|
65
|
+
| `owasp` | 19456 KiB / 2 / 1 | ~40 to 55 ms | ~25 ms |
|
|
66
|
+
| `light` | 4096 KiB / 1 / 1 | ~4 to 6 ms | ~2 ms |
|
|
67
|
+
|
|
68
|
+
Cloudflare Workers count **CPU time** per request: **10 ms on the free plan**, 30 s by default on the paid plan.
|
|
69
|
+
`owasp` does not fit the free plan (the request fails with "exceeded CPU"); on the paid plan it is fine.
|
|
70
|
+
`light` fits the free plan with room for the rest of the request, but each attacker guess against a stolen
|
|
71
|
+
database is about 10x cheaper: it is below the OWASP minimum. Use `light` only when the plan forces it, and
|
|
72
|
+
move to `owasp` later with `needsRehash(phc)` (it returns `true` for `light` hashes by default), which upgrades
|
|
73
|
+
each user on their next login.
|
|
74
|
+
|
|
75
|
+
Keep sign-in endpoints rate limited (`rateLimit` from `@tupik/middleware`): a slow hash is also a cheap way to
|
|
76
|
+
spend your CPU budget.
|
|
77
|
+
|
|
78
|
+
## Rebuilding the WebAssembly
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
rustup target add wasm32-unknown-unknown
|
|
82
|
+
pnpm --filter @tupik/password build:wasm # cargo build --release + copy to wasm/argon2.wasm (+ wasm-opt -Oz if installed)
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
The crate in `rust/` exports `alloc`, `dealloc` and `argon2id_hash` as plain `extern "C"` functions
|
|
86
|
+
(`opt-level = "z"`, LTO, `panic = "abort"`, stripped). The build is reproducible from `rust/Cargo.lock`.
|
|
87
|
+
|
|
88
|
+
## License
|
|
89
|
+
|
|
90
|
+
MIT
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/** Argon2id cost parameters, as they appear in the PHC string (`m=…,t=…,p=…`). */
|
|
2
|
+
interface Argon2Params {
|
|
3
|
+
/** Memory in KiB (`m`). */
|
|
4
|
+
readonly memoryCost: number;
|
|
5
|
+
/** Passes over memory (`t`). */
|
|
6
|
+
readonly timeCost: number;
|
|
7
|
+
/** Lanes (`p`). The WASM build is single-threaded: lanes run one after the other. */
|
|
8
|
+
readonly parallelism: number;
|
|
9
|
+
}
|
|
10
|
+
/** Built-in cost profiles (see `PROFILES`). */
|
|
11
|
+
type ProfileName = 'owasp' | 'light';
|
|
12
|
+
/** A `string` is UTF-8 encoded (after optional NFC); bytes are used as given. */
|
|
13
|
+
type PasswordInput = string | Uint8Array;
|
|
14
|
+
/** Options shared by hashing and verification. */
|
|
15
|
+
interface PasswordInputOptions {
|
|
16
|
+
/**
|
|
17
|
+
* Server-side pepper (Argon2 "secret" input, RFC 9106 `K`). Keep it out of
|
|
18
|
+
* the database; a hash made with a pepper only verifies with the same pepper.
|
|
19
|
+
*/
|
|
20
|
+
readonly secret?: PasswordInput;
|
|
21
|
+
/** Longest password accepted, in UTF-8 bytes. Default 1024. */
|
|
22
|
+
readonly maxPasswordBytes?: number;
|
|
23
|
+
/**
|
|
24
|
+
* `'NFC'` normalizes string passwords first, so the same password typed on
|
|
25
|
+
* different keyboards (composed vs decomposed accents) matches. Default
|
|
26
|
+
* `false`, which keeps hashes interoperable with other Argon2 libraries.
|
|
27
|
+
* Use the same value when hashing and verifying.
|
|
28
|
+
*/
|
|
29
|
+
readonly normalize?: 'NFC' | false;
|
|
30
|
+
}
|
|
31
|
+
interface HashOptions extends PasswordInputOptions, Partial<Argon2Params> {
|
|
32
|
+
/** Base profile; explicit `memoryCost`/`timeCost`/`parallelism` override it. Default `'owasp'`. */
|
|
33
|
+
readonly profile?: ProfileName;
|
|
34
|
+
/** Tag length in bytes. Default 32. */
|
|
35
|
+
readonly hashLength?: number;
|
|
36
|
+
/** Random salt length in bytes (min 8). Default 16. */
|
|
37
|
+
readonly saltLength?: number;
|
|
38
|
+
}
|
|
39
|
+
type VerifyOptions = PasswordInputOptions;
|
|
40
|
+
/** Rehash target: the parameters `hashPassword` would use with these options. */
|
|
41
|
+
type RehashOptions = Pick<HashOptions, 'profile' | 'memoryCost' | 'timeCost' | 'parallelism' | 'hashLength'>;
|
|
42
|
+
/** Low-level Argon2id input (`argon2idRaw`). */
|
|
43
|
+
interface RawArgon2Input extends Argon2Params {
|
|
44
|
+
readonly password: Uint8Array;
|
|
45
|
+
readonly salt: Uint8Array;
|
|
46
|
+
readonly secret?: Uint8Array;
|
|
47
|
+
readonly associatedData?: Uint8Array;
|
|
48
|
+
readonly hashLength: number;
|
|
49
|
+
}
|
|
50
|
+
/** Decoded PHC string. */
|
|
51
|
+
interface ParsedPhc extends Argon2Params {
|
|
52
|
+
readonly algorithm: 'argon2id';
|
|
53
|
+
readonly version: 19;
|
|
54
|
+
readonly salt: Uint8Array;
|
|
55
|
+
readonly hash: Uint8Array;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Where the WebAssembly module comes from: an already compiled
|
|
59
|
+
* `WebAssembly.Module` (Cloudflare Workers `.wasm` import), the raw bytes, or a
|
|
60
|
+
* `Response` (e.g. `fetch` of the `.wasm` URL in a browser or Deno).
|
|
61
|
+
*/
|
|
62
|
+
type WasmSource = WebAssembly.Module | BufferSource | Response;
|
|
63
|
+
|
|
64
|
+
/** Parses an Argon2id v1.3 PHC string; `undefined` when it is malformed or another variant. */
|
|
65
|
+
declare function parsePhc(phc: string): ParsedPhc | undefined;
|
|
66
|
+
|
|
67
|
+
/** Upper bound for `memoryCost` (1 GiB): fails fast instead of exhausting wasm memory. */
|
|
68
|
+
declare const MAX_MEMORY_COST: number;
|
|
69
|
+
/**
|
|
70
|
+
* Loads the Argon2id WebAssembly module. Optional on Node.js/Bun/Deno (the
|
|
71
|
+
* first hash reads the bundled `.wasm` from disk); required on Cloudflare
|
|
72
|
+
* Workers, which forbid compiling wasm from bytes at runtime: pass the module
|
|
73
|
+
* imported with `import wasm from '@tupik/password/argon2.wasm'`, or import
|
|
74
|
+
* `@tupik/password/workers`, which does it for you.
|
|
75
|
+
*/
|
|
76
|
+
declare function initPassword(source?: WasmSource): Promise<void>;
|
|
77
|
+
/**
|
|
78
|
+
* Raw Argon2id v1.3 (RFC 9106): returns the `hashLength`-byte tag. Building
|
|
79
|
+
* block for `hashPassword`; use it directly only for test vectors or KDF use.
|
|
80
|
+
*/
|
|
81
|
+
declare function argon2idRaw(input: RawArgon2Input): Promise<Uint8Array>;
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Cost profiles.
|
|
85
|
+
* - `owasp`: OWASP Password Storage Cheat Sheet minimum for Argon2id
|
|
86
|
+
* (19 MiB, 2 passes, 1 lane). Use it on servers without a tight CPU budget.
|
|
87
|
+
* - `light`: 4 MiB, 1 pass, 1 lane, about 10x cheaper per hash (~4 ms vs
|
|
88
|
+
* ~40 ms in Node.js 24 on this WASM build). Every guess of an attacker with
|
|
89
|
+
* a stolen database is 10x cheaper too: it is below the OWASP minimum and
|
|
90
|
+
* meant only for runtimes with a hard CPU cap (Cloudflare Workers free plan,
|
|
91
|
+
* 10 ms of CPU per request). Prefer `owasp` on the paid plan.
|
|
92
|
+
*/
|
|
93
|
+
declare const PROFILES: Readonly<Record<ProfileName, Argon2Params>>;
|
|
94
|
+
/**
|
|
95
|
+
* Hashes a password with Argon2id and a fresh random salt
|
|
96
|
+
* (`crypto.getRandomValues`). Returns the PHC string
|
|
97
|
+
* `$argon2id$v=19$m=…,t=…,p=…$<salt>$<hash>` to store as is.
|
|
98
|
+
* Throws `RangeError` for a password over `maxPasswordBytes` or invalid costs.
|
|
99
|
+
*/
|
|
100
|
+
declare function hashPassword(password: PasswordInput, options?: HashOptions): Promise<string>;
|
|
101
|
+
/**
|
|
102
|
+
* Checks a password against a stored PHC string in constant time. Resolves
|
|
103
|
+
* `false` for a wrong password (or one over `maxPasswordBytes`); throws
|
|
104
|
+
* `TypeError` when `phc` is not an Argon2id v1.3 PHC string, since that is a
|
|
105
|
+
* storage bug rather than a failed login.
|
|
106
|
+
*/
|
|
107
|
+
declare function verifyPassword(phc: string, password: PasswordInput, options?: VerifyOptions): Promise<boolean>;
|
|
108
|
+
/**
|
|
109
|
+
* `true` when the stored hash should be recomputed on the next successful
|
|
110
|
+
* login: malformed, another Argon2 variant/version, or costs/tag length that
|
|
111
|
+
* differ from the target (`options`, default profile `owasp`).
|
|
112
|
+
*/
|
|
113
|
+
declare function needsRehash(phc: string, options?: RehashOptions): boolean;
|
|
114
|
+
|
|
115
|
+
export { MAX_MEMORY_COST, PROFILES, argon2idRaw, hashPassword, initPassword, needsRehash, parsePhc, verifyPassword };
|
|
116
|
+
export type { Argon2Params, HashOptions, ParsedPhc, PasswordInput, PasswordInputOptions, ProfileName, RawArgon2Input, RehashOptions, VerifyOptions, WasmSource };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/** Argon2id cost parameters, as they appear in the PHC string (`m=…,t=…,p=…`). */
|
|
2
|
+
interface Argon2Params {
|
|
3
|
+
/** Memory in KiB (`m`). */
|
|
4
|
+
readonly memoryCost: number;
|
|
5
|
+
/** Passes over memory (`t`). */
|
|
6
|
+
readonly timeCost: number;
|
|
7
|
+
/** Lanes (`p`). The WASM build is single-threaded: lanes run one after the other. */
|
|
8
|
+
readonly parallelism: number;
|
|
9
|
+
}
|
|
10
|
+
/** Built-in cost profiles (see `PROFILES`). */
|
|
11
|
+
type ProfileName = 'owasp' | 'light';
|
|
12
|
+
/** A `string` is UTF-8 encoded (after optional NFC); bytes are used as given. */
|
|
13
|
+
type PasswordInput = string | Uint8Array;
|
|
14
|
+
/** Options shared by hashing and verification. */
|
|
15
|
+
interface PasswordInputOptions {
|
|
16
|
+
/**
|
|
17
|
+
* Server-side pepper (Argon2 "secret" input, RFC 9106 `K`). Keep it out of
|
|
18
|
+
* the database; a hash made with a pepper only verifies with the same pepper.
|
|
19
|
+
*/
|
|
20
|
+
readonly secret?: PasswordInput;
|
|
21
|
+
/** Longest password accepted, in UTF-8 bytes. Default 1024. */
|
|
22
|
+
readonly maxPasswordBytes?: number;
|
|
23
|
+
/**
|
|
24
|
+
* `'NFC'` normalizes string passwords first, so the same password typed on
|
|
25
|
+
* different keyboards (composed vs decomposed accents) matches. Default
|
|
26
|
+
* `false`, which keeps hashes interoperable with other Argon2 libraries.
|
|
27
|
+
* Use the same value when hashing and verifying.
|
|
28
|
+
*/
|
|
29
|
+
readonly normalize?: 'NFC' | false;
|
|
30
|
+
}
|
|
31
|
+
interface HashOptions extends PasswordInputOptions, Partial<Argon2Params> {
|
|
32
|
+
/** Base profile; explicit `memoryCost`/`timeCost`/`parallelism` override it. Default `'owasp'`. */
|
|
33
|
+
readonly profile?: ProfileName;
|
|
34
|
+
/** Tag length in bytes. Default 32. */
|
|
35
|
+
readonly hashLength?: number;
|
|
36
|
+
/** Random salt length in bytes (min 8). Default 16. */
|
|
37
|
+
readonly saltLength?: number;
|
|
38
|
+
}
|
|
39
|
+
type VerifyOptions = PasswordInputOptions;
|
|
40
|
+
/** Rehash target: the parameters `hashPassword` would use with these options. */
|
|
41
|
+
type RehashOptions = Pick<HashOptions, 'profile' | 'memoryCost' | 'timeCost' | 'parallelism' | 'hashLength'>;
|
|
42
|
+
/** Low-level Argon2id input (`argon2idRaw`). */
|
|
43
|
+
interface RawArgon2Input extends Argon2Params {
|
|
44
|
+
readonly password: Uint8Array;
|
|
45
|
+
readonly salt: Uint8Array;
|
|
46
|
+
readonly secret?: Uint8Array;
|
|
47
|
+
readonly associatedData?: Uint8Array;
|
|
48
|
+
readonly hashLength: number;
|
|
49
|
+
}
|
|
50
|
+
/** Decoded PHC string. */
|
|
51
|
+
interface ParsedPhc extends Argon2Params {
|
|
52
|
+
readonly algorithm: 'argon2id';
|
|
53
|
+
readonly version: 19;
|
|
54
|
+
readonly salt: Uint8Array;
|
|
55
|
+
readonly hash: Uint8Array;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Where the WebAssembly module comes from: an already compiled
|
|
59
|
+
* `WebAssembly.Module` (Cloudflare Workers `.wasm` import), the raw bytes, or a
|
|
60
|
+
* `Response` (e.g. `fetch` of the `.wasm` URL in a browser or Deno).
|
|
61
|
+
*/
|
|
62
|
+
type WasmSource = WebAssembly.Module | BufferSource | Response;
|
|
63
|
+
|
|
64
|
+
/** Parses an Argon2id v1.3 PHC string; `undefined` when it is malformed or another variant. */
|
|
65
|
+
declare function parsePhc(phc: string): ParsedPhc | undefined;
|
|
66
|
+
|
|
67
|
+
/** Upper bound for `memoryCost` (1 GiB): fails fast instead of exhausting wasm memory. */
|
|
68
|
+
declare const MAX_MEMORY_COST: number;
|
|
69
|
+
/**
|
|
70
|
+
* Loads the Argon2id WebAssembly module. Optional on Node.js/Bun/Deno (the
|
|
71
|
+
* first hash reads the bundled `.wasm` from disk); required on Cloudflare
|
|
72
|
+
* Workers, which forbid compiling wasm from bytes at runtime: pass the module
|
|
73
|
+
* imported with `import wasm from '@tupik/password/argon2.wasm'`, or import
|
|
74
|
+
* `@tupik/password/workers`, which does it for you.
|
|
75
|
+
*/
|
|
76
|
+
declare function initPassword(source?: WasmSource): Promise<void>;
|
|
77
|
+
/**
|
|
78
|
+
* Raw Argon2id v1.3 (RFC 9106): returns the `hashLength`-byte tag. Building
|
|
79
|
+
* block for `hashPassword`; use it directly only for test vectors or KDF use.
|
|
80
|
+
*/
|
|
81
|
+
declare function argon2idRaw(input: RawArgon2Input): Promise<Uint8Array>;
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Cost profiles.
|
|
85
|
+
* - `owasp`: OWASP Password Storage Cheat Sheet minimum for Argon2id
|
|
86
|
+
* (19 MiB, 2 passes, 1 lane). Use it on servers without a tight CPU budget.
|
|
87
|
+
* - `light`: 4 MiB, 1 pass, 1 lane, about 10x cheaper per hash (~4 ms vs
|
|
88
|
+
* ~40 ms in Node.js 24 on this WASM build). Every guess of an attacker with
|
|
89
|
+
* a stolen database is 10x cheaper too: it is below the OWASP minimum and
|
|
90
|
+
* meant only for runtimes with a hard CPU cap (Cloudflare Workers free plan,
|
|
91
|
+
* 10 ms of CPU per request). Prefer `owasp` on the paid plan.
|
|
92
|
+
*/
|
|
93
|
+
declare const PROFILES: Readonly<Record<ProfileName, Argon2Params>>;
|
|
94
|
+
/**
|
|
95
|
+
* Hashes a password with Argon2id and a fresh random salt
|
|
96
|
+
* (`crypto.getRandomValues`). Returns the PHC string
|
|
97
|
+
* `$argon2id$v=19$m=…,t=…,p=…$<salt>$<hash>` to store as is.
|
|
98
|
+
* Throws `RangeError` for a password over `maxPasswordBytes` or invalid costs.
|
|
99
|
+
*/
|
|
100
|
+
declare function hashPassword(password: PasswordInput, options?: HashOptions): Promise<string>;
|
|
101
|
+
/**
|
|
102
|
+
* Checks a password against a stored PHC string in constant time. Resolves
|
|
103
|
+
* `false` for a wrong password (or one over `maxPasswordBytes`); throws
|
|
104
|
+
* `TypeError` when `phc` is not an Argon2id v1.3 PHC string, since that is a
|
|
105
|
+
* storage bug rather than a failed login.
|
|
106
|
+
*/
|
|
107
|
+
declare function verifyPassword(phc: string, password: PasswordInput, options?: VerifyOptions): Promise<boolean>;
|
|
108
|
+
/**
|
|
109
|
+
* `true` when the stored hash should be recomputed on the next successful
|
|
110
|
+
* login: malformed, another Argon2 variant/version, or costs/tag length that
|
|
111
|
+
* differ from the target (`options`, default profile `owasp`).
|
|
112
|
+
*/
|
|
113
|
+
declare function needsRehash(phc: string, options?: RehashOptions): boolean;
|
|
114
|
+
|
|
115
|
+
export { MAX_MEMORY_COST, PROFILES, argon2idRaw, hashPassword, initPassword, needsRehash, parsePhc, verifyPassword };
|
|
116
|
+
export type { Argon2Params, HashOptions, ParsedPhc, PasswordInput, PasswordInputOptions, ProfileName, RawArgon2Input, RehashOptions, VerifyOptions, WasmSource };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
const PHC_PATTERN = /^\$argon2id\$v=19\$m=(\d{1,10}),t=(\d{1,10}),p=(\d{1,8})\$([A-Za-z0-9+/]{11,})\$([A-Za-z0-9+/]{6,})$/;
|
|
2
|
+
function encodeB64(bytes) {
|
|
3
|
+
let binary = "";
|
|
4
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
5
|
+
return btoa(binary).replace(/=+$/, "");
|
|
6
|
+
}
|
|
7
|
+
function decodeB64(text) {
|
|
8
|
+
if (text.length % 4 === 1) return void 0;
|
|
9
|
+
const binary = atob(text);
|
|
10
|
+
const bytes = new Uint8Array(binary.length);
|
|
11
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
12
|
+
return encodeB64(bytes) === text ? bytes : void 0;
|
|
13
|
+
}
|
|
14
|
+
function formatPhc(params, salt, hash) {
|
|
15
|
+
return `$argon2id$v=19$m=${params.memoryCost},t=${params.timeCost},p=${params.parallelism}$${encodeB64(salt)}$${encodeB64(hash)}`;
|
|
16
|
+
}
|
|
17
|
+
function parsePhc(phc) {
|
|
18
|
+
const match = PHC_PATTERN.exec(phc);
|
|
19
|
+
if (!match) return void 0;
|
|
20
|
+
const [, m = "", t = "", p = "", saltText = "", hashText = ""] = match;
|
|
21
|
+
const salt = decodeB64(saltText);
|
|
22
|
+
const hash = decodeB64(hashText);
|
|
23
|
+
if (!salt || !hash) return void 0;
|
|
24
|
+
return {
|
|
25
|
+
algorithm: "argon2id",
|
|
26
|
+
version: 19,
|
|
27
|
+
memoryCost: Number(m),
|
|
28
|
+
timeCost: Number(t),
|
|
29
|
+
parallelism: Number(p),
|
|
30
|
+
salt,
|
|
31
|
+
hash
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const STATUS_MESSAGES = {
|
|
36
|
+
1: "invalid Argon2id parameters",
|
|
37
|
+
2: "Argon2id hashing failed"
|
|
38
|
+
};
|
|
39
|
+
const MAX_MEMORY_COST = 1024 * 1024;
|
|
40
|
+
let instance;
|
|
41
|
+
function exportedFunction(exports, name) {
|
|
42
|
+
const value = exports[name];
|
|
43
|
+
if (typeof value !== "function") throw new TypeError(`@tupik/password: wasm export "${name}" is missing`);
|
|
44
|
+
return value;
|
|
45
|
+
}
|
|
46
|
+
function bindExports(instance2) {
|
|
47
|
+
const { exports } = instance2;
|
|
48
|
+
const memory = exports["memory"];
|
|
49
|
+
if (!(memory instanceof WebAssembly.Memory)) throw new TypeError("@tupik/password: wasm memory export is missing");
|
|
50
|
+
return {
|
|
51
|
+
memory,
|
|
52
|
+
alloc: exportedFunction(exports, "alloc"),
|
|
53
|
+
dealloc: exportedFunction(exports, "dealloc"),
|
|
54
|
+
argon2id_hash: exportedFunction(exports, "argon2id_hash")
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
async function readBundledWasm() {
|
|
58
|
+
const specifier = ["node", "fs/promises"].join(":");
|
|
59
|
+
const fs = await import(
|
|
60
|
+
/* @vite-ignore */
|
|
61
|
+
specifier
|
|
62
|
+
);
|
|
63
|
+
return fs.readFile(new URL("../wasm/argon2.wasm", import.meta.url));
|
|
64
|
+
}
|
|
65
|
+
async function instantiate(source) {
|
|
66
|
+
const resolved = source ?? await readBundledWasm();
|
|
67
|
+
if (resolved instanceof WebAssembly.Module) return bindExports(await WebAssembly.instantiate(resolved, {}));
|
|
68
|
+
const bytes = resolved instanceof Response ? await resolved.arrayBuffer() : resolved;
|
|
69
|
+
const { instance: created } = await WebAssembly.instantiate(bytes, {});
|
|
70
|
+
return bindExports(created);
|
|
71
|
+
}
|
|
72
|
+
function load(source) {
|
|
73
|
+
const next = instantiate(source);
|
|
74
|
+
instance = next;
|
|
75
|
+
next.catch(() => {
|
|
76
|
+
if (instance === next) instance = void 0;
|
|
77
|
+
});
|
|
78
|
+
return next;
|
|
79
|
+
}
|
|
80
|
+
async function initPassword(source) {
|
|
81
|
+
await load(source);
|
|
82
|
+
}
|
|
83
|
+
function checkParams(input) {
|
|
84
|
+
const { memoryCost, timeCost, parallelism, hashLength, salt } = input;
|
|
85
|
+
const ints = [
|
|
86
|
+
["parallelism", parallelism, 1, 16777215],
|
|
87
|
+
["timeCost", timeCost, 1, 4294967295],
|
|
88
|
+
["memoryCost", memoryCost, 8 * parallelism, MAX_MEMORY_COST],
|
|
89
|
+
["hashLength", hashLength, 4, 1024],
|
|
90
|
+
["salt length", salt.length, 8, 1024]
|
|
91
|
+
];
|
|
92
|
+
for (const [name, value, min, max] of ints) {
|
|
93
|
+
if (!Number.isInteger(value) || value < min || value > max) {
|
|
94
|
+
throw new RangeError(`@tupik/password: ${name} must be an integer in [${min}, ${max}], got ${value}`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
async function argon2idRaw(input) {
|
|
99
|
+
checkParams(input);
|
|
100
|
+
const pending = instance ?? load(void 0);
|
|
101
|
+
const wasm = await pending;
|
|
102
|
+
const buffers = [];
|
|
103
|
+
const put = (bytes) => {
|
|
104
|
+
if (!bytes || bytes.length === 0) return [0, 0];
|
|
105
|
+
const ptr = wasm.alloc(bytes.length);
|
|
106
|
+
if (ptr === 0) throw new RangeError("@tupik/password: wasm allocation failed");
|
|
107
|
+
buffers.push([ptr, bytes.length]);
|
|
108
|
+
new Uint8Array(wasm.memory.buffer, ptr, bytes.length).set(bytes);
|
|
109
|
+
return [ptr, bytes.length];
|
|
110
|
+
};
|
|
111
|
+
let trapped = false;
|
|
112
|
+
try {
|
|
113
|
+
const password = put(input.password);
|
|
114
|
+
const salt = put(input.salt);
|
|
115
|
+
const secret = put(input.secret);
|
|
116
|
+
const ad = put(input.associatedData);
|
|
117
|
+
const out = wasm.alloc(input.hashLength);
|
|
118
|
+
if (out === 0) throw new RangeError("@tupik/password: wasm allocation failed");
|
|
119
|
+
buffers.push([out, input.hashLength]);
|
|
120
|
+
let status;
|
|
121
|
+
try {
|
|
122
|
+
status = wasm.argon2id_hash(...password, ...salt, ...secret, ...ad, input.memoryCost, input.timeCost, input.parallelism, out, input.hashLength);
|
|
123
|
+
} catch (error) {
|
|
124
|
+
trapped = true;
|
|
125
|
+
throw error;
|
|
126
|
+
}
|
|
127
|
+
if (status !== 0) throw new RangeError(`@tupik/password: ${STATUS_MESSAGES[status] ?? `status ${status}`}`);
|
|
128
|
+
return new Uint8Array(wasm.memory.buffer, out, input.hashLength).slice();
|
|
129
|
+
} finally {
|
|
130
|
+
if (trapped) {
|
|
131
|
+
if (instance === pending) instance = void 0;
|
|
132
|
+
} else {
|
|
133
|
+
for (const [ptr, len] of buffers) {
|
|
134
|
+
new Uint8Array(wasm.memory.buffer, ptr, len).fill(0);
|
|
135
|
+
wasm.dealloc(ptr, len);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const PROFILES = {
|
|
142
|
+
owasp: { memoryCost: 19456, timeCost: 2, parallelism: 1 },
|
|
143
|
+
light: { memoryCost: 4096, timeCost: 1, parallelism: 1 }
|
|
144
|
+
};
|
|
145
|
+
const DEFAULT_HASH_LENGTH = 32;
|
|
146
|
+
const DEFAULT_SALT_LENGTH = 16;
|
|
147
|
+
const DEFAULT_MAX_PASSWORD_BYTES = 1024;
|
|
148
|
+
const encoder = new TextEncoder();
|
|
149
|
+
function encodeInput(input, normalize) {
|
|
150
|
+
if (typeof input !== "string") return input;
|
|
151
|
+
return encoder.encode(normalize === "NFC" ? input.normalize("NFC") : input);
|
|
152
|
+
}
|
|
153
|
+
function passwordBytes(password, options) {
|
|
154
|
+
const bytes = encodeInput(password, options.normalize);
|
|
155
|
+
return bytes.length > (options.maxPasswordBytes ?? DEFAULT_MAX_PASSWORD_BYTES) ? void 0 : bytes;
|
|
156
|
+
}
|
|
157
|
+
function secretBytes(options) {
|
|
158
|
+
return options.secret === void 0 ? void 0 : encodeInput(options.secret, false);
|
|
159
|
+
}
|
|
160
|
+
function targetParams(options) {
|
|
161
|
+
const base = PROFILES[options.profile ?? "owasp"];
|
|
162
|
+
return {
|
|
163
|
+
memoryCost: options.memoryCost ?? base.memoryCost,
|
|
164
|
+
timeCost: options.timeCost ?? base.timeCost,
|
|
165
|
+
parallelism: options.parallelism ?? base.parallelism,
|
|
166
|
+
hashLength: options.hashLength ?? DEFAULT_HASH_LENGTH
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
function timingSafeEqual(a, b) {
|
|
170
|
+
if (a.length !== b.length) return false;
|
|
171
|
+
let diff = 0;
|
|
172
|
+
for (let i = 0; i < a.length; i++) diff |= (a[i] ?? 0) ^ (b[i] ?? 0);
|
|
173
|
+
return diff === 0;
|
|
174
|
+
}
|
|
175
|
+
async function hashPassword(password, options = {}) {
|
|
176
|
+
const bytes = passwordBytes(password, options);
|
|
177
|
+
if (!bytes) {
|
|
178
|
+
throw new RangeError(`@tupik/password: password longer than ${options.maxPasswordBytes ?? DEFAULT_MAX_PASSWORD_BYTES} bytes`);
|
|
179
|
+
}
|
|
180
|
+
const params = targetParams(options);
|
|
181
|
+
const salt = crypto.getRandomValues(new Uint8Array(options.saltLength ?? DEFAULT_SALT_LENGTH));
|
|
182
|
+
const secret = secretBytes(options);
|
|
183
|
+
const hash = await argon2idRaw({ ...params, password: bytes, salt, ...secret ? { secret } : {} });
|
|
184
|
+
return formatPhc(params, salt, hash);
|
|
185
|
+
}
|
|
186
|
+
async function verifyPassword(phc, password, options = {}) {
|
|
187
|
+
const parsed = parsePhc(phc);
|
|
188
|
+
if (!parsed) throw new TypeError("@tupik/password: not an Argon2id v1.3 PHC string");
|
|
189
|
+
const bytes = passwordBytes(password, options);
|
|
190
|
+
if (!bytes) return false;
|
|
191
|
+
const secret = secretBytes(options);
|
|
192
|
+
const computed = await argon2idRaw({
|
|
193
|
+
memoryCost: parsed.memoryCost,
|
|
194
|
+
timeCost: parsed.timeCost,
|
|
195
|
+
parallelism: parsed.parallelism,
|
|
196
|
+
hashLength: parsed.hash.length,
|
|
197
|
+
password: bytes,
|
|
198
|
+
salt: parsed.salt,
|
|
199
|
+
...secret ? { secret } : {}
|
|
200
|
+
});
|
|
201
|
+
return timingSafeEqual(computed, parsed.hash);
|
|
202
|
+
}
|
|
203
|
+
function needsRehash(phc, options = {}) {
|
|
204
|
+
const parsed = parsePhc(phc);
|
|
205
|
+
if (!parsed) return true;
|
|
206
|
+
const target = targetParams(options);
|
|
207
|
+
return parsed.memoryCost !== target.memoryCost || parsed.timeCost !== target.timeCost || parsed.parallelism !== target.parallelism || parsed.hash.length !== target.hashLength;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
export { MAX_MEMORY_COST, PROFILES, argon2idRaw, hashPassword, initPassword, needsRehash, parsePhc, verifyPassword };
|
package/package.json
CHANGED
|
@@ -1,6 +1,64 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tupik/password",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Argon2id password hashing for Tupik, compiled from Rust to WebAssembly: PHC strings, constant-time verify and needsRehash on Workers, Node.js and Bun.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"tupik",
|
|
8
|
+
"argon2",
|
|
9
|
+
"argon2id",
|
|
10
|
+
"password",
|
|
11
|
+
"hash",
|
|
12
|
+
"wasm",
|
|
13
|
+
"cloudflare-workers"
|
|
14
|
+
],
|
|
15
|
+
"homepage": "https://github.com/CodeHamper/tupikjs/tree/main/packages/password#readme",
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "https://github.com/CodeHamper/tupikjs.git",
|
|
19
|
+
"directory": "packages/password"
|
|
20
|
+
},
|
|
21
|
+
"bugs": {
|
|
22
|
+
"url": "https://github.com/CodeHamper/tupikjs/issues"
|
|
23
|
+
},
|
|
24
|
+
"type": "module",
|
|
25
|
+
"sideEffects": [
|
|
26
|
+
"./workers.mjs"
|
|
27
|
+
],
|
|
28
|
+
"publishConfig": {
|
|
29
|
+
"access": "public"
|
|
30
|
+
},
|
|
31
|
+
"files": [
|
|
32
|
+
"dist",
|
|
33
|
+
"wasm",
|
|
34
|
+
"workers.mjs",
|
|
35
|
+
"workers.d.ts"
|
|
36
|
+
],
|
|
37
|
+
"exports": {
|
|
38
|
+
".": {
|
|
39
|
+
"types": "./dist/index.d.ts",
|
|
40
|
+
"import": "./dist/index.mjs"
|
|
41
|
+
},
|
|
42
|
+
"./workers": {
|
|
43
|
+
"types": "./workers.d.ts",
|
|
44
|
+
"import": "./workers.mjs"
|
|
45
|
+
},
|
|
46
|
+
"./argon2.wasm": "./wasm/argon2.wasm"
|
|
47
|
+
},
|
|
48
|
+
"engines": {
|
|
49
|
+
"node": ">=22.12"
|
|
50
|
+
},
|
|
51
|
+
"dependencies": {},
|
|
52
|
+
"devDependencies": {
|
|
53
|
+
"@node-rs/argon2": "^2.0.2",
|
|
54
|
+
"typescript": "^5.6.0",
|
|
55
|
+
"unbuild": "^3.0.0",
|
|
56
|
+
"vitest": "^2.1.0"
|
|
57
|
+
},
|
|
58
|
+
"scripts": {
|
|
59
|
+
"build": "unbuild",
|
|
60
|
+
"build:wasm": "node scripts/build-wasm.mjs",
|
|
61
|
+
"typecheck": "tsc --noEmit",
|
|
62
|
+
"test": "vitest run"
|
|
63
|
+
}
|
|
6
64
|
}
|
package/wasm/argon2.wasm
ADDED
|
Binary file
|
package/workers.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './dist/index.js';
|
package/workers.mjs
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Cloudflare Workers entry: Wrangler bundles `.wasm` imports as a compiled
|
|
2
|
+
// `WebAssembly.Module` (Workers cannot compile wasm from bytes at runtime).
|
|
3
|
+
// `initPassword` registers the instance synchronously; the first hash awaits it.
|
|
4
|
+
import wasm from './wasm/argon2.wasm';
|
|
5
|
+
import { initPassword } from './dist/index.mjs';
|
|
6
|
+
|
|
7
|
+
initPassword(wasm).catch((error) => console.error('@tupik/password: wasm init failed', error));
|
|
8
|
+
|
|
9
|
+
export * from './dist/index.mjs';
|