@venizia/ignis-helpers 0.4.8-3 → 0.4.8-5

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.
Files changed (60) hide show
  1. package/dist/esm/common/redact.d.ts +5 -0
  2. package/dist/esm/common/redact.js +50 -4
  3. package/dist/esm/common/redact.js.map +1 -1
  4. package/dist/esm/core.d.ts +1 -0
  5. package/dist/esm/core.js +1 -0
  6. package/dist/esm/core.js.map +1 -1
  7. package/dist/esm/modules/crypto/algorithms/aes.algorithm.d.ts +7 -9
  8. package/dist/esm/modules/crypto/algorithms/aes.algorithm.js +56 -64
  9. package/dist/esm/modules/crypto/algorithms/aes.algorithm.js.map +1 -1
  10. package/dist/esm/modules/crypto/algorithms/base.algorithm.d.ts +12 -2
  11. package/dist/esm/modules/crypto/algorithms/base.algorithm.js +31 -21
  12. package/dist/esm/modules/crypto/algorithms/base.algorithm.js.map +1 -1
  13. package/dist/esm/modules/crypto/algorithms/derived-key-cache.d.ts +24 -0
  14. package/dist/esm/modules/crypto/algorithms/derived-key-cache.js +55 -0
  15. package/dist/esm/modules/crypto/algorithms/derived-key-cache.js.map +1 -0
  16. package/dist/esm/modules/crypto/algorithms/hash.algorithm.d.ts +15 -3
  17. package/dist/esm/modules/crypto/algorithms/hash.algorithm.js +24 -8
  18. package/dist/esm/modules/crypto/algorithms/hash.algorithm.js.map +1 -1
  19. package/dist/esm/modules/crypto/algorithms/rsa.algorithm.d.ts +0 -1
  20. package/dist/esm/modules/crypto/algorithms/rsa.algorithm.js +10 -24
  21. package/dist/esm/modules/crypto/algorithms/rsa.algorithm.js.map +1 -1
  22. package/dist/esm/modules/logger/formatting/deep-splat.js +2 -1
  23. package/dist/esm/modules/logger/formatting/deep-splat.js.map +1 -1
  24. package/dist/esm/modules/network/utilities/url-safety/common/types.d.ts +7 -0
  25. package/dist/esm/modules/network/utilities/url-safety/common/types.js.map +1 -1
  26. package/dist/esm/modules/network/utilities/url-safety/ingest.d.ts +51 -8
  27. package/dist/esm/modules/network/utilities/url-safety/ingest.js +189 -25
  28. package/dist/esm/modules/network/utilities/url-safety/ingest.js.map +1 -1
  29. package/dist/esm/modules/network/utilities/url-safety/policy.d.ts +20 -1
  30. package/dist/esm/modules/network/utilities/url-safety/policy.js +110 -26
  31. package/dist/esm/modules/network/utilities/url-safety/policy.js.map +1 -1
  32. package/dist/esm/modules/socket/socket-io/common/constants.d.ts +2 -0
  33. package/dist/esm/modules/socket/socket-io/common/constants.js +2 -0
  34. package/dist/esm/modules/socket/socket-io/common/constants.js.map +1 -1
  35. package/dist/esm/modules/socket/socket-io/server/helper.js +9 -5
  36. package/dist/esm/modules/socket/socket-io/server/helper.js.map +1 -1
  37. package/dist/esm/modules/socket/websocket/server/helper.js +9 -3
  38. package/dist/esm/modules/socket/websocket/server/helper.js.map +1 -1
  39. package/dist/esm/modules/storage/base.d.ts +1 -1
  40. package/dist/esm/modules/storage/base.js +19 -4
  41. package/dist/esm/modules/storage/base.js.map +1 -1
  42. package/dist/esm/modules/storage/bun-s3/helper.d.ts +6 -0
  43. package/dist/esm/modules/storage/bun-s3/helper.js +28 -8
  44. package/dist/esm/modules/storage/bun-s3/helper.js.map +1 -1
  45. package/dist/esm/modules/storage/disk/helper.d.ts +21 -1
  46. package/dist/esm/modules/storage/disk/helper.js +116 -15
  47. package/dist/esm/modules/storage/disk/helper.js.map +1 -1
  48. package/dist/esm/utilities/form-body.utility.d.ts +8 -0
  49. package/dist/esm/utilities/form-body.utility.js +5 -0
  50. package/dist/esm/utilities/form-body.utility.js.map +1 -1
  51. package/dist/esm/utilities/promise.utility.d.ts +16 -1
  52. package/dist/esm/utilities/promise.utility.js +35 -0
  53. package/dist/esm/utilities/promise.utility.js.map +1 -1
  54. package/dist/esm/utilities/record.utility.d.ts +11 -1
  55. package/dist/esm/utilities/record.utility.js +17 -1
  56. package/dist/esm/utilities/record.utility.js.map +1 -1
  57. package/dist/esm/utilities/request.utility.d.ts +4 -0
  58. package/dist/esm/utilities/request.utility.js +55 -4
  59. package/dist/esm/utilities/request.utility.js.map +1 -1
  60. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"base.algorithm.js","sourceRoot":"","sources":["../../../../../src/modules/crypto/algorithms/base.algorithm.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EACL,mBAAmB,EACnB,kBAAkB,EAClB,sBAAsB,EACtB,gBAAgB,EAChB,sBAAsB,GACvB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AAE/D,OAAO,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AAE/D,MAAM,sBAAsB,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;AAE3C,wEAAwE;AACxE,MAAM,cAAc,GAA2B,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC;AAErE,qGAAqG;AACrG,MAAM,iBAAiB,GAAG,IAAI,GAAG,EAA2B,CAAC;AAE7D,qIAAqI;AACrI,MAAM,OAAgB,mBAQpB,SAAQ,uBAQT;IACC,YAAY,IAAiD;QAC3D,KAAK,CAAC;YACJ,KAAK,EAAE,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,SAAS,IAAI,mBAAmB,CAAC,IAAI;YAC/D,UAAU,EAAE,IAAI,CAAC,SAAS;SAC3B,CAAC,CAAC;QACH,IAAI,CAAC,qBAAqB,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,CAAC,CAAC;QAE1D,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;IAClC,CAAC;IAED,qBAAqB,CAAC,IAAkC;QACtD,MAAM,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;QAE3B,IAAI,CAAC,SAAS,EAAE,CAAC;YACf,MAAM,QAAQ,CAAC;gB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AAC;QACzB,MAAM,UAAU,GAAG,MAAM,CAAC,UAAU,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAEvD,IAAI,UAAU,GAAG,sBAAsB,EAAE,CAAC;YACxC,MAAM,QAAQ,CAAC;gBACb,OAAO,EAAE,mEAAmE,sBAAsB,eAAe,UAAU,EAAE;aAC9H,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,mBAAmB;QACjB,MAAM,CAAC,GAAG,YAAY,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,SAAS,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,mBAAmB,EAAE,CAAC,CAAC;QAEhG,OAAO,YAAY,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAC9C,CAAC;CACF","sourcesContent":["import { getError } from '@/modules/error';\nimport { ParseUtility } from '@/utilities';\nimport {\n DEFAULT_CIPHER_BITS,\n DEFAULT_KDF_DIGEST,\n DEFAULT_KDF_ITERATIONS,\n DEFAULT_KDF_SALT,\n MINIMUM_KDF_SALT_BYTES,\n} from '../common';\nimport { AbstractCryptoAlgorithm } from './abstract.algorithm';\n\nexport { AbstractCryptoAlgorithm } from './abstract.algorithm';\n\nconst MAXIMUM_KDF_ITERATIONS = 2 ** 31 - 1;\n\n/** The Web Crypto name of each digest `DEFAULT_KDF_DIGEST` may hold. */\nconst KDF_HASH_NAMES: Record<string, string> = { sha256: 'SHA-256' };\n\n/** One entry per derivation. It holds the promise, so callers that arrive while it runs share it. */\nconst DERIVED_KEY_CACHE = new Map<string, Promise<Buffer>>();\n\n/** Base for the symmetric algorithms: validates the algorithm name and derives a key of a given length from a secret with PBKDF2. */\nexport abstract class BaseCryptoAlgorithm<\n AlgorithmType extends string,\n EncryptInputType = unknown,\n DecryptInputType = unknown,\n SecretKeyType = unknown,\n EncryptReturnType = unknown,\n DecryptReturnType = unknown,\n ExtraOptions = unknown,\n> extends AbstractCryptoAlgorithm<\n AlgorithmType,\n EncryptInputType,\n DecryptInputType,\n SecretKeyType,\n EncryptReturnType,\n DecryptReturnType,\n ExtraOptions\n> {\n constructor(opts: { scope: string; algorithm: AlgorithmType }) {\n super({\n scope: opts.scope ?? opts.algorithm ?? BaseCryptoAlgorithm.name,\n identifier: opts.algorithm,\n });\n this.validateAlgorithmName({ algorithm: opts.algorithm });\n\n this.algorithm = opts.algorithm;\n }\n\n validateAlgorithmName(opts: { algorithm: AlgorithmType }) {\n const { algorithm } = opts;\n\n if (!algorithm) {\n throw getError({\n message: `[validateAlgorithmName] Invalid algorithm name | algorithm: ${algorithm}`,\n });\n }\n }\n\n /**\n * Omit `kdfSalt`/`kdfIterations` for the shipped default (byte-identical to every prior release). Supplying either requires supplying the same value again on decrypt.\n * Derived with PBKDF2 over `crypto.subtle`, once per secret: a second call, even one that starts while the first runs, shares its result.\n */\n async normalizeSecretKey(opts: {\n secret: string;\n length: number;\n kdfSalt?: string;\n kdfIterations?: number;\n }): Promise<Buffer> {\n const { secret, length, kdfSalt, kdfIterations } = opts;\n\n if (kdfSalt !== undefined) {\n this.validateKdfSalt({ kdfSalt });\n }\n\n const salt = kdfSalt ?? DEFAULT_KDF_SALT;\n const iterations = kdfIterations ?? DEFAULT_KDF_ITERATIONS;\n\n // `pbkdf2Sync` refused anything but an integer from 1 up to 2^31 - 1; Web Crypto would round a fraction down and take up to 2^32 - 1.\n if (!Number.isInteger(iterations) || iterations < 1 || iterations > MAXIMUM_KDF_ITERATIONS) {\n throw getError({\n message: `[BaseCryptoAlgorithm][normalizeSecretKey] kdfIterations must be an integer from 1 to ${MAXIMUM_KDF_ITERATIONS}, got ${iterations}`,\n });\n }\n\n const cacheKey = `${DEFAULT_KDF_DIGEST}:${iterations}:${length}:${salt}:${secret}`;\n\n return this.deriveOnce({\n cacheKey,\n derive: () => this.derivePbkdf2({ secret, salt, iterations, length }),\n });\n }\n\n /** Runs `derive` once per `cacheKey`. A failed derivation leaves nothing behind, so the next call tries again. */\n private deriveOnce(opts: { cacheKey: string; derive: () => Promise<Buffer> }): Promise<Buffer> {\n const { cacheKey, derive } = opts;\n const pending = DERIVED_KEY_CACHE.get(cacheKey);\n\n if (pending) {\n return pending;\n }\n\n const derived = derive();\n DERIVED_KEY_CACHE.set(cacheKey, derived);\n derived.catch(() => {\n if (DERIVED_KEY_CACHE.get(cacheKey) === derived) {\n DERIVED_KEY_CACHE.delete(cacheKey);\n }\n });\n\n return derived;\n }\n\n private async derivePbkdf2(opts: {\n secret: string;\n salt: string;\n iterations: number;\n length: number;\n }): Promise<Buffer> {\n const { secret, salt, iterations, length } = opts;\n const hash = KDF_HASH_NAMES[DEFAULT_KDF_DIGEST];\n\n if (hash === undefined) {\n throw getError({\n message: `[BaseCryptoAlgorithm][derivePbkdf2] No Web Crypto name for the digest \"${DEFAULT_KDF_DIGEST}\"`,\n });\n }\n\n const encoder = new TextEncoder();\n const material = await crypto.subtle.importKey('raw', encoder.encode(secret), 'PBKDF2', false, [\n 'deriveBits',\n ]);\n const bits = await crypto.subtle.deriveBits(\n { name: 'PBKDF2', hash, salt: encoder.encode(salt), iterations },\n material,\n length * 8,\n );\n\n return Buffer.from(bits);\n }\n\n /** Rejects a `kdfSalt` short enough to look configured while giving up most of the protection a salt exists for (NIST SP 800-132: 128-bit minimum). */\n private validateKdfSalt(opts: { kdfSalt: string }): void {\n const { kdfSalt } = opts;\n const byteLength = Buffer.byteLength(kdfSalt, 'utf-8');\n\n if (byteLength < MINIMUM_KDF_SALT_BYTES) {\n throw getError({\n message: `[BaseCryptoAlgorithm][validateKdfSalt] kdfSalt must be at least ${MINIMUM_KDF_SALT_BYTES} bytes, got ${byteLength}`,\n });\n }\n }\n\n getAlgorithmKeySize() {\n const b = ParseUtility.toInt({ input: this.algorithm?.split('-')?.[1] ?? DEFAULT_CIPHER_BITS });\n\n return ParseUtility.toInt({ input: b / 8 });\n }\n}\n"]}
