@push.rocks/smartcrypto 3.0.0 → 3.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.
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Argon2id password hashing in the PHC string format, on `node:crypto.argon2`
3
+ * (Node.js 24.7.0 or later; checked at call time, not declared in `engines`).
4
+ *
5
+ * Only Argon2id version 19 (0x13) is read and written, the one variant and
6
+ * version `node:crypto.argon2` computes that the stored verifiers use. The
7
+ * limits are the PHC string format's Argon2 limits (C2SP phc-strings).
8
+ */
9
+ /** The decoded fields of an Argon2id PHC string. */
10
+ export interface IArgon2idPhc {
11
+ /** Argon2 version; always 19 (0x13). */
12
+ version: 19;
13
+ /** Memory cost `m` in KiB. */
14
+ memoryCost: number;
15
+ /** Number of passes `t`. */
16
+ timeCost: number;
17
+ /** Degree of parallelism (lanes) `p`. */
18
+ parallelism: number;
19
+ /** Salt, 8 to 48 bytes. */
20
+ salt: Uint8Array;
21
+ /** Digest (Argon2 tag), 12 to 64 bytes. */
22
+ digest: Uint8Array;
23
+ }
24
+ /** Cost and length options of `hashArgon2id()`; omitted fields use `argon2idDefaultOptions`. */
25
+ export interface IArgon2idHashOptions {
26
+ /** Memory cost in KiB, at least `8 * parallelism` and at most 2^32-1. */
27
+ memoryCost?: number;
28
+ /** Number of passes, 1 to 2^32-1. */
29
+ timeCost?: number;
30
+ /** Degree of parallelism, 1 to 255. */
31
+ parallelism?: number;
32
+ /** Random salt length in bytes, 8 to 48. */
33
+ saltLength?: number;
34
+ /** Digest length in bytes, 12 to 64. */
35
+ hashLength?: number;
36
+ }
37
+ /** The defaults: the cost and lengths of the stored CoreMail credential verifiers. */
38
+ export declare const argon2idDefaultOptions: Readonly<Required<IArgon2idHashOptions>>;
39
+ /**
40
+ * Upper bounds on the cost `verifyArgon2id()` accepts from a hash; omitted
41
+ * fields use `argon2idDefaultVerifyLimits`. The hash sets the cost of its own
42
+ * verification, so the limits keep an untrusted or corrupted hash from costing
43
+ * unbounded memory or CPU.
44
+ */
45
+ export interface IArgon2idVerifyLimits {
46
+ /** Largest accepted memory cost `m` in KiB, 8 to 2^32-1. */
47
+ maxMemoryCost?: number;
48
+ /** Largest accepted number of passes `t`, 1 to 2^32-1. */
49
+ maxTimeCost?: number;
50
+ /** Largest accepted parallelism `p`, 1 to 255. */
51
+ maxParallelism?: number;
52
+ }
53
+ /** The default verify limits: 1 GiB of memory, 10 passes, 16 lanes. */
54
+ export declare const argon2idDefaultVerifyLimits: Readonly<Required<IArgon2idVerifyLimits>>;
55
+ /**
56
+ * Parses an Argon2id PHC string, `$argon2id$v=19$m=<kib>,t=<passes>,p=<lanes>$<salt>$<digest>`.
57
+ *
58
+ * Reads the parameter orders `m,t,p` and `m,p,t`; rejects other variants and
59
+ * versions (`UNSUPPORTED_PROFILE`, `UNSUPPORTED_VERSION`) and every other
60
+ * deviation (`INVALID_PASSWORD_HASH`): unknown, duplicate, missing or
61
+ * out-of-range parameters, padded, non-canonical or invalid base64, and
62
+ * salt or digest lengths outside 8 to 48 and 12 to 64 bytes.
63
+ */
64
+ export declare const parseArgon2idPhc: (phcArg: string) => IArgon2idPhc;
65
+ /** Encodes Argon2id fields as a PHC string in the canonical `m,t,p` order. */
66
+ export declare const encodeArgon2idPhc: (phcArg: IArgon2idPhc) => string;
67
+ /**
68
+ * Hashes a password with Argon2id and returns the PHC string
69
+ * `$argon2id$v=19$m=<kib>,t=<passes>,p=<lanes>$<salt>$<digest>` (base64 without padding).
70
+ * The salt is random; omitted options use `argon2idDefaultOptions`.
71
+ */
72
+ export declare const hashArgon2id: (passwordArg: string | Uint8Array, optionsArg?: IArgon2idHashOptions) => Promise<string>;
73
+ /**
74
+ * Verifies a password against an Argon2id PHC string. Resolves `false` for a
75
+ * wrong password; rejects with `SmartCryptoError` for a hash `parseArgon2idPhc()`
76
+ * refuses, and with `INVALID_PASSWORD_HASH` before any hashing for a hash whose
77
+ * cost exceeds the limits (`argon2idDefaultVerifyLimits` by default). The
78
+ * digests are compared in constant time.
79
+ */
80
+ export declare const verifyArgon2id: (phcArg: string, passwordArg: string | Uint8Array, limitsArg?: IArgon2idVerifyLimits) => Promise<boolean>;
@@ -0,0 +1,265 @@
1
+ import * as plugins from './smartcrypto.plugins.js';
2
+ import { createSmartCryptoError } from '../dist_ts/smartcrypto.errors.js';
3
+ /** The defaults: the cost and lengths of the stored CoreMail credential verifiers. */
4
+ export const argon2idDefaultOptions = Object.freeze({
5
+ memoryCost: 65_536,
6
+ timeCost: 3,
7
+ parallelism: 1,
8
+ saltLength: 16,
9
+ hashLength: 32,
10
+ });
11
+ /** The default verify limits: 1 GiB of memory, 10 passes, 16 lanes. */
12
+ export const argon2idDefaultVerifyLimits = Object.freeze({
13
+ maxMemoryCost: 1_048_576,
14
+ maxTimeCost: 10,
15
+ maxParallelism: 16,
16
+ });
17
+ const argon2idVersion = 19;
18
+ const maximumUint32 = 2 ** 32 - 1;
19
+ const maximumParallelism = 255;
20
+ const saltLengthRange = { minimum: 8, maximum: 48 };
21
+ const digestLengthRange = { minimum: 12, maximum: 64 };
22
+ /** The longest valid string: `$argon2id$v=19$m=<10>,t=<10>,p=<3>$<64>$<86>` is 198 characters. */
23
+ const maximumPhcLength = 256;
24
+ const decimalPattern = /^(?:0|[1-9][0-9]*)$/;
25
+ const b64Pattern = /^[A-Za-z0-9+/]+$/;
26
+ /** The parameter orders read: `m,t,p` (PHC order) and `m,p,t` (written by the `argon2` npm package). */
27
+ const acceptedParameterOrders = ['m,t,p', 'm,p,t'];
28
+ const invalidHash = (detailArg) => createSmartCryptoError('INVALID_PASSWORD_HASH', detailArg);
29
+ const requireInteger = (valueArg, minimumArg, maximumArg, detailArg) => {
30
+ if (typeof valueArg !== 'number'
31
+ || !Number.isInteger(valueArg)
32
+ || valueArg < minimumArg
33
+ || valueArg > maximumArg) {
34
+ throw createSmartCryptoError('INVALID_ARGUMENT', detailArg);
35
+ }
36
+ return valueArg;
37
+ };
38
+ /** Validates the cost parameters shared by encoding and hashing. */
39
+ const requireCost = (memoryCostArg, timeCostArg, parallelismArg) => {
40
+ const parallelism = requireInteger(parallelismArg, 1, maximumParallelism, 'parallelism must be an integer from 1 to 255');
41
+ const memoryCost = requireInteger(memoryCostArg, 8 * parallelism, maximumUint32, 'memoryCost must be an integer from 8 * parallelism to 2^32-1');
42
+ const timeCost = requireInteger(timeCostArg, 1, maximumUint32, 'timeCost must be an integer from 1 to 2^32-1');
43
+ return { memoryCost, timeCost, parallelism };
44
+ };
45
+ const requireBytes = (valueArg, rangeArg, detailArg) => {
46
+ if (!(valueArg instanceof Uint8Array)
47
+ || valueArg.byteLength < rangeArg.minimum
48
+ || valueArg.byteLength > rangeArg.maximum) {
49
+ throw createSmartCryptoError('INVALID_ARGUMENT', detailArg);
50
+ }
51
+ return valueArg;
52
+ };
53
+ const encodeB64 = (valueArg) => Buffer.from(valueArg.buffer, valueArg.byteOffset, valueArg.byteLength)
54
+ .toString('base64')
55
+ .replace(/=+$/, '');
56
+ /** Decodes canonical B64: standard alphabet, no padding, zero trailing bits. */
57
+ const decodeB64 = (valueArg, rangeArg, fieldArg) => {
58
+ if (valueArg.includes('=')) {
59
+ throw invalidHash(`${fieldArg} must be base64 without padding`);
60
+ }
61
+ if (!b64Pattern.test(valueArg) || valueArg.length % 4 === 1) {
62
+ throw invalidHash(`${fieldArg} must be standard base64`);
63
+ }
64
+ const decoded = new Uint8Array(Buffer.from(valueArg, 'base64'));
65
+ if (encodeB64(decoded) !== valueArg) {
66
+ throw invalidHash(`${fieldArg} must be canonical base64`);
67
+ }
68
+ if (decoded.byteLength < rangeArg.minimum || decoded.byteLength > rangeArg.maximum) {
69
+ throw invalidHash(`${fieldArg} must be ${rangeArg.minimum} to ${rangeArg.maximum} bytes`);
70
+ }
71
+ return decoded;
72
+ };
73
+ const parseDecimal = (valueArg, nameArg) => {
74
+ const maximumDigits = nameArg === 'p' ? 3 : 10;
75
+ if (!decimalPattern.test(valueArg) || valueArg.length > maximumDigits) {
76
+ throw invalidHash(`parameter ${nameArg} must be a decimal integer without sign or leading zeros`);
77
+ }
78
+ return Number(valueArg);
79
+ };
80
+ /** Reads the `m`, `t` and `p` parameters, each exactly once, in an accepted order. */
81
+ const parseParameters = (blockArg) => {
82
+ const values = new Map();
83
+ const names = [];
84
+ for (const entry of blockArg.split(',')) {
85
+ const separatorIndex = entry.indexOf('=');
86
+ if (separatorIndex < 1) {
87
+ throw invalidHash('parameters must be name=value pairs');
88
+ }
89
+ const name = entry.slice(0, separatorIndex);
90
+ if (name !== 'm' && name !== 't' && name !== 'p') {
91
+ throw invalidHash('only the parameters m, t and p are supported');
92
+ }
93
+ if (values.has(name)) {
94
+ throw invalidHash(`parameter ${name} must appear once`);
95
+ }
96
+ values.set(name, parseDecimal(entry.slice(separatorIndex + 1), name));
97
+ names.push(name);
98
+ }
99
+ const memoryCost = values.get('m');
100
+ const timeCost = values.get('t');
101
+ const parallelism = values.get('p');
102
+ if (memoryCost === undefined || timeCost === undefined || parallelism === undefined) {
103
+ throw invalidHash('parameters m, t and p are required');
104
+ }
105
+ if (!acceptedParameterOrders.includes(names.join(','))) {
106
+ throw invalidHash('parameters must appear in the order m,t,p or m,p,t');
107
+ }
108
+ if (parallelism < 1 || parallelism > maximumParallelism) {
109
+ throw invalidHash('parameter p must be from 1 to 255');
110
+ }
111
+ if (memoryCost < 8 * parallelism || memoryCost > maximumUint32) {
112
+ throw invalidHash('parameter m must be from 8 * p to 2^32-1');
113
+ }
114
+ if (timeCost < 1 || timeCost > maximumUint32) {
115
+ throw invalidHash('parameter t must be from 1 to 2^32-1');
116
+ }
117
+ return { memoryCost, timeCost, parallelism };
118
+ };
119
+ /**
120
+ * Parses an Argon2id PHC string, `$argon2id$v=19$m=<kib>,t=<passes>,p=<lanes>$<salt>$<digest>`.
121
+ *
122
+ * Reads the parameter orders `m,t,p` and `m,p,t`; rejects other variants and
123
+ * versions (`UNSUPPORTED_PROFILE`, `UNSUPPORTED_VERSION`) and every other
124
+ * deviation (`INVALID_PASSWORD_HASH`): unknown, duplicate, missing or
125
+ * out-of-range parameters, padded, non-canonical or invalid base64, and
126
+ * salt or digest lengths outside 8 to 48 and 12 to 64 bytes.
127
+ */
128
+ export const parseArgon2idPhc = (phcArg) => {
129
+ if (typeof phcArg !== 'string') {
130
+ throw createSmartCryptoError('INVALID_ARGUMENT', 'the hash must be a string');
131
+ }
132
+ if (phcArg.length > maximumPhcLength) {
133
+ throw invalidHash(`the hash must not exceed ${maximumPhcLength} characters`);
134
+ }
135
+ const fields = phcArg.split('$');
136
+ if (fields[0] !== '' || fields.length < 2) {
137
+ throw invalidHash('the hash must be a PHC string starting with $');
138
+ }
139
+ const variant = fields[1];
140
+ if (!/^[a-z0-9-]{1,32}$/.test(variant)) {
141
+ throw invalidHash('the hash must start with a PHC function identifier');
142
+ }
143
+ if (variant !== 'argon2id') {
144
+ throw createSmartCryptoError('UNSUPPORTED_PROFILE', 'only argon2id is supported');
145
+ }
146
+ if (fields.length !== 6) {
147
+ throw invalidHash('the hash must carry version, parameters, salt and digest');
148
+ }
149
+ const [, , versionField, parameterField, saltField, digestField] = fields;
150
+ if (!versionField.startsWith('v=')) {
151
+ throw invalidHash('the hash must carry the version field v=19');
152
+ }
153
+ if (versionField !== `v=${argon2idVersion}`) {
154
+ throw createSmartCryptoError('UNSUPPORTED_VERSION', 'only argon2 version 19 is supported');
155
+ }
156
+ const cost = parseParameters(parameterField);
157
+ return {
158
+ version: argon2idVersion,
159
+ ...cost,
160
+ salt: decodeB64(saltField, saltLengthRange, 'salt'),
161
+ digest: decodeB64(digestField, digestLengthRange, 'digest'),
162
+ };
163
+ };
164
+ /** Encodes Argon2id fields as a PHC string in the canonical `m,t,p` order. */
165
+ export const encodeArgon2idPhc = (phcArg) => {
166
+ if (phcArg?.version !== argon2idVersion) {
167
+ throw createSmartCryptoError('UNSUPPORTED_VERSION', 'only argon2 version 19 is supported');
168
+ }
169
+ const { memoryCost, timeCost, parallelism } = requireCost(phcArg.memoryCost, phcArg.timeCost, phcArg.parallelism);
170
+ const salt = requireBytes(phcArg.salt, saltLengthRange, 'salt must be 8 to 48 bytes');
171
+ const digest = requireBytes(phcArg.digest, digestLengthRange, 'digest must be 12 to 64 bytes');
172
+ return `$argon2id$v=${argon2idVersion}$m=${memoryCost},t=${timeCost},p=${parallelism}`
173
+ + `$${encodeB64(salt)}$${encodeB64(digest)}`;
174
+ };
175
+ /** Passwords are strings, hashed as UTF-8, or bytes. */
176
+ const requirePassword = (passwordArg) => {
177
+ if (typeof passwordArg === 'string') {
178
+ return Buffer.from(passwordArg, 'utf8');
179
+ }
180
+ if (passwordArg instanceof Uint8Array) {
181
+ return passwordArg;
182
+ }
183
+ throw createSmartCryptoError('INVALID_ARGUMENT', 'the password must be a string or a Uint8Array');
184
+ };
185
+ /** Runs `node:crypto.argon2` (Argon2id, version 0x13) as a promise. */
186
+ const deriveArgon2id = (passwordArg, costArg, saltArg, tagLengthArg) => {
187
+ if (typeof plugins.crypto.argon2 !== 'function') {
188
+ return Promise.reject(createSmartCryptoError('CRYPTO_OPERATION_FAILED', 'Argon2id requires Node.js ≥24.7.0 crypto.argon2, which this runtime lacks'));
189
+ }
190
+ return new Promise((resolve, reject) => {
191
+ try {
192
+ plugins.crypto.argon2('argon2id', {
193
+ message: passwordArg,
194
+ nonce: saltArg,
195
+ parallelism: costArg.parallelism,
196
+ tagLength: tagLengthArg,
197
+ memory: costArg.memoryCost,
198
+ passes: costArg.timeCost,
199
+ }, (errorArg, derivedKeyArg) => {
200
+ if (errorArg) {
201
+ reject(argon2Failure(errorArg));
202
+ return;
203
+ }
204
+ resolve(derivedKeyArg);
205
+ });
206
+ }
207
+ catch (error) {
208
+ reject(argon2Failure(error));
209
+ }
210
+ });
211
+ };
212
+ /** Maps a `node:crypto` failure to an error without its details; only a missing Argon2 is named. */
213
+ const argon2Failure = (errorArg) => createSmartCryptoError('CRYPTO_OPERATION_FAILED', errorArg instanceof Error
214
+ && 'code' in errorArg
215
+ && errorArg.code === 'ERR_CRYPTO_ARGON2_NOT_SUPPORTED'
216
+ ? 'the OpenSSL of this Node.js does not support Argon2'
217
+ : 'Argon2id derivation failed');
218
+ /**
219
+ * Hashes a password with Argon2id and returns the PHC string
220
+ * `$argon2id$v=19$m=<kib>,t=<passes>,p=<lanes>$<salt>$<digest>` (base64 without padding).
221
+ * The salt is random; omitted options use `argon2idDefaultOptions`.
222
+ */
223
+ export const hashArgon2id = async (passwordArg, optionsArg = {}) => {
224
+ const password = requirePassword(passwordArg);
225
+ const options = { ...argon2idDefaultOptions, ...optionsArg };
226
+ const cost = requireCost(options.memoryCost, options.timeCost, options.parallelism);
227
+ const saltLength = requireInteger(options.saltLength, saltLengthRange.minimum, saltLengthRange.maximum, 'saltLength must be an integer from 8 to 48');
228
+ const hashLength = requireInteger(options.hashLength, digestLengthRange.minimum, digestLengthRange.maximum, 'hashLength must be an integer from 12 to 64');
229
+ const salt = new Uint8Array(plugins.crypto.randomBytes(saltLength));
230
+ const digest = await deriveArgon2id(password, cost, salt, hashLength);
231
+ return encodeArgon2idPhc({ version: argon2idVersion, ...cost, salt, digest });
232
+ };
233
+ /** Validates verify limits against the PHC parameter ranges. */
234
+ const requireVerifyLimits = (limitsArg) => {
235
+ const limits = { ...argon2idDefaultVerifyLimits, ...limitsArg };
236
+ return {
237
+ maxMemoryCost: requireInteger(limits.maxMemoryCost, 8, maximumUint32, 'maxMemoryCost must be an integer from 8 to 2^32-1'),
238
+ maxTimeCost: requireInteger(limits.maxTimeCost, 1, maximumUint32, 'maxTimeCost must be an integer from 1 to 2^32-1'),
239
+ maxParallelism: requireInteger(limits.maxParallelism, 1, maximumParallelism, 'maxParallelism must be an integer from 1 to 255'),
240
+ };
241
+ };
242
+ /**
243
+ * Verifies a password against an Argon2id PHC string. Resolves `false` for a
244
+ * wrong password; rejects with `SmartCryptoError` for a hash `parseArgon2idPhc()`
245
+ * refuses, and with `INVALID_PASSWORD_HASH` before any hashing for a hash whose
246
+ * cost exceeds the limits (`argon2idDefaultVerifyLimits` by default). The
247
+ * digests are compared in constant time.
248
+ */
249
+ export const verifyArgon2id = async (phcArg, passwordArg, limitsArg = {}) => {
250
+ const limits = requireVerifyLimits(limitsArg);
251
+ const phc = parseArgon2idPhc(phcArg);
252
+ const password = requirePassword(passwordArg);
253
+ if (phc.memoryCost > limits.maxMemoryCost) {
254
+ throw invalidHash('parameter m exceeds the maxMemoryCost limit');
255
+ }
256
+ if (phc.timeCost > limits.maxTimeCost) {
257
+ throw invalidHash('parameter t exceeds the maxTimeCost limit');
258
+ }
259
+ if (phc.parallelism > limits.maxParallelism) {
260
+ throw invalidHash('parameter p exceeds the maxParallelism limit');
261
+ }
262
+ const computed = await deriveArgon2id(password, phc, phc.salt, phc.digest.byteLength);
263
+ return plugins.crypto.timingSafeEqual(computed, phc.digest);
264
+ };
265
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic21hcnRjcnlwdG8uYXJnb24yLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vdHNfbm9kZS9zbWFydGNyeXB0by5hcmdvbjIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsT0FBTyxLQUFLLE9BQU8sTUFBTSwwQkFBMEIsQ0FBQztBQUNwRCxPQUFPLEVBQUUsc0JBQXNCLEVBQUUsTUFBTSw2QkFBNkIsQ0FBQztBQXlDckUsc0ZBQXNGO0FBQ3RGLE1BQU0sQ0FBQyxNQUFNLHNCQUFzQixHQUE2QyxNQUFNLENBQUMsTUFBTSxDQUFDO0lBQzVGLFVBQVUsRUFBRSxNQUFNO0lBQ2xCLFFBQVEsRUFBRSxDQUFDO0lBQ1gsV0FBVyxFQUFFLENBQUM7SUFDZCxVQUFVLEVBQUUsRUFBRTtJQUNkLFVBQVUsRUFBRSxFQUFFO0NBQ2YsQ0FBQyxDQUFDO0FBaUJILHVFQUF1RTtBQUN2RSxNQUFNLENBQUMsTUFBTSwyQkFBMkIs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FDO0lBQ0QsSUFBSSxHQUFHLENBQUMsUUFBUSxHQUFHLE1BQU0sQ0FBQyxXQUFXLEVBQUUsQ0FBQztRQUN0QyxNQUFNLFdBQVcsQ0FBQywyQ0FBMkMsQ0FBQyxDQUFDO0lBQ2pFLENBQUM7SUFDRCxJQUFJLEdBQUcsQ0FBQyxXQUFXLEdBQUcsTUFBTSxDQUFDLGNBQWMsRUFBRSxDQUFDO1FBQzVDLE1BQU0sV0FBVyxDQUFDLDhDQUE4QyxDQUFDLENBQUM7SUFDcEUsQ0FBQztJQUNELE1BQU0sUUFBUSxHQUFHLE1BQU0sY0FBYyxDQUFDLFFBQVEsRUFBRSxHQUFHLEVBQUUsR0FBRyxDQUFDLElBQUksRUFBRSxHQUFHLENBQUMsTUFBTSxDQUFDLFVBQVUsQ0FBQyxDQUFDO0lBQ3RGLE9BQU8sT0FBTyxDQUFDLE1BQU0sQ0FBQyxlQUFlLENBQUMsUUFBUSxFQUFFLEdBQUcsQ0FBQyxNQUFNLENBQUMsQ0FBQztBQUM5RCxDQUFDLENBQUMifQ==
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@push.rocks/smartcrypto",
3
- "version": "3.0.0",
3
+ "version": "3.2.0",
4
4
  "private": false,
