@plinthjs/encryption 0.1.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 +47 -0
- package/dist/index.cjs +317 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +149 -0
- package/dist/index.d.ts +149 -0
- package/dist/index.js +310 -0
- package/dist/index.js.map +1 -0
- package/package.json +61 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 The Mason 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
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# @plinthjs/encryption
|
|
2
|
+
|
|
3
|
+
Authenticated encryption and password hashing for Mason, built on Node's `node:crypto` — no
|
|
4
|
+
native dependencies. The `Illuminate\Encryption` + `Illuminate\Hashing` equivalent.
|
|
5
|
+
|
|
6
|
+
## Encryption
|
|
7
|
+
|
|
8
|
+
`Encrypter` uses AES-256-GCM with a random 12-byte IV and a verified authentication tag.
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
import { Encrypter } from '@plinthjs/encryption'
|
|
12
|
+
|
|
13
|
+
// A 32-byte key, raw or `base64:<...>` (the Laravel APP_KEY convention).
|
|
14
|
+
const key = Encrypter.generateKeyBase64()
|
|
15
|
+
const cipher = new Encrypter(key)
|
|
16
|
+
|
|
17
|
+
const payload = cipher.encrypt({ userId: 42, admin: true })
|
|
18
|
+
const data = cipher.decrypt<{ userId: number; admin: boolean }>(payload)
|
|
19
|
+
|
|
20
|
+
// Raw strings (no JSON round-trip):
|
|
21
|
+
const token = cipher.encryptString('s3cret')
|
|
22
|
+
cipher.decryptString(token) // 's3cret'
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
A tampered payload or a wrong key throws `DecryptionError`; a wrong-length key throws
|
|
26
|
+
`InvalidKeyError`.
|
|
27
|
+
|
|
28
|
+
## Hashing
|
|
29
|
+
|
|
30
|
+
`Hasher` uses scrypt, a memory-hard KDF built into `node:crypto`. (Laravel defaults to bcrypt /
|
|
31
|
+
argon2, both native deps; scrypt is the dependency-free port substitute.) Hashes are
|
|
32
|
+
self-describing: `scrypt$<N>$<r>$<p>$<saltB64>$<hashB64>`.
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
import { Hasher } from '@plinthjs/encryption'
|
|
36
|
+
|
|
37
|
+
const hasher = new Hasher()
|
|
38
|
+
const hash = hasher.make('correct horse battery staple')
|
|
39
|
+
|
|
40
|
+
hasher.check('correct horse battery staple', hash) // true
|
|
41
|
+
hasher.check('wrong', hash) // false
|
|
42
|
+
|
|
43
|
+
// Tune cost and detect stale hashes:
|
|
44
|
+
hasher.needsRehash(hash, { cost: 32768 }) // true
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Verification uses `crypto.timingSafeEqual` for constant-time comparison.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var crypto = require('crypto');
|
|
4
|
+
|
|
5
|
+
// src/encrypter.ts
|
|
6
|
+
var CIPHER = "aes-256-gcm";
|
|
7
|
+
var KEY_BYTES = 32;
|
|
8
|
+
var IV_BYTES = 12;
|
|
9
|
+
var TAG_BYTES = 16;
|
|
10
|
+
var BASE64_PREFIX = "base64:";
|
|
11
|
+
var DecryptionError = class extends Error {
|
|
12
|
+
name = "DecryptionError";
|
|
13
|
+
constructor(message = "The payload is invalid or could not be authenticated.") {
|
|
14
|
+
super(message);
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
var InvalidKeyError = class extends Error {
|
|
18
|
+
name = "InvalidKeyError";
|
|
19
|
+
constructor(message = `Encryption key must be ${KEY_BYTES} bytes for AES-256-GCM.`) {
|
|
20
|
+
super(message);
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
function normalizeKey(key) {
|
|
24
|
+
const buffer = typeof key === "string" ? key.startsWith(BASE64_PREFIX) ? Buffer.from(key.slice(BASE64_PREFIX.length), "base64") : Buffer.from(key, "utf8") : Buffer.from(key);
|
|
25
|
+
if (buffer.length !== KEY_BYTES) {
|
|
26
|
+
throw new InvalidKeyError();
|
|
27
|
+
}
|
|
28
|
+
return buffer;
|
|
29
|
+
}
|
|
30
|
+
var Encrypter = class _Encrypter {
|
|
31
|
+
key;
|
|
32
|
+
previousKeys;
|
|
33
|
+
/**
|
|
34
|
+
* @param key A 32-byte key, either a raw `Buffer`, a 32-byte UTF-8 string, or a
|
|
35
|
+
* `base64:<...>` string (the Laravel `APP_KEY` convention). Throws {@link InvalidKeyError}
|
|
36
|
+
* if it does not decode to exactly 32 bytes.
|
|
37
|
+
* @param previousKeys Rotated-out keys (same accepted formats) that {@link decrypt} /
|
|
38
|
+
* {@link decryptString} fall back to, in order, when the current key fails. The Laravel
|
|
39
|
+
* `APP_PREVIOUS_KEYS` equivalent. Each must also decode to exactly 32 bytes.
|
|
40
|
+
*/
|
|
41
|
+
constructor(key, previousKeys = []) {
|
|
42
|
+
this.key = normalizeKey(key);
|
|
43
|
+
this.previousKeys = previousKeys.map((previous) => normalizeKey(previous));
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Return a new `Encrypter` with the same current key and the given previous keys. The Laravel
|
|
47
|
+
* `Encrypter::previousKeys()` equivalent, expressed immutably in Mason's `with*` style.
|
|
48
|
+
*/
|
|
49
|
+
withPreviousKeys(keys) {
|
|
50
|
+
return new _Encrypter(this.key, keys);
|
|
51
|
+
}
|
|
52
|
+
/** The current encryption key. The Laravel `Encrypter::getKey()` equivalent. */
|
|
53
|
+
getKey() {
|
|
54
|
+
return Buffer.from(this.key);
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* The current key followed by every previous key, in fallback order. The Laravel
|
|
58
|
+
* `Encrypter::getAllKeys()` equivalent.
|
|
59
|
+
*/
|
|
60
|
+
getAllKeys() {
|
|
61
|
+
return [this.key, ...this.previousKeys].map((key) => Buffer.from(key));
|
|
62
|
+
}
|
|
63
|
+
/** The previous (rotated-out) keys. The Laravel `Encrypter::getPreviousKeys()` equivalent. */
|
|
64
|
+
getPreviousKeys() {
|
|
65
|
+
return this.previousKeys.map((key) => Buffer.from(key));
|
|
66
|
+
}
|
|
67
|
+
/** Generate a fresh 32-byte key. The Laravel `Encrypter::generateKey()` equivalent. */
|
|
68
|
+
static generateKey() {
|
|
69
|
+
return crypto.randomBytes(KEY_BYTES);
|
|
70
|
+
}
|
|
71
|
+
/** Generate a fresh key as a `base64:<...>` string, ready to drop into config. */
|
|
72
|
+
static generateKeyBase64() {
|
|
73
|
+
return `${BASE64_PREFIX}${_Encrypter.generateKey().toString("base64")}`;
|
|
74
|
+
}
|
|
75
|
+
/** True if `key` is a valid 32-byte key (raw, utf-8, or `base64:`-prefixed). */
|
|
76
|
+
static supported(key) {
|
|
77
|
+
try {
|
|
78
|
+
normalizeKey(key);
|
|
79
|
+
return true;
|
|
80
|
+
} catch {
|
|
81
|
+
return false;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* JSON-serialize and encrypt a value. Returns a base64-encoded envelope containing the random
|
|
86
|
+
* IV, the GCM auth tag, and the ciphertext. The Laravel `Encrypter::encrypt()` equivalent.
|
|
87
|
+
*/
|
|
88
|
+
encrypt(value) {
|
|
89
|
+
return this.encryptString(JSON.stringify(value));
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Decrypt a payload produced by {@link encrypt} and JSON-parse the result. Throws
|
|
93
|
+
* {@link DecryptionError} on tamper or wrong key. The Laravel `Encrypter::decrypt()` equivalent.
|
|
94
|
+
*/
|
|
95
|
+
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- T is the caller-supplied cast type for the deserialized value; removing it loses call-site inference
|
|
96
|
+
decrypt(payload) {
|
|
97
|
+
return JSON.parse(this.decryptString(payload));
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Encrypt a raw string without JSON-serializing it. The Laravel `Encrypter::encryptString()`
|
|
101
|
+
* equivalent — use when the plaintext is already a string and you want it back verbatim.
|
|
102
|
+
*/
|
|
103
|
+
encryptString(value) {
|
|
104
|
+
const iv = crypto.randomBytes(IV_BYTES);
|
|
105
|
+
const cipher = crypto.createCipheriv(CIPHER, this.key, iv, { authTagLength: TAG_BYTES });
|
|
106
|
+
const ciphertext = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
|
|
107
|
+
const tag = cipher.getAuthTag();
|
|
108
|
+
const envelope = {
|
|
109
|
+
iv: iv.toString("base64"),
|
|
110
|
+
tag: tag.toString("base64"),
|
|
111
|
+
ciphertext: ciphertext.toString("base64")
|
|
112
|
+
};
|
|
113
|
+
return Buffer.from(JSON.stringify(envelope), "utf8").toString("base64");
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Decrypt a raw-string payload produced by {@link encryptString}. Tries the current key first,
|
|
117
|
+
* then each previous key in order, and throws {@link DecryptionError} only once every key has
|
|
118
|
+
* failed (tamper, or no matching key). The Laravel `Encrypter::decryptString()` equivalent.
|
|
119
|
+
*/
|
|
120
|
+
decryptString(payload) {
|
|
121
|
+
const envelope = this.parse(payload);
|
|
122
|
+
const iv = Buffer.from(envelope.iv, "base64");
|
|
123
|
+
const tag = Buffer.from(envelope.tag, "base64");
|
|
124
|
+
const ciphertext = Buffer.from(envelope.ciphertext, "base64");
|
|
125
|
+
if (iv.length !== IV_BYTES || tag.length !== TAG_BYTES) {
|
|
126
|
+
throw new DecryptionError();
|
|
127
|
+
}
|
|
128
|
+
for (const key of [this.key, ...this.previousKeys]) {
|
|
129
|
+
try {
|
|
130
|
+
const decipher = crypto.createDecipheriv(CIPHER, key, iv, { authTagLength: TAG_BYTES });
|
|
131
|
+
decipher.setAuthTag(tag);
|
|
132
|
+
const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
|
|
133
|
+
return plaintext.toString("utf8");
|
|
134
|
+
} catch {
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
throw new DecryptionError();
|
|
138
|
+
}
|
|
139
|
+
/** Decode and validate the base64 envelope, raising {@link DecryptionError} if it is malformed. */
|
|
140
|
+
parse(payload) {
|
|
141
|
+
let decoded;
|
|
142
|
+
try {
|
|
143
|
+
decoded = JSON.parse(Buffer.from(payload, "base64").toString("utf8"));
|
|
144
|
+
} catch {
|
|
145
|
+
throw new DecryptionError();
|
|
146
|
+
}
|
|
147
|
+
if (!isEnvelope(decoded)) {
|
|
148
|
+
throw new DecryptionError();
|
|
149
|
+
}
|
|
150
|
+
return decoded;
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Constant-time equality for two strings, exposed for callers that need to compare opaque
|
|
154
|
+
* tokens without leaking length-independent timing. The Laravel `hash_equals()` analog.
|
|
155
|
+
*/
|
|
156
|
+
static hashEquals(a, b) {
|
|
157
|
+
const left = Buffer.from(a, "utf8");
|
|
158
|
+
const right = Buffer.from(b, "utf8");
|
|
159
|
+
if (left.length !== right.length) return false;
|
|
160
|
+
return crypto.timingSafeEqual(left, right);
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
function isEnvelope(value) {
|
|
164
|
+
if (value === null || typeof value !== "object") return false;
|
|
165
|
+
const record = value;
|
|
166
|
+
return typeof record["iv"] === "string" && typeof record["tag"] === "string" && typeof record["ciphertext"] === "string";
|
|
167
|
+
}
|
|
168
|
+
var ALGORITHM = "scrypt";
|
|
169
|
+
var SEPARATOR = "$";
|
|
170
|
+
var SALT_BYTES = 16;
|
|
171
|
+
var KEY_LENGTH = 64;
|
|
172
|
+
var DEFAULTS = { cost: 16384, blockSize: 8, parallelism: 1 };
|
|
173
|
+
function maxmem(opts) {
|
|
174
|
+
return 256 * opts.cost * opts.blockSize + 1024 * 1024;
|
|
175
|
+
}
|
|
176
|
+
function resolve(options) {
|
|
177
|
+
return {
|
|
178
|
+
cost: options?.cost ?? DEFAULTS.cost,
|
|
179
|
+
blockSize: options?.blockSize ?? DEFAULTS.blockSize,
|
|
180
|
+
parallelism: options?.parallelism ?? DEFAULTS.parallelism
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
var InvalidHashError = class extends Error {
|
|
184
|
+
name = "InvalidHashError";
|
|
185
|
+
constructor(message = "The given hash is not a valid Mason scrypt hash.") {
|
|
186
|
+
super(message);
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
function parse(hash) {
|
|
190
|
+
const parts = hash.split(SEPARATOR);
|
|
191
|
+
if (parts.length !== 6) return null;
|
|
192
|
+
const [algorithm, nRaw, rRaw, pRaw, saltB64, hashB64] = parts;
|
|
193
|
+
if (algorithm !== ALGORITHM) return null;
|
|
194
|
+
const cost = Number(nRaw);
|
|
195
|
+
const blockSize = Number(rRaw);
|
|
196
|
+
const parallelism = Number(pRaw);
|
|
197
|
+
if (!Number.isInteger(cost) || !Number.isInteger(blockSize) || !Number.isInteger(parallelism)) {
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
if (cost <= 0 || blockSize <= 0 || parallelism <= 0) return null;
|
|
201
|
+
return {
|
|
202
|
+
algorithm,
|
|
203
|
+
options: { cost, blockSize, parallelism },
|
|
204
|
+
salt: Buffer.from(saltB64, "base64"),
|
|
205
|
+
hash: Buffer.from(hashB64, "base64")
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
var Hasher = class {
|
|
209
|
+
options;
|
|
210
|
+
/** @param options Default cost parameters applied when {@link make} is called without overrides. */
|
|
211
|
+
constructor(options) {
|
|
212
|
+
this.options = resolve(options);
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Hash a password with a fresh random 16-byte salt, returning a self-describing string of the
|
|
216
|
+
* form `scrypt$<N>$<r>$<p>$<saltB64>$<hashB64>`. The Laravel `Hash::make()` equivalent.
|
|
217
|
+
*/
|
|
218
|
+
make(password, options) {
|
|
219
|
+
const opts = options ? resolve(options) : this.options;
|
|
220
|
+
const salt = crypto.randomBytes(SALT_BYTES);
|
|
221
|
+
const derived = crypto.scryptSync(password, salt, KEY_LENGTH, {
|
|
222
|
+
N: opts.cost,
|
|
223
|
+
r: opts.blockSize,
|
|
224
|
+
p: opts.parallelism,
|
|
225
|
+
maxmem: maxmem(opts)
|
|
226
|
+
});
|
|
227
|
+
return [
|
|
228
|
+
ALGORITHM,
|
|
229
|
+
opts.cost,
|
|
230
|
+
opts.blockSize,
|
|
231
|
+
opts.parallelism,
|
|
232
|
+
salt.toString("base64"),
|
|
233
|
+
derived.toString("base64")
|
|
234
|
+
].join(SEPARATOR);
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Verify a password against a hash in constant time. Returns `false` for a wrong password or a
|
|
238
|
+
* malformed hash. The Laravel `Hash::check()` equivalent.
|
|
239
|
+
*/
|
|
240
|
+
check(password, hash) {
|
|
241
|
+
const parsed = parse(hash);
|
|
242
|
+
if (parsed === null || parsed.hash.length === 0) return false;
|
|
243
|
+
let computed;
|
|
244
|
+
try {
|
|
245
|
+
computed = crypto.scryptSync(password, parsed.salt, parsed.hash.length, {
|
|
246
|
+
N: parsed.options.cost,
|
|
247
|
+
r: parsed.options.blockSize,
|
|
248
|
+
p: parsed.options.parallelism,
|
|
249
|
+
maxmem: maxmem(parsed.options)
|
|
250
|
+
});
|
|
251
|
+
} catch {
|
|
252
|
+
return false;
|
|
253
|
+
}
|
|
254
|
+
if (computed.length !== parsed.hash.length) return false;
|
|
255
|
+
return crypto.timingSafeEqual(computed, parsed.hash);
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Determine whether a hash should be re-computed because its cost parameters differ from the
|
|
259
|
+
* given (or default) options. The Laravel `Hash::needsRehash()` equivalent.
|
|
260
|
+
*/
|
|
261
|
+
needsRehash(hash, options) {
|
|
262
|
+
const parsed = parse(hash);
|
|
263
|
+
if (parsed === null) return true;
|
|
264
|
+
const target = options ? resolve(options) : this.options;
|
|
265
|
+
return parsed.options.cost !== target.cost || parsed.options.blockSize !== target.blockSize || parsed.options.parallelism !== target.parallelism;
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Extract the algorithm and cost parameters from a hash, or `null` if it is not a valid Mason
|
|
269
|
+
* scrypt hash. The Laravel `Hash::info()` equivalent.
|
|
270
|
+
*/
|
|
271
|
+
info(hash) {
|
|
272
|
+
const parsed = parse(hash);
|
|
273
|
+
if (parsed === null) return null;
|
|
274
|
+
return { algorithm: parsed.algorithm, options: { ...parsed.options } };
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Determine whether a value is already a Mason scrypt hash — i.e. it parses as the
|
|
278
|
+
* self-describing `scrypt$N$r$p$salt$hash` format with a non-empty salt and digest. The Laravel
|
|
279
|
+
* `Hash::isHashed()` equivalent.
|
|
280
|
+
*/
|
|
281
|
+
isHashed(value) {
|
|
282
|
+
const parsed = parse(value);
|
|
283
|
+
return parsed !== null && parsed.salt.length > 0 && parsed.hash.length > 0;
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Verify that the given (or default) cost parameters are sane — `cost` a power of two greater
|
|
287
|
+
* than one, `blockSize`/`parallelism` positive integers — and that a test hash actually
|
|
288
|
+
* round-trips under them. The Laravel `Hash::verifyConfiguration()` equivalent.
|
|
289
|
+
*/
|
|
290
|
+
verifyConfiguration(options) {
|
|
291
|
+
const opts = options ? resolve(options) : this.options;
|
|
292
|
+
if (!isPowerOfTwo(opts.cost) || opts.cost < 2) return false;
|
|
293
|
+
if (!Number.isInteger(opts.blockSize) || opts.blockSize < 1) return false;
|
|
294
|
+
if (!Number.isInteger(opts.parallelism) || opts.parallelism < 1) return false;
|
|
295
|
+
try {
|
|
296
|
+
const probe = "mason-verify-configuration";
|
|
297
|
+
return this.check(probe, this.make(probe, opts));
|
|
298
|
+
} catch {
|
|
299
|
+
return false;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
};
|
|
303
|
+
function isPowerOfTwo(value) {
|
|
304
|
+
return Number.isInteger(value) && value >= 1 && Number.isInteger(Math.log2(value));
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// src/index.ts
|
|
308
|
+
var VERSION = "0.1.0";
|
|
309
|
+
|
|
310
|
+
exports.DecryptionError = DecryptionError;
|
|
311
|
+
exports.Encrypter = Encrypter;
|
|
312
|
+
exports.Hasher = Hasher;
|
|
313
|
+
exports.InvalidHashError = InvalidHashError;
|
|
314
|
+
exports.InvalidKeyError = InvalidKeyError;
|
|
315
|
+
exports.VERSION = VERSION;
|
|
316
|
+
//# sourceMappingURL=index.cjs.map
|
|
317
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/encr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IAAM,OAAA,GAAU","file":"index.cjs","sourcesContent":["/**\n * `Encrypter` — authenticated symmetric encryption over `node:crypto`.\n * The Laravel `Illuminate\\Encryption\\Encrypter` equivalent: a 32-byte application key,\n * AES-256-GCM with a random IV, and an authentication tag verified on decrypt. Values are\n * JSON-serialized before encryption and revived afterwards, so any JSON-safe value round-trips.\n */\nimport { createCipheriv, createDecipheriv, randomBytes, timingSafeEqual } from 'node:crypto'\n\n/** The cipher Mason uses. AES-256-GCM gives confidentiality plus a built-in auth tag (AEAD). */\nconst CIPHER = 'aes-256-gcm'\n/** Required key length for AES-256, in bytes. */\nconst KEY_BYTES = 32\n/** Recommended GCM IV length, in bytes. */\nconst IV_BYTES = 12\n/** GCM authentication tag length, in bytes. */\nconst TAG_BYTES = 16\n/** Prefix used by `base64:`-encoded keys — the Laravel `APP_KEY` convention. */\nconst BASE64_PREFIX = 'base64:'\n\n/**\n * The on-the-wire shape of an encrypted payload, before base64-wrapping. Mirrors Laravel's\n * `{ iv, value, mac }` envelope, adapted to GCM (the auth tag replaces a separate HMAC).\n */\ninterface EncryptedEnvelope {\n /** Base64 initialization vector. */\n iv: string\n /** Base64 GCM authentication tag. */\n tag: string\n /** Base64 ciphertext. */\n ciphertext: string\n}\n\n/**\n * Thrown when a payload cannot be decrypted: a malformed envelope, the wrong key, or a tampered\n * IV/tag/ciphertext (the auth tag fails to verify). The Laravel `DecryptException` equivalent.\n */\nexport class DecryptionError extends Error {\n override readonly name = 'DecryptionError'\n\n constructor(message = 'The payload is invalid or could not be authenticated.') {\n super(message)\n }\n}\n\n/** Thrown when constructing an {@link Encrypter} with a key of the wrong length. */\nexport class InvalidKeyError extends Error {\n override readonly name = 'InvalidKeyError'\n\n constructor(message = `Encryption key must be ${KEY_BYTES} bytes for AES-256-GCM.`) {\n super(message)\n }\n}\n\n/** Normalize a `Buffer | string` key into a validated 32-byte Buffer. */\nfunction normalizeKey(key: Buffer | string): Buffer {\n const buffer =\n typeof key === 'string'\n ? key.startsWith(BASE64_PREFIX)\n ? Buffer.from(key.slice(BASE64_PREFIX.length), 'base64')\n : Buffer.from(key, 'utf8')\n : Buffer.from(key)\n\n if (buffer.length !== KEY_BYTES) {\n throw new InvalidKeyError()\n }\n return buffer\n}\n\n/**\n * Authenticated AES-256-GCM encrypter. The Laravel `Illuminate\\Encryption\\Encrypter` equivalent.\n */\nexport class Encrypter {\n private readonly key: Buffer\n\n private readonly previousKeys: readonly Buffer[]\n\n /**\n * @param key A 32-byte key, either a raw `Buffer`, a 32-byte UTF-8 string, or a\n * `base64:<...>` string (the Laravel `APP_KEY` convention). Throws {@link InvalidKeyError}\n * if it does not decode to exactly 32 bytes.\n * @param previousKeys Rotated-out keys (same accepted formats) that {@link decrypt} /\n * {@link decryptString} fall back to, in order, when the current key fails. The Laravel\n * `APP_PREVIOUS_KEYS` equivalent. Each must also decode to exactly 32 bytes.\n */\n constructor(key: Buffer | string, previousKeys: readonly (Buffer | string)[] = []) {\n this.key = normalizeKey(key)\n this.previousKeys = previousKeys.map((previous) => normalizeKey(previous))\n }\n\n /**\n * Return a new `Encrypter` with the same current key and the given previous keys. The Laravel\n * `Encrypter::previousKeys()` equivalent, expressed immutably in Mason's `with*` style.\n */\n withPreviousKeys(keys: readonly (Buffer | string)[]): Encrypter {\n return new Encrypter(this.key, keys)\n }\n\n /** The current encryption key. The Laravel `Encrypter::getKey()` equivalent. */\n getKey(): Buffer {\n return Buffer.from(this.key)\n }\n\n /**\n * The current key followed by every previous key, in fallback order. The Laravel\n * `Encrypter::getAllKeys()` equivalent.\n */\n getAllKeys(): Buffer[] {\n return [this.key, ...this.previousKeys].map((key) => Buffer.from(key))\n }\n\n /** The previous (rotated-out) keys. The Laravel `Encrypter::getPreviousKeys()` equivalent. */\n getPreviousKeys(): Buffer[] {\n return this.previousKeys.map((key) => Buffer.from(key))\n }\n\n /** Generate a fresh 32-byte key. The Laravel `Encrypter::generateKey()` equivalent. */\n static generateKey(): Buffer {\n return randomBytes(KEY_BYTES)\n }\n\n /** Generate a fresh key as a `base64:<...>` string, ready to drop into config. */\n static generateKeyBase64(): string {\n return `${BASE64_PREFIX}${Encrypter.generateKey().toString('base64')}`\n }\n\n /** True if `key` is a valid 32-byte key (raw, utf-8, or `base64:`-prefixed). */\n static supported(key: Buffer | string): boolean {\n try {\n normalizeKey(key)\n return true\n } catch {\n return false\n }\n }\n\n /**\n * JSON-serialize and encrypt a value. Returns a base64-encoded envelope containing the random\n * IV, the GCM auth tag, and the ciphertext. The Laravel `Encrypter::encrypt()` equivalent.\n */\n encrypt(value: unknown): string {\n return this.encryptString(JSON.stringify(value))\n }\n\n /**\n * Decrypt a payload produced by {@link encrypt} and JSON-parse the result. Throws\n * {@link DecryptionError} on tamper or wrong key. The Laravel `Encrypter::decrypt()` equivalent.\n */\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- T is the caller-supplied cast type for the deserialized value; removing it loses call-site inference\n decrypt<T = unknown>(payload: string): T {\n return JSON.parse(this.decryptString(payload)) as T\n }\n\n /**\n * Encrypt a raw string without JSON-serializing it. The Laravel `Encrypter::encryptString()`\n * equivalent — use when the plaintext is already a string and you want it back verbatim.\n */\n encryptString(value: string): string {\n const iv = randomBytes(IV_BYTES)\n const cipher = createCipheriv(CIPHER, this.key, iv, { authTagLength: TAG_BYTES })\n const ciphertext = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()])\n const tag = cipher.getAuthTag()\n\n const envelope: EncryptedEnvelope = {\n iv: iv.toString('base64'),\n tag: tag.toString('base64'),\n ciphertext: ciphertext.toString('base64'),\n }\n return Buffer.from(JSON.stringify(envelope), 'utf8').toString('base64')\n }\n\n /**\n * Decrypt a raw-string payload produced by {@link encryptString}. Tries the current key first,\n * then each previous key in order, and throws {@link DecryptionError} only once every key has\n * failed (tamper, or no matching key). The Laravel `Encrypter::decryptString()` equivalent.\n */\n decryptString(payload: string): string {\n const envelope = this.parse(payload)\n const iv = Buffer.from(envelope.iv, 'base64')\n const tag = Buffer.from(envelope.tag, 'base64')\n const ciphertext = Buffer.from(envelope.ciphertext, 'base64')\n\n if (iv.length !== IV_BYTES || tag.length !== TAG_BYTES) {\n throw new DecryptionError()\n }\n\n for (const key of [this.key, ...this.previousKeys]) {\n try {\n const decipher = createDecipheriv(CIPHER, key, iv, { authTagLength: TAG_BYTES })\n decipher.setAuthTag(tag)\n const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()])\n return plaintext.toString('utf8')\n } catch {\n // A bad key or tampered ciphertext/tag fails the GCM tag check in `final()`;\n // fall through to the next rotated-out key.\n }\n }\n throw new DecryptionError()\n }\n\n /** Decode and validate the base64 envelope, raising {@link DecryptionError} if it is malformed. */\n private parse(payload: string): EncryptedEnvelope {\n let decoded: unknown\n try {\n decoded = JSON.parse(Buffer.from(payload, 'base64').toString('utf8'))\n } catch {\n throw new DecryptionError()\n }\n\n if (!isEnvelope(decoded)) {\n throw new DecryptionError()\n }\n return decoded\n }\n\n /**\n * Constant-time equality for two strings, exposed for callers that need to compare opaque\n * tokens without leaking length-independent timing. The Laravel `hash_equals()` analog.\n */\n static hashEquals(a: string, b: string): boolean {\n const left = Buffer.from(a, 'utf8')\n const right = Buffer.from(b, 'utf8')\n if (left.length !== right.length) return false\n return timingSafeEqual(left, right)\n }\n}\n\n/** Structural guard for a decoded envelope — all three fields must be present strings. */\nfunction isEnvelope(value: unknown): value is EncryptedEnvelope {\n if (value === null || typeof value !== 'object') return false\n const record = value as Record<string, unknown>\n return (\n typeof record['iv'] === 'string' &&\n typeof record['tag'] === 'string' &&\n typeof record['ciphertext'] === 'string'\n )\n}\n","/**\n * `Hasher` — password hashing over `node:crypto`'s `scryptSync`.\n * The Laravel `Illuminate\\Hashing\\HashManager` / `Hash` facade equivalent.\n *\n * NOTE ON ALGORITHM: Laravel defaults to bcrypt and offers argon2i/argon2id. Both are native\n * dependencies in Node. To keep Mason dependency-free, this port uses scrypt — a memory-hard\n * KDF built into `node:crypto`. It is a standardized, well-regarded password hash and an\n * acceptable substitute for the port. Hashes are self-describing\n * (`scrypt$<N>$<r>$<p>$<saltB64>$<hashB64>`) so parameters can be tuned and detected over time.\n */\nimport { randomBytes, scryptSync, timingSafeEqual } from 'node:crypto'\n\n/** The algorithm tag stored in every hash, so the format can evolve without ambiguity. */\nconst ALGORITHM = 'scrypt'\n/** Field separator inside a hash string. `$` never appears in base64url-free base64 we emit. */\nconst SEPARATOR = '$'\n/** Random salt length, in bytes. */\nconst SALT_BYTES = 16\n/** Derived key (hash) length, in bytes. */\nconst KEY_LENGTH = 64\n\n/**\n * Tunable scrypt cost parameters. The Laravel hashing `options` (`rounds`/`memory`/`time`)\n * equivalent, expressed in scrypt's own terms.\n */\nexport interface HashOptions {\n /** CPU/memory cost parameter `N`; must be a power of two. Default `16384` (2^14). */\n cost?: number\n /** Block size `r`. Default `8`. */\n blockSize?: number\n /** Parallelization `p`. Default `1`. */\n parallelism?: number\n}\n\n/** The resolved scrypt parameters after defaults are applied. */\ninterface ResolvedOptions {\n cost: number\n blockSize: number\n parallelism: number\n}\n\nconst DEFAULTS: ResolvedOptions = { cost: 16_384, blockSize: 8, parallelism: 1 }\n\n/** scrypt's `maxmem` ceiling scales with `128 * N * r`; give it generous headroom. */\nfunction maxmem(opts: ResolvedOptions): number {\n return 256 * opts.cost * opts.blockSize + 1024 * 1024\n}\n\nfunction resolve(options?: HashOptions): ResolvedOptions {\n return {\n cost: options?.cost ?? DEFAULTS.cost,\n blockSize: options?.blockSize ?? DEFAULTS.blockSize,\n parallelism: options?.parallelism ?? DEFAULTS.parallelism,\n }\n}\n\n/** The parsed components of a self-describing hash string. */\ninterface ParsedHash {\n algorithm: string\n options: ResolvedOptions\n salt: Buffer\n hash: Buffer\n}\n\n/** Thrown by {@link Hasher.info}-style parsing when a hash string is not in the expected format. */\nexport class InvalidHashError extends Error {\n override readonly name = 'InvalidHashError'\n\n constructor(message = 'The given hash is not a valid Mason scrypt hash.') {\n super(message)\n }\n}\n\n/** Parse a `scrypt$N$r$p$salt$hash` string, or return `null` if it does not match. */\nfunction parse(hash: string): ParsedHash | null {\n const parts = hash.split(SEPARATOR)\n if (parts.length !== 6) return null\n\n const [algorithm, nRaw, rRaw, pRaw, saltB64, hashB64] = parts as [\n string,\n string,\n string,\n string,\n string,\n string,\n ]\n if (algorithm !== ALGORITHM) return null\n\n const cost = Number(nRaw)\n const blockSize = Number(rRaw)\n const parallelism = Number(pRaw)\n if (!Number.isInteger(cost) || !Number.isInteger(blockSize) || !Number.isInteger(parallelism)) {\n return null\n }\n if (cost <= 0 || blockSize <= 0 || parallelism <= 0) return null\n\n return {\n algorithm,\n options: { cost, blockSize, parallelism },\n salt: Buffer.from(saltB64, 'base64'),\n hash: Buffer.from(hashB64, 'base64'),\n }\n}\n\n/**\n * Password hasher backed by scrypt. The Laravel `Hash` facade equivalent.\n */\nexport class Hasher {\n private readonly options: ResolvedOptions\n\n /** @param options Default cost parameters applied when {@link make} is called without overrides. */\n constructor(options?: HashOptions) {\n this.options = resolve(options)\n }\n\n /**\n * Hash a password with a fresh random 16-byte salt, returning a self-describing string of the\n * form `scrypt$<N>$<r>$<p>$<saltB64>$<hashB64>`. The Laravel `Hash::make()` equivalent.\n */\n make(password: string, options?: HashOptions): string {\n const opts = options ? resolve(options) : this.options\n const salt = randomBytes(SALT_BYTES)\n const derived = scryptSync(password, salt, KEY_LENGTH, {\n N: opts.cost,\n r: opts.blockSize,\n p: opts.parallelism,\n maxmem: maxmem(opts),\n })\n\n return [\n ALGORITHM,\n opts.cost,\n opts.blockSize,\n opts.parallelism,\n salt.toString('base64'),\n derived.toString('base64'),\n ].join(SEPARATOR)\n }\n\n /**\n * Verify a password against a hash in constant time. Returns `false` for a wrong password or a\n * malformed hash. The Laravel `Hash::check()` equivalent.\n */\n check(password: string, hash: string): boolean {\n const parsed = parse(hash)\n if (parsed === null || parsed.hash.length === 0) return false\n\n let computed: Buffer\n try {\n computed = scryptSync(password, parsed.salt, parsed.hash.length, {\n N: parsed.options.cost,\n r: parsed.options.blockSize,\n p: parsed.options.parallelism,\n maxmem: maxmem(parsed.options),\n })\n } catch {\n return false\n }\n\n if (computed.length !== parsed.hash.length) return false\n return timingSafeEqual(computed, parsed.hash)\n }\n\n /**\n * Determine whether a hash should be re-computed because its cost parameters differ from the\n * given (or default) options. The Laravel `Hash::needsRehash()` equivalent.\n */\n needsRehash(hash: string, options?: HashOptions): boolean {\n const parsed = parse(hash)\n if (parsed === null) return true\n\n const target = options ? resolve(options) : this.options\n return (\n parsed.options.cost !== target.cost ||\n parsed.options.blockSize !== target.blockSize ||\n parsed.options.parallelism !== target.parallelism\n )\n }\n\n /**\n * Extract the algorithm and cost parameters from a hash, or `null` if it is not a valid Mason\n * scrypt hash. The Laravel `Hash::info()` equivalent.\n */\n info(hash: string): { algorithm: string; options: HashOptions } | null {\n const parsed = parse(hash)\n if (parsed === null) return null\n return { algorithm: parsed.algorithm, options: { ...parsed.options } }\n }\n\n /**\n * Determine whether a value is already a Mason scrypt hash — i.e. it parses as the\n * self-describing `scrypt$N$r$p$salt$hash` format with a non-empty salt and digest. The Laravel\n * `Hash::isHashed()` equivalent.\n */\n isHashed(value: string): boolean {\n const parsed = parse(value)\n return parsed !== null && parsed.salt.length > 0 && parsed.hash.length > 0\n }\n\n /**\n * Verify that the given (or default) cost parameters are sane — `cost` a power of two greater\n * than one, `blockSize`/`parallelism` positive integers — and that a test hash actually\n * round-trips under them. The Laravel `Hash::verifyConfiguration()` equivalent.\n */\n verifyConfiguration(options?: HashOptions): boolean {\n const opts = options ? resolve(options) : this.options\n if (!isPowerOfTwo(opts.cost) || opts.cost < 2) return false\n if (!Number.isInteger(opts.blockSize) || opts.blockSize < 1) return false\n if (!Number.isInteger(opts.parallelism) || opts.parallelism < 1) return false\n\n try {\n const probe = 'mason-verify-configuration'\n return this.check(probe, this.make(probe, opts))\n } catch {\n return false\n }\n }\n}\n\n/** True when `value` is a positive-integer power of two (1, 2, 4, …). */\nfunction isPowerOfTwo(value: number): boolean {\n return Number.isInteger(value) && value >= 1 && Number.isInteger(Math.log2(value))\n}\n","/**\n * @plinthjs/encryption — authenticated encryption and password hashing over `node:crypto`.\n *\n * The Laravel `Illuminate\\Encryption` + `Illuminate\\Hashing` equivalent, with zero native\n * dependencies: {@link Encrypter} uses AES-256-GCM, and {@link Hasher} uses scrypt (a built-in,\n * memory-hard KDF standing in for bcrypt/argon2, which are native deps).\n */\nexport const VERSION = '0.1.0'\n\nexport { DecryptionError, Encrypter, InvalidKeyError } from './encrypter'\nexport { Hasher, type HashOptions, InvalidHashError } from './hasher'\n"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thrown when a payload cannot be decrypted: a malformed envelope, the wrong key, or a tampered
|
|
3
|
+
* IV/tag/ciphertext (the auth tag fails to verify). The Laravel `DecryptException` equivalent.
|
|
4
|
+
*/
|
|
5
|
+
declare class DecryptionError extends Error {
|
|
6
|
+
readonly name = "DecryptionError";
|
|
7
|
+
constructor(message?: string);
|
|
8
|
+
}
|
|
9
|
+
/** Thrown when constructing an {@link Encrypter} with a key of the wrong length. */
|
|
10
|
+
declare class InvalidKeyError extends Error {
|
|
11
|
+
readonly name = "InvalidKeyError";
|
|
12
|
+
constructor(message?: string);
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Authenticated AES-256-GCM encrypter. The Laravel `Illuminate\Encryption\Encrypter` equivalent.
|
|
16
|
+
*/
|
|
17
|
+
declare class Encrypter {
|
|
18
|
+
private readonly key;
|
|
19
|
+
private readonly previousKeys;
|
|
20
|
+
/**
|
|
21
|
+
* @param key A 32-byte key, either a raw `Buffer`, a 32-byte UTF-8 string, or a
|
|
22
|
+
* `base64:<...>` string (the Laravel `APP_KEY` convention). Throws {@link InvalidKeyError}
|
|
23
|
+
* if it does not decode to exactly 32 bytes.
|
|
24
|
+
* @param previousKeys Rotated-out keys (same accepted formats) that {@link decrypt} /
|
|
25
|
+
* {@link decryptString} fall back to, in order, when the current key fails. The Laravel
|
|
26
|
+
* `APP_PREVIOUS_KEYS` equivalent. Each must also decode to exactly 32 bytes.
|
|
27
|
+
*/
|
|
28
|
+
constructor(key: Buffer | string, previousKeys?: readonly (Buffer | string)[]);
|
|
29
|
+
/**
|
|
30
|
+
* Return a new `Encrypter` with the same current key and the given previous keys. The Laravel
|
|
31
|
+
* `Encrypter::previousKeys()` equivalent, expressed immutably in Mason's `with*` style.
|
|
32
|
+
*/
|
|
33
|
+
withPreviousKeys(keys: readonly (Buffer | string)[]): Encrypter;
|
|
34
|
+
/** The current encryption key. The Laravel `Encrypter::getKey()` equivalent. */
|
|
35
|
+
getKey(): Buffer;
|
|
36
|
+
/**
|
|
37
|
+
* The current key followed by every previous key, in fallback order. The Laravel
|
|
38
|
+
* `Encrypter::getAllKeys()` equivalent.
|
|
39
|
+
*/
|
|
40
|
+
getAllKeys(): Buffer[];
|
|
41
|
+
/** The previous (rotated-out) keys. The Laravel `Encrypter::getPreviousKeys()` equivalent. */
|
|
42
|
+
getPreviousKeys(): Buffer[];
|
|
43
|
+
/** Generate a fresh 32-byte key. The Laravel `Encrypter::generateKey()` equivalent. */
|
|
44
|
+
static generateKey(): Buffer;
|
|
45
|
+
/** Generate a fresh key as a `base64:<...>` string, ready to drop into config. */
|
|
46
|
+
static generateKeyBase64(): string;
|
|
47
|
+
/** True if `key` is a valid 32-byte key (raw, utf-8, or `base64:`-prefixed). */
|
|
48
|
+
static supported(key: Buffer | string): boolean;
|
|
49
|
+
/**
|
|
50
|
+
* JSON-serialize and encrypt a value. Returns a base64-encoded envelope containing the random
|
|
51
|
+
* IV, the GCM auth tag, and the ciphertext. The Laravel `Encrypter::encrypt()` equivalent.
|
|
52
|
+
*/
|
|
53
|
+
encrypt(value: unknown): string;
|
|
54
|
+
/**
|
|
55
|
+
* Decrypt a payload produced by {@link encrypt} and JSON-parse the result. Throws
|
|
56
|
+
* {@link DecryptionError} on tamper or wrong key. The Laravel `Encrypter::decrypt()` equivalent.
|
|
57
|
+
*/
|
|
58
|
+
decrypt<T = unknown>(payload: string): T;
|
|
59
|
+
/**
|
|
60
|
+
* Encrypt a raw string without JSON-serializing it. The Laravel `Encrypter::encryptString()`
|
|
61
|
+
* equivalent — use when the plaintext is already a string and you want it back verbatim.
|
|
62
|
+
*/
|
|
63
|
+
encryptString(value: string): string;
|
|
64
|
+
/**
|
|
65
|
+
* Decrypt a raw-string payload produced by {@link encryptString}. Tries the current key first,
|
|
66
|
+
* then each previous key in order, and throws {@link DecryptionError} only once every key has
|
|
67
|
+
* failed (tamper, or no matching key). The Laravel `Encrypter::decryptString()` equivalent.
|
|
68
|
+
*/
|
|
69
|
+
decryptString(payload: string): string;
|
|
70
|
+
/** Decode and validate the base64 envelope, raising {@link DecryptionError} if it is malformed. */
|
|
71
|
+
private parse;
|
|
72
|
+
/**
|
|
73
|
+
* Constant-time equality for two strings, exposed for callers that need to compare opaque
|
|
74
|
+
* tokens without leaking length-independent timing. The Laravel `hash_equals()` analog.
|
|
75
|
+
*/
|
|
76
|
+
static hashEquals(a: string, b: string): boolean;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Tunable scrypt cost parameters. The Laravel hashing `options` (`rounds`/`memory`/`time`)
|
|
81
|
+
* equivalent, expressed in scrypt's own terms.
|
|
82
|
+
*/
|
|
83
|
+
interface HashOptions {
|
|
84
|
+
/** CPU/memory cost parameter `N`; must be a power of two. Default `16384` (2^14). */
|
|
85
|
+
cost?: number;
|
|
86
|
+
/** Block size `r`. Default `8`. */
|
|
87
|
+
blockSize?: number;
|
|
88
|
+
/** Parallelization `p`. Default `1`. */
|
|
89
|
+
parallelism?: number;
|
|
90
|
+
}
|
|
91
|
+
/** Thrown by {@link Hasher.info}-style parsing when a hash string is not in the expected format. */
|
|
92
|
+
declare class InvalidHashError extends Error {
|
|
93
|
+
readonly name = "InvalidHashError";
|
|
94
|
+
constructor(message?: string);
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Password hasher backed by scrypt. The Laravel `Hash` facade equivalent.
|
|
98
|
+
*/
|
|
99
|
+
declare class Hasher {
|
|
100
|
+
private readonly options;
|
|
101
|
+
/** @param options Default cost parameters applied when {@link make} is called without overrides. */
|
|
102
|
+
constructor(options?: HashOptions);
|
|
103
|
+
/**
|
|
104
|
+
* Hash a password with a fresh random 16-byte salt, returning a self-describing string of the
|
|
105
|
+
* form `scrypt$<N>$<r>$<p>$<saltB64>$<hashB64>`. The Laravel `Hash::make()` equivalent.
|
|
106
|
+
*/
|
|
107
|
+
make(password: string, options?: HashOptions): string;
|
|
108
|
+
/**
|
|
109
|
+
* Verify a password against a hash in constant time. Returns `false` for a wrong password or a
|
|
110
|
+
* malformed hash. The Laravel `Hash::check()` equivalent.
|
|
111
|
+
*/
|
|
112
|
+
check(password: string, hash: string): boolean;
|
|
113
|
+
/**
|
|
114
|
+
* Determine whether a hash should be re-computed because its cost parameters differ from the
|
|
115
|
+
* given (or default) options. The Laravel `Hash::needsRehash()` equivalent.
|
|
116
|
+
*/
|
|
117
|
+
needsRehash(hash: string, options?: HashOptions): boolean;
|
|
118
|
+
/**
|
|
119
|
+
* Extract the algorithm and cost parameters from a hash, or `null` if it is not a valid Mason
|
|
120
|
+
* scrypt hash. The Laravel `Hash::info()` equivalent.
|
|
121
|
+
*/
|
|
122
|
+
info(hash: string): {
|
|
123
|
+
algorithm: string;
|
|
124
|
+
options: HashOptions;
|
|
125
|
+
} | null;
|
|
126
|
+
/**
|
|
127
|
+
* Determine whether a value is already a Mason scrypt hash — i.e. it parses as the
|
|
128
|
+
* self-describing `scrypt$N$r$p$salt$hash` format with a non-empty salt and digest. The Laravel
|
|
129
|
+
* `Hash::isHashed()` equivalent.
|
|
130
|
+
*/
|
|
131
|
+
isHashed(value: string): boolean;
|
|
132
|
+
/**
|
|
133
|
+
* Verify that the given (or default) cost parameters are sane — `cost` a power of two greater
|
|
134
|
+
* than one, `blockSize`/`parallelism` positive integers — and that a test hash actually
|
|
135
|
+
* round-trips under them. The Laravel `Hash::verifyConfiguration()` equivalent.
|
|
136
|
+
*/
|
|
137
|
+
verifyConfiguration(options?: HashOptions): boolean;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* @plinthjs/encryption — authenticated encryption and password hashing over `node:crypto`.
|
|
142
|
+
*
|
|
143
|
+
* The Laravel `Illuminate\Encryption` + `Illuminate\Hashing` equivalent, with zero native
|
|
144
|
+
* dependencies: {@link Encrypter} uses AES-256-GCM, and {@link Hasher} uses scrypt (a built-in,
|
|
145
|
+
* memory-hard KDF standing in for bcrypt/argon2, which are native deps).
|
|
146
|
+
*/
|
|
147
|
+
declare const VERSION = "0.1.0";
|
|
148
|
+
|
|
149
|
+
export { DecryptionError, Encrypter, type HashOptions, Hasher, InvalidHashError, InvalidKeyError, VERSION };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thrown when a payload cannot be decrypted: a malformed envelope, the wrong key, or a tampered
|
|
3
|
+
* IV/tag/ciphertext (the auth tag fails to verify). The Laravel `DecryptException` equivalent.
|
|
4
|
+
*/
|
|
5
|
+
declare class DecryptionError extends Error {
|
|
6
|
+
readonly name = "DecryptionError";
|
|
7
|
+
constructor(message?: string);
|
|
8
|
+
}
|
|
9
|
+
/** Thrown when constructing an {@link Encrypter} with a key of the wrong length. */
|
|
10
|
+
declare class InvalidKeyError extends Error {
|
|
11
|
+
readonly name = "InvalidKeyError";
|
|
12
|
+
constructor(message?: string);
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Authenticated AES-256-GCM encrypter. The Laravel `Illuminate\Encryption\Encrypter` equivalent.
|
|
16
|
+
*/
|
|
17
|
+
declare class Encrypter {
|
|
18
|
+
private readonly key;
|
|
19
|
+
private readonly previousKeys;
|
|
20
|
+
/**
|
|
21
|
+
* @param key A 32-byte key, either a raw `Buffer`, a 32-byte UTF-8 string, or a
|
|
22
|
+
* `base64:<...>` string (the Laravel `APP_KEY` convention). Throws {@link InvalidKeyError}
|
|
23
|
+
* if it does not decode to exactly 32 bytes.
|
|
24
|
+
* @param previousKeys Rotated-out keys (same accepted formats) that {@link decrypt} /
|
|
25
|
+
* {@link decryptString} fall back to, in order, when the current key fails. The Laravel
|
|
26
|
+
* `APP_PREVIOUS_KEYS` equivalent. Each must also decode to exactly 32 bytes.
|
|
27
|
+
*/
|
|
28
|
+
constructor(key: Buffer | string, previousKeys?: readonly (Buffer | string)[]);
|
|
29
|
+
/**
|
|
30
|
+
* Return a new `Encrypter` with the same current key and the given previous keys. The Laravel
|
|
31
|
+
* `Encrypter::previousKeys()` equivalent, expressed immutably in Mason's `with*` style.
|
|
32
|
+
*/
|
|
33
|
+
withPreviousKeys(keys: readonly (Buffer | string)[]): Encrypter;
|
|
34
|
+
/** The current encryption key. The Laravel `Encrypter::getKey()` equivalent. */
|
|
35
|
+
getKey(): Buffer;
|
|
36
|
+
/**
|
|
37
|
+
* The current key followed by every previous key, in fallback order. The Laravel
|
|
38
|
+
* `Encrypter::getAllKeys()` equivalent.
|
|
39
|
+
*/
|
|
40
|
+
getAllKeys(): Buffer[];
|
|
41
|
+
/** The previous (rotated-out) keys. The Laravel `Encrypter::getPreviousKeys()` equivalent. */
|
|
42
|
+
getPreviousKeys(): Buffer[];
|
|
43
|
+
/** Generate a fresh 32-byte key. The Laravel `Encrypter::generateKey()` equivalent. */
|
|
44
|
+
static generateKey(): Buffer;
|
|
45
|
+
/** Generate a fresh key as a `base64:<...>` string, ready to drop into config. */
|
|
46
|
+
static generateKeyBase64(): string;
|
|
47
|
+
/** True if `key` is a valid 32-byte key (raw, utf-8, or `base64:`-prefixed). */
|
|
48
|
+
static supported(key: Buffer | string): boolean;
|
|
49
|
+
/**
|
|
50
|
+
* JSON-serialize and encrypt a value. Returns a base64-encoded envelope containing the random
|
|
51
|
+
* IV, the GCM auth tag, and the ciphertext. The Laravel `Encrypter::encrypt()` equivalent.
|
|
52
|
+
*/
|
|
53
|
+
encrypt(value: unknown): string;
|
|
54
|
+
/**
|
|
55
|
+
* Decrypt a payload produced by {@link encrypt} and JSON-parse the result. Throws
|
|
56
|
+
* {@link DecryptionError} on tamper or wrong key. The Laravel `Encrypter::decrypt()` equivalent.
|
|
57
|
+
*/
|
|
58
|
+
decrypt<T = unknown>(payload: string): T;
|
|
59
|
+
/**
|
|
60
|
+
* Encrypt a raw string without JSON-serializing it. The Laravel `Encrypter::encryptString()`
|
|
61
|
+
* equivalent — use when the plaintext is already a string and you want it back verbatim.
|
|
62
|
+
*/
|
|
63
|
+
encryptString(value: string): string;
|
|
64
|
+
/**
|
|
65
|
+
* Decrypt a raw-string payload produced by {@link encryptString}. Tries the current key first,
|
|
66
|
+
* then each previous key in order, and throws {@link DecryptionError} only once every key has
|
|
67
|
+
* failed (tamper, or no matching key). The Laravel `Encrypter::decryptString()` equivalent.
|
|
68
|
+
*/
|
|
69
|
+
decryptString(payload: string): string;
|
|
70
|
+
/** Decode and validate the base64 envelope, raising {@link DecryptionError} if it is malformed. */
|
|
71
|
+
private parse;
|
|
72
|
+
/**
|
|
73
|
+
* Constant-time equality for two strings, exposed for callers that need to compare opaque
|
|
74
|
+
* tokens without leaking length-independent timing. The Laravel `hash_equals()` analog.
|
|
75
|
+
*/
|
|
76
|
+
static hashEquals(a: string, b: string): boolean;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Tunable scrypt cost parameters. The Laravel hashing `options` (`rounds`/`memory`/`time`)
|
|
81
|
+
* equivalent, expressed in scrypt's own terms.
|
|
82
|
+
*/
|
|
83
|
+
interface HashOptions {
|
|
84
|
+
/** CPU/memory cost parameter `N`; must be a power of two. Default `16384` (2^14). */
|
|
85
|
+
cost?: number;
|
|
86
|
+
/** Block size `r`. Default `8`. */
|
|
87
|
+
blockSize?: number;
|
|
88
|
+
/** Parallelization `p`. Default `1`. */
|
|
89
|
+
parallelism?: number;
|
|
90
|
+
}
|
|
91
|
+
/** Thrown by {@link Hasher.info}-style parsing when a hash string is not in the expected format. */
|
|
92
|
+
declare class InvalidHashError extends Error {
|
|
93
|
+
readonly name = "InvalidHashError";
|
|
94
|
+
constructor(message?: string);
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Password hasher backed by scrypt. The Laravel `Hash` facade equivalent.
|
|
98
|
+
*/
|
|
99
|
+
declare class Hasher {
|
|
100
|
+
private readonly options;
|
|
101
|
+
/** @param options Default cost parameters applied when {@link make} is called without overrides. */
|
|
102
|
+
constructor(options?: HashOptions);
|
|
103
|
+
/**
|
|
104
|
+
* Hash a password with a fresh random 16-byte salt, returning a self-describing string of the
|
|
105
|
+
* form `scrypt$<N>$<r>$<p>$<saltB64>$<hashB64>`. The Laravel `Hash::make()` equivalent.
|
|
106
|
+
*/
|
|
107
|
+
make(password: string, options?: HashOptions): string;
|
|
108
|
+
/**
|
|
109
|
+
* Verify a password against a hash in constant time. Returns `false` for a wrong password or a
|
|
110
|
+
* malformed hash. The Laravel `Hash::check()` equivalent.
|
|
111
|
+
*/
|
|
112
|
+
check(password: string, hash: string): boolean;
|
|
113
|
+
/**
|
|
114
|
+
* Determine whether a hash should be re-computed because its cost parameters differ from the
|
|
115
|
+
* given (or default) options. The Laravel `Hash::needsRehash()` equivalent.
|
|
116
|
+
*/
|
|
117
|
+
needsRehash(hash: string, options?: HashOptions): boolean;
|
|
118
|
+
/**
|
|
119
|
+
* Extract the algorithm and cost parameters from a hash, or `null` if it is not a valid Mason
|
|
120
|
+
* scrypt hash. The Laravel `Hash::info()` equivalent.
|
|
121
|
+
*/
|
|
122
|
+
info(hash: string): {
|
|
123
|
+
algorithm: string;
|
|
124
|
+
options: HashOptions;
|
|
125
|
+
} | null;
|
|
126
|
+
/**
|
|
127
|
+
* Determine whether a value is already a Mason scrypt hash — i.e. it parses as the
|
|
128
|
+
* self-describing `scrypt$N$r$p$salt$hash` format with a non-empty salt and digest. The Laravel
|
|
129
|
+
* `Hash::isHashed()` equivalent.
|
|
130
|
+
*/
|
|
131
|
+
isHashed(value: string): boolean;
|
|
132
|
+
/**
|
|
133
|
+
* Verify that the given (or default) cost parameters are sane — `cost` a power of two greater
|
|
134
|
+
* than one, `blockSize`/`parallelism` positive integers — and that a test hash actually
|
|
135
|
+
* round-trips under them. The Laravel `Hash::verifyConfiguration()` equivalent.
|
|
136
|
+
*/
|
|
137
|
+
verifyConfiguration(options?: HashOptions): boolean;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* @plinthjs/encryption — authenticated encryption and password hashing over `node:crypto`.
|
|
142
|
+
*
|
|
143
|
+
* The Laravel `Illuminate\Encryption` + `Illuminate\Hashing` equivalent, with zero native
|
|
144
|
+
* dependencies: {@link Encrypter} uses AES-256-GCM, and {@link Hasher} uses scrypt (a built-in,
|
|
145
|
+
* memory-hard KDF standing in for bcrypt/argon2, which are native deps).
|
|
146
|
+
*/
|
|
147
|
+
declare const VERSION = "0.1.0";
|
|
148
|
+
|
|
149
|
+
export { DecryptionError, Encrypter, type HashOptions, Hasher, InvalidHashError, InvalidKeyError, VERSION };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
import { randomBytes, createCipheriv, createDecipheriv, timingSafeEqual, scryptSync } from 'crypto';
|
|
2
|
+
|
|
3
|
+
// src/encrypter.ts
|
|
4
|
+
var CIPHER = "aes-256-gcm";
|
|
5
|
+
var KEY_BYTES = 32;
|
|
6
|
+
var IV_BYTES = 12;
|
|
7
|
+
var TAG_BYTES = 16;
|
|
8
|
+
var BASE64_PREFIX = "base64:";
|
|
9
|
+
var DecryptionError = class extends Error {
|
|
10
|
+
name = "DecryptionError";
|
|
11
|
+
constructor(message = "The payload is invalid or could not be authenticated.") {
|
|
12
|
+
super(message);
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
var InvalidKeyError = class extends Error {
|
|
16
|
+
name = "InvalidKeyError";
|
|
17
|
+
constructor(message = `Encryption key must be ${KEY_BYTES} bytes for AES-256-GCM.`) {
|
|
18
|
+
super(message);
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
function normalizeKey(key) {
|
|
22
|
+
const buffer = typeof key === "string" ? key.startsWith(BASE64_PREFIX) ? Buffer.from(key.slice(BASE64_PREFIX.length), "base64") : Buffer.from(key, "utf8") : Buffer.from(key);
|
|
23
|
+
if (buffer.length !== KEY_BYTES) {
|
|
24
|
+
throw new InvalidKeyError();
|
|
25
|
+
}
|
|
26
|
+
return buffer;
|
|
27
|
+
}
|
|
28
|
+
var Encrypter = class _Encrypter {
|
|
29
|
+
key;
|
|
30
|
+
previousKeys;
|
|
31
|
+
/**
|
|
32
|
+
* @param key A 32-byte key, either a raw `Buffer`, a 32-byte UTF-8 string, or a
|
|
33
|
+
* `base64:<...>` string (the Laravel `APP_KEY` convention). Throws {@link InvalidKeyError}
|
|
34
|
+
* if it does not decode to exactly 32 bytes.
|
|
35
|
+
* @param previousKeys Rotated-out keys (same accepted formats) that {@link decrypt} /
|
|
36
|
+
* {@link decryptString} fall back to, in order, when the current key fails. The Laravel
|
|
37
|
+
* `APP_PREVIOUS_KEYS` equivalent. Each must also decode to exactly 32 bytes.
|
|
38
|
+
*/
|
|
39
|
+
constructor(key, previousKeys = []) {
|
|
40
|
+
this.key = normalizeKey(key);
|
|
41
|
+
this.previousKeys = previousKeys.map((previous) => normalizeKey(previous));
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Return a new `Encrypter` with the same current key and the given previous keys. The Laravel
|
|
45
|
+
* `Encrypter::previousKeys()` equivalent, expressed immutably in Mason's `with*` style.
|
|
46
|
+
*/
|
|
47
|
+
withPreviousKeys(keys) {
|
|
48
|
+
return new _Encrypter(this.key, keys);
|
|
49
|
+
}
|
|
50
|
+
/** The current encryption key. The Laravel `Encrypter::getKey()` equivalent. */
|
|
51
|
+
getKey() {
|
|
52
|
+
return Buffer.from(this.key);
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* The current key followed by every previous key, in fallback order. The Laravel
|
|
56
|
+
* `Encrypter::getAllKeys()` equivalent.
|
|
57
|
+
*/
|
|
58
|
+
getAllKeys() {
|
|
59
|
+
return [this.key, ...this.previousKeys].map((key) => Buffer.from(key));
|
|
60
|
+
}
|
|
61
|
+
/** The previous (rotated-out) keys. The Laravel `Encrypter::getPreviousKeys()` equivalent. */
|
|
62
|
+
getPreviousKeys() {
|
|
63
|
+
return this.previousKeys.map((key) => Buffer.from(key));
|
|
64
|
+
}
|
|
65
|
+
/** Generate a fresh 32-byte key. The Laravel `Encrypter::generateKey()` equivalent. */
|
|
66
|
+
static generateKey() {
|
|
67
|
+
return randomBytes(KEY_BYTES);
|
|
68
|
+
}
|
|
69
|
+
/** Generate a fresh key as a `base64:<...>` string, ready to drop into config. */
|
|
70
|
+
static generateKeyBase64() {
|
|
71
|
+
return `${BASE64_PREFIX}${_Encrypter.generateKey().toString("base64")}`;
|
|
72
|
+
}
|
|
73
|
+
/** True if `key` is a valid 32-byte key (raw, utf-8, or `base64:`-prefixed). */
|
|
74
|
+
static supported(key) {
|
|
75
|
+
try {
|
|
76
|
+
normalizeKey(key);
|
|
77
|
+
return true;
|
|
78
|
+
} catch {
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* JSON-serialize and encrypt a value. Returns a base64-encoded envelope containing the random
|
|
84
|
+
* IV, the GCM auth tag, and the ciphertext. The Laravel `Encrypter::encrypt()` equivalent.
|
|
85
|
+
*/
|
|
86
|
+
encrypt(value) {
|
|
87
|
+
return this.encryptString(JSON.stringify(value));
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Decrypt a payload produced by {@link encrypt} and JSON-parse the result. Throws
|
|
91
|
+
* {@link DecryptionError} on tamper or wrong key. The Laravel `Encrypter::decrypt()` equivalent.
|
|
92
|
+
*/
|
|
93
|
+
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- T is the caller-supplied cast type for the deserialized value; removing it loses call-site inference
|
|
94
|
+
decrypt(payload) {
|
|
95
|
+
return JSON.parse(this.decryptString(payload));
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Encrypt a raw string without JSON-serializing it. The Laravel `Encrypter::encryptString()`
|
|
99
|
+
* equivalent — use when the plaintext is already a string and you want it back verbatim.
|
|
100
|
+
*/
|
|
101
|
+
encryptString(value) {
|
|
102
|
+
const iv = randomBytes(IV_BYTES);
|
|
103
|
+
const cipher = createCipheriv(CIPHER, this.key, iv, { authTagLength: TAG_BYTES });
|
|
104
|
+
const ciphertext = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
|
|
105
|
+
const tag = cipher.getAuthTag();
|
|
106
|
+
const envelope = {
|
|
107
|
+
iv: iv.toString("base64"),
|
|
108
|
+
tag: tag.toString("base64"),
|
|
109
|
+
ciphertext: ciphertext.toString("base64")
|
|
110
|
+
};
|
|
111
|
+
return Buffer.from(JSON.stringify(envelope), "utf8").toString("base64");
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Decrypt a raw-string payload produced by {@link encryptString}. Tries the current key first,
|
|
115
|
+
* then each previous key in order, and throws {@link DecryptionError} only once every key has
|
|
116
|
+
* failed (tamper, or no matching key). The Laravel `Encrypter::decryptString()` equivalent.
|
|
117
|
+
*/
|
|
118
|
+
decryptString(payload) {
|
|
119
|
+
const envelope = this.parse(payload);
|
|
120
|
+
const iv = Buffer.from(envelope.iv, "base64");
|
|
121
|
+
const tag = Buffer.from(envelope.tag, "base64");
|
|
122
|
+
const ciphertext = Buffer.from(envelope.ciphertext, "base64");
|
|
123
|
+
if (iv.length !== IV_BYTES || tag.length !== TAG_BYTES) {
|
|
124
|
+
throw new DecryptionError();
|
|
125
|
+
}
|
|
126
|
+
for (const key of [this.key, ...this.previousKeys]) {
|
|
127
|
+
try {
|
|
128
|
+
const decipher = createDecipheriv(CIPHER, key, iv, { authTagLength: TAG_BYTES });
|
|
129
|
+
decipher.setAuthTag(tag);
|
|
130
|
+
const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
|
|
131
|
+
return plaintext.toString("utf8");
|
|
132
|
+
} catch {
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
throw new DecryptionError();
|
|
136
|
+
}
|
|
137
|
+
/** Decode and validate the base64 envelope, raising {@link DecryptionError} if it is malformed. */
|
|
138
|
+
parse(payload) {
|
|
139
|
+
let decoded;
|
|
140
|
+
try {
|
|
141
|
+
decoded = JSON.parse(Buffer.from(payload, "base64").toString("utf8"));
|
|
142
|
+
} catch {
|
|
143
|
+
throw new DecryptionError();
|
|
144
|
+
}
|
|
145
|
+
if (!isEnvelope(decoded)) {
|
|
146
|
+
throw new DecryptionError();
|
|
147
|
+
}
|
|
148
|
+
return decoded;
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Constant-time equality for two strings, exposed for callers that need to compare opaque
|
|
152
|
+
* tokens without leaking length-independent timing. The Laravel `hash_equals()` analog.
|
|
153
|
+
*/
|
|
154
|
+
static hashEquals(a, b) {
|
|
155
|
+
const left = Buffer.from(a, "utf8");
|
|
156
|
+
const right = Buffer.from(b, "utf8");
|
|
157
|
+
if (left.length !== right.length) return false;
|
|
158
|
+
return timingSafeEqual(left, right);
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
function isEnvelope(value) {
|
|
162
|
+
if (value === null || typeof value !== "object") return false;
|
|
163
|
+
const record = value;
|
|
164
|
+
return typeof record["iv"] === "string" && typeof record["tag"] === "string" && typeof record["ciphertext"] === "string";
|
|
165
|
+
}
|
|
166
|
+
var ALGORITHM = "scrypt";
|
|
167
|
+
var SEPARATOR = "$";
|
|
168
|
+
var SALT_BYTES = 16;
|
|
169
|
+
var KEY_LENGTH = 64;
|
|
170
|
+
var DEFAULTS = { cost: 16384, blockSize: 8, parallelism: 1 };
|
|
171
|
+
function maxmem(opts) {
|
|
172
|
+
return 256 * opts.cost * opts.blockSize + 1024 * 1024;
|
|
173
|
+
}
|
|
174
|
+
function resolve(options) {
|
|
175
|
+
return {
|
|
176
|
+
cost: options?.cost ?? DEFAULTS.cost,
|
|
177
|
+
blockSize: options?.blockSize ?? DEFAULTS.blockSize,
|
|
178
|
+
parallelism: options?.parallelism ?? DEFAULTS.parallelism
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
var InvalidHashError = class extends Error {
|
|
182
|
+
name = "InvalidHashError";
|
|
183
|
+
constructor(message = "The given hash is not a valid Mason scrypt hash.") {
|
|
184
|
+
super(message);
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
function parse(hash) {
|
|
188
|
+
const parts = hash.split(SEPARATOR);
|
|
189
|
+
if (parts.length !== 6) return null;
|
|
190
|
+
const [algorithm, nRaw, rRaw, pRaw, saltB64, hashB64] = parts;
|
|
191
|
+
if (algorithm !== ALGORITHM) return null;
|
|
192
|
+
const cost = Number(nRaw);
|
|
193
|
+
const blockSize = Number(rRaw);
|
|
194
|
+
const parallelism = Number(pRaw);
|
|
195
|
+
if (!Number.isInteger(cost) || !Number.isInteger(blockSize) || !Number.isInteger(parallelism)) {
|
|
196
|
+
return null;
|
|
197
|
+
}
|
|
198
|
+
if (cost <= 0 || blockSize <= 0 || parallelism <= 0) return null;
|
|
199
|
+
return {
|
|
200
|
+
algorithm,
|
|
201
|
+
options: { cost, blockSize, parallelism },
|
|
202
|
+
salt: Buffer.from(saltB64, "base64"),
|
|
203
|
+
hash: Buffer.from(hashB64, "base64")
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
var Hasher = class {
|
|
207
|
+
options;
|
|
208
|
+
/** @param options Default cost parameters applied when {@link make} is called without overrides. */
|
|
209
|
+
constructor(options) {
|
|
210
|
+
this.options = resolve(options);
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Hash a password with a fresh random 16-byte salt, returning a self-describing string of the
|
|
214
|
+
* form `scrypt$<N>$<r>$<p>$<saltB64>$<hashB64>`. The Laravel `Hash::make()` equivalent.
|
|
215
|
+
*/
|
|
216
|
+
make(password, options) {
|
|
217
|
+
const opts = options ? resolve(options) : this.options;
|
|
218
|
+
const salt = randomBytes(SALT_BYTES);
|
|
219
|
+
const derived = scryptSync(password, salt, KEY_LENGTH, {
|
|
220
|
+
N: opts.cost,
|
|
221
|
+
r: opts.blockSize,
|
|
222
|
+
p: opts.parallelism,
|
|
223
|
+
maxmem: maxmem(opts)
|
|
224
|
+
});
|
|
225
|
+
return [
|
|
226
|
+
ALGORITHM,
|
|
227
|
+
opts.cost,
|
|
228
|
+
opts.blockSize,
|
|
229
|
+
opts.parallelism,
|
|
230
|
+
salt.toString("base64"),
|
|
231
|
+
derived.toString("base64")
|
|
232
|
+
].join(SEPARATOR);
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Verify a password against a hash in constant time. Returns `false` for a wrong password or a
|
|
236
|
+
* malformed hash. The Laravel `Hash::check()` equivalent.
|
|
237
|
+
*/
|
|
238
|
+
check(password, hash) {
|
|
239
|
+
const parsed = parse(hash);
|
|
240
|
+
if (parsed === null || parsed.hash.length === 0) return false;
|
|
241
|
+
let computed;
|
|
242
|
+
try {
|
|
243
|
+
computed = scryptSync(password, parsed.salt, parsed.hash.length, {
|
|
244
|
+
N: parsed.options.cost,
|
|
245
|
+
r: parsed.options.blockSize,
|
|
246
|
+
p: parsed.options.parallelism,
|
|
247
|
+
maxmem: maxmem(parsed.options)
|
|
248
|
+
});
|
|
249
|
+
} catch {
|
|
250
|
+
return false;
|
|
251
|
+
}
|
|
252
|
+
if (computed.length !== parsed.hash.length) return false;
|
|
253
|
+
return timingSafeEqual(computed, parsed.hash);
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Determine whether a hash should be re-computed because its cost parameters differ from the
|
|
257
|
+
* given (or default) options. The Laravel `Hash::needsRehash()` equivalent.
|
|
258
|
+
*/
|
|
259
|
+
needsRehash(hash, options) {
|
|
260
|
+
const parsed = parse(hash);
|
|
261
|
+
if (parsed === null) return true;
|
|
262
|
+
const target = options ? resolve(options) : this.options;
|
|
263
|
+
return parsed.options.cost !== target.cost || parsed.options.blockSize !== target.blockSize || parsed.options.parallelism !== target.parallelism;
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* Extract the algorithm and cost parameters from a hash, or `null` if it is not a valid Mason
|
|
267
|
+
* scrypt hash. The Laravel `Hash::info()` equivalent.
|
|
268
|
+
*/
|
|
269
|
+
info(hash) {
|
|
270
|
+
const parsed = parse(hash);
|
|
271
|
+
if (parsed === null) return null;
|
|
272
|
+
return { algorithm: parsed.algorithm, options: { ...parsed.options } };
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Determine whether a value is already a Mason scrypt hash — i.e. it parses as the
|
|
276
|
+
* self-describing `scrypt$N$r$p$salt$hash` format with a non-empty salt and digest. The Laravel
|
|
277
|
+
* `Hash::isHashed()` equivalent.
|
|
278
|
+
*/
|
|
279
|
+
isHashed(value) {
|
|
280
|
+
const parsed = parse(value);
|
|
281
|
+
return parsed !== null && parsed.salt.length > 0 && parsed.hash.length > 0;
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Verify that the given (or default) cost parameters are sane — `cost` a power of two greater
|
|
285
|
+
* than one, `blockSize`/`parallelism` positive integers — and that a test hash actually
|
|
286
|
+
* round-trips under them. The Laravel `Hash::verifyConfiguration()` equivalent.
|
|
287
|
+
*/
|
|
288
|
+
verifyConfiguration(options) {
|
|
289
|
+
const opts = options ? resolve(options) : this.options;
|
|
290
|
+
if (!isPowerOfTwo(opts.cost) || opts.cost < 2) return false;
|
|
291
|
+
if (!Number.isInteger(opts.blockSize) || opts.blockSize < 1) return false;
|
|
292
|
+
if (!Number.isInteger(opts.parallelism) || opts.parallelism < 1) return false;
|
|
293
|
+
try {
|
|
294
|
+
const probe = "mason-verify-configuration";
|
|
295
|
+
return this.check(probe, this.make(probe, opts));
|
|
296
|
+
} catch {
|
|
297
|
+
return false;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
};
|
|
301
|
+
function isPowerOfTwo(value) {
|
|
302
|
+
return Number.isInteger(value) && value >= 1 && Number.isInteger(Math.log2(value));
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// src/index.ts
|
|
306
|
+
var VERSION = "0.1.0";
|
|
307
|
+
|
|
308
|
+
export { DecryptionError, Encrypter, Hasher, InvalidHashError, InvalidKeyError, VERSION };
|
|
309
|
+
//# sourceMappingURL=index.js.map
|
|
310
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/encrypter.ts","../src/hasher.ts","../src/index.ts"],"names":["randomBytes","timingSafeEqual"],"mappings":";;;AASA,IAAM,MAAA,GAAS,aAAA;AAEf,IAAM,SAAA,GAAY,EAAA;AAElB,IAAM,QAAA,GAAW,EAAA;AAEjB,IAAM,SAAA,GAAY,EAAA;AAElB,IAAM,aAAA,GAAgB,SAAA;AAmBf,IAAM,eAAA,GAAN,cAA8B,KAAA,CAAM;AAAA,EACvB,IAAA,GAAO,iBAAA;AAAA,EAEzB,WAAA,CAAY,UAAU,uDAAA,EAAyD;AAC7E,IAAA,KAAA,CAAM,OAAO,CAAA;AAAA,EACf;AACF;AAGO,IAAM,eAAA,GAAN,cAA8B,KAAA,CAAM;AAAA,EACvB,IAAA,GAAO,iBAAA;AAAA,EAEzB,WAAA,CAAY,OAAA,GAAU,CAAA,uBAAA,EAA0B,SAAS,CAAA,uBAAA,CAAA,EAA2B;AAClF,IAAA,KAAA,CAAM,OAAO,CAAA;AAAA,EACf;AACF;AAGA,SAAS,aAAa,GAAA,EAA8B;AAClD,EAAA,MAAM,MAAA,GACJ,OAAO,GAAA,KAAQ,QAAA,GACX,GAAA,CAAI,WAAW,aAAa,CAAA,GAC1B,MAAA,CAAO,IAAA,CAAK,GAAA,CAAI,KAAA,CAAM,cAAc,MAAM,CAAA,EAAG,QAAQ,CAAA,GACrD,MAAA,CAAO,IAAA,CAAK,KAAK,MAAM,CAAA,GAC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,CAAK,KAAA,EAAO,IAAI,CAAC,CAAA;AAAA,IACjD,CAAA,CAAA,MAAQ;AACN,MAAA,OAAO,KAAA;AAAA,IACT;AAAA,EACF;AACF;AAGA,SAAS,aAAa,KAAA,EAAwB;AAC5C,EAAA,OAAO,MAAA,CAAO,SAAA,CAAU,KAAK,CAAA,IAAK,KAAA,IAAS,CAAA,IAAK,MAAA,CAAO,SAAA,CAAU,IAAA,CAAK,IAAA,CAAK,KAAK,CAAC,CAAA;AACnF;;;ACvNO,IAAM,OAAA,GAAU","file":"index.js","sourcesContent":["/**\n * `Encrypter` — authenticated symmetric encryption over `node:crypto`.\n * The Laravel `Illuminate\\Encryption\\Encrypter` equivalent: a 32-byte application key,\n * AES-256-GCM with a random IV, and an authentication tag verified on decrypt. Values are\n * JSON-serialized before encryption and revived afterwards, so any JSON-safe value round-trips.\n */\nimport { createCipheriv, createDecipheriv, randomBytes, timingSafeEqual } from 'node:crypto'\n\n/** The cipher Mason uses. AES-256-GCM gives confidentiality plus a built-in auth tag (AEAD). */\nconst CIPHER = 'aes-256-gcm'\n/** Required key length for AES-256, in bytes. */\nconst KEY_BYTES = 32\n/** Recommended GCM IV length, in bytes. */\nconst IV_BYTES = 12\n/** GCM authentication tag length, in bytes. */\nconst TAG_BYTES = 16\n/** Prefix used by `base64:`-encoded keys — the Laravel `APP_KEY` convention. */\nconst BASE64_PREFIX = 'base64:'\n\n/**\n * The on-the-wire shape of an encrypted payload, before base64-wrapping. Mirrors Laravel's\n * `{ iv, value, mac }` envelope, adapted to GCM (the auth tag replaces a separate HMAC).\n */\ninterface EncryptedEnvelope {\n /** Base64 initialization vector. */\n iv: string\n /** Base64 GCM authentication tag. */\n tag: string\n /** Base64 ciphertext. */\n ciphertext: string\n}\n\n/**\n * Thrown when a payload cannot be decrypted: a malformed envelope, the wrong key, or a tampered\n * IV/tag/ciphertext (the auth tag fails to verify). The Laravel `DecryptException` equivalent.\n */\nexport class DecryptionError extends Error {\n override readonly name = 'DecryptionError'\n\n constructor(message = 'The payload is invalid or could not be authenticated.') {\n super(message)\n }\n}\n\n/** Thrown when constructing an {@link Encrypter} with a key of the wrong length. */\nexport class InvalidKeyError extends Error {\n override readonly name = 'InvalidKeyError'\n\n constructor(message = `Encryption key must be ${KEY_BYTES} bytes for AES-256-GCM.`) {\n super(message)\n }\n}\n\n/** Normalize a `Buffer | string` key into a validated 32-byte Buffer. */\nfunction normalizeKey(key: Buffer | string): Buffer {\n const buffer =\n typeof key === 'string'\n ? key.startsWith(BASE64_PREFIX)\n ? Buffer.from(key.slice(BASE64_PREFIX.length), 'base64')\n : Buffer.from(key, 'utf8')\n : Buffer.from(key)\n\n if (buffer.length !== KEY_BYTES) {\n throw new InvalidKeyError()\n }\n return buffer\n}\n\n/**\n * Authenticated AES-256-GCM encrypter. The Laravel `Illuminate\\Encryption\\Encrypter` equivalent.\n */\nexport class Encrypter {\n private readonly key: Buffer\n\n private readonly previousKeys: readonly Buffer[]\n\n /**\n * @param key A 32-byte key, either a raw `Buffer`, a 32-byte UTF-8 string, or a\n * `base64:<...>` string (the Laravel `APP_KEY` convention). Throws {@link InvalidKeyError}\n * if it does not decode to exactly 32 bytes.\n * @param previousKeys Rotated-out keys (same accepted formats) that {@link decrypt} /\n * {@link decryptString} fall back to, in order, when the current key fails. The Laravel\n * `APP_PREVIOUS_KEYS` equivalent. Each must also decode to exactly 32 bytes.\n */\n constructor(key: Buffer | string, previousKeys: readonly (Buffer | string)[] = []) {\n this.key = normalizeKey(key)\n this.previousKeys = previousKeys.map((previous) => normalizeKey(previous))\n }\n\n /**\n * Return a new `Encrypter` with the same current key and the given previous keys. The Laravel\n * `Encrypter::previousKeys()` equivalent, expressed immutably in Mason's `with*` style.\n */\n withPreviousKeys(keys: readonly (Buffer | string)[]): Encrypter {\n return new Encrypter(this.key, keys)\n }\n\n /** The current encryption key. The Laravel `Encrypter::getKey()` equivalent. */\n getKey(): Buffer {\n return Buffer.from(this.key)\n }\n\n /**\n * The current key followed by every previous key, in fallback order. The Laravel\n * `Encrypter::getAllKeys()` equivalent.\n */\n getAllKeys(): Buffer[] {\n return [this.key, ...this.previousKeys].map((key) => Buffer.from(key))\n }\n\n /** The previous (rotated-out) keys. The Laravel `Encrypter::getPreviousKeys()` equivalent. */\n getPreviousKeys(): Buffer[] {\n return this.previousKeys.map((key) => Buffer.from(key))\n }\n\n /** Generate a fresh 32-byte key. The Laravel `Encrypter::generateKey()` equivalent. */\n static generateKey(): Buffer {\n return randomBytes(KEY_BYTES)\n }\n\n /** Generate a fresh key as a `base64:<...>` string, ready to drop into config. */\n static generateKeyBase64(): string {\n return `${BASE64_PREFIX}${Encrypter.generateKey().toString('base64')}`\n }\n\n /** True if `key` is a valid 32-byte key (raw, utf-8, or `base64:`-prefixed). */\n static supported(key: Buffer | string): boolean {\n try {\n normalizeKey(key)\n return true\n } catch {\n return false\n }\n }\n\n /**\n * JSON-serialize and encrypt a value. Returns a base64-encoded envelope containing the random\n * IV, the GCM auth tag, and the ciphertext. The Laravel `Encrypter::encrypt()` equivalent.\n */\n encrypt(value: unknown): string {\n return this.encryptString(JSON.stringify(value))\n }\n\n /**\n * Decrypt a payload produced by {@link encrypt} and JSON-parse the result. Throws\n * {@link DecryptionError} on tamper or wrong key. The Laravel `Encrypter::decrypt()` equivalent.\n */\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- T is the caller-supplied cast type for the deserialized value; removing it loses call-site inference\n decrypt<T = unknown>(payload: string): T {\n return JSON.parse(this.decryptString(payload)) as T\n }\n\n /**\n * Encrypt a raw string without JSON-serializing it. The Laravel `Encrypter::encryptString()`\n * equivalent — use when the plaintext is already a string and you want it back verbatim.\n */\n encryptString(value: string): string {\n const iv = randomBytes(IV_BYTES)\n const cipher = createCipheriv(CIPHER, this.key, iv, { authTagLength: TAG_BYTES })\n const ciphertext = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()])\n const tag = cipher.getAuthTag()\n\n const envelope: EncryptedEnvelope = {\n iv: iv.toString('base64'),\n tag: tag.toString('base64'),\n ciphertext: ciphertext.toString('base64'),\n }\n return Buffer.from(JSON.stringify(envelope), 'utf8').toString('base64')\n }\n\n /**\n * Decrypt a raw-string payload produced by {@link encryptString}. Tries the current key first,\n * then each previous key in order, and throws {@link DecryptionError} only once every key has\n * failed (tamper, or no matching key). The Laravel `Encrypter::decryptString()` equivalent.\n */\n decryptString(payload: string): string {\n const envelope = this.parse(payload)\n const iv = Buffer.from(envelope.iv, 'base64')\n const tag = Buffer.from(envelope.tag, 'base64')\n const ciphertext = Buffer.from(envelope.ciphertext, 'base64')\n\n if (iv.length !== IV_BYTES || tag.length !== TAG_BYTES) {\n throw new DecryptionError()\n }\n\n for (const key of [this.key, ...this.previousKeys]) {\n try {\n const decipher = createDecipheriv(CIPHER, key, iv, { authTagLength: TAG_BYTES })\n decipher.setAuthTag(tag)\n const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()])\n return plaintext.toString('utf8')\n } catch {\n // A bad key or tampered ciphertext/tag fails the GCM tag check in `final()`;\n // fall through to the next rotated-out key.\n }\n }\n throw new DecryptionError()\n }\n\n /** Decode and validate the base64 envelope, raising {@link DecryptionError} if it is malformed. */\n private parse(payload: string): EncryptedEnvelope {\n let decoded: unknown\n try {\n decoded = JSON.parse(Buffer.from(payload, 'base64').toString('utf8'))\n } catch {\n throw new DecryptionError()\n }\n\n if (!isEnvelope(decoded)) {\n throw new DecryptionError()\n }\n return decoded\n }\n\n /**\n * Constant-time equality for two strings, exposed for callers that need to compare opaque\n * tokens without leaking length-independent timing. The Laravel `hash_equals()` analog.\n */\n static hashEquals(a: string, b: string): boolean {\n const left = Buffer.from(a, 'utf8')\n const right = Buffer.from(b, 'utf8')\n if (left.length !== right.length) return false\n return timingSafeEqual(left, right)\n }\n}\n\n/** Structural guard for a decoded envelope — all three fields must be present strings. */\nfunction isEnvelope(value: unknown): value is EncryptedEnvelope {\n if (value === null || typeof value !== 'object') return false\n const record = value as Record<string, unknown>\n return (\n typeof record['iv'] === 'string' &&\n typeof record['tag'] === 'string' &&\n typeof record['ciphertext'] === 'string'\n )\n}\n","/**\n * `Hasher` — password hashing over `node:crypto`'s `scryptSync`.\n * The Laravel `Illuminate\\Hashing\\HashManager` / `Hash` facade equivalent.\n *\n * NOTE ON ALGORITHM: Laravel defaults to bcrypt and offers argon2i/argon2id. Both are native\n * dependencies in Node. To keep Mason dependency-free, this port uses scrypt — a memory-hard\n * KDF built into `node:crypto`. It is a standardized, well-regarded password hash and an\n * acceptable substitute for the port. Hashes are self-describing\n * (`scrypt$<N>$<r>$<p>$<saltB64>$<hashB64>`) so parameters can be tuned and detected over time.\n */\nimport { randomBytes, scryptSync, timingSafeEqual } from 'node:crypto'\n\n/** The algorithm tag stored in every hash, so the format can evolve without ambiguity. */\nconst ALGORITHM = 'scrypt'\n/** Field separator inside a hash string. `$` never appears in base64url-free base64 we emit. */\nconst SEPARATOR = '$'\n/** Random salt length, in bytes. */\nconst SALT_BYTES = 16\n/** Derived key (hash) length, in bytes. */\nconst KEY_LENGTH = 64\n\n/**\n * Tunable scrypt cost parameters. The Laravel hashing `options` (`rounds`/`memory`/`time`)\n * equivalent, expressed in scrypt's own terms.\n */\nexport interface HashOptions {\n /** CPU/memory cost parameter `N`; must be a power of two. Default `16384` (2^14). */\n cost?: number\n /** Block size `r`. Default `8`. */\n blockSize?: number\n /** Parallelization `p`. Default `1`. */\n parallelism?: number\n}\n\n/** The resolved scrypt parameters after defaults are applied. */\ninterface ResolvedOptions {\n cost: number\n blockSize: number\n parallelism: number\n}\n\nconst DEFAULTS: ResolvedOptions = { cost: 16_384, blockSize: 8, parallelism: 1 }\n\n/** scrypt's `maxmem` ceiling scales with `128 * N * r`; give it generous headroom. */\nfunction maxmem(opts: ResolvedOptions): number {\n return 256 * opts.cost * opts.blockSize + 1024 * 1024\n}\n\nfunction resolve(options?: HashOptions): ResolvedOptions {\n return {\n cost: options?.cost ?? DEFAULTS.cost,\n blockSize: options?.blockSize ?? DEFAULTS.blockSize,\n parallelism: options?.parallelism ?? DEFAULTS.parallelism,\n }\n}\n\n/** The parsed components of a self-describing hash string. */\ninterface ParsedHash {\n algorithm: string\n options: ResolvedOptions\n salt: Buffer\n hash: Buffer\n}\n\n/** Thrown by {@link Hasher.info}-style parsing when a hash string is not in the expected format. */\nexport class InvalidHashError extends Error {\n override readonly name = 'InvalidHashError'\n\n constructor(message = 'The given hash is not a valid Mason scrypt hash.') {\n super(message)\n }\n}\n\n/** Parse a `scrypt$N$r$p$salt$hash` string, or return `null` if it does not match. */\nfunction parse(hash: string): ParsedHash | null {\n const parts = hash.split(SEPARATOR)\n if (parts.length !== 6) return null\n\n const [algorithm, nRaw, rRaw, pRaw, saltB64, hashB64] = parts as [\n string,\n string,\n string,\n string,\n string,\n string,\n ]\n if (algorithm !== ALGORITHM) return null\n\n const cost = Number(nRaw)\n const blockSize = Number(rRaw)\n const parallelism = Number(pRaw)\n if (!Number.isInteger(cost) || !Number.isInteger(blockSize) || !Number.isInteger(parallelism)) {\n return null\n }\n if (cost <= 0 || blockSize <= 0 || parallelism <= 0) return null\n\n return {\n algorithm,\n options: { cost, blockSize, parallelism },\n salt: Buffer.from(saltB64, 'base64'),\n hash: Buffer.from(hashB64, 'base64'),\n }\n}\n\n/**\n * Password hasher backed by scrypt. The Laravel `Hash` facade equivalent.\n */\nexport class Hasher {\n private readonly options: ResolvedOptions\n\n /** @param options Default cost parameters applied when {@link make} is called without overrides. */\n constructor(options?: HashOptions) {\n this.options = resolve(options)\n }\n\n /**\n * Hash a password with a fresh random 16-byte salt, returning a self-describing string of the\n * form `scrypt$<N>$<r>$<p>$<saltB64>$<hashB64>`. The Laravel `Hash::make()` equivalent.\n */\n make(password: string, options?: HashOptions): string {\n const opts = options ? resolve(options) : this.options\n const salt = randomBytes(SALT_BYTES)\n const derived = scryptSync(password, salt, KEY_LENGTH, {\n N: opts.cost,\n r: opts.blockSize,\n p: opts.parallelism,\n maxmem: maxmem(opts),\n })\n\n return [\n ALGORITHM,\n opts.cost,\n opts.blockSize,\n opts.parallelism,\n salt.toString('base64'),\n derived.toString('base64'),\n ].join(SEPARATOR)\n }\n\n /**\n * Verify a password against a hash in constant time. Returns `false` for a wrong password or a\n * malformed hash. The Laravel `Hash::check()` equivalent.\n */\n check(password: string, hash: string): boolean {\n const parsed = parse(hash)\n if (parsed === null || parsed.hash.length === 0) return false\n\n let computed: Buffer\n try {\n computed = scryptSync(password, parsed.salt, parsed.hash.length, {\n N: parsed.options.cost,\n r: parsed.options.blockSize,\n p: parsed.options.parallelism,\n maxmem: maxmem(parsed.options),\n })\n } catch {\n return false\n }\n\n if (computed.length !== parsed.hash.length) return false\n return timingSafeEqual(computed, parsed.hash)\n }\n\n /**\n * Determine whether a hash should be re-computed because its cost parameters differ from the\n * given (or default) options. The Laravel `Hash::needsRehash()` equivalent.\n */\n needsRehash(hash: string, options?: HashOptions): boolean {\n const parsed = parse(hash)\n if (parsed === null) return true\n\n const target = options ? resolve(options) : this.options\n return (\n parsed.options.cost !== target.cost ||\n parsed.options.blockSize !== target.blockSize ||\n parsed.options.parallelism !== target.parallelism\n )\n }\n\n /**\n * Extract the algorithm and cost parameters from a hash, or `null` if it is not a valid Mason\n * scrypt hash. The Laravel `Hash::info()` equivalent.\n */\n info(hash: string): { algorithm: string; options: HashOptions } | null {\n const parsed = parse(hash)\n if (parsed === null) return null\n return { algorithm: parsed.algorithm, options: { ...parsed.options } }\n }\n\n /**\n * Determine whether a value is already a Mason scrypt hash — i.e. it parses as the\n * self-describing `scrypt$N$r$p$salt$hash` format with a non-empty salt and digest. The Laravel\n * `Hash::isHashed()` equivalent.\n */\n isHashed(value: string): boolean {\n const parsed = parse(value)\n return parsed !== null && parsed.salt.length > 0 && parsed.hash.length > 0\n }\n\n /**\n * Verify that the given (or default) cost parameters are sane — `cost` a power of two greater\n * than one, `blockSize`/`parallelism` positive integers — and that a test hash actually\n * round-trips under them. The Laravel `Hash::verifyConfiguration()` equivalent.\n */\n verifyConfiguration(options?: HashOptions): boolean {\n const opts = options ? resolve(options) : this.options\n if (!isPowerOfTwo(opts.cost) || opts.cost < 2) return false\n if (!Number.isInteger(opts.blockSize) || opts.blockSize < 1) return false\n if (!Number.isInteger(opts.parallelism) || opts.parallelism < 1) return false\n\n try {\n const probe = 'mason-verify-configuration'\n return this.check(probe, this.make(probe, opts))\n } catch {\n return false\n }\n }\n}\n\n/** True when `value` is a positive-integer power of two (1, 2, 4, …). */\nfunction isPowerOfTwo(value: number): boolean {\n return Number.isInteger(value) && value >= 1 && Number.isInteger(Math.log2(value))\n}\n","/**\n * @plinthjs/encryption — authenticated encryption and password hashing over `node:crypto`.\n *\n * The Laravel `Illuminate\\Encryption` + `Illuminate\\Hashing` equivalent, with zero native\n * dependencies: {@link Encrypter} uses AES-256-GCM, and {@link Hasher} uses scrypt (a built-in,\n * memory-hard KDF standing in for bcrypt/argon2, which are native deps).\n */\nexport const VERSION = '0.1.0'\n\nexport { DecryptionError, Encrypter, InvalidKeyError } from './encrypter'\nexport { Hasher, type HashOptions, InvalidHashError } from './hasher'\n"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@plinthjs/encryption",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Mason encryption + hashing over node:crypto (the Illuminate Encryption/Hashing equivalent).",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"mason",
|
|
7
|
+
"laravel",
|
|
8
|
+
"framework",
|
|
9
|
+
"typescript",
|
|
10
|
+
"encryption"
|
|
11
|
+
],
|
|
12
|
+
"homepage": "https://github.com/anilkumarthakur60/js-framework/tree/main/packages/encryption#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/anilkumarthakur60/js-framework/issues"
|
|
15
|
+
},
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/anilkumarthakur60/js-framework.git",
|
|
19
|
+
"directory": "packages/encryption"
|
|
20
|
+
},
|
|
21
|
+
"license": "MIT",
|
|
22
|
+
"author": "Er. Anil Kumar Thakur",
|
|
23
|
+
"type": "module",
|
|
24
|
+
"sideEffects": false,
|
|
25
|
+
"files": [
|
|
26
|
+
"dist"
|
|
27
|
+
],
|
|
28
|
+
"exports": {
|
|
29
|
+
".": {
|
|
30
|
+
"types": "./dist/index.d.ts",
|
|
31
|
+
"import": "./dist/index.js",
|
|
32
|
+
"require": "./dist/index.cjs"
|
|
33
|
+
},
|
|
34
|
+
"./package.json": "./package.json"
|
|
35
|
+
},
|
|
36
|
+
"main": "./dist/index.cjs",
|
|
37
|
+
"module": "./dist/index.js",
|
|
38
|
+
"types": "./dist/index.d.ts",
|
|
39
|
+
"engines": {
|
|
40
|
+
"node": ">=20"
|
|
41
|
+
},
|
|
42
|
+
"publishConfig": {
|
|
43
|
+
"access": "public"
|
|
44
|
+
},
|
|
45
|
+
"dependencies": {
|
|
46
|
+
"@plinthjs/support": "^0.1.0"
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"@types/node": "^22.10.0",
|
|
50
|
+
"tsup": "^8.3.5",
|
|
51
|
+
"typescript": "^5.7.2",
|
|
52
|
+
"vitest": "^3.0.0"
|
|
53
|
+
},
|
|
54
|
+
"scripts": {
|
|
55
|
+
"build": "tsup",
|
|
56
|
+
"dev": "tsup --watch",
|
|
57
|
+
"test": "vitest run",
|
|
58
|
+
"typecheck": "tsc --noEmit",
|
|
59
|
+
"clean": "rm -rf dist .turbo *.tsbuildinfo"
|
|
60
|
+
}
|
|
61
|
+
}
|