1
+ {"version":3,"file":"base.algorithm.js","sour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M,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;QACzB,MAAM,UAAU,GAAG,MAAM,CAAC,UAAU,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAEvD,IAAI,UAAU,GAAG,sBAAsB,EAAE,CAAC;YACxC,MAAM,QAAQ,CAAC;gBACb,OAAO,EAAE,mEAAmE,sBAAsB,eAAe,UAAU,EAAE;aAC9H,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,mBAAmB;QACjB,MAAM,CAAC,GAAG,YAAY,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,SAAS,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,mBAAmB,EAAE,CAAC,CAAC;QAEhG,OAAO,YAAY,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAC9C,CAAC","sourcesContent":["import { getError } from '@/modules/error';\nimport { ParseUtility } from '@/utilities';\nimport {\n DEFAULT_CIPHER_BITS,\n DEFAULT_KDF_DIGEST,\n DEFAULT_KDF_ITERATIONS,\n DEFAULT_KDF_SALT,\n MINIMUM_KDF_SALT_BYTES,\n} from '../common';\nimport { AbstractCryptoAlgorithm } from './abstract.algorithm';\nimport { DerivedKeyCache } from './derived-key-cache';\n\nexport { AbstractCryptoAlgorithm } from './abstract.algorithm';\n\nconst MAXIMUM_KDF_ITERATIONS = 2 ** 31 - 1;\n\n/** The Web Crypto name of each digest `DEFAULT_KDF_DIGEST` may hold. */\nconst KDF_HASH_NAMES: Record<string, string> = { sha256: 'SHA-256' };\n\n/** One entry per derivation, bounded. It holds the promise, so callers that arrive while it runs share it. */\nconst DERIVED_KEY_CACHE = new DerivedKeyCache();\n\n/** Base for the symmetric algorithms: validates the algorithm name and derives a key of a given length from a secret with PBKDF2. */\nexport abstract class BaseCryptoAlgorithm<\n AlgorithmType extends string,\n EncryptInputType = unknown,\n DecryptInputType = unknown,\n SecretKeyType = unknown,\n EncryptReturnType = unknown,\n DecryptReturnType = unknown,\n ExtraOptions = unknown,\n> extends AbstractCryptoAlgorithm<\n AlgorithmType,\n EncryptInputType,\n DecryptInputType,\n SecretKeyType,\n EncryptReturnType,\n DecryptReturnType,\n ExtraOptions\n> {\n /** What a caller that still passes a removed option is told: the option, and what replaced it. */\n private static readonly REMOVED_OPTION_HINTS: Record<string, string> = {\n doThrow:\n 'a failure always throws: catch the error where a fallback is wanted, and never treat the input as the result',\n iv: 'every encryption draws a fresh random IV, and decrypt reads it from the ciphertext: a chosen IV is how a nonce is reused',\n };\n\n /**\n * A caller that still passes a removed option is refused, not ignored, so nobody believes it still works.\n * `doThrow: false` is gone: a failed encrypt or decrypt used to hand the input back, which a caller could take for\n * ciphertext or plaintext. `iv` is gone from AES: a caller-chosen IV reused under GCM breaks confidentiality and integrity.\n */\n protected assertNoRemovedOptions(opts: {\n method: string;\n options?: object;\n removed?: ReadonlyArray<string>;\n }): void {\n const { method, options, removed = ['doThrow'] } = opts;\n\n if (options === undefined || options === null) {\n return;\n }\n\n for (const name of removed) {\n if (name in options) {\n throw getError({\n message: `[${this.constructor.name}][${method}] The ${name} option was removed | ${BaseCryptoAlgorithm.REMOVED_OPTION_HINTS[name]}`,\n });\n }\n }\n }\n\n constructor(opts: { scope: string; algorithm: AlgorithmType }) {\n super({\n scope: opts.scope ?? opts.algorithm ?? BaseCryptoAlgorithm.name,\n identifier: opts.algorithm,\n });\n this.validateAlgorithmName({ algorithm: opts.algorithm });\n\n this.algorithm = opts.algorithm;\n }\n\n validateAlgorithmName(opts: { algorithm: AlgorithmType }) {\n const { algorithm } = opts;\n\n if (!algorithm) {\n throw getError({\n message: `[validateAlgorithmName] Invalid algorithm name | algorithm: ${algorithm}`,\n });\n }\n }\n\n /**\n * Omit `kdfSalt`/`kdfIterations` for the shipped default (byte-identical to every prior release). Supplying either requires supplying the same value again on decrypt.\n * Derived with PBKDF2 over `crypto.subtle`, once per secret: a second call, even one that starts while the first runs, shares its result.\n */\n async normalizeSecretKey(opts: {\n secret: string;\n length: number;\n kdfSalt?: string;\n kdfIterations?: number;\n }): Promise<Buffer> {\n const { secret, length, kdfSalt, kdfIterations } = opts;\n\n if (kdfSalt !== undefined) {\n this.validateKdfSalt({ kdfSalt });\n }\n\n const salt = kdfSalt ?? DEFAULT_KDF_SALT;\n const iterations = kdfIterations ?? DEFAULT_KDF_ITERATIONS;\n\n // `pbkdf2Sync` refused anything but an integer from 1 up to 2^31 - 1; Web Crypto would round a fraction down and take up to 2^32 - 1.\n if (!Number.isInteger(iterations) || iterations < 1 || iterations > MAXIMUM_KDF_ITERATIONS) {\n throw getError({\n message: `[BaseCryptoAlgorithm][normalizeSecretKey] kdfIterations must be an integer from 1 to ${MAXIMUM_KDF_ITERATIONS}, got ${iterations}`,\n });\n }\n\n const key = DerivedKeyCache.keyOf({\n parts: [DEFAULT_KDF_DIGEST, iterations, length, salt, secret],\n });\n\n return DERIVED_KEY_CACHE.deriveOnce({\n key,\n derive: () => this.derivePbkdf2({ secret, salt, iterations, length }),\n });\n }\n\n private async derivePbkdf2(opts: {\n secret: string;\n salt: string;\n iterations: number;\n length: number;\n }): Promise<Buffer> {\n const { secret, salt, iterations, length } = opts;\n const hash = KDF_HASH_NAMES[DEFAULT_KDF_DIGEST];\n\n if (hash === undefined) {\n throw getError({\n message: `[BaseCryptoAlgorithm][derivePbkdf2] No Web Crypto name for the digest \"${DEFAULT_KDF_DIGEST}\"`,\n });\n }\n\n const encoder = new TextEncoder();\n const material = await crypto.subtle.importKey('raw', encoder.encode(secret), 'PBKDF2', false, [\n 'deriveBits',\n ]);\n const bits = await crypto.subtle.deriveBits(\n { name: 'PBKDF2', hash, salt: encoder.encode(salt), iterations },\n material,\n length * 8,\n );\n\n return Buffer.from(bits);\n }\n\n /** Rejects a `kdfSalt` short enough to look configured while giving up most of the protection a salt exists for (NIST SP 800-132: 128-bit minimum). */\n private validateKdfSalt(opts: { kdfSalt: string }): void {\n const { kdfSalt } = opts;\n const byteLength = Buffer.byteLength(kdfSalt, 'utf-8');\n\n if (byteLength < MINIMUM_KDF_SALT_BYTES) {\n throw getError({\n message: `[BaseCryptoAlgorithm][validateKdfSalt] kdfSalt must be at least ${MINIMUM_KDF_SALT_BYTES} bytes, got ${byteLength}`,\n });\n }\n }\n\n getAlgorithmKeySize() {\n const b = ParseUtility.toInt({ input: this.algorithm?.split('-')?.[1] ?? DEFAULT_CIPHER_BITS });\n\n return ParseUtility.toInt({ input: b / 8 });\n }\n}\n"]}
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The keys PBKDF2 has derived, kept so a second call (one that starts while the first runs included) shares the result.
3
+ * Bounded, least recently used out first: the entries are keyed by what went into the derivation, which includes a secret
4
+ * a caller may supply per request, so an unbounded map would grow with every distinct one. The key is an HMAC of the
5
+ * inputs under a random key made once per process, so the secret itself is not kept as a map key, and a key read from
6
+ * memory cannot be tested against guesses at SHA-256 speed without that process key.
7
+ */
8
+ export declare class DerivedKeyCache {
9
+ static readonly MAX_ENTRIES = 64;
10
+ /** Made once per process and never leaves it: a cache key from one process means nothing in another. */
11
+ private static readonly PROCESS_KEY;
12
+ private readonly entries;
13
+ get size(): number;
14
+ /** The keyed digest of the derivation inputs: what the cache is keyed by. */
15
+ static keyOf(opts: {
16
+ parts: Array<string | number>;
17
+ }): string;
18
+ /** Runs `derive` once per key. A failed derivation leaves nothing behind, so the next call tries again. */
19
+ deriveOnce(opts: {
20
+ key: string;
21
+ derive: () => Promise<Buffer>;
22
+ }): Promise<Buffer>;
23
+ }
24
+ //# sourceMappingURL=derived-key-cache.d.ts.map
@@ -0,0 +1,55 @@
1
+ import { createHmac, randomBytes } from 'node:crypto';
2
+ /**
3
+ * The keys PBKDF2 has derived, kept so a second call (one that starts while the first runs included) shares the result.
4
+ * Bounded, least recently used out first: the entries are keyed by what went into the derivation, which includes a secret
5
+ * a caller may supply per request, so an unbounded map would grow with every distinct one. The key is an HMAC of the
6
+ * inputs under a random key made once per process, so the secret itself is not kept as a map key, and a key read from
7
+ * memory cannot be tested against guesses at SHA-256 speed without that process key.
8
+ */
9
+ export class DerivedKeyCache {
10
+ constructor() {
11
+ this.entries = new Map();
12
+ }
13
+ static { this.MAX_ENTRIES = 64; }
14
+ /** Made once per process and never leaves it: a cache key from one process means nothing in another. */
15
+ static { this.PROCESS_KEY = randomBytes(32); }
16
+ get size() {
17
+ return this.entries.size;
18
+ }
19
+ /** The keyed digest of the derivation inputs: what the cache is keyed by. */
20
+ static keyOf(opts) {
21
+ const hash = createHmac('sha256', DerivedKeyCache.PROCESS_KEY);
22
+ for (const part of opts.parts) {
23
+ const text = String(part);
24
+ // Length-prefixed, so ["ab", "c"] and ["a", "bc"] cannot meet.
25
+ hash.update(`${text.length}:${text}`);
26
+ }
27
+ return hash.digest('hex');
28
+ }
29
+ /** Runs `derive` once per key. A failed derivation leaves nothing behind, so the next call tries again. */
30
+ deriveOnce(opts) {
31
+ const { key, derive } = opts;
32
+ const pending = this.entries.get(key);
33
+ if (pending) {
34
+ // Most recently used moves to the end.
35
+ this.entries.delete(key);
36
+ this.entries.set(key, pending);
37
+ return pending;
38
+ }
39
+ const derived = derive();
40
+ this.entries.set(key, derived);
41
+ for (const oldest of this.entries.keys()) {
42
+ if (this.entries.size <= DerivedKeyCache.MAX_ENTRIES) {
43
+ break;
44
+ }
45
+ this.entries.delete(oldest);
46
+ }
47
+ derived.catch(() => {
48
+ if (this.entries.get(key) === derived) {
49
+ this.entries.delete(key);
50
+ }
51
+ });
52
+ return derived;
53
+ }
54
+ }
55
+ //# sourceMappingURL=derived-key-cache.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"derived-key-cache.js","sourceRoot":"","sources":["../../../../../src/modules/crypto/algorithms/derived-key-cache.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAEtD;;;;;;GAMG;AACH,MAAM,OAAO,eAAe;IAA5B;QAMmB,YAAO,GAAG,IAAI,GAAG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AC;YACzC,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,IAAI,eAAe,CAAC,WAAW,EAAE,CAAC;gBACrD,MAAM;YACR,CAAC;YAED,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QAC9B,CAAC;QAED,OAAO,CAAC,KAAK,CAAC,GAAG,EAAE;YACjB,IAAI,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,OAAO,EAAE,CAAC;gBACtC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;YAC3B,CAAC;QACH,CAAC,CAAC,CAAC;QAEH,OAAO,OAAO,CAAC;IACjB,CAAC","sourcesContent":["import { createHmac, randomBytes } from 'node:crypto';\n\n/**\n * The keys PBKDF2 has derived, kept so a second call (one that starts while the first runs included) shares the result.\n * Bounded, least recently used out first: the entries are keyed by what went into the derivation, which includes a secret\n * a caller may supply per request, so an unbounded map would grow with every distinct one. The key is an HMAC of the\n * inputs under a random key made once per process, so the secret itself is not kept as a map key, and a key read from\n * memory cannot be tested against guesses at SHA-256 speed without that process key.\n */\nexport class DerivedKeyCache {\n static readonly MAX_ENTRIES = 64;\n\n /** Made once per process and never leaves it: a cache key from one process means nothing in another. */\n private static readonly PROCESS_KEY = randomBytes(32);\n\n private readonly entries = new Map<string, Promise<Buffer>>();\n\n get size(): number {\n return this.entries.size;\n }\n\n /** The keyed digest of the derivation inputs: what the cache is keyed by. */\n static keyOf(opts: { parts: Array<string | number> }): string {\n const hash = createHmac('sha256', DerivedKeyCache.PROCESS_KEY);\n\n for (const part of opts.parts) {\n const text = String(part);\n\n // Length-prefixed, so [\"ab\", \"c\"] and [\"a\", \"bc\"] cannot meet.\n hash.update(`${text.length}:${text}`);\n }\n\n return hash.digest('hex');\n }\n\n /** Runs `derive` once per key. A failed derivation leaves nothing behind, so the next call tries again. */\n deriveOnce(opts: { key: string; derive: () => Promise<Buffer> }): Promise<Buffer> {\n const { key, derive } = opts;\n const pending = this.entries.get(key);\n\n if (pending) {\n // Most recently used moves to the end.\n this.entries.delete(key);\n this.entries.set(key, pending);\n\n return pending;\n }\n\n const derived = derive();\n this.entries.set(key, derived);\n\n for (const oldest of this.entries.keys()) {\n if (this.entries.size <= DerivedKeyCache.MAX_ENTRIES) {\n break;\n }\n\n this.entries.delete(oldest);\n }\n\n derived.catch(() => {\n if (this.entries.get(key) === derived) {\n this.entries.delete(key);\n }\n });\n\n return derived;\n }\n}\n"]}
@@ -39,15 +39,27 @@ export declare class Hash extends BaseHelper {
39
39
  secret: THashInput;
40
40
  opts?: IHashExtraOptions;
41
41
  }): string;
