@plinthjs/encryption 0.1.0 → 0.1.1

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 The Mason contributors
3
+ Copyright (c) 2026 The Plinth contributors
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # @plinthjs/encryption
2
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.
3
+ Authenticated encryption and password hashing for Plinth, built on Node's `node:crypto` — no
4
+ native dependencies. The.
5
5
 
6
6
  ## Encryption
7
7
 
@@ -10,7 +10,7 @@ native dependencies. The `Illuminate\Encryption` + `Illuminate\Hashing` equivale
10
10
  ```ts
11
11
  import { Encrypter } from '@plinthjs/encryption'
12
12
 
13
- // A 32-byte key, raw or `base64:<...>` (the Laravel APP_KEY convention).
13
+ // A 32-byte key, raw or `base64:<...>`.
14
14
  const key = Encrypter.generateKeyBase64()
15
15
  const cipher = new Encrypter(key)
16
16
 
@@ -27,8 +27,7 @@ A tampered payload or a wrong key throws `DecryptionError`; a wrong-length key t
27
27
 
28
28
  ## Hashing
29
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
30
+ `Hasher` uses scrypt, a memory-hard KDF built into `node:crypto`. Hashes are
32
31
  self-describing: `scrypt$<N>$<r>$<p>$<saltB64>$<hashB64>`.
33
32
 
34
33
  ```ts
