evlog 2.13.0 → 2.14.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 (89) hide show
  1. package/README.md +73 -0
  2. package/dist/adapters/axiom.d.mts +1 -1
  3. package/dist/adapters/better-stack.d.mts +1 -1
  4. package/dist/adapters/datadog.d.mts +1 -1
  5. package/dist/adapters/fs.d.mts +1 -1
  6. package/dist/adapters/hyperdx.d.mts +1 -1
  7. package/dist/adapters/otlp.d.mts +1 -1
  8. package/dist/adapters/posthog.d.mts +1 -1
  9. package/dist/adapters/sentry.d.mts +1 -1
  10. package/dist/ai/index.d.mts +106 -5
  11. package/dist/ai/index.d.mts.map +1 -1
  12. package/dist/ai/index.mjs +28 -5
  13. package/dist/ai/index.mjs.map +1 -1
  14. package/dist/{logger-DnobymUQ.mjs → audit-d9esRZOK.mjs} +703 -4
  15. package/dist/audit-d9esRZOK.mjs.map +1 -0
  16. package/dist/{types-DbzDln7O.d.mts → audit-mUutdf6A.d.mts} +499 -3
  17. package/dist/audit-mUutdf6A.d.mts.map +1 -0
  18. package/dist/better-auth/index.d.mts +1 -1
  19. package/dist/browser.d.mts +1 -1
  20. package/dist/elysia/index.d.mts +2 -2
  21. package/dist/elysia/index.mjs +2 -2
  22. package/dist/enrichers.d.mts +1 -1
  23. package/dist/{error-B9CiGK_i.d.mts → error-D1FZI2Kd.d.mts} +2 -2
  24. package/dist/{error-B9CiGK_i.d.mts.map → error-D1FZI2Kd.d.mts.map} +1 -1
  25. package/dist/error.d.mts +1 -1
  26. package/dist/{errors-Dr0r4OpR.d.mts → errors-NIXCyk6I.d.mts} +2 -2
  27. package/dist/{errors-Dr0r4OpR.d.mts.map → errors-NIXCyk6I.d.mts.map} +1 -1
  28. package/dist/express/index.d.mts +2 -2
  29. package/dist/express/index.mjs +2 -2
  30. package/dist/fastify/index.d.mts +2 -2
  31. package/dist/fastify/index.mjs +2 -2
  32. package/dist/{fork-Y4z8iHti.mjs → fork-CTJXnpl8.mjs} +3 -3
  33. package/dist/{fork-Y4z8iHti.mjs.map → fork-CTJXnpl8.mjs.map} +1 -1
  34. package/dist/hono/index.d.mts +2 -2
  35. package/dist/hono/index.mjs +1 -1
  36. package/dist/http.d.mts +1 -1
  37. package/dist/index.d.mts +7 -7
  38. package/dist/index.mjs +2 -2
  39. package/dist/{logger-Dp6nYWjH.d.mts → logger-b3epPH0N.d.mts} +4 -4
  40. package/dist/logger-b3epPH0N.d.mts.map +1 -0
  41. package/dist/logger.d.mts +1 -1
  42. package/dist/logger.mjs +1 -1
  43. package/dist/{middleware-BtBuosFV.mjs → middleware-BWOJ7JI0.mjs} +2 -2
  44. package/dist/{middleware-BtBuosFV.mjs.map → middleware-BWOJ7JI0.mjs.map} +1 -1
  45. package/dist/{middleware-FgC1OdOD.d.mts → middleware-BYf26Lfu.d.mts} +2 -2
  46. package/dist/{middleware-FgC1OdOD.d.mts.map → middleware-BYf26Lfu.d.mts.map} +1 -1
  47. package/dist/nestjs/index.d.mts +2 -2
  48. package/dist/nestjs/index.mjs +2 -2
  49. package/dist/next/client.d.mts +1 -1
  50. package/dist/next/index.d.mts +4 -4
  51. package/dist/next/index.mjs +2 -2
  52. package/dist/next/instrumentation.d.mts +1 -1
  53. package/dist/next/instrumentation.mjs +1 -1
  54. package/dist/nitro/module.d.mts +2 -2
  55. package/dist/nitro/plugin.mjs +1 -1
  56. package/dist/nitro/v3/index.d.mts +2 -2
  57. package/dist/nitro/v3/module.d.mts +1 -1
  58. package/dist/nitro/v3/plugin.mjs +1 -1
  59. package/dist/nitro/v3/useLogger.d.mts +1 -1
  60. package/dist/{nitro-CDHLfRdw.d.mts → nitro-DenB86W6.d.mts} +2 -2
  61. package/dist/{nitro-CDHLfRdw.d.mts.map → nitro-DenB86W6.d.mts.map} +1 -1
  62. package/dist/nuxt/module.d.mts +1 -1
  63. package/dist/nuxt/module.mjs +1 -1
  64. package/dist/{parseError-DM-lyezZ.d.mts → parseError-BR9pocvY.d.mts} +2 -2
  65. package/dist/parseError-BR9pocvY.d.mts.map +1 -0
  66. package/dist/react-router/index.d.mts +2 -2
  67. package/dist/react-router/index.mjs +2 -2
  68. package/dist/runtime/client/log.d.mts +1 -1
  69. package/dist/runtime/server/routes/_evlog/ingest.post.mjs +1 -1
  70. package/dist/runtime/server/useLogger.d.mts +1 -1
  71. package/dist/runtime/utils/parseError.d.mts +2 -2
  72. package/dist/sveltekit/index.d.mts +2 -2
  73. package/dist/sveltekit/index.mjs +2 -2
  74. package/dist/toolkit.d.mts +3 -3
  75. package/dist/toolkit.mjs +2 -2
  76. package/dist/types.d.mts +2 -2
  77. package/dist/{useLogger-N5A-d5l9.d.mts → useLogger-C56tDPwf.d.mts} +2 -2
  78. package/dist/{useLogger-N5A-d5l9.d.mts.map → useLogger-C56tDPwf.d.mts.map} +1 -1
  79. package/dist/{utils-DnX6VMNi.d.mts → utils-DzGCLRFe.d.mts} +2 -2
  80. package/dist/{utils-DnX6VMNi.d.mts.map → utils-DzGCLRFe.d.mts.map} +1 -1
  81. package/dist/utils.d.mts +1 -1
  82. package/dist/vite/index.d.mts +1 -1
  83. package/dist/workers.d.mts +1 -1
  84. package/dist/workers.mjs +1 -1
  85. package/package.json +1 -1
  86. package/dist/logger-DnobymUQ.mjs.map +0 -1
  87. package/dist/logger-Dp6nYWjH.d.mts.map +0 -1
  88. package/dist/parseError-DM-lyezZ.d.mts.map +0 -1
  89. package/dist/types-DbzDln7O.d.mts.map +0 -1