42
+ /**
43
+ * Compares two strings exactly as given, in constant time: the byte length first, then `crypto.timingSafeEqual`. For
44
+ * two digests that are both already in hand, such as an idempotency fingerprint against a saved one, where
45
+ * {@link Hash.verify} has nothing to hash. `false` for any difference, never a throw, and `false` too for a value that
46
+ * is not a string. Two empty strings are equal. The text is compared, not the bytes it stands for: hex in upper case
47
+ * does not equal hex in lower case.
48
+ */
49
+ static equals(opts: {
50
+ value: string;
51
+ expected: string;
52
+ }): boolean;
42
53
  /**
43
54
  * Checks a received digest against the one `value` produces, in constant time. Use it for a webhook signature or a
44
55
  * payment callback instead of `===`, which stops at the first differing character and so tells an attacker how many
45
56
  * leading characters of a forged value were right.
46
57
  *
47
58
  * `value` is hashed the way {@link Hash.digest} does, or keyed with `secret` the way {@link Hash.hmac} does, then
48
- * written in `outputEncoding` (hex by default) and compared with `expected` as text. A different length answers
49
- * `false` without comparing, and the answer is `false`, never a throw, for any mismatch. The text must match exactly:
50
- * hex in upper case does not equal hex in lower case.
59
+ * written in `outputEncoding` (hex by default) and compared with `expected` by {@link Hash.equals}. A different length
60
+ * answers `false` without comparing, and the answer is `false`, never a throw, for any mismatch. `expected` is exact
61
+ * text: hex in upper case does not equal hex in lower case, and an unpadded or URL-safe form of the same base64 digest
62
+ * is refused. Pass the matching `outputEncoding` (`base64url`), or normalise the text first.
51
63
  */
52
64
  verify(opts: {
53
65
  value: THashInput;
@@ -60,24 +60,40 @@ export class Hash extends BaseHelper {
60
60
  }
61
61
  return new Bun.CryptoHasher(this.algorithm, secret).update(message).digest(outputEncoding);
62
62
  }
63
+ /**
64
+ * Compares two strings exactly as given, in constant time: the byte length first, then `crypto.timingSafeEqual`. For
65
+ * two digests that are both already in hand, such as an idempotency fingerprint against a saved one, where
66
+ * {@link Hash.verify} has nothing to hash. `false` for any difference, never a throw, and `false` too for a value that
67
+ * is not a string. Two empty strings are equal. The text is compared, not the bytes it stands for: hex in upper case
68
+ * does not equal hex in lower case.
69
+ */
70
+ static equals(opts) {
71
+ const { value, expected } = opts;
72
+ if (typeof value !== 'string' || typeof expected !== 'string') {
73
+ return false;
74
+ }
75
+ const left = Buffer.from(value);
76
+ const right = Buffer.from(expected);
77
+ // Length-checked first: `timingSafeEqual` throws on a length mismatch instead of answering false.
78
+ return left.length === right.length && crypto.timingSafeEqual(left, right);
79
+ }
63
80
  /**
64
81
  * Checks a received digest against the one `value` produces, in constant time. Use it for a webhook signature or a
65
82
  * payment callback instead of `===`, which stops at the first differing character and so tells an attacker how many
66
83
  * leading characters of a forged value were right.
67
84
  *
68
85
  * `value` is hashed the way {@link Hash.digest} does, or keyed with `secret` the way {@link Hash.hmac} does, then
69
- * written in `outputEncoding` (hex by default) and compared with `expected` as text. A different length answers
70
- * `false` without comparing, and the answer is `false`, never a throw, for any mismatch. The text must match exactly:
71
- * hex in upper case does not equal hex in lower case.
86
+ * written in `outputEncoding` (hex by default) and compared with `expected` by {@link Hash.equals}. A different length
87
+ * answers `false` without comparing, and the answer is `false`, never a throw, for any mismatch. `expected` is exact
88
+ * text: hex in upper case does not equal hex in lower case, and an unpadded or URL-safe form of the same base64 digest
89
+ * is refused. Pass the matching `outputEncoding` (`base64url`), or normalise the text first.
72
90
  */
73
91
  verify(opts) {
74
92
  const { value, expected, secret } = opts;
75
- const computed = Buffer.from(secret === undefined
93
+ const computed = secret === undefined
76
94
  ? this.digest({ message: value, opts: opts.opts })
77
- : this.hmac({ message: value, secret, opts: opts.opts }));
78
- const given = Buffer.from(expected);
79
- // Length-checked first: `timingSafeEqual` throws on a length mismatch instead of answering false.
80
- return computed.length === given.length && crypto.timingSafeEqual(computed, given);
95
+ : this.hmac({ message: value, secret, opts: opts.opts });
96
+ return Hash.equals({ value: computed, expected });
81
97
  }
82
98
  }
