micro509 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +6 -6
  2. package/dist/index.d.ts +13 -14
  3. package/dist/index.js +1 -1
  4. package/dist/internal/crypto/pbes2.d.ts +6 -6
  5. package/dist/internal/crypto/pbes2.js +1 -1
  6. package/dist/internal/crypto/pbes2.js.map +1 -1
  7. package/dist/internal/verify/name-constraints-engine.js +1 -1
  8. package/dist/internal/verify/name-constraints-engine.js.map +1 -1
  9. package/dist/internal/x509/extension-bits.js.map +1 -1
  10. package/dist/keys/keys.d.ts +15 -15
  11. package/dist/keys/keys.js +1 -1
  12. package/dist/keys/keys.js.map +1 -1
  13. package/dist/keys.d.ts +2 -3
  14. package/dist/pem/pem.d.ts +57 -6
  15. package/dist/pem/pem.js +5 -5
  16. package/dist/pem/pem.js.map +1 -1
  17. package/dist/pem.d.ts +2 -2
  18. package/dist/pem.js +1 -1
  19. package/dist/pkcs/pfx.d.ts +4 -4
  20. package/dist/pkcs/pfx.js +1 -1
  21. package/dist/pkcs/pfx.js.map +1 -1
  22. package/dist/pkcs/pkcs12-mac.d.ts +29 -5
  23. package/dist/pkcs/pkcs12-mac.js +1 -1
  24. package/dist/pkcs/pkcs12-mac.js.map +1 -1
  25. package/dist/pkcs/pkcs7.d.ts +36 -50
  26. package/dist/pkcs/pkcs7.js +1 -1
  27. package/dist/pkcs/pkcs7.js.map +1 -1
  28. package/dist/pkcs.d.ts +3 -4
  29. package/dist/pkcs.js +1 -1
  30. package/dist/result/result.d.ts +3 -12
  31. package/dist/result/result.js.map +1 -1
  32. package/dist/result.d.ts +2 -2
  33. package/dist/result.js +1 -1
  34. package/dist/revocation/chain.d.ts +35 -34
  35. package/dist/revocation/chain.js +1 -1
  36. package/dist/revocation/chain.js.map +1 -1
  37. package/dist/revocation/crl.d.ts +40 -15
  38. package/dist/revocation/crl.js +1 -1
  39. package/dist/revocation/crl.js.map +1 -1
  40. package/dist/revocation/ocsp.d.ts +63 -13
  41. package/dist/revocation/ocsp.js +1 -1
  42. package/dist/revocation/ocsp.js.map +1 -1
  43. package/dist/revocation/revocation.d.ts +21 -19
  44. package/dist/revocation/revocation.js +1 -1
  45. package/dist/revocation/revocation.js.map +1 -1
  46. package/dist/revocation.d.ts +7 -5
  47. package/dist/revocation.js +1 -1
  48. package/dist/verify/identity.d.ts +4 -10
  49. package/dist/verify/identity.js +1 -1
  50. package/dist/verify/identity.js.map +1 -1
  51. package/dist/verify/verify.d.ts +9 -9
  52. package/dist/verify/verify.js +1 -1
  53. package/dist/verify/verify.js.map +1 -1
  54. package/dist/verify.d.ts +2 -2
  55. package/dist/x509/certificate.d.ts +2 -2
  56. package/dist/x509/certificate.js.map +1 -1
  57. package/dist/x509/csr.d.ts +2 -2
  58. package/dist/x509/csr.js.map +1 -1
  59. package/dist/x509/extensions.d.ts +21 -6
  60. package/dist/x509/extensions.js.map +1 -1
  61. package/dist/x509/parse.d.ts +3 -4
  62. package/dist/x509/parse.js +1 -1
  63. package/dist/x509/parse.js.map +1 -1
  64. package/dist/x509.d.ts +3 -4
  65. package/package.json +3 -1
  66. package/dist/internal/x509/extension-bits.d.ts +0 -18
@@ -29,12 +29,12 @@ interface ErrorResult<TCode extends string, TDetails, TError extends Micro509Err
29
29
  /** Human-readable diagnostic, mirrored from `error.message`. */
30
30
  readonly message: string;
31
31
  /** Optional structured context for the failure. */
32
- readonly details?: TDetails | undefined;
32
+ readonly details?: TDetails;
33
33
  }
34
34
  /** Like {@link ErrorResult} but also carries an index into the collection that was being processed. */
35
35
  interface IndexedErrorResult<TCode extends string, TDetails, TError extends IndexedMicro509Error<TCode, TDetails>> extends ErrorResult<TCode, TDetails, TError> {
36
36
  /** Zero-based position of the failing item in the input collection. */
37
- readonly index?: number | undefined;
37
+ readonly index?: number;
38
38
  }
39
39
  /** Base error shape carried by all failure results in the library. */