package/dist/index.cjs CHANGED
@@ -32,39 +32,36 @@ var Encrypter = class _Encrypter {
32
32
  previousKeys;
33
33
  /**
34
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}
35
+ * `base64:<...>` string. Throws {@link InvalidKeyError}
36
36
  * if it does not decode to exactly 32 bytes.
37
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.
38
+ * {@link decryptString} fall back to, in order, when the current key fails. Each must also decode to exactly 32 bytes.
40
39
  */
41
40
  constructor(key, previousKeys = []) {
42
41
  this.key = normalizeKey(key);
43
42
  this.previousKeys = previousKeys.map((previous) => normalizeKey(previous));
44
43
  }
45
44
  /**
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.
45
+ * Return a new `Encrypter` with the same current key and the given previous keys.
48
46
  */
49
47
  withPreviousKeys(keys) {
50
48
  return new _Encrypter(this.key, keys);
51
49
  }
52
- /** The current encryption key. The Laravel `Encrypter::getKey()` equivalent. */
50
+ /** The current encryption key. */
53
51
  getKey() {
54
52
  return Buffer.from(this.key);
55
53
  }
56
54
  /**
57
- * The current key followed by every previous key, in fallback order. The Laravel
58
- * `Encrypter::getAllKeys()` equivalent.
55
+ * The current key followed by every previous key, in fallback order.
59
56
  */
60
57
  getAllKeys() {
61
58
  return [this.key, ...this.previousKeys].map((key) => Buffer.from(key));
62
59
  }
63
- /** The previous (rotated-out) keys. The Laravel `Encrypter::getPreviousKeys()` equivalent. */
60
+ /** The previous (rotated-out) keys. */
64
61
  getPreviousKeys() {
65
62
  return this.previousKeys.map((key) => Buffer.from(key));
66
63
  }
67
- /** Generate a fresh 32-byte key. The Laravel `Encrypter::generateKey()` equivalent. */
64
+ /** Generate a fresh 32-byte key. */
68
65
  static generateKey() {
69
66
  return crypto.randomBytes(KEY_BYTES);
70
67
  }
@@ -83,22 +80,21 @@ var Encrypter = class _Encrypter {
83
80
  }
84
81
  /**
85
82
  * 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.
83
+ * IV, the GCM auth tag, and the ciphertext.
87
84
  */
88
85
  encrypt(value) {
89
86
  return this.encryptString(JSON.stringify(value));
90
87
  }
91
88
  /**
92
89
  * 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.
90
+ * {@link DecryptionError} on tamper or wrong key.
94
91
  */
95
92
  // 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
93
  decrypt(payload) {
97
94
  return JSON.parse(this.decryptString(payload));
98
95
  }
99
96
  /**
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.
97
+ * Encrypt a raw string without JSON-serializing it.
102
98
  */
103
99
  encryptString(value) {
104
100
  const iv = crypto.randomBytes(IV_BYTES);
@@ -115,7 +111,7 @@ var Encrypter = class _Encrypter {
115
111
  /**
116
112
  * Decrypt a raw-string payload produced by {@link encryptString}. Tries the current key first,
117
113
  * 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.
114
+ * failed (tamper, or no matching key).
119
115
  */
120
116
  decryptString(payload) {
121
117
  const envelope = this.parse(payload);
@@ -151,7 +147,7 @@ var Encrypter = class _Encrypter {
151
147
  }
152
148
  /**
153
149
  * 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.
150
+ * tokens without leaking length-independent timing.
155
151
  */
156
152
  static hashEquals(a, b) {
157
153
  const left = Buffer.from(a, "utf8");
@@ -182,7 +178,7 @@ function resolve(options) {
182
178
  }
183
179
  var InvalidHashError = class extends Error {
184
180
  name = "InvalidHashError";
185
- constructor(message = "The given hash is not a valid Mason scrypt hash.") {
181
+ constructor(message = "The given hash is not a valid Plinth scrypt hash.") {
186
182
  super(message);
187
183
  }
188
184
  };
@@ -213,7 +209,7 @@ var Hasher = class {
213
209
  }
214
210
  /**
215
211
  * 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.
212
+ * form `scrypt$<N>$<r>$<p>$<saltB64>$<hashB64>`.
217
213
  */
218
214
  make(password, options) {
219
215
  const opts = options ? resolve(options) : this.options;
@@ -235,7 +231,7 @@ var Hasher = class {
235
231
  }
236
232
  /**
237
233
  * 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.
234
+ * malformed hash.
239
235
  */
240
236
  check(password, hash) {
241
237
  const parsed = parse(hash);
@@ -256,7 +252,7 @@ var Hasher = class {
256
252
  }
257
253
  /**
258
254
  * 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.
255
+ * given (or default) options.
260
256
  */
261
257
  needsRehash(hash, options) {
262
258
  const parsed = parse(hash);
@@ -265,8 +261,8 @@ var Hasher = class {
265
261
  return parsed.options.cost !== target.cost || parsed.options.blockSize !== target.blockSize || parsed.options.parallelism !== target.parallelism;
266
262
  }
267
263
  /**
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.
264
+ * Extract the algorithm and cost parameters from a hash, or `null` if it is not a valid Plinth
265
+ * scrypt hash.
270
266
  */
271
267
  info(hash) {
272
268
  const parsed = parse(hash);
@@ -274,9 +270,8 @@ var Hasher = class {
274
270
  return { algorithm: parsed.algorithm, options: { ...parsed.options } };
275
271
  }
276
272
  /**
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.
273
+ * Determine whether a value is already a Plinth scrypt hash — i.e. it parses as the
274
+ * self-describing `scrypt$N$r$p$salt$hash` format with a non-empty salt and digest.
280
275
  */
281
276
  isHashed(value) {
282
277
  const parsed = parse(value);
@@ -285,7 +280,7 @@ var Hasher = class {
285
280
  /**
286
281
  * Verify that the given (or default) cost parameters are sane — `cost` a power of two greater
287
282
  * than one, `blockSize`/`parallelism` positive integers — and that a test hash actually
288
- * round-trips under them. The Laravel `Hash::verifyConfiguration()` equivalent.
283
+ * round-trips under them.
289
284
  */
290
285
  verifyConfiguration(options) {
291
286
  const opts = options ? resolve(options) : this.options;
@@ -293,7 +288,7 @@ var Hasher = class {
293
288
  if (!Number.isInteger(opts.blockSize) || opts.blockSize < 1) return false;
294
289
  if (!Number.isInteger(opts.parallelism) || opts.parallelism < 1) return false;
295
290
  try {
296
- const probe = "mason-verify-configuration";
291
+ const probe = "plinth-verify-configuration";
297
292
  return this.check(probe, this.make(probe, opts));
298
293
  } catch {
299
294
  return false;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/encrypter.ts","../src/hasher.ts","../src/index.ts"],"names":["randomBytes","createCipheriv","createDecipheriv","timingSafeEqual","scryptSync"],"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,WAA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AAI,KAAK,IAAA,CAAK,IAAA,GAAO,GAAG,OAAO,KAAA;AACtD,IAAA,IAAI,CAAC,OAAO,SAAA,CAAU,IAAA,CAAK,SAAS,CAAA,IAAK,IAAA,CAAK,SAAA,GAAY,CAAA,EAAG,OAAO,KAAA;AACpE,IAAA,IAAI,CAAC,OAAO,SAAA,CAAU,IAAA,CAAK,WAAW,CAAA,IAAK,IAAA,CAAK,WAAA,GAAc,CAAA,EAAG,OAAO,KAAA;AAExE,IAAA,IAAI;AACF,MAAA,MAAM,KAAA,GAAQ,4BAAA;AACd,MAAA,OAAO,KAAK,KAAA,CAAM,KAAA,EAAO,KAAK,IAAA,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.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"]}
1
+ {"version":3,"sources":["../src/encrypter.ts","../src/hasher.ts","../src/index.ts"],"names":["randomBytes","createCipheriv","createDecipheriv","timingSafeEqual","scryptSync"],"mappings":";;;;;AASA,IAAM,MAAA,GAAS,aAAA;AAEf,IAAM,SAAA,GAAY,EAAA;AAEl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AAC1B,IAAA,OAAO,MAAA,KAAW,QAAQ,MAAA,CAAO,IAAA,CAAK,SAAS,CAAA,IAAK,MAAA,CAAO,KAAK,MAAA,GAAS,CAAA;AAAA,EAC3E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,oBAAoB,OAAA,EAAgC;AAClD,IAAA,MAAM,IAAA,GAAO,OAAA,GAAU,OAAA,CAAQ,OAAO,IAAI,IAAA,CAAK,OAAA;AAC/C,IAAA,IAAI,CAAC,aAAa,IAAA,CAAK,IAAI,KAAK,IAAA,CAAK,IAAA,GAAO,GAAG,OAAO,KAAA;AACtD,IAAA,IAAI,CAAC,OAAO,SAAA,CAAU,IAAA,CAAK,SAAS,CAAA,IAAK,IAAA,CAAK,SAAA,GAAY,CAAA,EAAG,OAAO,KAAA;AACpE,IAAA,IAAI,CAAC,OAAO,SAAA,CAAU,IAAA,CAAK,WAAW,CAAA,IAAK,IAAA,CAAK,WAAA,GAAc,CAAA,EAAG,OAAO,KAAA;AAExE,IAAA,IAAI;AACF,MAAA,MAAM,KAAA,GAAQ,6BAAA;AACd,MAAA,OAAO,KAAK,KAAA,CAAM,KAAA,EAAO,KAAK,IAAA,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;;;ACrNO,IAAM,OAAA,GAAU","file":"index.cjs","sourcesContent":["/**\n * `Encrypter` — authenticated symmetric encryption over `node:crypto`.\n * The 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 Plinth 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 `APP_KEY` convention. */\nconst BASE64_PREFIX = 'base64:'\n\n/**\n * The on-the-wire shape of an encrypted payload, before base64-wrapping. Mirrors the reference framework'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).\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.\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. 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. 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.\n */\n withPreviousKeys(keys: readonly (Buffer | string)[]): Encrypter {\n return new Encrypter(this.key, keys)\n }\n\n /** The current encryption key. */\n getKey(): Buffer {\n return Buffer.from(this.key)\n }\n\n /**\n * The current key followed by every previous key, in fallback order.\n */\n getAllKeys(): Buffer[] {\n return [this.key, ...this.previousKeys].map((key) => Buffer.from(key))\n }\n\n /** The previous (rotated-out) keys. */\n getPreviousKeys(): Buffer[] {\n return this.previousKeys.map((key) => Buffer.from(key))\n }\n\n /** Generate a fresh 32-byte key. */\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.\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.\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.\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).\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.\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 *\n *\n * NOTE ON ALGORITHM: the reference framework defaults to bcrypt and offers argon2i/argon2id. Both are native\n * dependencies in Node. To keep Plinth 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.\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 Plinth 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.\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>`.\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.\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.\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 Plinth\n * scrypt hash.\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 Plinth 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.\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.\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 = 'plinth-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, 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 CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
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.
3
+ * IV/tag/ciphertext (the auth tag fails to verify).
4
4
  */
5
5
  declare class DecryptionError extends Error {
6
6
  readonly name = "DecryptionError";
@@ -12,35 +12,32 @@ declare class InvalidKeyError extends Error {
12
12
  constructor(message?: string);
13
13
  }
14
14
  /**
15
- * Authenticated AES-256-GCM encrypter. The Laravel `Illuminate\Encryption\Encrypter` equivalent.
15
+ * Authenticated AES-256-GCM encrypter.
16
16
  */
17
17
  declare class Encrypter {
18
18
  private readonly key;
19
19
  private readonly previousKeys;
20
20
  /**
21
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}
22
+ * `base64:<...>` string. Throws {@link InvalidKeyError}
23
23
  * if it does not decode to exactly 32 bytes.
24
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.
25
+ * {@link decryptString} fall back to, in order, when the current key fails. Each must also decode to exactly 32 bytes.
27
26
  */
28
27
  constructor(key: Buffer | string, previousKeys?: readonly (Buffer | string)[]);
29
28
  /**
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.
29
+ * Return a new `Encrypter` with the same current key and the given previous keys.
32
30
  */
33
31
  withPreviousKeys(keys: readonly (Buffer | string)[]): Encrypter;
34
- /** The current encryption key. The Laravel `Encrypter::getKey()` equivalent. */
32
+ /** The current encryption key. */
35
33
  getKey(): Buffer;
36
34
  /**
37
- * The current key followed by every previous key, in fallback order. The Laravel
38
- * `Encrypter::getAllKeys()` equivalent.
35
+ * The current key followed by every previous key, in fallback order.
39
36
  */
40
37
  getAllKeys(): Buffer[];
41
- /** The previous (rotated-out) keys. The Laravel `Encrypter::getPreviousKeys()` equivalent. */
38
+ /** The previous (rotated-out) keys. */
42
39
  getPreviousKeys(): Buffer[];
43
- /** Generate a fresh 32-byte key. The Laravel `Encrypter::generateKey()` equivalent. */
40
+ /** Generate a fresh 32-byte key. */
44
41
  static generateKey(): Buffer;
45
42
  /** Generate a fresh key as a `base64:<...>` string, ready to drop into config. */
46
43
  static generateKeyBase64(): string;
@@ -48,37 +45,35 @@ declare class Encrypter {
48
45
  static supported(key: Buffer | string): boolean;
49
46
  /**
50
47
  * 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.
48
+ * IV, the GCM auth tag, and the ciphertext.
52
49
  */
53
50
  encrypt(value: unknown): string;
54
51
  /**
55
52
  * 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.
53
+ * {@link DecryptionError} on tamper or wrong key.
57
54
  */
58
55
  decrypt<T = unknown>(payload: string): T;
59
56
  /**
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.
57
+ * Encrypt a raw string without JSON-serializing it.
62
58
  */
63
59
  encryptString(value: string): string;
64
60
  /**
65
61
  * Decrypt a raw-string payload produced by {@link encryptString}. Tries the current key first,
66
62
  * 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.
63
+ * failed (tamper, or no matching key).
68
64
  */
69
65
  decryptString(payload: string): string;
70
66
  /** Decode and validate the base64 envelope, raising {@link DecryptionError} if it is malformed. */
71
67
  private parse;
72
68
  /**
73
69
  * 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.
70
+ * tokens without leaking length-independent timing.
75
71
  */
76
72
  static hashEquals(a: string, b: string): boolean;
77
73
  }
78
74
 
79
75
  /**
80
- * Tunable scrypt cost parameters. The Laravel hashing `options` (`rounds`/`memory`/`time`)
81
- * equivalent, expressed in scrypt's own terms.
76
+ * Tunable scrypt cost parameters.
82
77
  */
83
78
  interface HashOptions {
84
79
  /** CPU/memory cost parameter `N`; must be a power of two. Default `16384` (2^14). */
@@ -94,7 +89,7 @@ declare class InvalidHashError extends Error {
94
89
  constructor(message?: string);
95
90
  }
96
91
  /**
97
- * Password hasher backed by scrypt. The Laravel `Hash` facade equivalent.
92
+ * Password hasher backed by scrypt.
98
93
  */
99
94
  declare class Hasher {
100
95
  private readonly options;
@@ -102,37 +97,36 @@ declare class Hasher {
102
97
  constructor(options?: HashOptions);
103
98
  /**
104
99
  * 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.
100
+ * form `scrypt$<N>$<r>$<p>$<saltB64>$<hashB64>`.
106
101
  */
107
102
  make(password: string, options?: HashOptions): string;
108
103
  /**
109
104
  * 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.
105
+ * malformed hash.
111
106
  */
112
107
  check(password: string, hash: string): boolean;
113
108
  /**
114
109
  * 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.
110
+ * given (or default) options.
116
111
  */
117
112
  needsRehash(hash: string, options?: HashOptions): boolean;
118
113
  /**
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.
114
+ * Extract the algorithm and cost parameters from a hash, or `null` if it is not a valid Plinth
115
+ * scrypt hash.
121
116
  */
122
117
  info(hash: string): {
123
118
  algorithm: string;
124
119
  options: HashOptions;
125
120
  } | null;
126
121
  /**
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.
122
+ * Determine whether a value is already a Plinth scrypt hash — i.e. it parses as the
123
+ * self-describing `scrypt$N$r$p$salt$hash` format with a non-empty salt and digest.
130
124
  */
131
125
  isHashed(value: string): boolean;
132
126
  /**
133
127
  * Verify that the given (or default) cost parameters are sane — `cost` a power of two greater
134
128
  * than one, `blockSize`/`parallelism` positive integers — and that a test hash actually
135
- * round-trips under them. The Laravel `Hash::verifyConfiguration()` equivalent.
129
+ * round-trips under them.
136
130
  */
137
131
  verifyConfiguration(options?: HashOptions): boolean;
138
132
  }
@@ -140,7 +134,7 @@ declare class Hasher {
140
134
  /**
141
135
  * @plinthjs/encryption — authenticated encryption and password hashing over `node:crypto`.
142
136
  *
143
- * The Laravel `Illuminate\Encryption` + `Illuminate\Hashing` equivalent, with zero native
137
+ * The, with zero native
144
138
  * dependencies: {@link Encrypter} uses AES-256-GCM, and {@link Hasher} uses scrypt (a built-in,
145
139
  * memory-hard KDF standing in for bcrypt/argon2, which are native deps).
146
140
  */
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
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.
3
+ * IV/tag/ciphertext (the auth tag fails to verify).
4
4
  */
5
5
  declare class DecryptionError extends Error {
6
6
  readonly name = "DecryptionError";
@@ -12,35 +12,32 @@ declare class InvalidKeyError extends Error {
12
12
  constructor(message?: string);
13
13
  }
14
14
  /**
15
- * Authenticated AES-256-GCM encrypter. The Laravel `Illuminate\Encryption\Encrypter` equivalent.
15
+ * Authenticated AES-256-GCM encrypter.
16
16
  */
17
17
  declare class Encrypter {
18
18
  private readonly key;
19
19
  private readonly previousKeys;
20
20
  /**
21
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}
22
+ * `base64:<...>` string. Throws {@link InvalidKeyError}
23
23
  * if it does not decode to exactly 32 bytes.
24
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.
25
+ * {@link decryptString} fall back to, in order, when the current key fails. Each must also decode to exactly 32 bytes.
27
26
  */
28
27
  constructor(key: Buffer | string, previousKeys?: readonly (Buffer | string)[]);
29
28
  /**
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.
29
+ * Return a new `Encrypter` with the same current key and the given previous keys.
32
30
  */
33
31
  withPreviousKeys(keys: readonly (Buffer | string)[]): Encrypter;
34
- /** The current encryption key. The Laravel `Encrypter::getKey()` equivalent. */
32
+ /** The current encryption key. */
35
33
  getKey(): Buffer;
36
34
  /**
37
- * The current key followed by every previous key, in fallback order. The Laravel
38
- * `Encrypter::getAllKeys()` equivalent.
35
+ * The current key followed by every previous key, in fallback order.
39
36
  */
40
37
  getAllKeys(): Buffer[];
41
- /** The previous (rotated-out) keys. The Laravel `Encrypter::getPreviousKeys()` equivalent. */
38
+ /** The previous (rotated-out) keys. */
42
39
  getPreviousKeys(): Buffer[];
43
- /** Generate a fresh 32-byte key. The Laravel `Encrypter::generateKey()` equivalent. */
40
+ /** Generate a fresh 32-byte key. */
44
41
  static generateKey(): Buffer;
45
42
  /** Generate a fresh key as a `base64:<...>` string, ready to drop into config. */
46
43
  static generateKeyBase64(): string;
@@ -48,37 +45,35 @@ declare class Encrypter {
48
45
  static supported(key: Buffer | string): boolean;
49
46
  /**
50
47
  * 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.
48
+ * IV, the GCM auth tag, and the ciphertext.
52
49
  */
53
50
  encrypt(value: unknown): string;
54
51
  /**
55
52
  * 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.
53
+ * {@link DecryptionError} on tamper or wrong key.
57
54
  */
58
55
  decrypt<T = unknown>(payload: string): T;
59
56
  /**
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.
57
+ * Encrypt a raw string without JSON-serializing it.
62
58
  */
63
59
  encryptString(value: string): string;
64
60
  /**
65
61
  * Decrypt a raw-string payload produced by {@link encryptString}. Tries the current key first,
66
62
  * 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.
63
+ * failed (tamper, or no matching key).
68
64
  */
69
65
  decryptString(payload: string): string;
70
66
  /** Decode and validate the base64 envelope, raising {@link DecryptionError} if it is malformed. */
71
67
  private parse;
72
68
  /**
73
69
  * 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.
70
+ * tokens without leaking length-independent timing.
75
71
  */
76
72
  static hashEquals(a: string, b: string): boolean;
77
73
  }
78
74
 
79
75
  /**
80
- * Tunable scrypt cost parameters. The Laravel hashing `options` (`rounds`/`memory`/`time`)
81
- * equivalent, expressed in scrypt's own terms.
76
+ * Tunable scrypt cost parameters.
82
77
  */
83
78
  interface HashOptions {
84
79
  /** CPU/memory cost parameter `N`; must be a power of two. Default `16384` (2^14). */
@@ -94,7 +89,7 @@ declare class InvalidHashError extends Error {
94
89
  constructor(message?: string);
95
90
  }
96
91
  /**
97
- * Password hasher backed by scrypt. The Laravel `Hash` facade equivalent.
92
+ * Password hasher backed by scrypt.
98
93
  */
99
94
  declare class Hasher {
100
95
  private readonly options;
@@ -102,37 +97,36 @@ declare class Hasher {
102
97
  constructor(options?: HashOptions);
103
98
  /**
104
99
  * 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.
100
+ * form `scrypt$<N>$<r>$<p>$<saltB64>$<hashB64>`.
106
101
  */
107
102
  make(password: string, options?: HashOptions): string;
108
103
  /**
109
104
  * 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.
105
+ * malformed hash.
111
106
  */
112
107
  check(password: string, hash: string): boolean;
113
108
  /**
114
109
  * 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.
110
+ * given (or default) options.
116
111
  */
117
112
  needsRehash(hash: string, options?: HashOptions): boolean;
118
113
  /**
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.
114
+ * Extract the algorithm and cost parameters from a hash, or `null` if it is not a valid Plinth
115
+ * scrypt hash.
121
116
  */
122
117
  info(hash: string): {
123
118
  algorithm: string;
124
119
  options: HashOptions;
125
120
  } | null;
126
121
  /**
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.
122
+ * Determine whether a value is already a Plinth scrypt hash — i.e. it parses as the
123
+ * self-describing `scrypt$N$r$p$salt$hash` format with a non-empty salt and digest.
130
124
  */
131
125
  isHashed(value: string): boolean;
132
126
  /**
133
127
  * Verify that the given (or default) cost parameters are sane — `cost` a power of two greater
134
128
  * than one, `blockSize`/`parallelism` positive integers — and that a test hash actually
135
- * round-trips under them. The Laravel `Hash::verifyConfiguration()` equivalent.
129
+ * round-trips under them.
136
130
  */
137
131
  verifyConfiguration(options?: HashOptions): boolean;
138
132
  }
@@ -140,7 +134,7 @@ declare class Hasher {
140
134
  /**
141
135
  * @plinthjs/encryption — authenticated encryption and password hashing over `node:crypto`.
142
136
  *
143
- * The Laravel `Illuminate\Encryption` + `Illuminate\Hashing` equivalent, with zero native
137
+ * The, with zero native
144
138
  * dependencies: {@link Encrypter} uses AES-256-GCM, and {@link Hasher} uses scrypt (a built-in,
145
139
  * memory-hard KDF standing in for bcrypt/argon2, which are native deps).
146
140
  */
package/dist/index.js CHANGED
@@ -30,39 +30,36 @@ var Encrypter = class _Encrypter {
30
30
  previousKeys;
31
31
  /**
32
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}
33
+ * `base64:<...>` string. Throws {@link InvalidKeyError}
34
34
  * if it does not decode to exactly 32 bytes.
35
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.
36
+ * {@link decryptString} fall back to, in order, when the current key fails. Each must also decode to exactly 32 bytes.
38
37
  */
39
38
  constructor(key, previousKeys = []) {
40
39
  this.key = normalizeKey(key);
41
40
  this.previousKeys = previousKeys.map((previous) => normalizeKey(previous));
42
41
  }
43
42
  /**
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.
43
+ * Return a new `Encrypter` with the same current key and the given previous keys.
46
44
  */
47
45
  withPreviousKeys(keys) {
48
46
  return new _Encrypter(this.key, keys);
49
47
  }
50
- /** The current encryption key. The Laravel `Encrypter::getKey()` equivalent. */
48
+ /** The current encryption key. */
51
49
  getKey() {
52
50
  return Buffer.from(this.key);
53
51
  }
54
52
  /**
55
- * The current key followed by every previous key, in fallback order. The Laravel
56
- * `Encrypter::getAllKeys()` equivalent.
53
+ * The current key followed by every previous key, in fallback order.
57
54
  */
58
55
  getAllKeys() {
59
56
  return [this.key, ...this.previousKeys].map((key) => Buffer.from(key));
60
57
  }
61
- /** The previous (rotated-out) keys. The Laravel `Encrypter::getPreviousKeys()` equivalent. */
58
+ /** The previous (rotated-out) keys. */
62
59
  getPreviousKeys() {
63
60
  return this.previousKeys.map((key) => Buffer.from(key));
64
61
  }
65
- /** Generate a fresh 32-byte key. The Laravel `Encrypter::generateKey()` equivalent. */
62
+ /** Generate a fresh 32-byte key. */
66
63
  static generateKey() {
67
64
  return randomBytes(KEY_BYTES);
68
65
  }
@@ -81,22 +78,21 @@ var Encrypter = class _Encrypter {
81
78
  }
82
79
  /**
83
80
  * 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.
81
+ * IV, the GCM auth tag, and the ciphertext.
85
82
  */
86
83
  encrypt(value) {
87
84
  return this.encryptString(JSON.stringify(value));
88
85
  }
89
86
  /**
90
87
  * 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.
88
+ * {@link DecryptionError} on tamper or wrong key.
92
89
  */
93
90
  // 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
91
  decrypt(payload) {
95
92
  return JSON.parse(this.decryptString(payload));
96
93
  }
97
94
  /**
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.
95
+ * Encrypt a raw string without JSON-serializing it.
100
96
  */
101
97
  encryptString(value) {
102
98
  const iv = randomBytes(IV_BYTES);
@@ -113,7 +109,7 @@ var Encrypter = class _Encrypter {
113
109
  /**
114
110
  * Decrypt a raw-string payload produced by {@link encryptString}. Tries the current key first,
115
111
  * 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.
112
+ * failed (tamper, or no matching key).
117
113
  */
118
114
  decryptString(payload) {
119
115
  const envelope = this.parse(payload);
@@ -149,7 +145,7 @@ var Encrypter = class _Encrypter {
149
145
  }
150
146
  /**
151
147
  * 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.
148
+ * tokens without leaking length-independent timing.
153
149
  */
154
150
  static hashEquals(a, b) {
155
151
  const left = Buffer.from(a, "utf8");
@@ -180,7 +176,7 @@ function resolve(options) {
180
176
  }
181
177
  var InvalidHashError = class extends Error {
182
178
  name = "InvalidHashError";
183
- constructor(message = "The given hash is not a valid Mason scrypt hash.") {
179
+ constructor(message = "The given hash is not a valid Plinth scrypt hash.") {
184
180
  super(message);
185
181
  }
186
182
  };
@@ -211,7 +207,7 @@ var Hasher = class {
211
207
  }
212
208
  /**
213
209
  * 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.
210
+ * form `scrypt$<N>$<r>$<p>$<saltB64>$<hashB64>`.
215
211
  */
216
212
  make(password, options) {
217
213
  const opts = options ? resolve(options) : this.options;
@@ -233,7 +229,7 @@ var Hasher = class {
233
229
  }
234
230
  /**
235
231
  * 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.
232
+ * malformed hash.
237
233
  */
238
234
  check(password, hash) {
239
235
  const parsed = parse(hash);
@@ -254,7 +250,7 @@ var Hasher = class {
254
250
  }
255
251
  /**
256
252
  * 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.
253
+ * given (or default) options.
258
254
  */
259
255
  needsRehash(hash, options) {
260
256
  const parsed = parse(hash);
@@ -263,8 +259,8 @@ var Hasher = class {
263
259
  return parsed.options.cost !== target.cost || parsed.options.blockSize !== target.blockSize || parsed.options.parallelism !== target.parallelism;
264
260
  }
265
261
  /**
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.
262
+ * Extract the algorithm and cost parameters from a hash, or `null` if it is not a valid Plinth
263
+ * scrypt hash.
268
264
  */
269
265
  info(hash) {
270
266
  const parsed = parse(hash);
@@ -272,9 +268,8 @@ var Hasher = class {
272
268
  return { algorithm: parsed.algorithm, options: { ...parsed.options } };
273
269
  }
274
270
  /**
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.
271
+ * Determine whether a value is already a Plinth scrypt hash — i.e. it parses as the
272
+ * self-describing `scrypt$N$r$p$salt$hash` format with a non-empty salt and digest.
278
273
  */
279
274
  isHashed(value) {
280
275
  const parsed = parse(value);
@@ -283,7 +278,7 @@ var Hasher = class {
283
278
  /**
284
279
  * Verify that the given (or default) cost parameters are sane — `cost` a power of two greater
285
280
  * than one, `blockSize`/`parallelism` positive integers — and that a test hash actually
286
- * round-trips under them. The Laravel `Hash::verifyConfiguration()` equivalent.
281
+ * round-trips under them.
287
282
  */
288
283
  verifyConfiguration(options) {
289
284
  const opts = options ? resolve(options) : this.options;
@@ -291,7 +286,7 @@ var Hasher = class {
291
286
  if (!Number.isInteger(opts.blockSize) || opts.blockSize < 1) return false;
292
287
  if (!Number.isInteger(opts.parallelism) || opts.parallelism < 1) return false;
293
288
  try {
294
- const probe = "mason-verify-configuration";
289
+ const probe = "plinth-verify-configuration";
295
290
  return this.check(probe, this.make(probe, opts));
296
291
  } catch {
297
292
  return false;
package/dist/index.js.map CHANGED
@@ -1 +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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WAAW,CAAA,IAAK,IAAA,CAAK,WAAA,GAAc,CAAA,EAAG,OAAO,KAAA;AAExE,IAAA,IAAI;AACF,MAAA,MAAM,KAAA,GAAQ,4BAAA;AACd,MAAA,OAAO,KAAK,KAAA,CAAM,KAAA,EAAO,KAAK,IAAA,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"]}
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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AAA;AAC/C,IAAA,IAAI,CAAC,aAAa,IAAA,CAAK,IAAI,KAAK,IAAA,CAAK,IAAA,GAAO,GAAG,OAAO,KAAA;AACtD,IAAA,IAAI,CAAC,OAAO,SAAA,CAAU,IAAA,CAAK,SAAS,CAAA,IAAK,IAAA,CAAK,SAAA,GAAY,CAAA,EAAG,OAAO,KAAA;AACpE,IAAA,IAAI,CAAC,OAAO,SAAA,CAAU,IAAA,CAAK,WAAW,CAAA,IAAK,IAAA,CAAK,WAAA,GAAc,CAAA,EAAG,OAAO,KAAA;AAExE,IAAA,IAAI;AACF,MAAA,MAAM,KAAA,GAAQ,6BAAA;AACd,MAAA,OAAO,KAAK,KAAA,CAAM,KAAA,EAAO,KAAK,IAAA,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;;;ACrNO,IAAM,OAAA,GAAU","file":"index.js","sourcesContent":["/**\n * `Encrypter` — authenticated symmetric encryption over `node:crypto`.\n * The 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 Plinth 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 `APP_KEY` convention. */\nconst BASE64_PREFIX = 'base64:'\n\n/**\n * The on-the-wire shape of an encrypted payload, before base64-wrapping. Mirrors the reference framework'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).\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.\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. 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. 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.\n */\n withPreviousKeys(keys: readonly (Buffer | string)[]): Encrypter {\n return new Encrypter(this.key, keys)\n }\n\n /** The current encryption key. */\n getKey(): Buffer {\n return Buffer.from(this.key)\n }\n\n /**\n * The current key followed by every previous key, in fallback order.\n */\n getAllKeys(): Buffer[] {\n return [this.key, ...this.previousKeys].map((key) => Buffer.from(key))\n }\n\n /** The previous (rotated-out) keys. */\n getPreviousKeys(): Buffer[] {\n return this.previousKeys.map((key) => Buffer.from(key))\n }\n\n /** Generate a fresh 32-byte key. */\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.\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.\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.\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).\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.\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 *\n *\n * NOTE ON ALGORITHM: the reference framework defaults to bcrypt and offers argon2i/argon2id. Both are native\n * dependencies in Node. To keep Plinth 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.\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 Plinth 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.\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>`.\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.\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.\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 Plinth\n * scrypt hash.\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 Plinth 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.\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.\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 = 'plinth-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, 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 CHANGED
@@ -1,10 +1,9 @@
1
1
  {
2
2
  "name": "@plinthjs/encryption",
3
- "version": "0.1.0",
4
- "description": "Mason encryption + hashing over node:crypto (the Illuminate Encryption/Hashing equivalent).",
3
+ "version": "0.1.1",
4
+ "description": "Plinth encryption + hashing over node:crypto.",
5
5
  "keywords": [
6
- "mason",
7
- "laravel",
6
+ "plinth",
8
7
  "framework",
9
8
  "typescript",
10
9
  "encryption"
@@ -43,7 +42,7 @@
43
42
  "access": "public"
44
43
  },
45
44
  "dependencies": {
46
- "@plinthjs/support": "^0.1.0"
45
+ "@plinthjs/support": "^0.1.1"
47
46
  },
48
47
  "devDependencies": {
49
48
  "@types/node": "^22.10.0",