83
99
  //# sourceMappingURL=hash.algorithm.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"hash.algorithm.js","sourceRoot":"","sources":["../../../../../src/modules/crypto/algorithms/hash.algorithm.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,aAAa,CAAC;AAEjC,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EACL,4BAA4B,EAC5B,cAAc,GAGf,MAAM,WAAW,CAAC;AASnB;;;GAGG;AACH,MAAM,OAAO,IAAK,SAAQ,UAAU;IAGlC,YAAY,IAAmC;QAC7C,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,IAAI,EAAE,UAAU,EAAE,IAAI,CAAC,SAAS,EAAE,CAAC,CAAC;QACxD,IAAI,CAAC,qBAAqB,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,CAAC,CAAC;QAE1D,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;IAClC,CAAC;IAED,wJAAwJ;aAChI,cAAS,GAAG,IAAI,GAAG,EAAwB,CAAC;IAEpE,MAAM,CAAC,aAAa,CAAC,SAAyB;QAC5C,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;QAE7C,IAAI,MAAM,EAAE,CAAC;YACX,OAAO,MAAM,CAAC;QAChB,CAAC;QAED,MAAM,OAAO,GAAG,IAAI,IAAI,CAAC,EAAE,SAAS,EAAE,CAAC,CAAC;QAC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,CAAC,CAAC;QACL,CAAC;QAED,OAAO,IAAI,GAAG,CAAC,YAAY,CAAC,IAAI,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;IAC7F,CAAC;IAED;;;;;;;;;OASG;IACH,MAAM,CAAC,IAKN;QACC,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;QACzC,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,CAC1B,MAAM,KAAK,SAAS;YAClB,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,CAAC;YAClD,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,CAAC,CAC3D,CAAC;QACF,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAEpC,kGAAkG;QAClG,OAAO,QAAQ,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM,IAAI,MAAM,CAAC,eAAe,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;IACrF,CAAC","sourcesContent":["import crypto from 'node:crypto';\n\nimport { BaseHelper } from '@/modules/base';\nimport { getError } from '@/modules/error';\nimport {\n DEFAULT_HASH_OUTPUT_ENCODING,\n HashAlgorithms,\n type THashAlgorithm,\n type THashOutputEncoding,\n} from '../common';\n\ninterface IHashExtraOptions {\n outputEncoding?: THashOutputEncoding;\n}\n\n/** Text is hashed as UTF-8, bytes as they are. */\ntype THashInput = string | Uint8Array;\n\n/**\n * One-way message digests and keyed HMACs. Unlike `AES`/`RSA` this has no `decrypt` - a digest\n * cannot be reversed, so `digest`/`hmac` are the only operations, not `ICryptoAlgorithm`.\n */\nexport class Hash extends BaseHelper {\n algorithm: THashAlgorithm;\n\n constructor(opts: { algorithm: THashAlgorithm }) {\n super({ scope: Hash.name, identifier: opts.algorithm });\n this.validateAlgorithmName({ algorithm: opts.algorithm });\n\n this.algorithm = opts.algorithm;\n }\n\n /** Memoized - `BaseHelper`'s constructor resolves a logger on every allocation (~50ns), and downstream token code calls `withAlgorithm` per request. */\n private static readonly instances = new Map<THashAlgorithm, Hash>();\n\n static withAlgorithm(algorithm: THashAlgorithm) {\n const cached = Hash.instances.get(algorithm);\n\n if (cached) {\n return cached;\n }\n\n const created = new Hash({ algorithm });\n Hash.instances.set(algorithm, created);\n\n return created;\n }\n\n validateAlgorithmName(opts: { algorithm: THashAlgorithm }) {\n const { algorithm } = opts;\n\n if (!algorithm || !HashAlgorithms.isValid(algorithm)) {\n throw getError({\n message: `[Hash][validateAlgorithmName] Invalid algorithm name | algorithm: ${algorithm}`,\n });\n }\n }\n\n /**\n * Plain digest, no secret. `message` is text (UTF-8), bytes, or several parts hashed in order as ONE message: a git\n * blob is the header text \"blob <size>\" and a NUL byte, then the bytes, so its parts are the header and the bytes. MD5/SHA1\n * are broken/weak - see {@link HashAlgorithms} - never use for security decisions.\n */\n digest(opts: {\n message: THashInput | ReadonlyArray<THashInput>;\n opts?: IHashExtraOptions;\n }): string {\n const { message } = opts;\n const { outputEncoding = DEFAULT_HASH_OUTPUT_ENCODING } = opts.opts ?? {};\n const hash = new Bun.CryptoHasher(this.algorithm);\n\n for (const part of Array.isArray(message) ? message : [message]) {\n hash.update(part);\n }\n\n return hash.digest(outputEncoding);\n }\n\n /**\n * Keyed HMAC. `message` and `secret` are text (UTF-8) or bytes: a `Buffer` or `Uint8Array` key gives the same output\n * as the text of the same bytes, so a token printed with one keeps verifying with the other. `secret` is mandatory and\n * validated non-empty so a request for an HMAC never silently degrades into an unkeyed digest.\n */\n hmac(opts: { message: THashInput; secret: THashInput; opts?: IHashExtraOptions }): string {\n const { message, secret } = opts;\n const { outputEncoding = DEFAULT_HASH_OUTPUT_ENCODING } = opts.opts ?? {};\n\n if (secret.length === 0) {\n throw getError({\n message: `[Hash][hmac] Missing secret for HMAC-${this.algorithm.toUpperCase()}`,\n });\n }\n\n return new Bun.CryptoHasher(this.algorithm, secret).update(message).digest(outputEncoding);\n }\n\n /**\n * Checks a received digest against the one `value` produces, in constant time. Use it for a webhook signature or a\n * payment callback instead of `===`, which stops at the first differing character and so tells an attacker how many\n * leading characters of a forged value were right.\n *\n * `value` is hashed the way {@link Hash.digest} does, or keyed with `secret` the way {@link Hash.hmac} does, then\n * written in `outputEncoding` (hex by default) and compared with `expected` as text. A different length answers\n * `false` without comparing, and the answer is `false`, never a throw, for any mismatch. The text must match exactly:\n * hex in upper case does not equal hex in lower case.\n */\n verify(opts: {\n value: THashInput;\n expected: string;\n secret?: THashInput;\n opts?: IHashExtraOptions;\n }): boolean {\n const { value, expected, secret } = opts;\n const computed = Buffer.from(\n secret === undefined\n ? this.digest({ message: value, opts: opts.opts })\n : this.hmac({ message: value, secret, opts: opts.opts }),\n );\n const given = Buffer.from(expected);\n\n // Length-checked first: `timingSafeEqual` throws on a length mismatch instead of answering false.\n return computed.length === given.length && crypto.timingSafeEqual(computed, given);\n }\n}\n"]}