5
5
  "description": "A library providing easy methods for cryptographic operations, including key pair generation.",
6
6
  "main": "dist_ts/index.js",
@@ -13,10 +13,11 @@
13
13
  "author": "Task Venture Capital GmbH",
14
14
  "license": "MIT",
15
15
  "devDependencies": {
16
- "@git.zone/tsbuild": "^5.1.0",
17
- "@git.zone/tsrun": "^3.0.2",
18
- "@git.zone/tstest": "^6.3.2",
19
- "@types/node": "^26.6.2"
16
+ "@git.zone/tsbuild": "^6.0.2",
17
+ "@git.zone/tsrun": "^3.0.3",
18
+ "@git.zone/tstest": "^8.0.0",
19
+ "@types/node": "^26.6.4",
20
+ "argon2": "^0.45.1"
20
21
  },
21
22
  "dependencies": {},
22
23
  "files": [
package/readme.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @push.rocks/smartcrypto
2
2
 
3
- Cross-runtime cryptographic primitives for Node.js and browsers, including strict X25519 envelopes, AES-256-GCM authenticated encryption, DEK wrapping, SHA-256 hashing, and RSA keys, all on the platform's WebCrypto without third-party runtime dependencies.
3
+ Cross-runtime cryptographic primitives for Node.js and browsers, including strict X25519 envelopes, AES-256-GCM authenticated encryption, DEK wrapping, SHA-256 hashing, RSA keys, and self-signed X.509 certificates, all on the platform's WebCrypto without third-party runtime dependencies, plus Argon2id password hashing on Node.js.
4
4
 
5
5
  ## Issue Reporting and Security
6
6
 
@@ -159,7 +159,7 @@ esbuild does not tree-shake a namespace that is re-exported and then read throug
159
159
 
160
160
  ### Node.js Entry
161
161
 
162
- `@push.rocks/smartcrypto/node` exports the same hashing functions backed by `node:crypto`, plus file and MD5 hashing. It runs in Node.js and Deno.
162
+ `@push.rocks/smartcrypto/node` exports the same hashing functions backed by `node:crypto`, plus file and MD5 hashing. It runs in Node.js.
163
163
 
164
164
  ```typescript
165
165
  import {
@@ -188,9 +188,45 @@ const checksum = await md5FromString('legacy payload');
188
188
  | `sha256FromFile(path)` | - | yes |
189
189
  | `md5FromString(string)` | - | yes |
190
190
 
191
+ ## Argon2id Password Hashing
192
+
193
+ `@push.rocks/smartcrypto/node` hashes and verifies passwords with Argon2id in the PHC string format, on Node.js's built-in `node:crypto.argon2` (no native addon). These functions require Node.js 24.7.0 or later; the package declares no `engines` for them, because the rest of the package runs on older Node.js and in browsers. Hashes are byte-compatible with the `argon2` npm package in both directions.
194
+
195
+ ```typescript
196
+ import {
197
+ encodeArgon2idPhc,
198
+ hashArgon2id,
199
+ parseArgon2idPhc,
200
+ verifyArgon2id,
201
+ } from '@push.rocks/smartcrypto/node';
202
+
203
+ const verifier = await hashArgon2id(secret);
204
+ // '$argon2id$v=19$m=65536,t=3,p=1$<16-byte salt>$<32-byte digest>'
205
+ const matches = await verifyArgon2id(verifier, secret); // true or false
206
+ // Admit a costlier stored hash by raising a limit.
207
+ const legacyMatches = await verifyArgon2id(legacyVerifier, secret, { maxMemoryCost: 2_097_152 });
208
+
209
+ // Read an `argon2` npm hash (parameters m,p,t) and re-emit it in the canonical m,t,p order.
210
+ const canonical = encodeArgon2idPhc(parseArgon2idPhc(argon2NpmHash));
211
+ ```
212
+
213
+ - `hashArgon2id(password, options?)` draws a random salt and returns `$argon2id$v=19$m=<KiB>,t=<passes>,p=<lanes>$<salt>$<digest>`, salt and digest in standard base64 without padding. The defaults (`argon2idDefaultOptions`) are those of the stored CoreMail credential verifiers: `memoryCost` 65536 KiB, `timeCost` 3, `parallelism` 1, `saltLength` 16 bytes, `hashLength` 32 bytes. Invalid options fail with `INVALID_ARGUMENT`.
214
+ - `verifyArgon2id(phc, password, limits?)` recomputes the digest with the hash's own parameters and compares it in constant time (`crypto.timingSafeEqual`). It resolves `false` for a wrong password and rejects for a hash it cannot read.
215
+ - The hash sets the cost of its own verification, so `verifyArgon2id()` bounds it: an untrusted or corrupted hash must not cost unbounded memory or CPU. A hash above a limit fails with `INVALID_PASSWORD_HASH` naming the limit (for example `parameter m exceeds the maxMemoryCost limit`) before any hashing. The defaults (`argon2idDefaultVerifyLimits`) are `maxMemoryCost` 1048576 KiB (1 GiB), `maxTimeCost` 10 and `maxParallelism` 16; the stored CoreMail verifiers (65536/3/1) and the `argon2` npm defaults (65536/3/4) are well inside. Pass `IArgon2idVerifyLimits` to raise or lower them; invalid limits fail with `INVALID_ARGUMENT`.
216
+ - `parseArgon2idPhc(phc)` returns `IArgon2idPhc` (`version`, `memoryCost`, `timeCost`, `parallelism`, `salt`, `digest`); `encodeArgon2idPhc(fields)` writes the canonical `m,t,p` form.
217
+ - Passwords are strings, hashed as UTF-8, or `Uint8Array`s.
218
+
219
+ Parsing is strict. Only `argon2id` is read; `argon2i`, `argon2d` and every other identifier fail with `UNSUPPORTED_PROFILE`, and every version but 19 (including a missing `v=`, which means version 16) with `UNSUPPORTED_VERSION`. Everything else fails with `INVALID_PASSWORD_HASH`, whose message names the rule:
220
+
221
+ - the parameters `m`, `t` and `p`, each exactly once, in the PHC order `m,t,p` or the `m,p,t` order the `argon2` npm package writes; `keyid`, `data` and unknown parameters are refused;
222
+ - decimal values without sign or leading zeros, within the PHC limits: `p` 1 to 255, `m` from `8 * p` to 2^32-1, `t` 1 to 2^32-1;
223
+ - standard base64 without padding and with zero trailing bits; salt 8 to 48 bytes, digest 12 to 64 bytes.
224
+
225
+ Without `node:crypto.argon2` (Node.js before 24.7.0, or Deno, which does not implement it) hashing and verifying fail with `CRYPTO_OPERATION_FAILED` (`Argon2id requires Node.js ≥24.7.0 crypto.argon2, which this runtime lacks`).
226
+
191
227
  ## Errors
192
228
 
193
- Cryptographic and validation failures use `SmartCryptoError` with a stable `TSmartCryptoErrorCode`. Messages, JSON output, Node inspection, stack metadata, and `cause` do not retain plaintext, keys, shared secrets, or ciphertext details.
229
+ Cryptographic and validation failures use `SmartCryptoError` with a stable `TSmartCryptoErrorCode`. Messages, JSON output, Node inspection, stack metadata, and `cause` do not retain plaintext, keys, shared secrets, or ciphertext details. A message may name the rule that failed (for example `INVALID_PASSWORD_HASH: parameter m must appear once`) with a fixed phrase, never with input material.
194
230
 
195
231
  ## RSA APIs
196
232
 
@@ -239,9 +275,38 @@ const privateKey = await PrivateKey.fromEncryptedPemString(encryptedPem, 'my pas
239
275
 
240
276
  Passphrases are asymmetric between export and import: `toEncryptedPemString('')` fails with `INVALID_ARGUMENT`, while `fromEncryptedPemString(pem, '')` accepts an empty passphrase so that keys stored by `@push.rocks/smartkey` (encrypted under an empty passphrase by default) stay readable. A non-string passphrase fails with `INVALID_ARGUMENT`, a wrong passphrase with `AUTHENTICATION_FAILED`, a malformed or non-RSA key with `INVALID_KEY`, and other encryption schemes with `UNSUPPORTED_PROFILE`.
241
277
 
278
+ ## Self-Signed X.509 Certificates
279
+
280
+ `createSelfSignedCertificate()` creates a self-signed X.509 v3 end-entity certificate and its key with WebCrypto and the built-in DER encoder, for TLS servers that need a certificate without a CA: test servers, development servers and fallback certificates.
281
+
282
+ ```typescript
283
+ import * as https from 'node:https';
284
+ import { createSelfSignedCertificate } from '@push.rocks/smartcrypto';
285
+
286
+ const { certificatePem, privateKeyPem } = await createSelfSignedCertificate({
287
+ commonName: 'localhost',
288
+ dnsNames: ['localhost'],
289
+ ipAddresses: ['127.0.0.1', '::1'],
290
+ });
291
+
292
+ const server = https.createServer({ cert: certificatePem, key: privateKeyPem });
293
+ // A client trusts it explicitly: https.get({ ..., ca: certificatePem })
294
+ ```
295
+
296
+ | Option | Default | Meaning |
297
+ |---|---|---|
298
+ | `commonName` | required | subject and issuer `CN`, 1 to 64 characters without control characters |
299
+ | `dnsNames` | none | `dNSName` subject alternative names (printable ASCII, so IDNs go in A-label form; wildcards such as `*.example.com` are written as given) |
300
+ | `ipAddresses` | none | `iPAddress` subject alternative names: IPv4 dotted quads, or IPv6 groups with at most one `::` (no zone index, no embedded IPv4) |
301
+ | `notBefore` | now | start of validity, truncated to whole seconds |
302
+ | `notAfter` | `notBefore` + 365 days | end of validity, truncated to whole seconds; must be later than `notBefore` |
303
+ | `keyAlgorithm` | `'RSA-2048'` | `'RSA-2048'` (sha256WithRSAEncryption) or `'ECDSA-P256'` (ecdsa-with-SHA256) |
304
+
305
+ The certificate has a random positive 16-byte serial number, `CN=<commonName>` as subject and issuer, and the extensions `basicConstraints` CA:FALSE and `keyUsage` (both critical; digitalSignature, plus keyEncipherment for RSA), `extendedKeyUsage` serverAuth, and `subjectAltName` when names are given. Validity dates through 2049 are UTCTime, later ones GeneralizedTime (RFC 5280). It passes `openssl verify -x509_strict -purpose sslserver` with itself as the trust anchor. `certificatePem` is a `CERTIFICATE` PEM and `privateKeyPem` an unencrypted PKCS#8 `PRIVATE KEY` PEM. Invalid options fail with `INVALID_ARGUMENT`, WebCrypto failures with `CRYPTO_OPERATION_FAILED`. Certificate parsing, chains and CA-issued certificates are out of scope.
306
+
242
307
  ## Runtime Support
243
308
 
244
- The WebCrypto APIs, including the RSA APIs and encrypted private-key PEMs, and the package-entry hashing functions are tested with Node.js 22 and current Chromium. Browsers require a secure context for WebCrypto. The `@push.rocks/smartcrypto/node` entry is tested with Node.js 22 and Deno.
309
+ The WebCrypto APIs, including the RSA APIs and encrypted private-key PEMs, and the package-entry hashing functions are tested with Node.js and current Chromium. Browsers require a secure context for WebCrypto. The `@push.rocks/smartcrypto/node` entry is tested with Node.js; its Argon2id functions require Node.js 24.7.0 or later, the first release with `node:crypto.argon2`.
245
310
 
246
311
  The package has no runtime dependencies. It declares `"sideEffects": false`, and no module does work at import time. Browser bundlers such as esbuild, Rollup, Rolldown and webpack therefore keep only what a bundle imports: a bundle that uses only the hashing functions stays a few kilobytes.
247
312
 
@@ -256,7 +321,7 @@ The package has no runtime dependencies. It declares `"sideEffects": false`, and
256
321
  | `privateKey.forgePrivateKey.sign(md)` | `await privateKey.createRs256Signature(data)` for RS256 |
257
322
  | `key.forge*Key.n.bitLength()` | `key.modulusLength` |
258
323
  | `new PublicKey(forgeKey)`, `new PrivateKey(forgeKey)` | `PublicKey.fromPemString(pem)`, `PrivateKey.fromPemString(pem)`, or the constructors with `IRsaPublicKeyComponents` / `IRsaPrivateKeyComponents` |
259
- | `import { nodeForge } from '@push.rocks/smartcrypto'` | removed without a replacement in this package; see the X.509 note below |
324
+ | `import { nodeForge } from '@push.rocks/smartcrypto'` | removed; for self-signed certificates see the X.509 note below |
260
325
  | `privateKey.toOpenSSH()` returned a legacy PEM encrypted with the passphrase `user@host` | returns an unencrypted `openssh-key-v1` key with the comment `user@host`; `PublicKey.toOpenSSH()` is unchanged |
261
326
  | `fromPemString()` / `createFromPrivateKey()` threw a plain `Error` | throw `SmartCryptoError` with `INVALID_KEY` |
262
327
  | PEM label and content could disagree (forge read either key format under `PRIVATE KEY` or `RSA PRIVATE KEY`) | the label must match the content: `RSA PRIVATE KEY` is PKCS#1, `PRIVATE KEY` is PKCS#8, `PUBLIC KEY` is SPKI, `RSA PUBLIC KEY` is PKCS#1; a mismatch fails with `INVALID_KEY` |
@@ -265,7 +330,7 @@ The package has no runtime dependencies. It declares `"sideEffects": false`, and
265
330
 
266
331
  PEM output is byte-identical to 2.x for the same key.
267
332
 
268
- **No X.509 API.** smartcrypto 3 has no certificate or X.509 support, and 2.x had none beyond re-exporting `nodeForge`. Code that generated or parsed certificates through `smartcrypto.nodeForge`, such as self-signed certificates in `@git.zone/tstest` and `@push.rocks/smartproxy` or test fixtures in social.io, needs a dedicated X.509 library.
333
+ **X.509.** 2.x had no X.509 API beyond re-exporting `nodeForge`. Code that generated self-signed certificates through `smartcrypto.nodeForge`, such as `@git.zone/tstest`, `@push.rocks/smartproxy` and test fixtures in social.io, moves to `createSelfSignedCertificate()` (since 3.1.0; see [Self-Signed X.509 Certificates](#self-signed-x509-certificates)). The private key PEM is PKCS#8 (`PRIVATE KEY`) instead of forge's PKCS#1 (`RSA PRIVATE KEY`); Node.js TLS accepts both. Certificate parsing still needs Node.js `X509Certificate` or a dedicated library.
269
334
 
270
335
  ## Migration from @push.rocks/smartkey
271
336
 
@@ -3,6 +3,6 @@
3
3
  */
4
4
  export const commitinfo = {
5
5
  name: '@push.rocks/smartcrypto',
6
- version: '3.0.0',
6
+ version: '3.2.0',
7
7
  description: 'A library providing easy methods for cryptographic operations, including key pair generation.'
8
8
  }
package/ts/index.ts CHANGED
@@ -14,3 +14,4 @@ export type {
14
14
  export * from './smartcrypto.webcrypto.js';
15
15
  export * from './smartcrypto.x25519.js';
16
16
  export * from './smartcrypto.hash.js';
17
+ export * from './smartcrypto.x509.js';
@@ -8,13 +8,19 @@ import { concatBytes } from './smartcrypto.internal.js';
8
8
  */
9
9
 
10
10
  export const derTags = {
11
+ boolean: 0x01,
11
12
  integer: 0x02,
12
13
  bitString: 0x03,
13
14
  octetString: 0x04,
14
15
  null: 0x05,
15
16
  oid: 0x06,
17
+ utf8String: 0x0c,
18
+ utcTime: 0x17,
19
+ generalizedTime: 0x18,
16
20
  sequence: 0x30,
21
+ set: 0x31,
17
22
  contextSpecificConstructed0: 0xa0,
23
+ contextSpecificConstructed3: 0xa3,
18
24
  } as const;
19
25
 
20
26
  export interface IDerElement {
@@ -216,8 +222,15 @@ export const encodeDerSmallInteger = (valueArg: number): Uint8Array => {
216
222
  export const encodeDerOctetString = (bytesArg: Uint8Array): Uint8Array =>
217
223
  encodeDerElement(derTags.octetString, bytesArg);
218
224
 
219
- export const encodeDerBitString = (bytesArg: Uint8Array): Uint8Array =>
220
- encodeDerElement(derTags.bitString, concatBytes(new Uint8Array([0]), bytesArg));
225
+ /**
226
+ * Encodes a BIT STRING whose last `unusedBitsArg` bits are padding. DER
227
+ * requires the padding bits to be zero; the caller supplies them that way.
228
+ */
229
+ export const encodeDerBitString = (bytesArg: Uint8Array, unusedBitsArg = 0): Uint8Array =>
230
+ encodeDerElement(derTags.bitString, concatBytes(new Uint8Array([unusedBitsArg]), bytesArg));
231
+
232
+ export const encodeDerBoolean = (valueArg: boolean): Uint8Array =>
233
+ encodeDerElement(derTags.boolean, new Uint8Array([valueArg ? 0xff : 0x00]));
221
234
 
222
235
  export const encodeDerNull = (): Uint8Array => encodeDerElement(derTags.null, new Uint8Array(0));
223
236
 
@@ -5,6 +5,7 @@ export type TSmartCryptoErrorCode =
5
5
  | 'INVALID_ARGUMENT'
6
6
  | 'INVALID_ENVELOPE'
7
7
  | 'INVALID_KEY'
8
+ | 'INVALID_PASSWORD_HASH'
8
9
  | 'INVALID_SHARED_SECRET'
9
10
  | 'INVALID_STATE'
10
11
  | 'RECIPIENT_MISMATCH'
@@ -20,13 +21,21 @@ export interface ISmartCryptoErrorJson {
20
21
 
21
22
  const inspectSymbol = Symbol.for('nodejs.util.inspect.custom');
22
23
 
23
- /** A stable error that intentionally retains no sensitive operation details. */
24
+ /**
25
+ * A stable error that intentionally retains no sensitive operation details.
26
+ * The optional detail is a fixed library phrase naming the rule that failed,
27
+ * never input material.
28
+ */
24
29
  export class SmartCryptoError extends Error {
25
30
  public readonly code: TSmartCryptoErrorCode;
26
31
  public readonly cause: undefined;
27
32
 
28
- constructor(codeArg: TSmartCryptoErrorCode) {
29
- super(`SmartCrypto operation failed (${codeArg}).`);
33
+ constructor(codeArg: TSmartCryptoErrorCode, detailArg?: string) {
34
+ super(
35
+ detailArg === undefined
36
+ ? `SmartCrypto operation failed (${codeArg}).`
37
+ : `SmartCrypto operation failed (${codeArg}): ${detailArg}.`,
38
+ );
30
39
  this.name = 'SmartCryptoError';
31
40
  this.code = codeArg;
32
41
  Object.defineProperty(this, 'cause', {
@@ -52,4 +61,5 @@ export class SmartCryptoError extends Error {
52
61
 
53
62
  export const createSmartCryptoError = (
54
63
  codeArg: TSmartCryptoErrorCode,
55
- ): SmartCryptoError => new SmartCryptoError(codeArg);
64
+ detailArg?: string,
65
+ ): SmartCryptoError => new SmartCryptoError(codeArg, detailArg);