@xtandard/audit 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +386 -2
- package/bin/xtandard-audit.mjs +3 -0
- package/dist/basic-DU_nPrWV.mjs +176 -0
- package/dist/basic-DU_nPrWV.mjs.map +1 -0
- package/dist/basic-hcXnMF9X.cjs +199 -0
- package/dist/basic-hcXnMF9X.cjs.map +1 -0
- package/dist/canonical-BOgkrX9_.d.cts +17 -0
- package/dist/canonical-CL7gfwhb.d.mts +17 -0
- package/dist/chunk-D7D4PA-g.mjs +13 -0
- package/dist/cli.cjs +773 -0
- package/dist/cli.cjs.map +1 -0
- package/dist/cli.d.cts +46 -0
- package/dist/cli.d.mts +46 -0
- package/dist/cli.mjs +762 -0
- package/dist/cli.mjs.map +1 -0
- package/dist/context-BtR9k9Mt.d.mts +52 -0
- package/dist/context-CJM87uG8.d.cts +52 -0
- package/dist/context-shared-AgBWIRUQ.d.mts +29 -0
- package/dist/context-shared-CUq3cSpV.d.cts +29 -0
- package/dist/context-shared-CupikwQo.mjs +39 -0
- package/dist/context-shared-CupikwQo.mjs.map +1 -0
- package/dist/context-shared-X2ulHHSB.cjs +44 -0
- package/dist/context-shared-X2ulHHSB.cjs.map +1 -0
- package/dist/context.cjs +82 -0
- package/dist/context.cjs.map +1 -0
- package/dist/context.d.cts +2 -0
- package/dist/context.d.mts +2 -0
- package/dist/context.mjs +78 -0
- package/dist/context.mjs.map +1 -0
- package/dist/contract-BljSE-Hx.mjs +33 -0
- package/dist/contract-BljSE-Hx.mjs.map +1 -0
- package/dist/contract-BmwHIiMR.d.mts +150 -0
- package/dist/contract-CWJSYoJl.d.cts +150 -0
- package/dist/contract-Cht05WYQ.d.mts +159 -0
- package/dist/contract-CqYQzB6e.d.cts +49 -0
- package/dist/contract-DYvBNdnR.cjs +74 -0
- package/dist/contract-DYvBNdnR.cjs.map +1 -0
- package/dist/contract-DlTo4u2t.d.cts +30 -0
- package/dist/contract-DlTo4u2t.d.mts +30 -0
- package/dist/contract-DsVL5-gy.cjs +50 -0
- package/dist/contract-DsVL5-gy.cjs.map +1 -0
- package/dist/contract-isM9SjjQ.mjs +39 -0
- package/dist/contract-isM9SjjQ.mjs.map +1 -0
- package/dist/contract-pU3wGFmo.d.cts +159 -0
- package/dist/contract-yPNuFnVy.d.mts +49 -0
- package/dist/core-C0ceVOTk.d.cts +513 -0
- package/dist/core-CTr7dw0v.cjs +1725 -0
- package/dist/core-CTr7dw0v.cjs.map +1 -0
- package/dist/core-IdGEbYdM.mjs +1541 -0
- package/dist/core-IdGEbYdM.mjs.map +1 -0
- package/dist/core-KtEHRScZ.d.mts +513 -0
- package/dist/core.cjs +9 -0
- package/dist/core.d.cts +2 -0
- package/dist/core.d.mts +2 -0
- package/dist/core.mjs +2 -0
- package/dist/create-fetch-handler-1pXSEhGi.d.cts +311 -0
- package/dist/create-fetch-handler-BwQQ_IWf.mjs +2156 -0
- package/dist/create-fetch-handler-BwQQ_IWf.mjs.map +1 -0
- package/dist/create-fetch-handler-D8cTMVX9.cjs +2232 -0
- package/dist/create-fetch-handler-D8cTMVX9.cjs.map +1 -0
- package/dist/create-fetch-handler-zioPVS18.d.mts +311 -0
- package/dist/elysia-shared-C7geKqPP.mjs +55 -0
- package/dist/elysia-shared-C7geKqPP.mjs.map +1 -0
- package/dist/elysia-shared-DT4bfekR.d.cts +20 -0
- package/dist/elysia-shared-DXyAyGz_.cjs +66 -0
- package/dist/elysia-shared-DXyAyGz_.cjs.map +1 -0
- package/dist/elysia-shared-DoL5ab52.d.mts +20 -0
- package/dist/entry-auth-basic.cjs +5 -0
- package/dist/entry-auth-basic.d.cts +83 -0
- package/dist/entry-auth-basic.d.mts +83 -0
- package/dist/entry-auth-basic.mjs +2 -0
- package/dist/entry-auth-delegated.cjs +28 -0
- package/dist/entry-auth-delegated.cjs.map +1 -0
- package/dist/entry-auth-delegated.d.cts +36 -0
- package/dist/entry-auth-delegated.d.mts +36 -0
- package/dist/entry-auth-delegated.mjs +27 -0
- package/dist/entry-auth-delegated.mjs.map +1 -0
- package/dist/entry-auth-none.cjs +4 -0
- package/dist/entry-auth-none.d.cts +25 -0
- package/dist/entry-auth-none.d.mts +25 -0
- package/dist/entry-auth-none.mjs +2 -0
- package/dist/entry-authorization-delegated.cjs +28 -0
- package/dist/entry-authorization-delegated.cjs.map +1 -0
- package/dist/entry-authorization-delegated.d.cts +32 -0
- package/dist/entry-authorization-delegated.d.mts +32 -0
- package/dist/entry-authorization-delegated.mjs +27 -0
- package/dist/entry-authorization-delegated.mjs.map +1 -0
- package/dist/entry-authorization-none.cjs +3 -0
- package/dist/entry-authorization-none.d.cts +18 -0
- package/dist/entry-authorization-none.d.mts +18 -0
- package/dist/entry-authorization-none.mjs +2 -0
- package/dist/entry-authorization-roles.cjs +8 -0
- package/dist/entry-authorization-roles.d.cts +64 -0
- package/dist/entry-authorization-roles.d.mts +64 -0
- package/dist/entry-authorization-roles.mjs +3 -0
- package/dist/entry-bun.cjs +55 -0
- package/dist/entry-bun.cjs.map +1 -0
- package/dist/entry-bun.d.cts +29 -0
- package/dist/entry-bun.d.mts +29 -0
- package/dist/entry-bun.mjs +52 -0
- package/dist/entry-bun.mjs.map +1 -0
- package/dist/entry-drizzle-audit.cjs +191 -0
- package/dist/entry-drizzle-audit.cjs.map +1 -0
- package/dist/entry-drizzle-audit.d.cts +118 -0
- package/dist/entry-drizzle-audit.d.mts +118 -0
- package/dist/entry-drizzle-audit.mjs +186 -0
- package/dist/entry-drizzle-audit.mjs.map +1 -0
- package/dist/entry-drizzle-mysql.cjs +75 -0
- package/dist/entry-drizzle-mysql.cjs.map +1 -0
- package/dist/entry-drizzle-mysql.d.cts +42 -0
- package/dist/entry-drizzle-mysql.d.mts +42 -0
- package/dist/entry-drizzle-mysql.mjs +71 -0
- package/dist/entry-drizzle-mysql.mjs.map +1 -0
- package/dist/entry-drizzle-pg.cjs +82 -0
- package/dist/entry-drizzle-pg.cjs.map +1 -0
- package/dist/entry-drizzle-pg.d.cts +48 -0
- package/dist/entry-drizzle-pg.d.mts +48 -0
- package/dist/entry-drizzle-pg.mjs +78 -0
- package/dist/entry-drizzle-pg.mjs.map +1 -0
- package/dist/entry-drizzle-sqlite.cjs +71 -0
- package/dist/entry-drizzle-sqlite.cjs.map +1 -0
- package/dist/entry-drizzle-sqlite.d.cts +37 -0
- package/dist/entry-drizzle-sqlite.d.mts +37 -0
- package/dist/entry-drizzle-sqlite.mjs +67 -0
- package/dist/entry-drizzle-sqlite.mjs.map +1 -0
- package/dist/entry-elysia.cjs +112 -0
- package/dist/entry-elysia.cjs.map +1 -0
- package/dist/entry-elysia.d.cts +710 -0
- package/dist/entry-elysia.d.mts +710 -0
- package/dist/entry-elysia.mjs +109 -0
- package/dist/entry-elysia.mjs.map +1 -0
- package/dist/entry-elysia2.cjs +101 -0
- package/dist/entry-elysia2.cjs.map +1 -0
- package/dist/entry-elysia2.d.cts +905 -0
- package/dist/entry-elysia2.d.mts +905 -0
- package/dist/entry-elysia2.mjs +98 -0
- package/dist/entry-elysia2.mjs.map +1 -0
- package/dist/entry-express.cjs +90 -0
- package/dist/entry-express.cjs.map +1 -0
- package/dist/entry-express.d.cts +24 -0
- package/dist/entry-express.d.mts +24 -0
- package/dist/entry-express.mjs +88 -0
- package/dist/entry-express.mjs.map +1 -0
- package/dist/entry-hono.cjs +36 -0
- package/dist/entry-hono.cjs.map +1 -0
- package/dist/entry-hono.d.cts +24 -0
- package/dist/entry-hono.d.mts +24 -0
- package/dist/entry-hono.mjs +34 -0
- package/dist/entry-hono.mjs.map +1 -0
- package/dist/entry-hooks-log.cjs +22 -0
- package/dist/entry-hooks-log.cjs.map +1 -0
- package/dist/entry-hooks-log.d.cts +23 -0
- package/dist/entry-hooks-log.d.mts +23 -0
- package/dist/entry-hooks-log.mjs +21 -0
- package/dist/entry-hooks-log.mjs.map +1 -0
- package/dist/entry-sinks-console.cjs +43 -0
- package/dist/entry-sinks-console.cjs.map +1 -0
- package/dist/entry-sinks-console.d.cts +26 -0
- package/dist/entry-sinks-console.d.mts +26 -0
- package/dist/entry-sinks-console.mjs +41 -0
- package/dist/entry-sinks-console.mjs.map +1 -0
- package/dist/entry-sinks-datadog.cjs +97 -0
- package/dist/entry-sinks-datadog.cjs.map +1 -0
- package/dist/entry-sinks-datadog.d.cts +66 -0
- package/dist/entry-sinks-datadog.d.mts +66 -0
- package/dist/entry-sinks-datadog.mjs +91 -0
- package/dist/entry-sinks-datadog.mjs.map +1 -0
- package/dist/entry-sinks-file.cjs +100 -0
- package/dist/entry-sinks-file.cjs.map +1 -0
- package/dist/entry-sinks-file.d.cts +70 -0
- package/dist/entry-sinks-file.d.mts +70 -0
- package/dist/entry-sinks-file.mjs +97 -0
- package/dist/entry-sinks-file.mjs.map +1 -0
- package/dist/entry-sinks-http.cjs +63 -0
- package/dist/entry-sinks-http.cjs.map +1 -0
- package/dist/entry-sinks-http.d.cts +55 -0
- package/dist/entry-sinks-http.d.mts +55 -0
- package/dist/entry-sinks-http.mjs +60 -0
- package/dist/entry-sinks-http.mjs.map +1 -0
- package/dist/entry-sinks-s3.cjs +115 -0
- package/dist/entry-sinks-s3.cjs.map +1 -0
- package/dist/entry-sinks-s3.d.cts +79 -0
- package/dist/entry-sinks-s3.d.mts +79 -0
- package/dist/entry-sinks-s3.mjs +112 -0
- package/dist/entry-sinks-s3.mjs.map +1 -0
- package/dist/entry-sinks-splunk.cjs +80 -0
- package/dist/entry-sinks-splunk.cjs.map +1 -0
- package/dist/entry-sinks-splunk.d.cts +58 -0
- package/dist/entry-sinks-splunk.d.mts +58 -0
- package/dist/entry-sinks-splunk.mjs +77 -0
- package/dist/entry-sinks-splunk.mjs.map +1 -0
- package/dist/entry-sinks-webhook.cjs +130 -0
- package/dist/entry-sinks-webhook.cjs.map +1 -0
- package/dist/entry-sinks-webhook.d.cts +69 -0
- package/dist/entry-sinks-webhook.d.mts +69 -0
- package/dist/entry-sinks-webhook.mjs +125 -0
- package/dist/entry-sinks-webhook.mjs.map +1 -0
- package/dist/entry-sinks-xtandard-webhooks.cjs +64 -0
- package/dist/entry-sinks-xtandard-webhooks.cjs.map +1 -0
- package/dist/entry-sinks-xtandard-webhooks.d.cts +64 -0
- package/dist/entry-sinks-xtandard-webhooks.d.mts +64 -0
- package/dist/entry-sinks-xtandard-webhooks.mjs +63 -0
- package/dist/entry-sinks-xtandard-webhooks.mjs.map +1 -0
- package/dist/entry-storage-cloudflare-kv.cjs +47 -0
- package/dist/entry-storage-cloudflare-kv.cjs.map +1 -0
- package/dist/entry-storage-cloudflare-kv.d.cts +42 -0
- package/dist/entry-storage-cloudflare-kv.d.mts +42 -0
- package/dist/entry-storage-cloudflare-kv.mjs +46 -0
- package/dist/entry-storage-cloudflare-kv.mjs.map +1 -0
- package/dist/entry-storage-drizzle.cjs +228 -0
- package/dist/entry-storage-drizzle.cjs.map +1 -0
- package/dist/entry-storage-drizzle.d.cts +43 -0
- package/dist/entry-storage-drizzle.d.mts +43 -0
- package/dist/entry-storage-drizzle.mjs +227 -0
- package/dist/entry-storage-drizzle.mjs.map +1 -0
- package/dist/entry-storage-file.cjs +175 -0
- package/dist/entry-storage-file.cjs.map +1 -0
- package/dist/entry-storage-file.d.cts +41 -0
- package/dist/entry-storage-file.d.mts +41 -0
- package/dist/entry-storage-file.mjs +171 -0
- package/dist/entry-storage-file.mjs.map +1 -0
- package/dist/entry-storage-libsql.cjs +133 -0
- package/dist/entry-storage-libsql.cjs.map +1 -0
- package/dist/entry-storage-libsql.d.cts +60 -0
- package/dist/entry-storage-libsql.d.mts +60 -0
- package/dist/entry-storage-libsql.mjs +132 -0
- package/dist/entry-storage-libsql.mjs.map +1 -0
- package/dist/entry-storage-memory.cjs +3 -0
- package/dist/entry-storage-memory.d.cts +2 -0
- package/dist/entry-storage-memory.d.mts +2 -0
- package/dist/entry-storage-memory.mjs +2 -0
- package/dist/entry-storage-mongodb.cjs +306 -0
- package/dist/entry-storage-mongodb.cjs.map +1 -0
- package/dist/entry-storage-mongodb.d.cts +65 -0
- package/dist/entry-storage-mongodb.d.mts +65 -0
- package/dist/entry-storage-mongodb.mjs +304 -0
- package/dist/entry-storage-mongodb.mjs.map +1 -0
- package/dist/entry-storage-postgres.cjs +261 -0
- package/dist/entry-storage-postgres.cjs.map +1 -0
- package/dist/entry-storage-postgres.d.cts +66 -0
- package/dist/entry-storage-postgres.d.mts +66 -0
- package/dist/entry-storage-postgres.mjs +260 -0
- package/dist/entry-storage-postgres.mjs.map +1 -0
- package/dist/entry-storage-redis.cjs +223 -0
- package/dist/entry-storage-redis.cjs.map +1 -0
- package/dist/entry-storage-redis.d.cts +77 -0
- package/dist/entry-storage-redis.d.mts +77 -0
- package/dist/entry-storage-redis.mjs +221 -0
- package/dist/entry-storage-redis.mjs.map +1 -0
- package/dist/entry-storage-sqlite.cjs +85 -0
- package/dist/entry-storage-sqlite.cjs.map +1 -0
- package/dist/entry-storage-sqlite.d.cts +40 -0
- package/dist/entry-storage-sqlite.d.mts +40 -0
- package/dist/entry-storage-sqlite.mjs +84 -0
- package/dist/entry-storage-sqlite.mjs.map +1 -0
- package/dist/entry-storage-unstorage.cjs +57 -0
- package/dist/entry-storage-unstorage.cjs.map +1 -0
- package/dist/entry-storage-unstorage.d.cts +29 -0
- package/dist/entry-storage-unstorage.d.mts +29 -0
- package/dist/entry-storage-unstorage.mjs +56 -0
- package/dist/entry-storage-unstorage.mjs.map +1 -0
- package/dist/export-B9S-JeYl.mjs +239 -0
- package/dist/export-B9S-JeYl.mjs.map +1 -0
- package/dist/export-BZq0KCCn.d.mts +70 -0
- package/dist/export-DYfMd-ep.cjs +280 -0
- package/dist/export-DYfMd-ep.cjs.map +1 -0
- package/dist/export-Dh8T8I1p.d.cts +70 -0
- package/dist/index.cjs +279 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +286 -0
- package/dist/index.d.mts +284 -0
- package/dist/index.mjs +177 -0
- package/dist/index.mjs.map +1 -0
- package/dist/integrity-BHhjTBNk.cjs +614 -0
- package/dist/integrity-BHhjTBNk.cjs.map +1 -0
- package/dist/integrity-kfY2DNAi.mjs +483 -0
- package/dist/integrity-kfY2DNAi.mjs.map +1 -0
- package/dist/memory-CfykUo9W.cjs +155 -0
- package/dist/memory-CfykUo9W.cjs.map +1 -0
- package/dist/memory-DrR-Tlbf.d.mts +28 -0
- package/dist/memory-GG2Nba1D.mjs +150 -0
- package/dist/memory-GG2Nba1D.mjs.map +1 -0
- package/dist/memory-HpFdlMR_.d.cts +28 -0
- package/dist/none-Be7r6kHH.cjs +33 -0
- package/dist/none-Be7r6kHH.cjs.map +1 -0
- package/dist/none-CGmIIbI8.cjs +49 -0
- package/dist/none-CGmIIbI8.cjs.map +1 -0
- package/dist/none-CkV5mZsB.mjs +33 -0
- package/dist/none-CkV5mZsB.mjs.map +1 -0
- package/dist/none-DBeBeU0Z.mjs +23 -0
- package/dist/none-DBeBeU0Z.mjs.map +1 -0
- package/dist/query-ChGGtlA7.cjs +243 -0
- package/dist/query-ChGGtlA7.cjs.map +1 -0
- package/dist/query-LvZbyi37.mjs +172 -0
- package/dist/query-LvZbyi37.mjs.map +1 -0
- package/dist/react.css +1 -0
- package/dist/react.js +31936 -0
- package/dist/recorder-B3dG3jbd.d.mts +64 -0
- package/dist/recorder-CGY7HK29.d.cts +64 -0
- package/dist/roles-BARtYLSX.cjs +112 -0
- package/dist/roles-BARtYLSX.cjs.map +1 -0
- package/dist/roles-D7Pg89IJ.mjs +83 -0
- package/dist/roles-D7Pg89IJ.mjs.map +1 -0
- package/dist/schema-DmU7Wp0F.d.cts +251 -0
- package/dist/schema-DmU7Wp0F.d.mts +251 -0
- package/dist/schema.cjs +20 -0
- package/dist/schema.cjs.map +1 -0
- package/dist/schema.d.cts +2 -0
- package/dist/schema.d.mts +2 -0
- package/dist/schema.mjs +17 -0
- package/dist/schema.mjs.map +1 -0
- package/dist/shared-CJOyJKqT.d.mts +20 -0
- package/dist/shared-DSDY-V0n.mjs +100 -0
- package/dist/shared-DSDY-V0n.mjs.map +1 -0
- package/dist/shared-EANCdRqn.d.cts +20 -0
- package/dist/shared-OOAq-U4S.cjs +141 -0
- package/dist/shared-OOAq-U4S.cjs.map +1 -0
- package/dist/sql-B7b6HzGy.cjs +280 -0
- package/dist/sql-B7b6HzGy.cjs.map +1 -0
- package/dist/sql-COjPyn3F.mjs +209 -0
- package/dist/sql-COjPyn3F.mjs.map +1 -0
- package/dist/sqlite-event-log-BnoG8eos.cjs +184 -0
- package/dist/sqlite-event-log-BnoG8eos.cjs.map +1 -0
- package/dist/sqlite-event-log-nXmS2DS_.mjs +179 -0
- package/dist/sqlite-event-log-nXmS2DS_.mjs.map +1 -0
- package/dist/streams-CRuxOYcb.d.cts +124 -0
- package/dist/streams-DU0_gvI8.d.mts +124 -0
- package/dist/table-BcarDd10.d.cts +48 -0
- package/dist/table-BcarDd10.d.mts +48 -0
- package/dist/testing.cjs +189 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +103 -0
- package/dist/testing.d.mts +103 -0
- package/dist/testing.mjs +185 -0
- package/dist/testing.mjs.map +1 -0
- package/dist/types-elysia2/adapters/bun.d.ts +47 -0
- package/dist/types-elysia2/adapters/context-shared.d.ts +40 -0
- package/dist/types-elysia2/adapters/elysia-shared.d.ts +36 -0
- package/dist/types-elysia2/adapters/elysia2.d.ts +588 -0
- package/dist/types-elysia2/auth/contract.d.ts +26 -0
- package/dist/types-elysia2/authorization/contract.d.ts +54 -0
- package/dist/types-elysia2/canonical.d.ts +25 -0
- package/dist/types-elysia2/context.d.ts +61 -0
- package/dist/types-elysia2/core.d.ts +232 -0
- package/dist/types-elysia2/duration.d.ts +26 -0
- package/dist/types-elysia2/entry-elysia2.d.ts +10 -0
- package/dist/types-elysia2/event-log.d.ts +33 -0
- package/dist/types-elysia2/export.d.ts +77 -0
- package/dist/types-elysia2/hooks/contract.d.ts +177 -0
- package/dist/types-elysia2/id.d.ts +27 -0
- package/dist/types-elysia2/integrity.d.ts +193 -0
- package/dist/types-elysia2/keys.d.ts +91 -0
- package/dist/types-elysia2/portal.d.ts +137 -0
- package/dist/types-elysia2/query.d.ts +88 -0
- package/dist/types-elysia2/schema.d.ts +247 -0
- package/dist/types-elysia2/server/base-path.d.ts +15 -0
- package/dist/types-elysia2/server/cors.d.ts +36 -0
- package/dist/types-elysia2/server/create-fetch-handler.d.ts +140 -0
- package/dist/types-elysia2/server/openapi.d.ts +25 -0
- package/dist/types-elysia2/server/render-index-html.d.ts +18 -0
- package/dist/types-elysia2/server/routes.d.ts +83 -0
- package/dist/types-elysia2/server/static-assets.d.ts +13 -0
- package/dist/types-elysia2/standard-schema.d.ts +100 -0
- package/dist/types-elysia2/storage/contract.d.ts +106 -0
- package/dist/types-elysia2/streams.d.ts +134 -0
- package/dist/types-elysia2/transforms.d.ts +56 -0
- package/dist/types-elysia2/validation.d.ts +48 -0
- package/dist/types-react/canonical.d.ts +25 -0
- package/dist/types-react/context.d.ts +61 -0
- package/dist/types-react/core.d.ts +232 -0
- package/dist/types-react/duration.d.ts +26 -0
- package/dist/types-react/event-log.d.ts +33 -0
- package/dist/types-react/hooks/contract.d.ts +177 -0
- package/dist/types-react/id.d.ts +27 -0
- package/dist/types-react/integrity.d.ts +193 -0
- package/dist/types-react/keys.d.ts +91 -0
- package/dist/types-react/query.d.ts +88 -0
- package/dist/types-react/react.d.ts +114 -0
- package/dist/types-react/schema.d.ts +247 -0
- package/dist/types-react/standard-schema.d.ts +100 -0
- package/dist/types-react/storage/contract.d.ts +106 -0
- package/dist/types-react/streams.d.ts +134 -0
- package/dist/types-react/transforms.d.ts +56 -0
- package/dist/types-react/ui/App.d.ts +36 -0
- package/dist/types-react/ui/api.d.ts +61 -0
- package/dist/types-react/ui/components/ActionFilter.d.ts +17 -0
- package/dist/types-react/ui/components/ExportMenu.d.ts +13 -0
- package/dist/types-react/ui/components/JsonCodeEditor.d.ts +12 -0
- package/dist/types-react/ui/components/ThemeToggle.d.ts +2 -0
- package/dist/types-react/ui/components/Toast.d.ts +16 -0
- package/dist/types-react/ui/components/audit-bits.d.ts +91 -0
- package/dist/types-react/ui/components/integrity-bits.d.ts +19 -0
- package/dist/types-react/ui/components/primitives.d.ts +50 -0
- package/dist/types-react/ui/components/ui-bits.d.ts +22 -0
- package/dist/types-react/ui/lib/filters.d.ts +70 -0
- package/dist/types-react/ui/lib/format.d.ts +82 -0
- package/dist/types-react/ui/lib/nav-guard.d.ts +20 -0
- package/dist/types-react/ui/lib/portal-container.d.ts +24 -0
- package/dist/types-react/ui/lib/utils.d.ts +3 -0
- package/dist/types-react/ui/theme.d.ts +40 -0
- package/dist/types-react/ui/types.d.ts +67 -0
- package/dist/types-react/ui/views/ActionsView.d.ts +10 -0
- package/dist/types-react/ui/views/EventDrawer.d.ts +15 -0
- package/dist/types-react/ui/views/EventsView.d.ts +10 -0
- package/dist/types-react/ui/views/IntegrityView.d.ts +10 -0
- package/dist/types-react/ui/views/OverviewView.d.ts +9 -0
- package/dist/types-react/ui/views/StreamsView.d.ts +10 -0
- package/dist/types-react/ui/views/TenantsView.d.ts +6 -0
- package/dist/types-react/validation.d.ts +48 -0
- package/dist/ui/assets/favicon-BSj8MPnj.svg +11 -0
- package/dist/ui/assets/index-B-qrQSOM.css +1 -0
- package/dist/ui/assets/index-CemlP5hR.js +244 -0
- package/dist/ui/index.html +15 -0
- package/dist/validation-DFrLESZD.mjs +150 -0
- package/dist/validation-DFrLESZD.mjs.map +1 -0
- package/dist/validation-lb0YXrxx.cjs +235 -0
- package/dist/validation-lb0YXrxx.cjs.map +1 -0
- package/dist/verify.cjs +14 -0
- package/dist/verify.d.cts +5 -0
- package/dist/verify.d.mts +5 -0
- package/dist/verify.mjs +3 -0
- package/package.json +610 -4
package/dist/cli.mjs.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli.mjs","names":[],"sources":["../src/cli.ts"],"sourcesContent":["/**\n * `xtandard-audit` CLI. Operates on the same storage your app/panel uses\n * (configured via `STORAGE_DRIVER` and friends, mirroring the standalone app),\n * so it slots into shell, CI, cron and auditor workflows.\n *\n * Commands: `serve` (panel + streams + retention, no Docker), `record`,\n * `query`, `export`, `verify` (a bundle offline, or a tenant in storage),\n * `prune`, `checkpoint`, `keygen`, `tenants`, `actions`.\n *\n * Storage drivers and sinks are loaded lazily by **dynamic import of their\n * subpath entries** (`entry-storage-<driver>`, `entry-sinks-<kind>`) next to\n * this module, so the CLI only pulls the peer dependency of the driver you\n * pick — and a driver that is not part of a build is a clear runtime error,\n * not a bundling failure.\n *\n * @module\n */\n\nimport type { AuthProvider } from \"./auth/contract.ts\";\nimport type { AuthorizationProvider } from \"./authorization/contract.ts\";\nimport { createAuditCore, type AuditCore, type RetentionOptions } from \"./core.ts\";\nimport { durationToMs } from \"./duration.ts\";\nimport {\n EXPORT_CONTENT_TYPES,\n exportEvents,\n parseBundle,\n verifyBundle,\n type ExportFormat,\n} from \"./export.ts\";\nimport {\n ed25519Signer,\n generateSigningKeyPair,\n hmacSigner,\n hmacVerificationKey,\n keysFromJwks,\n type AuditSigner,\n type AuditVerificationKey,\n type VerifyReport,\n} from \"./integrity.ts\";\nimport type { AuditDuration, AuditEventInput, AuditQuery, JsonObject } from \"./schema.ts\";\nimport type { ActionMap } from \"./standard-schema.ts\";\nimport type { AuditStorage } from \"./storage/contract.ts\";\nimport type { AuditSink, StreamDefinition } from \"./streams.ts\";\n\n/** The storage drivers the CLI knows how to configure from env. */\nexport const CLI_DRIVERS = [\n \"memory\",\n \"file\",\n \"redis\",\n \"postgres\",\n \"mongodb\",\n \"sqlite\",\n \"libsql\",\n] as const;\ntype Driver = (typeof CLI_DRIVERS)[number];\n\nconst env = (key: string, fallback = \"\"): string => process.env[key] ?? fallback;\n\nconst isTruthy = (value: string): boolean => value === \"1\" || value.toLowerCase() === \"true\";\nconst isFalsy = (value: string): boolean => value === \"0\" || value.toLowerCase() === \"false\";\n\nconst warn = (message: string): void => {\n process.stderr.write(`[xtandard/audit] ${message}\\n`);\n};\n\n/** Raised when a lazily-imported subpath entry is not part of this build. */\nexport class MissingModuleError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"MissingModuleError\";\n }\n}\n\n/**\n * Import a sibling entry module by name: `./<entry>.mjs` in the built package\n * (`dist/`), `./<entry>.ts` when running from source. The specifier is computed\n * so bundlers leave it alone. Errors raised *inside* a found module (e.g. a\n * missing peer dependency) propagate unchanged.\n */\nexport async function importEntry(entry: string): Promise<Record<string, unknown>> {\n for (const ext of [\".mjs\", \".ts\"]) {\n const specifier = `./${entry}${ext}`;\n try {\n return (await import(/* @vite-ignore */ specifier)) as Record<string, unknown>;\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n const code = (err as { code?: string }).code;\n const notFound =\n code === \"ERR_MODULE_NOT_FOUND\" ||\n /Cannot find (module|package)|Failed to load url|failed to resolve|does not exist/i.test(\n message,\n );\n if (notFound && message.includes(entry)) continue;\n throw err;\n }\n }\n throw new MissingModuleError(`Module \"${entry}\" is not available in this build`);\n}\n\n/** Find a factory export by name, else the single export matching `pattern`. */\nfunction pickFactory<T>(\n mod: Record<string, unknown>,\n name: string,\n pattern: RegExp,\n): ((...args: unknown[]) => T) | null {\n if (typeof mod[name] === \"function\") return mod[name] as (...args: unknown[]) => T;\n const candidates = Object.entries(mod).filter(\n ([k, v]) => typeof v === \"function\" && pattern.test(k),\n );\n return candidates.length === 1 ? (candidates[0]![1] as (...args: unknown[]) => T) : null;\n}\n\n/** The storage driver named by `STORAGE_DRIVER` (CLI default: `file`). */\nfunction driverFromEnv(): Driver {\n const raw = env(\"STORAGE_DRIVER\", \"file\") || \"file\";\n if (!(CLI_DRIVERS as readonly string[]).includes(raw)) {\n throw new Error(`Unknown STORAGE_DRIVER \"${raw}\" (expected ${CLI_DRIVERS.join(\" | \")})`);\n }\n return raw as Driver;\n}\n\n/** Driver → [entry module, factory export, options from env]. */\nfunction driverSpec(driver: Driver): [string, string, Record<string, unknown>] {\n switch (driver) {\n case \"memory\":\n return [\"entry-storage-memory\", \"createMemoryStorage\", {}];\n case \"redis\":\n return [\n \"entry-storage-redis\",\n \"createRedisStorage\",\n {\n url: env(\"REDIS_URL\", \"redis://localhost:6379\"),\n prefix: env(\"STORAGE_PREFIX\", \"xtandard:audit\"),\n },\n ];\n case \"postgres\":\n return [\n \"entry-storage-postgres\",\n \"createPostgresStorage\",\n {\n connectionString:\n env(\"DATABASE_URL\") || env(\"POSTGRES_URL\", \"postgres://localhost:5432/postgres\"),\n table: env(\"STORAGE_PG_TABLE\", \"xtandard_audit\"),\n },\n ];\n case \"mongodb\":\n return [\n \"entry-storage-mongodb\",\n \"createMongoStorage\",\n {\n url: env(\"MONGO_URL\", \"mongodb://localhost:27017\"),\n dbName: env(\"MONGO_DB\", \"xtandard_audit\"),\n collectionName: env(\"STORAGE_MONGO_COLLECTION\", \"audit\"),\n },\n ];\n case \"sqlite\":\n // Requires running the CLI under Bun (`bunx xtandard-audit …`).\n return [\n \"entry-storage-sqlite\",\n \"createSqliteStorage\",\n { path: env(\"STORAGE_SQLITE_PATH\", \"./.audit/audit.sqlite\") },\n ];\n case \"libsql\": {\n const authToken = env(\"LIBSQL_AUTH_TOKEN\");\n return [\n \"entry-storage-libsql\",\n \"createLibsqlStorage\",\n {\n url: env(\"LIBSQL_URL\", \"file:./.audit/audit.db\"),\n ...(authToken ? { authToken } : {}),\n },\n ];\n }\n case \"file\":\n return [\n \"entry-storage-file\",\n \"createFileStorage\",\n { dir: env(\"STORAGE_FILE_DIR\", \"./.audit\") },\n ];\n }\n}\n\n/** Build the storage from env, importing the driver's subpath lazily. */\nexport async function buildStorage(): Promise<AuditStorage> {\n const driver = driverFromEnv();\n const [entry, factoryName, options] = driverSpec(driver);\n let mod: Record<string, unknown>;\n try {\n mod = await importEntry(entry);\n } catch (err) {\n if (err instanceof MissingModuleError) {\n throw new Error(\n `Storage driver \"${driver}\" is not available (missing @xtandard/audit/storage/${driver})`,\n );\n }\n throw err;\n }\n const factory = pickFactory<AuditStorage>(mod, factoryName, /^create\\w*Storage$/);\n if (!factory) throw new Error(`@xtandard/audit/storage/${driver} exports no ${factoryName}`);\n return factory(options);\n}\n\n/**\n * A human-readable, log-safe description of where storage persists data — for\n * the `serve` startup banner. Connection-string drivers print only the driver\n * name (never the URL, which may carry credentials).\n */\nasync function describeStorage(): Promise<string> {\n const { resolve } = await import(\"node:path\");\n const driver = driverFromEnv();\n switch (driver) {\n case \"file\":\n return `file → ${resolve(env(\"STORAGE_FILE_DIR\", \"./.audit\"))}`;\n case \"sqlite\":\n return `sqlite → ${resolve(env(\"STORAGE_SQLITE_PATH\", \"./.audit/audit.sqlite\"))}`;\n case \"memory\":\n return \"memory (ephemeral — not persisted)\";\n default:\n return driver;\n }\n}\n\n/** Parse a duration env like `\"365d\"`, warning and ignoring malformed values. */\nfunction parseDurationEnv(name: string): AuditDuration | undefined {\n const raw = env(name);\n if (!raw) return undefined;\n try {\n durationToMs(raw as AuditDuration); // validate eagerly\n return raw as AuditDuration;\n } catch {\n warn(`Ignoring ${name}=\"${raw}\" — expected <number><unit> with unit ms|s|m|h|d (e.g. 365d).`);\n return undefined;\n }\n}\n\n/** Retention from env: `RETENTION_MAX_AGE` / `RETENTION_KEEP_LAST`. */\nexport function retentionFromEnv(): RetentionOptions | undefined {\n const keepRaw = env(\"RETENTION_KEEP_LAST\");\n const keepLast = keepRaw && /^\\d+$/.test(keepRaw) ? Number(keepRaw) : undefined;\n if (keepRaw && keepLast === undefined) {\n warn(`Ignoring RETENTION_KEEP_LAST=\"${keepRaw}\" — expected a number.`);\n }\n const maxAge = parseDurationEnv(\"RETENTION_MAX_AGE\");\n if (keepLast === undefined && !maxAge) return undefined;\n return {\n ...(keepLast !== undefined ? { keepLast } : {}),\n ...(maxAge !== undefined ? { maxAge } : {}),\n };\n}\n\n/** Checkpoint signer from env: `AUDIT_SIGNING_KEY` (Ed25519 private JWK JSON) or `AUDIT_HMAC_SECRET`. */\nexport async function signerFromEnv(): Promise<AuditSigner | undefined> {\n const jwk = env(\"AUDIT_SIGNING_KEY\");\n if (jwk) {\n let parsed: JsonWebKey;\n try {\n parsed = JSON.parse(jwk) as JsonWebKey;\n } catch {\n throw new Error(\n \"AUDIT_SIGNING_KEY must be a private JWK as JSON (see `xtandard-audit keygen`)\",\n );\n }\n return ed25519Signer(parsed);\n }\n const secret = env(\"AUDIT_HMAC_SECRET\");\n return secret ? hmacSigner(secret) : undefined;\n}\n\n/** A stream declared in `AUDIT_STREAMS` (JSON array). */\ninterface StreamEnv {\n name: string;\n /** Sink kind: loads `@xtandard/audit/sinks/<sink>` and calls its `<kind>Sink(options)` factory. */\n sink: string;\n options?: Record<string, unknown>;\n tenants?: string[];\n filter?: StreamDefinition[\"filter\"];\n batchSize?: number;\n startFrom?: \"beginning\" | \"now\";\n checkpoints?: boolean;\n}\n\nconst camel = (kind: string) => kind.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase());\n\n/** Streams from `AUDIT_STREAMS` (JSON array of {@link StreamEnv}). */\nexport async function streamsFromEnv(): Promise<StreamDefinition[]> {\n const raw = env(\"AUDIT_STREAMS\");\n if (!raw) return [];\n let specs: StreamEnv[];\n try {\n specs = JSON.parse(raw) as StreamEnv[];\n if (!Array.isArray(specs)) throw new Error(\"not an array\");\n } catch {\n throw new Error('AUDIT_STREAMS must be a JSON array of { \"name\", \"sink\", \"options\"? , … }');\n }\n const out: StreamDefinition[] = [];\n for (const spec of specs) {\n let mod: Record<string, unknown>;\n try {\n mod = await importEntry(`entry-sinks-${spec.sink}`);\n } catch (err) {\n if (err instanceof MissingModuleError) {\n throw new Error(\n `Sink \"${spec.sink}\" (stream \"${spec.name}\") is not available (missing @xtandard/audit/sinks/${spec.sink})`,\n );\n }\n throw err;\n }\n const factory = pickFactory<AuditSink>(mod, `${camel(spec.sink)}Sink`, /Sink$/);\n if (!factory) throw new Error(`@xtandard/audit/sinks/${spec.sink} exports no sink factory`);\n out.push({\n name: spec.name,\n sink: await factory(spec.options ?? {}),\n ...(spec.tenants ? { tenants: spec.tenants } : {}),\n ...(spec.filter ? { filter: spec.filter } : {}),\n ...(spec.batchSize ? { batchSize: spec.batchSize } : {}),\n ...(spec.startFrom ? { startFrom: spec.startFrom } : {}),\n ...(spec.checkpoints !== undefined ? { checkpoints: spec.checkpoints } : {}),\n });\n }\n return out;\n}\n\n/** Build the auth + authorization providers from env (mirrors the standalone app). */\nasync function buildAuth(): Promise<{ auth: AuthProvider; authorization: AuthorizationProvider }> {\n const mode = env(\"AUTH_MODE\", \"none\");\n if (mode === \"basic\") {\n const [{ basicAuth }, { rolesAuthorization }] = await Promise.all([\n import(\"./auth/basic.ts\"),\n import(\"./authorization/roles.ts\"),\n ]);\n const passwordHash = env(\"AUTH_PASSWORD_HASH\");\n const password = env(\"AUTH_PASSWORD\");\n if (!passwordHash && !password) {\n warn(\"AUTH_MODE=basic but neither AUTH_PASSWORD_HASH nor AUTH_PASSWORD is set.\");\n }\n return {\n auth: basicAuth({\n users: [\n {\n username: env(\"AUTH_USERNAME\", \"admin\"),\n ...(passwordHash ? { passwordHash } : {}),\n ...(password ? { password } : {}),\n roles: [env(\"AUTH_ROLE\", \"admin\")],\n },\n ],\n }),\n authorization: rolesAuthorization({}),\n };\n }\n const [{ noAuth }, { noAuthorization }] = await Promise.all([\n import(\"./auth/none.ts\"),\n import(\"./authorization/none.ts\"),\n ]);\n return { auth: noAuth(), authorization: noAuthorization() };\n}\n\ntype FetchHandler = (request: Request) => Response | Promise<Response>;\n\n/**\n * Serve a web-standard fetch handler under whatever runtime the CLI runs on:\n * `Bun.serve` under `bunx`, a `node:http` bridge under `npx`/Node (streaming\n * response bodies, so exports are never buffered). Resolves once listening.\n */\nasync function startServer(port: number, fetch: FetchHandler): Promise<void> {\n const bun = (globalThis as { Bun?: { serve: (options: unknown) => unknown } }).Bun;\n if (bun) {\n bun.serve({ port, fetch });\n return;\n }\n const { createServer } = await import(\"node:http\");\n const server = createServer((req, res) => {\n void (async () => {\n try {\n const chunks: Buffer[] = [];\n for await (const c of req) chunks.push(c as Buffer);\n const method = req.method ?? \"GET\";\n const headers = new Headers();\n for (const [k, v] of Object.entries(req.headers)) {\n if (v === undefined) continue;\n headers.set(k, Array.isArray(v) ? v.join(\", \") : v);\n }\n const host = req.headers.host ?? `localhost:${port}`;\n const url = `http://${host}${req.url ?? \"/\"}`;\n const hasBody = method !== \"GET\" && method !== \"HEAD\" && chunks.length > 0;\n const request = new Request(url, {\n method,\n headers,\n body: hasBody ? Buffer.concat(chunks) : undefined,\n });\n const response = await fetch(request);\n res.statusCode = response.status;\n response.headers.forEach((value, key) => res.setHeader(key, value));\n if (response.body) {\n for await (const chunk of response.body as unknown as AsyncIterable<Uint8Array>) {\n res.write(chunk);\n }\n }\n res.end();\n } catch (err) {\n res.statusCode = 500;\n res.end(`Internal error: ${err instanceof Error ? err.message : String(err)}`);\n }\n })();\n });\n await new Promise<void>((resolve) => server.listen(port, resolve));\n}\n\ntype Flags = Record<string, string | boolean>;\n\n/** Minimal flag/value argv parser: `--key value`, `--key=value` and `--flag`. */\nexport function parseArgs(argv: string[]): { _: string[]; flags: Flags } {\n const _: string[] = [];\n const flags: Flags = {};\n for (let i = 0; i < argv.length; i++) {\n const a = argv[i]!;\n if (a.startsWith(\"--\")) {\n const eq = a.indexOf(\"=\");\n if (eq > 0) {\n flags[a.slice(2, eq)] = a.slice(eq + 1);\n continue;\n }\n const key = a.slice(2);\n const next = argv[i + 1];\n if (next === undefined || next.startsWith(\"--\")) flags[key] = true;\n else {\n flags[key] = next;\n i++;\n }\n } else _.push(a);\n }\n return { _, flags };\n}\n\nconst str = (flags: Flags, key: string): string | undefined =>\n typeof flags[key] === \"string\" ? (flags[key] as string) : undefined;\n\n/** The query model from flags (same names as the HTTP query parameters). */\nexport function queryFromFlags(flags: Flags): AuditQuery {\n const q: AuditQuery = {};\n const list = (key: string) =>\n str(flags, key)\n ?.split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n const actions = list(\"actions\");\n if (actions?.length) q.actions = actions;\n const exclude = list(\"excludeActions\");\n if (exclude?.length) q.excludeActions = exclude;\n for (const k of [\n \"tenant\",\n \"actorId\",\n \"actorType\",\n \"targetType\",\n \"targetId\",\n \"from\",\n \"to\",\n \"search\",\n \"cursor\",\n ] as const) {\n const v = str(flags, k);\n if (v) q[k] = v;\n }\n const outcome = str(flags, \"outcome\");\n if (outcome === \"success\" || outcome === \"failure\") q.outcome = outcome;\n else if (outcome) throw new Error(`Invalid --outcome \"${outcome}\" (success | failure)`);\n const order = str(flags, \"order\");\n if (order === \"asc\" || order === \"desc\") q.order = order;\n else if (order) throw new Error(`Invalid --order \"${order}\" (asc | desc)`);\n const limit = str(flags, \"limit\");\n if (limit) q.limit = Number(limit);\n return q;\n}\n\n/** A core over the env-configured storage (no runner, no timers). */\nasync function makeCore(): Promise<AuditCore<ActionMap>> {\n const [storage, signer] = await Promise.all([buildStorage(), signerFromEnv()]);\n const retention = retentionFromEnv();\n return createAuditCore({\n storage,\n ...(signer ? { signer } : {}),\n ...(retention ? { retention } : {}),\n });\n}\n\n/** Read this package's version from the nearest package.json (dist or src). */\nasync function pkgVersion(): Promise<string> {\n try {\n const { readFile } = await import(\"node:fs/promises\");\n const { fileURLToPath } = await import(\"node:url\");\n const pkg = JSON.parse(\n await readFile(fileURLToPath(new URL(\"../package.json\", import.meta.url)), \"utf8\"),\n ) as { version?: string };\n return pkg.version ?? \"unknown\";\n } catch {\n return \"unknown\";\n }\n}\n\n/**\n * The `verify` exit code: `0` valid and anchored (genesis or a verified\n * checkpoint) with every event covered by a verified checkpoint, `2` valid\n * but the tail (or the start) is not anchored by a signature, `1` invalid.\n */\nexport function verifyExitCode(report: VerifyReport): 0 | 1 | 2 {\n if (!report.ok) return 1;\n if (report.checked === 0) return 0;\n const anchored = report.anchor === \"genesis\" || report.anchor === \"checkpoint\";\n const signed = report.signedThrough !== null && report.signedThrough >= (report.toSeq ?? 0);\n return anchored && signed ? 0 : 2;\n}\n\nfunction describeReport(report: VerifyReport): string {\n const lines = [\n `${report.ok ? \"VALID\" : \"INVALID\"}: ${report.checked} event(s)` +\n (report.fromSeq !== null ? ` (seq ${report.fromSeq}..${report.toSeq})` : \"\") +\n (report.tenant ? ` of tenant \"${report.tenant}\"` : \"\"),\n `anchor: ${report.anchor}; checkpoints verified: ${report.checkpointsVerified}; signed through: ${report.signedThrough ?? \"—\"}`,\n ];\n if (report.erased.length)\n lines.push(`erased: ${report.erased.length} event(s) with erased sections`);\n for (const issue of report.issues) {\n lines.push(\n ` ✗ ${issue.kind}${issue.seq !== undefined ? ` @${issue.seq}` : \"\"}: ${issue.message}`,\n );\n }\n const code = verifyExitCode(report);\n if (code === 2) {\n lines.push(\n report.signedThrough === null\n ? \"warning: no verified checkpoint covers these events (unsigned)\"\n : `warning: events after seq ${report.signedThrough} are not covered by a verified checkpoint`,\n );\n }\n return lines.join(\"\\n\") + \"\\n\";\n}\n\n/** Keys from `--jwks <file|url>`. */\nasync function loadJwks(source: string): Promise<AuditVerificationKey[]> {\n let text: string;\n if (/^https?:\\/\\//.test(source)) {\n const res = await fetch(source);\n if (!res.ok) throw new Error(`GET ${source} → ${res.status}`);\n text = await res.text();\n } else {\n const { readFile } = await import(\"node:fs/promises\");\n text = await readFile(source, \"utf8\");\n }\n return keysFromJwks(JSON.parse(text) as { keys: JsonWebKey[] });\n}\n\nfunction helpText(version: string): string {\n return `xtandard-audit v${version} — self-hosted, tamper-evident audit-log control plane\n\nUsage:\n xtandard-audit <command> [options] # the binary, after: npm i -g @xtandard/audit\n npx @xtandard/audit <command> # without installing (or: bunx @xtandard/audit …)\n\nCommands:\n serve [--port <n>] Run the panel + API + streams + retention (no Docker).\n record --tenant <t> --action <a> --actor <id> [--actor-type <type>]\n [--targets type:id,…] [--metadata '<json>'] [--outcome success|failure]\n [--description <text>]\n record --event '<json>' Record one event (ingest from shell/CI). Prints it.\n query [--tenant <t>] [--actions a,b] [--excludeActions …] [--actorId …] [--actorType …]\n [--targetType …] [--targetId …] [--outcome …] [--from …] [--to …] [--search …]\n [--order asc|desc] [--limit n] [--cursor c] [--json]\n Search events (flags = the HTTP query parameters).\n export --tenant <t> [--format csv|json|jsonl|bundle] [--out <file>] [query flags]\n Stream an export to stdout (or --out).\n verify --bundle <file.jsonl> [--jwks <file|url>] [--hmac-secret <s>]\n verify --tenant <t> [--fromSeq n] [--toSeq n]\n Verify an export bundle offline (or a tenant's chain in\n storage). Exit 0 = valid and anchored by genesis or a\n verified checkpoint; 2 = valid but the tail is not covered\n by a verified checkpoint (unsigned); 1 = invalid.\n prune [--tenant <t>] Apply the retention policy (RETENTION_*).\n checkpoint --tenant <t> Sign a tenant's chain head (needs AUDIT_SIGNING_KEY or\n AUDIT_HMAC_SECRET).\n keygen Print a new Ed25519 private JWK (→ AUDIT_SIGNING_KEY) and\n its public JWKS.\n tenants List tenants with their head seq and retained count.\n actions List the action catalog.\n\nGlobal options:\n -h, --help Show this help.\n -v, --version Print the version.\n\nEnvironment variables\n Storage:\n STORAGE_DRIVER memory | file | redis | postgres | mongodb | sqlite | libsql\n (CLI default: file · Docker default: memory)\n STORAGE_FILE_DIR ./.audit (driver: file)\n REDIS_URL, STORAGE_PREFIX redis://localhost:6379, xtandard:audit (driver: redis)\n DATABASE_URL | POSTGRES_URL, STORAGE_PG_TABLE (driver: postgres)\n MONGO_URL, MONGO_DB, STORAGE_MONGO_COLLECTION (driver: mongodb)\n STORAGE_SQLITE_PATH ./.audit/audit.sqlite (driver: sqlite, Bun only)\n LIBSQL_URL, LIBSQL_AUTH_TOKEN (driver: libsql)\n\n Integrity:\n AUDIT_SIGNING_KEY Ed25519 private JWK (JSON) — signs checkpoints; the public\n key is served at {BASE_PATH}/api/integrity/keys.\n AUDIT_HMAC_SECRET HMAC checkpoint secret (when no AUDIT_SIGNING_KEY).\n\n Retention (kept if EITHER rule keeps it; never past an undelivered stream cursor):\n RETENTION_MAX_AGE e.g. 365d (ms|s|m|h|d)\n RETENTION_KEEP_LAST Keep at most the N most recent events per tenant.\n MAINTENANCE_INTERVAL 1h How often \\`serve\\` prunes; 0|false disables.\n\n Server (\\`serve\\` / standalone):\n PORT 3000 Port to listen on (or --port).\n BASE_PATH \"\" URL prefix, e.g. \"/audit\".\n TITLE Navbar wordmark.\n LOGO_URL Logo image URL.\n READONLY 1|true Block all mutating operations.\n AUTH_MODE none|basic Authentication mode (default none).\n AUTH_USERNAME admin Username for basic auth.\n AUTH_PASSWORD_HASH scrypt hash (preferred; see docs/AUTH.md).\n AUTH_PASSWORD Plaintext password (dev only).\n AUTH_ROLE admin Role of the basic-auth user (admin | auditor | viewer).\n PORTAL_SECRET Enables portal-token access (audpt_… bearer tokens).\n\n Streams (\\`serve\\` / standalone):\n AUDIT_STREAMS JSON array: [{ \"name\": \"siem\", \"sink\": \"http\",\n \"options\": { \"url\": \"https://…\" }, \"startFrom\": \"now\" }]\n STREAM_RUNNER 1 0|false: show stream status but do not run them here.\n\nExamples:\n # Quick local panel (file storage, no auth):\n npx @xtandard/audit serve --port 3004\n\n # Signed checkpoints:\n export AUDIT_SIGNING_KEY=\"$(xtandard-audit keygen | head -1)\"\n\n # Record from CI:\n xtandard-audit record --tenant acme --action deploy.finished --actor ci \\\\\n --metadata '{\"sha\":\"abc123\"}'\n\n # Export a verifiable bundle and verify it against the published keys:\n xtandard-audit export --tenant acme --format bundle --out acme.jsonl\n xtandard-audit verify --bundle acme.jsonl --jwks https://app.example.com/audit/api/integrity/keys\n\nDocs: https://github.com/xantiagoma/xtandard-audit\n`;\n}\n\n/** Entry point. Returns the process exit code. */\nexport async function run(argv: string[]): Promise<number> {\n const { _, flags } = parseArgs(argv);\n const command = _[0];\n\n // `--version` (bare) / `-v` / `version` → print version.\n if (flags.version === true || argv.includes(\"-v\") || command === \"version\") {\n process.stdout.write(`${await pkgVersion()}\\n`);\n return 0;\n }\n\n const wantsHelp = Boolean(flags.help) || argv.includes(\"-h\") || command === \"help\";\n if (!command || wantsHelp) {\n process.stdout.write(helpText(await pkgVersion()));\n // Explicit help request → success; bare invocation with no command → usage error.\n return wantsHelp ? 0 : 1;\n }\n\n try {\n switch (command) {\n case \"keygen\": {\n const { privateJwk, publicJwk } = await generateSigningKeyPair();\n process.stdout.write(\n `${JSON.stringify(privateJwk)}\\n${JSON.stringify({ keys: [{ ...publicJwk, alg: \"Ed25519\", use: \"sig\" }] })}\\n`,\n );\n process.stderr.write(\n \"Line 1: private JWK — set it as AUDIT_SIGNING_KEY (keep it secret).\\n\" +\n \"Line 2: public JWKS — publish it so auditors can verify checkpoints.\\n\",\n );\n return 0;\n }\n case \"tenants\": {\n const core = await makeCore();\n const tenants = await core.listTenants();\n if (tenants.length === 0) process.stdout.write(\"No tenants.\\n\");\n for (const t of tenants) {\n process.stdout.write(\n `${t.key} seq ${t.head.seq} ${t.count ?? 0} event(s)` +\n (t.head.baseSeq && t.head.baseSeq > 1 ? ` (pruned before ${t.head.baseSeq})` : \"\") +\n \"\\n\",\n );\n }\n return 0;\n }\n case \"actions\": {\n const core = await makeCore();\n const actions = await core.listActions();\n if (actions.length === 0) process.stdout.write(\"No actions in the catalog.\\n\");\n for (const a of actions) {\n process.stdout.write(\n `${a.name}${a.group ? ` [${a.group}]` : \"\"}${a.deprecated ? \" (deprecated)\" : \"\"}` +\n `${a.description ? ` ${a.description}` : \"\"}\\n`,\n );\n }\n return 0;\n }\n case \"record\": {\n let input: Partial<AuditEventInput>;\n const eventJson = str(flags, \"event\");\n if (eventJson) {\n try {\n input = JSON.parse(eventJson) as Partial<AuditEventInput>;\n } catch {\n process.stderr.write(\"Invalid --event JSON.\\n\");\n return 1;\n }\n } else {\n const tenant = str(flags, \"tenant\");\n const action = str(flags, \"action\");\n const actorId = str(flags, \"actor\");\n if (!tenant || !action || !actorId) {\n process.stderr.write(\n \"Usage: xtandard-audit record --tenant <t> --action <a> --actor <id> [--metadata '<json>'] [--targets type:id,…]\\n\" +\n \" or: xtandard-audit record --event '<json>'\\n\",\n );\n return 1;\n }\n let metadata: JsonObject | undefined;\n const raw = str(flags, \"metadata\");\n if (raw) {\n try {\n metadata = JSON.parse(raw) as JsonObject;\n } catch {\n process.stderr.write(\"Invalid --metadata JSON.\\n\");\n return 1;\n }\n }\n const targets = str(flags, \"targets\")\n ?.split(\",\")\n .filter(Boolean)\n .map((t) => {\n const i = t.indexOf(\":\");\n return i > 0 ? { type: t.slice(0, i), id: t.slice(i + 1) } : { type: t, id: t };\n });\n const actorType = str(flags, \"actor-type\");\n const outcome = str(flags, \"outcome\");\n const description = str(flags, \"description\");\n input = {\n tenant,\n action,\n actor: { id: actorId, ...(actorType ? { type: actorType } : {}) },\n ...(targets?.length ? { targets } : {}),\n ...(metadata ? { metadata } : {}),\n ...(outcome ? { outcome: outcome as AuditEventInput[\"outcome\"] } : {}),\n ...(description ? { description } : {}),\n };\n }\n const core = await makeCore();\n const event = await core.record(input as AuditEventInput);\n process.stdout.write(`${JSON.stringify(event, null, 2)}\\n`);\n return 0;\n }\n case \"query\": {\n const core = await makeCore();\n const page = await core.query(queryFromFlags(flags));\n if (flags.json) {\n process.stdout.write(`${JSON.stringify(page, null, 2)}\\n`);\n return 0;\n }\n if (page.items.length === 0) process.stdout.write(\"No events.\\n\");\n for (const e of page.items) {\n process.stdout.write(\n `${e.occurredAt} ${e.tenant}#${e.seq} ${e.action} by ${e.actor.id}` +\n (e.targets.length\n ? ` → ${e.targets.map((t) => `${t.type}:${t.id}`).join(\",\")}`\n : \"\") +\n (e.outcome === \"failure\" ? \" (failure)\" : \"\") +\n \"\\n\",\n );\n }\n if (page.pageInfo.hasNextPage) {\n process.stdout.write(`… more: --cursor ${page.pageInfo.endCursor}\\n`);\n }\n return 0;\n }\n case \"export\": {\n const tenant = str(flags, \"tenant\");\n const format = (str(flags, \"format\") ?? \"jsonl\") as ExportFormat;\n if (!tenant) {\n process.stderr.write(\n \"Usage: xtandard-audit export --tenant <t> [--format csv|json|jsonl|bundle] [--out <file>]\\n\",\n );\n return 1;\n }\n if (!(format in EXPORT_CONTENT_TYPES)) {\n process.stderr.write(`Invalid --format \"${format}\" (csv | json | jsonl | bundle).\\n`);\n return 1;\n }\n const core = await makeCore();\n const query = { ...queryFromFlags(flags), tenant };\n delete query.limit;\n delete query.cursor;\n const stream = await exportEvents(core, query, {\n format,\n actor: { id: \"cli\", name: \"xtandard-audit CLI\" },\n });\n const out = str(flags, \"out\");\n if (out) {\n const { createWriteStream } = await import(\"node:fs\");\n const file = createWriteStream(out);\n for await (const chunk of stream as unknown as AsyncIterable<Uint8Array>)\n file.write(chunk);\n await new Promise<void>((resolve, reject) => {\n file.end((err?: Error | null) => (err ? reject(err) : resolve()));\n });\n process.stderr.write(`Exported ${format} → ${out}\\n`);\n } else {\n for await (const chunk of stream as unknown as AsyncIterable<Uint8Array>) {\n process.stdout.write(chunk);\n }\n }\n return 0;\n }\n case \"verify\": {\n const bundlePath = str(flags, \"bundle\");\n const tenant = str(flags, \"tenant\");\n if (!bundlePath && !tenant) {\n process.stderr.write(\n \"Usage: xtandard-audit verify --bundle <file.jsonl> [--jwks <file|url>] [--hmac-secret <s>]\\n\" +\n \" or: xtandard-audit verify --tenant <t> [--fromSeq n] [--toSeq n]\\n\",\n );\n return 1;\n }\n let report: VerifyReport;\n if (bundlePath) {\n const { readFile } = await import(\"node:fs/promises\");\n const text = await readFile(bundlePath, \"utf8\");\n const keys: AuditVerificationKey[] = [];\n const jwks = str(flags, \"jwks\");\n if (jwks) {\n keys.push(...(await loadJwks(jwks)));\n } else {\n // Without --jwks, trust the bundle's own JWKS (and say so).\n const embedded = parseBundle(text).jwks;\n if (embedded?.keys.length) {\n keys.push(...(await keysFromJwks(embedded as { keys: JsonWebKey[] })));\n process.stderr.write(\n \"note: checkpoint signatures verified with the keys embedded in the bundle — pass --jwks <operator's published keys> to not trust the file for them.\\n\",\n );\n }\n }\n const hmac = str(flags, \"hmac-secret\") ?? env(\"AUDIT_HMAC_SECRET\");\n if (hmac) keys.push(hmacVerificationKey(hmac));\n report = await verifyBundle(text, keys.length ? { keys } : {});\n } else {\n const core = await makeCore();\n const fromSeq = str(flags, \"fromSeq\");\n const toSeq = str(flags, \"toSeq\");\n report = await core.verify(tenant!, {\n ...(fromSeq ? { fromSeq: Number(fromSeq) } : {}),\n ...(toSeq ? { toSeq: Number(toSeq) } : {}),\n });\n }\n if (flags.json) process.stdout.write(`${JSON.stringify(report, null, 2)}\\n`);\n else process.stdout.write(describeReport(report));\n return verifyExitCode(report);\n }\n case \"prune\": {\n const core = await makeCore();\n if (!core.options.retention) {\n process.stderr.write(\n \"No retention policy: set RETENTION_MAX_AGE and/or RETENTION_KEEP_LAST.\\n\",\n );\n return 1;\n }\n const tenant = str(flags, \"tenant\");\n const actor = { actor: { id: \"cli\", name: \"xtandard-audit CLI\" } };\n const results = tenant ? [await core.pruneTenant(tenant, actor)] : await core.prune(actor);\n for (const r of results) {\n process.stdout.write(\n `${r.tenant}: pruned ${r.pruned}, first retained seq ${r.baseSeq}\\n`,\n );\n }\n return 0;\n }\n case \"checkpoint\": {\n const tenant = str(flags, \"tenant\");\n if (!tenant) {\n process.stderr.write(\"Usage: xtandard-audit checkpoint --tenant <t>\\n\");\n return 1;\n }\n const core = await makeCore();\n const cp = await core.checkpoint(tenant, {\n actor: { id: \"cli\", name: \"xtandard-audit CLI\" },\n });\n process.stdout.write(`${JSON.stringify(cp, null, 2)}\\n`);\n return 0;\n }\n case \"serve\": {\n const port = Number(str(flags, \"port\") || env(\"PORT\", \"3000\"));\n const basePath = env(\"BASE_PATH\", \"\");\n const title = env(\"TITLE\", \"@xtandard/audit\");\n const logoUrl = env(\"LOGO_URL\");\n const readonly = isTruthy(env(\"READONLY\"));\n const authMode = env(\"AUTH_MODE\", \"none\");\n const portalSecret = env(\"PORTAL_SECRET\");\n const maintenanceRaw = env(\"MAINTENANCE_INTERVAL\");\n\n const { createFetchHandler } = await import(\"./server/create-fetch-handler.ts\");\n const [storage, signer, streams, { auth, authorization }] = await Promise.all([\n buildStorage(),\n signerFromEnv(),\n streamsFromEnv(),\n buildAuth(),\n ]);\n\n if (authMode === \"none\") {\n warn(\"AUTH_MODE=none — do NOT expose this publicly without authentication.\");\n }\n\n const retention = retentionFromEnv();\n const panel = createFetchHandler({\n storage,\n basePath,\n title,\n ...(logoUrl ? { logoUrl } : {}),\n readonly,\n auth,\n authorization,\n ...(signer ? { signer } : {}),\n ...(portalSecret ? { portal: { secret: portalSecret } } : {}),\n ...(retention ? { retention } : {}),\n ...(streams.length ? { streams } : {}),\n ...(isFalsy(env(\"STREAM_RUNNER\", \"1\")) ? { streamRunner: false as const } : {}),\n maintenance:\n maintenanceRaw && isFalsy(maintenanceRaw)\n ? false\n : { interval: (parseDurationEnv(\"MAINTENANCE_INTERVAL\") ?? \"1h\") as AuditDuration },\n });\n\n const normalizedBase =\n basePath && basePath !== \"/\"\n ? basePath.startsWith(\"/\")\n ? basePath\n : `/${basePath}`\n : \"\";\n\n const handler: FetchHandler = (request) => {\n const url = new URL(request.url);\n if (url.pathname === \"/healthcheck\" || url.pathname === `${normalizedBase}/healthcheck`) {\n return new Response(JSON.stringify({ status: \"ok\", title }), {\n headers: { \"content-type\": \"application/json\" },\n });\n }\n return panel.fetch(request);\n };\n\n process.stdout.write(`[xtandard/audit] storage: ${await describeStorage()}\\n`);\n process.stdout.write(\n `[xtandard/audit] signer: ${signer ? `${signer.alg} (${signer.keyId})` : \"none (no checkpoints)\"}\\n`,\n );\n process.stdout.write(\n `[xtandard/audit] streams: ${\n streams.length\n ? `${streams.map((s) => s.name).join(\", \")}${isFalsy(env(\"STREAM_RUNNER\", \"1\")) ? \" (not running here)\" : \"\"}`\n : \"none\"\n }\\n`,\n );\n\n await startServer(port, handler);\n process.stdout.write(\n `[xtandard/audit] listening on http://localhost:${port}${normalizedBase || \"/\"}\\n`,\n );\n // The server owns the process now; never resolve so the bin doesn't exit.\n return await new Promise<number>(() => {});\n }\n default:\n process.stderr.write(`Unknown command: ${command}\\n\\n${helpText(await pkgVersion())}`);\n return 1;\n }\n } catch (err) {\n process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}\\n`);\n return 1;\n }\n}\n\n// `bun src/cli.ts <command>` (contributors); the published bin calls `run` itself.\nif ((import.meta as ImportMeta & { main?: boolean }).main) {\n void run(process.argv.slice(2)).then((code) => process.exit(code));\n}\n"],"mappings":";;;;;AA6CA,MAAa,cAAc;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAGA,MAAM,OAAO,KAAa,WAAW,OAAe,QAAQ,IAAI,QAAQ;AAExE,MAAM,YAAY,UAA2B,UAAU,OAAO,MAAM,YAAY,MAAM;AACtF,MAAM,WAAW,UAA2B,UAAU,OAAO,MAAM,YAAY,MAAM;AAErF,MAAM,QAAQ,YAA0B;CACtC,QAAQ,OAAO,MAAM,oBAAoB,QAAQ,GAAG;AACtD;;AAGA,IAAa,qBAAb,cAAwC,MAAM;CAC5C,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;;;;;;AAQA,eAAsB,YAAY,OAAiD;CACjF,KAAK,MAAM,OAAO,CAAC,QAAQ,KAAK,GAAG;EACjC,MAAM,YAAY,KAAK,QAAQ;EAC/B,IAAI;GACF,OAAQ,MAAM;;IAA0B;;EAC1C,SAAS,KAAK;GACZ,MAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;GAO/D,KANc,IAA0B,SAE7B,0BACT,oFAAoF,KAClF,OACF,MACc,QAAQ,SAAS,KAAK,GAAG;GACzC,MAAM;EACR;CACF;CACA,MAAM,IAAI,mBAAmB,WAAW,MAAM,iCAAiC;AACjF;;AAGA,SAAS,YACP,KACA,MACA,SACoC;CACpC,IAAI,OAAO,IAAI,UAAU,YAAY,OAAO,IAAI;CAChD,MAAM,aAAa,OAAO,QAAQ,GAAG,EAAE,QACpC,CAAC,GAAG,OAAO,OAAO,MAAM,cAAc,QAAQ,KAAK,CAAC,CACvD;CACA,OAAO,WAAW,WAAW,IAAK,WAAW,GAAI,KAAmC;AACtF;;AAGA,SAAS,gBAAwB;CAC/B,MAAM,MAAM,IAAI,kBAA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E,KAAK,IAAI,IAAI,QAAQ,IAAI,iBAAiB,GAAG,CAAC,IAAI,wBAAwB,OACxG,OACL,GACH;IAEA,MAAM,YAAY,MAAM,OAAO;IAC/B,QAAQ,OAAO,MACb,kDAAkD,OAAO,kBAAkB,IAAI,GACjF;IAEA,OAAO,MAAM,IAAI,cAAsB,CAAC,CAAC;GAC3C;GACA;IACE,QAAQ,OAAO,MAAM,oBAAoB,QAAQ,MAAM,SAAS,MAAM,WAAW,CAAC,GAAG;IACrF,OAAO;EACX;CACF,SAAS,KAAK;EACZ,QAAQ,OAAO,MAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,EAAE,GAAG;EACnF,OAAO;CACT;AACF;AAGA,IAAK,OAAO,KAAyC,MACnD,IAAS,QAAQ,KAAK,MAAM,CAAC,CAAC,EAAE,MAAM,SAAS,QAAQ,KAAK,IAAI,CAAC"}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { a as AuditContext, r as AuditActor } from "./schema-DmU7Wp0F.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/context.d.ts
|
|
4
|
+
/** What a request scope carries. */
|
|
5
|
+
interface AuditScope {
|
|
6
|
+
/** Default actor for events recorded in this scope. */
|
|
7
|
+
actor?: AuditActor;
|
|
8
|
+
/** Default tenant for events recorded in this scope. */
|
|
9
|
+
tenant?: string;
|
|
10
|
+
/** Request context merged under each event's explicit `context`. */
|
|
11
|
+
context?: AuditContext;
|
|
12
|
+
}
|
|
13
|
+
/** The current scope, or `null` outside any scope. Never throws. */
|
|
14
|
+
declare function getAuditContext(): AuditScope | null;
|
|
15
|
+
/**
|
|
16
|
+
* Run `fn` inside a scope. Nested scopes inherit and override the outer one
|
|
17
|
+
* (`context` keys merge).
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* ```ts
|
|
21
|
+
* import { runWithAuditContext } from "@xtandard/audit/context";
|
|
22
|
+
*
|
|
23
|
+
* await runWithAuditContext({ actor: { id: user.id }, tenant: user.orgId }, () =>
|
|
24
|
+
* audit.record({ action: "invoice.paid", metadata: { invoiceId } }),
|
|
25
|
+
* );
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
declare function runWithAuditContext<T>(scope: AuditScope, fn: () => T): T;
|
|
29
|
+
/**
|
|
30
|
+
* Patch the current scope for the rest of the current async execution
|
|
31
|
+
* (`enterWith` semantics) — for middleware that cannot wrap `next()`, or to
|
|
32
|
+
* attach the actor once auth resolves.
|
|
33
|
+
*/
|
|
34
|
+
declare function setAuditContext(patch: AuditScope): void;
|
|
35
|
+
/** Options for {@link auditContextFromRequest}. */
|
|
36
|
+
interface RequestContextOptions {
|
|
37
|
+
/**
|
|
38
|
+
* Trust proxy headers (`x-forwarded-for`, `cf-connecting-ip`, `x-real-ip`,
|
|
39
|
+
* `fly-client-ip`) for the client IP. Default `true` — set `false` when the
|
|
40
|
+
* app is reachable directly, or clients can spoof their IP.
|
|
41
|
+
*/
|
|
42
|
+
trustProxy?: boolean;
|
|
43
|
+
/** Header carrying the request id. Default: `x-request-id`, then `cf-ray`. */
|
|
44
|
+
requestIdHeader?: string;
|
|
45
|
+
/** Fallback IP when no header carries one (e.g. Bun's `server.requestIP`). */
|
|
46
|
+
ip?: string;
|
|
47
|
+
}
|
|
48
|
+
/** Extract `{ ip, userAgent, requestId }` from a web-standard Request. */
|
|
49
|
+
declare function auditContextFromRequest(request: Request, options?: RequestContextOptions): AuditContext;
|
|
50
|
+
//#endregion
|
|
51
|
+
export { runWithAuditContext as a, getAuditContext as i, RequestContextOptions as n, setAuditContext as o, auditContextFromRequest as r, AuditScope as t };
|
|
52
|
+
//# sourceMappingURL=context-BtR9k9Mt.d.mts.map
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { a as AuditContext, r as AuditActor } from "./schema-DmU7Wp0F.cjs";
|
|
2
|
+
|
|
3
|
+
//#region src/context.d.ts
|
|
4
|
+
/** What a request scope carries. */
|
|
5
|
+
interface AuditScope {
|
|
6
|
+
/** Default actor for events recorded in this scope. */
|
|
7
|
+
actor?: AuditActor;
|
|
8
|
+
/** Default tenant for events recorded in this scope. */
|
|
9
|
+
tenant?: string;
|
|
10
|
+
/** Request context merged under each event's explicit `context`. */
|
|
11
|
+
context?: AuditContext;
|
|
12
|
+
}
|
|
13
|
+
/** The current scope, or `null` outside any scope. Never throws. */
|
|
14
|
+
declare function getAuditContext(): AuditScope | null;
|
|
15
|
+
/**
|
|
16
|
+
* Run `fn` inside a scope. Nested scopes inherit and override the outer one
|
|
17
|
+
* (`context` keys merge).
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* ```ts
|
|
21
|
+
* import { runWithAuditContext } from "@xtandard/audit/context";
|
|
22
|
+
*
|
|
23
|
+
* await runWithAuditContext({ actor: { id: user.id }, tenant: user.orgId }, () =>
|
|
24
|
+
* audit.record({ action: "invoice.paid", metadata: { invoiceId } }),
|
|
25
|
+
* );
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
declare function runWithAuditContext<T>(scope: AuditScope, fn: () => T): T;
|
|
29
|
+
/**
|
|
30
|
+
* Patch the current scope for the rest of the current async execution
|
|
31
|
+
* (`enterWith` semantics) — for middleware that cannot wrap `next()`, or to
|
|
32
|
+
* attach the actor once auth resolves.
|
|
33
|
+
*/
|
|
34
|
+
declare function setAuditContext(patch: AuditScope): void;
|
|
35
|
+
/** Options for {@link auditContextFromRequest}. */
|
|
36
|
+
interface RequestContextOptions {
|
|
37
|
+
/**
|
|
38
|
+
* Trust proxy headers (`x-forwarded-for`, `cf-connecting-ip`, `x-real-ip`,
|
|
39
|
+
* `fly-client-ip`) for the client IP. Default `true` — set `false` when the
|
|
40
|
+
* app is reachable directly, or clients can spoof their IP.
|
|
41
|
+
*/
|
|
42
|
+
trustProxy?: boolean;
|
|
43
|
+
/** Header carrying the request id. Default: `x-request-id`, then `cf-ray`. */
|
|
44
|
+
requestIdHeader?: string;
|
|
45
|
+
/** Fallback IP when no header carries one (e.g. Bun's `server.requestIP`). */
|
|
46
|
+
ip?: string;
|
|
47
|
+
}
|
|
48
|
+
/** Extract `{ ip, userAgent, requestId }` from a web-standard Request. */
|
|
49
|
+
declare function auditContextFromRequest(request: Request, options?: RequestContextOptions): AuditContext;
|
|
50
|
+
//#endregion
|
|
51
|
+
export { runWithAuditContext as a, getAuditContext as i, RequestContextOptions as n, setAuditContext as o, auditContextFromRequest as r, AuditScope as t };
|
|
52
|
+
//# sourceMappingURL=context-CJM87uG8.d.cts.map
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { a as AuditContext, r as AuditActor } from "./schema-DmU7Wp0F.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/adapters/context-shared.d.ts
|
|
4
|
+
type MaybePromise<T> = T | Promise<T>;
|
|
5
|
+
/**
|
|
6
|
+
* Options for every framework's `auditContext()` middleware. The callbacks
|
|
7
|
+
* receive the framework's own request context (Hono's `c`, Express's `req`,
|
|
8
|
+
* Elysia's `ctx`, Bun's `Request`) so they can read whatever the host's auth
|
|
9
|
+
* already resolved (a session, a decoded JWT, `req.user`, …).
|
|
10
|
+
*/
|
|
11
|
+
interface AuditContextOptions<Ctx> {
|
|
12
|
+
/** Resolve the actor for events recorded in this request (or nothing). */
|
|
13
|
+
actor?: (ctx: Ctx) => MaybePromise<AuditActor | null | undefined>;
|
|
14
|
+
/** Resolve the tenant for events recorded in this request (or nothing). */
|
|
15
|
+
tenant?: (ctx: Ctx) => MaybePromise<string | null | undefined>;
|
|
16
|
+
/** Extra context keys merged over the captured IP / user agent / request id. */
|
|
17
|
+
context?: (ctx: Ctx) => MaybePromise<AuditContext | null | undefined>;
|
|
18
|
+
/**
|
|
19
|
+
* Trust proxy headers (`x-forwarded-for`, `cf-connecting-ip`, `x-real-ip`,
|
|
20
|
+
* `fly-client-ip`) for the client IP. Default `true` — set `false` when the
|
|
21
|
+
* app is reachable directly, or clients can spoof their IP.
|
|
22
|
+
*/
|
|
23
|
+
trustProxy?: boolean;
|
|
24
|
+
/** Header carrying the request id. Default: `x-request-id`, then `cf-ray`. */
|
|
25
|
+
requestIdHeader?: string;
|
|
26
|
+
}
|
|
27
|
+
//#endregion
|
|
28
|
+
export { AuditContextOptions as t };
|
|
29
|
+
//# sourceMappingURL=context-shared-AgBWIRUQ.d.mts.map
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { a as AuditContext, r as AuditActor } from "./schema-DmU7Wp0F.cjs";
|
|
2
|
+
|
|
3
|
+
//#region src/adapters/context-shared.d.ts
|
|
4
|
+
type MaybePromise<T> = T | Promise<T>;
|
|
5
|
+
/**
|
|
6
|
+
* Options for every framework's `auditContext()` middleware. The callbacks
|
|
7
|
+
* receive the framework's own request context (Hono's `c`, Express's `req`,
|
|
8
|
+
* Elysia's `ctx`, Bun's `Request`) so they can read whatever the host's auth
|
|
9
|
+
* already resolved (a session, a decoded JWT, `req.user`, …).
|
|
10
|
+
*/
|
|
11
|
+
interface AuditContextOptions<Ctx> {
|
|
12
|
+
/** Resolve the actor for events recorded in this request (or nothing). */
|
|
13
|
+
actor?: (ctx: Ctx) => MaybePromise<AuditActor | null | undefined>;
|
|
14
|
+
/** Resolve the tenant for events recorded in this request (or nothing). */
|
|
15
|
+
tenant?: (ctx: Ctx) => MaybePromise<string | null | undefined>;
|
|
16
|
+
/** Extra context keys merged over the captured IP / user agent / request id. */
|
|
17
|
+
context?: (ctx: Ctx) => MaybePromise<AuditContext | null | undefined>;
|
|
18
|
+
/**
|
|
19
|
+
* Trust proxy headers (`x-forwarded-for`, `cf-connecting-ip`, `x-real-ip`,
|
|
20
|
+
* `fly-client-ip`) for the client IP. Default `true` — set `false` when the
|
|
21
|
+
* app is reachable directly, or clients can spoof their IP.
|
|
22
|
+
*/
|
|
23
|
+
trustProxy?: boolean;
|
|
24
|
+
/** Header carrying the request id. Default: `x-request-id`, then `cf-ray`. */
|
|
25
|
+
requestIdHeader?: string;
|
|
26
|
+
}
|
|
27
|
+
//#endregion
|
|
28
|
+
export { AuditContextOptions as t };
|
|
29
|
+
//# sourceMappingURL=context-shared-CUq3cSpV.d.cts.map
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { auditContextFromRequest } from "./context.mjs";
|
|
2
|
+
//#region src/adapters/context-shared.ts
|
|
3
|
+
/**
|
|
4
|
+
* Framework-independent half of the `auditContext()` middlewares (ADR 0013):
|
|
5
|
+
* the options every adapter accepts and the resolution of an {@link AuditScope}
|
|
6
|
+
* from a web-standard `Request` plus the framework's own context object.
|
|
7
|
+
* Must not import any framework.
|
|
8
|
+
*
|
|
9
|
+
* @module
|
|
10
|
+
*/
|
|
11
|
+
/**
|
|
12
|
+
* Build the scope for one request: IP / user agent / request id from the
|
|
13
|
+
* headers (with `ip` as the socket-level fallback), then the host's actor,
|
|
14
|
+
* tenant and extra context.
|
|
15
|
+
*/
|
|
16
|
+
async function resolveAuditScope(request, ctx, options, ip) {
|
|
17
|
+
const reqOptions = {
|
|
18
|
+
...options.trustProxy !== void 0 ? { trustProxy: options.trustProxy } : {},
|
|
19
|
+
...options.requestIdHeader ? { requestIdHeader: options.requestIdHeader } : {},
|
|
20
|
+
...ip ? { ip } : {}
|
|
21
|
+
};
|
|
22
|
+
const [actor, tenant, extra] = await Promise.all([
|
|
23
|
+
options.actor?.(ctx),
|
|
24
|
+
options.tenant?.(ctx),
|
|
25
|
+
options.context?.(ctx)
|
|
26
|
+
]);
|
|
27
|
+
return {
|
|
28
|
+
context: {
|
|
29
|
+
...auditContextFromRequest(request, reqOptions),
|
|
30
|
+
...extra
|
|
31
|
+
},
|
|
32
|
+
...actor ? { actor } : {},
|
|
33
|
+
...tenant ? { tenant } : {}
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
//#endregion
|
|
37
|
+
export { resolveAuditScope as t };
|
|
38
|
+
|
|
39
|
+
//# sourceMappingURL=context-shared-CupikwQo.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context-shared-CupikwQo.mjs","names":[],"sources":["../src/adapters/context-shared.ts"],"sourcesContent":["/**\n * Framework-independent half of the `auditContext()` middlewares (ADR 0013):\n * the options every adapter accepts and the resolution of an {@link AuditScope}\n * from a web-standard `Request` plus the framework's own context object.\n * Must not import any framework.\n *\n * @module\n */\n\nimport {\n auditContextFromRequest,\n type AuditScope,\n type RequestContextOptions,\n} from \"../context.ts\";\nimport type { AuditActor, AuditContext } from \"../schema.ts\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\n/**\n * Options for every framework's `auditContext()` middleware. The callbacks\n * receive the framework's own request context (Hono's `c`, Express's `req`,\n * Elysia's `ctx`, Bun's `Request`) so they can read whatever the host's auth\n * already resolved (a session, a decoded JWT, `req.user`, …).\n */\nexport interface AuditContextOptions<Ctx> {\n /** Resolve the actor for events recorded in this request (or nothing). */\n actor?: (ctx: Ctx) => MaybePromise<AuditActor | null | undefined>;\n /** Resolve the tenant for events recorded in this request (or nothing). */\n tenant?: (ctx: Ctx) => MaybePromise<string | null | undefined>;\n /** Extra context keys merged over the captured IP / user agent / request id. */\n context?: (ctx: Ctx) => MaybePromise<AuditContext | null | undefined>;\n /**\n * Trust proxy headers (`x-forwarded-for`, `cf-connecting-ip`, `x-real-ip`,\n * `fly-client-ip`) for the client IP. Default `true` — set `false` when the\n * app is reachable directly, or clients can spoof their IP.\n */\n trustProxy?: boolean;\n /** Header carrying the request id. Default: `x-request-id`, then `cf-ray`. */\n requestIdHeader?: string;\n}\n\n/**\n * Build the scope for one request: IP / user agent / request id from the\n * headers (with `ip` as the socket-level fallback), then the host's actor,\n * tenant and extra context.\n */\nexport async function resolveAuditScope<Ctx>(\n request: Request,\n ctx: Ctx,\n options: AuditContextOptions<Ctx>,\n ip?: string | null,\n): Promise<AuditScope> {\n const reqOptions: RequestContextOptions = {\n ...(options.trustProxy !== undefined ? { trustProxy: options.trustProxy } : {}),\n ...(options.requestIdHeader ? { requestIdHeader: options.requestIdHeader } : {}),\n ...(ip ? { ip } : {}),\n };\n const [actor, tenant, extra] = await Promise.all([\n options.actor?.(ctx),\n options.tenant?.(ctx),\n options.context?.(ctx),\n ]);\n return {\n context: { ...auditContextFromRequest(request, reqOptions), ...extra },\n ...(actor ? { actor } : {}),\n ...(tenant ? { tenant } : {}),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AA8CA,eAAsB,kBACpB,SACA,KACA,SACA,IACqB;CACrB,MAAM,aAAoC;EACxC,GAAI,QAAQ,eAAe,KAAA,IAAY,EAAE,YAAY,QAAQ,WAAW,IAAI,CAAC;EAC7E,GAAI,QAAQ,kBAAkB,EAAE,iBAAiB,QAAQ,gBAAgB,IAAI,CAAC;EAC9E,GAAI,KAAK,EAAE,GAAG,IAAI,CAAC;CACrB;CACA,MAAM,CAAC,OAAO,QAAQ,SAAS,MAAM,QAAQ,IAAI;EAC/C,QAAQ,QAAQ,GAAG;EACnB,QAAQ,SAAS,GAAG;EACpB,QAAQ,UAAU,GAAG;CACvB,CAAC;CACD,OAAO;EACL,SAAS;GAAE,GAAG,wBAAwB,SAAS,UAAU;GAAG,GAAG;EAAM;EACrE,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC;EACzB,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;CAC7B;AACF"}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
const require_context = require("./context.cjs");
|
|
2
|
+
//#region src/adapters/context-shared.ts
|
|
3
|
+
/**
|
|
4
|
+
* Framework-independent half of the `auditContext()` middlewares (ADR 0013):
|
|
5
|
+
* the options every adapter accepts and the resolution of an {@link AuditScope}
|
|
6
|
+
* from a web-standard `Request` plus the framework's own context object.
|
|
7
|
+
* Must not import any framework.
|
|
8
|
+
*
|
|
9
|
+
* @module
|
|
10
|
+
*/
|
|
11
|
+
/**
|
|
12
|
+
* Build the scope for one request: IP / user agent / request id from the
|
|
13
|
+
* headers (with `ip` as the socket-level fallback), then the host's actor,
|
|
14
|
+
* tenant and extra context.
|
|
15
|
+
*/
|
|
16
|
+
async function resolveAuditScope(request, ctx, options, ip) {
|
|
17
|
+
const reqOptions = {
|
|
18
|
+
...options.trustProxy !== void 0 ? { trustProxy: options.trustProxy } : {},
|
|
19
|
+
...options.requestIdHeader ? { requestIdHeader: options.requestIdHeader } : {},
|
|
20
|
+
...ip ? { ip } : {}
|
|
21
|
+
};
|
|
22
|
+
const [actor, tenant, extra] = await Promise.all([
|
|
23
|
+
options.actor?.(ctx),
|
|
24
|
+
options.tenant?.(ctx),
|
|
25
|
+
options.context?.(ctx)
|
|
26
|
+
]);
|
|
27
|
+
return {
|
|
28
|
+
context: {
|
|
29
|
+
...require_context.auditContextFromRequest(request, reqOptions),
|
|
30
|
+
...extra
|
|
31
|
+
},
|
|
32
|
+
...actor ? { actor } : {},
|
|
33
|
+
...tenant ? { tenant } : {}
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
//#endregion
|
|
37
|
+
Object.defineProperty(exports, "resolveAuditScope", {
|
|
38
|
+
enumerable: true,
|
|
39
|
+
get: function() {
|
|
40
|
+
return resolveAuditScope;
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
//# sourceMappingURL=context-shared-X2ulHHSB.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context-shared-X2ulHHSB.cjs","names":["auditContextFromRequest"],"sources":["../src/adapters/context-shared.ts"],"sourcesContent":["/**\n * Framework-independent half of the `auditContext()` middlewares (ADR 0013):\n * the options every adapter accepts and the resolution of an {@link AuditScope}\n * from a web-standard `Request` plus the framework's own context object.\n * Must not import any framework.\n *\n * @module\n */\n\nimport {\n auditContextFromRequest,\n type AuditScope,\n type RequestContextOptions,\n} from \"../context.ts\";\nimport type { AuditActor, AuditContext } from \"../schema.ts\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\n/**\n * Options for every framework's `auditContext()` middleware. The callbacks\n * receive the framework's own request context (Hono's `c`, Express's `req`,\n * Elysia's `ctx`, Bun's `Request`) so they can read whatever the host's auth\n * already resolved (a session, a decoded JWT, `req.user`, …).\n */\nexport interface AuditContextOptions<Ctx> {\n /** Resolve the actor for events recorded in this request (or nothing). */\n actor?: (ctx: Ctx) => MaybePromise<AuditActor | null | undefined>;\n /** Resolve the tenant for events recorded in this request (or nothing). */\n tenant?: (ctx: Ctx) => MaybePromise<string | null | undefined>;\n /** Extra context keys merged over the captured IP / user agent / request id. */\n context?: (ctx: Ctx) => MaybePromise<AuditContext | null | undefined>;\n /**\n * Trust proxy headers (`x-forwarded-for`, `cf-connecting-ip`, `x-real-ip`,\n * `fly-client-ip`) for the client IP. Default `true` — set `false` when the\n * app is reachable directly, or clients can spoof their IP.\n */\n trustProxy?: boolean;\n /** Header carrying the request id. Default: `x-request-id`, then `cf-ray`. */\n requestIdHeader?: string;\n}\n\n/**\n * Build the scope for one request: IP / user agent / request id from the\n * headers (with `ip` as the socket-level fallback), then the host's actor,\n * tenant and extra context.\n */\nexport async function resolveAuditScope<Ctx>(\n request: Request,\n ctx: Ctx,\n options: AuditContextOptions<Ctx>,\n ip?: string | null,\n): Promise<AuditScope> {\n const reqOptions: RequestContextOptions = {\n ...(options.trustProxy !== undefined ? { trustProxy: options.trustProxy } : {}),\n ...(options.requestIdHeader ? { requestIdHeader: options.requestIdHeader } : {}),\n ...(ip ? { ip } : {}),\n };\n const [actor, tenant, extra] = await Promise.all([\n options.actor?.(ctx),\n options.tenant?.(ctx),\n options.context?.(ctx),\n ]);\n return {\n context: { ...auditContextFromRequest(request, reqOptions), ...extra },\n ...(actor ? { actor } : {}),\n ...(tenant ? { tenant } : {}),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AA8CA,eAAsB,kBACpB,SACA,KACA,SACA,IACqB;CACrB,MAAM,aAAoC;EACxC,GAAI,QAAQ,eAAe,KAAA,IAAY,EAAE,YAAY,QAAQ,WAAW,IAAI,CAAC;EAC7E,GAAI,QAAQ,kBAAkB,EAAE,iBAAiB,QAAQ,gBAAgB,IAAI,CAAC;EAC9E,GAAI,KAAK,EAAE,GAAG,IAAI,CAAC;CACrB;CACA,MAAM,CAAC,OAAO,QAAQ,SAAS,MAAM,QAAQ,IAAI;EAC/C,QAAQ,QAAQ,GAAG;EACnB,QAAQ,SAAS,GAAG;EACpB,QAAQ,UAAU,GAAG;CACvB,CAAC;CACD,OAAO;EACL,SAAS;GAAE,GAAGA,gBAAAA,wBAAwB,SAAS,UAAU;GAAG,GAAG;EAAM;EACrE,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC;EACzB,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;CAC7B;AACF"}
|
package/dist/context.cjs
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let node_async_hooks = require("node:async_hooks");
|
|
3
|
+
//#region src/context.ts
|
|
4
|
+
/**
|
|
5
|
+
* Ambient request context (ADR 0013): open a scope per request with the actor,
|
|
6
|
+
* tenant, IP, user agent and request id, and every `record()` inside it picks
|
|
7
|
+
* them up — no threading through call sites. Pattern borrowed from
|
|
8
|
+
* `drizzle-audit`'s context.
|
|
9
|
+
*
|
|
10
|
+
* Uses `node:async_hooks` `AsyncLocalStorage` (Bun, Node, Deno, Cloudflare
|
|
11
|
+
* Workers with `nodejs_compat`). Framework adapters wrap this in an
|
|
12
|
+
* `auditContext()` middleware.
|
|
13
|
+
*
|
|
14
|
+
* Import from `@xtandard/audit/context`.
|
|
15
|
+
*
|
|
16
|
+
* @module context
|
|
17
|
+
*/
|
|
18
|
+
const ALS_KEY = Symbol.for("@xtandard/audit:context");
|
|
19
|
+
const g = globalThis;
|
|
20
|
+
const storage = g[ALS_KEY] ??= new node_async_hooks.AsyncLocalStorage();
|
|
21
|
+
/** The current scope, or `null` outside any scope. Never throws. */
|
|
22
|
+
function getAuditContext() {
|
|
23
|
+
return storage.getStore() ?? null;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Run `fn` inside a scope. Nested scopes inherit and override the outer one
|
|
27
|
+
* (`context` keys merge).
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* ```ts
|
|
31
|
+
* import { runWithAuditContext } from "@xtandard/audit/context";
|
|
32
|
+
*
|
|
33
|
+
* await runWithAuditContext({ actor: { id: user.id }, tenant: user.orgId }, () =>
|
|
34
|
+
* audit.record({ action: "invoice.paid", metadata: { invoiceId } }),
|
|
35
|
+
* );
|
|
36
|
+
* ```
|
|
37
|
+
*/
|
|
38
|
+
function runWithAuditContext(scope, fn) {
|
|
39
|
+
return storage.run(mergeScopes(getAuditContext(), scope), fn);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Patch the current scope for the rest of the current async execution
|
|
43
|
+
* (`enterWith` semantics) — for middleware that cannot wrap `next()`, or to
|
|
44
|
+
* attach the actor once auth resolves.
|
|
45
|
+
*/
|
|
46
|
+
function setAuditContext(patch) {
|
|
47
|
+
storage.enterWith(mergeScopes(getAuditContext(), patch));
|
|
48
|
+
}
|
|
49
|
+
function mergeScopes(base, patch) {
|
|
50
|
+
if (!base) return { ...patch };
|
|
51
|
+
return {
|
|
52
|
+
...base,
|
|
53
|
+
...patch,
|
|
54
|
+
...base.context || patch.context ? { context: {
|
|
55
|
+
...base.context,
|
|
56
|
+
...patch.context
|
|
57
|
+
} } : {}
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
/** Extract `{ ip, userAgent, requestId }` from a web-standard Request. */
|
|
61
|
+
function auditContextFromRequest(request, options = {}) {
|
|
62
|
+
const h = request.headers;
|
|
63
|
+
const ctx = {};
|
|
64
|
+
if (options.trustProxy ?? true) {
|
|
65
|
+
const forwarded = h.get("x-forwarded-for")?.split(",")[0]?.trim();
|
|
66
|
+
const ip = h.get("cf-connecting-ip") ?? forwarded ?? h.get("x-real-ip") ?? h.get("fly-client-ip");
|
|
67
|
+
if (ip) ctx.ip = ip;
|
|
68
|
+
}
|
|
69
|
+
if (!ctx.ip && options.ip) ctx.ip = options.ip;
|
|
70
|
+
const ua = h.get("user-agent");
|
|
71
|
+
if (ua) ctx.userAgent = ua;
|
|
72
|
+
const requestId = options.requestIdHeader ? h.get(options.requestIdHeader) : h.get("x-request-id") ?? h.get("cf-ray");
|
|
73
|
+
if (requestId) ctx.requestId = requestId;
|
|
74
|
+
return ctx;
|
|
75
|
+
}
|
|
76
|
+
//#endregion
|
|
77
|
+
exports.auditContextFromRequest = auditContextFromRequest;
|
|
78
|
+
exports.getAuditContext = getAuditContext;
|
|
79
|
+
exports.runWithAuditContext = runWithAuditContext;
|
|
80
|
+
exports.setAuditContext = setAuditContext;
|
|
81
|
+
|
|
82
|
+
//# sourceMappingURL=context.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.cjs","names":["AsyncLocalStorage"],"sources":["../src/context.ts"],"sourcesContent":["/**\n * Ambient request context (ADR 0013): open a scope per request with the actor,\n * tenant, IP, user agent and request id, and every `record()` inside it picks\n * them up — no threading through call sites. Pattern borrowed from\n * `drizzle-audit`'s context.\n *\n * Uses `node:async_hooks` `AsyncLocalStorage` (Bun, Node, Deno, Cloudflare\n * Workers with `nodejs_compat`). Framework adapters wrap this in an\n * `auditContext()` middleware.\n *\n * Import from `@xtandard/audit/context`.\n *\n * @module context\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { AuditActor, AuditContext } from \"./schema.ts\";\n\n/** What a request scope carries. */\nexport interface AuditScope {\n /** Default actor for events recorded in this scope. */\n actor?: AuditActor;\n /** Default tenant for events recorded in this scope. */\n tenant?: string;\n /** Request context merged under each event's explicit `context`. */\n context?: AuditContext;\n}\n\n// One store per process even if the module is loaded twice (dual ESM/CJS).\nconst ALS_KEY = Symbol.for(\"@xtandard/audit:context\");\nconst g = globalThis as unknown as Record<symbol, AsyncLocalStorage<AuditScope> | undefined>;\nconst storage: AsyncLocalStorage<AuditScope> = (g[ALS_KEY] ??= new AsyncLocalStorage<AuditScope>());\n\n/** The current scope, or `null` outside any scope. Never throws. */\nexport function getAuditContext(): AuditScope | null {\n return storage.getStore() ?? null;\n}\n\n/**\n * Run `fn` inside a scope. Nested scopes inherit and override the outer one\n * (`context` keys merge).\n *\n * @example\n * ```ts\n * import { runWithAuditContext } from \"@xtandard/audit/context\";\n *\n * await runWithAuditContext({ actor: { id: user.id }, tenant: user.orgId }, () =>\n * audit.record({ action: \"invoice.paid\", metadata: { invoiceId } }),\n * );\n * ```\n */\nexport function runWithAuditContext<T>(scope: AuditScope, fn: () => T): T {\n return storage.run(mergeScopes(getAuditContext(), scope), fn);\n}\n\n/**\n * Patch the current scope for the rest of the current async execution\n * (`enterWith` semantics) — for middleware that cannot wrap `next()`, or to\n * attach the actor once auth resolves.\n */\nexport function setAuditContext(patch: AuditScope): void {\n storage.enterWith(mergeScopes(getAuditContext(), patch));\n}\n\nfunction mergeScopes(base: AuditScope | null, patch: AuditScope): AuditScope {\n if (!base) return { ...patch };\n return {\n ...base,\n ...patch,\n ...(base.context || patch.context ? { context: { ...base.context, ...patch.context } } : {}),\n };\n}\n\n/** Options for {@link auditContextFromRequest}. */\nexport interface RequestContextOptions {\n /**\n * Trust proxy headers (`x-forwarded-for`, `cf-connecting-ip`, `x-real-ip`,\n * `fly-client-ip`) for the client IP. Default `true` — set `false` when the\n * app is reachable directly, or clients can spoof their IP.\n */\n trustProxy?: boolean;\n /** Header carrying the request id. Default: `x-request-id`, then `cf-ray`. */\n requestIdHeader?: string;\n /** Fallback IP when no header carries one (e.g. Bun's `server.requestIP`). */\n ip?: string;\n}\n\n/** Extract `{ ip, userAgent, requestId }` from a web-standard Request. */\nexport function auditContextFromRequest(\n request: Request,\n options: RequestContextOptions = {},\n): AuditContext {\n const h = request.headers;\n const ctx: AuditContext = {};\n if (options.trustProxy ?? true) {\n const forwarded = h.get(\"x-forwarded-for\")?.split(\",\")[0]?.trim();\n const ip =\n h.get(\"cf-connecting-ip\") ?? forwarded ?? h.get(\"x-real-ip\") ?? h.get(\"fly-client-ip\");\n if (ip) ctx.ip = ip;\n }\n if (!ctx.ip && options.ip) ctx.ip = options.ip;\n const ua = h.get(\"user-agent\");\n if (ua) ctx.userAgent = ua;\n const requestId = options.requestIdHeader\n ? h.get(options.requestIdHeader)\n : (h.get(\"x-request-id\") ?? h.get(\"cf-ray\"));\n if (requestId) ctx.requestId = requestId;\n return ctx;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA6BA,MAAM,UAAU,OAAO,IAAI,yBAAyB;AACpD,MAAM,IAAI;AACV,MAAM,UAA0C,EAAE,aAAa,IAAIA,iBAAAA,kBAA8B;;AAGjG,SAAgB,kBAAqC;CACnD,OAAO,QAAQ,SAAS,KAAK;AAC/B;;;;;;;;;;;;;;AAeA,SAAgB,oBAAuB,OAAmB,IAAgB;CACxE,OAAO,QAAQ,IAAI,YAAY,gBAAgB,GAAG,KAAK,GAAG,EAAE;AAC9D;;;;;;AAOA,SAAgB,gBAAgB,OAAyB;CACvD,QAAQ,UAAU,YAAY,gBAAgB,GAAG,KAAK,CAAC;AACzD;AAEA,SAAS,YAAY,MAAyB,OAA+B;CAC3E,IAAI,CAAC,MAAM,OAAO,EAAE,GAAG,MAAM;CAC7B,OAAO;EACL,GAAG;EACH,GAAG;EACH,GAAI,KAAK,WAAW,MAAM,UAAU,EAAE,SAAS;GAAE,GAAG,KAAK;GAAS,GAAG,MAAM;EAAQ,EAAE,IAAI,CAAC;CAC5F;AACF;;AAiBA,SAAgB,wBACd,SACA,UAAiC,CAAC,GACpB;CACd,MAAM,IAAI,QAAQ;CAClB,MAAM,MAAoB,CAAC;CAC3B,IAAI,QAAQ,cAAc,MAAM;EAC9B,MAAM,YAAY,EAAE,IAAI,iBAAiB,GAAG,MAAM,GAAG,EAAE,IAAI,KAAK;EAChE,MAAM,KACJ,EAAE,IAAI,kBAAkB,KAAK,aAAa,EAAE,IAAI,WAAW,KAAK,EAAE,IAAI,eAAe;EACvF,IAAI,IAAI,IAAI,KAAK;CACnB;CACA,IAAI,CAAC,IAAI,MAAM,QAAQ,IAAI,IAAI,KAAK,QAAQ;CAC5C,MAAM,KAAK,EAAE,IAAI,YAAY;CAC7B,IAAI,IAAI,IAAI,YAAY;CACxB,MAAM,YAAY,QAAQ,kBACtB,EAAE,IAAI,QAAQ,eAAe,IAC5B,EAAE,IAAI,cAAc,KAAK,EAAE,IAAI,QAAQ;CAC5C,IAAI,WAAW,IAAI,YAAY;CAC/B,OAAO;AACT"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as runWithAuditContext, i as getAuditContext, n as RequestContextOptions, o as setAuditContext, r as auditContextFromRequest, t as AuditScope } from "./context-CJM87uG8.cjs";
|
|
2
|
+
export { AuditScope, RequestContextOptions, auditContextFromRequest, getAuditContext, runWithAuditContext, setAuditContext };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as runWithAuditContext, i as getAuditContext, n as RequestContextOptions, o as setAuditContext, r as auditContextFromRequest, t as AuditScope } from "./context-BtR9k9Mt.mjs";
|
|
2
|
+
export { AuditScope, RequestContextOptions, auditContextFromRequest, getAuditContext, runWithAuditContext, setAuditContext };
|
package/dist/context.mjs
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
//#region src/context.ts
|
|
3
|
+
/**
|
|
4
|
+
* Ambient request context (ADR 0013): open a scope per request with the actor,
|
|
5
|
+
* tenant, IP, user agent and request id, and every `record()` inside it picks
|
|
6
|
+
* them up — no threading through call sites. Pattern borrowed from
|
|
7
|
+
* `drizzle-audit`'s context.
|
|
8
|
+
*
|
|
9
|
+
* Uses `node:async_hooks` `AsyncLocalStorage` (Bun, Node, Deno, Cloudflare
|
|
10
|
+
* Workers with `nodejs_compat`). Framework adapters wrap this in an
|
|
11
|
+
* `auditContext()` middleware.
|
|
12
|
+
*
|
|
13
|
+
* Import from `@xtandard/audit/context`.
|
|
14
|
+
*
|
|
15
|
+
* @module context
|
|
16
|
+
*/
|
|
17
|
+
const ALS_KEY = Symbol.for("@xtandard/audit:context");
|
|
18
|
+
const g = globalThis;
|
|
19
|
+
const storage = g[ALS_KEY] ??= new AsyncLocalStorage();
|
|
20
|
+
/** The current scope, or `null` outside any scope. Never throws. */
|
|
21
|
+
function getAuditContext() {
|
|
22
|
+
return storage.getStore() ?? null;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Run `fn` inside a scope. Nested scopes inherit and override the outer one
|
|
26
|
+
* (`context` keys merge).
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```ts
|
|
30
|
+
* import { runWithAuditContext } from "@xtandard/audit/context";
|
|
31
|
+
*
|
|
32
|
+
* await runWithAuditContext({ actor: { id: user.id }, tenant: user.orgId }, () =>
|
|
33
|
+
* audit.record({ action: "invoice.paid", metadata: { invoiceId } }),
|
|
34
|
+
* );
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
function runWithAuditContext(scope, fn) {
|
|
38
|
+
return storage.run(mergeScopes(getAuditContext(), scope), fn);
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Patch the current scope for the rest of the current async execution
|
|
42
|
+
* (`enterWith` semantics) — for middleware that cannot wrap `next()`, or to
|
|
43
|
+
* attach the actor once auth resolves.
|
|
44
|
+
*/
|
|
45
|
+
function setAuditContext(patch) {
|
|
46
|
+
storage.enterWith(mergeScopes(getAuditContext(), patch));
|
|
47
|
+
}
|
|
48
|
+
function mergeScopes(base, patch) {
|
|
49
|
+
if (!base) return { ...patch };
|
|
50
|
+
return {
|
|
51
|
+
...base,
|
|
52
|
+
...patch,
|
|
53
|
+
...base.context || patch.context ? { context: {
|
|
54
|
+
...base.context,
|
|
55
|
+
...patch.context
|
|
56
|
+
} } : {}
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
/** Extract `{ ip, userAgent, requestId }` from a web-standard Request. */
|
|
60
|
+
function auditContextFromRequest(request, options = {}) {
|
|
61
|
+
const h = request.headers;
|
|
62
|
+
const ctx = {};
|
|
63
|
+
if (options.trustProxy ?? true) {
|
|
64
|
+
const forwarded = h.get("x-forwarded-for")?.split(",")[0]?.trim();
|
|
65
|
+
const ip = h.get("cf-connecting-ip") ?? forwarded ?? h.get("x-real-ip") ?? h.get("fly-client-ip");
|
|
66
|
+
if (ip) ctx.ip = ip;
|
|
67
|
+
}
|
|
68
|
+
if (!ctx.ip && options.ip) ctx.ip = options.ip;
|
|
69
|
+
const ua = h.get("user-agent");
|
|
70
|
+
if (ua) ctx.userAgent = ua;
|
|
71
|
+
const requestId = options.requestIdHeader ? h.get(options.requestIdHeader) : h.get("x-request-id") ?? h.get("cf-ray");
|
|
72
|
+
if (requestId) ctx.requestId = requestId;
|
|
73
|
+
return ctx;
|
|
74
|
+
}
|
|
75
|
+
//#endregion
|
|
76
|
+
export { auditContextFromRequest, getAuditContext, runWithAuditContext, setAuditContext };
|
|
77
|
+
|
|
78
|
+
//# sourceMappingURL=context.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.mjs","names":[],"sources":["../src/context.ts"],"sourcesContent":["/**\n * Ambient request context (ADR 0013): open a scope per request with the actor,\n * tenant, IP, user agent and request id, and every `record()` inside it picks\n * them up — no threading through call sites. Pattern borrowed from\n * `drizzle-audit`'s context.\n *\n * Uses `node:async_hooks` `AsyncLocalStorage` (Bun, Node, Deno, Cloudflare\n * Workers with `nodejs_compat`). Framework adapters wrap this in an\n * `auditContext()` middleware.\n *\n * Import from `@xtandard/audit/context`.\n *\n * @module context\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { AuditActor, AuditContext } from \"./schema.ts\";\n\n/** What a request scope carries. */\nexport interface AuditScope {\n /** Default actor for events recorded in this scope. */\n actor?: AuditActor;\n /** Default tenant for events recorded in this scope. */\n tenant?: string;\n /** Request context merged under each event's explicit `context`. */\n context?: AuditContext;\n}\n\n// One store per process even if the module is loaded twice (dual ESM/CJS).\nconst ALS_KEY = Symbol.for(\"@xtandard/audit:context\");\nconst g = globalThis as unknown as Record<symbol, AsyncLocalStorage<AuditScope> | undefined>;\nconst storage: AsyncLocalStorage<AuditScope> = (g[ALS_KEY] ??= new AsyncLocalStorage<AuditScope>());\n\n/** The current scope, or `null` outside any scope. Never throws. */\nexport function getAuditContext(): AuditScope | null {\n return storage.getStore() ?? null;\n}\n\n/**\n * Run `fn` inside a scope. Nested scopes inherit and override the outer one\n * (`context` keys merge).\n *\n * @example\n * ```ts\n * import { runWithAuditContext } from \"@xtandard/audit/context\";\n *\n * await runWithAuditContext({ actor: { id: user.id }, tenant: user.orgId }, () =>\n * audit.record({ action: \"invoice.paid\", metadata: { invoiceId } }),\n * );\n * ```\n */\nexport function runWithAuditContext<T>(scope: AuditScope, fn: () => T): T {\n return storage.run(mergeScopes(getAuditContext(), scope), fn);\n}\n\n/**\n * Patch the current scope for the rest of the current async execution\n * (`enterWith` semantics) — for middleware that cannot wrap `next()`, or to\n * attach the actor once auth resolves.\n */\nexport function setAuditContext(patch: AuditScope): void {\n storage.enterWith(mergeScopes(getAuditContext(), patch));\n}\n\nfunction mergeScopes(base: AuditScope | null, patch: AuditScope): AuditScope {\n if (!base) return { ...patch };\n return {\n ...base,\n ...patch,\n ...(base.context || patch.context ? { context: { ...base.context, ...patch.context } } : {}),\n };\n}\n\n/** Options for {@link auditContextFromRequest}. */\nexport interface RequestContextOptions {\n /**\n * Trust proxy headers (`x-forwarded-for`, `cf-connecting-ip`, `x-real-ip`,\n * `fly-client-ip`) for the client IP. Default `true` — set `false` when the\n * app is reachable directly, or clients can spoof their IP.\n */\n trustProxy?: boolean;\n /** Header carrying the request id. Default: `x-request-id`, then `cf-ray`. */\n requestIdHeader?: string;\n /** Fallback IP when no header carries one (e.g. Bun's `server.requestIP`). */\n ip?: string;\n}\n\n/** Extract `{ ip, userAgent, requestId }` from a web-standard Request. */\nexport function auditContextFromRequest(\n request: Request,\n options: RequestContextOptions = {},\n): AuditContext {\n const h = request.headers;\n const ctx: AuditContext = {};\n if (options.trustProxy ?? true) {\n const forwarded = h.get(\"x-forwarded-for\")?.split(\",\")[0]?.trim();\n const ip =\n h.get(\"cf-connecting-ip\") ?? forwarded ?? h.get(\"x-real-ip\") ?? h.get(\"fly-client-ip\");\n if (ip) ctx.ip = ip;\n }\n if (!ctx.ip && options.ip) ctx.ip = options.ip;\n const ua = h.get(\"user-agent\");\n if (ua) ctx.userAgent = ua;\n const requestId = options.requestIdHeader\n ? h.get(options.requestIdHeader)\n : (h.get(\"x-request-id\") ?? h.get(\"cf-ray\"));\n if (requestId) ctx.requestId = requestId;\n return ctx;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA6BA,MAAM,UAAU,OAAO,IAAI,yBAAyB;AACpD,MAAM,IAAI;AACV,MAAM,UAA0C,EAAE,aAAa,IAAI,kBAA8B;;AAGjG,SAAgB,kBAAqC;CACnD,OAAO,QAAQ,SAAS,KAAK;AAC/B;;;;;;;;;;;;;;AAeA,SAAgB,oBAAuB,OAAmB,IAAgB;CACxE,OAAO,QAAQ,IAAI,YAAY,gBAAgB,GAAG,KAAK,GAAG,EAAE;AAC9D;;;;;;AAOA,SAAgB,gBAAgB,OAAyB;CACvD,QAAQ,UAAU,YAAY,gBAAgB,GAAG,KAAK,CAAC;AACzD;AAEA,SAAS,YAAY,MAAyB,OAA+B;CAC3E,IAAI,CAAC,MAAM,OAAO,EAAE,GAAG,MAAM;CAC7B,OAAO;EACL,GAAG;EACH,GAAG;EACH,GAAI,KAAK,WAAW,MAAM,UAAU,EAAE,SAAS;GAAE,GAAG,KAAK;GAAS,GAAG,MAAM;EAAQ,EAAE,IAAI,CAAC;CAC5F;AACF;;AAiBA,SAAgB,wBACd,SACA,UAAiC,CAAC,GACpB;CACd,MAAM,IAAI,QAAQ;CAClB,MAAM,MAAoB,CAAC;CAC3B,IAAI,QAAQ,cAAc,MAAM;EAC9B,MAAM,YAAY,EAAE,IAAI,iBAAiB,GAAG,MAAM,GAAG,EAAE,IAAI,KAAK;EAChE,MAAM,KACJ,EAAE,IAAI,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