1
+ {"version":3,"file":"hash.algorithm.js","sourceRoot":"","sources":["../../../../../src/modules/crypto/algorithms/hash.algorithm.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,aAAa,CAAC;AAEjC,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EACL,4BAA4B,EAC5B,cAAc,GAGf,MAAM,WAAW,CAAC;AASnB;;;GAGG;AACH,MAAM,OAAO,IAAK,SAAQ,UAAU;IAGlC,YAAY,IAAmC;QAC7C,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,IAAI,EAAE,UAAU,EAAE,IAAI,CAAC,SAAS,EAAE,CAAC,CAAC;QACxD,IAAI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E,MAAM,EAAE,GAAG,IAAI,CAAC;QACzC,MAAM,QAAQ,GACZ,MAAM,KAAK,SAAS;YAClB,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,CAAC;YAClD,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;QAE7D,OAAO,IAAI,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,CAAC,CAAC;IACpD,CAAC","sourcesContent":["import crypto from 'node:crypto';\n\nimport { BaseHelper } from '@/modules/base';\nimport { getError } from '@/modules/error';\nimport {\n DEFAULT_HASH_OUTPUT_ENCODING,\n HashAlgorithms,\n type THashAlgorithm,\n type THashOutputEncoding,\n} from '../common';\n\ninterface IHashExtraOptions {\n outputEncoding?: THashOutputEncoding;\n}\n\n/** Text is hashed as UTF-8, bytes as they are. */\ntype THashInput = string | Uint8Array;\n\n/**\n * One-way message digests and keyed HMACs. Unlike `AES`/`RSA` this has no `decrypt` - a digest\n * cannot be reversed, so `digest`/`hmac` are the only operations, not `ICryptoAlgorithm`.\n */\nexport class Hash extends BaseHelper {\n algorithm: THashAlgorithm;\n\n constructor(opts: { algorithm: THashAlgorithm }) {\n super({ scope: Hash.name, identifier: opts.algorithm });\n this.validateAlgorithmName({ algorithm: opts.algorithm });\n\n this.algorithm = opts.algorithm;\n }\n\n /** Memoized - `BaseHelper`'s constructor resolves a logger on every allocation (~50ns), and downstream token code calls `withAlgorithm` per request. */\n private static readonly instances = new Map<THashAlgorithm, Hash>();\n\n static withAlgorithm(algorithm: THashAlgorithm) {\n const cached = Hash.instances.get(algorithm);\n\n if (cached) {\n return cached;\n }\n\n const created = new Hash({ algorithm });\n Hash.instances.set(algorithm, created);\n\n return created;\n }\n\n validateAlgorithmName(opts: { algorithm: THashAlgorithm }) {\n const { algorithm } = opts;\n\n if (!algorithm || !HashAlgorithms.isValid(algorithm)) {\n throw getError({\n message: `[Hash][validateAlgorithmName] Invalid algorithm name | algorithm: ${algorithm}`,\n });\n }\n }\n\n /**\n * Plain digest, no secret. `message` is text (UTF-8), bytes, or several parts hashed in order as ONE message: a git\n * blob is the header text \"blob <size>\" and a NUL byte, then the bytes, so its parts are the header and the bytes. MD5/SHA1\n * are broken/weak - see {@link HashAlgorithms} - never use for security decisions.\n */\n digest(opts: {\n message: THashInput | ReadonlyArray<THashInput>;\n opts?: IHashExtraOptions;\n }): string {\n const { message } = opts;\n const { outputEncoding = DEFAULT_HASH_OUTPUT_ENCODING } = opts.opts ?? {};\n const hash = new Bun.CryptoHasher(this.algorithm);\n\n for (const part of Array.isArray(message) ? message : [message]) {\n hash.update(part);\n }\n\n return hash.digest(outputEncoding);\n }\n\n /**\n * Keyed HMAC. `message` and `secret` are text (UTF-8) or bytes: a `Buffer` or `Uint8Array` key gives the same output\n * as the text of the same bytes, so a token printed with one keeps verifying with the other. `secret` is mandatory and\n * validated non-empty so a request for an HMAC never silently degrades into an unkeyed digest.\n */\n hmac(opts: { message: THashInput; secret: THashInput; opts?: IHashExtraOptions }): string {\n const { message, secret } = opts;\n const { outputEncoding = DEFAULT_HASH_OUTPUT_ENCODING } = opts.opts ?? {};\n\n if (secret.length === 0) {\n throw getError({\n message: `[Hash][hmac] Missing secret for HMAC-${this.algorithm.toUpperCase()}`,\n });\n }\n\n return new Bun.CryptoHasher(this.algorithm, secret).update(message).digest(outputEncoding);\n }\n\n /**\n * Compares two strings exactly as given, in constant time: the byte length first, then `crypto.timingSafeEqual`. For\n * two digests that are both already in hand, such as an idempotency fingerprint against a saved one, where\n * {@link Hash.verify} has nothing to hash. `false` for any difference, never a throw, and `false` too for a value that\n * is not a string. Two empty strings are equal. The text is compared, not the bytes it stands for: hex in upper case\n * does not equal hex in lower case.\n */\n static equals(opts: { value: string; expected: string }): boolean {\n const { value, expected } = opts;\n\n if (typeof value !== 'string' || typeof expected !== 'string') {\n return false;\n }\n\n const left = Buffer.from(value);\n const right = Buffer.from(expected);\n\n // Length-checked first: `timingSafeEqual` throws on a length mismatch instead of answering false.\n return left.length === right.length && crypto.timingSafeEqual(left, right);\n }\n\n /**\n * Checks a received digest against the one `value` produces, in constant time. Use it for a webhook signature or a\n * payment callback instead of `===`, which stops at the first differing character and so tells an attacker how many\n * leading characters of a forged value were right.\n *\n * `value` is hashed the way {@link Hash.digest} does, or keyed with `secret` the way {@link Hash.hmac} does, then\n * written in `outputEncoding` (hex by default) and compared with `expected` by {@link Hash.equals}. A different length\n * answers `false` without comparing, and the answer is `false`, never a throw, for any mismatch. `expected` is exact\n * text: hex in upper case does not equal hex in lower case, and an unpadded or URL-safe form of the same base64 digest\n * is refused. Pass the matching `outputEncoding` (`base64url`), or normalise the text first.\n */\n verify(opts: {\n value: THashInput;\n expected: string;\n secret?: THashInput;\n opts?: IHashExtraOptions;\n }): boolean {\n const { value, expected, secret } = opts;\n const computed =\n secret === undefined\n ? this.digest({ message: value, opts: opts.opts })\n : this.hmac({ message: value, secret, opts: opts.opts });\n\n return Hash.equals({ value: computed, expected });\n }\n}\n"]}
@@ -5,7 +5,6 @@ interface IRSAExtraOptions {
5
5
  message: BufferEncoding;
6
6
  };
7
7
  outputEncoding?: BufferEncoding;
8
- doThrow?: boolean;
9
8
  }
10
9
  /** The algorithm name `RSA` reports as its `algorithm`. */
11
10
  export type RSAAlgorithmType = 'rsa';
@@ -35,33 +35,19 @@ export class RSA extends BaseCryptoAlgorithm {
35
35
  }
36
36
  async encrypt(opts) {
37
37
  const { message, secret: pubKey } = opts;
38
- const { inputEncoding = { key: 'base64', message: 'utf-8' }, outputEncoding = 'base64', doThrow = true, } = opts.opts ?? {};
39
- try {
40
- const key = await crypto.subtle.importKey('spki', Buffer.from(pubKey, inputEncoding.key), OAEP, false, ['encrypt']);
41
- const cipherBytes = await crypto.subtle.encrypt({ name: OAEP.name }, key, Buffer.from(message, inputEncoding.message));
42
- return Buffer.from(cipherBytes).toString(outputEncoding);
43
- }
44
- catch (error) {
45
- if (doThrow) {
46
- throw error;
47
- }
48
- return message;
49
- }
38
+ this.assertNoRemovedOptions({ method: 'encrypt', options: opts.opts });
39
+ const { inputEncoding = { key: 'base64', message: 'utf-8' }, outputEncoding = 'base64' } = opts.opts ?? {};
40
+ const key = await crypto.subtle.importKey('spki', Buffer.from(pubKey, inputEncoding.key), OAEP, false, ['encrypt']);
41
+ const cipherBytes = await crypto.subtle.encrypt({ name: OAEP.name }, key, Buffer.from(message, inputEncoding.message));
42
+ return Buffer.from(cipherBytes).toString(outputEncoding);
50
43
  }
51
44
  async decrypt(opts) {
52
45
  const { message, secret: privKey } = opts;
53
- const { inputEncoding = { key: 'base64', message: 'base64' }, outputEncoding = 'utf-8', doThrow = true, } = opts.opts ?? {};
54
- try {
55
- const key = await crypto.subtle.importKey('pkcs8', Buffer.from(privKey, inputEncoding.key), OAEP, false, ['decrypt']);
56
- const plainBytes = await crypto.subtle.decrypt({ name: OAEP.name }, key, Buffer.from(message, inputEncoding.message));
57
- return Buffer.from(plainBytes).toString(outputEncoding);
58
- }
59
- catch (error) {
60
- if (doThrow) {
61
- throw error;
62
- }
63
- return message;
64
- }
46
+ this.assertNoRemovedOptions({ method: 'decrypt', options: opts.opts });
47
+ const { inputEncoding = { key: 'base64', message: 'base64' }, outputEncoding = 'utf-8' } = opts.opts ?? {};
48
+ const key = await crypto.subtle.importKey('pkcs8', Buffer.from(privKey, inputEncoding.key), OAEP, false, ['decrypt']);
49
+ const plainBytes = await crypto.subtle.decrypt({ name: OAEP.name }, key, Buffer.from(message, inputEncoding.message));
50
+ return Buffer.from(plainBytes).toString(outputEncoding);
65
51
  }
66
52
  }
