@plinthjs/encryption 0.1.1 → 0.1.2
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/README.md +1 -1
- package/dist/index.cjs +3 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
package/README.md
CHANGED
package/dist/index.cjs
CHANGED
|
@@ -270,7 +270,7 @@ var Hasher = class {
|
|
|
270
270
|
return { algorithm: parsed.algorithm, options: { ...parsed.options } };
|
|
271
271
|
}
|
|
272
272
|
/**
|
|
273
|
-
* Determine whether a value is already a Plinth scrypt hash
|
|
273
|
+
* Determine whether a value is already a Plinth scrypt hash - i.e. it parses as the
|
|
274
274
|
* self-describing `scrypt$N$r$p$salt$hash` format with a non-empty salt and digest.
|
|
275
275
|
*/
|
|
276
276
|
isHashed(value) {
|
|
@@ -278,8 +278,8 @@ var Hasher = class {
|
|
|
278
278
|
return parsed !== null && parsed.salt.length > 0 && parsed.hash.length > 0;
|
|
279
279
|
}
|
|
280
280
|
/**
|
|
281
|
-
* Verify that the given (or default) cost parameters are sane
|
|
282
|
-
* than one, `blockSize`/`parallelism` positive integers
|
|
281
|
+
* Verify that the given (or default) cost parameters are sane - `cost` a power of two greater
|
|
282
|
+
* than one, `blockSize`/`parallelism` positive integers - and that a test hash actually
|
|
283
283
|
* round-trips under them.
|
|
284
284
|
*/
|
|
285
285
|
verifyConfiguration(options) {
|
package/dist/index.cjs.map
CHANGED
|
@@ -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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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"]}
|
|
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,WAAA,CAAY,OAAA,GAAU,CAAA,uBAAA,EAA0B,SAAS,CAAA,uBAAA,CAAA,EAA2B;AAClF,IAAA,KAAA,CAAM,OAAO,CAAA;AAAA,EACf;AACF;AAGA,SAAS,aAAa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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
|
@@ -119,20 +119,20 @@ declare class Hasher {
|
|
|
119
119
|
options: HashOptions;
|
|
120
120
|
} | null;
|
|
121
121
|
/**
|
|
122
|
-
* Determine whether a value is already a Plinth scrypt hash
|
|
122
|
+
* Determine whether a value is already a Plinth scrypt hash - i.e. it parses as the
|
|
123
123
|
* self-describing `scrypt$N$r$p$salt$hash` format with a non-empty salt and digest.
|
|
124
124
|
*/
|
|
125
125
|
isHashed(value: string): boolean;
|
|
126
126
|
/**
|
|
127
|
-
* Verify that the given (or default) cost parameters are sane
|
|
128
|
-
* than one, `blockSize`/`parallelism` positive integers
|
|
127
|
+
* Verify that the given (or default) cost parameters are sane - `cost` a power of two greater
|
|
128
|
+
* than one, `blockSize`/`parallelism` positive integers - and that a test hash actually
|
|
129
129
|
* round-trips under them.
|
|
130
130
|
*/
|
|
131
131
|
verifyConfiguration(options?: HashOptions): boolean;
|
|
132
132
|
}
|
|
133
133
|
|
|
134
134
|
/**
|
|
135
|
-
* @plinthjs/encryption
|
|
135
|
+
* @plinthjs/encryption - authenticated encryption and password hashing over `node:crypto`.
|
|
136
136
|
*
|
|
137
137
|
* The, with zero native
|
|
138
138
|
* dependencies: {@link Encrypter} uses AES-256-GCM, and {@link Hasher} uses scrypt (a built-in,
|
package/dist/index.d.ts
CHANGED
|
@@ -119,20 +119,20 @@ declare class Hasher {
|
|
|
119
119
|
options: HashOptions;
|
|
120
120
|
} | null;
|
|
121
121
|
/**
|
|
122
|
-
* Determine whether a value is already a Plinth scrypt hash
|
|
122
|
+
* Determine whether a value is already a Plinth scrypt hash - i.e. it parses as the
|
|
123
123
|
* self-describing `scrypt$N$r$p$salt$hash` format with a non-empty salt and digest.
|
|
124
124
|
*/
|
|
125
125
|
isHashed(value: string): boolean;
|
|
126
126
|
/**
|
|
127
|
-
* Verify that the given (or default) cost parameters are sane
|
|
128
|
-
* than one, `blockSize`/`parallelism` positive integers
|
|
127
|
+
* Verify that the given (or default) cost parameters are sane - `cost` a power of two greater
|
|
128
|
+
* than one, `blockSize`/`parallelism` positive integers - and that a test hash actually
|
|
129
129
|
* round-trips under them.
|
|
130
130
|
*/
|
|
131
131
|
verifyConfiguration(options?: HashOptions): boolean;
|
|
132
132
|
}
|
|
133
133
|
|
|
134
134
|
/**
|
|
135
|
-
* @plinthjs/encryption
|
|
135
|
+
* @plinthjs/encryption - authenticated encryption and password hashing over `node:crypto`.
|
|
136
136
|
*
|
|
137
137
|
* The, with zero native
|
|
138
138
|
* dependencies: {@link Encrypter} uses AES-256-GCM, and {@link Hasher} uses scrypt (a built-in,
|
package/dist/index.js
CHANGED
|
@@ -268,7 +268,7 @@ var Hasher = class {
|
|
|
268
268
|
return { algorithm: parsed.algorithm, options: { ...parsed.options } };
|
|
269
269
|
}
|
|
270
270
|
/**
|
|
271
|
-
* Determine whether a value is already a Plinth scrypt hash
|
|
271
|
+
* Determine whether a value is already a Plinth scrypt hash - i.e. it parses as the
|
|
272
272
|
* self-describing `scrypt$N$r$p$salt$hash` format with a non-empty salt and digest.
|
|
273
273
|
*/
|
|
274
274
|
isHashed(value) {
|
|
@@ -276,8 +276,8 @@ var Hasher = class {
|
|
|
276
276
|
return parsed !== null && parsed.salt.length > 0 && parsed.hash.length > 0;
|
|
277
277
|
}
|
|
278
278
|
/**
|
|
279
|
-
* Verify that the given (or default) cost parameters are sane
|
|
280
|
-
* than one, `blockSize`/`parallelism` positive integers
|
|
279
|
+
* Verify that the given (or default) cost parameters are sane - `cost` a power of two greater
|
|
280
|
+
* than one, `blockSize`/`parallelism` positive integers - and that a test hash actually
|
|
281
281
|
* round-trips under them.
|
|
282
282
|
*/
|
|
283
283
|
verifyConfiguration(options) {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/encrypter.ts","../src/hasher.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te 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"]}
|
|
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,E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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,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@plinthjs/encryption",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "Plinth encryption + hashing over node:crypto.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"plinth",
|
|
@@ -8,13 +8,13 @@
|
|
|
8
8
|
"typescript",
|
|
9
9
|
"encryption"
|
|
10
10
|
],
|
|
11
|
-
"homepage": "https://github.com/anilkumarthakur60/
|
|
11
|
+
"homepage": "https://github.com/anilkumarthakur60/plinthjs/tree/main/packages/encryption#readme",
|
|
12
12
|
"bugs": {
|
|
13
|
-
"url": "https://github.com/anilkumarthakur60/
|
|
13
|
+
"url": "https://github.com/anilkumarthakur60/plinthjs/issues"
|
|
14
14
|
},
|
|
15
15
|
"repository": {
|
|
16
16
|
"type": "git",
|
|
17
|
-
"url": "git+https://github.com/anilkumarthakur60/
|
|
17
|
+
"url": "git+https://github.com/anilkumarthakur60/plinthjs.git",
|
|
18
18
|
"directory": "packages/encryption"
|
|
19
19
|
},
|
|
20
20
|
"license": "MIT",
|
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
"access": "public"
|
|
43
43
|
},
|
|
44
44
|
"dependencies": {
|
|
45
|
-
"@plinthjs/support": "^0.1.
|
|
45
|
+
"@plinthjs/support": "^0.1.2"
|
|
46
46
|
},
|
|
47
47
|
"devDependencies": {
|
|
48
48
|
"@types/node": "^22.10.0",
|