40
40
  interface Micro509Error<TCode extends string, TDetails = Record<never, never>> {
@@ -87,15 +87,6 @@ type UnwrappableResult<TValue, TError> = {
87
87
  declare function unwrap<TValue, TError extends Micro509Error<string, unknown>>(result: UnwrappableResult<TValue, TError>): TValue;
88
88
  /** Returns the success value, or `fallback` when the result is a failure. */
89
89
  declare function unwrapOr<TValue>(result: UnwrappableResult<TValue, unknown>, fallback: TValue): TValue;
90
- /**
91
- * Rethrows `error` if it is an invariant/programmer error (`TypeError`,
92
- * `RangeError`, `ReferenceError`, `SyntaxError`); otherwise returns.
93
- *
94
- * Boundary wrappers that turn an expected failure into a `Result` should call
95
- * this first, so a genuine crash is never masked as a clean parse/decode
96
- * failure (AGENTS.md: throw only for invariants).
97
- */
98
- declare function rethrowIfInvariant(error: unknown): void;
99
90
  /** Constructs a {@link Micro509Error} payload. */
100
91
  declare function micro509Error<TCode extends string, TDetails = Record<never, never>>(code: TCode, message: string, details?: TDetails): Micro509Error<TCode, TDetails>;
101
92
  /** Constructs an {@link IndexedMicro509Error} payload with an optional collection index. */
@@ -117,5 +108,5 @@ declare function failureResult<TCode extends string, TDetails = Record<never, ne
117
108
  /** Wraps an {@link IndexedMicro509Error} in a flattened {@link IndexedErrorResult}. */
118
109
  declare function indexedErrorResult<TCode extends string, TDetails, TError extends IndexedMicro509Error<TCode, TDetails>>(error: TError): IndexedErrorResult<TCode, TDetails, TError>;
119
110
  //#endregion
120
- export { ErrorResult, IndexedErrorResult, IndexedMicro509Error, Micro509Error, Result, ResultError, UnwrappableResult, errorResult, failureResult, indexedErrorResult, indexedMicro509Error, isResultError, micro509Error, rethrowIfInvariant, successResult, unwrap, unwrapOr };
111
+ export { ErrorResult, IndexedErrorResult, IndexedMicro509Error, Micro509Error, Result, ResultError, UnwrappableResult, errorResult, failureResult, indexedErrorResult, indexedMicro509Error, isResultError, micro509Error, successResult, unwrap, unwrapOr };
121
112
  //# sourceMappingURL=result.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"result.js","names":[],"sources":["../../src/result/result.ts"],"sourcesContent":["/**\n * Internal result helper types and constructors shared by low-level modules.\n *\n * Mirrors the public result model without depending on the public barrel.\n *\n * @module\n */\n\n/**\n * Discriminated `ok` union: either `{ ok: true; value }` or `{ ok: false; error }`.\n *\n * Every fallible public API in micro509 returns a specialization of this type.\n */\nexport type Result<TValue, TError> =\n\t| {\n\t\t\t/** Operation succeeded. */\n\t\t\treadonly ok: true;\n\t\t\t/** Successful payload. */\n\t\t\treadonly value: TValue;\n\t }\n\t| {\n\t\t\t/** Operation failed. */\n\t\t\treadonly ok: false;\n\t\t\t/** Structured error payload. */\n\t\t\treadonly error: TError;\n\t };\n\n/** Failed result with a flattened code/message/details surface for ergonomic matching. */\nexport interface ErrorResult<\n\tTCode extends string,\n\tTDetails,\n\tTError extends Micro509Error<TCode, TDetails>,\n> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n\t/** Structured error payload. */\n\treadonly error: TError;\n\t/** Machine-readable failure reason, mirrored from `error.code`. */\n\treadonly code: TCode;\n\t/** Human-readable diagnostic, mirrored from `error.message`. */\n\treadonly message: string;\n\t/** Optional structured context for the failure. */\n\treadonly details?: TDetails | undefined;\n}\n\n/** Like {@link ErrorResult} but also carries an index into the collection that was being processed. */\nexport interface IndexedErrorResult<\n\tTCode extends string,\n\tTDetails,\n\tTError extends IndexedMicro509Error<TCode, TDetails>,\n> extends ErrorResult<TCode, TDetails, TError> {\n\t/** Zero-based position of the failing item in the input collection. */\n\treadonly index?: number | undefined;\n}\n\n/** Base error shape carried by all failure results in the library. */\nexport interface Micro509Error<TCode extends string, TDetails = Record<never, never>> {\n\t/** Machine-readable failure reason (e.g. `'malformed'`, `'expired'`). */\n\treadonly code: TCode;\n\t/** Human-readable diagnostic message. */\n\treadonly message: string;\n\t/** Optional structured context for the failure. */\n\treadonly details?: TDetails;\n}\n\n/** Like {@link Micro509Error} but includes a positional index for collection-processing APIs. */\nexport interface IndexedMicro509Error<TCode extends string, TDetails = Record<never, never>>\n\textends Micro509Error<TCode, TDetails> {\n\t/** Zero-based position of the failing item in the input collection. */\n\treadonly index?: number;\n}\n\n/** Wraps a value in a success result (`{ ok: true, value }`). */\nexport function successResult<TValue>(value: TValue): {\n\treadonly ok: true;\n\treadonly value: TValue;\n} {\n\treturn { ok: true, value };\n}\n\n/**\n * Error thrown by {@link unwrap} when a result is a failure.\n *\n * Carries the structured {@link Micro509Error} payload so callers using the\n * throwing escape hatch still get the machine-readable `code` and any details.\n */\nexport interface ResultError<\n\tTError extends Micro509Error<string, unknown> = Micro509Error<string, unknown>,\n> extends Error {\n\t/** Machine-readable failure reason, mirrored from `error.code`. */\n\treadonly code: TError['code'];\n\t/** The structured error payload that produced this exception. */\n\treadonly error: TError;\n}\n\n/** Module-private brand so {@link isResultError} cannot be fooled by look-alike objects. */\nconst resultErrorBrand = Symbol('micro509.ResultError');\n\n/** Builds a {@link ResultError}: a branded `Error` (no class) carrying the structured failure. */\nfunction makeResultError<TError extends Micro509Error<string, unknown>>(\n\terror: TError,\n): ResultError<TError> {\n\treturn Object.assign(new Error(`${error.code}: ${error.message}`), {\n\t\tname: 'ResultError',\n\t\tcode: error.code,\n\t\terror,\n\t\t[resultErrorBrand]: true,\n\t});\n}\n\n/** Type guard: was `value` thrown by {@link unwrap}? Narrows to {@link ResultError}. */\nexport function isResultError(value: unknown): value is ResultError {\n\treturn value instanceof Error && resultErrorBrand in value;\n}\n\n/** A minimal fallible-result shape: `{ ok: true, value }` or `{ ok: false, error }`. */\nexport type UnwrappableResult<TValue, TError> =\n\t| { readonly ok: true; readonly value: TValue }\n\t| { readonly ok: false; readonly error: TError };\n\n/**\n * Explicit escape hatch: returns the success value, or throws a\n * {@link ResultError} carrying the structured failure.\n *\n * Use when you have already validated the input (or prefer exceptions) and the\n * Result ceremony is noise. Accepts any of the library's `*Result` types.\n */\nexport function unwrap<TValue, TError extends Micro509Error<string, unknown>>(\n\tresult: UnwrappableResult<TValue, TError>,\n): TValue {\n\tif (result.ok) {\n\t\treturn result.value;\n\t}\n\tthrow makeResultError(result.error);\n}\n\n/** Returns the success value, or `fallback` when the result is a failure. */\nexport function unwrapOr<TValue>(\n\tresult: UnwrappableResult<TValue, unknown>,\n\tfallback: TValue,\n): TValue {\n\treturn result.ok ? result.value : fallback;\n}\n\n/** JS error types that signal a programmer bug / broken invariant rather than malformed input. */\nconst invariantErrorTypes = [TypeError, RangeError, ReferenceError, SyntaxError] as const;\n\n/**\n * Rethrows `error` if it is an invariant/programmer error (`TypeError`,\n * `RangeError`, `ReferenceError`, `SyntaxError`); otherwise returns.\n *\n * Boundary wrappers that turn an expected failure into a `Result` should call\n * this first, so a genuine crash is never masked as a clean parse/decode\n * failure (AGENTS.md: throw only for invariants).\n */\nexport function rethrowIfInvariant(error: unknown): void {\n\tif (invariantErrorTypes.some((type) => error instanceof type)) {\n\t\tthrow error;\n\t}\n}\n\n/** Constructs a {@link Micro509Error} payload. */\nexport function micro509Error<TCode extends string, TDetails = Record<never, never>>(\n\tcode: TCode,\n\tmessage: string,\n\tdetails?: TDetails,\n): Micro509Error<TCode, TDetails> {\n\treturn {\n\t\tcode,\n\t\tmessage,\n\t\t...(details === undefined ? {} : { details }),\n\t};\n}\n\n/** Constructs an {@link IndexedMicro509Error} payload with an optional collection index. */\nexport function indexedMicro509Error<TCode extends string, TDetails = Record<never, never>>(\n\tcode: TCode,\n\tmessage: string,\n\tindex?: number,\n\tdetails?: TDetails,\n): IndexedMicro509Error<TCode, TDetails> {\n\treturn {\n\t\tcode,\n\t\tmessage,\n\t\t...(index === undefined ? {} : { index }),\n\t\t...(details === undefined ? {} : { details }),\n\t};\n}\n\n/** Wraps a {@link Micro509Error} in a flattened {@link ErrorResult}. */\nexport function errorResult<\n\tTCode extends string,\n\tTDetails,\n\tTError extends Micro509Error<TCode, TDetails>,\n>(error: TError): ErrorResult<TCode, TDetails, TError> {\n\treturn {\n\t\tok: false,\n\t\terror,\n\t\tcode: error.code,\n\t\tmessage: error.message,\n\t\t...(error.details === undefined ? {} : { details: error.details }),\n\t};\n}\n\n/**\n * Builds a flattened failure result in one step.\n *\n * Single source of truth for the `{ ok: false, error, code, message }` shape:\n * modules should construct failures with this instead of hand-rolling the\n * object literal. The `error` payload carries the redundant `ok: false`\n * discriminant so it matches the per-operation `*Failure` interfaces\n * (`interface XFailure extends Micro509Error<…> { ok: false }`).\n */\nexport function failureResult<TCode extends string, TDetails = Record<never, never>>(\n\tcode: TCode,\n\tmessage: string,\n\tdetails?: TDetails,\n): ErrorResult<TCode, TDetails, Micro509Error<TCode, TDetails> & { readonly ok: false }> {\n\treturn errorResult({ ok: false, ...micro509Error(code, message, details) });\n}\n\n/** Wraps an {@link IndexedMicro509Error} in a flattened {@link IndexedErrorResult}. */\nexport function indexedErrorResult<\n\tTCode extends string,\n\tTDetails,\n\tTError extends IndexedMicro509Error<TCode, TDetails>,\n>(error: TError): IndexedErrorResult<TCode, TDetails, TError> {\n\treturn {\n\t\tok: false,\n\t\terror,\n\t\tcode: error.code,\n\t\tmessage: error.message,\n\t\t...(error.details === undefined ? {} : { details: error.details }),\n\t\t...(error.index === undefined ? {} : { index: error.index }),\n\t};\n}\n"],"mappings":"AAyEA,SAAgB,EAAsB,EAGpC,CACD,MAAO,CAAE,GAAI,GAAM,OAAM,CAC1B,CAkBA,MAAM,EAAmB,OAAO,sBAAsB,EAGtD,SAAS,EACR,EACsB,CACtB,OAAO,OAAO,OAAW,MAAM,GAAG,EAAM,KAAK,IAAI,EAAM,SAAS,EAAG,CAClE,KAAM,cACN,KAAM,EAAM,KACZ,SACC,GAAmB,EACrB,CAAC,CACF,CAGA,SAAgB,EAAc,EAAsC,CACnE,OAAO,aAAiB,OAAS,KAAoB,CACtD,CAcA,SAAgB,EACf,EACS,CACT,GAAI,EAAO,GACV,OAAO,EAAO,MAEf,MAAM,EAAgB,EAAO,KAAK,CACnC,CAGA,SAAgB,EACf,EACA,EACS,CACT,OAAO,EAAO,GAAK,EAAO,MAAQ,CACnC,CAGA,MAAM,EAAsB,CAAC,UAAW,WAAY,eAAgB,WAAW,EAU/E,SAAgB,EAAmB,EAAsB,CACxD,GAAI,EAAoB,KAAM,GAAS,aAAiB,CAAI,EAC3D,MAAM,CAER,CAGA,SAAgB,EACf,EACA,EACA,EACiC,CACjC,MAAO,CACN,OACA,UACA,GAAI,IAAY,IAAA,GAAY,CAAC,EAAI,CAAE,SAAQ,CAC5C,CACD,CAGA,SAAgB,EACf,EACA,EACA,EACA,EACwC,CACxC,MAAO,CACN,OACA,UACA,GAAI,IAAU,IAAA,GAAY,CAAC,EAAI,CAAE,OAAM,EACvC,GAAI,IAAY,IAAA,GAAY,CAAC,EAAI,CAAE,SAAQ,CAC5C,CACD,CAGA,SAAgB,EAId,EAAqD,CACtD,MAAO,CACN,GAAI,GACJ,QACA,KAAM,EAAM,KACZ,QAAS,EAAM,QACf,GAAI,EAAM,UAAY,IAAA,GAAY,CAAC,EAAI,CAAE,QAAS,EAAM,OAAQ,CACjE,CACD,CAWA,SAAgB,EACf,EACA,EACA,EACwF,CACxF,OAAO,EAAY,CAAE,GAAI,GAAO,GAAG,EAAc,EAAM,EAAS,CAAO,CAAE,CAAC,CAC3E,CAGA,SAAgB,EAId,EAA4D,CAC7D,MAAO,CACN,GAAI,GACJ,QACA,KAAM,EAAM,KACZ,QAAS,EAAM,QACf,GAAI,EAAM,UAAY,IAAA,GAAY,CAAC,EAAI,CAAE,QAAS,EAAM,OAAQ,EAChE,GAAI,EAAM,QAAU,IAAA,GAAY,CAAC,EAAI,CAAE,MAAO,EAAM,KAAM,CAC3D,CACD"}
1
+ {"version":3,"file":"result.js","names":[],"sources":["../../src/result/result.ts"],"sourcesContent":["/**\n * Internal result helper types and constructors shared by low-level modules.\n *\n * Mirrors the public result model without depending on the public barrel.\n *\n * @module\n */\n\n/**\n * Discriminated `ok` union: either `{ ok: true; value }` or `{ ok: false; error }`.\n *\n * Every fallible public API in micro509 returns a specialization of this type.\n */\nexport type Result<TValue, TError> =\n\t| {\n\t\t\t/** Operation succeeded. */\n\t\t\treadonly ok: true;\n\t\t\t/** Successful payload. */\n\t\t\treadonly value: TValue;\n\t }\n\t| {\n\t\t\t/** Operation failed. */\n\t\t\treadonly ok: false;\n\t\t\t/** Structured error payload. */\n\t\t\treadonly error: TError;\n\t };\n\n/** Failed result with a flattened code/message/details surface for ergonomic matching. */\nexport interface ErrorResult<\n\tTCode extends string,\n\tTDetails,\n\tTError extends Micro509Error<TCode, TDetails>,\n> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n\t/** Structured error payload. */\n\treadonly error: TError;\n\t/** Machine-readable failure reason, mirrored from `error.code`. */\n\treadonly code: TCode;\n\t/** Human-readable diagnostic, mirrored from `error.message`. */\n\treadonly message: string;\n\t/** Optional structured context for the failure. */\n\treadonly details?: TDetails;\n}\n\n/** Like {@link ErrorResult} but also carries an index into the collection that was being processed. */\nexport interface IndexedErrorResult<\n\tTCode extends string,\n\tTDetails,\n\tTError extends IndexedMicro509Error<TCode, TDetails>,\n> extends ErrorResult<TCode, TDetails, TError> {\n\t/** Zero-based position of the failing item in the input collection. */\n\treadonly index?: number;\n}\n\n/** Base error shape carried by all failure results in the library. */\nexport interface Micro509Error<TCode extends string, TDetails = Record<never, never>> {\n\t/** Machine-readable failure reason (e.g. `'malformed'`, `'expired'`). */\n\treadonly code: TCode;\n\t/** Human-readable diagnostic message. */\n\treadonly message: string;\n\t/** Optional structured context for the failure. */\n\treadonly details?: TDetails;\n}\n\n/** Like {@link Micro509Error} but includes a positional index for collection-processing APIs. */\nexport interface IndexedMicro509Error<TCode extends string, TDetails = Record<never, never>>\n\textends Micro509Error<TCode, TDetails> {\n\t/** Zero-based position of the failing item in the input collection. */\n\treadonly index?: number;\n}\n\n/** Wraps a value in a success result (`{ ok: true, value }`). */\nexport function successResult<TValue>(value: TValue): {\n\treadonly ok: true;\n\treadonly value: TValue;\n} {\n\treturn { ok: true, value };\n}\n\n/**\n * Error thrown by {@link unwrap} when a result is a failure.\n *\n * Carries the structured {@link Micro509Error} payload so callers using the\n * throwing escape hatch still get the machine-readable `code` and any details.\n */\nexport interface ResultError<\n\tTError extends Micro509Error<string, unknown> = Micro509Error<string, unknown>,\n> extends Error {\n\t/** Machine-readable failure reason, mirrored from `error.code`. */\n\treadonly code: TError['code'];\n\t/** The structured error payload that produced this exception. */\n\treadonly error: TError;\n}\n\n/** Module-private brand so {@link isResultError} cannot be fooled by look-alike objects. */\nconst resultErrorBrand = Symbol('micro509.ResultError');\n\n/** Builds a {@link ResultError}: a branded `Error` (no class) carrying the structured failure. */\nfunction makeResultError<TError extends Micro509Error<string, unknown>>(\n\terror: TError,\n): ResultError<TError> {\n\treturn Object.assign(new Error(`${error.code}: ${error.message}`), {\n\t\tname: 'ResultError',\n\t\tcode: error.code,\n\t\terror,\n\t\t[resultErrorBrand]: true,\n\t});\n}\n\n/** Type guard: was `value` thrown by {@link unwrap}? Narrows to {@link ResultError}. */\nexport function isResultError(value: unknown): value is ResultError {\n\treturn value instanceof Error && resultErrorBrand in value;\n}\n\n/** A minimal fallible-result shape: `{ ok: true, value }` or `{ ok: false, error }`. */\nexport type UnwrappableResult<TValue, TError> =\n\t| { readonly ok: true; readonly value: TValue }\n\t| { readonly ok: false; readonly error: TError };\n\n/**\n * Explicit escape hatch: returns the success value, or throws a\n * {@link ResultError} carrying the structured failure.\n *\n * Use when you have already validated the input (or prefer exceptions) and the\n * Result ceremony is noise. Accepts any of the library's `*Result` types.\n */\nexport function unwrap<TValue, TError extends Micro509Error<string, unknown>>(\n\tresult: UnwrappableResult<TValue, TError>,\n): TValue {\n\tif (result.ok) {\n\t\treturn result.value;\n\t}\n\tthrow makeResultError(result.error);\n}\n\n/** Returns the success value, or `fallback` when the result is a failure. */\nexport function unwrapOr<TValue>(\n\tresult: UnwrappableResult<TValue, unknown>,\n\tfallback: TValue,\n): TValue {\n\treturn result.ok ? result.value : fallback;\n}\n\n/** JS error types that signal a programmer bug / broken invariant rather than malformed input. */\nconst invariantErrorTypes = [TypeError, RangeError, ReferenceError, SyntaxError] as const;\n\n/**\n * Rethrows `error` if it is an invariant/programmer error (`TypeError`,\n * `RangeError`, `ReferenceError`, `SyntaxError`); otherwise returns.\n *\n * Boundary wrappers that turn an expected failure into a `Result` should call\n * this first, so a genuine crash is never masked as a clean parse/decode\n * failure (AGENTS.md: throw only for invariants).\n */\nexport function rethrowIfInvariant(error: unknown): void {\n\tif (invariantErrorTypes.some((type) => error instanceof type)) {\n\t\tthrow error;\n\t}\n}\n\n/** Constructs a {@link Micro509Error} payload. */\nexport function micro509Error<TCode extends string, TDetails = Record<never, never>>(\n\tcode: TCode,\n\tmessage: string,\n\tdetails?: TDetails,\n): Micro509Error<TCode, TDetails> {\n\treturn {\n\t\tcode,\n\t\tmessage,\n\t\t...(details === undefined ? {} : { details }),\n\t};\n}\n\n/** Constructs an {@link IndexedMicro509Error} payload with an optional collection index. */\nexport function indexedMicro509Error<TCode extends string, TDetails = Record<never, never>>(\n\tcode: TCode,\n\tmessage: string,\n\tindex?: number,\n\tdetails?: TDetails,\n): IndexedMicro509Error<TCode, TDetails> {\n\treturn {\n\t\tcode,\n\t\tmessage,\n\t\t...(index === undefined ? {} : { index }),\n\t\t...(details === undefined ? {} : { details }),\n\t};\n}\n\n/** Wraps a {@link Micro509Error} in a flattened {@link ErrorResult}. */\nexport function errorResult<\n\tTCode extends string,\n\tTDetails,\n\tTError extends Micro509Error<TCode, TDetails>,\n>(error: TError): ErrorResult<TCode, TDetails, TError> {\n\treturn {\n\t\tok: false,\n\t\terror,\n\t\tcode: error.code,\n\t\tmessage: error.message,\n\t\t...(error.details === undefined ? {} : { details: error.details }),\n\t};\n}\n\n/**\n * Builds a flattened failure result in one step.\n *\n * Single source of truth for the `{ ok: false, error, code, message }` shape:\n * modules should construct failures with this instead of hand-rolling the\n * object literal. The `error` payload carries the redundant `ok: false`\n * discriminant so it matches the per-operation `*Failure` interfaces\n * (`interface XFailure extends Micro509Error<…> { ok: false }`).\n */\nexport function failureResult<TCode extends string, TDetails = Record<never, never>>(\n\tcode: TCode,\n\tmessage: string,\n\tdetails?: TDetails,\n): ErrorResult<TCode, TDetails, Micro509Error<TCode, TDetails> & { readonly ok: false }> {\n\treturn errorResult({ ok: false, ...micro509Error(code, message, details) });\n}\n\n/** Wraps an {@link IndexedMicro509Error} in a flattened {@link IndexedErrorResult}. */\nexport function indexedErrorResult<\n\tTCode extends string,\n\tTDetails,\n\tTError extends IndexedMicro509Error<TCode, TDetails>,\n>(error: TError): IndexedErrorResult<TCode, TDetails, TError> {\n\treturn {\n\t\tok: false,\n\t\terror,\n\t\tcode: error.code,\n\t\tmessage: error.message,\n\t\t...(error.details === undefined ? {} : { details: error.details }),\n\t\t...(error.index === undefined ? {} : { index: error.index }),\n\t};\n}\n"],"mappings":"AAyEA,SAAgB,EAAsB,EAGpC,CACD,MAAO,CAAE,GAAI,GAAM,OAAM,CAC1B,CAkBA,MAAM,EAAmB,OAAO,sBAAsB,EAGtD,SAAS,EACR,EACsB,CACtB,OAAO,OAAO,OAAW,MAAM,GAAG,EAAM,KAAK,IAAI,EAAM,SAAS,EAAG,CAClE,KAAM,cACN,KAAM,EAAM,KACZ,SACC,GAAmB,EACrB,CAAC,CACF,CAGA,SAAgB,EAAc,EAAsC,CACnE,OAAO,aAAiB,OAAS,KAAoB,CACtD,CAcA,SAAgB,EACf,EACS,CACT,GAAI,EAAO,GACV,OAAO,EAAO,MAEf,MAAM,EAAgB,EAAO,KAAK,CACnC,CAGA,SAAgB,EACf,EACA,EACS,CACT,OAAO,EAAO,GAAK,EAAO,MAAQ,CACnC,CAGA,MAAM,EAAsB,CAAC,UAAW,WAAY,eAAgB,WAAW,EAU/E,SAAgB,EAAmB,EAAsB,CACxD,GAAI,EAAoB,KAAM,GAAS,aAAiB,CAAI,EAC3D,MAAM,CAER,CAGA,SAAgB,EACf,EACA,EACA,EACiC,CACjC,MAAO,CACN,OACA,UACA,GAAI,IAAY,IAAA,GAAY,CAAC,EAAI,CAAE,SAAQ,CAC5C,CACD,CAGA,SAAgB,EACf,EACA,EACA,EACA,EACwC,CACxC,MAAO,CACN,OACA,UACA,GAAI,IAAU,IAAA,GAAY,CAAC,EAAI,CAAE,OAAM,EACvC,GAAI,IAAY,IAAA,GAAY,CAAC,EAAI,CAAE,SAAQ,CAC5C,CACD,CAGA,SAAgB,EAId,EAAqD,CACtD,MAAO,CACN,GAAI,GACJ,QACA,KAAM,EAAM,KACZ,QAAS,EAAM,QACf,GAAI,EAAM,UAAY,IAAA,GAAY,CAAC,EAAI,CAAE,QAAS,EAAM,OAAQ,CACjE,CACD,CAWA,SAAgB,EACf,EACA,EACA,EACwF,CACxF,OAAO,EAAY,CAAE,GAAI,GAAO,GAAG,EAAc,EAAM,EAAS,CAAO,CAAE,CAAC,CAC3E,CAGA,SAAgB,EAId,EAA4D,CAC7D,MAAO,CACN,GAAI,GACJ,QACA,KAAM,EAAM,KACZ,QAAS,EAAM,QACf,GAAI,EAAM,UAAY,IAAA,GAAY,CAAC,EAAI,CAAE,QAAS,EAAM,OAAQ,EAChE,GAAI,EAAM,QAAU,IAAA,GAAY,CAAC,EAAI,CAAE,MAAO,EAAM,KAAM,CAC3D,CACD"}
package/dist/result.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { ErrorResult, IndexedErrorResult, IndexedMicro509Error, Micro509Error, Result, ResultError, UnwrappableResult, errorResult, failureResult, indexedErrorResult, indexedMicro509Error, isResultError, micro509Error, rethrowIfInvariant, successResult, unwrap, unwrapOr } from "./result/result.js";
2
- export { type ErrorResult, type IndexedErrorResult, type IndexedMicro509Error, type Micro509Error, type Result, type ResultError, type UnwrappableResult, errorResult, failureResult, indexedErrorResult, indexedMicro509Error, isResultError, micro509Error, rethrowIfInvariant, successResult, unwrap, unwrapOr };
1
+ import { ErrorResult, IndexedErrorResult, IndexedMicro509Error, Micro509Error, Result, ResultError, UnwrappableResult, errorResult, failureResult, indexedErrorResult, indexedMicro509Error, isResultError, micro509Error, successResult, unwrap, unwrapOr } from "./result/result.js";
2
+ export { type ErrorResult, type IndexedErrorResult, type IndexedMicro509Error, type Micro509Error, type Result, type ResultError, type UnwrappableResult, errorResult, failureResult, indexedErrorResult, indexedMicro509Error, isResultError, micro509Error, successResult, unwrap, unwrapOr };
package/dist/result.js CHANGED
@@ -1 +1 @@
1
- import{errorResult as e,failureResult as t,indexedErrorResult as n,indexedMicro509Error as r,isResultError as i,micro509Error as a,rethrowIfInvariant as o,successResult as s,unwrap as c,unwrapOr as l}from"./result/result.js";export{e as errorResult,t as failureResult,n as indexedErrorResult,r as indexedMicro509Error,i as isResultError,a as micro509Error,o as rethrowIfInvariant,s as successResult,c as unwrap,l as unwrapOr};
1
+ import{errorResult as e,failureResult as t,indexedErrorResult as n,indexedMicro509Error as r,isResultError as i,micro509Error as a,successResult as o,unwrap as s,unwrapOr as c}from"./result/result.js";export{e as errorResult,t as failureResult,n as indexedErrorResult,r as indexedMicro509Error,i as isResultError,a as micro509Error,o as successResult,s as unwrap,c as unwrapOr};
@@ -1,16 +1,10 @@
1
1
  import { ParsedCertificate } from "../x509/parse.js";
2
2
  import { CrlSource, RevocationReason } from "./crl.js";
3
3
  import { OcspResponderRevocationPolicy } from "./ocsp.js";
4
+ import { RevocationCertificateSource } from "./revocation.js";
4
5
 
5
6
  //#region src/revocation/chain.d.ts
6
7
  /**
7
- * Certificate in any supported format.
8
- *
9
- * Accepts PEM string, DER bytes, or an already-parsed {@linkcode ParsedCertificate}.
10
- * Used for {@linkcode CheckChainRevocationInput.extraCertificates}.
11
- */
12
- type CertificateSource = string | Uint8Array | ParsedCertificate;
13
- /**
14
8
  * OCSP response in any supported format.
15
9
  *
16
10
  * Accepts PEM string or DER bytes. Used for
@@ -27,8 +21,12 @@ interface RevocationPolicy {
27
21
  /**
28
22
  * How to handle indeterminate status.
29
23
  *
30
- * - `'soft-fail'`: indeterminate certificates are allowed (default)
31
- * - `'hard-fail'`: indeterminate certificates cause denial
24
+ * - `'hard-fail'`: indeterminate certificates cause denial (default)
25
+ * - `'soft-fail'`: indeterminate certificates are allowed — an explicit
26
+ * availability/compatibility choice
27
+ *
28
+ * Revocation checking itself is opt-in: no check runs unless evidence is
29
+ * supplied. Once it is, indeterminate status denies by default.
32
30
  */
33
31
  readonly mode?: "soft-fail" | "hard-fail";
34
32
  /**
@@ -62,13 +60,13 @@ interface CheckChainRevocationInput {
62
60
  /** OCSP responses to evaluate. */
63
61
  readonly ocspResponses?: readonly OcspResponseSource[];
64
62
  /** Extra certs for indirect CRL issuers / delegated OCSP responders. */
65
- readonly extraCertificates?: readonly CertificateSource[];
63
+ readonly extraCertificates?: readonly RevocationCertificateSource[];
66
64
  /**
67
65
  * Explicitly trusted OCSP responder certificates (RFC 6960 §4.2.2.2
68
66
  * criterion 1). A response signed by one of these is accepted without
69
67
  * delegated-responder issuance, EKU, and revocation checks.
70
68
  */
71
- readonly trustedOcspResponders?: readonly CertificateSource[];
69
+ readonly trustedOcspResponders?: readonly RevocationCertificateSource[];
72
70
  /** Evaluation time. Defaults to `new Date()`. */
73
71
  readonly at?: Date;
74
72
  /** Revocation policy. */
@@ -87,7 +85,9 @@ interface CheckChainRevocationInput {
87
85
  * `crl_signer_revoked`, `crl_signer_indeterminate`, and OCSP equivalents
88
86
  * - **Freshness**: `crl_expired`, `ocsp_response_expired`
89
87
  */
90
- type RevocationIndeterminateReason = "no_applicable_crl" | "no_applicable_ocsp" | "distribution_point_mismatch" | "issuer_name_mismatch" | "reason_scope_mismatch" | "indirect_crl_scope_mismatch" | "reason_coverage_incomplete" | "crl_signer_not_found" | "crl_signer_not_authorized" | "crl_signer_revoked" | "crl_signer_indeterminate" | "ocsp_responder_not_found" | "ocsp_responder_not_authorized" | "ocsp_responder_revoked" | "ocsp_responder_indeterminate" | "crl_expired" | "ocsp_response_expired" | "ocsp_status_unknown";
88
+ declare const REVOCATION_INDETERMINATE_REASONS: readonly ["no_applicable_crl", "no_applicable_ocsp", "distribution_point_mismatch", "issuer_name_mismatch", "reason_scope_mismatch", "indirect_crl_scope_mismatch", "reason_coverage_incomplete", "crl_signer_not_found", "crl_signer_not_authorized", "crl_signer_revoked", "crl_signer_indeterminate", "ocsp_responder_not_found", "ocsp_responder_not_authorized", "ocsp_responder_revoked", "ocsp_responder_indeterminate", "crl_expired", "ocsp_response_expired", "ocsp_status_unknown"];
89
+ /** See the doc comment above {@linkcode REVOCATION_INDETERMINATE_REASONS}. */
90
+ type RevocationIndeterminateReason = (typeof REVOCATION_INDETERMINATE_REASONS)[number];
91
91
  /**
92
92
  * Identifies the source of revocation evidence.
93
93
  *
@@ -96,7 +96,7 @@ type RevocationIndeterminateReason = "no_applicable_crl" | "no_applicable_ocsp"
96
96
  */
97
97
  interface RevocationSource {
98
98
  /** Whether evidence came from a CRL or OCSP response. */
99
- readonly type: "crl" | "ocsp";
99
+ readonly kind: "crl" | "ocsp";
100
100
  /** Certificate that signed the evidence (CRL issuer or OCSP responder). */
101
101
  readonly signerCertificate?: ParsedCertificate;
102
102
  /** Identifier for debugging (e.g., CRL issuer DN or OCSP responder URL). */
@@ -114,27 +114,28 @@ interface RevocationSource {
114
114
  * One entry per certificate in {@linkcode CheckChainRevocationValue.certificates}.
115
115
  * The trust anchor is excluded (never checked for revocation).
116
116
  */
117
- interface CertificateRevocationStatus {
118
- /** The certificate that was evaluated. */
119
- readonly certificate: ParsedCertificate;
120
- /**
121
- * Revocation status determination.
122
- *
123
- * - `'good'`: evidence confirms certificate is not revoked
124
- * - `'revoked'`: evidence confirms certificate is revoked
125
- * - `'indeterminate'`: could not determine status (see {@linkcode indeterminateReasons})
126
- */
127
- readonly status: "good" | "revoked" | "indeterminate";
128
- /** Evidence source when status is `'good'` or `'revoked'`. */
129
- readonly source?: RevocationSource;
130
- /** Why status could not be determined. Present when `status` is `'indeterminate'`. */
131
- readonly indeterminateReasons?: readonly RevocationIndeterminateReason[];
132
- /** Revocation details. Present when `status` is `'revoked'`. */
133
- readonly revocationInfo?: {
134
- /** When the certificate was revoked. */readonly date: Date; /** RFC 5280 CRLReason code, if provided by the CRL/OCSP response. */
117
+ type CertificateRevocationStatus = {
118
+ /** The certificate that was evaluated. */readonly certificate: ParsedCertificate; /** Evidence confirms the certificate is not revoked. */
119
+ readonly status: "good"; /** Evidence that produced the verdict. */
120
+ readonly source: RevocationSource; /** Never present on a `good` verdict. */
121
+ readonly indeterminateReasons?: undefined; /** Never present on a `good` verdict. */
122
+ readonly revocationInfo?: undefined;
123
+ } | {
124
+ /** The certificate that was evaluated. */readonly certificate: ParsedCertificate; /** Evidence confirms the certificate is revoked. */
125
+ readonly status: "revoked"; /** Evidence that produced the verdict. */
126
+ readonly source: RevocationSource; /** Revocation details from the CRL entry or OCSP response. */
127
+ readonly revocationInfo: {
128
+ /** When the certificate was revoked. */readonly revocationDate: Date; /** RFC 5280 CRLReason code, if provided by the CRL/OCSP response. */
135
129
  readonly reason?: RevocationReason;
136
- };
137
- }
130
+ }; /** Never present on a `revoked` verdict. */
131
+ readonly indeterminateReasons?: undefined;
132
+ } | {
133
+ /** The certificate that was evaluated. */readonly certificate: ParsedCertificate; /** Revocation status could not be determined. */
134
+ readonly status: "indeterminate"; /** Why status could not be determined. */
135
+ readonly indeterminateReasons: readonly RevocationIndeterminateReason[]; /** Never present on an `indeterminate` verdict. */
136
+ readonly source?: undefined; /** Never present on an `indeterminate` verdict. */
137
+ readonly revocationInfo?: undefined;
138
+ };
138
139
  /**
139
140
  * Errors encountered while processing revocation evidence.
140
141
  *
@@ -203,5 +204,5 @@ type CheckChainRevocationResult = {
203
204
  */
204
205
  declare function checkChainRevocation(input: CheckChainRevocationInput): Promise<CheckChainRevocationResult>;
205
206
  //#endregion
206
- export { CertificateRevocationStatus, CertificateSource, CheckChainRevocationInput, CheckChainRevocationResult, CheckChainRevocationValue, type CrlSource, OcspResponseSource, RevocationExecutionError, RevocationIndeterminateReason, RevocationPolicy, RevocationSource, checkChainRevocation };
207
+ export { CertificateRevocationStatus, CheckChainRevocationInput, CheckChainRevocationResult, CheckChainRevocationValue, type CrlSource, OcspResponseSource, REVOCATION_INDETERMINATE_REASONS, RevocationExecutionError, RevocationIndeterminateReason, RevocationPolicy, RevocationSource, checkChainRevocation };
207
208
  //# sourceMappingURL=chain.d.ts.map
@@ -1,2 +1,2 @@
1
- import{parseCertificateFromSource as e}from"../x509/parse.js";import{checkCertificateRevocationAgainstCrl as t,parseCertificateRevocationListDer as n,parseCertificateRevocationListPem as r,revocationReasonFromCode as i}from"./crl.js";import{parseOcspResponseDer as a,parseOcspResponsePem as o,validateOcspResponse as s}from"./ocsp.js";function c(e){return typeof e==`object`&&`issuer`in e?e:typeof e==`string`?r(e):n(e)}function l(t){try{return e(t)}catch{return}}function u(e,t){if(e.der.length!==t.der.length)return!1;for(let n=0;n<e.der.length;n++)if(e.der[n]!==t.der[n])return!1;return!0}function d(e,t,n){let r=[];for(let e of t){let t=l(e);t!==void 0&&r.push(t)}let i=[...r,...n];if(e.authorityKeyIdentifier!==void 0){for(let t of i)if(t.subjectKeyIdentifier!==void 0&&f(e.authorityKeyIdentifier)===f(t.subjectKeyIdentifier))return t}for(let t of i)if(e.issuer.derHex===t.subject.derHex)return t}function f(e){return e.toLowerCase()}function p(e){return`${e.issuer.derHex}:${e.serialNumberHex}`}async function m(e,t){let n=p(e),r=t.cache.get(n);if(r===`visiting`)return`resolved-indeterminate`;if(r!==void 0)return r;t.cache.set(n,`visiting`);let i=t.chain[t.chain.length-1];if(i!==void 0&&u(e,i)||t.chain.some(t=>u(t,e)))return t.cache.set(n,`resolved-valid`),`resolved-valid`;let a=h(e,t);if(a===void 0)return t.cache.set(n,`resolved-indeterminate`),`resolved-indeterminate`;let o=await g(e,a,t);return t.cache.set(n,o),o}function h(e,t){let n=[];for(let e of t.extraCertificates){let t=l(e);t!==void 0&&n.push(t)}let r=[...t.chain,...n];for(let t of r)if(e.authorityKeyIdentifier!==void 0&&t.subjectKeyIdentifier!==void 0&&f(e.authorityKeyIdentifier)===f(t.subjectKeyIdentifier)||e.issuer.derHex===t.subject.derHex)return t}async function g(e,n,r){let i=r.chain.some(e=>u(e,n));for(let i of r.crls){let a;try{a=c(i)}catch{continue}let o=await t({certificate:e,issuerCertificate:n,crl:a,at:r.at});if(o.ok){if(o.value.status===`revoked`)return`resolved-revoked`;if(o.value.status===`good`&&await m(n,r)===`resolved-valid`)return`resolved-valid`}}return i?`resolved-valid`:`resolved-indeterminate`}function _(e,t,n,r,i,a){return n===`revoked`&&i!==void 0?{certificate:e,status:`revoked`,source:{type:`crl`,signerCertificate:t,thisUpdate:r},revocationInfo:{date:i,...a===void 0?{}:{reason:a}}}:{certificate:e,status:`good`,source:{type:`crl`,signerCertificate:t,thisUpdate:r}}}function v(e){return typeof e==`string`?o(e):a(e)}function y(e){switch(e){case`stale_response`:return`ocsp_response_expired`;case`responder_id_mismatch`:case`responder_chain_invalid`:case`ocsp_signing_missing`:return`ocsp_responder_not_authorized`;case`responder_revoked`:return`ocsp_responder_revoked`;case`signature_invalid`:case`responder_revocation_unknown`:return`ocsp_responder_indeterminate`;case`response_status_invalid`:case`issuer_mismatch`:case`nonce_mismatch`:case`request_mismatch`:return`no_applicable_ocsp`}}const b=new Set([`signature_invalid`,`responder_id_mismatch`,`responder_chain_invalid`,`ocsp_signing_missing`]);async function x(e,t,n,r){let i={issuerCertificate:t,at:r,...n.trustedOcspResponders===void 0?{}:{trustedResponderCertificates:n.trustedOcspResponders},...n.policy?.ocspResponderRevocation===void 0?{}:{responderRevocationPolicy:n.policy.ocspResponderRevocation},...n.crls===void 0?{}:{responderRevocationCrls:n.crls}},a=await s({response:e,...i});if(a.ok||!b.has(a.code))return a;for(let t of n.extraCertificates??[]){let n=l(t);if(n===void 0)continue;let r=await s({response:e,...i,responderCertificate:n});if(r.ok)return r}return a}async function S(e,t,n){let{ocspResponses:r=[],at:a=new Date}=n,o=[],s=new Set;for(let c of r){let r;try{r=v(c)}catch(e){o.push({kind:`parse_error`,message:e instanceof Error?e.message:`OCSP response parse failed`});continue}let l=(r.responses??[]).find(t=>f(t.certId.serialNumberHex)===f(e.serialNumberHex));if(l===void 0)continue;let u=await x(r,t,n,a);if(!u.ok){s.add(y(u.code));continue}if(l.certStatus===`revoked`){let t=i(l.revocationReasonCode);return{status:{certificate:e,status:`revoked`,source:{type:`ocsp`,thisUpdate:l.thisUpdate},revocationInfo:{date:l.revokedAt??l.thisUpdate,...t===void 0?{}:{reason:t}}},executionErrors:o}}if(l.certStatus===`good`)return{status:{certificate:e,status:`good`,source:{type:`ocsp`,thisUpdate:l.thisUpdate}},executionErrors:o};s.add(`ocsp_status_unknown`)}return s.size===0&&s.add(`no_applicable_ocsp`),{status:{certificate:e,status:`indeterminate`,indeterminateReasons:[...s]},executionErrors:o}}const C=[`keyCompromise`,`cACompromise`,`affiliationChanged`,`superseded`,`cessationOfOperation`,`certificateHold`,`privilegeWithdrawn`,`aACompromise`];async function w(e,n,r,i){let{crls:a=[],extraCertificates:o=[],chain:s=[],at:l=new Date}=r,f=[],p=!1,h=!1,g=!1,v,y=new Set,b=[];for(let e of a)try{b.push(c(e))}catch(e){f.push({kind:`parse_error`,message:e instanceof Error?e.message:`CRL parse failed`})}let x=b.filter(e=>e.baseCrlNumber===void 0),S=b.filter(e=>e.baseCrlNumber!==void 0),w=async(n,r,i)=>t({certificate:e,issuerCertificate:i,crl:n,...r===void 0?{}:{deltaCrl:r},at:l});for(let t of x){let r=S.find(e=>e.issuer.derHex===t.issuer.derHex&&e.baseCrlNumber!==void 0&&t.crlNumber!==void 0&&BigInt(e.baseCrlNumber)<=BigInt(t.crlNumber)),a=await w(t,r,n),c=n;if(!a.ok){let e=d(t,o,s);e!==void 0&&!u(e,n)&&(a=await w(t,r,e),c=e)}if(!a.ok)continue;let l=await m(c,i);if(l===`resolved-revoked`){p=!0;continue}if(l===`resolved-indeterminate`){h=!0;continue}let b=r!==void 0&&r.thisUpdate.getTime()>t.thisUpdate.getTime()?r.thisUpdate:t.thisUpdate;if(a.value.status===`revoked`)return{status:_(e,c,`revoked`,b,a.value.revocationDate,a.value.reasonCode),executionErrors:f};g=!0,(v===void 0||b.getTime()>v.thisUpdate.getTime())&&(v={signer:c,thisUpdate:b});let x=t.issuingDistributionPoint?.onlySomeReasons?.flags;if(x===void 0)for(let e of C)y.add(e);else for(let e of x)y.add(e)}if(g)return C.every(e=>y.has(e))?{status:{certificate:e,status:`good`,...v===void 0?{}:{source:{type:`crl`,signerCertificate:v.signer,thisUpdate:v.thisUpdate}}},executionErrors:f}:{status:{certificate:e,status:`indeterminate`,indeterminateReasons:[`reason_coverage_incomplete`]},executionErrors:f};let T=[];return p?T.push(`crl_signer_revoked`):h?T.push(`crl_signer_indeterminate`):T.push(`no_applicable_crl`),{status:{certificate:e,status:`indeterminate`,indeterminateReasons:T},executionErrors:f}}async function T(e,t,n,r){let i=n.policy?.prefer??`best-available`,a=await S(e,t,n),o=await w(e,t,n,r),s=[...a.executionErrors,...o.executionErrors],c=i===`crl`?[o,a]:i===`ocsp`?[a,o]:[a,o].sort((e,t)=>(t.status.source?.thisUpdate?.getTime()??0)-(e.status.source?.thisUpdate?.getTime()??0)),l=c.find(e=>e.status.status===`revoked`);if(l!==void 0)return{status:l.status,executionErrors:s};let u=c.find(e=>e.status.status===`good`);if(u!==void 0)return{status:u.status,executionErrors:s};let d=new Set;for(let e of c)for(let t of e.status.indeterminateReasons??[])d.add(t);return{status:{certificate:e,status:`indeterminate`,indeterminateReasons:[...d]},executionErrors:s}}async function E(e){let{chain:t,policy:n,crls:r=[],extraCertificates:i=[],at:a=new Date}=e,o=n?.mode??`soft-fail`;if(t.length===0)return{ok:!0,value:{decision:`allow`,summary:{revokedCertificates:[],indeterminateCertificates:[]},certificates:[]}};let s={cache:new Map,chain:t,crls:r,extraCertificates:i,at:a},c=t.slice(0,-1),l=[],u=[],d=[],f=[];for(let n=0;n<c.length;n++){let r=c[n],i=t[n+1];if(r===void 0||i===void 0)continue;let{status:a,executionErrors:o}=await T(r,i,e,s);l.push(a),f.push(...o),a.status===`revoked`?u.push(r):a.status===`indeterminate`&&d.push(r)}let p=u.length>0,m=d.length>0;return{ok:!0,value:{decision:p||m&&o===`hard-fail`?`deny`:`allow`,summary:{revokedCertificates:u,indeterminateCertificates:d},certificates:l,...f.length>0?{executionErrors:f}:{}}}}export{E as checkChainRevocation};
1
+ import{parseCertificateFromSource as e}from"../x509/parse.js";import{checkCertificateRevocationAgainstCrl as t,parseCertificateRevocationListDerOrThrow as n,parseCertificateRevocationListPemOrThrow as r,revocationReasonFromCode as i}from"./crl.js";import{parseOcspResponseDerOrThrow as a,parseOcspResponsePemOrThrow as o,validateOcspResponse as s}from"./ocsp.js";const c=[`no_applicable_crl`,`no_applicable_ocsp`,`distribution_point_mismatch`,`issuer_name_mismatch`,`reason_scope_mismatch`,`indirect_crl_scope_mismatch`,`reason_coverage_incomplete`,`crl_signer_not_found`,`crl_signer_not_authorized`,`crl_signer_revoked`,`crl_signer_indeterminate`,`ocsp_responder_not_found`,`ocsp_responder_not_authorized`,`ocsp_responder_revoked`,`ocsp_responder_indeterminate`,`crl_expired`,`ocsp_response_expired`,`ocsp_status_unknown`];function l(e){return typeof e==`object`&&`issuer`in e?e:typeof e==`string`?r(e):n(e)}function u(t){try{return e(t)}catch{return}}function d(e,t){if(e.der.length!==t.der.length)return!1;for(let n=0;n<e.der.length;n++)if(e.der[n]!==t.der[n])return!1;return!0}function f(e,t,n){let r=[];for(let e of t){let t=u(e);t!==void 0&&r.push(t)}let i=[...r,...n];if(e.authorityKeyIdentifier!==void 0){for(let t of i)if(t.subjectKeyIdentifier!==void 0&&p(e.authorityKeyIdentifier)===p(t.subjectKeyIdentifier))return t}for(let t of i)if(e.issuer.derHex===t.subject.derHex)return t}function p(e){return e.toLowerCase()}function m(e){return`${e.issuer.derHex}:${e.serialNumberHex}`}async function h(e,t){let n=m(e),r=t.cache.get(n);if(r===`visiting`)return`resolved-indeterminate`;if(r!==void 0)return r;t.cache.set(n,`visiting`);let i=t.chain[t.chain.length-1];if(i!==void 0&&d(e,i)||t.chain.some(t=>d(t,e)))return t.cache.set(n,`resolved-valid`),`resolved-valid`;let a=g(e,t);if(a===void 0)return t.cache.set(n,`resolved-indeterminate`),`resolved-indeterminate`;let o=await _(e,a,t);return t.cache.set(n,o),o}function g(e,t){let n=[];for(let e of t.extraCertificates){let t=u(e);t!==void 0&&n.push(t)}let r=[...t.chain,...n];for(let t of r)if(e.authorityKeyIdentifier!==void 0&&t.subjectKeyIdentifier!==void 0&&p(e.authorityKeyIdentifier)===p(t.subjectKeyIdentifier)||e.issuer.derHex===t.subject.derHex)return t}async function _(e,n,r){let i=r.chain.some(e=>d(e,n));for(let i of r.crls){let a;try{a=l(i)}catch{continue}let o=await t({certificate:e,issuerCertificate:n,crl:a,at:r.at});if(o.ok){if(o.value.status===`revoked`)return`resolved-revoked`;if(o.value.status===`good`&&await h(n,r)===`resolved-valid`)return`resolved-valid`}}return i?`resolved-valid`:`resolved-indeterminate`}function v(e,t,n,r,i){return{certificate:e,status:`revoked`,source:{kind:`crl`,signerCertificate:t,thisUpdate:n},revocationInfo:{revocationDate:r,...i===void 0?{}:{reason:i}}}}function y(e){return typeof e==`string`?o(e):a(e)}function b(e){switch(e){case`stale_response`:return`ocsp_response_expired`;case`responder_id_mismatch`:case`responder_chain_invalid`:case`ocsp_signing_missing`:return`ocsp_responder_not_authorized`;case`responder_revoked`:return`ocsp_responder_revoked`;case`signature_invalid`:case`responder_revocation_unknown`:return`ocsp_responder_indeterminate`;case`response_status_invalid`:case`issuer_mismatch`:case`nonce_mismatch`:case`request_mismatch`:return`no_applicable_ocsp`}}const x=new Set([`signature_invalid`,`responder_id_mismatch`,`responder_chain_invalid`,`ocsp_signing_missing`]);async function S(e,t,n,r){let i={issuerCertificate:t,at:r,...n.trustedOcspResponders===void 0?{}:{trustedOcspResponders:n.trustedOcspResponders},...n.policy?.ocspResponderRevocation===void 0?{}:{responderRevocationPolicy:n.policy.ocspResponderRevocation},...n.crls===void 0?{}:{responderRevocationCrls:n.crls}},a=await s({response:e,...i});if(a.ok||!x.has(a.code))return a;for(let t of n.extraCertificates??[]){let n=u(t);if(n===void 0)continue;let r=await s({response:e,...i,responderCertificate:n});if(r.ok)return r}return a}async function C(e,t,n){let{ocspResponses:r=[],at:a=new Date}=n,o=[],s=new Set;for(let c of r){let r;try{r=y(c)}catch(e){o.push({kind:`parse_error`,message:e instanceof Error?e.message:`OCSP response parse failed`});continue}let l=(r.responses??[]).find(t=>p(t.certId.serialNumberHex)===p(e.serialNumberHex));if(l===void 0)continue;let u=await S(r,t,n,a);if(!u.ok){s.add(b(u.code));continue}if(l.certStatus===`revoked`){let t=i(l.revocationReasonCode);return{status:{certificate:e,status:`revoked`,source:{kind:`ocsp`,thisUpdate:l.thisUpdate},revocationInfo:{revocationDate:l.revokedAt??l.thisUpdate,...t===void 0?{}:{reason:t}}},executionErrors:o}}if(l.certStatus===`good`)return{status:{certificate:e,status:`good`,source:{kind:`ocsp`,thisUpdate:l.thisUpdate}},executionErrors:o};s.add(`ocsp_status_unknown`)}return s.size===0&&s.add(`no_applicable_ocsp`),{status:{certificate:e,status:`indeterminate`,indeterminateReasons:[...s]},executionErrors:o}}const w=[`keyCompromise`,`cACompromise`,`affiliationChanged`,`superseded`,`cessationOfOperation`,`certificateHold`,`privilegeWithdrawn`,`aACompromise`];async function T(e,n,r,i){let{crls:a=[],extraCertificates:o=[],chain:s=[],at:c=new Date}=r,u=[],p=!1,m=!1,g=!1,_,y=new Set,b=[];for(let e of a)try{b.push(l(e))}catch(e){u.push({kind:`parse_error`,message:e instanceof Error?e.message:`CRL parse failed`})}let x=b.filter(e=>e.baseCrlNumber===void 0),S=b.filter(e=>e.baseCrlNumber!==void 0),C=async(n,r,i)=>t({certificate:e,issuerCertificate:i,crl:n,...r===void 0?{}:{deltaCrl:r},at:c});for(let t of x){let r=S.find(e=>e.issuer.derHex===t.issuer.derHex&&e.baseCrlNumber!==void 0&&t.crlNumber!==void 0&&BigInt(e.baseCrlNumber)<=BigInt(t.crlNumber)),a=await C(t,r,n),c=n;if(!a.ok){let e=f(t,o,s);e!==void 0&&!d(e,n)&&(a=await C(t,r,e),c=e)}if(!a.ok)continue;let l=await h(c,i);if(l===`resolved-revoked`){p=!0;continue}if(l===`resolved-indeterminate`){m=!0;continue}let b=r!==void 0&&r.thisUpdate.getTime()>t.thisUpdate.getTime()?r.thisUpdate:t.thisUpdate;if(a.value.status===`revoked`)return{status:v(e,c,b,a.value.revocationDate,a.value.reasonCode),executionErrors:u};g=!0,(_===void 0||b.getTime()>_.thisUpdate.getTime())&&(_={signer:c,thisUpdate:b});let x=t.issuingDistributionPoint?.onlySomeReasons?.flags;if(x===void 0)for(let e of w)y.add(e);else for(let e of x)y.add(e)}if(g&&_!==void 0)return w.every(e=>y.has(e))?{status:{certificate:e,status:`good`,source:{kind:`crl`,signerCertificate:_.signer,thisUpdate:_.thisUpdate}},executionErrors:u}:{status:{certificate:e,status:`indeterminate`,indeterminateReasons:[`reason_coverage_incomplete`]},executionErrors:u};let T=[];return p?T.push(`crl_signer_revoked`):m?T.push(`crl_signer_indeterminate`):T.push(`no_applicable_crl`),{status:{certificate:e,status:`indeterminate`,indeterminateReasons:T},executionErrors:u}}async function E(e,t,n,r){let i=n.policy?.prefer??`best-available`,a=await C(e,t,n),o=await T(e,t,n,r),s=[...a.executionErrors,...o.executionErrors],c=i===`crl`?[o,a]:i===`ocsp`?[a,o]:[a,o].sort((e,t)=>(t.status.source?.thisUpdate?.getTime()??0)-(e.status.source?.thisUpdate?.getTime()??0)),l=c.find(e=>e.status.status===`revoked`);if(l!==void 0)return{status:l.status,executionErrors:s};let u=c.find(e=>e.status.status===`good`);if(u!==void 0)return{status:u.status,executionErrors:s};let d=new Set;for(let e of c)for(let t of e.status.indeterminateReasons??[])d.add(t);return{status:{certificate:e,status:`indeterminate`,indeterminateReasons:[...d]},executionErrors:s}}async function D(e){let{chain:t,policy:n,crls:r=[],extraCertificates:i=[],at:a=new Date}=e,o=n?.mode??`hard-fail`;if(t.length===0)return{ok:!0,value:{decision:`allow`,summary:{revokedCertificates:[],indeterminateCertificates:[]},certificates:[]}};let s={cache:new Map,chain:t,crls:r,extraCertificates:i,at:a},c=t.slice(0,-1),l=[],u=[],d=[],f=[];for(let n=0;n<c.length;n++){let r=c[n],i=t[n+1];if(r===void 0||i===void 0)continue;let{status:a,executionErrors:o}=await E(r,i,e,s);l.push(a),f.push(...o),a.status===`revoked`?u.push(r):a.status===`indeterminate`&&d.push(r)}let p=u.length>0,m=d.length>0;return{ok:!0,value:{decision:p||m&&o===`hard-fail`?`deny`:`allow`,summary:{revokedCertificates:u,indeterminateCertificates:d},certificates:l,...f.length>0?{executionErrors:f}:{}}}}export{c as REVOCATION_INDETERMINATE_REASONS,D as checkChainRevocation};
2
2
  //# sourceMappingURL=chain.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"chain.js","names":[],"sources":["../../src/revocation/chain.ts"],"sourcesContent":["/**\n * Chain-level revocation orchestration.\n *\n * Evaluates CRL and OCSP evidence for an entire validated certificate chain,\n * implementing the revocation checking portion of RFC 5280 §6.3.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc5280#section-6.3 | RFC 5280 §6.3 CRL Validation}\n * @module\n */\n\nimport type { ParsedCertificate } from '#micro509/x509/parse.ts';\nimport { parseCertificateFromSource } from '#micro509/x509/parse.ts';\nimport {\n\tcheckCertificateRevocationAgainstCrl,\n\tparseCertificateRevocationListDer,\n\tparseCertificateRevocationListPem,\n\ttype ParsedCertificateRevocationList,\n\ttype RevocationReason,\n\trevocationReasonFromCode,\n} from './crl.ts';\nimport type { CrlSource } from './crl.ts';\nimport {\n\ttype OcspResponderRevocationPolicy,\n\ttype ParsedOcspResponse,\n\tparseOcspResponseDer,\n\tparseOcspResponsePem,\n\ttype ValidateOcspResponseFailure,\n\ttype ValidateOcspResponseResult,\n\tvalidateOcspResponse,\n} from './ocsp.ts';\n\nexport type { CrlSource };\n\n// ---------------------------------------------------------------------------\n// Input Types\n// ---------------------------------------------------------------------------\n\n/**\n * Certificate in any supported format.\n *\n * Accepts PEM string, DER bytes, or an already-parsed {@linkcode ParsedCertificate}.\n * Used for {@linkcode CheckChainRevocationInput.extraCertificates}.\n */\nexport type CertificateSource = string | Uint8Array | ParsedCertificate;\n\n/**\n * OCSP response in any supported format.\n *\n * Accepts PEM string or DER bytes. Used for\n * {@linkcode CheckChainRevocationInput.ocspResponses}.\n */\nexport type OcspResponseSource = string | Uint8Array;\n\n/**\n * Revocation checking policy for {@linkcode checkChainRevocation}.\n *\n * Controls how indeterminate results (missing evidence, expired CRLs) affect\n * the final {@linkcode CheckChainRevocationValue.decision | decision}.\n */\nexport interface RevocationPolicy {\n\t/**\n\t * How to handle indeterminate status.\n\t *\n\t * - `'soft-fail'`: indeterminate certificates are allowed (default)\n\t * - `'hard-fail'`: indeterminate certificates cause denial\n\t */\n\treadonly mode?: 'soft-fail' | 'hard-fail';\n\t/**\n\t * Evidence preference when multiple sources are available.\n\t *\n\t * Both evidence kinds are always evaluated, and a validated `revoked`\n\t * verdict from either source wins regardless of preference (fail-closed).\n\t * Preference only decides which source's `good` verdict is reported when\n\t * both yield one.\n\t *\n\t * - `'best-available'`: the source with the fresher evidence — the later\n\t * `thisUpdate` on the validated OCSP entry or CRL — is reported; ties\n\t * favor OCSP (default)\n\t * - `'ocsp'`: prefer OCSP over CRL\n\t * - `'crl'`: prefer CRL over OCSP\n\t */\n\treadonly prefer?: 'ocsp' | 'crl' | 'best-available';\n\t/**\n\t * Revocation policy for delegated OCSP responder certificates\n\t * (RFC 6960 §4.2.2.2.1). Supplied CRLs double as responder revocation\n\t * evidence. Defaults to `'honor-nocheck'`.\n\t */\n\treadonly ocspResponderRevocation?: OcspResponderRevocationPolicy;\n}\n\n/** Input for {@linkcode checkChainRevocation}. */\nexport interface CheckChainRevocationInput {\n\t/** Validated certificate chain (leaf first, root last). */\n\treadonly chain: readonly ParsedCertificate[];\n\t/** CRLs to evaluate. */\n\treadonly crls?: readonly CrlSource[];\n\t/** OCSP responses to evaluate. */\n\treadonly ocspResponses?: readonly OcspResponseSource[];\n\t/** Extra certs for indirect CRL issuers / delegated OCSP responders. */\n\treadonly extraCertificates?: readonly CertificateSource[];\n\t/**\n\t * Explicitly trusted OCSP responder certificates (RFC 6960 §4.2.2.2\n\t * criterion 1). A response signed by one of these is accepted without\n\t * delegated-responder issuance, EKU, and revocation checks.\n\t */\n\treadonly trustedOcspResponders?: readonly CertificateSource[];\n\t/** Evaluation time. Defaults to `new Date()`. */\n\treadonly at?: Date;\n\t/** Revocation policy. */\n\treadonly policy?: RevocationPolicy;\n}\n\n// ---------------------------------------------------------------------------\n// Output Types\n// ---------------------------------------------------------------------------\n\n/**\n * Granular reasons why revocation status could not be determined.\n *\n * Returned in {@linkcode CertificateRevocationStatus.indeterminateReasons} when\n * `status` is `'indeterminate'`. Grouped by category:\n *\n * - **Evidence not found**: `no_applicable_crl`, `no_applicable_ocsp`\n * - **Scope mismatch**: `distribution_point_mismatch`, `issuer_name_mismatch`,\n * `reason_scope_mismatch`, `indirect_crl_scope_mismatch`, `reason_coverage_incomplete`\n * - **Signer trust**: `crl_signer_not_found`, `crl_signer_not_authorized`,\n * `crl_signer_revoked`, `crl_signer_indeterminate`, and OCSP equivalents\n * - **Freshness**: `crl_expired`, `ocsp_response_expired`\n */\nexport type RevocationIndeterminateReason =\n\t// Evidence not found\n\t| 'no_applicable_crl'\n\t| 'no_applicable_ocsp'\n\t// Scope issues\n\t| 'distribution_point_mismatch'\n\t| 'issuer_name_mismatch'\n\t| 'reason_scope_mismatch'\n\t| 'indirect_crl_scope_mismatch'\n\t| 'reason_coverage_incomplete'\n\t// Signer trust issues\n\t| 'crl_signer_not_found'\n\t| 'crl_signer_not_authorized'\n\t| 'crl_signer_revoked'\n\t| 'crl_signer_indeterminate'\n\t| 'ocsp_responder_not_found'\n\t| 'ocsp_responder_not_authorized'\n\t| 'ocsp_responder_revoked'\n\t| 'ocsp_responder_indeterminate'\n\t// Freshness\n\t| 'crl_expired'\n\t| 'ocsp_response_expired'\n\t// OCSP specific\n\t| 'ocsp_status_unknown';\n\n/**\n * Identifies the source of revocation evidence.\n *\n * Included in {@linkcode CertificateRevocationStatus.source} when status is\n * `'good'` or `'revoked'` to indicate which CRL or OCSP response provided the answer.\n */\nexport interface RevocationSource {\n\t/** Whether evidence came from a CRL or OCSP response. */\n\treadonly type: 'crl' | 'ocsp';\n\t/** Certificate that signed the evidence (CRL issuer or OCSP responder). */\n\treadonly signerCertificate?: ParsedCertificate;\n\t/** Identifier for debugging (e.g., CRL issuer DN or OCSP responder URL). */\n\treadonly evidenceIdentifier?: string;\n\t/**\n\t * `thisUpdate` of the evidence backing the verdict — the OCSP single\n\t * response entry or the freshest contributing CRL (an applied delta CRL\n\t * supersedes its base). This is the timestamp `'best-available'` compares.\n\t */\n\treadonly thisUpdate?: Date;\n}\n\n/**\n * Revocation evaluation result for a single certificate.\n *\n * One entry per certificate in {@linkcode CheckChainRevocationValue.certificates}.\n * The trust anchor is excluded (never checked for revocation).\n */\nexport interface CertificateRevocationStatus {\n\t/** The certificate that was evaluated. */\n\treadonly certificate: ParsedCertificate;\n\t/**\n\t * Revocation status determination.\n\t *\n\t * - `'good'`: evidence confirms certificate is not revoked\n\t * - `'revoked'`: evidence confirms certificate is revoked\n\t * - `'indeterminate'`: could not determine status (see {@linkcode indeterminateReasons})\n\t */\n\treadonly status: 'good' | 'revoked' | 'indeterminate';\n\t/** Evidence source when status is `'good'` or `'revoked'`. */\n\treadonly source?: RevocationSource;\n\t/** Why status could not be determined. Present when `status` is `'indeterminate'`. */\n\treadonly indeterminateReasons?: readonly RevocationIndeterminateReason[];\n\t/** Revocation details. Present when `status` is `'revoked'`. */\n\treadonly revocationInfo?: {\n\t\t/** When the certificate was revoked. */\n\t\treadonly date: Date;\n\t\t/** RFC 5280 CRLReason code, if provided by the CRL/OCSP response. */\n\t\treadonly reason?: RevocationReason;\n\t};\n}\n\n/**\n * Errors encountered while processing revocation evidence.\n *\n * Distinct from {@linkcode RevocationIndeterminateReason}: execution errors are\n * code failures (malformed CRL, unsupported extension) rather than evaluation\n * outcomes (CRL doesn't cover this certificate).\n *\n * Collected in {@linkcode CheckChainRevocationValue.executionErrors}.\n */\nexport interface RevocationExecutionError {\n\t/** Error category. */\n\treadonly kind: 'parse_error' | 'unsupported_extension' | 'internal_error';\n\t/** Human-readable error description. */\n\treadonly message: string;\n\t/** Which evidence caused the error (e.g., CRL issuer DN). */\n\treadonly evidenceIdentifier?: string;\n}\n\n/**\n * Detailed revocation check results.\n *\n * Returned as {@linkcode CheckChainRevocationResult.value} from\n * {@linkcode checkChainRevocation}. Contains both the policy decision and\n * detailed per-certificate findings for debugging.\n */\nexport interface CheckChainRevocationValue {\n\t/**\n\t * Final policy decision based on {@linkcode RevocationPolicy}.\n\t *\n\t * - `'allow'`: chain passes revocation check\n\t * - `'deny'`: chain fails (revoked certificate or hard-fail on indeterminate)\n\t */\n\treadonly decision: 'allow' | 'deny';\n\t/** Quick-access summary of problematic certificates. */\n\treadonly summary: {\n\t\t/** Certificates confirmed as revoked. */\n\t\treadonly revokedCertificates: readonly ParsedCertificate[];\n\t\t/** Certificates whose status could not be determined. */\n\t\treadonly indeterminateCertificates: readonly ParsedCertificate[];\n\t};\n\t/** Per-certificate evaluation results. See {@linkcode CertificateRevocationStatus}. */\n\treadonly certificates: readonly CertificateRevocationStatus[];\n\t/** Evidence that could not be processed. See {@linkcode RevocationExecutionError}. */\n\treadonly executionErrors?: readonly RevocationExecutionError[];\n}\n\n/** Result type for {@linkcode checkChainRevocation}. */\nexport type CheckChainRevocationResult = {\n\treadonly ok: true;\n\treadonly value: CheckChainRevocationValue;\n};\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Parses a CRL from various source formats.\n */\nfunction parseCrlFromSource(source: CrlSource): ParsedCertificateRevocationList {\n\tif (typeof source === 'object' && 'issuer' in source) {\n\t\treturn source;\n\t}\n\tif (typeof source === 'string') {\n\t\treturn parseCertificateRevocationListPem(source);\n\t}\n\treturn parseCertificateRevocationListDer(source);\n}\n\n/**\n * Parses a certificate from various source formats, returning undefined on failure.\n */\nfunction parseCertificateSafe(source: CertificateSource): ParsedCertificate | undefined {\n\ttry {\n\t\treturn parseCertificateFromSource(source);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Compares two certificates by DER bytes for identity.\n * Reference equality fails when same cert is parsed from different sources.\n */\nfunction sameCertificate(a: ParsedCertificate, b: ParsedCertificate): boolean {\n\tif (a.der.length !== b.der.length) return false;\n\tfor (let i = 0; i < a.der.length; i++) {\n\t\tif (a.der[i] !== b.der[i]) return false;\n\t}\n\treturn true;\n}\n\n/**\n * Searches for a certificate that could have signed the given CRL.\n * Matches by AKI/SKI or issuer/subject DN.\n */\nfunction findIndirectCrlIssuer(\n\tcrl: ParsedCertificateRevocationList,\n\textraCertificates: readonly CertificateSource[],\n\tchain: readonly ParsedCertificate[],\n): ParsedCertificate | undefined {\n\t// Combine extra certs with chain certs for searching\n\t// Chain certs are already parsed; extra certs may need parsing\n\tconst parsedExtras: ParsedCertificate[] = [];\n\tfor (const source of extraCertificates) {\n\t\tconst parsed = parseCertificateSafe(source);\n\t\tif (parsed !== undefined) {\n\t\t\tparsedExtras.push(parsed);\n\t\t}\n\t}\n\n\tconst candidates = [...parsedExtras, ...chain];\n\n\t// First pass: prefer AKI/SKI match (more specific)\n\tif (crl.authorityKeyIdentifier !== undefined) {\n\t\tfor (const candidate of candidates) {\n\t\t\tif (\n\t\t\t\tcandidate.subjectKeyIdentifier !== undefined &&\n\t\t\t\tnormalizeHex(crl.authorityKeyIdentifier) === normalizeHex(candidate.subjectKeyIdentifier)\n\t\t\t) {\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Second pass: fall back to DN match\n\tfor (const candidate of candidates) {\n\t\tif (crl.issuer.derHex === candidate.subject.derHex) {\n\t\t\treturn candidate;\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\n/** Lowercases a hex string for bytewise comparison. */\nfunction normalizeHex(value: string): string {\n\treturn value.toLowerCase();\n}\n\n// ---------------------------------------------------------------------------\n// CRL Signer Validation (RFC 5280 §6.3.3)\n// ---------------------------------------------------------------------------\n\n/**\n * State machine for CRL signer validation with memoization.\n * - `visiting`: Currently being checked (cycle detection)\n * - `resolved-valid`: Signer is not revoked\n * - `resolved-revoked`: Signer is revoked\n * - `resolved-indeterminate`: Can't determine signer status\n */\ntype SignerValidationState =\n\t| 'visiting'\n\t| 'resolved-valid'\n\t| 'resolved-revoked'\n\t| 'resolved-indeterminate';\n\n/** Context for CRL signer validation with memoization cache. */\ninterface SignerValidationContext {\n\treadonly cache: Map<string, SignerValidationState>;\n\treadonly chain: readonly ParsedCertificate[];\n\treadonly crls: readonly CrlSource[];\n\treadonly extraCertificates: readonly CertificateSource[];\n\treadonly at: Date;\n}\n\n/**\n * Builds a unique cache key for a certificate.\n * Uses issuer DN + serial number which uniquely identifies a cert.\n */\nfunction certCacheKey(cert: ParsedCertificate): string {\n\treturn `${cert.issuer.derHex}:${cert.serialNumberHex}`;\n}\n\n/**\n * Validates that a CRL signer certificate is not revoked.\n * Uses memoization to avoid redundant checks and detect cycles.\n */\nasync function validateCrlSigner(\n\tsigner: ParsedCertificate,\n\tctx: SignerValidationContext,\n): Promise<SignerValidationState> {\n\t// Use issuer+serial as cache key (unique per certificate)\n\tconst key = certCacheKey(signer);\n\tconst cached = ctx.cache.get(key);\n\n\t// Cycle detection: if we're already visiting this signer, it's indeterminate\n\tif (cached === 'visiting') {\n\t\treturn 'resolved-indeterminate';\n\t}\n\n\t// Return cached result if already resolved\n\tif (cached !== undefined) {\n\t\treturn cached;\n\t}\n\n\t// Mark as visiting before recursive checks\n\tctx.cache.set(key, 'visiting');\n\n\t// Trust anchor (last in chain) is trusted by definition\n\tconst trustAnchor = ctx.chain[ctx.chain.length - 1];\n\tif (trustAnchor !== undefined && sameCertificate(signer, trustAnchor)) {\n\t\tctx.cache.set(key, 'resolved-valid');\n\t\treturn 'resolved-valid';\n\t}\n\n\t// If signer is in the validated chain, it's trusted\n\t// (Chain was already validated before revocation checking)\n\tconst isInChain = ctx.chain.some((c) => sameCertificate(c, signer));\n\tif (isInChain) {\n\t\tctx.cache.set(key, 'resolved-valid');\n\t\treturn 'resolved-valid';\n\t}\n\n\t// Signer is not in chain — need to check its revocation status\n\t// Find signer's issuer to perform revocation check\n\tconst signerIssuer = findSignerIssuer(signer, ctx);\n\tif (signerIssuer === undefined) {\n\t\tctx.cache.set(key, 'resolved-indeterminate');\n\t\treturn 'resolved-indeterminate';\n\t}\n\n\t// Check signer's revocation status (recursive)\n\tconst signerRevocation = await checkSignerRevocation(signer, signerIssuer, ctx);\n\tctx.cache.set(key, signerRevocation);\n\treturn signerRevocation;\n}\n\n/**\n * Finds the issuer certificate for a CRL signer.\n * Searches the chain and extraCertificates by AKI/SKI or DN matching.\n */\nfunction findSignerIssuer(\n\tsigner: ParsedCertificate,\n\tctx: SignerValidationContext,\n): ParsedCertificate | undefined {\n\t// Parse extra certificates\n\tconst parsedExtras: ParsedCertificate[] = [];\n\tfor (const source of ctx.extraCertificates) {\n\t\tconst parsed = parseCertificateSafe(source);\n\t\tif (parsed !== undefined) {\n\t\t\tparsedExtras.push(parsed);\n\t\t}\n\t}\n\n\tconst candidates = [...ctx.chain, ...parsedExtras];\n\n\tfor (const candidate of candidates) {\n\t\t// Match by AKI → SKI (preferred, more specific)\n\t\tif (\n\t\t\tsigner.authorityKeyIdentifier !== undefined &&\n\t\t\tcandidate.subjectKeyIdentifier !== undefined &&\n\t\t\tnormalizeHex(signer.authorityKeyIdentifier) === normalizeHex(candidate.subjectKeyIdentifier)\n\t\t) {\n\t\t\treturn candidate;\n\t\t}\n\n\t\t// Match by issuer DN → subject DN\n\t\tif (signer.issuer.derHex === candidate.subject.derHex) {\n\t\t\treturn candidate;\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Checks if a CRL signer certificate is revoked by examining available CRLs.\n * Recursively validates the CRL signer of any CRL used to check revocation.\n */\nasync function checkSignerRevocation(\n\tsigner: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tctx: SignerValidationContext,\n): Promise<SignerValidationState> {\n\t// If the signer's issuer is in the validated chain, the signer is trusted\n\t// by virtue of being issued by a trusted CA. We only need to check if\n\t// it's explicitly revoked, not prove \"good\" status.\n\tconst issuerInChain = ctx.chain.some((c) => sameCertificate(c, issuer));\n\n\t// Try each CRL to check signer's revocation\n\tfor (const crlSource of ctx.crls) {\n\t\tlet crl: ParsedCertificateRevocationList;\n\t\ttry {\n\t\t\tcrl = parseCrlFromSource(crlSource);\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Check if this CRL can provide revocation info for the signer\n\t\tconst result = await checkCertificateRevocationAgainstCrl({\n\t\t\tcertificate: signer,\n\t\t\tissuerCertificate: issuer,\n\t\t\tcrl,\n\t\t\tat: ctx.at,\n\t\t});\n\n\t\tif (result.ok) {\n\t\t\tif (result.value.status === 'revoked') {\n\t\t\t\treturn 'resolved-revoked';\n\t\t\t}\n\t\t\tif (result.value.status === 'good') {\n\t\t\t\t// Before accepting this result, validate the CRL's signer\n\t\t\t\t// The CRL's signer is the issuer we just used\n\t\t\t\tconst crlSignerStatus = await validateCrlSigner(issuer, ctx);\n\t\t\t\tif (crlSignerStatus === 'resolved-valid') {\n\t\t\t\t\treturn 'resolved-valid';\n\t\t\t\t}\n\t\t\t\t// If CRL signer is revoked or indeterminate, can't trust this result\n\t\t\t}\n\t\t}\n\t}\n\n\t// If the signer's issuer is in the chain and we found no revocation,\n\t// trust the signer (issued by trusted CA, no evidence of revocation)\n\tif (issuerInChain) {\n\t\treturn 'resolved-valid';\n\t}\n\n\treturn 'resolved-indeterminate';\n}\n\n/** Builds a CertificateRevocationStatus for a CRL check result. */\nfunction buildCrlStatus(\n\tcert: ParsedCertificate,\n\tsigner: ParsedCertificate,\n\tstatus: 'good' | 'revoked',\n\tthisUpdate: Date,\n\trevocationDate?: Date,\n\treasonCode?: RevocationReason,\n): CertificateRevocationStatus {\n\tif (status === 'revoked' && revocationDate !== undefined) {\n\t\treturn {\n\t\t\tcertificate: cert,\n\t\t\tstatus: 'revoked',\n\t\t\tsource: { type: 'crl', signerCertificate: signer, thisUpdate },\n\t\t\trevocationInfo: {\n\t\t\t\tdate: revocationDate,\n\t\t\t\t...(reasonCode !== undefined ? { reason: reasonCode } : {}),\n\t\t\t},\n\t\t};\n\t}\n\treturn {\n\t\tcertificate: cert,\n\t\tstatus: 'good',\n\t\tsource: { type: 'crl', signerCertificate: signer, thisUpdate },\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// OCSP Evidence Evaluation (RFC 6960)\n// ---------------------------------------------------------------------------\n\n/** Per-certificate evidence evaluation outcome shared by the CRL and OCSP evaluators. */\ninterface EvidenceEvaluation {\n\treadonly status: CertificateRevocationStatus;\n\treadonly executionErrors: readonly RevocationExecutionError[];\n}\n\n/** Parses an OCSP response from PEM string or DER bytes. */\nfunction parseOcspResponseFromSource(source: OcspResponseSource): ParsedOcspResponse {\n\tif (typeof source === 'string') {\n\t\treturn parseOcspResponsePem(source);\n\t}\n\treturn parseOcspResponseDer(source);\n}\n\n/** Maps a {@linkcode validateOcspResponse} failure code to an indeterminate reason. */\nfunction ocspIndeterminateReasonFromFailure(\n\tcode: ValidateOcspResponseFailure['code'],\n): RevocationIndeterminateReason {\n\tswitch (code) {\n\t\tcase 'stale_response':\n\t\t\treturn 'ocsp_response_expired';\n\t\tcase 'responder_id_mismatch':\n\t\tcase 'responder_chain_invalid':\n\t\tcase 'ocsp_signing_missing':\n\t\t\treturn 'ocsp_responder_not_authorized';\n\t\tcase 'responder_revoked':\n\t\t\treturn 'ocsp_responder_revoked';\n\t\tcase 'signature_invalid':\n\t\tcase 'responder_revocation_unknown':\n\t\t\treturn 'ocsp_responder_indeterminate';\n\t\tcase 'response_status_invalid':\n\t\tcase 'issuer_mismatch':\n\t\tcase 'nonce_mismatch':\n\t\tcase 'request_mismatch':\n\t\t\treturn 'no_applicable_ocsp';\n\t}\n}\n\n/** Validation failures worth retrying with an explicit responder certificate. */\nconst OCSP_RESPONDER_FAILURE_CODES: ReadonlySet<ValidateOcspResponseFailure['code']> = new Set([\n\t'signature_invalid',\n\t'responder_id_mismatch',\n\t'responder_chain_invalid',\n\t'ocsp_signing_missing',\n]);\n\n/**\n * Validates an OCSP response, retrying with caller-provided extra certificates\n * as explicit responder certificates when embedded discovery fails.\n */\nasync function validateOcspResponseWithResponderFallback(\n\tresponse: ParsedOcspResponse,\n\tissuer: ParsedCertificate,\n\tinput: CheckChainRevocationInput,\n\tat: Date,\n): Promise<ValidateOcspResponseResult> {\n\tconst shared = {\n\t\tissuerCertificate: issuer,\n\t\tat,\n\t\t...(input.trustedOcspResponders !== undefined\n\t\t\t? { trustedResponderCertificates: input.trustedOcspResponders }\n\t\t\t: {}),\n\t\t...(input.policy?.ocspResponderRevocation !== undefined\n\t\t\t? { responderRevocationPolicy: input.policy.ocspResponderRevocation }\n\t\t\t: {}),\n\t\t// Chain-level CRLs double as responder revocation evidence\n\t\t...(input.crls !== undefined ? { responderRevocationCrls: input.crls } : {}),\n\t};\n\tconst primary = await validateOcspResponse({ response, ...shared });\n\tif (primary.ok || !OCSP_RESPONDER_FAILURE_CODES.has(primary.code)) {\n\t\treturn primary;\n\t}\n\tfor (const source of input.extraCertificates ?? []) {\n\t\tconst responder = parseCertificateSafe(source);\n\t\tif (responder === undefined) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst retry = await validateOcspResponse({\n\t\t\tresponse,\n\t\t\t...shared,\n\t\t\tresponderCertificate: responder,\n\t\t});\n\t\tif (retry.ok) {\n\t\t\treturn retry;\n\t\t}\n\t}\n\treturn primary;\n}\n\n/**\n * Evaluates OCSP evidence for a single certificate (RFC 6960).\n *\n * Every response is fully validated — signature, responder binding and\n * authorization, and freshness — via {@linkcode validateOcspResponse} before\n * its status entry is trusted. Issuer binding of each CertID is enforced by\n * the validator, so a serial-number match on a validated response is\n * sufficient to attribute the entry to `cert`.\n */\nasync function evaluateOcspEvidence(\n\tcert: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tinput: CheckChainRevocationInput,\n): Promise<EvidenceEvaluation> {\n\tconst { ocspResponses = [], at = new Date() } = input;\n\tconst executionErrors: RevocationExecutionError[] = [];\n\tconst reasons = new Set<RevocationIndeterminateReason>();\n\n\tfor (const source of ocspResponses) {\n\t\tlet parsed: ParsedOcspResponse;\n\t\ttry {\n\t\t\tparsed = parseOcspResponseFromSource(source);\n\t\t} catch (e) {\n\t\t\texecutionErrors.push({\n\t\t\t\tkind: 'parse_error',\n\t\t\t\tmessage: e instanceof Error ? e.message : 'OCSP response parse failed',\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst entry = (parsed.responses ?? []).find(\n\t\t\t(single) =>\n\t\t\t\tnormalizeHex(single.certId.serialNumberHex) === normalizeHex(cert.serialNumberHex),\n\t\t);\n\t\tif (entry === undefined) {\n\t\t\tcontinue; // Response does not cover this certificate\n\t\t}\n\n\t\tconst validation = await validateOcspResponseWithResponderFallback(parsed, issuer, input, at);\n\t\tif (!validation.ok) {\n\t\t\treasons.add(ocspIndeterminateReasonFromFailure(validation.code));\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (entry.certStatus === 'revoked') {\n\t\t\tconst reason = revocationReasonFromCode(entry.revocationReasonCode);\n\t\t\treturn {\n\t\t\t\tstatus: {\n\t\t\t\t\tcertificate: cert,\n\t\t\t\t\tstatus: 'revoked',\n\t\t\t\t\tsource: { type: 'ocsp', thisUpdate: entry.thisUpdate },\n\t\t\t\t\trevocationInfo: {\n\t\t\t\t\t\tdate: entry.revokedAt ?? entry.thisUpdate,\n\t\t\t\t\t\t...(reason !== undefined ? { reason } : {}),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\texecutionErrors,\n\t\t\t};\n\t\t}\n\t\tif (entry.certStatus === 'good') {\n\t\t\treturn {\n\t\t\t\tstatus: {\n\t\t\t\t\tcertificate: cert,\n\t\t\t\t\tstatus: 'good',\n\t\t\t\t\tsource: { type: 'ocsp', thisUpdate: entry.thisUpdate },\n\t\t\t\t},\n\t\t\t\texecutionErrors,\n\t\t\t};\n\t\t}\n\t\treasons.add('ocsp_status_unknown');\n\t}\n\n\tif (reasons.size === 0) {\n\t\treasons.add('no_applicable_ocsp');\n\t}\n\treturn {\n\t\tstatus: {\n\t\t\tcertificate: cert,\n\t\t\tstatus: 'indeterminate',\n\t\t\tindeterminateReasons: [...reasons],\n\t\t},\n\t\texecutionErrors,\n\t};\n}\n\n/**\n * Evaluates revocation status for a single certificate using available CRLs.\n * Returns both status and any execution errors encountered.\n *\n * Tries the chain issuer first; if that fails, searches extraCertificates\n * and chain for an indirect CRL issuer that matches the CRL's AKI or issuer DN.\n *\n * Also validates that CRL signers are not revoked (RFC 5280 §6.3.3).\n */\n// RFC 5280 ReasonFlags — all possible revocation reasons that CRLs can cover.\nconst ALL_REASON_FLAGS: readonly string[] = [\n\t'keyCompromise',\n\t'cACompromise',\n\t'affiliationChanged',\n\t'superseded',\n\t'cessationOfOperation',\n\t'certificateHold',\n\t'privilegeWithdrawn',\n\t'aACompromise',\n];\n\nasync function evaluateCrlEvidence(\n\tcert: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tinput: CheckChainRevocationInput,\n\tsignerCtx: SignerValidationContext,\n): Promise<EvidenceEvaluation> {\n\tconst { crls = [], extraCertificates = [], chain = [], at = new Date() } = input;\n\tconst executionErrors: RevocationExecutionError[] = [];\n\tlet sawCrlSignerRevoked = false;\n\tlet sawCrlSignerIndeterminate = false;\n\tlet sawGood = false;\n\t// Signer and thisUpdate are tracked together so the reported\n\t// signerCertificate always belongs to the CRL whose freshness is reported.\n\tlet freshestGood: { readonly signer: ParsedCertificate; readonly thisUpdate: Date } | undefined;\n\tconst coveredReasons = new Set<string>();\n\n\t// Parse all CRLs and separate base CRLs from delta CRLs\n\tconst parsedCrls: ParsedCertificateRevocationList[] = [];\n\tfor (const crlSource of crls) {\n\t\ttry {\n\t\t\tparsedCrls.push(parseCrlFromSource(crlSource));\n\t\t} catch (e) {\n\t\t\texecutionErrors.push({\n\t\t\t\tkind: 'parse_error',\n\t\t\t\tmessage: e instanceof Error ? e.message : 'CRL parse failed',\n\t\t\t});\n\t\t}\n\t}\n\n\tconst baseCrls = parsedCrls.filter((crl) => crl.baseCrlNumber === undefined);\n\tconst deltaCrls = parsedCrls.filter((crl) => crl.baseCrlNumber !== undefined);\n\n\t// Helper to check CRL with given issuer and optional delta\n\tconst checkWithIssuer = async (\n\t\tcrl: ParsedCertificateRevocationList,\n\t\tdeltaCrl: ParsedCertificateRevocationList | undefined,\n\t\tcrlIssuer: ParsedCertificate,\n\t) => {\n\t\treturn checkCertificateRevocationAgainstCrl({\n\t\t\tcertificate: cert,\n\t\t\tissuerCertificate: crlIssuer,\n\t\t\tcrl,\n\t\t\t...(deltaCrl !== undefined ? { deltaCrl } : {}),\n\t\t\tat,\n\t\t});\n\t};\n\n\t// Process base CRLs (optionally paired with delta CRLs)\n\tfor (const baseCrl of baseCrls) {\n\t\t// Find applicable delta CRL for this base CRL (if any)\n\t\t// Delta CRL applies if it has the same issuer and crlNumber matches baseCrlNumber\n\t\tconst applicableDelta = deltaCrls.find(\n\t\t\t(d) =>\n\t\t\t\td.issuer.derHex === baseCrl.issuer.derHex &&\n\t\t\t\td.baseCrlNumber !== undefined &&\n\t\t\t\tbaseCrl.crlNumber !== undefined &&\n\t\t\t\tBigInt(d.baseCrlNumber) <= BigInt(baseCrl.crlNumber),\n\t\t);\n\n\t\t// Try chain issuer first\n\t\tlet result = await checkWithIssuer(baseCrl, applicableDelta, issuer);\n\t\tlet effectiveSigner = issuer;\n\n\t\t// Chain issuer failed — try to find indirect CRL issuer\n\t\tif (!result.ok) {\n\t\t\tconst indirectIssuer = findIndirectCrlIssuer(baseCrl, extraCertificates, chain);\n\t\t\tif (indirectIssuer !== undefined && !sameCertificate(indirectIssuer, issuer)) {\n\t\t\t\tresult = await checkWithIssuer(baseCrl, applicableDelta, indirectIssuer);\n\t\t\t\teffectiveSigner = indirectIssuer;\n\t\t\t}\n\t\t}\n\n\t\tif (!result.ok) {\n\t\t\tcontinue; // CRL doesn't apply to this certificate\n\t\t}\n\n\t\t// Validate CRL signer is not revoked before accepting result\n\t\tconst signerStatus = await validateCrlSigner(effectiveSigner, signerCtx);\n\t\tif (signerStatus === 'resolved-revoked') {\n\t\t\tsawCrlSignerRevoked = true;\n\t\t\tcontinue; // CRL signer revoked — can't trust this CRL\n\t\t}\n\t\tif (signerStatus === 'resolved-indeterminate') {\n\t\t\tsawCrlSignerIndeterminate = true;\n\t\t\tcontinue; // CRL signer status unknown — try other CRLs\n\t\t}\n\n\t\t// Evidence freshness: an applied delta CRL supersedes its base\n\t\tconst crlThisUpdate =\n\t\t\tapplicableDelta !== undefined &&\n\t\t\tapplicableDelta.thisUpdate.getTime() > baseCrl.thisUpdate.getTime()\n\t\t\t\t? applicableDelta.thisUpdate\n\t\t\t\t: baseCrl.thisUpdate;\n\n\t\t// CRL is valid — check result\n\t\tif (result.value.status === 'revoked') {\n\t\t\t// Immediately return revoked status\n\t\t\treturn {\n\t\t\t\tstatus: buildCrlStatus(\n\t\t\t\t\tcert,\n\t\t\t\t\teffectiveSigner,\n\t\t\t\t\t'revoked',\n\t\t\t\t\tcrlThisUpdate,\n\t\t\t\t\tresult.value.revocationDate,\n\t\t\t\t\tresult.value.reasonCode,\n\t\t\t\t),\n\t\t\t\texecutionErrors,\n\t\t\t};\n\t\t}\n\n\t\t// Status is 'good' — track which reasons this CRL covers\n\t\tsawGood = true;\n\t\tif (freshestGood === undefined || crlThisUpdate.getTime() > freshestGood.thisUpdate.getTime()) {\n\t\t\tfreshestGood = { signer: effectiveSigner, thisUpdate: crlThisUpdate };\n\t\t}\n\t\tconst crlReasons = baseCrl.issuingDistributionPoint?.onlySomeReasons?.flags;\n\t\tif (crlReasons === undefined) {\n\t\t\t// CRL covers all reasons\n\t\t\tfor (const reason of ALL_REASON_FLAGS) {\n\t\t\t\tcoveredReasons.add(reason);\n\t\t\t}\n\t\t} else {\n\t\t\t// CRL only covers specific reasons\n\t\t\tfor (const reason of crlReasons) {\n\t\t\t\tcoveredReasons.add(reason);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return 'good' only if we saw at least one good result AND all reasons are covered\n\tif (sawGood) {\n\t\tconst allReasonsCovered = ALL_REASON_FLAGS.every((r) => coveredReasons.has(r));\n\t\tif (allReasonsCovered) {\n\t\t\treturn {\n\t\t\t\tstatus: {\n\t\t\t\t\tcertificate: cert,\n\t\t\t\t\tstatus: 'good',\n\t\t\t\t\t...(freshestGood !== undefined\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tsource: {\n\t\t\t\t\t\t\t\t\ttype: 'crl',\n\t\t\t\t\t\t\t\t\tsignerCertificate: freshestGood.signer,\n\t\t\t\t\t\t\t\t\tthisUpdate: freshestGood.thisUpdate,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t},\n\t\t\t\texecutionErrors,\n\t\t\t};\n\t\t}\n\t\t// Not all reasons covered — indeterminate\n\t\treturn {\n\t\t\tstatus: {\n\t\t\t\tcertificate: cert,\n\t\t\t\tstatus: 'indeterminate',\n\t\t\t\tindeterminateReasons: ['reason_coverage_incomplete'],\n\t\t\t},\n\t\t\texecutionErrors,\n\t\t};\n\t}\n\n\t// No applicable CRL found — determine most appropriate indeterminate reason\n\tconst reasons: RevocationIndeterminateReason[] = [];\n\tif (sawCrlSignerRevoked) {\n\t\treasons.push('crl_signer_revoked');\n\t} else if (sawCrlSignerIndeterminate) {\n\t\treasons.push('crl_signer_indeterminate');\n\t} else {\n\t\treasons.push('no_applicable_crl');\n\t}\n\n\treturn {\n\t\tstatus: {\n\t\t\tcertificate: cert,\n\t\t\tstatus: 'indeterminate',\n\t\t\tindeterminateReasons: reasons,\n\t\t},\n\t\texecutionErrors,\n\t};\n}\n\n/**\n * Evaluates revocation status for a single certificate by combining OCSP and\n * CRL evidence.\n *\n * Both evidence kinds are always evaluated: a validated `revoked` verdict from\n * either source wins regardless of {@linkcode RevocationPolicy.prefer}\n * (fail-closed). Otherwise the preferred source's `good` verdict is reported —\n * for `'best-available'` the source with the later evidence `thisUpdate` wins,\n * ties favoring OCSP. If neither source is definitive, indeterminate reasons\n * from both are merged.\n */\nasync function evaluateCertificateRevocation(\n\tcert: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tinput: CheckChainRevocationInput,\n\tsignerCtx: SignerValidationContext,\n): Promise<EvidenceEvaluation> {\n\tconst prefer = input.policy?.prefer ?? 'best-available';\n\tconst ocsp = await evaluateOcspEvidence(cert, issuer, input);\n\tconst crl = await evaluateCrlEvidence(cert, issuer, input, signerCtx);\n\tconst executionErrors = [...ocsp.executionErrors, ...crl.executionErrors];\n\n\t// 'best-available' ranks by evidence freshness; the sort is stable, so\n\t// equal (or absent) thisUpdate keeps OCSP first.\n\tconst ordered =\n\t\tprefer === 'crl'\n\t\t\t? [crl, ocsp]\n\t\t\t: prefer === 'ocsp'\n\t\t\t\t? [ocsp, crl]\n\t\t\t\t: [ocsp, crl].sort(\n\t\t\t\t\t\t(a, b) =>\n\t\t\t\t\t\t\t(b.status.source?.thisUpdate?.getTime() ?? 0) -\n\t\t\t\t\t\t\t(a.status.source?.thisUpdate?.getTime() ?? 0),\n\t\t\t\t\t);\n\tconst revoked = ordered.find((evaluation) => evaluation.status.status === 'revoked');\n\tif (revoked !== undefined) {\n\t\treturn { status: revoked.status, executionErrors };\n\t}\n\tconst good = ordered.find((evaluation) => evaluation.status.status === 'good');\n\tif (good !== undefined) {\n\t\treturn { status: good.status, executionErrors };\n\t}\n\n\tconst reasons = new Set<RevocationIndeterminateReason>();\n\tfor (const evaluation of ordered) {\n\t\tfor (const reason of evaluation.status.indeterminateReasons ?? []) {\n\t\t\treasons.add(reason);\n\t\t}\n\t}\n\treturn {\n\t\tstatus: {\n\t\t\tcertificate: cert,\n\t\t\tstatus: 'indeterminate',\n\t\t\tindeterminateReasons: [...reasons],\n\t\t},\n\t\texecutionErrors,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Function\n// ---------------------------------------------------------------------------\n\n/**\n * Checks revocation status for all certificates in a validated chain.\n *\n * Evaluates CRL and OCSP evidence against each certificate (except the trust\n * anchor), applies the revocation policy, and returns a unified decision.\n *\n * @example\n * ```ts\n * const result = await checkChainRevocation({\n * chain: validatedChain,\n * crls: [crl1, crl2],\n * ocspResponses: [ocspResponseDer],\n * policy: { mode: 'hard-fail' },\n * });\n * if (result.value.decision === 'deny') {\n * console.log('Revocation check failed');\n * }\n * ```\n */\nexport async function checkChainRevocation(\n\tinput: CheckChainRevocationInput,\n): Promise<CheckChainRevocationResult> {\n\tconst { chain, policy, crls = [], extraCertificates = [], at = new Date() } = input;\n\tconst mode = policy?.mode ?? 'soft-fail';\n\n\t// Empty chain → allow\n\tif (chain.length === 0) {\n\t\treturn {\n\t\t\tok: true,\n\t\t\tvalue: {\n\t\t\t\tdecision: 'allow',\n\t\t\t\tsummary: { revokedCertificates: [], indeterminateCertificates: [] },\n\t\t\t\tcertificates: [],\n\t\t\t},\n\t\t};\n\t}\n\n\t// Create signer validation context with memoization cache\n\t// This cache is shared across all certificate checks in this chain evaluation\n\tconst signerCtx: SignerValidationContext = {\n\t\tcache: new Map(),\n\t\tchain,\n\t\tcrls,\n\t\textraCertificates,\n\t\tat,\n\t};\n\n\t// Skip trust anchor (last cert) — it's the trust base\n\tconst certsToCheck = chain.slice(0, -1);\n\tconst certificates: CertificateRevocationStatus[] = [];\n\tconst revokedCertificates: ParsedCertificate[] = [];\n\tconst indeterminateCertificates: ParsedCertificate[] = [];\n\tconst allExecutionErrors: RevocationExecutionError[] = [];\n\n\tfor (let i = 0; i < certsToCheck.length; i++) {\n\t\tconst cert = certsToCheck[i];\n\t\tconst issuer = chain[i + 1]; // Next cert in chain is the issuer\n\t\tif (cert === undefined || issuer === undefined) {\n\t\t\tcontinue; // Should never happen given loop bounds\n\t\t}\n\n\t\tconst { status, executionErrors } = await evaluateCertificateRevocation(\n\t\t\tcert,\n\t\t\tissuer,\n\t\t\tinput,\n\t\t\tsignerCtx,\n\t\t);\n\t\tcertificates.push(status);\n\t\tallExecutionErrors.push(...executionErrors);\n\n\t\tif (status.status === 'revoked') {\n\t\t\trevokedCertificates.push(cert);\n\t\t} else if (status.status === 'indeterminate') {\n\t\t\tindeterminateCertificates.push(cert);\n\t\t}\n\t}\n\n\t// Apply policy\n\tconst hasRevoked = revokedCertificates.length > 0;\n\tconst hasIndeterminate = indeterminateCertificates.length > 0;\n\tconst decision: 'allow' | 'deny' = hasRevoked\n\t\t? 'deny'\n\t\t: hasIndeterminate && mode === 'hard-fail'\n\t\t\t? 'deny'\n\t\t\t: 'allow';\n\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tdecision,\n\t\t\tsummary: { revokedCertificates, indeterminateCertificates },\n\t\t\tcertificates,\n\t\t\t...(allExecutionErrors.length > 0 ? { executionErrors: allExecutionErrors } : {}),\n\t\t},\n\t};\n}\n"],"mappings":"+UAwQA,SAAS,EAAmB,EAAoD,CAO/E,OANI,OAAO,GAAW,UAAY,WAAY,EACtC,EAEJ,OAAO,GAAW,SACd,EAAkC,CAAM,EAEzC,EAAkC,CAAM,CAChD,CAKA,SAAS,EAAqB,EAA0D,CACvF,GAAI,CACH,OAAO,EAA2B,CAAM,CACzC,MAAQ,CACP,MACD,CACD,CAMA,SAAS,EAAgB,EAAsB,EAA+B,CAC7E,GAAI,EAAE,IAAI,SAAW,EAAE,IAAI,OAAQ,MAAO,GAC1C,IAAK,IAAI,EAAI,EAAG,EAAI,EAAE,IAAI,OAAQ,IACjC,GAAI,EAAE,IAAI,KAAO,EAAE,IAAI,GAAI,MAAO,GAEnC,MAAO,EACR,CAMA,SAAS,EACR,EACA,EACA,EACgC,CAGhC,IAAM,EAAoC,CAAC,EAC3C,IAAK,IAAM,KAAU,EAAmB,CACvC,IAAM,EAAS,EAAqB,CAAM,EACtC,IAAW,IAAA,IACd,EAAa,KAAK,CAAM,CAE1B,CAEA,IAAM,EAAa,CAAC,GAAG,EAAc,G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GACpC,SAGD,GAAM,CAAE,SAAQ,mBAAoB,MAAM,EACzC,EACA,EACA,EACA,CACD,EACA,EAAa,KAAK,CAAM,EACxB,EAAmB,KAAK,GAAG,CAAe,EAEtC,EAAO,SAAW,UACrB,EAAoB,KAAK,CAAI,EACnB,EAAO,SAAW,iBAC5B,EAA0B,KAAK,CAAI,CAErC,CAGA,IAAM,EAAa,EAAoB,OAAS,EAC1C,EAAmB,EAA0B,OAAS,EAO5D,MAAO,CACN,GAAI,GACJ,MAAO,CACN,SATiC,GAEhC,GAAoB,IAAS,YAD7B,OAGC,QAMF,QAAS,CAAE,sBAAqB,2BAA0B,EAC1D,eACA,GAAI,EAAmB,OAAS,EAAI,CAAE,gBAAiB,CAAmB,EAAI,CAAC,CAChF,CACD,CACD"}
1
+ {"version":3,"file":"chain.js","names":[],"sources":["../../src/revocation/chain.ts"],"sourcesContent":["/**\n * Chain-level revocation orchestration.\n *\n * Evaluates CRL and OCSP evidence for an entire validated certificate chain,\n * implementing the revocation checking portion of RFC 5280 §6.3.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc5280#section-6.3 | RFC 5280 §6.3 CRL Validation}\n * @module\n */\n\nimport type { ParsedCertificate } from '#micro509/x509/parse.ts';\nimport { parseCertificateFromSource } from '#micro509/x509/parse.ts';\nimport {\n\tcheckCertificateRevocationAgainstCrl,\n\tparseCertificateRevocationListDerOrThrow,\n\tparseCertificateRevocationListPemOrThrow,\n\ttype ParsedCertificateRevocationList,\n\ttype RevocationReason,\n\trevocationReasonFromCode,\n} from './crl.ts';\nimport type { CrlSource } from './crl.ts';\nimport {\n\ttype OcspResponderRevocationPolicy,\n\ttype ParsedOcspResponse,\n\tparseOcspResponseDerOrThrow,\n\tparseOcspResponsePemOrThrow,\n\ttype ValidateOcspResponseFailure,\n\ttype ValidateOcspResponseResult,\n\tvalidateOcspResponse,\n} from './ocsp.ts';\n\nimport type { RevocationCertificateSource } from './revocation.ts';\n\nexport type { CrlSource };\n\n// ---------------------------------------------------------------------------\n// Input Types\n// ---------------------------------------------------------------------------\n\n/**\n * OCSP response in any supported format.\n *\n * Accepts PEM string or DER bytes. Used for\n * {@linkcode CheckChainRevocationInput.ocspResponses}.\n */\nexport type OcspResponseSource = string | Uint8Array;\n\n/**\n * Revocation checking policy for {@linkcode checkChainRevocation}.\n *\n * Controls how indeterminate results (missing evidence, expired CRLs) affect\n * the final {@linkcode CheckChainRevocationValue.decision | decision}.\n */\nexport interface RevocationPolicy {\n\t/**\n\t * How to handle indeterminate status.\n\t *\n\t * - `'hard-fail'`: indeterminate certificates cause denial (default)\n\t * - `'soft-fail'`: indeterminate certificates are allowed — an explicit\n\t * availability/compatibility choice\n\t *\n\t * Revocation checking itself is opt-in: no check runs unless evidence is\n\t * supplied. Once it is, indeterminate status denies by default.\n\t */\n\treadonly mode?: 'soft-fail' | 'hard-fail';\n\t/**\n\t * Evidence preference when multiple sources are available.\n\t *\n\t * Both evidence kinds are always evaluated, and a validated `revoked`\n\t * verdict from either source wins regardless of preference (fail-closed).\n\t * Preference only decides which source's `good` verdict is reported when\n\t * both yield one.\n\t *\n\t * - `'best-available'`: the source with the fresher evidence — the later\n\t * `thisUpdate` on the validated OCSP entry or CRL — is reported; ties\n\t * favor OCSP (default)\n\t * - `'ocsp'`: prefer OCSP over CRL\n\t * - `'crl'`: prefer CRL over OCSP\n\t */\n\treadonly prefer?: 'ocsp' | 'crl' | 'best-available';\n\t/**\n\t * Revocation policy for delegated OCSP responder certificates\n\t * (RFC 6960 §4.2.2.2.1). Supplied CRLs double as responder revocation\n\t * evidence. Defaults to `'honor-nocheck'`.\n\t */\n\treadonly ocspResponderRevocation?: OcspResponderRevocationPolicy;\n}\n\n/** Input for {@linkcode checkChainRevocation}. */\nexport interface CheckChainRevocationInput {\n\t/** Validated certificate chain (leaf first, root last). */\n\treadonly chain: readonly ParsedCertificate[];\n\t/** CRLs to evaluate. */\n\treadonly crls?: readonly CrlSource[];\n\t/** OCSP responses to evaluate. */\n\treadonly ocspResponses?: readonly OcspResponseSource[];\n\t/** Extra certs for indirect CRL issuers / delegated OCSP responders. */\n\treadonly extraCertificates?: readonly RevocationCertificateSource[];\n\t/**\n\t * Explicitly trusted OCSP responder certificates (RFC 6960 §4.2.2.2\n\t * criterion 1). A response signed by one of these is accepted without\n\t * delegated-responder issuance, EKU, and revocation checks.\n\t */\n\treadonly trustedOcspResponders?: readonly RevocationCertificateSource[];\n\t/** Evaluation time. Defaults to `new Date()`. */\n\treadonly at?: Date;\n\t/** Revocation policy. */\n\treadonly policy?: RevocationPolicy;\n}\n\n// ---------------------------------------------------------------------------\n// Output Types\n// ---------------------------------------------------------------------------\n\n/**\n * Granular reasons why revocation status could not be determined.\n *\n * Returned in {@linkcode CertificateRevocationStatus.indeterminateReasons} when\n * `status` is `'indeterminate'`. Grouped by category:\n *\n * - **Evidence not found**: `no_applicable_crl`, `no_applicable_ocsp`\n * - **Scope mismatch**: `distribution_point_mismatch`, `issuer_name_mismatch`,\n * `reason_scope_mismatch`, `indirect_crl_scope_mismatch`, `reason_coverage_incomplete`\n * - **Signer trust**: `crl_signer_not_found`, `crl_signer_not_authorized`,\n * `crl_signer_revoked`, `crl_signer_indeterminate`, and OCSP equivalents\n * - **Freshness**: `crl_expired`, `ocsp_response_expired`\n */\nexport const REVOCATION_INDETERMINATE_REASONS = [\n\t// Evidence not found\n\t'no_applicable_crl',\n\t'no_applicable_ocsp',\n\t// Scope issues\n\t'distribution_point_mismatch',\n\t'issuer_name_mismatch',\n\t'reason_scope_mismatch',\n\t'indirect_crl_scope_mismatch',\n\t'reason_coverage_incomplete',\n\t// Signer trust issues\n\t'crl_signer_not_found',\n\t'crl_signer_not_authorized',\n\t'crl_signer_revoked',\n\t'crl_signer_indeterminate',\n\t'ocsp_responder_not_found',\n\t'ocsp_responder_not_authorized',\n\t'ocsp_responder_revoked',\n\t'ocsp_responder_indeterminate',\n\t// Freshness\n\t'crl_expired',\n\t'ocsp_response_expired',\n\t// OCSP specific\n\t'ocsp_status_unknown',\n] as const;\n\n/** See the doc comment above {@linkcode REVOCATION_INDETERMINATE_REASONS}. */\nexport type RevocationIndeterminateReason = (typeof REVOCATION_INDETERMINATE_REASONS)[number];\n\n/**\n * Identifies the source of revocation evidence.\n *\n * Included in {@linkcode CertificateRevocationStatus.source} when status is\n * `'good'` or `'revoked'` to indicate which CRL or OCSP response provided the answer.\n */\nexport interface RevocationSource {\n\t/** Whether evidence came from a CRL or OCSP response. */\n\treadonly kind: 'crl' | 'ocsp';\n\t/** Certificate that signed the evidence (CRL issuer or OCSP responder). */\n\treadonly signerCertificate?: ParsedCertificate;\n\t/** Identifier for debugging (e.g., CRL issuer DN or OCSP responder URL). */\n\treadonly evidenceIdentifier?: string;\n\t/**\n\t * `thisUpdate` of the evidence backing the verdict — the OCSP single\n\t * response entry or the freshest contributing CRL (an applied delta CRL\n\t * supersedes its base). This is the timestamp `'best-available'` compares.\n\t */\n\treadonly thisUpdate?: Date;\n}\n\n/**\n * Revocation evaluation result for a single certificate.\n *\n * One entry per certificate in {@linkcode CheckChainRevocationValue.certificates}.\n * The trust anchor is excluded (never checked for revocation).\n */\nexport type CertificateRevocationStatus =\n\t| {\n\t\t\t/** The certificate that was evaluated. */\n\t\t\treadonly certificate: ParsedCertificate;\n\t\t\t/** Evidence confirms the certificate is not revoked. */\n\t\t\treadonly status: 'good';\n\t\t\t/** Evidence that produced the verdict. */\n\t\t\treadonly source: RevocationSource;\n\t\t\t/** Never present on a `good` verdict. */\n\t\t\treadonly indeterminateReasons?: undefined;\n\t\t\t/** Never present on a `good` verdict. */\n\t\t\treadonly revocationInfo?: undefined;\n\t }\n\t| {\n\t\t\t/** The certificate that was evaluated. */\n\t\t\treadonly certificate: ParsedCertificate;\n\t\t\t/** Evidence confirms the certificate is revoked. */\n\t\t\treadonly status: 'revoked';\n\t\t\t/** Evidence that produced the verdict. */\n\t\t\treadonly source: RevocationSource;\n\t\t\t/** Revocation details from the CRL entry or OCSP response. */\n\t\t\treadonly revocationInfo: {\n\t\t\t\t/** When the certificate was revoked. */\n\t\t\t\treadonly revocationDate: Date;\n\t\t\t\t/** RFC 5280 CRLReason code, if provided by the CRL/OCSP response. */\n\t\t\t\treadonly reason?: RevocationReason;\n\t\t\t};\n\t\t\t/** Never present on a `revoked` verdict. */\n\t\t\treadonly indeterminateReasons?: undefined;\n\t }\n\t| {\n\t\t\t/** The certificate that was evaluated. */\n\t\t\treadonly certificate: ParsedCertificate;\n\t\t\t/** Revocation status could not be determined. */\n\t\t\treadonly status: 'indeterminate';\n\t\t\t/** Why status could not be determined. */\n\t\t\treadonly indeterminateReasons: readonly RevocationIndeterminateReason[];\n\t\t\t/** Never present on an `indeterminate` verdict. */\n\t\t\treadonly source?: undefined;\n\t\t\t/** Never present on an `indeterminate` verdict. */\n\t\t\treadonly revocationInfo?: undefined;\n\t };\n\n/**\n * Errors encountered while processing revocation evidence.\n *\n * Distinct from {@linkcode RevocationIndeterminateReason}: execution errors are\n * code failures (malformed CRL, unsupported extension) rather than evaluation\n * outcomes (CRL doesn't cover this certificate).\n *\n * Collected in {@linkcode CheckChainRevocationValue.executionErrors}.\n */\nexport interface RevocationExecutionError {\n\t/** Error category. */\n\treadonly kind: 'parse_error' | 'unsupported_extension' | 'internal_error';\n\t/** Human-readable error description. */\n\treadonly message: string;\n\t/** Which evidence caused the error (e.g., CRL issuer DN). */\n\treadonly evidenceIdentifier?: string;\n}\n\n/**\n * Detailed revocation check results.\n *\n * Returned as {@linkcode CheckChainRevocationResult.value} from\n * {@linkcode checkChainRevocation}. Contains both the policy decision and\n * detailed per-certificate findings for debugging.\n */\nexport interface CheckChainRevocationValue {\n\t/**\n\t * Final policy decision based on {@linkcode RevocationPolicy}.\n\t *\n\t * - `'allow'`: chain passes revocation check\n\t * - `'deny'`: chain fails (revoked certificate or hard-fail on indeterminate)\n\t */\n\treadonly decision: 'allow' | 'deny';\n\t/** Quick-access summary of problematic certificates. */\n\treadonly summary: {\n\t\t/** Certificates confirmed as revoked. */\n\t\treadonly revokedCertificates: readonly ParsedCertificate[];\n\t\t/** Certificates whose status could not be determined. */\n\t\treadonly indeterminateCertificates: readonly ParsedCertificate[];\n\t};\n\t/** Per-certificate evaluation results. See {@linkcode CertificateRevocationStatus}. */\n\treadonly certificates: readonly CertificateRevocationStatus[];\n\t/** Evidence that could not be processed. See {@linkcode RevocationExecutionError}. */\n\treadonly executionErrors?: readonly RevocationExecutionError[];\n}\n\n/** Result type for {@linkcode checkChainRevocation}. */\nexport type CheckChainRevocationResult = {\n\treadonly ok: true;\n\treadonly value: CheckChainRevocationValue;\n};\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Parses a CRL from various source formats.\n */\nfunction parseCrlFromSource(source: CrlSource): ParsedCertificateRevocationList {\n\tif (typeof source === 'object' && 'issuer' in source) {\n\t\treturn source;\n\t}\n\tif (typeof source === 'string') {\n\t\treturn parseCertificateRevocationListPemOrThrow(source);\n\t}\n\treturn parseCertificateRevocationListDerOrThrow(source);\n}\n\n/**\n * Parses a certificate from various source formats, returning undefined on failure.\n */\nfunction parseCertificateSafe(source: RevocationCertificateSource): ParsedCertificate | undefined {\n\ttry {\n\t\treturn parseCertificateFromSource(source);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Compares two certificates by DER bytes for identity.\n * Reference equality fails when same cert is parsed from different sources.\n */\nfunction sameCertificate(a: ParsedCertificate, b: ParsedCertificate): boolean {\n\tif (a.der.length !== b.der.length) return false;\n\tfor (let i = 0; i < a.der.length; i++) {\n\t\tif (a.der[i] !== b.der[i]) return false;\n\t}\n\treturn true;\n}\n\n/**\n * Searches for a certificate that could have signed the given CRL.\n * Matches by AKI/SKI or issuer/subject DN.\n */\nfunction findIndirectCrlIssuer(\n\tcrl: ParsedCertificateRevocationList,\n\textraCertificates: readonly RevocationCertificateSource[],\n\tchain: readonly ParsedCertificate[],\n): ParsedCertificate | undefined {\n\t// Combine extra certs with chain certs for searching\n\t// Chain certs are already parsed; extra certs may need parsing\n\tconst parsedExtras: ParsedCertificate[] = [];\n\tfor (const source of extraCertificates) {\n\t\tconst parsed = parseCertificateSafe(source);\n\t\tif (parsed !== undefined) {\n\t\t\tparsedExtras.push(parsed);\n\t\t}\n\t}\n\n\tconst candidates = [...parsedExtras, ...chain];\n\n\t// First pass: prefer AKI/SKI match (more specific)\n\tif (crl.authorityKeyIdentifier !== undefined) {\n\t\tfor (const candidate of candidates) {\n\t\t\tif (\n\t\t\t\tcandidate.subjectKeyIdentifier !== undefined &&\n\t\t\t\tnormalizeHex(crl.authorityKeyIdentifier) === normalizeHex(candidate.subjectKeyIdentifier)\n\t\t\t) {\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Second pass: fall back to DN match\n\tfor (const candidate of candidates) {\n\t\tif (crl.issuer.derHex === candidate.subject.derHex) {\n\t\t\treturn candidate;\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\n/** Lowercases a hex string for bytewise comparison. */\nfunction normalizeHex(value: string): string {\n\treturn value.toLowerCase();\n}\n\n// ---------------------------------------------------------------------------\n// CRL Signer Validation (RFC 5280 §6.3.3)\n// ---------------------------------------------------------------------------\n\n/**\n * State machine for CRL signer validation with memoization.\n * - `visiting`: Currently being checked (cycle detection)\n * - `resolved-valid`: Signer is not revoked\n * - `resolved-revoked`: Signer is revoked\n * - `resolved-indeterminate`: Can't determine signer status\n */\ntype SignerValidationState =\n\t| 'visiting'\n\t| 'resolved-valid'\n\t| 'resolved-revoked'\n\t| 'resolved-indeterminate';\n\n/** Context for CRL signer validation with memoization cache. */\ninterface SignerValidationContext {\n\treadonly cache: Map<string, SignerValidationState>;\n\treadonly chain: readonly ParsedCertificate[];\n\treadonly crls: readonly CrlSource[];\n\treadonly extraCertificates: readonly RevocationCertificateSource[];\n\treadonly at: Date;\n}\n\n/**\n * Builds a unique cache key for a certificate.\n * Uses issuer DN + serial number which uniquely identifies a cert.\n */\nfunction certCacheKey(cert: ParsedCertificate): string {\n\treturn `${cert.issuer.derHex}:${cert.serialNumberHex}`;\n}\n\n/**\n * Validates that a CRL signer certificate is not revoked.\n * Uses memoization to avoid redundant checks and detect cycles.\n */\nasync function validateCrlSigner(\n\tsigner: ParsedCertificate,\n\tctx: SignerValidationContext,\n): Promise<SignerValidationState> {\n\t// Use issuer+serial as cache key (unique per certificate)\n\tconst key = certCacheKey(signer);\n\tconst cached = ctx.cache.get(key);\n\n\t// Cycle detection: if we're already visiting this signer, it's indeterminate\n\tif (cached === 'visiting') {\n\t\treturn 'resolved-indeterminate';\n\t}\n\n\t// Return cached result if already resolved\n\tif (cached !== undefined) {\n\t\treturn cached;\n\t}\n\n\t// Mark as visiting before recursive checks\n\tctx.cache.set(key, 'visiting');\n\n\t// Trust anchor (last in chain) is trusted by definition\n\tconst trustAnchor = ctx.chain[ctx.chain.length - 1];\n\tif (trustAnchor !== undefined && sameCertificate(signer, trustAnchor)) {\n\t\tctx.cache.set(key, 'resolved-valid');\n\t\treturn 'resolved-valid';\n\t}\n\n\t// If signer is in the validated chain, it's trusted\n\t// (Chain was already validated before revocation checking)\n\tconst isInChain = ctx.chain.some((c) => sameCertificate(c, signer));\n\tif (isInChain) {\n\t\tctx.cache.set(key, 'resolved-valid');\n\t\treturn 'resolved-valid';\n\t}\n\n\t// Signer is not in chain — need to check its revocation status\n\t// Find signer's issuer to perform revocation check\n\tconst signerIssuer = findSignerIssuer(signer, ctx);\n\tif (signerIssuer === undefined) {\n\t\tctx.cache.set(key, 'resolved-indeterminate');\n\t\treturn 'resolved-indeterminate';\n\t}\n\n\t// Check signer's revocation status (recursive)\n\tconst signerRevocation = await checkSignerRevocation(signer, signerIssuer, ctx);\n\tctx.cache.set(key, signerRevocation);\n\treturn signerRevocation;\n}\n\n/**\n * Finds the issuer certificate for a CRL signer.\n * Searches the chain and extraCertificates by AKI/SKI or DN matching.\n */\nfunction findSignerIssuer(\n\tsigner: ParsedCertificate,\n\tctx: SignerValidationContext,\n): ParsedCertificate | undefined {\n\t// Parse extra certificates\n\tconst parsedExtras: ParsedCertificate[] = [];\n\tfor (const source of ctx.extraCertificates) {\n\t\tconst parsed = parseCertificateSafe(source);\n\t\tif (parsed !== undefined) {\n\t\t\tparsedExtras.push(parsed);\n\t\t}\n\t}\n\n\tconst candidates = [...ctx.chain, ...parsedExtras];\n\n\tfor (const candidate of candidates) {\n\t\t// Match by AKI → SKI (preferred, more specific)\n\t\tif (\n\t\t\tsigner.authorityKeyIdentifier !== undefined &&\n\t\t\tcandidate.subjectKeyIdentifier !== undefined &&\n\t\t\tnormalizeHex(signer.authorityKeyIdentifier) === normalizeHex(candidate.subjectKeyIdentifier)\n\t\t) {\n\t\t\treturn candidate;\n\t\t}\n\n\t\t// Match by issuer DN → subject DN\n\t\tif (signer.issuer.derHex === candidate.subject.derHex) {\n\t\t\treturn candidate;\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Checks if a CRL signer certificate is revoked by examining available CRLs.\n * Recursively validates the CRL signer of any CRL used to check revocation.\n */\nasync function checkSignerRevocation(\n\tsigner: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tctx: SignerValidationContext,\n): Promise<SignerValidationState> {\n\t// If the signer's issuer is in the validated chain, the signer is trusted\n\t// by virtue of being issued by a trusted CA. We only need to check if\n\t// it's explicitly revoked, not prove \"good\" status.\n\tconst issuerInChain = ctx.chain.some((c) => sameCertificate(c, issuer));\n\n\t// Try each CRL to check signer's revocation\n\tfor (const crlSource of ctx.crls) {\n\t\tlet crl: ParsedCertificateRevocationList;\n\t\ttry {\n\t\t\tcrl = parseCrlFromSource(crlSource);\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Check if this CRL can provide revocation info for the signer\n\t\tconst result = await checkCertificateRevocationAgainstCrl({\n\t\t\tcertificate: signer,\n\t\t\tissuerCertificate: issuer,\n\t\t\tcrl,\n\t\t\tat: ctx.at,\n\t\t});\n\n\t\tif (result.ok) {\n\t\t\tif (result.value.status === 'revoked') {\n\t\t\t\treturn 'resolved-revoked';\n\t\t\t}\n\t\t\tif (result.value.status === 'good') {\n\t\t\t\t// Before accepting this result, validate the CRL's signer\n\t\t\t\t// The CRL's signer is the issuer we just used\n\t\t\t\tconst crlSignerStatus = await validateCrlSigner(issuer, ctx);\n\t\t\t\tif (crlSignerStatus === 'resolved-valid') {\n\t\t\t\t\treturn 'resolved-valid';\n\t\t\t\t}\n\t\t\t\t// If CRL signer is revoked or indeterminate, can't trust this result\n\t\t\t}\n\t\t}\n\t}\n\n\t// If the signer's issuer is in the chain and we found no revocation,\n\t// trust the signer (issued by trusted CA, no evidence of revocation)\n\tif (issuerInChain) {\n\t\treturn 'resolved-valid';\n\t}\n\n\treturn 'resolved-indeterminate';\n}\n\n/** Builds the `revoked` CertificateRevocationStatus for a CRL hit. */\nfunction buildCrlRevokedStatus(\n\tcert: ParsedCertificate,\n\tsigner: ParsedCertificate,\n\tthisUpdate: Date,\n\trevocationDate: Date,\n\treasonCode?: RevocationReason,\n): CertificateRevocationStatus {\n\treturn {\n\t\tcertificate: cert,\n\t\tstatus: 'revoked',\n\t\tsource: { kind: 'crl', signerCertificate: signer, thisUpdate },\n\t\trevocationInfo: {\n\t\t\trevocationDate,\n\t\t\t...(reasonCode !== undefined ? { reason: reasonCode } : {}),\n\t\t},\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// OCSP Evidence Evaluation (RFC 6960)\n// ---------------------------------------------------------------------------\n\n/** Per-certificate evidence evaluation outcome shared by the CRL and OCSP evaluators. */\ninterface EvidenceEvaluation {\n\treadonly status: CertificateRevocationStatus;\n\treadonly executionErrors: readonly RevocationExecutionError[];\n}\n\n/** Parses an OCSP response from PEM string or DER bytes. */\nfunction parseOcspResponseFromSource(source: OcspResponseSource): ParsedOcspResponse {\n\tif (typeof source === 'string') {\n\t\treturn parseOcspResponsePemOrThrow(source);\n\t}\n\treturn parseOcspResponseDerOrThrow(source);\n}\n\n/** Maps a {@linkcode validateOcspResponse} failure code to an indeterminate reason. */\nfunction ocspIndeterminateReasonFromFailure(\n\tcode: ValidateOcspResponseFailure['code'],\n): RevocationIndeterminateReason {\n\tswitch (code) {\n\t\tcase 'stale_response':\n\t\t\treturn 'ocsp_response_expired';\n\t\tcase 'responder_id_mismatch':\n\t\tcase 'responder_chain_invalid':\n\t\tcase 'ocsp_signing_missing':\n\t\t\treturn 'ocsp_responder_not_authorized';\n\t\tcase 'responder_revoked':\n\t\t\treturn 'ocsp_responder_revoked';\n\t\tcase 'signature_invalid':\n\t\tcase 'responder_revocation_unknown':\n\t\t\treturn 'ocsp_responder_indeterminate';\n\t\tcase 'response_status_invalid':\n\t\tcase 'issuer_mismatch':\n\t\tcase 'nonce_mismatch':\n\t\tcase 'request_mismatch':\n\t\t\treturn 'no_applicable_ocsp';\n\t}\n}\n\n/** Validation failures worth retrying with an explicit responder certificate. */\nconst OCSP_RESPONDER_FAILURE_CODES: ReadonlySet<ValidateOcspResponseFailure['code']> = new Set([\n\t'signature_invalid',\n\t'responder_id_mismatch',\n\t'responder_chain_invalid',\n\t'ocsp_signing_missing',\n]);\n\n/**\n * Validates an OCSP response, retrying with caller-provided extra certificates\n * as explicit responder certificates when embedded discovery fails.\n */\nasync function validateOcspResponseWithResponderFallback(\n\tresponse: ParsedOcspResponse,\n\tissuer: ParsedCertificate,\n\tinput: CheckChainRevocationInput,\n\tat: Date,\n): Promise<ValidateOcspResponseResult> {\n\tconst shared = {\n\t\tissuerCertificate: issuer,\n\t\tat,\n\t\t...(input.trustedOcspResponders !== undefined\n\t\t\t? { trustedOcspResponders: input.trustedOcspResponders }\n\t\t\t: {}),\n\t\t...(input.policy?.ocspResponderRevocation !== undefined\n\t\t\t? { responderRevocationPolicy: input.policy.ocspResponderRevocation }\n\t\t\t: {}),\n\t\t// Chain-level CRLs double as responder revocation evidence\n\t\t...(input.crls !== undefined ? { responderRevocationCrls: input.crls } : {}),\n\t};\n\tconst primary = await validateOcspResponse({ response, ...shared });\n\tif (primary.ok || !OCSP_RESPONDER_FAILURE_CODES.has(primary.code)) {\n\t\treturn primary;\n\t}\n\tfor (const source of input.extraCertificates ?? []) {\n\t\tconst responder = parseCertificateSafe(source);\n\t\tif (responder === undefined) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst retry = await validateOcspResponse({\n\t\t\tresponse,\n\t\t\t...shared,\n\t\t\tresponderCertificate: responder,\n\t\t});\n\t\tif (retry.ok) {\n\t\t\treturn retry;\n\t\t}\n\t}\n\treturn primary;\n}\n\n/**\n * Evaluates OCSP evidence for a single certificate (RFC 6960).\n *\n * Every response is fully validated — signature, responder binding and\n * authorization, and freshness — via {@linkcode validateOcspResponse} before\n * its status entry is trusted. Issuer binding of each CertID is enforced by\n * the validator, so a serial-number match on a validated response is\n * sufficient to attribute the entry to `cert`.\n */\nasync function evaluateOcspEvidence(\n\tcert: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tinput: CheckChainRevocationInput,\n): Promise<EvidenceEvaluation> {\n\tconst { ocspResponses = [], at = new Date() } = input;\n\tconst executionErrors: RevocationExecutionError[] = [];\n\tconst reasons = new Set<RevocationIndeterminateReason>();\n\n\tfor (const source of ocspResponses) {\n\t\tlet parsed: ParsedOcspResponse;\n\t\ttry {\n\t\t\tparsed = parseOcspResponseFromSource(source);\n\t\t} catch (e) {\n\t\t\texecutionErrors.push({\n\t\t\t\tkind: 'parse_error',\n\t\t\t\tmessage: e instanceof Error ? e.message : 'OCSP response parse failed',\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst entry = (parsed.responses ?? []).find(\n\t\t\t(single) =>\n\t\t\t\tnormalizeHex(single.certId.serialNumberHex) === normalizeHex(cert.serialNumberHex),\n\t\t);\n\t\tif (entry === undefined) {\n\t\t\tcontinue; // Response does not cover this certificate\n\t\t}\n\n\t\tconst validation = await validateOcspResponseWithResponderFallback(parsed, issuer, input, at);\n\t\tif (!validation.ok) {\n\t\t\treasons.add(ocspIndeterminateReasonFromFailure(validation.code));\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (entry.certStatus === 'revoked') {\n\t\t\tconst reason = revocationReasonFromCode(entry.revocationReasonCode);\n\t\t\treturn {\n\t\t\t\tstatus: {\n\t\t\t\t\tcertificate: cert,\n\t\t\t\t\tstatus: 'revoked',\n\t\t\t\t\tsource: { kind: 'ocsp', thisUpdate: entry.thisUpdate },\n\t\t\t\t\trevocationInfo: {\n\t\t\t\t\t\trevocationDate: entry.revokedAt ?? entry.thisUpdate,\n\t\t\t\t\t\t...(reason !== undefined ? { reason } : {}),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\texecutionErrors,\n\t\t\t};\n\t\t}\n\t\tif (entry.certStatus === 'good') {\n\t\t\treturn {\n\t\t\t\tstatus: {\n\t\t\t\t\tcertificate: cert,\n\t\t\t\t\tstatus: 'good',\n\t\t\t\t\tsource: { kind: 'ocsp', thisUpdate: entry.thisUpdate },\n\t\t\t\t},\n\t\t\t\texecutionErrors,\n\t\t\t};\n\t\t}\n\t\treasons.add('ocsp_status_unknown');\n\t}\n\n\tif (reasons.size === 0) {\n\t\treasons.add('no_applicable_ocsp');\n\t}\n\treturn {\n\t\tstatus: {\n\t\t\tcertificate: cert,\n\t\t\tstatus: 'indeterminate',\n\t\t\tindeterminateReasons: [...reasons],\n\t\t},\n\t\texecutionErrors,\n\t};\n}\n\n/**\n * Evaluates revocation status for a single certificate using available CRLs.\n * Returns both status and any execution errors encountered.\n *\n * Tries the chain issuer first; if that fails, searches extraCertificates\n * and chain for an indirect CRL issuer that matches the CRL's AKI or issuer DN.\n *\n * Also validates that CRL signers are not revoked (RFC 5280 §6.3.3).\n */\n// RFC 5280 ReasonFlags — all possible revocation reasons that CRLs can cover.\nconst ALL_REASON_FLAGS: readonly string[] = [\n\t'keyCompromise',\n\t'cACompromise',\n\t'affiliationChanged',\n\t'superseded',\n\t'cessationOfOperation',\n\t'certificateHold',\n\t'privilegeWithdrawn',\n\t'aACompromise',\n];\n\nasync function evaluateCrlEvidence(\n\tcert: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tinput: CheckChainRevocationInput,\n\tsignerCtx: SignerValidationContext,\n): Promise<EvidenceEvaluation> {\n\tconst { crls = [], extraCertificates = [], chain = [], at = new Date() } = input;\n\tconst executionErrors: RevocationExecutionError[] = [];\n\tlet sawCrlSignerRevoked = false;\n\tlet sawCrlSignerIndeterminate = false;\n\tlet sawGood = false;\n\t// Signer and thisUpdate are tracked together so the reported\n\t// signerCertificate always belongs to the CRL whose freshness is reported.\n\tlet freshestGood: { readonly signer: ParsedCertificate; readonly thisUpdate: Date } | undefined;\n\tconst coveredReasons = new Set<string>();\n\n\t// Parse all CRLs and separate base CRLs from delta CRLs\n\tconst parsedCrls: ParsedCertificateRevocationList[] = [];\n\tfor (const crlSource of crls) {\n\t\ttry {\n\t\t\tparsedCrls.push(parseCrlFromSource(crlSource));\n\t\t} catch (e) {\n\t\t\texecutionErrors.push({\n\t\t\t\tkind: 'parse_error',\n\t\t\t\tmessage: e instanceof Error ? e.message : 'CRL parse failed',\n\t\t\t});\n\t\t}\n\t}\n\n\tconst baseCrls = parsedCrls.filter((crl) => crl.baseCrlNumber === undefined);\n\tconst deltaCrls = parsedCrls.filter((crl) => crl.baseCrlNumber !== undefined);\n\n\t// Helper to check CRL with given issuer and optional delta\n\tconst checkWithIssuer = async (\n\t\tcrl: ParsedCertificateRevocationList,\n\t\tdeltaCrl: ParsedCertificateRevocationList | undefined,\n\t\tcrlIssuer: ParsedCertificate,\n\t) => {\n\t\treturn checkCertificateRevocationAgainstCrl({\n\t\t\tcertificate: cert,\n\t\t\tissuerCertificate: crlIssuer,\n\t\t\tcrl,\n\t\t\t...(deltaCrl !== undefined ? { deltaCrl } : {}),\n\t\t\tat,\n\t\t});\n\t};\n\n\t// Process base CRLs (optionally paired with delta CRLs)\n\tfor (const baseCrl of baseCrls) {\n\t\t// Find applicable delta CRL for this base CRL (if any)\n\t\t// Delta CRL applies if it has the same issuer and crlNumber matches baseCrlNumber\n\t\tconst applicableDelta = deltaCrls.find(\n\t\t\t(d) =>\n\t\t\t\td.issuer.derHex === baseCrl.issuer.derHex &&\n\t\t\t\td.baseCrlNumber !== undefined &&\n\t\t\t\tbaseCrl.crlNumber !== undefined &&\n\t\t\t\tBigInt(d.baseCrlNumber) <= BigInt(baseCrl.crlNumber),\n\t\t);\n\n\t\t// Try chain issuer first\n\t\tlet result = await checkWithIssuer(baseCrl, applicableDelta, issuer);\n\t\tlet effectiveSigner = issuer;\n\n\t\t// Chain issuer failed — try to find indirect CRL issuer\n\t\tif (!result.ok) {\n\t\t\tconst indirectIssuer = findIndirectCrlIssuer(baseCrl, extraCertificates, chain);\n\t\t\tif (indirectIssuer !== undefined && !sameCertificate(indirectIssuer, issuer)) {\n\t\t\t\tresult = await checkWithIssuer(baseCrl, applicableDelta, indirectIssuer);\n\t\t\t\teffectiveSigner = indirectIssuer;\n\t\t\t}\n\t\t}\n\n\t\tif (!result.ok) {\n\t\t\tcontinue; // CRL doesn't apply to this certificate\n\t\t}\n\n\t\t// Validate CRL signer is not revoked before accepting result\n\t\tconst signerStatus = await validateCrlSigner(effectiveSigner, signerCtx);\n\t\tif (signerStatus === 'resolved-revoked') {\n\t\t\tsawCrlSignerRevoked = true;\n\t\t\tcontinue; // CRL signer revoked — can't trust this CRL\n\t\t}\n\t\tif (signerStatus === 'resolved-indeterminate') {\n\t\t\tsawCrlSignerIndeterminate = true;\n\t\t\tcontinue; // CRL signer status unknown — try other CRLs\n\t\t}\n\n\t\t// Evidence freshness: an applied delta CRL supersedes its base\n\t\tconst crlThisUpdate =\n\t\t\tapplicableDelta !== undefined &&\n\t\t\tapplicableDelta.thisUpdate.getTime() > baseCrl.thisUpdate.getTime()\n\t\t\t\t? applicableDelta.thisUpdate\n\t\t\t\t: baseCrl.thisUpdate;\n\n\t\t// CRL is valid — check result\n\t\tif (result.value.status === 'revoked') {\n\t\t\t// Immediately return revoked status\n\t\t\treturn {\n\t\t\t\tstatus: buildCrlRevokedStatus(\n\t\t\t\t\tcert,\n\t\t\t\t\teffectiveSigner,\n\t\t\t\t\tcrlThisUpdate,\n\t\t\t\t\tresult.value.revocationDate,\n\t\t\t\t\tresult.value.reasonCode,\n\t\t\t\t),\n\t\t\t\texecutionErrors,\n\t\t\t};\n\t\t}\n\n\t\t// Status is 'good' — track which reasons this CRL covers\n\t\tsawGood = true;\n\t\tif (freshestGood === undefined || crlThisUpdate.getTime() > freshestGood.thisUpdate.getTime()) {\n\t\t\tfreshestGood = { signer: effectiveSigner, thisUpdate: crlThisUpdate };\n\t\t}\n\t\tconst crlReasons = baseCrl.issuingDistributionPoint?.onlySomeReasons?.flags;\n\t\tif (crlReasons === undefined) {\n\t\t\t// CRL covers all reasons\n\t\t\tfor (const reason of ALL_REASON_FLAGS) {\n\t\t\t\tcoveredReasons.add(reason);\n\t\t\t}\n\t\t} else {\n\t\t\t// CRL only covers specific reasons\n\t\t\tfor (const reason of crlReasons) {\n\t\t\t\tcoveredReasons.add(reason);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return 'good' only if we saw at least one good result AND all reasons are covered\n\tif (sawGood && freshestGood !== undefined) {\n\t\tconst allReasonsCovered = ALL_REASON_FLAGS.every((r) => coveredReasons.has(r));\n\t\tif (allReasonsCovered) {\n\t\t\treturn {\n\t\t\t\tstatus: {\n\t\t\t\t\tcertificate: cert,\n\t\t\t\t\tstatus: 'good',\n\t\t\t\t\tsource: {\n\t\t\t\t\t\tkind: 'crl',\n\t\t\t\t\t\tsignerCertificate: freshestGood.signer,\n\t\t\t\t\t\tthisUpdate: freshestGood.thisUpdate,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\texecutionErrors,\n\t\t\t};\n\t\t}\n\t\t// Not all reasons covered — indeterminate\n\t\treturn {\n\t\t\tstatus: {\n\t\t\t\tcertificate: cert,\n\t\t\t\tstatus: 'indeterminate',\n\t\t\t\tindeterminateReasons: ['reason_coverage_incomplete'],\n\t\t\t},\n\t\t\texecutionErrors,\n\t\t};\n\t}\n\n\t// No applicable CRL found — determine most appropriate indeterminate reason\n\tconst reasons: RevocationIndeterminateReason[] = [];\n\tif (sawCrlSignerRevoked) {\n\t\treasons.push('crl_signer_revoked');\n\t} else if (sawCrlSignerIndeterminate) {\n\t\treasons.push('crl_signer_indeterminate');\n\t} else {\n\t\treasons.push('no_applicable_crl');\n\t}\n\n\treturn {\n\t\tstatus: {\n\t\t\tcertificate: cert,\n\t\t\tstatus: 'indeterminate',\n\t\t\tindeterminateReasons: reasons,\n\t\t},\n\t\texecutionErrors,\n\t};\n}\n\n/**\n * Evaluates revocation status for a single certificate by combining OCSP and\n * CRL evidence.\n *\n * Both evidence kinds are always evaluated: a validated `revoked` verdict from\n * either source wins regardless of {@linkcode RevocationPolicy.prefer}\n * (fail-closed). Otherwise the preferred source's `good` verdict is reported —\n * for `'best-available'` the source with the later evidence `thisUpdate` wins,\n * ties favoring OCSP. If neither source is definitive, indeterminate reasons\n * from both are merged.\n */\nasync function evaluateCertificateRevocation(\n\tcert: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tinput: CheckChainRevocationInput,\n\tsignerCtx: SignerValidationContext,\n): Promise<EvidenceEvaluation> {\n\tconst prefer = input.policy?.prefer ?? 'best-available';\n\tconst ocsp = await evaluateOcspEvidence(cert, issuer, input);\n\tconst crl = await evaluateCrlEvidence(cert, issuer, input, signerCtx);\n\tconst executionErrors = [...ocsp.executionErrors, ...crl.executionErrors];\n\n\t// 'best-available' ranks by evidence freshness; the sort is stable, so\n\t// equal (or absent) thisUpdate keeps OCSP first.\n\tconst ordered =\n\t\tprefer === 'crl'\n\t\t\t? [crl, ocsp]\n\t\t\t: prefer === 'ocsp'\n\t\t\t\t? [ocsp, crl]\n\t\t\t\t: [ocsp, crl].sort(\n\t\t\t\t\t\t(a, b) =>\n\t\t\t\t\t\t\t(b.status.source?.thisUpdate?.getTime() ?? 0) -\n\t\t\t\t\t\t\t(a.status.source?.thisUpdate?.getTime() ?? 0),\n\t\t\t\t\t);\n\tconst revoked = ordered.find((evaluation) => evaluation.status.status === 'revoked');\n\tif (revoked !== undefined) {\n\t\treturn { status: revoked.status, executionErrors };\n\t}\n\tconst good = ordered.find((evaluation) => evaluation.status.status === 'good');\n\tif (good !== undefined) {\n\t\treturn { status: good.status, executionErrors };\n\t}\n\n\tconst reasons = new Set<RevocationIndeterminateReason>();\n\tfor (const evaluation of ordered) {\n\t\tfor (const reason of evaluation.status.indeterminateReasons ?? []) {\n\t\t\treasons.add(reason);\n\t\t}\n\t}\n\treturn {\n\t\tstatus: {\n\t\t\tcertificate: cert,\n\t\t\tstatus: 'indeterminate',\n\t\t\tindeterminateReasons: [...reasons],\n\t\t},\n\t\texecutionErrors,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Function\n// ---------------------------------------------------------------------------\n\n/**\n * Checks revocation status for all certificates in a validated chain.\n *\n * Evaluates CRL and OCSP evidence against each certificate (except the trust\n * anchor), applies the revocation policy, and returns a unified decision.\n *\n * @example\n * ```ts\n * const result = await checkChainRevocation({\n * chain: validatedChain,\n * crls: [crl1, crl2],\n * ocspResponses: [ocspResponseDer],\n * policy: { mode: 'hard-fail' },\n * });\n * if (result.value.decision === 'deny') {\n * console.log('Revocation check failed');\n * }\n * ```\n */\nexport async function checkChainRevocation(\n\tinput: CheckChainRevocationInput,\n): Promise<CheckChainRevocationResult> {\n\tconst { chain, policy, crls = [], extraCertificates = [], at = new Date() } = input;\n\tconst mode = policy?.mode ?? 'hard-fail';\n\n\t// Empty chain → allow\n\tif (chain.length === 0) {\n\t\treturn {\n\t\t\tok: true,\n\t\t\tvalue: {\n\t\t\t\tdecision: 'allow',\n\t\t\t\tsummary: { revokedCertificates: [], indeterminateCertificates: [] },\n\t\t\t\tcertificates: [],\n\t\t\t},\n\t\t};\n\t}\n\n\t// Create signer validation context with memoization cache\n\t// This cache is shared across all certificate checks in this chain evaluation\n\tconst signerCtx: SignerValidationContext = {\n\t\tcache: new Map(),\n\t\tchain,\n\t\tcrls,\n\t\textraCertificates,\n\t\tat,\n\t};\n\n\t// Skip trust anchor (last cert) — it's the trust base\n\tconst certsToCheck = chain.slice(0, -1);\n\tconst certificates: CertificateRevocationStatus[] = [];\n\tconst revokedCertificates: ParsedCertificate[] = [];\n\tconst indeterminateCertificates: ParsedCertificate[] = [];\n\tconst allExecutionErrors: RevocationExecutionError[] = [];\n\n\tfor (let i = 0; i < certsToCheck.length; i++) {\n\t\tconst cert = certsToCheck[i];\n\t\tconst issuer = chain[i + 1]; // Next cert in chain is the issuer\n\t\tif (cert === undefined || issuer === undefined) {\n\t\t\tcontinue; // Should never happen given loop bounds\n\t\t}\n\n\t\tconst { status, executionErrors } = await evaluateCertificateRevocation(\n\t\t\tcert,\n\t\t\tissuer,\n\t\t\tinput,\n\t\t\tsignerCtx,\n\t\t);\n\t\tcertificates.push(status);\n\t\tallExecutionErrors.push(...executionErrors);\n\n\t\tif (status.status === 'revoked') {\n\t\t\trevokedCertificates.push(cert);\n\t\t} else if (status.status === 'indeterminate') {\n\t\t\tindeterminateCertificates.push(cert);\n\t\t}\n\t}\n\n\t// Apply policy\n\tconst hasRevoked = revokedCertificates.length > 0;\n\tconst hasIndeterminate = indeterminateCertificates.length > 0;\n\tconst decision: 'allow' | 'deny' = hasRevoked\n\t\t? 'deny'\n\t\t: hasIndeterminate && mode === 'hard-fail'\n\t\t\t? 'deny'\n\t\t\t: 'allow';\n\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tdecision,\n\t\t\tsummary: { revokedCertificates, indeterminateCertificates },\n\t\t\tcertificates,\n\t\t\t...(allExecutionErrors.length > 0 ? { executionErrors: allExecutionErrors } : {}),\n\t\t},\n\t};\n}\n"],"mappings":"2WA+HA,MAAa,EAAmC,CAE/C,oBACA,qBAEA,8BACA,uBACA,wBACA,8BACA,6BAEA,uBACA,4BACA,qBACA,2BACA,2BACA,gCACA,yBACA,+BAEA,cACA,wBAEA,qBACD,EAsIA,SAAS,EAAmB,EAAoD,CAO/E,OANI,OAAO,GAAW,UAAY,WAAY,EACtC,EAEJ,OAAO,GAAW,S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