67
53
  //# sourceMappingURL=rsa.algorithm.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"rsa.algorithm.js","sourceRoot":"","sources":["../../../../../src/modules/crypto/algorithms/rsa.algorithm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AIb;QACC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;QAC1C,MAAM,EACJ,aAAa,GAAG,EAAE,GAAG,EAAE,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,EACpD,cAAc,GAAG,OAAO,EACxB,OAAO,GAAG,IAAI,GACf,GAAG,IAAI,CAAC,IAAI,IAAI,EAAE,CAAC;QAEpB,IAAI,CAAC;YACH,MAAM,GAAG,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,SAAS,CACvC,OAAO,EACP,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,aAAa,CAAC,GAAG,CAAC,EACvC,IAAI,EACJ,KAAK,EACL,CAAC,SAAS,CAAC,CACZ,CAAC;YACF,MAAM,UAAU,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,OAAO,CAC5C,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,EACnB,GAAG,EACH,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,aAAa,CAAC,OAAO,CAAC,CAC5C,CAAC;YAEF,OAAO,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,QAAQ,CAAC,cAAc,CAAC,CAAC;QAC1D,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,OAAO,EAAE,CAAC;gBACZ,MAAM,KAAK,CAAC;YACd,CAAC;YAED,OAAO,OAAO,CAAC;QACjB,CAAC;IACH,CAAC;CACF","sourcesContent":["import { getError } from '@/modules/error';\nimport { MINIMUM_RSA_MODULUS_BITS } from '../common/constants';\nimport { BaseCryptoAlgorithm } from './base.algorithm';\n\ninterface IRSAExtraOptions {\n inputEncoding?: { key: BufferEncoding; message: BufferEncoding };\n outputEncoding?: BufferEncoding;\n doThrow?: boolean;\n}\n\n/** The algorithm name `RSA` reports as its `algorithm`. */\nexport type RSAAlgorithmType = 'rsa';\n\n/**\n * OAEP with SHA-1 for both the label hash and MGF1, and the public exponent 65537: what Node's\n * `publicEncrypt`/`privateDecrypt` and `generateKeyPairSync('rsa')` used by default, so keys and\n * ciphertext written by earlier releases still work. Do not change them: every ciphertext stored under\n * them would stop decrypting.\n */\nconst OAEP = { name: 'RSA-OAEP', hash: 'SHA-1' } as const;\nconst PUBLIC_EXPONENT = new Uint8Array([0x01, 0x00, 0x01]);\n\n/** `generateDERKeyPair`, `encrypt` and `decrypt` are async: they run over `crypto.subtle`. */\nexport class RSA extends BaseCryptoAlgorithm<\n RSAAlgorithmType,\n string,\n string,\n string,\n Promise<string>,\n Promise<string>,\n IRSAExtraOptions\n> {\n constructor(opts: { algorithm: RSAAlgorithmType }) {\n super({ scope: RSA.name, ...opts });\n }\n\n static withAlgorithm() {\n return new RSA({ algorithm: 'rsa' });\n }\n\n /**\n * Rejects a modulus below `MINIMUM_RSA_MODULUS_BITS` rather than generating it - a weak key still\n * works, signs, and verifies, so this is the only point where the size is ever checked.\n */\n async generateDERKeyPair(opts?: { modulus: number }) {\n const modulus = opts?.modulus ?? MINIMUM_RSA_MODULUS_BITS;\n\n if (modulus < MINIMUM_RSA_MODULUS_BITS) {\n throw getError({\n message: `[RSA][generateDERKeyPair] Modulus ${modulus} is below the ${MINIMUM_RSA_MODULUS_BITS}-bit minimum`,\n });\n }\n\n const keys = await crypto.subtle.generateKey(\n { ...OAEP, modulusLength: modulus, publicExponent: PUBLIC_EXPONENT },\n true,\n ['encrypt', 'decrypt'],\n );\n\n const publicKey = await crypto.subtle.exportKey('spki', keys.publicKey);\n const privateKey = await crypto.subtle.exportKey('pkcs8', keys.privateKey);\n\n return { publicKey: Buffer.from(publicKey), privateKey: Buffer.from(privateKey) };\n }\n\n async encrypt(opts: {\n message: string;\n secret: string;\n opts?: IRSAExtraOptions;\n }): Promise<string> {\n const { message, secret: pubKey } = opts;\n const {\n inputEncoding = { key: 'base64', message: 'utf-8' },\n outputEncoding = 'base64',\n doThrow = true,\n } = opts.opts ?? {};\n\n try {\n const key = await crypto.subtle.importKey(\n 'spki',\n Buffer.from(pubKey, inputEncoding.key),\n OAEP,\n false,\n ['encrypt'],\n );\n const cipherBytes = await crypto.subtle.encrypt(\n { name: OAEP.name },\n key,\n Buffer.from(message, inputEncoding.message),\n );\n\n return Buffer.from(cipherBytes).toString(outputEncoding);\n } catch (error) {\n if (doThrow) {\n throw error;\n }\n\n return message;\n }\n }\n\n async decrypt(opts: {\n message: string;\n secret: string;\n opts?: IRSAExtraOptions;\n }): Promise<string> {\n const { message, secret: privKey } = opts;\n const {\n inputEncoding = { key: 'base64', message: 'base64' },\n outputEncoding = 'utf-8',\n doThrow = true,\n } = opts.opts ?? {};\n\n try {\n const key = await crypto.subtle.importKey(\n 'pkcs8',\n Buffer.from(privKey, inputEncoding.key),\n OAEP,\n false,\n ['decrypt'],\n );\n const plainBytes = await crypto.subtle.decrypt(\n { name: OAEP.name },\n key,\n Buffer.from(message, inputEncoding.message),\n );\n\n return Buffer.from(plainBytes).toString(outputEncoding);\n } catch (error) {\n if (doThrow) {\n throw error;\n }\n\n return message;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"rsa.algorithm.js","sourceRoot":"","sources":["../../../../../src/modules/crypto/algorithms/rsa.algorithm.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,wBAAwB,EAAE,MAAM,qBAAqB,CAAC;AAC/D,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAUvD;;;;;GAKG;AACH,MAAM,IAAI,GAAG,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE,OAAO,EAAW,CAAC;AAC1D,MAAM,eAAe,GAAG,IAAI,UAAU,CAAC,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;AAE3D,8FAA8F;AAC9F,MAAM,OAAO,GAAI,SAAQ,mBAQxB;IACC,YAAY,IAAqC;QAC/C,KAAK,CAAC,EAAE,KAAK,EAAE,GAAG,CAAC,IAAI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M,CAAC,MAAM,CAAC,OAAO,CAC5C,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,EACnB,GAAG,EACH,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,aAAa,CAAC,OAAO,CAAC,CAC5C,CAAC;QAEF,OAAO,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,QAAQ,CAAC,cAAc,CAAC,CAAC;IAC1D,CAAC;CACF","sourcesContent":["import { getError } from '@/modules/error';\nimport { MINIMUM_RSA_MODULUS_BITS } from '../common/constants';\nimport { BaseCryptoAlgorithm } from './base.algorithm';\n\ninterface IRSAExtraOptions {\n inputEncoding?: { key: BufferEncoding; message: BufferEncoding };\n outputEncoding?: BufferEncoding;\n}\n\n/** The algorithm name `RSA` reports as its `algorithm`. */\nexport type RSAAlgorithmType = 'rsa';\n\n/**\n * OAEP with SHA-1 for both the label hash and MGF1, and the public exponent 65537: what Node's\n * `publicEncrypt`/`privateDecrypt` and `generateKeyPairSync('rsa')` used by default, so keys and\n * ciphertext written by earlier releases still work. Do not change them: every ciphertext stored under\n * them would stop decrypting.\n */\nconst OAEP = { name: 'RSA-OAEP', hash: 'SHA-1' } as const;\nconst PUBLIC_EXPONENT = new Uint8Array([0x01, 0x00, 0x01]);\n\n/** `generateDERKeyPair`, `encrypt` and `decrypt` are async: they run over `crypto.subtle`. */\nexport class RSA extends BaseCryptoAlgorithm<\n RSAAlgorithmType,\n string,\n string,\n string,\n Promise<string>,\n Promise<string>,\n IRSAExtraOptions\n> {\n constructor(opts: { algorithm: RSAAlgorithmType }) {\n super({ scope: RSA.name, ...opts });\n }\n\n static withAlgorithm() {\n return new RSA({ algorithm: 'rsa' });\n }\n\n /**\n * Rejects a modulus below `MINIMUM_RSA_MODULUS_BITS` rather than generating it - a weak key still\n * works, signs, and verifies, so this is the only point where the size is ever checked.\n */\n async generateDERKeyPair(opts?: { modulus: number }) {\n const modulus = opts?.modulus ?? MINIMUM_RSA_MODULUS_BITS;\n\n if (modulus < MINIMUM_RSA_MODULUS_BITS) {\n throw getError({\n message: `[RSA][generateDERKeyPair] Modulus ${modulus} is below the ${MINIMUM_RSA_MODULUS_BITS}-bit minimum`,\n });\n }\n\n const keys = await crypto.subtle.generateKey(\n { ...OAEP, modulusLength: modulus, publicExponent: PUBLIC_EXPONENT },\n true,\n ['encrypt', 'decrypt'],\n );\n\n const publicKey = await crypto.subtle.exportKey('spki', keys.publicKey);\n const privateKey = await crypto.subtle.exportKey('pkcs8', keys.privateKey);\n\n return { publicKey: Buffer.from(publicKey), privateKey: Buffer.from(privateKey) };\n }\n\n async encrypt(opts: {\n message: string;\n secret: string;\n opts?: IRSAExtraOptions;\n }): Promise<string> {\n const { message, secret: pubKey } = opts;\n this.assertNoRemovedOptions({ method: 'encrypt', options: opts.opts });\n\n const { inputEncoding = { key: 'base64', message: 'utf-8' }, outputEncoding = 'base64' } =\n opts.opts ?? {};\n\n const key = await crypto.subtle.importKey(\n 'spki',\n Buffer.from(pubKey, inputEncoding.key),\n OAEP,\n false,\n ['encrypt'],\n );\n const cipherBytes = await crypto.subtle.encrypt(\n { name: OAEP.name },\n key,\n Buffer.from(message, inputEncoding.message),\n );\n\n return Buffer.from(cipherBytes).toString(outputEncoding);\n }\n\n async decrypt(opts: {\n message: string;\n secret: string;\n opts?: IRSAExtraOptions;\n }): Promise<string> {\n const { message, secret: privKey } = opts;\n this.assertNoRemovedOptions({ method: 'decrypt', options: opts.opts });\n\n const { inputEncoding = { key: 'base64', message: 'base64' }, outputEncoding = 'utf-8' } =\n opts.opts ?? {};\n\n const key = await crypto.subtle.importKey(\n 'pkcs8',\n Buffer.from(privKey, inputEncoding.key),\n OAEP,\n false,\n ['decrypt'],\n );\n const plainBytes = await crypto.subtle.decrypt(\n { name: OAEP.name },\n key,\n Buffer.from(message, inputEncoding.message),\n );\n\n return Buffer.from(plainBytes).toString(outputEncoding);\n }\n}\n"]}
