@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
@@ -22,6 +22,11 @@ export declare class RedactUtility {
22
22
  depth?: number;
23
23
  force?: boolean;
24
24
  }): unknown;
25
+ /** Masks the credentials a plain string carries (a url's password, a bearer token, credential query parameters). For a log line's string argument; objects go through {@link RedactUtility.redactSecrets}. `force: true` scrubs even when `APP_ENV_LOGGER_DO_REDACT=false`. */
26
+ static scrubText(opts: {
27
+ value: string;
28
+ force?: boolean;
29
+ }): string;
25
30
  /** Projects a value into something `JSON.stringify` can render: it answers `[Circular]` for the WHOLE payload when one cycle sits anywhere inside it, so cycles must be broken per-branch first. `depth` bounds the walk the way `util.inspect` does - a log argument may hold a live connector or request context, whose graph is effectively unbounded. The projection itself is unconditional: `APP_ENV_LOGGER_DO_REDACT=false` turns off the key masking, never the structural pass. `force: true` keeps the key masking on whatever the switch says; the projection stays lossy, as in {@link RedactUtility.redactSecrets}. */
26
31
  static toJsonSafe(opts: {
27
32
  value: unknown;
@@ -2,7 +2,7 @@
2
2
  const SECRET_KEY_PATTERN = new RegExp([
3
3
  // Options-object spellings (camelCase / snake_case).
4
4
  '^(pass|password|passphrase|secret|token|apiKey|api_key|accessKey|access_key',
5
- '|secretKey|secret_key|privateKey|private_key|key|cert|ca|pfx|credentials',
5
+ '|secretKey|secret_key|privateKey|private_key|key|cert|ca|pfx|credential|credentials',
6
6
  '|authorization|auth|jwtSecret|applicationSecret|connectionString)$',
7
7
  // Vault wire spellings (snake_case): node-vault's AppRole login/response bodies carry these exact keys, and none are matched by the anchored options list above.
8
8
  '|^(client_token|secret_id|role_id)$',
@@ -12,14 +12,50 @@ const SECRET_KEY_PATTERN = new RegExp([
12
12
  '|_secret$|[a-z0-9]secret$',
13
13
  // Connection descriptors: `connectionString` was anchored above but its snake_case twin was not, and `dsn` is the third common spelling for the same thing.
14
14
  '|^(connection_string|dsn|database_url|databaseUrl)$',
15
+ // Any `*_credential` / `*Credential` key, singular or plural - `dbCredential`, `api_credentials`. The bare words are anchored above; this catches the prefixed forms, the way the `*Secret` rule does.
16
+ '|_credentials?$|[a-z0-9]credentials?$',
15
17
  // Any `*_password` / `*Password` key - `dbPassword`, `admin_password`. The bare word is anchored above; this catches the prefixed forms.
16
18
  '|_password$|[a-z0-9]password$',
17
19
  // HTTP HEADER spellings: header names are kebab-case and often `x-`-prefixed, none of which the camelCase list above matches; `vault` is included so `X-Vault-Token` (node-vault's auth header) is caught.
18
20
  '|^(x-)?(api|auth|access|secret|session|csrf|xsrf|vault)-(key|token|secret|id)$',
19
21
  '|^(cookie|set-cookie|proxy-authorization|www-authenticate)$',
22
+ // Named secrets that no suffix rule reaches. An explicit list, never a blanket `*Key` or `code`: those would mask
23
+ // `primaryKey`, `cacheKey` and every status `code`. Cloud and signing keys, session and one-time values, signatures,
24
+ // card and national-id numbers, and the kebab spellings of tokens and secrets (the suffix rules above need a letter or
25
+ // an underscore before the word).
26
+ '|^(secret_?access_?key|aws_?secret_?access_?key|signing_?key|encryption_?key|master_?key|hmac_?key|account_?key|storage_?key|license_?key|reset_?key|reset_?code|verification_?code|authorization_?code|auth_?code)$',
27
+ '|^(jwt|session_?id|sid|signature|sig|passwd|pwd|passcode|pass_phrase|secret_?answer|otp|totp|cvv|cvc|card_?number|ssn|national_?id)$',
28
+ '|^(redis_?url|mongo_?uri|mongo_?url|webhook_?url|private_?key_?pem|password_?hash|mfa_?code|otp_?code|x_?api_?key)$',
29
+ '|^(api_?keys|refresh_?tokens|access_?tokens|secrets|tokens)$',
30
+ '|^(x-amz-signature|x-amz-security-token|x-amz-credential)$',
31
+ '|^(id|refresh|access|bearer|auth|api|session|csrf|xsrf)-token$',
32
+ '|^(client|api|app|webhook)-secret$|^(private|signing|secret|api|access|encryption)-key$',
20
33
  ].join(''), 'i');
21
34
  /** The placeholder that replaces a secret value in redacted output. */
22
35
  export const REDACTED = '[REDACTED]';
36
+ /**
37
+ * `://user:password@host`: the password of a url's userinfo, wherever the url sits inside a string. Anchored on `://`
38
+ * (not on the scheme, whose letters a pattern would rescan from every start) and every run is bounded, so the cost is
39
+ * linear in the string. The password runs to the LAST `@` before a space or slash, so one that holds an `@` is whole.
40
+ */
41
+ const URL_USERINFO_PATTERN = /(:\/\/[^\s/:@]{0,256}):[^\s/]{1,256}@/g;
42
+ /** `://token@host`: a userinfo with no password is the credential itself (`https://<token>@github.com`). */
43
+ const URL_USER_ONLY_PATTERN = /:\/\/[^\s/:@]{1,256}@/g;
44
+ /** `Bearer abc...` and `Basic abc...` credentials, as an `Authorization` header or a message quotes them. */
45
+ const AUTH_SCHEME_PATTERN = /\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi;
46
+ /** A credential-like `name=value` after a query, fragment, list or space: `?access_token=...`, `#id_token=...`, `, password=...`. */
47
+ const QUERY_CREDENTIAL_PATTERN = /([?&;,#\s])(access_token|refresh_token|id_token|token|api_key|apikey|x-api-key|key|auth|password|passwd|pwd|secret|client_secret|signature|sig|x-amz-signature|x-amz-security-token|jwt|session_id|sessionid|code)=([^&\s#,)]*)/gi;
48
+ /** A string with the credentials it carries masked: a connection url's password, a bearer token, a credential query parameter. */
49
+ const scrubString = (value) => {
50
+ if (!value.includes('@') && !value.includes('=') && !/bearer|basic/i.test(value)) {
51
+ return value;
52
+ }
53
+ return value
54
+ .replace(URL_USERINFO_PATTERN, `$1:${'[REDACTED]'}@`)
55
+ .replace(URL_USER_ONLY_PATTERN, `://${'[REDACTED]'}@`)
56
+ .replace(AUTH_SCHEME_PATTERN, `$1 ${'[REDACTED]'}`)
57
+ .replace(QUERY_CREDENTIAL_PATTERN, `$1$2=${'[REDACTED]'}`);
58
+ };
23
59
  /** Kill-switch for local debugging: only the literal `false` disables redaction (fail-closed); read per call so it can be flipped at runtime. Never disable in production. `force` is the caller opting out of the switch: it always masks. */
24
60
  const isRedactionEnabled = (force) => force === true || globalThis.process?.env?.APP_ENV_LOGGER_DO_REDACT !== 'false';
25
61
  /** Longest string a log line carries whole. `APP_ENV_LOGGER_MAX_STRING_LENGTH=0` turns capping off. */
@@ -50,7 +86,13 @@ const capString = (opts) => {
50
86
  const deepSanitize = (value, context) => {
51
87
  const { seen, doRedact, depth } = context;
52
88
  if (typeof value === 'string') {
53
- return capString({ value, key: context.key, limit: context.maxStringLength });
89
+ const text = doRedact ? scrubString(value) : value;
90
+ return capString({ value: text, key: context.key, limit: context.maxStringLength });
91
+ }
92
+ // A function is not data, and an own `toJSON` on an object would run after this walk, inside `JSON.stringify`, and
93
+ // hand back keys the walk never saw. Naming it keeps the redacted copy free of code.
94
+ if (typeof value === 'function') {
95
+ return '[Function]';
54
96
  }
55
97
  if (value === null || typeof value !== 'object') {
56
98
  return value;
@@ -80,8 +122,8 @@ const deepSanitize = (value, context) => {
80
122
  const source = value;
81
123
  const result = {
82
124
  name: value.name,
83
- message: value.message,
84
- stack: value.stack,
125
+ message: doRedact ? scrubString(value.message) : value.message,
126
+ stack: doRedact && value.stack ? scrubString(value.stack) : value.stack,
85
127
  };
86
128
  for (const [key, entry] of Object.entries(source)) {
87
129
  result[key] =
@@ -133,6 +175,10 @@ export class RedactUtility {
133
175
  maxStringLength: resolveMaxStringLength(),
134
176
  });
135
177
  }
178
+ /** Masks the credentials a plain string carries (a url's password, a bearer token, credential query parameters). For a log line's string argument; objects go through {@link RedactUtility.redactSecrets}. `force: true` scrubs even when `APP_ENV_LOGGER_DO_REDACT=false`. */
179
+ static scrubText(opts) {
180
+ return isRedactionEnabled(opts.force) ? scrubString(opts.value) : opts.value;
181
+ }
136
182
  /** Projects a value into something `JSON.stringify` can render: it answers `[Circular]` for the WHOLE payload when one cycle sits anywhere inside it, so cycles must be broken per-branch first. `depth` bounds the walk the way `util.inspect` does - a log argument may hold a live connector or request context, whose graph is effectively unbounded. The projection itself is unconditional: `APP_ENV_LOGGER_DO_REDACT=false` turns off the key masking, never the structural pass. `force: true` keeps the key masking on whatever the switch says; the projection stays lossy, as in {@link RedactUtility.redactSecrets}. */
137
183
  static toJsonSafe(opts) {
138
184
  return deepSanitize(opts.value, {
@@ -1 +1 @@
1
- {"version":3,"file":"redact.js","sourceRoot":"","sources":["../../../src/common/redact.ts"],"names":[],"mappings":"AAEA,gHAAgH;AAChH,MAAM,kBAAkB,GAAG,IAAI,MAAM,CACnC;IACE,qDAAqD;IACrD,6EAA6E;IAC7E,0EAA0E;IAC1E,oEAAoE;IAEpE,iKAAiK;IACjK,qCAAqC;IAErC,8MAA8M;IAC9M,yBAAyB;IAEzB,8RAA8R;IAC9R,2BAA2B;IAE3B,4JAA4J;IAC5J,qDAAqD;IAErD,yIAAyI;IACzI,+BAA+B;IAE/B,2MAA2M;IAC3M,gFAAgF;IAChF,6DAA6D;CAC9D,CAAC,IAAI,CAAC,EAAE,CAAC,EACV,GAAG,CACJ,CAAC;AAEF,uEAAuE;AACvE,MAAM,CAAC,MAAM,QAAQ,GAAG,YAAY,CAAC;AAErC,+OAA+O;AAC/O,MAAM,kBAAkB,GAAG,CAAC,KAAe,EAAW,EAAE,CACtD,KAAK,KAAK,IAAI,IAAI,UAAU,CAAC,OAAO,EAAE,GAAG,EAAE,wBAAwB,KAAK,OAAO,CAAC;AAElF,uGAAuG;AACvG,MAAM,yBAAyB,GAAG,IAAI,CAAC;AAEvC,MAAM,sBAAsB,GAAG,GAAW,EAAE;IAC1C,MAAM,UAAU,GAAG,MAAM,CAAC,UAAU,CAAC,OAAO,EAAE,GAAG,EAAE,gCAAgC,CAAC,CAAC;IAErF,OAAO,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAC,IAAI,UAAU,IAAI,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,yBAAyB,CAAC;AACjG,CAAC,CAAC;AAEF;;;GAGG;AACH,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC,CAAC,OAAO,EAAE,YAAY,EAAE,aAAa,CAAC,CAAC,CAAC;AAEtE;;;;;;GAMG;AACH,MAAM,SAAS,GAAG,CAAC,IAAoD,EAAU,EAAE;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B,IAAI,CAAC,kBAAkB,CAAC,KAAK,CAAC,EAAE,CAAC;YAC/B,OAAO,GAAG,CAAC;QACb,CAAC;QAED,IAAI,MAAW,CAAC;QAEhB,IAAI,CAAC;YACH,MAAM,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;QACxB,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,GAAG,CAAC;QACb,CAAC;QAED,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;YACrB,OAAO,GAAG,CAAC;QACb,CAAC;QAED,MAAM,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAE3B,OAAO,kBAAkB,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC,CAAC;IAC/C,CAAC;CACF","sourcesContent":["import { type AnyObject } from './types';\n\n/** Keys whose VALUES must never reach a log line - matched case-insensitively on the key name, at any depth. */\nconst SECRET_KEY_PATTERN = new RegExp(\n [\n // Options-object spellings (camelCase / snake_case).\n '^(pass|password|passphrase|secret|token|apiKey|api_key|accessKey|access_key',\n '|secretKey|secret_key|privateKey|private_key|key|cert|ca|pfx|credentials',\n '|authorization|auth|jwtSecret|applicationSecret|connectionString)$',\n\n // Vault wire spellings (snake_case): node-vault's AppRole login/response bodies carry these exact keys, and none are matched by the anchored options list above.\n '|^(client_token|secret_id|role_id)$',\n\n // Any `*_token` (snake_case) or `*Token` (camelCase) key; a preceding character is required so the bare word `token` (already covered above) is not the whole match, and so ordinary words are not swallowed.\n '|_token$|[a-z0-9]token$',\n\n // The `*Secret` counterpart the `*Token` rule always lacked. `clientSecret` / `client_secret` is the RFC 6749 parameter name and a live field on the search connector's model options, and `webhookSecret` is the standard spelling everywhere; none of them matched the anchored list above.\n '|_secret$|[a-z0-9]secret$',\n\n // Connection descriptors: `connectionString` was anchored above but its snake_case twin was not, and `dsn` is the third common spelling for the same thing.\n '|^(connection_string|dsn|database_url|databaseUrl)$',\n\n // Any `*_password` / `*Password` key - `dbPassword`, `admin_password`. The bare word is anchored above; this catches the prefixed forms.\n '|_password$|[a-z0-9]password$',\n\n // HTTP HEADER spellings: header names are kebab-case and often `x-`-prefixed, none of which the camelCase list above matches; `vault` is included so `X-Vault-Token` (node-vault's auth header) is caught.\n '|^(x-)?(api|auth|access|secret|session|csrf|xsrf|vault)-(key|token|secret|id)$',\n '|^(cookie|set-cookie|proxy-authorization|www-authenticate)$',\n ].join(''),\n 'i',\n);\n\n/** The placeholder that replaces a secret value in redacted output. */\nexport const REDACTED = '[REDACTED]';\n\n/** Kill-switch for local debugging: only the literal `false` disables redaction (fail-closed); read per call so it can be flipped at runtime. Never disable in production. `force` is the caller opting out of the switch: it always masks. */\nconst isRedactionEnabled = (force?: boolean): boolean =>\n force === true || globalThis.process?.env?.APP_ENV_LOGGER_DO_REDACT !== 'false';\n\n/** Longest string a log line carries whole. `APP_ENV_LOGGER_MAX_STRING_LENGTH=0` turns capping off. */\nconst DEFAULT_MAX_STRING_LENGTH = 2048;\n\nconst resolveMaxStringLength = (): number => {\n const configured = Number(globalThis.process?.env?.APP_ENV_LOGGER_MAX_STRING_LENGTH);\n\n return Number.isFinite(configured) && configured >= 0 ? configured : DEFAULT_MAX_STRING_LENGTH;\n};\n\n/**\n * Keys whose value is long BY NATURE and useless truncated. A stack trace is the whole reason you\n * are reading the line.\n */\nconst UNCAPPED_KEYS = new Set(['stack', 'stacktrace', 'stack_trace']);\n\n/**\n * Caps a long string, keeping the ORIGINAL LENGTH in the marker - that number is what tells you the\n * payload was a 300 KB image rather than a truncated sentence.\n *\n * A base64 body is the case this exists for: one `data:image/png;base64,...` field turns a request\n * log into hundreds of kilobytes, and nothing about it is readable.\n */\nconst capString = (opts: { value: string; key?: string; limit: number }): string => {\n const { value, key, limit } = opts;\n\n if (limit === 0 || value.length <= limit || (key && UNCAPPED_KEYS.has(key.toLowerCase()))) {\n return value;\n }\n\n return `${value.slice(0, limit)}... [truncated, ${value.length} chars total]`;\n};\n\ntype TSanitizeContext = {\n seen: WeakSet<object>;\n doRedact: boolean;\n /** Levels still allowed BELOW the current one; `Infinity` walks the whole graph. */\n depth: number;\n /** Longest string kept whole; 0 keeps every string. */\n maxStringLength: number;\n /** The key this value was found under, so a stack trace can be exempted from capping. */\n key?: string;\n};\n\nconst deepSanitize = (value: unknown, context: TSanitizeContext): unknown => {\n const { seen, doRedact, depth } = context;\n\n if (typeof value === 'string') {\n return capString({ value, key: context.key, limit: context.maxStringLength });\n }\n\n if (value === null || typeof value !== 'object') {\n return value;\n }\n\n // A Date holds its value in an internal slot, so the generic branch below - which reads Object.keys() - would flatten it to `{}`. Checked BEFORE `seen`: a Date cannot carry a cycle, and entering the set would make a second reference to the same instance read as `[Circular]`.\n if (value instanceof Date) {\n return value;\n }\n\n if (seen.has(value)) {\n return '[Circular]';\n }\n\n if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {\n return `[Binary ${(value as ArrayBufferView).byteLength ?? 0} bytes]`;\n }\n\n if (depth <= 0) {\n return Array.isArray(value) ? '[Array]' : '[Object]';\n }\n\n seen.add(value);\n const nested: TSanitizeContext = {\n seen,\n doRedact,\n depth: depth - 1,\n maxStringLength: context.maxStringLength,\n };\n\n // Error keeps name/message/stack NON-enumerable, so Object.keys() skips them and naive redaction would drop the message - reproject into a plain object carrying those fields plus its redacted enumerable own-props.\n if (value instanceof Error) {\n const source = value;\n const result: AnyObject = {\n name: value.name,\n message: value.message,\n stack: value.stack,\n };\n\n for (const [key, entry] of Object.entries(source)) {\n result[key] =\n doRedact && SECRET_KEY_PATTERN.test(key)\n ? REDACTED\n : deepSanitize(entry, { ...nested, key });\n }\n\n return result;\n }\n\n if (Array.isArray(value)) {\n return value.map((entry) => deepSanitize(entry, nested));\n }\n\n const source = value;\n const result: AnyObject = {};\n\n for (const [key, entry] of Object.entries(source)) {\n if (doRedact && SECRET_KEY_PATTERN.test(key)) {\n result[key] = REDACTED;\n continue;\n }\n\n result[key] = deepSanitize(entry, { ...nested, key });\n }\n\n return result;\n};\n\n/** Makes a log argument safe to print: masks secret-looking keys, breaks cycles, caps long strings and strips URL credentials. `APP_ENV_LOGGER_DO_REDACT=false` turns off the key masking only. */\nexport class RedactUtility {\n /**\n * Redacts every secret-looking KEY (not value shape - buffers/typed arrays are summarized, not\n * serialized). `APP_ENV_LOGGER_DO_REDACT=false` makes this the identity function.\n *\n * `depth` bounds the walk, exactly as {@link RedactUtility.toJsonSafe} already does. It defaults to\n * `Infinity` for callers that really do want the whole graph, but the logger passes its own bound:\n * rendering only inspects a handful of levels, so walking to `Infinity` did work whose result was\n * thrown away - 12x on a deep graph, and a `RangeError` on a very deep chain.\n *\n * `force: true` masks secret-looking KEYS even when `APP_ENV_LOGGER_DO_REDACT=false`. The result is still the\n * log-shaped copy: long strings are capped, a second reference to one object reads `[Circular]`, binary is\n * summarized, and a key is masked by name only (a card number under `number` is not). It is not a faithful\n * redacted document. The logger never sets it.\n */\n static redactSecrets(opts: {\n value: unknown;\n seen?: WeakSet<object>;\n depth?: number;\n force?: boolean;\n }): unknown {\n const { value, seen, depth = Infinity, force } = opts;\n\n if (!isRedactionEnabled(force)) {\n return value;\n }\n\n return deepSanitize(value, {\n seen: seen ?? new WeakSet<object>(),\n doRedact: true,\n depth,\n maxStringLength: resolveMaxStringLength(),\n });\n }\n\n /** Projects a value into something `JSON.stringify` can render: it answers `[Circular]` for the WHOLE payload when one cycle sits anywhere inside it, so cycles must be broken per-branch first. `depth` bounds the walk the way `util.inspect` does - a log argument may hold a live connector or request context, whose graph is effectively unbounded. The projection itself is unconditional: `APP_ENV_LOGGER_DO_REDACT=false` turns off the key masking, never the structural pass. `force: true` keeps the key masking on whatever the switch says; the projection stays lossy, as in {@link RedactUtility.redactSecrets}. */\n static toJsonSafe(opts: { value: unknown; depth?: number; force?: boolean }): unknown {\n return deepSanitize(opts.value, {\n seen: new WeakSet<object>(),\n doRedact: isRedactionEnabled(opts.force),\n depth: opts.depth ?? Infinity,\n // Capping is STRUCTURAL, like the projection itself: turning redaction off is about key masking,\n // never about letting a 300 KB base64 field through.\n maxStringLength: resolveMaxStringLength(),\n });\n }\n\n /** Strips credentials from a connection URL's authority section (`user:hunter2@host` -> `user:[REDACTED]@host`) - {@link RedactUtility.redactSecrets} matches on KEY names and can't see them there. A value that fails to parse as a URL is returned unchanged. `force: true` strips even when `APP_ENV_LOGGER_DO_REDACT=false`. */\n static redactUrlCredentials(opts: { url: string; force?: boolean }): string {\n const { url, force } = opts;\n\n if (!isRedactionEnabled(force)) {\n return url;\n }\n\n let parsed: URL;\n\n try {\n parsed = new URL(url);\n } catch {\n return url;\n }\n\n if (!parsed.password) {\n return url;\n }\n\n parsed.password = REDACTED;\n\n return decodeURIComponent(parsed.toString());\n }\n}\n"]}
1
+ {"version":3,"file":"redact.js","sourceRoot":"","sources":["../../../src/common/redact.ts"],"names":[],"mappings":"AAEA,gHAAgH;AAChH,MAAM,kBAAkB,GAAG,IAAI,MAAM,CACnC;IACE,qDAAqD;IACrD,6EAA6E;IAC7E,qFAAqF;IACrF,oEAAoE;IAEpE,iKAAiK;IACjK,qCAAqC;IAErC,8MAA8M;IAC9M,yBAAyB;IAEzB,8RAA8R;IAC9R,2BAA2B;IAE3B,4JAA4J;IAC5J,qDAAqD;IAErD,uMAAuM;IACvM,uCAAuC;IAEvC,yIAAyI;IACzI,+BAA+B;IAE/B,2MAA2M;IAC3M,gFAAgF;IAChF,6DAA6D;IAE7D,kHAAkH;IAClH,qHAAqH;IACrH,uHAAuH;IACvH,kCAAkC;IAClC,sNAAsN;IACtN,sIAAsI;IACtI,qHAAqH;IACrH,8DAA8D;IAC9D,4DAA4D;IAC5D,gEAAgE;IAChE,yFAAyF;CAC1F,CAAC,IAAI,CAAC,EAAE,CAAC,EACV,GAAG,CACJ,CAAC;AAEF,uEAAuE;AACvE,MAAM,CAAC,MAAM,QAAQ,GAAG,YAAY,CAAC;AAErC;;;;GAIG;AACH,MAAM,oBAAoB,GAAG,wCAAwC,CAAC;AAEtE,4GAA4G;AAC5G,MAAM,qBAAqB,GAAG,wBAAwB,CAAC;AAE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sB,EAAE;SAC1C,CAAC,CAAC;IACL,CAAC;IAED,+QAA+Q;IAC/Q,MAAM,CAAC,SAAS,CAAC,IAAwC;QACvD,OAAO,kBAAkB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC;IAC/E,CAAC;IAED,omBAAomB;IACpmB,MAAM,CAAC,UAAU,CAAC,IAAyD;QACzE,OAAO,YAAY,CAAC,IAAI,CAAC,KAAK,EAAE;YAC9B,IAAI,EAAE,IAAI,OAAO,EAAU;YAC3B,QAAQ,EAAE,kBAAkB,CAAC,IAAI,CAAC,KAAK,CAAC;YACxC,KAAK,EAAE,IAAI,CAAC,KAAK,IAAI,QAAQ;YAC7B,iGAAiG;YACjG,qDAAqD;YACrD,eAAe,EAAE,sBAAsB,EAAE;SAC1C,CAAC,CAAC;IACL,CAAC;IAED,qUAAqU;IACrU,MAAM,CAAC,oBAAoB,CAAC,IAAsC;QAChE,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC;QAE5B,IAAI,CAAC,kBAAkB,CAAC,KAAK,CAAC,EAAE,CAAC;YAC/B,OAAO,GAAG,CAAC;QACb,CAAC;QAED,IAAI,MAAW,CAAC;QAEhB,IAAI,CAAC;YACH,MAAM,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;QACxB,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,GAAG,CAAC;QACb,CAAC;QAED,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;YACrB,OAAO,GAAG,CAAC;QACb,CAAC;QAED,MAAM,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAE3B,OAAO,kBAAkB,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC,CAAC;IAC/C,CAAC;CACF","sourcesContent":["import { type AnyObject } from './types';\n\n/** Keys whose VALUES must never reach a log line - matched case-insensitively on the key name, at any depth. */\nconst SECRET_KEY_PATTERN = new RegExp(\n [\n // Options-object spellings (camelCase / snake_case).\n '^(pass|password|passphrase|secret|token|apiKey|api_key|accessKey|access_key',\n '|secretKey|secret_key|privateKey|private_key|key|cert|ca|pfx|credential|credentials',\n '|authorization|auth|jwtSecret|applicationSecret|connectionString)$',\n\n // Vault wire spellings (snake_case): node-vault's AppRole login/response bodies carry these exact keys, and none are matched by the anchored options list above.\n '|^(client_token|secret_id|role_id)$',\n\n // Any `*_token` (snake_case) or `*Token` (camelCase) key; a preceding character is required so the bare word `token` (already covered above) is not the whole match, and so ordinary words are not swallowed.\n '|_token$|[a-z0-9]token$',\n\n // The `*Secret` counterpart the `*Token` rule always lacked. `clientSecret` / `client_secret` is the RFC 6749 parameter name and a live field on the search connector's model options, and `webhookSecret` is the standard spelling everywhere; none of them matched the anchored list above.\n '|_secret$|[a-z0-9]secret$',\n\n // Connection descriptors: `connectionString` was anchored above but its snake_case twin was not, and `dsn` is the third common spelling for the same thing.\n '|^(connection_string|dsn|database_url|databaseUrl)$',\n\n // Any `*_credential` / `*Credential` key, singular or plural - `dbCredential`, `api_credentials`. The bare words are anchored above; this catches the prefixed forms, the way the `*Secret` rule does.\n '|_credentials?$|[a-z0-9]credentials?$',\n\n // Any `*_password` / `*Password` key - `dbPassword`, `admin_password`. The bare word is anchored above; this catches the prefixed forms.\n '|_password$|[a-z0-9]password$',\n\n // HTTP HEADER spellings: header names are kebab-case and often `x-`-prefixed, none of which the camelCase list above matches; `vault` is included so `X-Vault-Token` (node-vault's auth header) is caught.\n '|^(x-)?(api|auth|access|secret|session|csrf|xsrf|vault)-(key|token|secret|id)$',\n '|^(cookie|set-cookie|proxy-authorization|www-authenticate)$',\n\n // Named secrets that no suffix rule reaches. An explicit list, never a blanket `*Key` or `code`: those would mask\n // `primaryKey`, `cacheKey` and every status `code`. Cloud and signing keys, session and one-time values, signatures,\n // card and national-id numbers, and the kebab spellings of tokens and secrets (the suffix rules above need a letter or\n // an underscore before the word).\n '|^(secret_?access_?key|aws_?secret_?access_?key|signing_?key|encryption_?key|master_?key|hmac_?key|account_?key|storage_?key|license_?key|reset_?key|reset_?code|verification_?code|authorization_?code|auth_?code)$',\n '|^(jwt|session_?id|sid|signature|sig|passwd|pwd|passcode|pass_phrase|secret_?answer|otp|totp|cvv|cvc|card_?number|ssn|national_?id)$',\n '|^(redis_?url|mongo_?uri|mongo_?url|webhook_?url|private_?key_?pem|password_?hash|mfa_?code|otp_?code|x_?api_?key)$',\n '|^(api_?keys|refresh_?tokens|access_?tokens|secrets|tokens)$',\n '|^(x-amz-signature|x-amz-security-token|x-amz-credential)$',\n '|^(id|refresh|access|bearer|auth|api|session|csrf|xsrf)-token$',\n '|^(client|api|app|webhook)-secret$|^(private|signing|secret|api|access|encryption)-key$',\n ].join(''),\n 'i',\n);\n\n/** The placeholder that replaces a secret value in redacted output. */\nexport const REDACTED = '[REDACTED]';\n\n/**\n * `://user:password@host`: the password of a url's userinfo, wherever the url sits inside a string. Anchored on `://`\n * (not on the scheme, whose letters a pattern would rescan from every start) and every run is bounded, so the cost is\n * linear in the string. The password runs to the LAST `@` before a space or slash, so one that holds an `@` is whole.\n */\nconst URL_USERINFO_PATTERN = /(:\\/\\/[^\\s/:@]{0,256}):[^\\s/]{1,256}@/g;\n\n/** `://token@host`: a userinfo with no password is the credential itself (`https://<token>@github.com`). */\nconst URL_USER_ONLY_PATTERN = /:\\/\\/[^\\s/:@]{1,256}@/g;\n\n/** `Bearer abc...` and `Basic abc...` credentials, as an `Authorization` header or a message quotes them. */\nconst AUTH_SCHEME_PATTERN = /\\b(Bearer|Basic)\\s+[A-Za-z0-9._~+/=-]{8,}/gi;\n\n/** A credential-like `name=value` after a query, fragment, list or space: `?access_token=...`, `#id_token=...`, `, password=...`. */\nconst QUERY_CREDENTIAL_PATTERN =\n /([?&;,#\\s])(access_token|refresh_token|id_token|token|api_key|apikey|x-api-key|key|auth|password|passwd|pwd|secret|client_secret|signature|sig|x-amz-signature|x-amz-security-token|jwt|session_id|sessionid|code)=([^&\\s#,)]*)/gi;\n\n/** A string with the credentials it carries masked: a connection url's password, a bearer token, a credential query parameter. */\nconst scrubString = (value: string): string => {\n if (!value.includes('@') && !value.includes('=') && !/bearer|basic/i.test(value)) {\n return value;\n }\n\n return value\n .replace(URL_USERINFO_PATTERN, `$1:${'[REDACTED]'}@`)\n .replace(URL_USER_ONLY_PATTERN, `://${'[REDACTED]'}@`)\n .replace(AUTH_SCHEME_PATTERN, `$1 ${'[REDACTED]'}`)\n .replace(QUERY_CREDENTIAL_PATTERN, `$1$2=${'[REDACTED]'}`);\n};\n\n/** Kill-switch for local debugging: only the literal `false` disables redaction (fail-closed); read per call so it can be flipped at runtime. Never disable in production. `force` is the caller opting out of the switch: it always masks. */\nconst isRedactionEnabled = (force?: boolean): boolean =>\n force === true || globalThis.process?.env?.APP_ENV_LOGGER_DO_REDACT !== 'false';\n\n/** Longest string a log line carries whole. `APP_ENV_LOGGER_MAX_STRING_LENGTH=0` turns capping off. */\nconst DEFAULT_MAX_STRING_LENGTH = 2048;\n\nconst resolveMaxStringLength = (): number => {\n const configured = Number(globalThis.process?.env?.APP_ENV_LOGGER_MAX_STRING_LENGTH);\n\n return Number.isFinite(configured) && configured >= 0 ? configured : DEFAULT_MAX_STRING_LENGTH;\n};\n\n/**\n * Keys whose value is long BY NATURE and useless truncated. A stack trace is the whole reason you\n * are reading the line.\n */\nconst UNCAPPED_KEYS = new Set(['stack', 'stacktrace', 'stack_trace']);\n\n/**\n * Caps a long string, keeping the ORIGINAL LENGTH in the marker - that number is what tells you the\n * payload was a 300 KB image rather than a truncated sentence.\n *\n * A base64 body is the case this exists for: one `data:image/png;base64,...` field turns a request\n * log into hundreds of kilobytes, and nothing about it is readable.\n */\nconst capString = (opts: { value: string; key?: string; limit: number }): string => {\n const { value, key, limit } = opts;\n\n if (limit === 0 || value.length <= limit || (key && UNCAPPED_KEYS.has(key.toLowerCase()))) {\n return value;\n }\n\n return `${value.slice(0, limit)}... [truncated, ${value.length} chars total]`;\n};\n\ntype TSanitizeContext = {\n seen: WeakSet<object>;\n doRedact: boolean;\n /** Levels still allowed BELOW the current one; `Infinity` walks the whole graph. */\n depth: number;\n /** Longest string kept whole; 0 keeps every string. */\n maxStringLength: number;\n /** The key this value was found under, so a stack trace can be exempted from capping. */\n key?: string;\n};\n\nconst deepSanitize = (value: unknown, context: TSanitizeContext): unknown => {\n const { seen, doRedact, depth } = context;\n\n if (typeof value === 'string') {\n const text = doRedact ? scrubString(value) : value;\n\n return capString({ value: text, key: context.key, limit: context.maxStringLength });\n }\n\n // A function is not data, and an own `toJSON` on an object would run after this walk, inside `JSON.stringify`, and\n // hand back keys the walk never saw. Naming it keeps the redacted copy free of code.\n if (typeof value === 'function') {\n return '[Function]';\n }\n\n if (value === null || typeof value !== 'object') {\n return value;\n }\n\n // A Date holds its value in an internal slot, so the generic branch below - which reads Object.keys() - would flatten it to `{}`. Checked BEFORE `seen`: a Date cannot carry a cycle, and entering the set would make a second reference to the same instance read as `[Circular]`.\n if (value instanceof Date) {\n return value;\n }\n\n if (seen.has(value)) {\n return '[Circular]';\n }\n\n if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {\n return `[Binary ${(value as ArrayBufferView).byteLength ?? 0} bytes]`;\n }\n\n if (depth <= 0) {\n return Array.isArray(value) ? '[Array]' : '[Object]';\n }\n\n seen.add(value);\n const nested: TSanitizeContext = {\n seen,\n doRedact,\n depth: depth - 1,\n maxStringLength: context.maxStringLength,\n };\n\n // Error keeps name/message/stack NON-enumerable, so Object.keys() skips them and naive redaction would drop the message - reproject into a plain object carrying those fields plus its redacted enumerable own-props.\n if (value instanceof Error) {\n const source = value;\n const result: AnyObject = {\n name: value.name,\n message: doRedact ? scrubString(value.message) : value.message,\n stack: doRedact && value.stack ? scrubString(value.stack) : value.stack,\n };\n\n for (const [key, entry] of Object.entries(source)) {\n result[key] =\n doRedact && SECRET_KEY_PATTERN.test(key)\n ? REDACTED\n : deepSanitize(entry, { ...nested, key });\n }\n\n return result;\n }\n\n if (Array.isArray(value)) {\n return value.map((entry) => deepSanitize(entry, nested));\n }\n\n const source = value;\n const result: AnyObject = {};\n\n for (const [key, entry] of Object.entries(source)) {\n if (doRedact && SECRET_KEY_PATTERN.test(key)) {\n result[key] = REDACTED;\n continue;\n }\n\n result[key] = deepSanitize(entry, { ...nested, key });\n }\n\n return result;\n};\n\n/** Makes a log argument safe to print: masks secret-looking keys, breaks cycles, caps long strings and strips URL credentials. `APP_ENV_LOGGER_DO_REDACT=false` turns off the key masking only. */\nexport class RedactUtility {\n /**\n * Redacts every secret-looking KEY (not value shape - buffers/typed arrays are summarized, not\n * serialized). `APP_ENV_LOGGER_DO_REDACT=false` makes this the identity function.\n *\n * `depth` bounds the walk, exactly as {@link RedactUtility.toJsonSafe} already does. It defaults to\n * `Infinity` for callers that really do want the whole graph, but the logger passes its own bound:\n * rendering only inspects a handful of levels, so walking to `Infinity` did work whose result was\n * thrown away - 12x on a deep graph, and a `RangeError` on a very deep chain.\n *\n * `force: true` masks secret-looking KEYS even when `APP_ENV_LOGGER_DO_REDACT=false`. The result is still the\n * log-shaped copy: long strings are capped, a second reference to one object reads `[Circular]`, binary is\n * summarized, and a key is masked by name only (a card number under `number` is not). It is not a faithful\n * redacted document. The logger never sets it.\n */\n static redactSecrets(opts: {\n value: unknown;\n seen?: WeakSet<object>;\n depth?: number;\n force?: boolean;\n }): unknown {\n const { value, seen, depth = Infinity, force } = opts;\n\n if (!isRedactionEnabled(force)) {\n return value;\n }\n\n return deepSanitize(value, {\n seen: seen ?? new WeakSet<object>(),\n doRedact: true,\n depth,\n maxStringLength: resolveMaxStringLength(),\n });\n }\n\n /** Masks the credentials a plain string carries (a url's password, a bearer token, credential query parameters). For a log line's string argument; objects go through {@link RedactUtility.redactSecrets}. `force: true` scrubs even when `APP_ENV_LOGGER_DO_REDACT=false`. */\n static scrubText(opts: { value: string; force?: boolean }): string {\n return isRedactionEnabled(opts.force) ? scrubString(opts.value) : opts.value;\n }\n\n /** Projects a value into something `JSON.stringify` can render: it answers `[Circular]` for the WHOLE payload when one cycle sits anywhere inside it, so cycles must be broken per-branch first. `depth` bounds the walk the way `util.inspect` does - a log argument may hold a live connector or request context, whose graph is effectively unbounded. The projection itself is unconditional: `APP_ENV_LOGGER_DO_REDACT=false` turns off the key masking, never the structural pass. `force: true` keeps the key masking on whatever the switch says; the projection stays lossy, as in {@link RedactUtility.redactSecrets}. */\n static toJsonSafe(opts: { value: unknown; depth?: number; force?: boolean }): unknown {\n return deepSanitize(opts.value, {\n seen: new WeakSet<object>(),\n doRedact: isRedactionEnabled(opts.force),\n depth: opts.depth ?? Infinity,\n // Capping is STRUCTURAL, like the projection itself: turning redaction off is about key masking,\n // never about letting a 300 KB base64 field through.\n maxStringLength: resolveMaxStringLength(),\n });\n }\n\n /** Strips credentials from a connection URL's authority section (`user:hunter2@host` -> `user:[REDACTED]@host`) - {@link RedactUtility.redactSecrets} matches on KEY names and can't see them there. A value that fails to parse as a URL is returned unchanged. `force: true` strips even when `APP_ENV_LOGGER_DO_REDACT=false`. */\n static redactUrlCredentials(opts: { url: string; force?: boolean }): string {\n const { url, force } = opts;\n\n if (!isRedactionEnabled(force)) {\n return url;\n }\n\n let parsed: URL;\n\n try {\n parsed = new URL(url);\n } catch {\n return url;\n }\n\n if (!parsed.password) {\n return url;\n }\n\n parsed.password = REDACTED;\n\n return decodeURIComponent(parsed.toString());\n }\n}\n"]}
@@ -28,6 +28,7 @@ export { BuildInfoRegistry } from './utilities/build-info.utility.js';
28
28
  export type { IBuildInfo, TBuildInfoRecord } from './utilities/build-info.utility.js';
29
29
  export { ParseUtility } from './utilities/parse.utility.js';
30
30
  export { PerformanceUtility } from './utilities/performance.utility.js';
31
+ export { PromiseUtility } from './utilities/promise.utility.js';
31
32
  export { RecordUtility } from './utilities/record.utility.js';
32
33
  export { FormBodyUtility, RequestBodyErrors } from './utilities/form-body.utility.js';
33
34
  export { ProjectRootRegistry } from './utilities/project-root.utility.js';
package/dist/esm/core.js CHANGED
@@ -35,6 +35,7 @@ export { TreeWalker } from './modules/tree/walk.js';
35
35
  export { BuildInfoRegistry } from './utilities/build-info.utility.js';
36
36
  export { ParseUtility } from './utilities/parse.utility.js';
37
37
  export { PerformanceUtility } from './utilities/performance.utility.js';
38
+ export { PromiseUtility } from './utilities/promise.utility.js';
38
39
  export { RecordUtility } from './utilities/record.utility.js';
39
40
  export { FormBodyUtility, RequestBodyErrors } from './utilities/form-body.utility.js';
40
41
  export { ProjectRootRegistry } from './utilities/project-root.utility.js';
@@ -1 +1 @@
1
- {"version":3,"file":"core.js","sourceRoot":"","sources":["../../src/core.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,6FAA6F;AAC7F,8DAA8D;AAC9D,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,cAAc,iBAAiB,CAAC;AAChC,OAAO,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAE1D,6HAA6H;AAC7H,iHAAiH;AACjH,OAAO,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAC9D,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,cAAc,qDAAqD,CAAC;AACpE,qGAAqG;AACrG,4FAA4F;AAC5F,oBAAoB;AACpB,cAAc,qDAAqD,CAAC;AACpE,cAAc,4DAA4D,CAAC;AAC3E,cAAc,gBAAgB,CAAC;AAC/B,cAAc,6BAA6B,CAAC;AAC5C,cAAc,oBAAoB,CAAC;AACnC,cAAc,eAAe,CAAC;AAC9B,iGAAiG;AACjG,yFAAyF;AACzF,cAAc,yDAAyD,CAAC;AAExE,cAAc,+CAA+C,CAAC;AAC9D,cAAc,0CAA0C,CAAC;AACzD,OAAO,EAAE,sBAAsB,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAC;AAG5F,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AACnD,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAcrD,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAEjD,gGAAgG;AAChG,6FAA6F;AAC7F,iGAAiG;AACjG,0DAA0D;AAC1D,OAAO,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AAEnE,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AACrE,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AACnF,OAAO,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AAEvE,uHAAuH;AACvH,gGAAgG;AAChG,0EAA0E;AAC1E,OAAO,EAAE,uBAAuB,EAAE,MAAM,gDAAgD,CAAC;AACzF,OAAO,EAAE,IAAI,EAAE,MAAM,4CAA4C,CAAC;AAOlE,+FAA+F;AAC/F,6GAA6G;AAC7G,wCAAwC;AACxC,OAAO,EAAE,aAAa,EAAE,MAAM,2CAA2C,CAAC","sourcesContent":["export { BaseHelper } from './modules/base';\n// By name, never `export *` from `./modules/env`: that barrel also carries `Environment` and\n// `applicationEnvironment`, both of which read `process.env`.\nexport { EnvironmentNames } from './modules/env/names';\nexport * from './modules/error';\nexport { LogLevels } from './modules/logger/common/types';\nexport type { ILogger, ILoggerProvider, TLogLevel } from './modules/logger/common/types';\n// The one way to get a logger, the same in the browser and on the server: `LoggerFactory` imports nothing from node, and its\n// default provider is the console. An application chooses another with `LoggerFactory.use({ provider, level })`.\nexport { ConsoleLogger } from './modules/logger/base/console';\nexport { LoggerFactory } from './modules/logger/factory';\nexport * from './modules/network/http-request/fetcher/base-fetcher';\n// The node fetcher carries no node builtin - its one `querystring.stringify` is written out - so the\n// framework HTTP layer is reachable from a browser bundle, and a connector on HTTP need not\n// re-implement one.\nexport * from './modules/network/http-request/fetcher/node-fetcher';\nexport * from './modules/network/http-request/base-network-request.helper';\nexport * from './modules/pool';\nexport * from './modules/queue/internal/hf';\nexport * from './modules/temporal';\nexport * from './modules/uid';\n// The url guard, pure half only: `UrlPolicy` decides a url and a literal address with string and\n// number work. Its sibling `UrlIngest` reaches `node:dns` and stays out of this subpath.\nexport * from './modules/network/utilities/url-safety/common/constants';\nexport type { IUrlSafetyPolicy } from './modules/network/utilities/url-safety/common/types';\nexport * from './modules/network/utilities/url-safety/policy';\nexport * from './modules/network/utilities/query-string';\nexport { RetryBackoffStrategies, RetryJitterModes } from './modules/retry/common/constants';\nexport type { TRetryBackoffStrategy, TRetryJitterMode } from './modules/retry/common/constants';\nexport type { IRetryBackoffOptions, IRetryContext } from './modules/retry/common/types';\nexport { RetryHelper } from './modules/retry/helper';\nexport { SlugHelper } from './modules/slug/helper';\nexport { TreeBuilder } from './modules/tree/builder';\nexport type {\n IBuildOptions,\n IHeightWhereOptions,\n ILeavesOptions,\n INodeWithPath,\n IPrintOptions,\n ITreeNode,\n IWalkAsyncOptions,\n IWalkOptions,\n TNodePredicate,\n TOnVisit,\n TOnVisitAsync,\n} from './modules/tree/common/types';\nexport { TreeWalker } from './modules/tree/walk';\n\n// Pure value/type utilities that already live under the root barrel's `./utilities` re-export -\n// that barrel also carries node-only siblings (module.utility.ts, request.utility.ts), so it\n// cannot itself become a subpath. Named one at a time here instead of widening the barrel: every\n// symbol below is verified free of node builtins/globals.\nexport { BuildInfoRegistry } from './utilities/build-info.utility';\nexport type { IBuildInfo, TBuildInfoRecord } from './utilities/build-info.utility';\nexport { ParseUtility } from './utilities/parse.utility';\nexport { PerformanceUtility } from './utilities/performance.utility';\nexport { RecordUtility } from './utilities/record.utility';\nexport { FormBodyUtility, RequestBodyErrors } from './utilities/form-body.utility';\nexport { ProjectRootRegistry } from './utilities/project-root.utility';\n\n// `ECDH` is the one crypto algorithm that is browser-pure: it runs over `crypto.subtle`, `btoa` and `atob`. It and its\n// base class come by leaf path, never the algorithms barrel, which also carries `AES` and `RSA`\n// (server code: they use `Buffer`, and `AES` reads files with `node:fs`).\nexport { AbstractCryptoAlgorithm } from './modules/crypto/algorithms/abstract.algorithm';\nexport { ECDH } from './modules/crypto/algorithms/ecdh.algorithm';\nexport type {\n ECDHAlgorithmType,\n IECDHEncryptedPayload,\n IECDHExtraOptions,\n} from './modules/crypto/algorithms/ecdh.algorithm';\n\n// Type-only: erased at compile time, so re-exporting these carries no runtime/bundle cost even\n// though the concrete classes they describe (the other crypto algorithms, the ioredis-backed helper) are not\n// themselves part of this pure surface.\nexport { AESAlgorithms } from './modules/crypto/algorithms/aes.constants';\nexport type { AESAlgorithmType } from './modules/crypto/algorithms/aes.constants';\nexport type { IRedisHelper } from './modules/redis/common/interfaces';\n"]}
1
+ {"version":3,"file":"core.js","sourceRoot":"","sources":["../../src/core.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,6FAA6F;AAC7F,8DAA8D;AAC9D,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,cAAc,iBAAiB,CAAC;AAChC,OAAO,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAE1D,6HAA6H;AAC7H,iHAAiH;AACjH,OAAO,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAC9D,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,cAAc,qDAAqD,CAAC;AACpE,qGAAqG;AACrG,4FAA4F;AAC5F,oBAAoB;AACpB,cAAc,qDAAqD,CAAC;AACpE,cAAc,4DAA4D,CAAC;AAC3E,cAAc,gBAAgB,CAAC;AAC/B,cAAc,6BAA6B,CAAC;AAC5C,cAAc,oBAAoB,CAAC;AACnC,cAAc,eAAe,CAAC;AAC9B,iGAAiG;AACjG,yFAAyF;AACzF,cAAc,yDAAyD,CAAC;AAExE,cAAc,+CAA+C,CAAC;AAC9D,cAAc,0CAA0C,CAAC;AACzD,OAAO,EAAE,sBAAsB,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAC;AAG5F,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AACnD,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAcrD,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAEjD,gGAAgG;AAChG,6FAA6F;AAC7F,iGAAiG;AACjG,0DAA0D;AAC1D,OAAO,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AAEnE,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AACrE,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AACnF,OAAO,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AAEvE,uHAAuH;AACvH,gGAAgG;AAChG,0EAA0E;AAC1E,OAAO,EAAE,uBAAuB,EAAE,MAAM,gDAAgD,CAAC;AACzF,OAAO,EAAE,IAAI,EAAE,MAAM,4CAA4C,CAAC;AAOlE,+FAA+F;AAC/F,6GAA6G;AAC7G,wCAAwC;AACxC,OAAO,EAAE,aAAa,EAAE,MAAM,2CAA2C,CAAC","sourcesContent":["export { BaseHelper } from './modules/base';\n// By name, never `export *` from `./modules/env`: that barrel also carries `Environment` and\n// `applicationEnvironment`, both of which read `process.env`.\nexport { EnvironmentNames } from './modules/env/names';\nexport * from './modules/error';\nexport { LogLevels } from './modules/logger/common/types';\nexport type { ILogger, ILoggerProvider, TLogLevel } from './modules/logger/common/types';\n// The one way to get a logger, the same in the browser and on the server: `LoggerFactory` imports nothing from node, and its\n// default provider is the console. An application chooses another with `LoggerFactory.use({ provider, level })`.\nexport { ConsoleLogger } from './modules/logger/base/console';\nexport { LoggerFactory } from './modules/logger/factory';\nexport * from './modules/network/http-request/fetcher/base-fetcher';\n// The node fetcher carries no node builtin - its one `querystring.stringify` is written out - so the\n// framework HTTP layer is reachable from a browser bundle, and a connector on HTTP need not\n// re-implement one.\nexport * from './modules/network/http-request/fetcher/node-fetcher';\nexport * from './modules/network/http-request/base-network-request.helper';\nexport * from './modules/pool';\nexport * from './modules/queue/internal/hf';\nexport * from './modules/temporal';\nexport * from './modules/uid';\n// The url guard, pure half only: `UrlPolicy` decides a url and a literal address with string and\n// number work. Its sibling `UrlIngest` reaches `node:dns` and stays out of this subpath.\nexport * from './modules/network/utilities/url-safety/common/constants';\nexport type { IUrlSafetyPolicy } from './modules/network/utilities/url-safety/common/types';\nexport * from './modules/network/utilities/url-safety/policy';\nexport * from './modules/network/utilities/query-string';\nexport { RetryBackoffStrategies, RetryJitterModes } from './modules/retry/common/constants';\nexport type { TRetryBackoffStrategy, TRetryJitterMode } from './modules/retry/common/constants';\nexport type { IRetryBackoffOptions, IRetryContext } from './modules/retry/common/types';\nexport { RetryHelper } from './modules/retry/helper';\nexport { SlugHelper } from './modules/slug/helper';\nexport { TreeBuilder } from './modules/tree/builder';\nexport type {\n IBuildOptions,\n IHeightWhereOptions,\n ILeavesOptions,\n INodeWithPath,\n IPrintOptions,\n ITreeNode,\n IWalkAsyncOptions,\n IWalkOptions,\n TNodePredicate,\n TOnVisit,\n TOnVisitAsync,\n} from './modules/tree/common/types';\nexport { TreeWalker } from './modules/tree/walk';\n\n// Pure value/type utilities that already live under the root barrel's `./utilities` re-export -\n// that barrel also carries node-only siblings (module.utility.ts, request.utility.ts), so it\n// cannot itself become a subpath. Named one at a time here instead of widening the barrel: every\n// symbol below is verified free of node builtins/globals.\nexport { BuildInfoRegistry } from './utilities/build-info.utility';\nexport type { IBuildInfo, TBuildInfoRecord } from './utilities/build-info.utility';\nexport { ParseUtility } from './utilities/parse.utility';\nexport { PerformanceUtility } from './utilities/performance.utility';\nexport { PromiseUtility } from './utilities/promise.utility';\nexport { RecordUtility } from './utilities/record.utility';\nexport { FormBodyUtility, RequestBodyErrors } from './utilities/form-body.utility';\nexport { ProjectRootRegistry } from './utilities/project-root.utility';\n\n// `ECDH` is the one crypto algorithm that is browser-pure: it runs over `crypto.subtle`, `btoa` and `atob`. It and its\n// base class come by leaf path, never the algorithms barrel, which also carries `AES` and `RSA`\n// (server code: they use `Buffer`, and `AES` reads files with `node:fs`).\nexport { AbstractCryptoAlgorithm } from './modules/crypto/algorithms/abstract.algorithm';\nexport { ECDH } from './modules/crypto/algorithms/ecdh.algorithm';\nexport type {\n ECDHAlgorithmType,\n IECDHEncryptedPayload,\n IECDHExtraOptions,\n} from './modules/crypto/algorithms/ecdh.algorithm';\n\n// Type-only: erased at compile time, so re-exporting these carries no runtime/bundle cost even\n// though the concrete classes they describe (the other crypto algorithms, the ioredis-backed helper) are not\n// themselves part of this pure surface.\nexport { AESAlgorithms } from './modules/crypto/algorithms/aes.constants';\nexport type { AESAlgorithmType } from './modules/crypto/algorithms/aes.constants';\nexport type { IRedisHelper } from './modules/redis/common/interfaces';\n"]}
@@ -1,18 +1,14 @@
1
1
  import { AESAlgorithms, type AESAlgorithmType } from './aes.constants.js';
2
2
  import { BaseCryptoAlgorithm } from './base.algorithm.js';
3
- interface IAESDecryptOptions {
3
+ /** Options of `AES.encrypt` and `AES.decrypt`. There is no `iv`: every encryption draws a fresh random one, and decrypt reads it from the envelope. */
4
+ interface IAESOptions {
4
5
  inputEncoding?: BufferEncoding;
5
6
  outputEncoding?: BufferEncoding;
6
- doThrow?: boolean;
7
7
  /** Per-deployment PBKDF2 salt override. Must be supplied identically on encrypt and decrypt; omit for the shipped default. */
8
8
  kdfSalt?: string;
9
9
  /** PBKDF2 iteration count override. Must be supplied identically on encrypt and decrypt; omit for the shipped default. */
10
10
  kdfIterations?: number;
11
11
  }
12
- /** `iv` is encrypt-only: the envelope carries the IV, so decrypt reads it from there and a supplied one would be silently ignored. */
13
- interface IAESExtraOptions extends IAESDecryptOptions {
14
- iv?: Buffer;
15
- }
16
12
  /** One key in a keyring: `id` is written into the ciphertext so decrypt can pick the matching `secret`. */
17
13
  export interface IAESKeyringEntry {
18
14
  id: string;
@@ -22,7 +18,9 @@ export interface IAESKeyringEntry {
22
18
  export type TAESSecret = string | IAESKeyringEntry[];
23
19
  export { AESAlgorithms, type AESAlgorithmType };
24
20
  /** `encrypt` and `decrypt` are async: key derivation and the cipher run over `crypto.subtle`. */
25
- export declare class AES extends BaseCryptoAlgorithm<AESAlgorithmType, string, string, TAESSecret, Promise<string>, Promise<string>, IAESExtraOptions> {
21
+ export declare class AES extends BaseCryptoAlgorithm<AESAlgorithmType, string, string, TAESSecret, Promise<string>, Promise<string>, IAESOptions> {
22
+ /** The options AES refuses: `doThrow` (a failure always throws) and `iv` (every encryption draws its own). */
23
+ private static readonly REMOVED_OPTIONS;
26
24
  constructor(opts: {
27
25
  algorithm: AESAlgorithmType;
28
26
  });
@@ -44,7 +42,7 @@ export declare class AES extends BaseCryptoAlgorithm<AESAlgorithmType, string, s
44
42
  encrypt(opts: {
45
43
  message: string;
46
44
  secret: TAESSecret;
47
- opts?: IAESExtraOptions;
45
+ opts?: IAESOptions;
48
46
  }): Promise<string>;
49
47
  encryptFile(opts: {
50
48
  absolutePath: string;
@@ -53,7 +51,7 @@ export declare class AES extends BaseCryptoAlgorithm<AESAlgorithmType, string, s
53
51
  decrypt(opts: {
54
52
  message: string;
55
53
  secret: TAESSecret;
56
- opts?: IAESDecryptOptions;
54
+ opts?: IAESOptions;
57
55
  }): Promise<string>;
58
56
  decryptFile(opts: {
59
57
  absolutePath: string;
@@ -10,6 +10,8 @@ const DEFAULT_KEY_ID = '0';
10
10
  export { AESAlgorithms };
11
11
  /** `encrypt` and `decrypt` are async: key derivation and the cipher run over `crypto.subtle`. */
12
12
  export class AES extends BaseCryptoAlgorithm {
13
+ /** The options AES refuses: `doThrow` (a failure always throws) and `iv` (every encryption draws its own). */
14
+ static { this.REMOVED_OPTIONS = ['doThrow', 'iv']; }
13
15
  constructor(opts) {
14
16
  super({ scope: AES.name, ...opts });
15
17
  }
@@ -57,40 +59,33 @@ export class AES extends BaseCryptoAlgorithm {
57
59
  }
58
60
  async encrypt(opts) {
59
61
  const { message, secret } = opts;
60
- const { iv = Buffer.from(crypto.getRandomValues(new Uint8Array(DEFAULT_LENGTH))), inputEncoding = 'utf-8', outputEncoding = 'base64', doThrow = true, kdfSalt, kdfIterations, } = opts.opts ?? {};
61
- try {
62
- const { id, key } = await this.resolveEncryptKey({ secret, kdfSalt, kdfIterations });
63
- const idBuffer = Buffer.from(id, 'utf-8');
64
- if (idBuffer.length > 0xff) {
65
- throw getError({ message: '[AES][encrypt] Key id too long (max 255 bytes)' });
66
- }
67
- // `decrypt` reads exactly DEFAULT_LENGTH bytes of IV from the envelope, so any other length would write a ciphertext nothing can read.
68
- if (iv.length !== DEFAULT_LENGTH) {
69
- throw getError({
70
- message: `[AES][encrypt] The IV must be ${DEFAULT_LENGTH} bytes, got ${iv.length}`,
71
- });
72
- }
73
- const { cipherText, authTag } = await AesEngine.seal({
74
- algorithm: this.algorithm,
75
- key,
76
- iv,
77
- plain: Buffer.from(message, inputEncoding),
78
- });
79
- // Envelope: [version(1)][idLen(1)][id(idLen)][iv(16)][authTag(16, gcm only)][cipher]
80
- const header = Buffer.from([CIPHERTEXT_VERSION, idBuffer.length]);
81
- const parts = [header, idBuffer, iv];
82
- if (authTag !== null) {
83
- parts.push(authTag);
84
- }
85
- parts.push(cipherText);
86
- return Buffer.concat(parts).toString(outputEncoding);
62
+ this.assertNoRemovedOptions({
63
+ method: 'encrypt',
64
+ options: opts.opts,
65
+ removed: AES.REMOVED_OPTIONS,
66
+ });
67
+ // Fresh for every call, from the system's random source: the IV is never the caller's to choose.
68
+ const iv = Buffer.from(crypto.getRandomValues(new Uint8Array(DEFAULT_LENGTH)));
69
+ const { inputEncoding = 'utf-8', outputEncoding = 'base64', kdfSalt, kdfIterations, } = opts.opts ?? {};
70
+ const { id, key } = await this.resolveEncryptKey({ secret, kdfSalt, kdfIterations });
71
+ const idBuffer = Buffer.from(id, 'utf-8');
72
+ if (idBuffer.length > 0xff) {
73
+ throw getError({ message: '[AES][encrypt] Key id too long (max 255 bytes)' });
87
74
  }
88
- catch (error) {
89
- if (doThrow) {
90
- throw error;
91
- }
92
- return message;
75
+ const { cipherText, authTag } = await AesEngine.seal({
76
+ algorithm: this.algorithm,
77
+ key,
78
+ iv,
79
+ plain: Buffer.from(message, inputEncoding),
80
+ });
81
+ // Envelope: [version(1)][idLen(1)][id(idLen)][iv(16)][authTag(16, gcm only)][cipher]
82
+ const header = Buffer.from([CIPHERTEXT_VERSION, idBuffer.length]);
83
+ const parts = [header, idBuffer, iv];
84
+ if (authTag !== null) {
85
+ parts.push(authTag);
93
86
  }
87
+ parts.push(cipherText);
88
+ return Buffer.concat(parts).toString(outputEncoding);
94
89
  }
95
90
  async encryptFile(opts) {
96
91
  const { absolutePath, secret } = opts;
@@ -103,40 +98,37 @@ export class AES extends BaseCryptoAlgorithm {
103
98
  }
104
99
  async decrypt(opts) {
105
100
  const { message, secret } = opts;
106
- const { inputEncoding = 'base64', outputEncoding = 'utf-8', doThrow = true, kdfSalt, kdfIterations, } = opts.opts ?? {};
107
- try {
108
- const raw = Buffer.from(message, inputEncoding);
109
- const version = raw[0];
110
- if (version !== CIPHERTEXT_VERSION) {
111
- throw getError({ message: `[AES][decrypt] Unsupported ciphertext version: ${version}` });
112
- }
113
- const idLength = raw[1];
114
- let cursor = 2;
115
- const id = raw.subarray(cursor, cursor + idLength).toString('utf-8');
116
- cursor += idLength;
117
- const iv = raw.subarray(cursor, cursor + DEFAULT_LENGTH);
118
- cursor += DEFAULT_LENGTH;
119
- const key = await this.resolveDecryptKey({ secret, id, kdfSalt, kdfIterations });
120
- let authTag = null;
121
- if (this.algorithm === AESAlgorithms.AES_256_GCM) {
122
- authTag = raw.subarray(cursor, cursor + DEFAULT_LENGTH);
123
- cursor += DEFAULT_LENGTH;
124
- }
125
- const plain = await AesEngine.open({
126
- algorithm: this.algorithm,
127
- key,
128
- iv,
129
- cipherText: raw.subarray(cursor),
130
- authTag,
131
- });
132
- return Buffer.from(plain).toString(outputEncoding);
101
+ this.assertNoRemovedOptions({
102
+ method: 'decrypt',
103
+ options: opts.opts,
104
+ removed: AES.REMOVED_OPTIONS,
105
+ });
106
+ const { inputEncoding = 'base64', outputEncoding = 'utf-8', kdfSalt, kdfIterations, } = opts.opts ?? {};
107
+ const raw = Buffer.from(message, inputEncoding);
108
+ const version = raw[0];
109
+ if (version !== CIPHERTEXT_VERSION) {
110
+ throw getError({ message: `[AES][decrypt] Unsupported ciphertext version: ${version}` });
133
111
  }
134
- catch (error) {
135
- if (doThrow) {
136
- throw error;
137
- }
138
- return message;
112
+ const idLength = raw[1];
113
+ let cursor = 2;
114
+ const id = raw.subarray(cursor, cursor + idLength).toString('utf-8');
115
+ cursor += idLength;
116
+ const iv = raw.subarray(cursor, cursor + DEFAULT_LENGTH);
117
+ cursor += DEFAULT_LENGTH;
118
+ const key = await this.resolveDecryptKey({ secret, id, kdfSalt, kdfIterations });
119
+ let authTag = null;
120
+ if (this.algorithm === AESAlgorithms.AES_256_GCM) {
121
+ authTag = raw.subarray(cursor, cursor + DEFAULT_LENGTH);
122
+ cursor += DEFAULT_LENGTH;
139
123
  }
124
+ const plain = await AesEngine.open({
125
+ algorithm: this.algorithm,
126
+ key,
127
+ iv,
128
+ cipherText: raw.subarray(cursor),
129
+ authTag,
130
+ });
131
+ return Buffer.from(plain).toString(outputEncoding);
140
132
  }
141
133
  async decryptFile(opts) {
142
134
  const { absolutePath, secret } = opts;
@@ -1 +1 @@
1
- {"version":3,"file":"aes.algorithm.js","sourceRoot":"","sources":["../../../../../src/modules/crypto/algorithms/aes.algorith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C,CAAC,QAAQ,CAAC,cAAc,CAAC,CAAC;QACrD,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;IAED,KAAK,CAAC,WAAW,CAAC,IAAkD;QAClE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;QAEtC,IAAI,CAAC,YAAY,IAAI,aAAa,CAAC,OAAO,CAAC,EAAE,KAAK,EAAE,YAAY,EAAE,CAAC,EAAE,CAAC;YACpE,OAAO,EAAE,CAAC;QACZ,CAAC;QAED,MAAM,MAAM,GAAG,EAAE,CAAC,YAAY,CAAC,YAAY,CAAC,CAAC;QAC7C,MAAM,WAAW,GAAG,MAAM,EAAE,QAAQ,CAAC,OAAO,CAAC,CAAC;QAE9C,OAAO,IAAI,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,CAAC,CAAC;IACxD,CAAC;CACF","sourcesContent":["import { AESAlgorithms, type AESAlgorithmType } from './aes.constants';\nimport { ObjectUtility } from '@venizia/ignis-inversion';\nimport fs from 'node:fs';\nimport { getError } from '@/modules/error';\nimport { AesEngine } from './aes.engine';\nimport { BaseCryptoAlgorithm } from './base.algorithm';\n\nconst DEFAULT_LENGTH = 16;\nconst CIPHERTEXT_VERSION = 0x01;\nconst DEFAULT_KEY_ID = '0';\n\ninterface IAESDecryptOptions {\n inputEncoding?: BufferEncoding;\n outputEncoding?: BufferEncoding;\n doThrow?: boolean;\n /** Per-deployment PBKDF2 salt override. Must be supplied identically on encrypt and decrypt; omit for the shipped default. */\n kdfSalt?: string;\n /** PBKDF2 iteration count override. Must be supplied identically on encrypt and decrypt; omit for the shipped default. */\n kdfIterations?: number;\n}\n\n/** `iv` is encrypt-only: the envelope carries the IV, so decrypt reads it from there and a supplied one would be silently ignored. */\ninterface IAESExtraOptions extends IAESDecryptOptions {\n iv?: Buffer;\n}\n\n/** One key in a keyring: `id` is written into the ciphertext so decrypt can pick the matching `secret`. */\nexport interface IAESKeyringEntry {\n id: string;\n secret: string;\n}\n\n/** A single secret string, or a keyring. Encrypt uses the first keyring entry; decrypt uses the entry whose `id` matches the ciphertext. */\nexport type TAESSecret = string | IAESKeyringEntry[];\n\nexport { AESAlgorithms, type AESAlgorithmType };\n\n/** `encrypt` and `decrypt` are async: key derivation and the cipher run over `crypto.subtle`. */\nexport class AES extends BaseCryptoAlgorithm<\n AESAlgorithmType,\n string,\n string,\n TAESSecret,\n Promise<string>,\n Promise<string>,\n IAESExtraOptions\n> {\n constructor(opts: { algorithm: AESAlgorithmType }) {\n super({ scope: AES.name, ...opts });\n }\n\n static withAlgorithm(algorithm: AESAlgorithmType) {\n return new AES({ algorithm });\n }\n\n protected async resolveEncryptKey(opts: {\n secret: TAESSecret;\n kdfSalt?: string;\n kdfIterations?: number;\n }): Promise<{ id: string; key: Buffer }> {\n const { secret, kdfSalt, kdfIterations } = opts;\n const entry = Array.isArray(secret) ? secret[0] : { id: DEFAULT_KEY_ID, secret };\n\n if (!entry || ObjectUtility.isEmpty({ value: entry.secret })) {\n throw getError({ message: '[AES][resolveEncryptKey] Missing secret or empty keyring' });\n }\n\n const key = await this.normalizeSecretKey({\n secret: entry.secret,\n length: this.getAlgorithmKeySize(),\n kdfSalt,\n kdfIterations,\n });\n\n return { id: entry.id, key };\n }\n\n protected async resolveDecryptKey(opts: {\n secret: TAESSecret;\n id: string;\n kdfSalt?: string;\n kdfIterations?: number;\n }): Promise<Buffer> {\n const { secret, id, kdfSalt, kdfIterations } = opts;\n const length = this.getAlgorithmKeySize();\n\n if (!Array.isArray(secret)) {\n return this.normalizeSecretKey({ secret, length, kdfSalt, kdfIterations });\n }\n\n const entry = secret.find((e) => e.id === id);\n\n if (!entry) {\n throw getError({\n message: `[AES][resolveDecryptKey] No key in keyring matches ciphertext key id \"${id}\"`,\n });\n }\n\n // Without this the empty secret derives a key from '' and fails as an opaque OpenSSL error, hiding a plain configuration mistake.\n if (ObjectUtility.isEmpty({ value: entry.secret })) {\n throw getError({\n message: `[AES][resolveDecryptKey] Keyring entry for key id \"${id}\" has an empty secret`,\n });\n }\n\n return this.normalizeSecretKey({\n secret: entry.secret,\n length,\n kdfSalt,\n kdfIterations,\n });\n }\n\n async encrypt(opts: {\n message: string;\n secret: TAESSecret;\n opts?: IAESExtraOptions;\n }): Promise<string> {\n const { message, secret } = opts;\n const {\n iv = Buffer.from(crypto.getRandomValues(new Uint8Array(DEFAULT_LENGTH))),\n inputEncoding = 'utf-8',\n outputEncoding = 'base64',\n doThrow = true,\n kdfSalt,\n kdfIterations,\n } = opts.opts ?? {};\n\n try {\n const { id, key } = await this.resolveEncryptKey({ secret, kdfSalt, kdfIterations });\n const idBuffer = Buffer.from(id, 'utf-8');\n\n if (idBuffer.length > 0xff) {\n throw getError({ message: '[AES][encrypt] Key id too long (max 255 bytes)' });\n }\n\n // `decrypt` reads exactly DEFAULT_LENGTH bytes of IV from the envelope, so any other length would write a ciphertext nothing can read.\n if (iv.length !== DEFAULT_LENGTH) {\n throw getError({\n message: `[AES][encrypt] The IV must be ${DEFAULT_LENGTH} bytes, got ${iv.length}`,\n });\n }\n\n const { cipherText, authTag } = await AesEngine.seal({\n algorithm: this.algorithm,\n key,\n iv,\n plain: Buffer.from(message, inputEncoding),\n });\n\n // Envelope: [version(1)][idLen(1)][id(idLen)][iv(16)][authTag(16, gcm only)][cipher]\n const header = Buffer.from([CIPHERTEXT_VERSION, idBuffer.length]);\n const parts: Uint8Array[] = [header, idBuffer, iv];\n\n if (authTag !== null) {\n parts.push(authTag);\n }\n\n parts.push(cipherText);\n\n return Buffer.concat(parts).toString(outputEncoding);\n } catch (error) {\n if (doThrow) {\n throw error;\n }\n\n return message;\n }\n }\n\n async encryptFile(opts: { absolutePath: string; secret: TAESSecret }): Promise<string> {\n const { absolutePath, secret } = opts;\n\n if (!absolutePath || ObjectUtility.isEmpty({ value: absolutePath })) {\n return '';\n }\n\n const buffer = fs.readFileSync(absolutePath);\n const fileContent = buffer?.toString('utf-8');\n\n return this.encrypt({ message: fileContent, secret });\n }\n\n async decrypt(opts: {\n message: string;\n secret: TAESSecret;\n opts?: IAESDecryptOptions;\n }): Promise<string> {\n const { message, secret } = opts;\n const {\n inputEncoding = 'base64',\n outputEncoding = 'utf-8',\n doThrow = true,\n kdfSalt,\n kdfIterations,\n } = opts.opts ?? {};\n\n try {\n const raw = Buffer.from(message, inputEncoding);\n\n const version = raw[0];\n\n if (version !== CIPHERTEXT_VERSION) {\n throw getError({ message: `[AES][decrypt] Unsupported ciphertext version: ${version}` });\n }\n\n const idLength = raw[1];\n let cursor = 2;\n\n const id = raw.subarray(cursor, cursor + idLength).toString('utf-8');\n cursor += idLength;\n\n const iv = raw.subarray(cursor, cursor + DEFAULT_LENGTH);\n cursor += DEFAULT_LENGTH;\n\n const key = await this.resolveDecryptKey({ secret, id, kdfSalt, kdfIterations });\n\n let authTag: Uint8Array | null = null;\n\n if (this.algorithm === AESAlgorithms.AES_256_GCM) {\n authTag = raw.subarray(cursor, cursor + DEFAULT_LENGTH);\n cursor += DEFAULT_LENGTH;\n }\n\n const plain = await AesEngine.open({\n algorithm: this.algorithm,\n key,\n iv,\n cipherText: raw.subarray(cursor),\n authTag,\n });\n\n return Buffer.from(plain).toString(outputEncoding);\n } catch (error) {\n if (doThrow) {\n throw error;\n }\n\n return message;\n }\n }\n\n async decryptFile(opts: { absolutePath: string; secret: TAESSecret }): Promise<string> {\n const { absolutePath, secret } = opts;\n\n if (!absolutePath || ObjectUtility.isEmpty({ value: absolutePath })) {\n return '';\n }\n\n const buffer = fs.readFileSync(absolutePath);\n const fileContent = buffer?.toString('utf-8');\n\n return this.decrypt({ message: fileContent, secret });\n }\n}\n"]}
1
+ {"version":3,"file":"aes.algorithm.js","sourceRoot":"","sources":["../../../../../src/modules/crypto/algorithms/aes.algorithm.ts"],"names":[],"mappings":"AAAA,O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,KAAK,CAAC,WAAW,CAAC,IAAkD;QAClE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;QAEtC,IAAI,CAAC,YAAY,IAAI,aAAa,CAAC,OAAO,CAAC,EAAE,KAAK,EAAE,YAAY,EAAE,CAAC,EAAE,CAAC;YACpE,OAAO,EAAE,CAAC;QACZ,CAAC;QAED,MAAM,MAAM,GAAG,EAAE,CAAC,YAAY,CAAC,YAAY,CAAC,CAAC;QAC7C,MAAM,WAAW,GAAG,MAAM,EAAE,QAAQ,CAAC,OAAO,CAAC,CAAC;QAE9C,OAAO,IAAI,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,CAAC,CAAC;IACxD,CAAC","sourcesContent":["import { AESAlgorithms, type AESAlgorithmType } from './aes.constants';\nimport { ObjectUtility } from '@venizia/ignis-inversion';\nimport fs from 'node:fs';\nimport { getError } from '@/modules/error';\nimport { AesEngine } from './aes.engine';\nimport { BaseCryptoAlgorithm } from './base.algorithm';\n\nconst DEFAULT_LENGTH = 16;\nconst CIPHERTEXT_VERSION = 0x01;\nconst DEFAULT_KEY_ID = '0';\n\n/** Options of `AES.encrypt` and `AES.decrypt`. There is no `iv`: every encryption draws a fresh random one, and decrypt reads it from the envelope. */\ninterface IAESOptions {\n inputEncoding?: BufferEncoding;\n outputEncoding?: BufferEncoding;\n /** Per-deployment PBKDF2 salt override. Must be supplied identically on encrypt and decrypt; omit for the shipped default. */\n kdfSalt?: string;\n /** PBKDF2 iteration count override. Must be supplied identically on encrypt and decrypt; omit for the shipped default. */\n kdfIterations?: number;\n}\n\n/** One key in a keyring: `id` is written into the ciphertext so decrypt can pick the matching `secret`. */\nexport interface IAESKeyringEntry {\n id: string;\n secret: string;\n}\n\n/** A single secret string, or a keyring. Encrypt uses the first keyring entry; decrypt uses the entry whose `id` matches the ciphertext. */\nexport type TAESSecret = string | IAESKeyringEntry[];\n\nexport { AESAlgorithms, type AESAlgorithmType };\n\n/** `encrypt` and `decrypt` are async: key derivation and the cipher run over `crypto.subtle`. */\nexport class AES extends BaseCryptoAlgorithm<\n AESAlgorithmType,\n string,\n string,\n TAESSecret,\n Promise<string>,\n Promise<string>,\n IAESOptions\n> {\n /** The options AES refuses: `doThrow` (a failure always throws) and `iv` (every encryption draws its own). */\n private static readonly REMOVED_OPTIONS = ['doThrow', 'iv'] as const;\n\n constructor(opts: { algorithm: AESAlgorithmType }) {\n super({ scope: AES.name, ...opts });\n }\n\n static withAlgorithm(algorithm: AESAlgorithmType) {\n return new AES({ algorithm });\n }\n\n protected async resolveEncryptKey(opts: {\n secret: TAESSecret;\n kdfSalt?: string;\n kdfIterations?: number;\n }): Promise<{ id: string; key: Buffer }> {\n const { secret, kdfSalt, kdfIterations } = opts;\n const entry = Array.isArray(secret) ? secret[0] : { id: DEFAULT_KEY_ID, secret };\n\n if (!entry || ObjectUtility.isEmpty({ value: entry.secret })) {\n throw getError({ message: '[AES][resolveEncryptKey] Missing secret or empty keyring' });\n }\n\n const key = await this.normalizeSecretKey({\n secret: entry.secret,\n length: this.getAlgorithmKeySize(),\n kdfSalt,\n kdfIterations,\n });\n\n return { id: entry.id, key };\n }\n\n protected async resolveDecryptKey(opts: {\n secret: TAESSecret;\n id: string;\n kdfSalt?: string;\n kdfIterations?: number;\n }): Promise<Buffer> {\n const { secret, id, kdfSalt, kdfIterations } = opts;\n const length = this.getAlgorithmKeySize();\n\n if (!Array.isArray(secret)) {\n return this.normalizeSecretKey({ secret, length, kdfSalt, kdfIterations });\n }\n\n const entry = secret.find((e) => e.id === id);\n\n if (!entry) {\n throw getError({\n message: `[AES][resolveDecryptKey] No key in keyring matches ciphertext key id \"${id}\"`,\n });\n }\n\n // Without this the empty secret derives a key from '' and fails as an opaque OpenSSL error, hiding a plain configuration mistake.\n if (ObjectUtility.isEmpty({ value: entry.secret })) {\n throw getError({\n message: `[AES][resolveDecryptKey] Keyring entry for key id \"${id}\" has an empty secret`,\n });\n }\n\n return this.normalizeSecretKey({\n secret: entry.secret,\n length,\n kdfSalt,\n kdfIterations,\n });\n }\n\n async encrypt(opts: {\n message: string;\n secret: TAESSecret;\n opts?: IAESOptions;\n }): Promise<string> {\n const { message, secret } = opts;\n this.assertNoRemovedOptions({\n method: 'encrypt',\n options: opts.opts,\n removed: AES.REMOVED_OPTIONS,\n });\n\n // Fresh for every call, from the system's random source: the IV is never the caller's to choose.\n const iv = Buffer.from(crypto.getRandomValues(new Uint8Array(DEFAULT_LENGTH)));\n const {\n inputEncoding = 'utf-8',\n outputEncoding = 'base64',\n kdfSalt,\n kdfIterations,\n } = opts.opts ?? {};\n\n const { id, key } = await this.resolveEncryptKey({ secret, kdfSalt, kdfIterations });\n const idBuffer = Buffer.from(id, 'utf-8');\n\n if (idBuffer.length > 0xff) {\n throw getError({ message: '[AES][encrypt] Key id too long (max 255 bytes)' });\n }\n\n const { cipherText, authTag } = await AesEngine.seal({\n algorithm: this.algorithm,\n key,\n iv,\n plain: Buffer.from(message, inputEncoding),\n });\n\n // Envelope: [version(1)][idLen(1)][id(idLen)][iv(16)][authTag(16, gcm only)][cipher]\n const header = Buffer.from([CIPHERTEXT_VERSION, idBuffer.length]);\n const parts: Uint8Array[] = [header, idBuffer, iv];\n\n if (authTag !== null) {\n parts.push(authTag);\n }\n\n parts.push(cipherText);\n\n return Buffer.concat(parts).toString(outputEncoding);\n }\n\n async encryptFile(opts: { absolutePath: string; secret: TAESSecret }): Promise<string> {\n const { absolutePath, secret } = opts;\n\n if (!absolutePath || ObjectUtility.isEmpty({ value: absolutePath })) {\n return '';\n }\n\n const buffer = fs.readFileSync(absolutePath);\n const fileContent = buffer?.toString('utf-8');\n\n return this.encrypt({ message: fileContent, secret });\n }\n\n async decrypt(opts: {\n message: string;\n secret: TAESSecret;\n opts?: IAESOptions;\n }): Promise<string> {\n const { message, secret } = opts;\n this.assertNoRemovedOptions({\n method: 'decrypt',\n options: opts.opts,\n removed: AES.REMOVED_OPTIONS,\n });\n\n const {\n inputEncoding = 'base64',\n outputEncoding = 'utf-8',\n kdfSalt,\n kdfIterations,\n } = opts.opts ?? {};\n\n const raw = Buffer.from(message, inputEncoding);\n\n const version = raw[0];\n\n if (version !== CIPHERTEXT_VERSION) {\n throw getError({ message: `[AES][decrypt] Unsupported ciphertext version: ${version}` });\n }\n\n const idLength = raw[1];\n let cursor = 2;\n\n const id = raw.subarray(cursor, cursor + idLength).toString('utf-8');\n cursor += idLength;\n\n const iv = raw.subarray(cursor, cursor + DEFAULT_LENGTH);\n cursor += DEFAULT_LENGTH;\n\n const key = await this.resolveDecryptKey({ secret, id, kdfSalt, kdfIterations });\n\n let authTag: Uint8Array | null = null;\n\n if (this.algorithm === AESAlgorithms.AES_256_GCM) {\n authTag = raw.subarray(cursor, cursor + DEFAULT_LENGTH);\n cursor += DEFAULT_LENGTH;\n }\n\n const plain = await AesEngine.open({\n algorithm: this.algorithm,\n key,\n iv,\n cipherText: raw.subarray(cursor),\n authTag,\n });\n\n return Buffer.from(plain).toString(outputEncoding);\n }\n\n async decryptFile(opts: { absolutePath: string; secret: TAESSecret }): Promise<string> {\n const { absolutePath, secret } = opts;\n\n if (!absolutePath || ObjectUtility.isEmpty({ value: absolutePath })) {\n return '';\n }\n\n const buffer = fs.readFileSync(absolutePath);\n const fileContent = buffer?.toString('utf-8');\n\n return this.decrypt({ message: fileContent, secret });\n }\n}\n"]}
@@ -2,6 +2,18 @@ import { AbstractCryptoAlgorithm } from './abstract.algorithm.js';
2
2
  export { AbstractCryptoAlgorithm } from './abstract.algorithm.js';
3
3
  /** Base for the symmetric algorithms: validates the algorithm name and derives a key of a given length from a secret with PBKDF2. */
4
4
  export declare abstract class BaseCryptoAlgorithm<AlgorithmType extends string, EncryptInputType = unknown, DecryptInputType = unknown, SecretKeyType = unknown, EncryptReturnType = unknown, DecryptReturnType = unknown, ExtraOptions = unknown> extends AbstractCryptoAlgorithm<AlgorithmType, EncryptInputType, DecryptInputType, SecretKeyType, EncryptReturnType, DecryptReturnType, ExtraOptions> {
5
+ /** What a caller that still passes a removed option is told: the option, and what replaced it. */
6
+ private static readonly REMOVED_OPTION_HINTS;
7
+ /**
8
+ * A caller that still passes a removed option is refused, not ignored, so nobody believes it still works.
9
+ * `doThrow: false` is gone: a failed encrypt or decrypt used to hand the input back, which a caller could take for
10
+ * ciphertext or plaintext. `iv` is gone from AES: a caller-chosen IV reused under GCM breaks confidentiality and integrity.
11
+ */
12
+ protected assertNoRemovedOptions(opts: {
13
+ method: string;
14
+ options?: object;
15
+ removed?: ReadonlyArray<string>;
16
+ }): void;
5
17
  constructor(opts: {
6
18
  scope: string;
7
19
  algorithm: AlgorithmType;
@@ -19,8 +31,6 @@ export declare abstract class BaseCryptoAlgorithm<AlgorithmType extends string,
19
31
  kdfSalt?: string;
20
32
  kdfIterations?: number;
21
33
  }): Promise<Buffer>;
22
- /** Runs `derive` once per `cacheKey`. A failed derivation leaves nothing behind, so the next call tries again. */
23
- private deriveOnce;
24
34
  private derivePbkdf2;
25
35
  /** 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). */
26
36
  private validateKdfSalt;
@@ -2,14 +2,38 @@ import { getError } from '../../error/index.js';
2
2
  import { ParseUtility } from '../../../utilities/index.js';
3
3
  import { DEFAULT_CIPHER_BITS, DEFAULT_KDF_DIGEST, DEFAULT_KDF_ITERATIONS, DEFAULT_KDF_SALT, MINIMUM_KDF_SALT_BYTES, } from '../common/index.js';
4
4
  import { AbstractCryptoAlgorithm } from './abstract.algorithm.js';
5
+ import { DerivedKeyCache } from './derived-key-cache.js';
5
6
  export { AbstractCryptoAlgorithm } from './abstract.algorithm.js';
6
7
  const MAXIMUM_KDF_ITERATIONS = 2 ** 31 - 1;
7
8
  /** The Web Crypto name of each digest `DEFAULT_KDF_DIGEST` may hold. */
8
9
  const KDF_HASH_NAMES = { sha256: 'SHA-256' };
9
- /** One entry per derivation. It holds the promise, so callers that arrive while it runs share it. */
10
- const DERIVED_KEY_CACHE = new Map();
10
+ /** One entry per derivation, bounded. It holds the promise, so callers that arrive while it runs share it. */
11
+ const DERIVED_KEY_CACHE = new DerivedKeyCache();
11
12
  /** Base for the symmetric algorithms: validates the algorithm name and derives a key of a given length from a secret with PBKDF2. */
12
13
  export class BaseCryptoAlgorithm extends AbstractCryptoAlgorithm {
14
+ /** What a caller that still passes a removed option is told: the option, and what replaced it. */
15
+ static { this.REMOVED_OPTION_HINTS = {
16
+ doThrow: 'a failure always throws: catch the error where a fallback is wanted, and never treat the input as the result',
17
+ iv: 'every encryption draws a fresh random IV, and decrypt reads it from the ciphertext: a chosen IV is how a nonce is reused',
18
+ }; }
19
+ /**
20
+ * A caller that still passes a removed option is refused, not ignored, so nobody believes it still works.
21
+ * `doThrow: false` is gone: a failed encrypt or decrypt used to hand the input back, which a caller could take for
22
+ * ciphertext or plaintext. `iv` is gone from AES: a caller-chosen IV reused under GCM breaks confidentiality and integrity.
23
+ */
24
+ assertNoRemovedOptions(opts) {
25
+ const { method, options, removed = ['doThrow'] } = opts;
26
+ if (options === undefined || options === null) {
27
+ return;
28
+ }
29
+ for (const name of removed) {
30
+ if (name in options) {
31
+ throw getError({
32
+ message: `[${this.constructor.name}][${method}] The ${name} option was removed | ${BaseCryptoAlgorithm.REMOVED_OPTION_HINTS[name]}`,
33
+ });
34
+ }
35
+ }
36
+ }
13
37
  constructor(opts) {
14
38
  super({
15
39
  scope: opts.scope ?? opts.algorithm ?? BaseCryptoAlgorithm.name,
@@ -43,27 +67,13 @@ export class BaseCryptoAlgorithm extends AbstractCryptoAlgorithm {
43
67
  message: `[BaseCryptoAlgorithm][normalizeSecretKey] kdfIterations must be an integer from 1 to ${MAXIMUM_KDF_ITERATIONS}, got ${iterations}`,
44
68
  });
45
69
  }
46
- const cacheKey = `${DEFAULT_KDF_DIGEST}:${iterations}:${length}:${salt}:${secret}`;
47
- return this.deriveOnce({
48
- cacheKey,
49
- derive: () => this.derivePbkdf2({ secret, salt, iterations, length }),
70
+ const key = DerivedKeyCache.keyOf({
71
+ parts: [DEFAULT_KDF_DIGEST, iterations, length, salt, secret],
50
72
  });
51
- }
52
- /** Runs `derive` once per `cacheKey`. A failed derivation leaves nothing behind, so the next call tries again. */
53
- deriveOnce(opts) {
54
- const { cacheKey, derive } = opts;
55
- const pending = DERIVED_KEY_CACHE.get(cacheKey);
56
- if (pending) {
57
- return pending;
58
- }
59
- const derived = derive();
60
- DERIVED_KEY_CACHE.set(cacheKey, derived);
61
- derived.catch(() => {
62
- if (DERIVED_KEY_CACHE.get(cacheKey) === derived) {
63
- DERIVED_KEY_CACHE.delete(cacheKey);
64
- }
73
+ return DERIVED_KEY_CACHE.deriveOnce({
74
+ key,
75
+ derive: () => this.derivePbkdf2({ secret, salt, iterations, length }),
65
76
  });
66
- return derived;
67
77
  }
68
78
  async derivePbkdf2(opts) {
69
79
  const { secret, salt, iterations, length } = opts;