@@ -23,7 +23,7 @@ const builtinPatterns = {
23
23
  mask: (m) => `***.***.***.${m.split(".").pop()}`
24
24
  },
25
25
  phone: {
26
- pattern: /(?:\+\d{1,3}[\s.-]?)?\(?\d{1,4}\)?[\s.-]?\d{2,4}[\s.-]?\d{2,4}[\s.-]?\d{2,4}\b/g,
26
+ pattern: /(?:\+\d{1,3}[\s.-]?\(?\d{1,4}\)?|\(\d{1,4}\))(?:[\s.-]?\d{2,4}){2,4}\b/g,
27
27
  mask: (m) => {
28
28
  const digits = m.replace(/[^\d]/g, "");
29
29
  if (m.startsWith("+") && digits.length > 4) {
@@ -310,6 +310,7 @@ function emitWideEvent(level, event, deferDrain = false, ownsEvent = false) {
310
310
  ...globalEnv,
311
311
  ...event
312
312
  };
313
+ finalizeAudit(formatted);
313
314
  if (globalRedact) redactEvent(formatted, globalRedact);
314
315
  if (!globalSilent) if (globalPretty) prettyPrintWideEvent(formatted);
315
316
  else if (globalStringify) console[getConsoleMethod(level)](JSON.stringify(formatted));
@@ -584,7 +585,8 @@ const noopLogger = {
584
585
  },
585
586
  getContext() {
586
587
  return {};
587
- }
588
+ },
589
+ audit: Object.assign(() => {}, { deny: () => {} })
588
590
  };
589
591
  /**
590
592
  * Create a scoped logger for building wide events.
@@ -617,7 +619,25 @@ function createLogger(initialContext = {}, internalOptions) {
617
619
  timestamp: isoNow()
618
620
  });
619
621
  }
622
+ const auditMethod = function audit(input) {
623
+ if (emitted) {
624
+ warnPostEmit("log.audit()", `Audit dropped: action=${input.action}.`);
625
+ return;
626
+ }
627
+ const fields = buildAuditFields(input);
628
+ if (!isPlainObject(context.audit)) context.audit = fields;
629
+ else mergeInto(context.audit, fields);
630
+ context._auditForceKeep = true;
631
+ };
632
+ auditMethod.deny = function deny(reason, input) {
633
+ auditMethod({
634
+ ...input,
635
+ outcome: "denied",
636
+ reason
637
+ });
638
+ };
620
639
  return {
640
+ audit: auditMethod,
621
641
  set(data) {
622
642
  if (emitted) {
623
643
  const keys = Object.keys(data);
@@ -684,6 +704,7 @@ function createLogger(initialContext = {}, internalOptions) {
684
704
  const level = hasError ? "error" : hasWarn ? "warn" : "info";
685
705
  let forceKeep = false;
686
706
  if (overrides?._forceKeep) forceKeep = true;
707
+ else if (consumeAuditForceKeep(context)) forceKeep = true;
687
708
  else if (globalSampling.keep?.length) forceKeep = shouldKeep({
688
709
  status: overrides?.status ?? context.status,
689
710
  duration: durationMs,
@@ -736,6 +757,684 @@ function getEnvironment() {
736
757
  }
737
758
  if (typeof __EVLOG_CONFIG__ !== "undefined") initLogger(__EVLOG_CONFIG__);
738
759
  //#endregion
739
- export { getGlobalDrain as a, isLoggerLocked as c, normalizeRedactConfig as d, redactEvent as f, getEnvironment as i, lockLogger as l, createLogger as n, initLogger as o, resolveRedactConfig as p, createRequestLogger as r, isEnabled as s, _log as t, shouldKeep as u };
760
+ //#region src/audit.ts
761
+ /**
762
+ * Current version of the audit envelope. Bumped when `AuditFields` evolves
763
+ * in a backward-incompatible way so downstream pipelines can branch on it.
764
+ */
765
+ const AUDIT_SCHEMA_VERSION = 1;
766
+ /**
767
+ * @internal Stable JSON stringification with deterministic key order.
768
+ * Used by `idempotencyKey` and `hash-chain` so the same logical event always
769
+ * produces the same digest, regardless of how object keys were added.
770
+ */
771
+ function stableStringify(value) {
772
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
773
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
774
+ return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(",")}}`;
775
+ }
776
+ /**
777
+ * @internal Sync, isomorphic 32-bit FNV-1a. Used to derive the idempotency
778
+ * key without pulling `node:crypto` into the static import graph (which would
779
+ * break browser / Cloudflare Workers bundles that import `evlog` for types
780
+ * or shared utilities). Idempotency keys are dedup tokens, not security
781
+ * primitives — collision resistance at 128 bits is more than sufficient.
782
+ */
783
+ function fnv1a32(input, seed) {
784
+ let h = seed >>> 0;
785
+ for (let i = 0; i < input.length; i++) {
786
+ h ^= input.charCodeAt(i) & 255;
787
+ h = Math.imul(h, 16777619) >>> 0;
788
+ }
789
+ return h >>> 0;
790
+ }
791
+ /**
792
+ * @internal Compute the deterministic idempotency key for an audit event.
793
+ * Includes `action`, `actor.{type,id}`, `target.{type,id}`, `outcome`, and
794
+ * `timestamp` rounded to the second so retries within the same second collapse.
795
+ *
796
+ * Uses four interleaved FNV-1a 32-bit hashes (128-bit output, 32 hex chars)
797
+ * so the implementation stays sync and isomorphic across Node, browsers,
798
+ * Bun, Deno, and Cloudflare Workers.
799
+ */
800
+ function computeIdempotencyKey(audit, timestamp) {
801
+ const seconds = timestamp.slice(0, 19);
802
+ const payload = stableStringify({
803
+ action: audit.action,
804
+ actor: {
805
+ type: audit.actor.type,
806
+ id: audit.actor.id
807
+ },
808
+ target: audit.target ? {
809
+ type: audit.target.type,
810
+ id: audit.target.id
811
+ } : void 0,
812
+ outcome: audit.outcome,
813
+ timestamp: seconds
814
+ });
815
+ const a = fnv1a32(payload, 2166136261).toString(16).padStart(8, "0");
816
+ const b = fnv1a32(payload, 3735928559).toString(16).padStart(8, "0");
817
+ const c = fnv1a32(payload, 528734635).toString(16).padStart(8, "0");
818
+ const d = fnv1a32(payload, 1541459225).toString(16).padStart(8, "0");
819
+ return a + b + c + d;
820
+ }
821
+ /**
822
+ * Build a normalised {@link AuditFields} from caller input. Defaults:
823
+ * - `outcome` → `'success'`
824
+ * - `version` → {@link AUDIT_SCHEMA_VERSION}
825
+ *
826
+ * `idempotencyKey` is filled at emit time with the event timestamp so retries
827
+ * stay deterministic.
828
+ */
829
+ function buildAuditFields(input) {
830
+ return {
831
+ action: input.action,
832
+ actor: input.actor,
833
+ target: input.target,
834
+ outcome: input.outcome ?? "success",
835
+ reason: input.reason,
836
+ changes: input.changes,
837
+ causationId: input.causationId,
838
+ correlationId: input.correlationId,
839
+ version: input.version ?? 1
840
+ };
841
+ }
842
+ /**
843
+ * @internal Test-collector hook installed by {@link mockAudit}. When set, every
844
+ * audit event flowing through `log.audit()` / `audit()` is also pushed to it.
845
+ */
846
+ let _testCollector = null;
847
+ /** @internal Emit-time decoration: assign timestamp-based idempotency key. */
848
+ function decorateAudit(audit, timestamp) {
849
+ if (audit.idempotencyKey) return audit;
850
+ return {
851
+ ...audit,
852
+ idempotencyKey: computeIdempotencyKey(audit, timestamp)
853
+ };
854
+ }
855
+ /**
856
+ * Add audit semantics to an existing {@link RequestLogger}.
857
+ *
858
+ * Mutates the logger in place by adding an `audit` method (with a `.deny()`
859
+ * sub-method). Strictly equivalent to calling `log.set({ audit: ... })` plus
860
+ * `_forceKeep` on emit. Idempotent: calling twice on the same logger only
861
+ * attaches the methods once.
862
+ *
863
+ * @example
864
+ * ```ts
865
+ * const log = withAuditMethods(createLogger())
866
+ * log.audit({
867
+ * action: 'invoice.refund',
868
+ * actor: { type: 'user', id: user.id },
869
+ * target: { type: 'invoice', id: 'inv_889' },
870
+ * })
871
+ * ```
872
+ */
873
+ function withAuditMethods(logger) {
874
+ const target = logger;
875
+ if (target.audit) return target;
876
+ const audit = function audit(input) {
877
+ const fields = buildAuditFields(input);
878
+ target.set({ audit: fields });
879
+ markForceKeep(target);
880
+ };
881
+ audit.deny = function deny(reason, input) {
882
+ audit({
883
+ ...input,
884
+ outcome: "denied",
885
+ reason
886
+ });
887
+ };
888
+ target.audit = audit;
889
+ return target;
890
+ }
891
+ /**
892
+ * @internal Mark a logger so its next `emit()` is force-kept past tail sampling.
893
+ * Implemented by stamping a hidden flag on the accumulated context which
894
+ * `emit()` reads via `_forceKeep`.
895
+ */
896
+ function markForceKeep(logger) {
897
+ const ctx = logger.getContext();
898
+ ctx._auditForceKeep = true;
899
+ }
900
+ /**
901
+ * Standalone audit emitter for non-request contexts (jobs, scripts, CLIs).
902
+ *
903
+ * Creates a one-shot logger, sets the audit fields, and emits immediately.
904
+ * The event is force-kept past tail sampling. Returns the emitted wide event,
905
+ * or `null` if logging is globally disabled.
906
+ *
907
+ * @example
908
+ * ```ts
909
+ * import { audit } from 'evlog'
910
+ *
911
+ * audit({
912
+ * action: 'cron.cleanup',
913
+ * actor: { type: 'system', id: 'cron' },
914
+ * target: { type: 'job', id: 'cleanup-stale-sessions' },
915
+ * outcome: 'success',
916
+ * })
917
+ * ```
918
+ */
919
+ function audit(input) {
920
+ const fields = buildAuditFields(input);
921
+ const wide = createLogger({ audit: fields }).emit({ _forceKeep: true });
922
+ _testCollector?.(fields, wide);
923
+ return wide;
924
+ }
925
+ /**
926
+ * Wrap a function so its outcome (success / failure / denied) is automatically
927
+ * audited.
928
+ *
929
+ * Behaviour:
930
+ * - If `fn` resolves, an audit event with `outcome: 'success'` is emitted.
931
+ * - If `fn` throws an `EvlogError` (or any error) with `status === 403`, the
932
+ * audit event is recorded as `'denied'` with the error message as `reason`.
933
+ * - Any other thrown error produces `outcome: 'failure'` and re-throws.
934
+ *
935
+ * Use {@link AuditDeniedError} to signal denial without an HTTP status.
936
+ *
937
+ * @example
938
+ * ```ts
939
+ * const refundInvoice = withAudit(
940
+ * { action: 'invoice.refund', target: (input) => ({ type: 'invoice', id: input.id }) },
941
+ * async (input: { id: string }, ctx: { actor: AuditActor }) => {
942
+ * await db.invoices.refund(input.id)
943
+ * }
944
+ * )
945
+ *
946
+ * await refundInvoice({ id: 'inv_889' }, { actor: { type: 'user', id: user.id } })
947
+ * ```
948
+ */
949
+ function withAudit(options, fn) {
950
+ return async (input, ctx) => {
951
+ const target = typeof options.target === "function" ? options.target(input) : options.target;
952
+ try {
953
+ const result = await fn(input, ctx);
954
+ audit({
955
+ action: options.action,
956
+ actor: ctx.actor,
957
+ target,
958
+ outcome: "success",
959
+ causationId: ctx.causationId,
960
+ correlationId: ctx.correlationId
961
+ });
962
+ return result;
963
+ } catch (err) {
964
+ const error = err;
965
+ const status = error.status ?? error.statusCode;
966
+ const denied = err instanceof AuditDeniedError || status === 403;
967
+ audit({
968
+ action: options.action,
969
+ actor: ctx.actor,
970
+ target,
971
+ outcome: denied ? "denied" : "failure",
972
+ reason: error.message,
973
+ causationId: ctx.causationId,
974
+ correlationId: ctx.correlationId
975
+ });
976
+ throw err;
977
+ }
978
+ };
979
+ }
980
+ /**
981
+ * Throw inside a {@link withAudit} body to mark the action as `outcome: 'denied'`
982
+ * regardless of the underlying HTTP status. The constructor message becomes the
983
+ * audit `reason`.
984
+ */
985
+ var AuditDeniedError = class extends Error {
986
+ constructor(reason) {
987
+ super(reason);
988
+ this.name = "AuditDeniedError";
989
+ }
990
+ };
991
+ /**
992
+ * Compute a compact, redact-aware diff between two objects for the
993
+ * `changes` field. Output is a JSON Patch-style array (RFC 6902 subset:
994
+ * `add`, `remove`, `replace`) — small enough to ship over the wire.
995
+ *
996
+ * Object keys whose name matches one of the `redactPaths` (dot-notation, e.g.
997
+ * `'user.password'`, `'card.cvv'`) are replaced with `'[REDACTED]'` so PII
998
+ * never leaks through the diff.
999
+ *
1000
+ * @example
1001
+ * ```ts
1002
+ * log.audit({
1003
+ * action: 'user.update',
1004
+ * actor: { type: 'user', id: user.id },
1005
+ * target: { type: 'user', id: 'usr_42' },
1006
+ * changes: auditDiff(before, after, { redactPaths: ['password'] }),
1007
+ * })
1008
+ * ```
1009
+ */
1010
+ function auditDiff(before, after, options = {}) {
1011
+ const replacement = options.replacement ?? "[REDACTED]";
1012
+ const redactSet = new Set((options.redactPaths ?? []).map((p) => p));
1013
+ const patch = [];
1014
+ function isRedacted(path) {
1015
+ if (redactSet.size === 0) return false;
1016
+ if (redactSet.has(path)) return true;
1017
+ for (const p of redactSet) if (path.endsWith(`.${p}`)) return true;
1018
+ return false;
1019
+ }
1020
+ function diff(a, b, path) {
1021
+ if (a === b) return;
1022
+ if (a === void 0 && b !== void 0) {
1023
+ patch.push({
1024
+ op: "add",
1025
+ path: path || "/",
1026
+ value: redactValue(b, path)
1027
+ });
1028
+ return;
1029
+ }
1030
+ if (a !== void 0 && b === void 0) {
1031
+ patch.push({
1032
+ op: "remove",
1033
+ path: path || "/"
1034
+ });
1035
+ return;
1036
+ }
1037
+ if (a !== null && b !== null && typeof a === "object" && typeof b === "object" && !Array.isArray(a) && !Array.isArray(b)) {
1038
+ const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
1039
+ for (const key of keys) diff(a[key], b[key], `${path}/${key}`);
1040
+ return;
1041
+ }
1042
+ patch.push({
1043
+ op: "replace",
1044
+ path: path || "/",
1045
+ value: redactValue(b, path)
1046
+ });
1047
+ }
1048
+ function redactValue(value, path) {
1049
+ if (value === null || typeof value !== "object") {
1050
+ const segs = path.split("/").filter(Boolean);
1051
+ const last = segs[segs.length - 1];
1052
+ if (last && isRedacted(last)) return replacement;
1053
+ return value;
1054
+ }
1055
+ if (Array.isArray(value)) return value.map((v, i) => redactValue(v, `${path}/${i}`));
1056
+ const out = {};
1057
+ for (const [k, v] of Object.entries(value)) out[k] = isRedacted(k) ? replacement : redactValue(v, `${path}/${k}`);
1058
+ return out;
1059
+ }
1060
+ diff(before, after, "");
1061
+ const result = { patch };
1062
+ if (options.includeBefore) result.before = redactValue(before, "");
1063
+ if (options.includeAfter) result.after = redactValue(after, "");
1064
+ return result;
1065
+ }
1066
+ /**
1067
+ * Define a typed audit action with an optional fixed target type.
1068
+ *
1069
+ * Returns a curried helper that fills in the action name (and target shape
1070
+ * if provided) so call sites stay terse and the action set is discoverable
1071
+ * in one place.
1072
+ *
1073
+ * @example
1074
+ * ```ts
1075
+ * const refund = defineAuditAction('invoice.refund', { target: 'invoice' })
1076
+ *
1077
+ * log.audit(refund({
1078
+ * actor: { type: 'user', id: user.id },
1079
+ * target: { id: 'inv_889' }, // type inferred as 'invoice'
1080
+ * outcome: 'success',
1081
+ * }))
1082
+ * ```
1083
+ */
1084
+ function defineAuditAction(action, options) {
1085
+ const targetType = options?.target;
1086
+ return (input) => {
1087
+ const merged = {
1088
+ ...input,
1089
+ action
1090
+ };
1091
+ if (targetType && input.target && !input.target.type) merged.target = {
1092
+ ...input.target,
1093
+ type: targetType
1094
+ };
1095
+ return merged;
1096
+ };
1097
+ }
1098
+ /**
1099
+ * Test helper that captures every audit event emitted while it is active.
1100
+ *
1101
+ * Returns `{ events, restore, expect }`:
1102
+ * - `events` — live array of captured `AuditFields`, populated as audits fire.
1103
+ * - `restore()` — uninstall the collector. Call from `afterEach()`.
1104
+ * - `expect.toIncludeAuditOf(matcher)` — assertion helper used inside `expect`
1105
+ * blocks, returns `true` if at least one captured event matches.
1106
+ *
1107
+ * Only captures audits going through `log.audit()` and the standalone
1108
+ * `audit()` function. Events emitted via raw `log.set({ audit })` skip the
1109
+ * collector by design — wrap them with `log.audit()` to make them visible to
1110
+ * tests.
1111
+ *
1112
+ * @example
1113
+ * ```ts
1114
+ * const captured = mockAudit()
1115
+ * await refundInvoice('inv_889')
1116
+ * expect(captured.events).toHaveLength(1)
1117
+ * expect(captured.toIncludeAuditOf({ action: 'invoice.refund' })).toBe(true)
1118
+ * captured.restore()
1119
+ * ```
1120
+ */
1121
+ function mockAudit() {
1122
+ const events = [];
1123
+ const previous = _testCollector;
1124
+ _testCollector = (event) => {
1125
+ events.push(event);
1126
+ };
1127
+ return {
1128
+ events,
1129
+ restore() {
1130
+ _testCollector = previous;
1131
+ },
1132
+ toIncludeAuditOf(matcher) {
1133
+ return events.some((event) => matchesAudit(event, matcher));
1134
+ }
1135
+ };
1136
+ }
1137
+ function matchesAudit(event, matcher) {
1138
+ if (matcher.action !== void 0) {
1139
+ if (matcher.action instanceof RegExp) {
1140
+ if (!matcher.action.test(event.action)) return false;
1141
+ } else if (event.action !== matcher.action) return false;
1142
+ }
1143
+ if (matcher.outcome !== void 0 && event.outcome !== matcher.outcome) return false;
1144
+ if (matcher.actor) {
1145
+ for (const [k, v] of Object.entries(matcher.actor)) if (event.actor[k] !== v) return false;
1146
+ }
1147
+ if (matcher.target) {
1148
+ if (!event.target) return false;
1149
+ for (const [k, v] of Object.entries(matcher.target)) if (event.target[k] !== v) return false;
1150
+ }
1151
+ return true;
1152
+ }
1153
+ /**
1154
+ * @internal Hook used by `RequestLogger.emit()` to detect audit-driven
1155
+ * force-keep flags on the accumulated context. Returns whether the event was
1156
+ * marked by `log.audit()` and clears the flag.
1157
+ */
1158
+ function consumeAuditForceKeep(context) {
1159
+ if (context._auditForceKeep) {
1160
+ delete context._auditForceKeep;
1161
+ return true;
1162
+ }
1163
+ if (context.audit) return true;
1164
+ return false;
1165
+ }
1166
+ /**
1167
+ * @internal Decorate the audit field on an event right before drain — fills
1168
+ * in the deterministic idempotency key. Called by the logger pipeline so
1169
+ * it works for both `log.audit()` and direct `log.set({ audit })` paths.
1170
+ */
1171
+ function finalizeAudit(event) {
1172
+ const a = event.audit;
1173
+ if (!a) return;
1174
+ event.audit = decorateAudit(a, String(event.timestamp));
1175
+ }
1176
+ /**
1177
+ * Enrich audit-bearing wide events with request, runtime, and tenant context.
1178
+ *
1179
+ * Runs only when `event.audit` is present — every other event passes through
1180
+ * untouched. Populates:
1181
+ * - `event.audit.context.requestId` from `ctx.request.requestId`
1182
+ * - `event.audit.context.traceId` from `event.traceId`
1183
+ * - `event.audit.context.ip` from `x-forwarded-for` / `x-real-ip`
1184
+ * - `event.audit.context.userAgent` from `user-agent`
1185
+ * - `event.audit.context.tenantId` from `options.tenantId(ctx)`
1186
+ *
1187
+ * Optionally fills `event.audit.actor` from the better-auth bridge when the
1188
+ * caller did not provide one. Anything else (custom actor strategies,
1189
+ * extra context) belongs in a custom enricher — replace this one entirely.
1190
+ */
1191
+ function auditEnricher(options = {}) {
1192
+ return async (ctx) => {
1193
+ const event = ctx.event;
1194
+ const a = event.audit;
1195
+ if (!a) return;
1196
+ const context = { ...a.context ?? {} };
1197
+ function setIfMissing(key, value) {
1198
+ if (value === void 0) return;
1199
+ if (options.overwrite || context[key] === void 0) context[key] = value;
1200
+ }
1201
+ setIfMissing("requestId", ctx.request?.requestId);
1202
+ setIfMissing("traceId", typeof event.traceId === "string" ? event.traceId : void 0);
1203
+ setIfMissing("ip", getHeader(ctx.headers, "x-forwarded-for")?.split(",")[0]?.trim() ?? getHeader(ctx.headers, "x-real-ip"));
1204
+ setIfMissing("userAgent", getHeader(ctx.headers, "user-agent"));
1205
+ if (options.tenantId) {
1206
+ const tid = options.tenantId(ctx);
1207
+ if (tid !== void 0) setIfMissing("tenantId", tid);
1208
+ }
1209
+ let { actor } = a;
1210
+ if (!actor && options.bridge) {
1211
+ const fromBridge = await options.bridge.getSession(ctx);
1212
+ if (fromBridge) actor = fromBridge;
1213
+ }
1214
+ event.audit = {
1215
+ ...a,
1216
+ context,
1217
+ actor: actor ?? a.actor
1218
+ };
1219
+ };
1220
+ }
1221
+ function getHeader(headers, name) {
1222
+ if (!headers) return void 0;
1223
+ if (headers[name] !== void 0) return headers[name];
1224
+ const lower = name.toLowerCase();
1225
+ if (headers[lower] !== void 0) return headers[lower];
1226
+ for (const [k, v] of Object.entries(headers)) if (k.toLowerCase() === lower) return v;
1227
+ }
1228
+ /**
1229
+ * Wrap any drain so it only receives events that carry an `audit` field.
1230
+ *
1231
+ * Use to route audit events to dedicated storage (separate Axiom dataset,
1232
+ * append-only Postgres table, FS journal) without affecting your main drain.
1233
+ *
1234
+ * Per-sink failure isolation comes from `initLogger({ drain: [...] })`: each
1235
+ * drain in the array is invoked independently, so a crashed Axiom call never
1236
+ * blocks the FS audit drain.
1237
+ *
1238
+ * @example
1239
+ * ```ts
1240
+ * import { initLogger, auditOnly } from 'evlog'
1241
+ * import { createAxiomDrain } from 'evlog/axiom'
1242
+ * import { createFsDrain } from 'evlog/fs'
1243
+ *
1244
+ * initLogger({
1245
+ * drain: [
1246
+ * createAxiomDrain({ dataset: 'logs' }),
1247
+ * auditOnly(createFsDrain({ dir: '.audit' }), { await: true }),
1248
+ * ],
1249
+ * })
1250
+ * ```
1251
+ */
1252
+ function auditOnly(drain, options = {}) {
1253
+ return async (ctx) => {
1254
+ if (!ctx.event.audit) return;
1255
+ if (options.await) {
1256
+ await drain(ctx);
1257
+ return;
1258
+ }
1259
+ drain(ctx);
1260
+ };
1261
+ }
1262
+ /**
1263
+ * Wrap a drain so every event passing through gains tamper-evident integrity.
1264
+ *
1265
+ * - `'hmac'` — adds `event.audit.signature` (HMAC of the canonical event).
1266
+ * - `'hash-chain'` — adds `event.audit.prevHash` and `event.audit.hash` so the
1267
+ * sequence of events forms a verifiable chain. State persists in memory
1268
+ * by default; pass a `state: { load, save }` for cross-process / durable
1269
+ * chains (Redis, file, Postgres).
1270
+ *
1271
+ * The signature is computed before the event is forwarded to the wrapped
1272
+ * drain — combine with {@link auditOnly} when you only want integrity for
1273
+ * audit events.
1274
+ *
1275
+ * @example
1276
+ * ```ts
1277
+ * import { initLogger, auditOnly, signed } from 'evlog'
1278
+ * import { createFsDrain } from 'evlog/fs'
1279
+ *
1280
+ * initLogger({
1281
+ * drain: auditOnly(
1282
+ * signed(createFsDrain({ dir: '.audit' }), { strategy: 'hash-chain' }),
1283
+ * { await: true },
1284
+ * ),
1285
+ * })
1286
+ * ```
1287
+ */
1288
+ function signed(drain, options) {
1289
+ if (options.strategy === "hmac") {
1290
+ const algorithm = options.algorithm ?? "sha256";
1291
+ const { secret } = options;
1292
+ return async (ctx) => {
1293
+ const a = ctx.event.audit;
1294
+ if (a) {
1295
+ const signature = await hmacHex(algorithm, secret, stableStringify(stripIntegrity(ctx.event)));
1296
+ ctx.event.audit = {
1297
+ ...a,
1298
+ signature
1299
+ };
1300
+ }
1301
+ await drain(ctx);
1302
+ };
1303
+ }
1304
+ const algorithm = options.algorithm ?? "sha256";
1305
+ const { state } = options;
1306
+ let inMemoryPrev = null;
1307
+ let initialised = !state;
1308
+ let queue = Promise.resolve();
1309
+ return (ctx) => {
1310
+ queue = queue.then(async () => {
1311
+ const a = ctx.event.audit;
1312
+ if (a) {
1313
+ if (!initialised && state) {
1314
+ inMemoryPrev = await state.load() ?? null;
1315
+ initialised = true;
1316
+ }
1317
+ const prevHash = inMemoryPrev ?? void 0;
1318
+ const hash = await digestHex(algorithm, stableStringify({
1319
+ ...stripIntegrity(ctx.event),
1320
+ audit: {
1321
+ ...stripIntegrity(ctx.event).audit,
1322
+ prevHash
1323
+ }
1324
+ }));
1325
+ ctx.event.audit = {
1326
+ ...a,
1327
+ prevHash,
1328
+ hash
1329
+ };
1330
+ inMemoryPrev = hash;
1331
+ await state?.save(hash);
1332
+ }
1333
+ await drain(ctx);
1334
+ }).catch((err) => {
1335
+ console.error("[evlog/audit] signed drain failed:", err);
1336
+ });
1337
+ return queue;
1338
+ };
1339
+ }
1340
+ /**
1341
+ * @internal Resolve the Web Crypto SubtleCrypto interface. Available natively
1342
+ * in browsers, Node 19+, Bun, Deno, and Cloudflare Workers. Falls back to
1343
+ * Node's `webcrypto` for Node 18 (where `globalThis.crypto` is gated behind
1344
+ * a flag). The dynamic import keeps `node:crypto` out of browser bundles.
1345
+ */
1346
+ async function getSubtle() {
1347
+ const c = globalThis.crypto;
1348
+ if (c?.subtle) return c.subtle;
1349
+ return (await import(
1350
+ /* @vite-ignore */
1351
+ "node:crypto"
1352
+ )).webcrypto.subtle;
1353
+ }
1354
+ function normalizeAlgo(algorithm) {
1355
+ switch (algorithm.toLowerCase()) {
1356
+ case "sha1":
1357
+ case "sha-1": return "SHA-1";
1358
+ case "sha256":
1359
+ case "sha-256": return "SHA-256";
1360
+ case "sha384":
1361
+ case "sha-384": return "SHA-384";
1362
+ case "sha512":
1363
+ case "sha-512": return "SHA-512";
1364
+ default: return "SHA-256";
1365
+ }
1366
+ }
1367
+ function bufToHex(buf) {
1368
+ let out = "";
1369
+ for (const byte of new Uint8Array(buf)) out += byte.toString(16).padStart(2, "0");
1370
+ return out;
1371
+ }
1372
+ async function digestHex(algorithm, data) {
1373
+ return bufToHex(await (await getSubtle()).digest(normalizeAlgo(algorithm), new TextEncoder().encode(data)));
1374
+ }
1375
+ async function hmacHex(algorithm, secret, data) {
1376
+ const subtle = await getSubtle();
1377
+ const hash = normalizeAlgo(algorithm);
1378
+ const key = await subtle.importKey("raw", new TextEncoder().encode(secret), {
1379
+ name: "HMAC",
1380
+ hash
1381
+ }, false, ["sign"]);
1382
+ return bufToHex(await subtle.sign("HMAC", key, new TextEncoder().encode(data)));
1383
+ }
1384
+ /** @internal Strip integrity fields before hashing so signatures stay stable. */
1385
+ function stripIntegrity(event) {
1386
+ const a = event.audit;
1387
+ if (!a) return event;
1388
+ const { signature, prevHash, hash, ...rest } = a;
1389
+ return {
1390
+ ...event,
1391
+ audit: rest
1392
+ };
1393
+ }
1394
+ /**
1395
+ * Strict redact preset for audit events.
1396
+ *
1397
+ * Combine with the user's existing redact configuration via spread:
1398
+ * `initLogger({ redact: { paths: [...auditRedactPreset.paths!, ...mine] } })`.
1399
+ *
1400
+ * Hardens PII handling:
1401
+ * - Drops `Authorization` and `Cookie` headers anywhere they appear.
1402
+ * - Drops common credential field names (`password`, `passwordHash`, `token`,
1403
+ * `apiKey`, `secret`, `accessToken`, `refreshToken`, `cardNumber`, `cvv`,
1404
+ * `ssn`).
1405
+ *
1406
+ * Built-in pattern maskers (email, credit card, …) keep their default
1407
+ * behaviour — partial masking, not full redaction — so audit trails retain
1408
+ * enough signal to be useful.
1409
+ */
1410
+ const auditRedactPreset = { paths: [
1411
+ "audit.changes.before.password",
1412
+ "audit.changes.before.passwordHash",
1413
+ "audit.changes.before.token",
1414
+ "audit.changes.before.apiKey",
1415
+ "audit.changes.before.secret",
1416
+ "audit.changes.before.accessToken",
1417
+ "audit.changes.before.refreshToken",
1418
+ "audit.changes.before.cardNumber",
1419
+ "audit.changes.before.cvv",
1420
+ "audit.changes.before.ssn",
1421
+ "audit.changes.after.password",
1422
+ "audit.changes.after.passwordHash",
1423
+ "audit.changes.after.token",
1424
+ "audit.changes.after.apiKey",
1425
+ "audit.changes.after.secret",
1426
+ "audit.changes.after.accessToken",
1427
+ "audit.changes.after.refreshToken",
1428
+ "audit.changes.after.cardNumber",
1429
+ "audit.changes.after.cvv",
1430
+ "audit.changes.after.ssn",
1431
+ "headers.authorization",
1432
+ "headers.cookie",
1433
+ "headers.set-cookie",
1434
+ "audit.context.headers.authorization",
1435
+ "audit.context.headers.cookie"
1436
+ ] };
1437
+ //#endregion
1438
+ export { shouldKeep as C, resolveRedactConfig as E, lockLogger as S, redactEvent as T, getEnvironment as _, auditEnricher as a, isEnabled as b, buildAuditFields as c, signed as d, withAudit as f, createRequestLogger as g, createLogger as h, auditDiff as i, defineAuditAction as l, _log as m, AuditDeniedError as n, auditOnly as o, withAuditMethods as p, audit as r, auditRedactPreset as s, AUDIT_SCHEMA_VERSION as t, mockAudit as u, getGlobalDrain as v, normalizeRedactConfig as w, isLoggerLocked as x, initLogger as y };
740
1439
 
741
- //# sourceMappingURL=logger-DnobymUQ.mjs.map
1440
+ //# sourceMappingURL=audit-d9esRZOK.mjs.map