@@ -36,7 +36,8 @@ export class LogFormatUtility {
36
36
  const placeholder = placeholders[index];
37
37
  const isInspectable = typeof arg === 'object' && arg !== null;
38
38
  if (!isInspectable) {
39
- return arg;
39
+ // A string argument (`%s`, or none) is printed as written: the credentials it carries are masked first.
40
+ return typeof arg === 'string' ? RedactUtility.scrubText({ value: arg }) : arg;
40
41
  }
41
42
  // `%j` runs JSON.stringify, which answers `[Circular]` for the WHOLE argument when one cycle sits anywhere inside it - a transaction handle in the payload wipes out every other field. It also has no notion of secret keys, and no depth limit of its own. Project the value first, under the same depth cap `%s` gets.
42
43
  if (placeholder === '%j') {
@@ -1 +1 @@
1
- {"version":3,"file":"deep-splat.js","sourceRoot":"","sources":["../../../../../src/modules/logger/formatting/deep-splat.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEjD,wFAAwF;AACxF,MAAM,mBAAmB,GAAG,eAAe,CAAC;AAE5C,uQAAuQ;AACvQ,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAEhC,0KAA0K;AAC1K,MAAM,OAAO,gBAAgB;IACnB,MAAM,CAAC,YAAY;QACzB,MAAM,UAAU,GAAG,OAAO,CAAC,GAAG,CAAC,4BAA4B,CAAC;QAE5D,6IAA6I;QAC7I,IAAI,UAAU,KAAK,SAAS,IAAI,UAAU,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC;YACzD,OAAO,qBAAqB,CAAC;QAC/B,CAAC;QAED,MAAM,MAAM,GAAG,MAAM,CAAC,QAAQ,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;QAE/C,mJAAmJ;QACnJ,IAAI,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,MAAM,GAAG,CAAC,EAAE,CAAC;YACvC,OAAO,qBAAqB,CAAC;QAC/B,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;IAEO,MAAM,CAAC,mBAAmB;QA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C;gBAC9E,OAAO,aAAa,CAAC,aAAa,CAAC;oBACjC,KAAK,EAAE,GAAG;oBACV,KAAK,EAAE,CAAC,cAAc,CAAC,KAAK,IAAI,gBAAgB,CAAC,YAAY,EAAE,CAAC,GAAG,CAAC;iBACrE,CAAC,CAAC;YACL,CAAC;YAED,IAAI,WAAW,KAAK,IAAI,EAAE,CAAC;gBACzB,OAAO,GAAG,CAAC;YACb,CAAC;YAED,kOAAkO;YAClO,IAAI,GAAG,YAAY,KAAK,EAAE,CAAC;gBACzB,OAAO,KAAK,aAAa,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,GAAG,EAAE,cAAc,EAAE,CAAC,EAAE,CAAC;YACrE,CAAC;YAED,4FAA4F;YAC5F,4FAA4F;YAC5F,0DAA0D;YAC1D,OAAO,IAAI,CAAC,OAAO,CACjB,aAAa,CAAC,aAAa,CAAC;gBAC1B,KAAK,EAAE,GAAG;gBACV,KAAK,EAAE,CAAC,cAAc,CAAC,KAAK,IAAI,gBAAgB,CAAC,YAAY,EAAE,CAAC,GAAG,CAAC;aACrE,CAAC,EACF,cAAc,CACf,CAAC;QACJ,CAAC,CAAC,CAAC;QAEH,OAAO,IAAI,CAAC,iBAAiB,CAAC,cAAc,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,CAAC;IACrE,CAAC;CACF","sourcesContent":["import { RedactUtility } from '@/common/redact';\nimport util from 'node:util';\nimport { ErrorPrettier } from './error-prettier';\n\n/** The placeholders `util.format` understands. `%%` is an escape, not a placeholder. */\nconst PLACEHOLDER_PATTERN = /%[sjdifoOc%]/g;\n\n/** How deep an object is inspected before it collapses to `[Object]`: Node's default of 2 hides nested data (e.g. wrapped `cause`), 5 reaches it while staying bounded. `APP_ENV_LOGGER_INSPECT_DEPTH` overrides with a NON-NEGATIVE number - no unlimited setting. */\nconst DEFAULT_INSPECT_DEPTH = 5;\n\n/** Renders a log message and its arguments to one string, redacting secret keys and inspecting objects to a bounded depth (`APP_ENV_LOGGER_INSPECT_DEPTH`, default 5). */\nexport class LogFormatUtility {\n private static resolveDepth(): number {\n const configured = process.env.APP_ENV_LOGGER_INSPECT_DEPTH;\n\n // Not `ParseUtility.toInt()`: it answers 0 for an ABSENT value, which would silently mean \"depth 0\" - the one setting that hides everything.\n if (configured === undefined || configured.trim() === '') {\n return DEFAULT_INSPECT_DEPTH;\n }\n\n const parsed = Number.parseInt(configured, 10);\n\n // A negative or unparseable value is a misconfiguration, not a request: fall back rather than hand `util.inspect` a depth it reads as \"unlimited\".\n if (Number.isNaN(parsed) || parsed < 0) {\n return DEFAULT_INSPECT_DEPTH;\n }\n\n return parsed;\n }\n\n private static buildInspectOptions(): util.InspectOptions {\n return {\n depth: LogFormatUtility.resolveDepth(),\n maxArrayLength: null,\n maxStringLength: null,\n breakLength: Infinity,\n };\n }\n\n /** Formats like `util.format`, but `%s` inspects to configured depth instead of Node's hard-coded `depth: 0` (no inspect option overrides that), and `%j` is projected into a JSON-safe shape first. Per-placeholder only - handing `%j` the widened STRING would emit a JSON-quoted inspect dump instead of an object. */\n static formatMessage(opts: {\n message: string;\n args: Array<unknown>;\n inspectOptions?: util.InspectOptions;\n }): string {\n const { message, args, inspectOptions = LogFormatUtility.buildInspectOptions() } = opts;\n\n const placeholders = (message.match(PLACEHOLDER_PATTERN) ?? []).filter(\n (token) => token !== '%%',\n );\n\n const widened = args.map((arg, index) => {\n const placeholder = placeholders[index];\n const isInspectable = typeof arg === 'object' && arg !== null;\n\n if (!isInspectable) {\n return arg;\n }\n\n // `%j` runs JSON.stringify, which answers `[Circular]` for the WHOLE argument when one cycle sits anywhere inside it - a transaction handle in the payload wipes out every other field. It also has no notion of secret keys, and no depth limit of its own. Project the value first, under the same depth cap `%s` gets.\n if (placeholder === '%j') {\n return RedactUtility.toJsonSafe({\n value: arg,\n depth: inspectOptions.depth ?? LogFormatUtility.resolveDepth(),\n });\n }\n\n // `%o`, `%O` and arguments with NO placeholder (`util.format` appends those) are redacted but\n // left as objects, so `util.formatWithOptions` still renders them the way that placeholder\n // means. Pre-inspecting them into a string here would make `%o` print a quoted, escaped string\n // instead of an object. Only the redaction is added; the rendering is unchanged.\n //\n // Before this, `logger.info('login failed', { password })` printed the password verbatim: the\n // redactor only ever saw `%s`, while the reference docs recommend `%o` for data objects.\n //\n // Bounded like the `%s` path below, and for the same reason: an unbounded walk on a very deep\n // graph is work whose result the renderer discards, and deep enough it is a `RangeError` on a\n // call that could not throw before. `%o` renders at `depth`, so `+2` covers what is shown.\n if (placeholder === undefined || placeholder === '%o' || placeholder === '%O') {\n return RedactUtility.redactSecrets({\n value: arg,\n depth: (inspectOptions.depth ?? LogFormatUtility.resolveDepth()) + 2,\n });\n }\n\n if (placeholder !== '%s') {\n return arg;\n }\n\n // Inspecting an Error dumps every own property - a `jose` failure carries the whole JWT payload, a driver failure the whole query. Project it instead, onto its own line so it never trails off the end of the caller's sentence.\n if (arg instanceof Error) {\n return `\\n${ErrorPrettier.format({ error: arg, inspectOptions })}`;\n }\n\n // Bounded to just past what `util.inspect` will actually render. `+2`, not `+1`: at exactly\n // `depth + 1` the redactor replaces the last level with a string, and inspect then prints a\n // QUOTED `'[Object]'` instead of its own bare `[Object]`.\n return util.inspect(\n RedactUtility.redactSecrets({\n value: arg,\n depth: (inspectOptions.depth ?? LogFormatUtility.resolveDepth()) + 2,\n }),\n inspectOptions,\n );\n });\n\n return util.formatWithOptions(inspectOptions, message, ...widened);\n }\n}\n"]}
1
+ {"version":3,"file":"deep-splat.js","sourceRoot":"","sources":["../../../../../src/modules/logger/formatting/deep-splat.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEjD,wFAAwF;AACxF,MAAM,mBAAmB,GAAG,eAAe,CAAC;AAE5C,uQAAuQ;AACvQ,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAEhC,0KA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,KAAK,EAAE,GAAG;gBACV,KAAK,EAAE,CAAC,cAAc,CAAC,KAAK,IAAI,gBAAgB,CAAC,YAAY,EAAE,CAAC,GAAG,CAAC;aACrE,CAAC,EACF,cAAc,CACf,CAAC;QACJ,CAAC,CAAC,CAAC;QAEH,OAAO,IAAI,CAAC,iBAAiB,CAAC,cAAc,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,CAAC;IACrE,CAAC;CACF","sourcesContent":["import { RedactUtility } from '@/common/redact';\nimport util from 'node:util';\nimport { ErrorPrettier } from './error-prettier';\n\n/** The placeholders `util.format` understands. `%%` is an escape, not a placeholder. */\nconst PLACEHOLDER_PATTERN = /%[sjdifoOc%]/g;\n\n/** How deep an object is inspected before it collapses to `[Object]`: Node's default of 2 hides nested data (e.g. wrapped `cause`), 5 reaches it while staying bounded. `APP_ENV_LOGGER_INSPECT_DEPTH` overrides with a NON-NEGATIVE number - no unlimited setting. */\nconst DEFAULT_INSPECT_DEPTH = 5;\n\n/** Renders a log message and its arguments to one string, redacting secret keys and inspecting objects to a bounded depth (`APP_ENV_LOGGER_INSPECT_DEPTH`, default 5). */\nexport class LogFormatUtility {\n private static resolveDepth(): number {\n const configured = process.env.APP_ENV_LOGGER_INSPECT_DEPTH;\n\n // Not `ParseUtility.toInt()`: it answers 0 for an ABSENT value, which would silently mean \"depth 0\" - the one setting that hides everything.\n if (configured === undefined || configured.trim() === '') {\n return DEFAULT_INSPECT_DEPTH;\n }\n\n const parsed = Number.parseInt(configured, 10);\n\n // A negative or unparseable value is a misconfiguration, not a request: fall back rather than hand `util.inspect` a depth it reads as \"unlimited\".\n if (Number.isNaN(parsed) || parsed < 0) {\n return DEFAULT_INSPECT_DEPTH;\n }\n\n return parsed;\n }\n\n private static buildInspectOptions(): util.InspectOptions {\n return {\n depth: LogFormatUtility.resolveDepth(),\n maxArrayLength: null,\n maxStringLength: null,\n breakLength: Infinity,\n };\n }\n\n /** Formats like `util.format`, but `%s` inspects to configured depth instead of Node's hard-coded `depth: 0` (no inspect option overrides that), and `%j` is projected into a JSON-safe shape first. Per-placeholder only - handing `%j` the widened STRING would emit a JSON-quoted inspect dump instead of an object. */\n static formatMessage(opts: {\n message: string;\n args: Array<unknown>;\n inspectOptions?: util.InspectOptions;\n }): string {\n const { message, args, inspectOptions = LogFormatUtility.buildInspectOptions() } = opts;\n\n const placeholders = (message.match(PLACEHOLDER_PATTERN) ?? []).filter(\n (token) => token !== '%%',\n );\n\n const widened = args.map((arg, index) => {\n const placeholder = placeholders[index];\n const isInspectable = typeof arg === 'object' && arg !== null;\n\n if (!isInspectable) {\n // A string argument (`%s`, or none) is printed as written: the credentials it carries are masked first.\n return typeof arg === 'string' ? RedactUtility.scrubText({ value: arg }) : arg;\n }\n\n // `%j` runs JSON.stringify, which answers `[Circular]` for the WHOLE argument when one cycle sits anywhere inside it - a transaction handle in the payload wipes out every other field. It also has no notion of secret keys, and no depth limit of its own. Project the value first, under the same depth cap `%s` gets.\n if (placeholder === '%j') {\n return RedactUtility.toJsonSafe({\n value: arg,\n depth: inspectOptions.depth ?? LogFormatUtility.resolveDepth(),\n });\n }\n\n // `%o`, `%O` and arguments with NO placeholder (`util.format` appends those) are redacted but\n // left as objects, so `util.formatWithOptions` still renders them the way that placeholder\n // means. Pre-inspecting them into a string here would make `%o` print a quoted, escaped string\n // instead of an object. Only the redaction is added; the rendering is unchanged.\n //\n // Before this, `logger.info('login failed', { password })` printed the password verbatim: the\n // redactor only ever saw `%s`, while the reference docs recommend `%o` for data objects.\n //\n // Bounded like the `%s` path below, and for the same reason: an unbounded walk on a very deep\n // graph is work whose result the renderer discards, and deep enough it is a `RangeError` on a\n // call that could not throw before. `%o` renders at `depth`, so `+2` covers what is shown.\n if (placeholder === undefined || placeholder === '%o' || placeholder === '%O') {\n return RedactUtility.redactSecrets({\n value: arg,\n depth: (inspectOptions.depth ?? LogFormatUtility.resolveDepth()) + 2,\n });\n }\n\n if (placeholder !== '%s') {\n return arg;\n }\n\n // Inspecting an Error dumps every own property - a `jose` failure carries the whole JWT payload, a driver failure the whole query. Project it instead, onto its own line so it never trails off the end of the caller's sentence.\n if (arg instanceof Error) {\n return `\\n${ErrorPrettier.format({ error: arg, inspectOptions })}`;\n }\n\n // Bounded to just past what `util.inspect` will actually render. `+2`, not `+1`: at exactly\n // `depth + 1` the redactor replaces the last level with a string, and inspect then prints a\n // QUOTED `'[Object]'` instead of its own bare `[Object]`.\n return util.inspect(\n RedactUtility.redactSecrets({\n value: arg,\n depth: (inspectOptions.depth ?? LogFormatUtility.resolveDepth()) + 2,\n }),\n inspectOptions,\n );\n });\n\n return util.formatWithOptions(inspectOptions, message, ...widened);\n }\n}\n"]}
@@ -28,6 +28,13 @@ export interface IUrlSafetyPolicy {
28
28
  * @default UrlSafetyDefaults.TIMEOUT_MILLISECONDS
29
29
  */
30
30
  timeout?: IDuration;
31
+ /**
32
+ * A proxy for `UrlIngest.fetchGuarded` to send the request through, as `http://host:port`. Off by default, and the
33
+ * environment's `HTTP_PROXY` / `HTTPS_PROXY` is ignored: a proxy resolves the host name itself, so the vetted address
34
+ * the guard pins to would never be used. With this set the address check still runs, but the connection is NOT pinned:
35
+ * the proxy decides where the request goes, so only point it at a proxy you trust to refuse internal addresses.
36
+ */
37
+ proxy?: string;
31
38
  /**
32
39
  * Largest body, in bytes. The read stops and cancels the moment the body crosses it.
33
40
  * @default UrlSafetyDefaults.MAX_BYTES
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../../../src/modules/network/utilities/url-safety/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { IDuration } from '@/common/constants/duration';\n\n/**\n * What a caller will accept from an untrusted url. Every field is per call: an app that must reach\n * plain `http` says so at the call site rather than weakening a build-time constant for everyone.\n */\nexport interface IUrlSafetyPolicy {\n /**\n * The schemes a url may use.\n * @default ['https:']\n */\n allowedSchemes?: string[];\n\n /**\n * Whether a url may resolve to a private address. Turning it on in a path that takes urls from user input re-opens the\n * server-side request forgery this guard exists to close - a request can then be steered at\n * `169.254.169.254` and the cloud credentials behind it.\n * @default false\n */\n allowPrivateAddress?: boolean;\n\n /** When set, nothing outside the list passes, whatever it resolves to. */\n allowedHosts?: string[];\n\n /**\n * Redirects followed. Each hop is re-checked, so a public host cannot bounce into a private one.\n * @default 3\n */\n maxRedirects?: number;\n\n /**\n * How long a request may take. A slow host holds a worker slot for exactly this long.\n * @default UrlSafetyDefaults.TIMEOUT_MILLISECONDS\n */\n timeout?: IDuration;\n\n /**\n * Largest body, in bytes. The read stops and cancels the moment the body crosses it.\n * @default UrlSafetyDefaults.MAX_BYTES\n */\n maxBytes?: number;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../../../src/modules/network/utilities/url-safety/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { IDuration } from '@/common/constants/duration';\n\n/**\n * What a caller will accept from an untrusted url. Every field is per call: an app that must reach\n * plain `http` says so at the call site rather than weakening a build-time constant for everyone.\n */\nexport interface IUrlSafetyPolicy {\n /**\n * The schemes a url may use.\n * @default ['https:']\n */\n allowedSchemes?: string[];\n\n /**\n * Whether a url may resolve to a private address. Turning it on in a path that takes urls from user input re-opens the\n * server-side request forgery this guard exists to close - a request can then be steered at\n * `169.254.169.254` and the cloud credentials behind it.\n * @default false\n */\n allowPrivateAddress?: boolean;\n\n /** When set, nothing outside the list passes, whatever it resolves to. */\n allowedHosts?: string[];\n\n /**\n * Redirects followed. Each hop is re-checked, so a public host cannot bounce into a private one.\n * @default 3\n */\n maxRedirects?: number;\n\n /**\n * How long a request may take. A slow host holds a worker slot for exactly this long.\n * @default UrlSafetyDefaults.TIMEOUT_MILLISECONDS\n */\n timeout?: IDuration;\n\n /**\n * A proxy for `UrlIngest.fetchGuarded` to send the request through, as `http://host:port`. Off by default, and the\n * environment's `HTTP_PROXY` / `HTTPS_PROXY` is ignored: a proxy resolves the host name itself, so the vetted address\n * the guard pins to would never be used. With this set the address check still runs, but the connection is NOT pinned:\n * the proxy decides where the request goes, so only point it at a proxy you trust to refuse internal addresses.\n */\n proxy?: string;\n\n /**\n * Largest body, in bytes. The read stops and cancels the moment the body crosses it.\n * @default UrlSafetyDefaults.MAX_BYTES\n */\n maxBytes?: number;\n}\n"]}
@@ -2,12 +2,20 @@ import type { IUrlSafetyPolicy } from './common/types.js';
2
2
  /** Fetching an untrusted url without letting it reach inside the network. */
3
3
  export declare class UrlIngest {
4
4
  /**
5
- * Rejects when ANY resolved address is non-public. Checking only the first walks straight into a
6
- * host that publishes one public A record beside an internal one.
5
+ * Resolves `hostname` once and returns every address it answered, refusing the host when ANY of them is non-public.
6
+ * Checking only the first walks straight into a host that publishes one public A record beside an internal one.
7
+ * An IP literal answers itself. `allowPrivateAddress` skips the check and returns an empty list: nothing to pin to.
8
+ */
9
+ static resolvePublicAddresses(opts: {
10
+ hostname: string;
11
+ policy?: IUrlSafetyPolicy;
12
+ signal?: AbortSignal;
13
+ }): Promise<string[]>;
14
+ /**
15
+ * Rejects when ANY resolved address is non-public.
7
16
  *
8
- * A rebinding window remains: the address can change between this check and the connect. Closing
9
- * it means connecting to the resolved address and setting `Host` by hand, which no fetch API
10
- * exposes.
17
+ * A rebinding window remains when this is called on its own: the address can change between this check and a
18
+ * later connect. {@link UrlIngest.fetchGuarded} closes it by connecting to the address it vetted.
11
19
  */
12
20
  static assertPublicHost(opts: {
13
21
  hostname: string;
@@ -19,10 +27,43 @@ export declare class UrlIngest {
19
27
  policy?: IUrlSafetyPolicy;
20
28
  }): Promise<URL>;
21
29
  private static readTimeoutMilliseconds;
30
+ /** Settles with `work`, or rejects with the signal's reason when the deadline passes first: a slow resolver must not outlive it. */
31
+ private static withDeadline;
32
+ /** Request headers that name the body; they go when a redirect turns the request into a GET. */
33
+ private static readonly BODY_HEADERS;
34
+ /**
35
+ * The only caller headers a cross-origin redirect keeps. Every other one is dropped: a tenant's webhook secret
36
+ * (`x-api-key`, a signature) must not follow a redirect to a host that tenant did not name.
37
+ */
38
+ private static readonly CROSS_ORIGIN_HEADERS;
39
+ /** The statuses that name a new location; a 304 or a 300 is an answer, not a redirect. */
40
+ private static readonly REDIRECT_STATUSES;
41
+ /** Connect-phase errors: nothing was sent, so trying the next vetted address cannot deliver a request twice. */
42
+ private static readonly CONNECT_ERROR_CODES;
43
+ private static onlyHeaders;
44
+ private static withoutHeaders;
45
+ /**
46
+ * One request to `target`. With `addresses` it connects to those vetted addresses and nowhere else, in order, and
47
+ * moves to the next one only when the connection itself fails: the url's host is set as the `Host` header, and for
48
+ * https as the TLS server name, so the certificate is still checked against the name the caller asked for.
49
+ */
50
+ private static send;
22
51
  /**
23
- * A GET that an untrusted url cannot steer inside the network. Redirects are followed by hand so
24
- * every hop is re-checked - `redirect: 'follow'` would land on an internal host with no second
25
- * look.
52
+ * A request that an untrusted url cannot steer inside the network. GET by default; `method`, `headers` and `body`
53
+ * (text or bytes, so a redirect can replay it) make it a signed webhook dispatch.
54
+ *
55
+ * The host is resolved ONCE per hop, every answer is checked, and the request connects to those addresses and to no
56
+ * other, so a DNS answer that changes after the check (DNS rebinding) is never looked up again. The `Host` header and,
57
+ * for https, the TLS server name stay the url's own, so the certificate is verified for that name. A `Host` in
58
+ * `headers` is ignored. The environment's `HTTP_PROXY` / `HTTPS_PROXY` is ignored on a pinned
59
+ * connection, because a proxy would resolve the name itself and undo the pin. `policy.proxy` sends the request through a
60
+ * proxy on purpose; that connection is not pinned (see `IUrlSafetyPolicy.proxy`). `allowPrivateAddress` turns the guard,
61
+ * and so the pin, off.
62
+ *
63
+ * Redirects are followed by hand so every hop is re-checked and re-pinned - `redirect: 'follow'` would land on an
64
+ * internal host with no second look. 301, 302 (for a POST) and 303 turn the request into a GET without a body. A 307 or
65
+ * 308 repeats the request; with a body it is refused when it leaves the origin, so a signed payload is never replayed to
66
+ * a host a redirect chose. When a hop changes origin every caller header is dropped except `accept`, `accept-language` and `user-agent`.
26
67
  *
27
68
  * The body is returned unread: the caller decides whether to stream it onward or cap it with
28
69
  * {@link UrlIngest.readCappedBody}. Nothing is buffered here.
@@ -30,7 +71,9 @@ export declare class UrlIngest {
30
71
  static fetchGuarded(opts: {
31
72
  url: string;
32
73
  policy?: IUrlSafetyPolicy;
74
+ method?: string;
33
75
  headers?: Record<string, string>;
76
+ body?: string | Uint8Array;
34
77
  }): Promise<Response>;
35
78
  /**
36
79
  * Enforces `maxBytes` on a stream nothing reads into this process - the shape a caller wants when