@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.
Files changed (423) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +386 -2
  3. package/bin/xtandard-audit.mjs +3 -0
  4. package/dist/basic-DU_nPrWV.mjs +176 -0
  5. package/dist/basic-DU_nPrWV.mjs.map +1 -0
  6. package/dist/basic-hcXnMF9X.cjs +199 -0
  7. package/dist/basic-hcXnMF9X.cjs.map +1 -0
  8. package/dist/canonical-BOgkrX9_.d.cts +17 -0
  9. package/dist/canonical-CL7gfwhb.d.mts +17 -0
  10. package/dist/chunk-D7D4PA-g.mjs +13 -0
  11. package/dist/cli.cjs +773 -0
  12. package/dist/cli.cjs.map +1 -0
  13. package/dist/cli.d.cts +46 -0
  14. package/dist/cli.d.mts +46 -0
  15. package/dist/cli.mjs +762 -0
  16. package/dist/cli.mjs.map +1 -0
  17. package/dist/context-BtR9k9Mt.d.mts +52 -0
  18. package/dist/context-CJM87uG8.d.cts +52 -0
  19. package/dist/context-shared-AgBWIRUQ.d.mts +29 -0
  20. package/dist/context-shared-CUq3cSpV.d.cts +29 -0
  21. package/dist/context-shared-CupikwQo.mjs +39 -0
  22. package/dist/context-shared-CupikwQo.mjs.map +1 -0
  23. package/dist/context-shared-X2ulHHSB.cjs +44 -0
  24. package/dist/context-shared-X2ulHHSB.cjs.map +1 -0
  25. package/dist/context.cjs +82 -0
  26. package/dist/context.cjs.map +1 -0
  27. package/dist/context.d.cts +2 -0
  28. package/dist/context.d.mts +2 -0
  29. package/dist/context.mjs +78 -0
  30. package/dist/context.mjs.map +1 -0
  31. package/dist/contract-BljSE-Hx.mjs +33 -0
  32. package/dist/contract-BljSE-Hx.mjs.map +1 -0
  33. package/dist/contract-BmwHIiMR.d.mts +150 -0
  34. package/dist/contract-CWJSYoJl.d.cts +150 -0
  35. package/dist/contract-Cht05WYQ.d.mts +159 -0
  36. package/dist/contract-CqYQzB6e.d.cts +49 -0
  37. package/dist/contract-DYvBNdnR.cjs +74 -0
  38. package/dist/contract-DYvBNdnR.cjs.map +1 -0
  39. package/dist/contract-DlTo4u2t.d.cts +30 -0
  40. package/dist/contract-DlTo4u2t.d.mts +30 -0
  41. package/dist/contract-DsVL5-gy.cjs +50 -0
  42. package/dist/contract-DsVL5-gy.cjs.map +1 -0
  43. package/dist/contract-isM9SjjQ.mjs +39 -0
  44. package/dist/contract-isM9SjjQ.mjs.map +1 -0
  45. package/dist/contract-pU3wGFmo.d.cts +159 -0
  46. package/dist/contract-yPNuFnVy.d.mts +49 -0
  47. package/dist/core-C0ceVOTk.d.cts +513 -0
  48. package/dist/core-CTr7dw0v.cjs +1725 -0
  49. package/dist/core-CTr7dw0v.cjs.map +1 -0
  50. package/dist/core-IdGEbYdM.mjs +1541 -0
  51. package/dist/core-IdGEbYdM.mjs.map +1 -0
  52. package/dist/core-KtEHRScZ.d.mts +513 -0
  53. package/dist/core.cjs +9 -0
  54. package/dist/core.d.cts +2 -0
  55. package/dist/core.d.mts +2 -0
  56. package/dist/core.mjs +2 -0
  57. package/dist/create-fetch-handler-1pXSEhGi.d.cts +311 -0
  58. package/dist/create-fetch-handler-BwQQ_IWf.mjs +2156 -0
  59. package/dist/create-fetch-handler-BwQQ_IWf.mjs.map +1 -0
  60. package/dist/create-fetch-handler-D8cTMVX9.cjs +2232 -0
  61. package/dist/create-fetch-handler-D8cTMVX9.cjs.map +1 -0
  62. package/dist/create-fetch-handler-zioPVS18.d.mts +311 -0
  63. package/dist/elysia-shared-C7geKqPP.mjs +55 -0
  64. package/dist/elysia-shared-C7geKqPP.mjs.map +1 -0
  65. package/dist/elysia-shared-DT4bfekR.d.cts +20 -0
  66. package/dist/elysia-shared-DXyAyGz_.cjs +66 -0
  67. package/dist/elysia-shared-DXyAyGz_.cjs.map +1 -0
  68. package/dist/elysia-shared-DoL5ab52.d.mts +20 -0
  69. package/dist/entry-auth-basic.cjs +5 -0
  70. package/dist/entry-auth-basic.d.cts +83 -0
  71. package/dist/entry-auth-basic.d.mts +83 -0
  72. package/dist/entry-auth-basic.mjs +2 -0
  73. package/dist/entry-auth-delegated.cjs +28 -0
  74. package/dist/entry-auth-delegated.cjs.map +1 -0
  75. package/dist/entry-auth-delegated.d.cts +36 -0
  76. package/dist/entry-auth-delegated.d.mts +36 -0
  77. package/dist/entry-auth-delegated.mjs +27 -0
  78. package/dist/entry-auth-delegated.mjs.map +1 -0
  79. package/dist/entry-auth-none.cjs +4 -0
  80. package/dist/entry-auth-none.d.cts +25 -0
  81. package/dist/entry-auth-none.d.mts +25 -0
  82. package/dist/entry-auth-none.mjs +2 -0
  83. package/dist/entry-authorization-delegated.cjs +28 -0
  84. package/dist/entry-authorization-delegated.cjs.map +1 -0
  85. package/dist/entry-authorization-delegated.d.cts +32 -0
  86. package/dist/entry-authorization-delegated.d.mts +32 -0
  87. package/dist/entry-authorization-delegated.mjs +27 -0
  88. package/dist/entry-authorization-delegated.mjs.map +1 -0
  89. package/dist/entry-authorization-none.cjs +3 -0
  90. package/dist/entry-authorization-none.d.cts +18 -0
  91. package/dist/entry-authorization-none.d.mts +18 -0
  92. package/dist/entry-authorization-none.mjs +2 -0
  93. package/dist/entry-authorization-roles.cjs +8 -0
  94. package/dist/entry-authorization-roles.d.cts +64 -0
  95. package/dist/entry-authorization-roles.d.mts +64 -0
  96. package/dist/entry-authorization-roles.mjs +3 -0
  97. package/dist/entry-bun.cjs +55 -0
  98. package/dist/entry-bun.cjs.map +1 -0
  99. package/dist/entry-bun.d.cts +29 -0
  100. package/dist/entry-bun.d.mts +29 -0
  101. package/dist/entry-bun.mjs +52 -0
  102. package/dist/entry-bun.mjs.map +1 -0
  103. package/dist/entry-drizzle-audit.cjs +191 -0
  104. package/dist/entry-drizzle-audit.cjs.map +1 -0
  105. package/dist/entry-drizzle-audit.d.cts +118 -0
  106. package/dist/entry-drizzle-audit.d.mts +118 -0
  107. package/dist/entry-drizzle-audit.mjs +186 -0
  108. package/dist/entry-drizzle-audit.mjs.map +1 -0
  109. package/dist/entry-drizzle-mysql.cjs +75 -0
  110. package/dist/entry-drizzle-mysql.cjs.map +1 -0
  111. package/dist/entry-drizzle-mysql.d.cts +42 -0
  112. package/dist/entry-drizzle-mysql.d.mts +42 -0
  113. package/dist/entry-drizzle-mysql.mjs +71 -0
  114. package/dist/entry-drizzle-mysql.mjs.map +1 -0
  115. package/dist/entry-drizzle-pg.cjs +82 -0
  116. package/dist/entry-drizzle-pg.cjs.map +1 -0
  117. package/dist/entry-drizzle-pg.d.cts +48 -0
  118. package/dist/entry-drizzle-pg.d.mts +48 -0
  119. package/dist/entry-drizzle-pg.mjs +78 -0
  120. package/dist/entry-drizzle-pg.mjs.map +1 -0
  121. package/dist/entry-drizzle-sqlite.cjs +71 -0
  122. package/dist/entry-drizzle-sqlite.cjs.map +1 -0
  123. package/dist/entry-drizzle-sqlite.d.cts +37 -0
  124. package/dist/entry-drizzle-sqlite.d.mts +37 -0
  125. package/dist/entry-drizzle-sqlite.mjs +67 -0
  126. package/dist/entry-drizzle-sqlite.mjs.map +1 -0
  127. package/dist/entry-elysia.cjs +112 -0
  128. package/dist/entry-elysia.cjs.map +1 -0
  129. package/dist/entry-elysia.d.cts +710 -0
  130. package/dist/entry-elysia.d.mts +710 -0
  131. package/dist/entry-elysia.mjs +109 -0
  132. package/dist/entry-elysia.mjs.map +1 -0
  133. package/dist/entry-elysia2.cjs +101 -0
  134. package/dist/entry-elysia2.cjs.map +1 -0
  135. package/dist/entry-elysia2.d.cts +905 -0
  136. package/dist/entry-elysia2.d.mts +905 -0
  137. package/dist/entry-elysia2.mjs +98 -0
  138. package/dist/entry-elysia2.mjs.map +1 -0
  139. package/dist/entry-express.cjs +90 -0
  140. package/dist/entry-express.cjs.map +1 -0
  141. package/dist/entry-express.d.cts +24 -0
  142. package/dist/entry-express.d.mts +24 -0
  143. package/dist/entry-express.mjs +88 -0
  144. package/dist/entry-express.mjs.map +1 -0
  145. package/dist/entry-hono.cjs +36 -0
  146. package/dist/entry-hono.cjs.map +1 -0
  147. package/dist/entry-hono.d.cts +24 -0
  148. package/dist/entry-hono.d.mts +24 -0
  149. package/dist/entry-hono.mjs +34 -0
  150. package/dist/entry-hono.mjs.map +1 -0
  151. package/dist/entry-hooks-log.cjs +22 -0
  152. package/dist/entry-hooks-log.cjs.map +1 -0
  153. package/dist/entry-hooks-log.d.cts +23 -0
  154. package/dist/entry-hooks-log.d.mts +23 -0
  155. package/dist/entry-hooks-log.mjs +21 -0
  156. package/dist/entry-hooks-log.mjs.map +1 -0
  157. package/dist/entry-sinks-console.cjs +43 -0
  158. package/dist/entry-sinks-console.cjs.map +1 -0
  159. package/dist/entry-sinks-console.d.cts +26 -0
  160. package/dist/entry-sinks-console.d.mts +26 -0
  161. package/dist/entry-sinks-console.mjs +41 -0
  162. package/dist/entry-sinks-console.mjs.map +1 -0
  163. package/dist/entry-sinks-datadog.cjs +97 -0
  164. package/dist/entry-sinks-datadog.cjs.map +1 -0
  165. package/dist/entry-sinks-datadog.d.cts +66 -0
  166. package/dist/entry-sinks-datadog.d.mts +66 -0
  167. package/dist/entry-sinks-datadog.mjs +91 -0
  168. package/dist/entry-sinks-datadog.mjs.map +1 -0
  169. package/dist/entry-sinks-file.cjs +100 -0
  170. package/dist/entry-sinks-file.cjs.map +1 -0
  171. package/dist/entry-sinks-file.d.cts +70 -0
  172. package/dist/entry-sinks-file.d.mts +70 -0
  173. package/dist/entry-sinks-file.mjs +97 -0
  174. package/dist/entry-sinks-file.mjs.map +1 -0
  175. package/dist/entry-sinks-http.cjs +63 -0
  176. package/dist/entry-sinks-http.cjs.map +1 -0
  177. package/dist/entry-sinks-http.d.cts +55 -0
  178. package/dist/entry-sinks-http.d.mts +55 -0
  179. package/dist/entry-sinks-http.mjs +60 -0
  180. package/dist/entry-sinks-http.mjs.map +1 -0
  181. package/dist/entry-sinks-s3.cjs +115 -0
  182. package/dist/entry-sinks-s3.cjs.map +1 -0
  183. package/dist/entry-sinks-s3.d.cts +79 -0
  184. package/dist/entry-sinks-s3.d.mts +79 -0
  185. package/dist/entry-sinks-s3.mjs +112 -0
  186. package/dist/entry-sinks-s3.mjs.map +1 -0
  187. package/dist/entry-sinks-splunk.cjs +80 -0
  188. package/dist/entry-sinks-splunk.cjs.map +1 -0
  189. package/dist/entry-sinks-splunk.d.cts +58 -0
  190. package/dist/entry-sinks-splunk.d.mts +58 -0
  191. package/dist/entry-sinks-splunk.mjs +77 -0
  192. package/dist/entry-sinks-splunk.mjs.map +1 -0
  193. package/dist/entry-sinks-webhook.cjs +130 -0
  194. package/dist/entry-sinks-webhook.cjs.map +1 -0
  195. package/dist/entry-sinks-webhook.d.cts +69 -0
  196. package/dist/entry-sinks-webhook.d.mts +69 -0
  197. package/dist/entry-sinks-webhook.mjs +125 -0
  198. package/dist/entry-sinks-webhook.mjs.map +1 -0
  199. package/dist/entry-sinks-xtandard-webhooks.cjs +64 -0
  200. package/dist/entry-sinks-xtandard-webhooks.cjs.map +1 -0
  201. package/dist/entry-sinks-xtandard-webhooks.d.cts +64 -0
  202. package/dist/entry-sinks-xtandard-webhooks.d.mts +64 -0
  203. package/dist/entry-sinks-xtandard-webhooks.mjs +63 -0
  204. package/dist/entry-sinks-xtandard-webhooks.mjs.map +1 -0
  205. package/dist/entry-storage-cloudflare-kv.cjs +47 -0
  206. package/dist/entry-storage-cloudflare-kv.cjs.map +1 -0
  207. package/dist/entry-storage-cloudflare-kv.d.cts +42 -0
  208. package/dist/entry-storage-cloudflare-kv.d.mts +42 -0
  209. package/dist/entry-storage-cloudflare-kv.mjs +46 -0
  210. package/dist/entry-storage-cloudflare-kv.mjs.map +1 -0
  211. package/dist/entry-storage-drizzle.cjs +228 -0
  212. package/dist/entry-storage-drizzle.cjs.map +1 -0
  213. package/dist/entry-storage-drizzle.d.cts +43 -0
  214. package/dist/entry-storage-drizzle.d.mts +43 -0
  215. package/dist/entry-storage-drizzle.mjs +227 -0
  216. package/dist/entry-storage-drizzle.mjs.map +1 -0
  217. package/dist/entry-storage-file.cjs +175 -0
  218. package/dist/entry-storage-file.cjs.map +1 -0
  219. package/dist/entry-storage-file.d.cts +41 -0
  220. package/dist/entry-storage-file.d.mts +41 -0
  221. package/dist/entry-storage-file.mjs +171 -0
  222. package/dist/entry-storage-file.mjs.map +1 -0
  223. package/dist/entry-storage-libsql.cjs +133 -0
  224. package/dist/entry-storage-libsql.cjs.map +1 -0
  225. package/dist/entry-storage-libsql.d.cts +60 -0
  226. package/dist/entry-storage-libsql.d.mts +60 -0
  227. package/dist/entry-storage-libsql.mjs +132 -0
  228. package/dist/entry-storage-libsql.mjs.map +1 -0
  229. package/dist/entry-storage-memory.cjs +3 -0
  230. package/dist/entry-storage-memory.d.cts +2 -0
  231. package/dist/entry-storage-memory.d.mts +2 -0
  232. package/dist/entry-storage-memory.mjs +2 -0
  233. package/dist/entry-storage-mongodb.cjs +306 -0
  234. package/dist/entry-storage-mongodb.cjs.map +1 -0
  235. package/dist/entry-storage-mongodb.d.cts +65 -0
  236. package/dist/entry-storage-mongodb.d.mts +65 -0
  237. package/dist/entry-storage-mongodb.mjs +304 -0
  238. package/dist/entry-storage-mongodb.mjs.map +1 -0
  239. package/dist/entry-storage-postgres.cjs +261 -0
  240. package/dist/entry-storage-postgres.cjs.map +1 -0
  241. package/dist/entry-storage-postgres.d.cts +66 -0
  242. package/dist/entry-storage-postgres.d.mts +66 -0
  243. package/dist/entry-storage-postgres.mjs +260 -0
  244. package/dist/entry-storage-postgres.mjs.map +1 -0
  245. package/dist/entry-storage-redis.cjs +223 -0
  246. package/dist/entry-storage-redis.cjs.map +1 -0
  247. package/dist/entry-storage-redis.d.cts +77 -0
  248. package/dist/entry-storage-redis.d.mts +77 -0
  249. package/dist/entry-storage-redis.mjs +221 -0
  250. package/dist/entry-storage-redis.mjs.map +1 -0
  251. package/dist/entry-storage-sqlite.cjs +85 -0
  252. package/dist/entry-storage-sqlite.cjs.map +1 -0
  253. package/dist/entry-storage-sqlite.d.cts +40 -0
  254. package/dist/entry-storage-sqlite.d.mts +40 -0
  255. package/dist/entry-storage-sqlite.mjs +84 -0
  256. package/dist/entry-storage-sqlite.mjs.map +1 -0
  257. package/dist/entry-storage-unstorage.cjs +57 -0
  258. package/dist/entry-storage-unstorage.cjs.map +1 -0
  259. package/dist/entry-storage-unstorage.d.cts +29 -0
  260. package/dist/entry-storage-unstorage.d.mts +29 -0
  261. package/dist/entry-storage-unstorage.mjs +56 -0
  262. package/dist/entry-storage-unstorage.mjs.map +1 -0
  263. package/dist/export-B9S-JeYl.mjs +239 -0
  264. package/dist/export-B9S-JeYl.mjs.map +1 -0
  265. package/dist/export-BZq0KCCn.d.mts +70 -0
  266. package/dist/export-DYfMd-ep.cjs +280 -0
  267. package/dist/export-DYfMd-ep.cjs.map +1 -0
  268. package/dist/export-Dh8T8I1p.d.cts +70 -0
  269. package/dist/index.cjs +279 -0
  270. package/dist/index.cjs.map +1 -0
  271. package/dist/index.d.cts +286 -0
  272. package/dist/index.d.mts +284 -0
  273. package/dist/index.mjs +177 -0
  274. package/dist/index.mjs.map +1 -0
  275. package/dist/integrity-BHhjTBNk.cjs +614 -0
  276. package/dist/integrity-BHhjTBNk.cjs.map +1 -0
  277. package/dist/integrity-kfY2DNAi.mjs +483 -0
  278. package/dist/integrity-kfY2DNAi.mjs.map +1 -0
  279. package/dist/memory-CfykUo9W.cjs +155 -0
  280. package/dist/memory-CfykUo9W.cjs.map +1 -0
  281. package/dist/memory-DrR-Tlbf.d.mts +28 -0
  282. package/dist/memory-GG2Nba1D.mjs +150 -0
  283. package/dist/memory-GG2Nba1D.mjs.map +1 -0
  284. package/dist/memory-HpFdlMR_.d.cts +28 -0
  285. package/dist/none-Be7r6kHH.cjs +33 -0
  286. package/dist/none-Be7r6kHH.cjs.map +1 -0
  287. package/dist/none-CGmIIbI8.cjs +49 -0
  288. package/dist/none-CGmIIbI8.cjs.map +1 -0
  289. package/dist/none-CkV5mZsB.mjs +33 -0
  290. package/dist/none-CkV5mZsB.mjs.map +1 -0
  291. package/dist/none-DBeBeU0Z.mjs +23 -0
  292. package/dist/none-DBeBeU0Z.mjs.map +1 -0
  293. package/dist/query-ChGGtlA7.cjs +243 -0
  294. package/dist/query-ChGGtlA7.cjs.map +1 -0
  295. package/dist/query-LvZbyi37.mjs +172 -0
  296. package/dist/query-LvZbyi37.mjs.map +1 -0
  297. package/dist/react.css +1 -0
  298. package/dist/react.js +31936 -0
  299. package/dist/recorder-B3dG3jbd.d.mts +64 -0
  300. package/dist/recorder-CGY7HK29.d.cts +64 -0
  301. package/dist/roles-BARtYLSX.cjs +112 -0
  302. package/dist/roles-BARtYLSX.cjs.map +1 -0
  303. package/dist/roles-D7Pg89IJ.mjs +83 -0
  304. package/dist/roles-D7Pg89IJ.mjs.map +1 -0
  305. package/dist/schema-DmU7Wp0F.d.cts +251 -0
  306. package/dist/schema-DmU7Wp0F.d.mts +251 -0
  307. package/dist/schema.cjs +20 -0
  308. package/dist/schema.cjs.map +1 -0
  309. package/dist/schema.d.cts +2 -0
  310. package/dist/schema.d.mts +2 -0
  311. package/dist/schema.mjs +17 -0
  312. package/dist/schema.mjs.map +1 -0
  313. package/dist/shared-CJOyJKqT.d.mts +20 -0
  314. package/dist/shared-DSDY-V0n.mjs +100 -0
  315. package/dist/shared-DSDY-V0n.mjs.map +1 -0
  316. package/dist/shared-EANCdRqn.d.cts +20 -0
  317. package/dist/shared-OOAq-U4S.cjs +141 -0
  318. package/dist/shared-OOAq-U4S.cjs.map +1 -0
  319. package/dist/sql-B7b6HzGy.cjs +280 -0
  320. package/dist/sql-B7b6HzGy.cjs.map +1 -0
  321. package/dist/sql-COjPyn3F.mjs +209 -0
  322. package/dist/sql-COjPyn3F.mjs.map +1 -0
  323. package/dist/sqlite-event-log-BnoG8eos.cjs +184 -0
  324. package/dist/sqlite-event-log-BnoG8eos.cjs.map +1 -0
  325. package/dist/sqlite-event-log-nXmS2DS_.mjs +179 -0
  326. package/dist/sqlite-event-log-nXmS2DS_.mjs.map +1 -0
  327. package/dist/streams-CRuxOYcb.d.cts +124 -0
  328. package/dist/streams-DU0_gvI8.d.mts +124 -0
  329. package/dist/table-BcarDd10.d.cts +48 -0
  330. package/dist/table-BcarDd10.d.mts +48 -0
  331. package/dist/testing.cjs +189 -0
  332. package/dist/testing.cjs.map +1 -0
  333. package/dist/testing.d.cts +103 -0
  334. package/dist/testing.d.mts +103 -0
  335. package/dist/testing.mjs +185 -0
  336. package/dist/testing.mjs.map +1 -0
  337. package/dist/types-elysia2/adapters/bun.d.ts +47 -0
  338. package/dist/types-elysia2/adapters/context-shared.d.ts +40 -0
  339. package/dist/types-elysia2/adapters/elysia-shared.d.ts +36 -0
  340. package/dist/types-elysia2/adapters/elysia2.d.ts +588 -0
  341. package/dist/types-elysia2/auth/contract.d.ts +26 -0
  342. package/dist/types-elysia2/authorization/contract.d.ts +54 -0
  343. package/dist/types-elysia2/canonical.d.ts +25 -0
  344. package/dist/types-elysia2/context.d.ts +61 -0
  345. package/dist/types-elysia2/core.d.ts +232 -0
  346. package/dist/types-elysia2/duration.d.ts +26 -0
  347. package/dist/types-elysia2/entry-elysia2.d.ts +10 -0
  348. package/dist/types-elysia2/event-log.d.ts +33 -0
  349. package/dist/types-elysia2/export.d.ts +77 -0
  350. package/dist/types-elysia2/hooks/contract.d.ts +177 -0
  351. package/dist/types-elysia2/id.d.ts +27 -0
  352. package/dist/types-elysia2/integrity.d.ts +193 -0
  353. package/dist/types-elysia2/keys.d.ts +91 -0
  354. package/dist/types-elysia2/portal.d.ts +137 -0
  355. package/dist/types-elysia2/query.d.ts +88 -0
  356. package/dist/types-elysia2/schema.d.ts +247 -0
  357. package/dist/types-elysia2/server/base-path.d.ts +15 -0
  358. package/dist/types-elysia2/server/cors.d.ts +36 -0
  359. package/dist/types-elysia2/server/create-fetch-handler.d.ts +140 -0
  360. package/dist/types-elysia2/server/openapi.d.ts +25 -0
  361. package/dist/types-elysia2/server/render-index-html.d.ts +18 -0
  362. package/dist/types-elysia2/server/routes.d.ts +83 -0
  363. package/dist/types-elysia2/server/static-assets.d.ts +13 -0
  364. package/dist/types-elysia2/standard-schema.d.ts +100 -0
  365. package/dist/types-elysia2/storage/contract.d.ts +106 -0
  366. package/dist/types-elysia2/streams.d.ts +134 -0
  367. package/dist/types-elysia2/transforms.d.ts +56 -0
  368. package/dist/types-elysia2/validation.d.ts +48 -0
  369. package/dist/types-react/canonical.d.ts +25 -0
  370. package/dist/types-react/context.d.ts +61 -0
  371. package/dist/types-react/core.d.ts +232 -0
  372. package/dist/types-react/duration.d.ts +26 -0
  373. package/dist/types-react/event-log.d.ts +33 -0
  374. package/dist/types-react/hooks/contract.d.ts +177 -0
  375. package/dist/types-react/id.d.ts +27 -0
  376. package/dist/types-react/integrity.d.ts +193 -0
  377. package/dist/types-react/keys.d.ts +91 -0
  378. package/dist/types-react/query.d.ts +88 -0
  379. package/dist/types-react/react.d.ts +114 -0
  380. package/dist/types-react/schema.d.ts +247 -0
  381. package/dist/types-react/standard-schema.d.ts +100 -0
  382. package/dist/types-react/storage/contract.d.ts +106 -0
  383. package/dist/types-react/streams.d.ts +134 -0
  384. package/dist/types-react/transforms.d.ts +56 -0
  385. package/dist/types-react/ui/App.d.ts +36 -0
  386. package/dist/types-react/ui/api.d.ts +61 -0
  387. package/dist/types-react/ui/components/ActionFilter.d.ts +17 -0
  388. package/dist/types-react/ui/components/ExportMenu.d.ts +13 -0
  389. package/dist/types-react/ui/components/JsonCodeEditor.d.ts +12 -0
  390. package/dist/types-react/ui/components/ThemeToggle.d.ts +2 -0
  391. package/dist/types-react/ui/components/Toast.d.ts +16 -0
  392. package/dist/types-react/ui/components/audit-bits.d.ts +91 -0
  393. package/dist/types-react/ui/components/integrity-bits.d.ts +19 -0
  394. package/dist/types-react/ui/components/primitives.d.ts +50 -0
  395. package/dist/types-react/ui/components/ui-bits.d.ts +22 -0
  396. package/dist/types-react/ui/lib/filters.d.ts +70 -0
  397. package/dist/types-react/ui/lib/format.d.ts +82 -0
  398. package/dist/types-react/ui/lib/nav-guard.d.ts +20 -0
  399. package/dist/types-react/ui/lib/portal-container.d.ts +24 -0
  400. package/dist/types-react/ui/lib/utils.d.ts +3 -0
  401. package/dist/types-react/ui/theme.d.ts +40 -0
  402. package/dist/types-react/ui/types.d.ts +67 -0
  403. package/dist/types-react/ui/views/ActionsView.d.ts +10 -0
  404. package/dist/types-react/ui/views/EventDrawer.d.ts +15 -0
  405. package/dist/types-react/ui/views/EventsView.d.ts +10 -0
  406. package/dist/types-react/ui/views/IntegrityView.d.ts +10 -0
  407. package/dist/types-react/ui/views/OverviewView.d.ts +9 -0
  408. package/dist/types-react/ui/views/StreamsView.d.ts +10 -0
  409. package/dist/types-react/ui/views/TenantsView.d.ts +6 -0
  410. package/dist/types-react/validation.d.ts +48 -0
  411. package/dist/ui/assets/favicon-BSj8MPnj.svg +11 -0
  412. package/dist/ui/assets/index-B-qrQSOM.css +1 -0
  413. package/dist/ui/assets/index-CemlP5hR.js +244 -0
  414. package/dist/ui/index.html +15 -0
  415. package/dist/validation-DFrLESZD.mjs +150 -0
  416. package/dist/validation-DFrLESZD.mjs.map +1 -0
  417. package/dist/validation-lb0YXrxx.cjs +235 -0
  418. package/dist/validation-lb0YXrxx.cjs.map +1 -0
  419. package/dist/verify.cjs +14 -0
  420. package/dist/verify.d.cts +5 -0
  421. package/dist/verify.d.mts +5 -0
  422. package/dist/verify.mjs +3 -0
  423. package/package.json +610 -4
@@ -0,0 +1,2156 @@
1
+ import { t as __exportAll } from "./chunk-D7D4PA-g.mjs";
2
+ import { n as base64urlDecode, r as base64urlEncode } from "./integrity-kfY2DNAi.mjs";
3
+ import { A as streamMetaKey, O as streamCursorKey, a as SignerRequiredError, b as HookDeniedError, j as durationToMs, k as streamLeaseKey, n as NotFoundError, o as createAuditCore, r as ReadonlyError, t as ConflictError } from "./core-IdGEbYdM.mjs";
4
+ import { l as matchesQuery, r as QueryError, u as normalizeQuery } from "./query-LvZbyi37.mjs";
5
+ import { r as isCompareAndSwap, t as ChainConflictError } from "./contract-isM9SjjQ.mjs";
6
+ import { i as ValidationError } from "./validation-DFrLESZD.mjs";
7
+ import { a as exportEvents, n as EXPORT_CONTENT_TYPES } from "./export-B9S-JeYl.mjs";
8
+ import { r as isMutatingAction, t as ALL_ACTIONS } from "./contract-BljSE-Hx.mjs";
9
+ import { existsSync } from "node:fs";
10
+ import { fileURLToPath } from "node:url";
11
+ import { readFile } from "node:fs/promises";
12
+ import { join, normalize } from "node:path";
13
+ //#region src/streams.ts
14
+ const NAME_RE = /^[a-zA-Z0-9._-]+$/;
15
+ /**
16
+ * Create a stream runner over a core. The panel creates and starts one when
17
+ * given `streams`; call `start()` yourself otherwise (timers are `unref`ed).
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * import { createStreamRunner } from "@xtandard/audit";
22
+ * import { httpSink } from "@xtandard/audit/sinks/http";
23
+ *
24
+ * const runner = createStreamRunner(audit, {
25
+ * streams: [{ name: "siem", sink: httpSink({ url: "https://siem.example/ingest" }) }],
26
+ * });
27
+ * runner.start();
28
+ * ```
29
+ */
30
+ function createStreamRunner(core, options) {
31
+ const storage = core.options.storage;
32
+ const now = core.options.now;
33
+ const intervalMs = durationToMs(options.interval ?? "2s");
34
+ const maxBackoffMs = durationToMs(options.maxBackoff ?? "10m");
35
+ const leaseMs = durationToMs(options.lease ?? "30s");
36
+ const cas = isCompareAndSwap(storage) ? storage : null;
37
+ const ownerId = Math.random().toString(36).slice(2);
38
+ const onError = options.onError ?? ((error, info) => {
39
+ console.warn(`[@xtandard/audit] stream "${info.stream}" → tenant "${info.tenant}" failed:`, error);
40
+ });
41
+ const names = /* @__PURE__ */ new Set();
42
+ for (const s of options.streams) {
43
+ if (!NAME_RE.test(s.name)) throw new TypeError(`Invalid stream name "${s.name}"`);
44
+ if (names.has(s.name)) throw new TypeError(`Duplicate stream name "${s.name}"`);
45
+ names.add(s.name);
46
+ }
47
+ let timer = null;
48
+ let running = null;
49
+ async function tenantsFor(stream) {
50
+ const all = (await core.listTenants()).map((t) => t.key);
51
+ return stream.tenants ? all.filter((t) => stream.tenants.includes(t)) : all;
52
+ }
53
+ /**
54
+ * The first time a stream ever runs, `startFrom: "now"` pins every tenant that exists at that
55
+ * moment to its current head. Tenants that appear later start from the beginning of their log —
56
+ * otherwise events recorded before the runner first noticed a new tenant would never be streamed.
57
+ */
58
+ async function ensureStarted(stream) {
59
+ const key = streamMetaKey(stream.name);
60
+ if (await storage.getItem(key)) return;
61
+ if ((stream.startFrom ?? "now") === "now") for (const tenant of await tenantsFor(stream)) {
62
+ const cursorKey = streamCursorKey(stream.name, tenant);
63
+ if (await storage.getItem(cursorKey)) continue;
64
+ const head = await core.head(tenant);
65
+ const cps = await core.listCheckpoints(tenant);
66
+ const last = cps[cps.length - 1];
67
+ await storage.setItem(cursorKey, {
68
+ seq: head.seq,
69
+ failures: 0,
70
+ ...last ? { checkpointId: last.id } : {}
71
+ });
72
+ }
73
+ await storage.setItem(key, { startedAt: new Date(now()).toISOString() });
74
+ }
75
+ async function readCursor(stream, tenant) {
76
+ const existing = await storage.getItem(streamCursorKey(stream.name, tenant));
77
+ if (existing) return existing;
78
+ const cursor = {
79
+ seq: ((await core.head(tenant)).baseSeq ?? 1) - 1,
80
+ failures: 0
81
+ };
82
+ await storage.setItem(streamCursorKey(stream.name, tenant), cursor);
83
+ return cursor;
84
+ }
85
+ async function acquireLease(stream) {
86
+ if (!cas) return true;
87
+ const key = streamLeaseKey(stream.name);
88
+ const current = await storage.getItem(key);
89
+ const t = now();
90
+ if (current && current.owner !== ownerId && current.until > t) return false;
91
+ return cas.compareAndSwap({
92
+ key,
93
+ expected: current,
94
+ next: {
95
+ owner: ownerId,
96
+ until: t + leaseMs
97
+ }
98
+ });
99
+ }
100
+ async function pumpTenant(stream, tenant) {
101
+ let cursor = await readCursor(stream, tenant);
102
+ if (cursor.nextAttemptAt && Date.parse(cursor.nextAttemptAt) > now()) return;
103
+ const batchSize = stream.batchSize ?? 100;
104
+ const filter = stream.filter ? normalizeQuery({
105
+ ...stream.filter,
106
+ tenant
107
+ }) : null;
108
+ const head = await core.head(tenant);
109
+ if (head.baseSeq && cursor.seq < head.baseSeq - 1) cursor = {
110
+ ...cursor,
111
+ seq: head.baseSeq - 1
112
+ };
113
+ for (;;) {
114
+ if (!await acquireLease(stream)) return;
115
+ const events = await core.eventsBySeq(tenant, {
116
+ afterSeq: cursor.seq,
117
+ limit: batchSize
118
+ });
119
+ const items = [];
120
+ for (const event of events) if (!filter || matchesQuery(event, filter)) items.push({
121
+ kind: "event",
122
+ event
123
+ });
124
+ let checkpointId = cursor.checkpointId;
125
+ if (stream.checkpoints ?? true) {
126
+ const lastSeq = events[events.length - 1]?.seq ?? cursor.seq;
127
+ for (const cp of await core.listCheckpoints(tenant)) {
128
+ if (checkpointId && cp.id <= checkpointId || cp.seq > lastSeq) continue;
129
+ items.push({
130
+ kind: "checkpoint",
131
+ checkpoint: cp
132
+ });
133
+ checkpointId = cp.id;
134
+ }
135
+ }
136
+ if (events.length === 0 && items.length === 0) return;
137
+ const lastSeq = events[events.length - 1]?.seq ?? cursor.seq;
138
+ try {
139
+ if (items.length > 0) await stream.sink.send({
140
+ stream: stream.name,
141
+ tenant,
142
+ items
143
+ });
144
+ } catch (err) {
145
+ const failures = cursor.failures + 1;
146
+ const backoff = Math.min(maxBackoffMs, 1e3 * 2 ** Math.min(failures - 1, 20));
147
+ await storage.setItem(streamCursorKey(stream.name, tenant), {
148
+ ...cursor,
149
+ failures,
150
+ lastError: err instanceof Error ? err.message : String(err),
151
+ lastErrorAt: new Date(now()).toISOString(),
152
+ nextAttemptAt: new Date(now() + backoff).toISOString()
153
+ });
154
+ onError(err, {
155
+ stream: stream.name,
156
+ tenant
157
+ });
158
+ return;
159
+ }
160
+ cursor = {
161
+ seq: lastSeq,
162
+ ...checkpointId ? { checkpointId } : {},
163
+ failures: 0,
164
+ lastDeliveredAt: items.length > 0 ? new Date(now()).toISOString() : cursor.lastDeliveredAt
165
+ };
166
+ if (cursor.lastDeliveredAt === void 0) delete cursor.lastDeliveredAt;
167
+ await storage.setItem(streamCursorKey(stream.name, tenant), cursor);
168
+ if (events.length < batchSize) return;
169
+ }
170
+ }
171
+ async function tick() {
172
+ if (running) return running;
173
+ running = (async () => {
174
+ for (const stream of options.streams) {
175
+ if (!await acquireLease(stream)) continue;
176
+ await ensureStarted(stream);
177
+ for (const tenant of await tenantsFor(stream)) try {
178
+ await pumpTenant(stream, tenant);
179
+ } catch (err) {
180
+ onError(err, {
181
+ stream: stream.name,
182
+ tenant
183
+ });
184
+ }
185
+ }
186
+ })().finally(() => {
187
+ running = null;
188
+ });
189
+ return running;
190
+ }
191
+ const floor = async (tenant) => {
192
+ let min = null;
193
+ for (const stream of options.streams) {
194
+ if (stream.tenants && !stream.tenants.includes(tenant)) continue;
195
+ const c = await storage.getItem(streamCursorKey(stream.name, tenant));
196
+ if (c) min = min === null ? c.seq : Math.min(min, c.seq);
197
+ }
198
+ return min;
199
+ };
200
+ const unregisterFloor = core.addRetentionFloor(floor);
201
+ return {
202
+ streams: options.streams,
203
+ start() {
204
+ if (timer) return;
205
+ timer = setInterval(() => void tick(), intervalMs);
206
+ timer.unref?.();
207
+ tick();
208
+ },
209
+ async stop() {
210
+ if (timer) clearInterval(timer);
211
+ timer = null;
212
+ unregisterFloor();
213
+ await running;
214
+ for (const s of options.streams) await s.sink.close?.();
215
+ },
216
+ tick,
217
+ async status() {
218
+ const out = [];
219
+ for (const stream of options.streams) {
220
+ const tenants = [];
221
+ for (const tenant of await tenantsFor(stream)) {
222
+ const c = await storage.getItem(streamCursorKey(stream.name, tenant));
223
+ const head = await core.head(tenant);
224
+ const cursor = c?.seq ?? head.seq;
225
+ tenants.push({
226
+ tenant,
227
+ cursor,
228
+ headSeq: head.seq,
229
+ lag: Math.max(0, head.seq - cursor),
230
+ failures: c?.failures ?? 0,
231
+ ...c?.lastError ? { lastError: c.lastError } : {},
232
+ ...c?.lastErrorAt ? { lastErrorAt: c.lastErrorAt } : {},
233
+ ...c?.nextAttemptAt ? { nextAttemptAt: c.nextAttemptAt } : {},
234
+ ...c?.lastDeliveredAt ? { lastDeliveredAt: c.lastDeliveredAt } : {}
235
+ });
236
+ }
237
+ out.push({
238
+ name: stream.name,
239
+ kind: stream.sink.kind,
240
+ tenants
241
+ });
242
+ }
243
+ return out;
244
+ },
245
+ async retry(name, tenant) {
246
+ const stream = options.streams.find((s) => s.name === name);
247
+ if (!stream) return;
248
+ for (const t of tenant ? [tenant] : await tenantsFor(stream)) {
249
+ const c = await storage.getItem(streamCursorKey(name, t));
250
+ if (c?.nextAttemptAt) {
251
+ const { nextAttemptAt: _n, ...rest } = c;
252
+ await storage.setItem(streamCursorKey(name, t), rest);
253
+ }
254
+ }
255
+ }
256
+ };
257
+ }
258
+ /** A sink that calls your function (tests, custom destinations). */
259
+ function callbackSink(send, kind = "callback") {
260
+ return {
261
+ kind,
262
+ send: async (batch) => void await send(batch)
263
+ };
264
+ }
265
+ //#endregion
266
+ //#region src/portal.ts
267
+ /** Prefix of every portal token. */
268
+ const PORTAL_TOKEN_PREFIX = "audpt_";
269
+ const DEFAULT_EXPIRES_IN = "1h";
270
+ /**
271
+ * The default portal grant: browse, export and verify the tenant's own log,
272
+ * and read the action catalog. Nothing mutating.
273
+ */
274
+ const DEFAULT_PORTAL_ACTIONS = [
275
+ "event:read",
276
+ "event:export",
277
+ "action:read",
278
+ "integrity:read"
279
+ ];
280
+ /**
281
+ * Thrown by {@link verifyPortalToken} for any invalid token — malformed,
282
+ * bad signature, or expired. Maps to HTTP 401 at the API layer.
283
+ */
284
+ var PortalTokenError = class extends Error {
285
+ constructor(message) {
286
+ super(message);
287
+ this.name = "PortalTokenError";
288
+ }
289
+ };
290
+ /** HMAC-SHA256 keyed by the raw UTF-8 bytes of the (arbitrary-string) secret. */
291
+ async function hmac(secret, content) {
292
+ const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), {
293
+ name: "HMAC",
294
+ hash: "SHA-256"
295
+ }, false, ["sign"]);
296
+ const digest = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(content));
297
+ return new Uint8Array(digest);
298
+ }
299
+ /** Constant-time byte comparison (XOR accumulate — no early exit on content). */
300
+ function timingSafeEqual(a, b) {
301
+ if (a.length !== b.length) return false;
302
+ let diff = 0;
303
+ for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
304
+ return diff === 0;
305
+ }
306
+ const isStringArray = (v) => Array.isArray(v) && v.every((x) => typeof x === "string");
307
+ /** Keep only well-formed, non-empty filter fields (or `undefined` when nothing is left). */
308
+ function cleanFilter(input) {
309
+ if (input === null || typeof input !== "object" || Array.isArray(input)) return void 0;
310
+ const f = input;
311
+ const out = {};
312
+ if (isStringArray(f.actions) && f.actions.length) out.actions = [...f.actions];
313
+ if (isStringArray(f.excludeActions) && f.excludeActions.length) out.excludeActions = [...f.excludeActions];
314
+ for (const k of [
315
+ "actorId",
316
+ "targetType",
317
+ "targetId"
318
+ ]) if (typeof f[k] === "string" && f[k]) out[k] = f[k];
319
+ return Object.keys(out).length ? out : void 0;
320
+ }
321
+ /**
322
+ * Mint a portal token granting read access to `tenant`'s log until
323
+ * `expiresIn` elapses (default 1 hour). Call this **server-side** — anyone
324
+ * holding the portal secret can mint tokens for any tenant.
325
+ *
326
+ * @example
327
+ * ```ts
328
+ * import { createPortalToken } from "@xtandard/audit";
329
+ *
330
+ * // In the host app's session-guarded route:
331
+ * const token = await createPortalToken(process.env.PORTAL_SECRET!, user.orgId, {
332
+ * expiresIn: "30m",
333
+ * filter: { excludeActions: ["support.*"] },
334
+ * });
335
+ * // Hand `token` to the frontend for <AuditPortal token={token} />.
336
+ * ```
337
+ */
338
+ async function createPortalToken(secret, tenant, options = {}) {
339
+ if (!tenant) throw new TypeError("createPortalToken requires a tenant");
340
+ const expiresInMs = durationToMs(options.expiresIn ?? DEFAULT_EXPIRES_IN);
341
+ const filter = cleanFilter(options.filter);
342
+ const claims = {
343
+ tenant,
344
+ exp: Date.now() + expiresInMs,
345
+ ...filter ? { filter } : {}
346
+ };
347
+ const payloadPart = base64urlEncode(new TextEncoder().encode(JSON.stringify(claims)));
348
+ return `${PORTAL_TOKEN_PREFIX}${payloadPart}.${base64urlEncode(await hmac(secret, payloadPart))}`;
349
+ }
350
+ /**
351
+ * Verify a portal token: format, signature (constant time), then expiry.
352
+ * Returns the grant on success; throws {@link PortalTokenError} otherwise.
353
+ *
354
+ * @example
355
+ * ```ts
356
+ * import { verifyPortalToken } from "@xtandard/audit";
357
+ *
358
+ * const { tenant, filter } = await verifyPortalToken(secret, token);
359
+ * ```
360
+ */
361
+ async function verifyPortalToken(secret, token) {
362
+ if (!token.startsWith("audpt_")) throw new PortalTokenError("Invalid portal token: missing audpt_ prefix");
363
+ const parts = token.slice(6).split(".");
364
+ if (parts.length !== 2 || !parts[0] || !parts[1]) throw new PortalTokenError("Invalid portal token: malformed");
365
+ const [payloadPart, signaturePart] = parts;
366
+ let candidate;
367
+ try {
368
+ candidate = base64urlDecode(signaturePart);
369
+ } catch {
370
+ throw new PortalTokenError("Invalid portal token: malformed signature");
371
+ }
372
+ if (!timingSafeEqual(await hmac(secret, payloadPart), candidate)) throw new PortalTokenError("Invalid portal token: signature mismatch");
373
+ let claims;
374
+ try {
375
+ claims = JSON.parse(new TextDecoder().decode(base64urlDecode(payloadPart)));
376
+ } catch {
377
+ throw new PortalTokenError("Invalid portal token: malformed payload");
378
+ }
379
+ if (typeof claims.tenant !== "string" || claims.tenant.length === 0) throw new PortalTokenError("Invalid portal token: missing tenant");
380
+ if (typeof claims.exp !== "number" || !Number.isFinite(claims.exp)) throw new PortalTokenError("Invalid portal token: missing expiry");
381
+ if (Date.now() >= claims.exp) throw new PortalTokenError("Portal token has expired");
382
+ const filter = cleanFilter(claims.filter);
383
+ return {
384
+ tenant: claims.tenant,
385
+ expiresAt: claims.exp,
386
+ ...filter ? { filter } : {}
387
+ };
388
+ }
389
+ function toPattern(raw) {
390
+ const a = raw.trim();
391
+ if (a === "*") return { prefix: "" };
392
+ if (a.endsWith("*")) return { prefix: a.slice(0, -1) };
393
+ return { exact: a };
394
+ }
395
+ const fromPattern = (p) => "exact" in p ? p.exact : `${p.prefix}*`;
396
+ /** Does pattern `outer` include everything pattern `inner` matches? */
397
+ function covers(outer, inner) {
398
+ if ("exact" in outer) return "exact" in inner && inner.exact === outer.exact;
399
+ return "exact" in inner ? inner.exact.startsWith(outer.prefix) : inner.prefix.startsWith(outer.prefix);
400
+ }
401
+ /**
402
+ * Intersect two action include-lists (each an OR of exact names and families).
403
+ * Returns the narrowest list matching exactly what both match; `[]` means
404
+ * "nothing matches".
405
+ */
406
+ function intersectActions(a, b) {
407
+ const pa = a.map(toPattern);
408
+ const pb = b.map(toPattern);
409
+ const out = /* @__PURE__ */ new Set();
410
+ for (const x of pa) if (pb.some((y) => covers(y, x))) out.add(fromPattern(x));
411
+ for (const y of pb) if (pa.some((x) => covers(x, y))) out.add(fromPattern(y));
412
+ return [...out];
413
+ }
414
+ /**
415
+ * Force a client query into a portal grant: the tenant is the token's, and
416
+ * every filter field is AND-ed in. A client parameter can only **narrow** the
417
+ * view — action lists are intersected, exclusions are unioned, and a client
418
+ * `actorId` / `targetType` / `targetId` that differs from the token's makes
419
+ * the result empty (`empty: true`) instead of widening it.
420
+ *
421
+ * @example
422
+ * ```ts
423
+ * const { query, empty } = scopeQueryToPortal(clientQuery, grant);
424
+ * const page = empty ? { items: [], pageInfo: { hasNextPage: false, endCursor: null } } : await audit.query(query);
425
+ * ```
426
+ */
427
+ function scopeQueryToPortal(query, grant) {
428
+ const filter = grant.filter ?? {};
429
+ let empty = query.tenant !== void 0 && query.tenant !== grant.tenant;
430
+ const scoped = {
431
+ ...query,
432
+ tenant: grant.tenant
433
+ };
434
+ if (filter.actions?.length) if (query.actions?.length) {
435
+ const both = intersectActions(query.actions, filter.actions);
436
+ if (both.length === 0) empty = true;
437
+ scoped.actions = both.length ? both : [...filter.actions];
438
+ } else scoped.actions = [...filter.actions];
439
+ if (filter.excludeActions?.length) scoped.excludeActions = [...new Set([...query.excludeActions ?? [], ...filter.excludeActions])];
440
+ for (const k of [
441
+ "actorId",
442
+ "targetType",
443
+ "targetId"
444
+ ]) {
445
+ const forced = filter[k];
446
+ if (forced === void 0) continue;
447
+ if (query[k] !== void 0 && query[k] !== forced) empty = true;
448
+ scoped[k] = forced;
449
+ }
450
+ return {
451
+ query: scoped,
452
+ empty
453
+ };
454
+ }
455
+ /** Is `event` inside the grant's view (its tenant, and its filter)? */
456
+ function portalCanSee(event, grant) {
457
+ if (event.tenant !== grant.tenant) return false;
458
+ if (!grant.filter) return true;
459
+ return matchesQuery(event, normalizeQuery(scopeQueryToPortal({}, grant).query));
460
+ }
461
+ //#endregion
462
+ //#region src/server/base-path.ts
463
+ /**
464
+ * Base-path helpers. The panel can be mounted under any prefix (`/audit`,
465
+ * `/admin/audit`, ...). These normalize the configured base path and strip it
466
+ * from incoming request paths so routing is prefix-agnostic.
467
+ *
468
+ * @module
469
+ */
470
+ /** Normalize a base path to either `""` (root) or `/segment` with no trailing slash. */
471
+ function normalizeBasePath(basePath) {
472
+ if (!basePath || basePath === "/") return "";
473
+ let p = basePath.trim();
474
+ if (!p.startsWith("/")) p = "/" + p;
475
+ if (p.endsWith("/")) p = p.slice(0, -1);
476
+ return p;
477
+ }
478
+ /**
479
+ * Strip the (normalized) base path from a pathname. Returns a path that always
480
+ * starts with `/`. If the pathname does not start with the base path it is
481
+ * returned unchanged (the host framework may already have stripped the mount).
482
+ */
483
+ function stripBasePath(pathname, basePath) {
484
+ if (basePath === "") return pathname || "/";
485
+ if (pathname === basePath) return "/";
486
+ if (pathname.startsWith(basePath + "/")) return pathname.slice(basePath.length) || "/";
487
+ return pathname || "/";
488
+ }
489
+ //#endregion
490
+ //#region src/server/cors.ts
491
+ const DEFAULT_METHODS = "GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS";
492
+ /**
493
+ * Resolve the value for `Access-Control-Allow-Origin` for this request, or
494
+ * `null` when the origin is not allowed (no CORS headers → the browser blocks).
495
+ */
496
+ function resolveOrigin(cors, requestOrigin) {
497
+ const { origin } = cors;
498
+ if (origin === "*") return cors.credentials ? requestOrigin ?? null : "*";
499
+ if (requestOrigin === null) return null;
500
+ return (typeof origin === "string" ? origin === requestOrigin : Array.isArray(origin) ? origin.includes(requestOrigin) : origin(requestOrigin)) ? requestOrigin : null;
501
+ }
502
+ /** Attach `Access-Control-*` headers to `response` for an allowed cross-origin request. */
503
+ function applyCorsHeaders(request, response, cors) {
504
+ const allowOrigin = resolveOrigin(cors, request.headers.get("origin"));
505
+ if (allowOrigin === null) return response;
506
+ response.headers.set("access-control-allow-origin", allowOrigin);
507
+ if (cors.credentials) response.headers.set("access-control-allow-credentials", "true");
508
+ if (allowOrigin !== "*") response.headers.append("vary", "Origin");
509
+ return response;
510
+ }
511
+ /** Build the `204` response for a CORS preflight (`OPTIONS`). */
512
+ function preflightResponse(request, cors) {
513
+ const response = new Response(null, { status: 204 });
514
+ applyCorsHeaders(request, response, cors);
515
+ response.headers.set("access-control-allow-methods", (cors.methods ?? []).join(",") || DEFAULT_METHODS);
516
+ const requestedHeaders = request.headers.get("access-control-request-headers");
517
+ response.headers.set("access-control-allow-headers", cors.headers?.join(",") || requestedHeaders || "Content-Type, Authorization");
518
+ if (cors.maxAge !== void 0) response.headers.set("access-control-max-age", String(cors.maxAge));
519
+ return response;
520
+ }
521
+ //#endregion
522
+ //#region src/server/openapi.ts
523
+ const str = { type: "string" };
524
+ const dateTime = {
525
+ type: "string",
526
+ format: "date-time"
527
+ };
528
+ const int = { type: "integer" };
529
+ const strList = {
530
+ type: "array",
531
+ items: str
532
+ };
533
+ const SECTION = {
534
+ type: "string",
535
+ enum: [
536
+ "actor",
537
+ "targets",
538
+ "context",
539
+ "metadata",
540
+ "description"
541
+ ]
542
+ };
543
+ const schemas = {
544
+ Actor: {
545
+ type: "object",
546
+ required: ["id"],
547
+ properties: {
548
+ id: str,
549
+ type: {
550
+ type: "string",
551
+ description: "Default \"user\"."
552
+ },
553
+ name: str,
554
+ email: str,
555
+ metadata: { type: "object" }
556
+ }
557
+ },
558
+ Target: {
559
+ type: "object",
560
+ required: ["type", "id"],
561
+ properties: {
562
+ type: str,
563
+ id: str,
564
+ name: str,
565
+ metadata: { type: "object" }
566
+ }
567
+ },
568
+ Context: {
569
+ type: "object",
570
+ additionalProperties: true,
571
+ properties: {
572
+ ip: str,
573
+ userAgent: str,
574
+ requestId: str,
575
+ location: str
576
+ }
577
+ },
578
+ Integrity: {
579
+ type: "object",
580
+ required: [
581
+ "v",
582
+ "prevHash",
583
+ "hash",
584
+ "digests"
585
+ ],
586
+ properties: {
587
+ v: { const: 1 },
588
+ prevHash: str,
589
+ hash: {
590
+ type: "string",
591
+ description: "\"sha256:\" + hex."
592
+ },
593
+ digests: {
594
+ type: "object",
595
+ additionalProperties: str
596
+ },
597
+ erased: {
598
+ type: "array",
599
+ items: SECTION
600
+ }
601
+ }
602
+ },
603
+ AuditEvent: {
604
+ type: "object",
605
+ required: [
606
+ "id",
607
+ "tenant",
608
+ "seq",
609
+ "action",
610
+ "occurredAt",
611
+ "recordedAt",
612
+ "actor",
613
+ "targets",
614
+ "context",
615
+ "metadata",
616
+ "integrity"
617
+ ],
618
+ properties: {
619
+ id: {
620
+ type: "string",
621
+ description: "\"evt_\" + 26-char time-sortable id."
622
+ },
623
+ tenant: str,
624
+ seq: {
625
+ type: "integer",
626
+ minimum: 1,
627
+ description: "Position in the tenant's chain."
628
+ },
629
+ action: str,
630
+ occurredAt: dateTime,
631
+ recordedAt: dateTime,
632
+ actor: { $ref: "#/components/schemas/Actor" },
633
+ targets: {
634
+ type: "array",
635
+ items: { $ref: "#/components/schemas/Target" }
636
+ },
637
+ context: { $ref: "#/components/schemas/Context" },
638
+ metadata: { type: "object" },
639
+ outcome: {
640
+ type: "string",
641
+ enum: ["success", "failure"]
642
+ },
643
+ description: str,
644
+ integrity: { $ref: "#/components/schemas/Integrity" }
645
+ }
646
+ },
647
+ AuditEventInput: {
648
+ type: "object",
649
+ required: ["action"],
650
+ description: "The tenant comes from the path; the actor defaults to the authenticated principal.",
651
+ properties: {
652
+ id: {
653
+ type: "string",
654
+ description: "Explicit id for idempotent re-recording."
655
+ },
656
+ action: str,
657
+ occurredAt: dateTime,
658
+ actor: { $ref: "#/components/schemas/Actor" },
659
+ targets: {
660
+ type: "array",
661
+ items: { $ref: "#/components/schemas/Target" }
662
+ },
663
+ context: { $ref: "#/components/schemas/Context" },
664
+ metadata: { type: "object" },
665
+ outcome: {
666
+ type: "string",
667
+ enum: ["success", "failure"]
668
+ },
669
+ description: str
670
+ }
671
+ },
672
+ AuditPage: {
673
+ type: "object",
674
+ required: ["items", "pageInfo"],
675
+ properties: {
676
+ items: {
677
+ type: "array",
678
+ items: { $ref: "#/components/schemas/AuditEvent" }
679
+ },
680
+ pageInfo: {
681
+ type: "object",
682
+ required: ["hasNextPage", "endCursor"],
683
+ properties: {
684
+ hasNextPage: { type: "boolean" },
685
+ endCursor: { type: ["string", "null"] }
686
+ }
687
+ }
688
+ }
689
+ },
690
+ ChainHead: {
691
+ type: "object",
692
+ required: [
693
+ "tenant",
694
+ "seq",
695
+ "hash"
696
+ ],
697
+ properties: {
698
+ tenant: str,
699
+ seq: int,
700
+ hash: str,
701
+ baseSeq: int,
702
+ baseHash: str,
703
+ updatedAt: dateTime
704
+ }
705
+ },
706
+ AuditTenant: {
707
+ type: "object",
708
+ required: ["key", "head"],
709
+ properties: {
710
+ key: str,
711
+ count: {
712
+ type: "integer",
713
+ description: "Events currently retained."
714
+ },
715
+ head: { $ref: "#/components/schemas/ChainHead" },
716
+ createdAt: dateTime
717
+ }
718
+ },
719
+ AuditCheckpoint: {
720
+ type: "object",
721
+ required: [
722
+ "v",
723
+ "id",
724
+ "tenant",
725
+ "kind",
726
+ "seq",
727
+ "hash",
728
+ "at",
729
+ "keyId",
730
+ "alg",
731
+ "signature"
732
+ ],
733
+ properties: {
734
+ v: { const: 1 },
735
+ id: str,
736
+ tenant: str,
737
+ kind: {
738
+ type: "string",
739
+ enum: ["head", "base"]
740
+ },
741
+ seq: int,
742
+ hash: str,
743
+ at: dateTime,
744
+ keyId: str,
745
+ alg: {
746
+ type: "string",
747
+ enum: ["Ed25519", "HS256"]
748
+ },
749
+ signature: {
750
+ type: "string",
751
+ description: "base64url."
752
+ }
753
+ }
754
+ },
755
+ VerifyReport: {
756
+ type: "object",
757
+ required: [
758
+ "ok",
759
+ "checked",
760
+ "anchor",
761
+ "issues"
762
+ ],
763
+ properties: {
764
+ ok: { type: "boolean" },
765
+ tenant: { type: ["string", "null"] },
766
+ checked: int,
767
+ fromSeq: { type: ["integer", "null"] },
768
+ toSeq: { type: ["integer", "null"] },
769
+ headHash: { type: ["string", "null"] },
770
+ anchor: {
771
+ type: "string",
772
+ enum: [
773
+ "genesis",
774
+ "checkpoint",
775
+ "unanchored",
776
+ "none"
777
+ ]
778
+ },
779
+ linksChecked: { type: "boolean" },
780
+ checkpointsVerified: int,
781
+ signedThrough: { type: ["integer", "null"] },
782
+ erased: {
783
+ type: "array",
784
+ items: {
785
+ type: "object",
786
+ properties: {
787
+ seq: int,
788
+ eventId: str,
789
+ sections: {
790
+ type: "array",
791
+ items: SECTION
792
+ }
793
+ }
794
+ }
795
+ },
796
+ issues: {
797
+ type: "array",
798
+ items: {
799
+ type: "object",
800
+ required: ["kind", "message"],
801
+ properties: {
802
+ kind: str,
803
+ seq: int,
804
+ eventId: str,
805
+ checkpointId: str,
806
+ section: SECTION,
807
+ message: str
808
+ }
809
+ }
810
+ }
811
+ }
812
+ },
813
+ ActionDefinition: {
814
+ type: "object",
815
+ required: ["name"],
816
+ properties: {
817
+ name: {
818
+ type: "string",
819
+ pattern: "^[a-zA-Z0-9][a-zA-Z0-9._:-]*$"
820
+ },
821
+ description: str,
822
+ group: str,
823
+ targets: strList,
824
+ schema: { description: "JSON-Schema-ish description of metadata (documentation only)." },
825
+ deprecated: { type: "boolean" },
826
+ source: {
827
+ type: "string",
828
+ enum: ["code", "ui"]
829
+ },
830
+ createdAt: dateTime,
831
+ updatedAt: dateTime
832
+ }
833
+ },
834
+ EraseInput: {
835
+ type: "object",
836
+ properties: {
837
+ sections: {
838
+ type: "array",
839
+ items: SECTION,
840
+ description: "Default: every section."
841
+ },
842
+ reason: {
843
+ type: "string",
844
+ description: "Recorded in the self-audit event."
845
+ }
846
+ }
847
+ },
848
+ PruneResult: {
849
+ type: "object",
850
+ required: [
851
+ "tenant",
852
+ "pruned",
853
+ "baseSeq"
854
+ ],
855
+ properties: {
856
+ tenant: str,
857
+ pruned: int,
858
+ baseSeq: int
859
+ }
860
+ },
861
+ StreamStatus: {
862
+ type: "object",
863
+ required: [
864
+ "name",
865
+ "kind",
866
+ "tenants"
867
+ ],
868
+ properties: {
869
+ name: str,
870
+ kind: str,
871
+ tenants: {
872
+ type: "array",
873
+ items: {
874
+ type: "object",
875
+ properties: {
876
+ tenant: str,
877
+ cursor: int,
878
+ headSeq: int,
879
+ lag: int,
880
+ failures: int,
881
+ lastError: str,
882
+ lastErrorAt: dateTime,
883
+ nextAttemptAt: dateTime,
884
+ lastDeliveredAt: dateTime
885
+ }
886
+ }
887
+ }
888
+ }
889
+ },
890
+ Overview: {
891
+ type: "object",
892
+ required: [
893
+ "tenants",
894
+ "events",
895
+ "recent",
896
+ "streams"
897
+ ],
898
+ properties: {
899
+ tenants: int,
900
+ events: int,
901
+ recent: {
902
+ type: "array",
903
+ items: { $ref: "#/components/schemas/AuditEvent" }
904
+ },
905
+ streams: {
906
+ type: "array",
907
+ items: { $ref: "#/components/schemas/StreamStatus" }
908
+ }
909
+ }
910
+ },
911
+ PanelConfig: {
912
+ type: "object",
913
+ required: [
914
+ "title",
915
+ "basePath",
916
+ "readonly",
917
+ "portal",
918
+ "principal",
919
+ "allowed",
920
+ "features"
921
+ ],
922
+ properties: {
923
+ title: str,
924
+ basePath: str,
925
+ readonly: { type: "boolean" },
926
+ logoUrl: str,
927
+ portal: {
928
+ type: "boolean",
929
+ description: "True when the request carried a valid portal token."
930
+ },
931
+ tenant: {
932
+ type: "string",
933
+ description: "The portal principal's tenant."
934
+ },
935
+ principal: {
936
+ type: ["object", "null"],
937
+ properties: {
938
+ id: str,
939
+ name: str,
940
+ email: str
941
+ }
942
+ },
943
+ allowed: {
944
+ type: "array",
945
+ items: {
946
+ type: "string",
947
+ enum: [
948
+ "tenant:read",
949
+ "event:read",
950
+ "event:record",
951
+ "event:export",
952
+ "event:erase",
953
+ "integrity:read",
954
+ "integrity:checkpoint",
955
+ "action:read",
956
+ "action:update",
957
+ "action:delete",
958
+ "retention:prune",
959
+ "stream:read",
960
+ "stream:retry"
961
+ ]
962
+ }
963
+ },
964
+ features: {
965
+ type: "object",
966
+ properties: {
967
+ signer: { type: "boolean" },
968
+ streams: { type: "boolean" }
969
+ }
970
+ }
971
+ }
972
+ },
973
+ Jwks: {
974
+ type: "object",
975
+ required: ["keys"],
976
+ properties: { keys: {
977
+ type: "array",
978
+ items: { type: "object" }
979
+ } }
980
+ },
981
+ Error: {
982
+ type: "object",
983
+ required: ["error"],
984
+ properties: {
985
+ error: str,
986
+ code: str,
987
+ action: str,
988
+ errors: {
989
+ type: "array",
990
+ items: {
991
+ type: "object",
992
+ properties: {
993
+ path: str,
994
+ message: str
995
+ }
996
+ }
997
+ }
998
+ }
999
+ }
1000
+ };
1001
+ const TENANT = {
1002
+ name: "tenant",
1003
+ in: "path",
1004
+ required: true,
1005
+ schema: str
1006
+ };
1007
+ const ID = {
1008
+ name: "id",
1009
+ in: "path",
1010
+ required: true,
1011
+ schema: str
1012
+ };
1013
+ const NAME = {
1014
+ name: "name",
1015
+ in: "path",
1016
+ required: true,
1017
+ schema: str
1018
+ };
1019
+ const listQ = (name, description) => ({
1020
+ name,
1021
+ in: "query",
1022
+ description: `${description} Repeat the parameter or separate with commas.`,
1023
+ schema: strList,
1024
+ style: "form",
1025
+ explode: true
1026
+ });
1027
+ const q = (name, schema, description) => ({
1028
+ name,
1029
+ in: "query",
1030
+ schema,
1031
+ ...description ? { description } : {}
1032
+ });
1033
+ /** The query model as URL parameters (filters; pagination added separately). */
1034
+ const FILTER_PARAMS = [
1035
+ listQ("actions", "Exact action names, or families (\"invoice.*\")."),
1036
+ listQ("excludeActions", "Names / families to exclude."),
1037
+ q("actorId", str),
1038
+ q("actorType", str),
1039
+ q("targetType", str),
1040
+ q("targetId", str),
1041
+ q("outcome", {
1042
+ type: "string",
1043
+ enum: ["success", "failure"]
1044
+ }),
1045
+ q("from", dateTime, "Inclusive lower bound on occurredAt."),
1046
+ q("to", dateTime, "Exclusive upper bound on occurredAt."),
1047
+ q("search", str, "Case-insensitive substring search.")
1048
+ ];
1049
+ const PAGE_PARAMS = [
1050
+ q("order", {
1051
+ type: "string",
1052
+ enum: ["desc", "asc"],
1053
+ default: "desc"
1054
+ }),
1055
+ q("limit", {
1056
+ type: "integer",
1057
+ minimum: 1,
1058
+ maximum: 500,
1059
+ default: 50
1060
+ }),
1061
+ q("cursor", str, "Opaque, from pageInfo.endCursor.")
1062
+ ];
1063
+ const jsonBody = (schema, required = true) => ({
1064
+ required,
1065
+ content: { "application/json": { schema } }
1066
+ });
1067
+ const jsonRes = (desc, schema) => ({
1068
+ description: desc,
1069
+ content: { "application/json": { schema } }
1070
+ });
1071
+ const ref = (name) => ({ $ref: `#/components/schemas/${name}` });
1072
+ const errorRes = (desc) => jsonRes(desc, ref("Error"));
1073
+ const okRef = (name, desc = name) => jsonRes(desc, ref(name));
1074
+ const arrayOf = (name) => ({
1075
+ type: "array",
1076
+ items: ref(name)
1077
+ });
1078
+ const noContent$1 = { description: "No content" };
1079
+ /** Responses every authenticated route can produce. */
1080
+ const common = {
1081
+ "401": errorRes("Unauthenticated or invalid portal token"),
1082
+ "403": errorRes("Denied (authorization, portal scope, or a hook)")
1083
+ };
1084
+ /** Plus readonly, for mutating routes. */
1085
+ const mutating = {
1086
+ ...common,
1087
+ "423": errorRes("The panel is readonly")
1088
+ };
1089
+ /** Build the OpenAPI 3.1 document for the panel API. Pure — safe to call anywhere. */
1090
+ function buildOpenApiDocument(options = {}) {
1091
+ const base = options.basePath && options.basePath !== "/" ? options.basePath : "";
1092
+ const tenantPath = "/api/tenants/{tenant}";
1093
+ return {
1094
+ openapi: "3.1.0",
1095
+ info: {
1096
+ title: options.title ?? "@xtandard/audit API",
1097
+ version: options.version ?? "0.1.0",
1098
+ description: "Control-plane API for @xtandard/audit: browse, record, export and verify per-tenant tamper-evident audit logs; manage checkpoints, retention, the action catalog and SIEM streams. Portal tokens (Authorization: Bearer audpt_…) hit the same surface scoped to one tenant and an optional view filter."
1099
+ },
1100
+ servers: [{ url: base || "/" }],
1101
+ tags: [
1102
+ { name: "meta" },
1103
+ { name: "tenants" },
1104
+ { name: "events" },
1105
+ { name: "integrity" },
1106
+ { name: "retention" },
1107
+ { name: "actions" },
1108
+ { name: "streams" }
1109
+ ],
1110
+ security: [{ basicAuth: [] }, { bearerAuth: [] }],
1111
+ paths: {
1112
+ "/config": { get: {
1113
+ tags: ["meta"],
1114
+ security: [],
1115
+ summary: "Bootstrap config (principal, allowed actions, portal flag, features)",
1116
+ responses: { "200": okRef("PanelConfig") }
1117
+ } },
1118
+ "/api/openapi.json": { get: {
1119
+ tags: ["meta"],
1120
+ security: [],
1121
+ summary: "This OpenAPI document",
1122
+ responses: { "200": jsonRes("OpenAPI 3.1 document", { type: "object" }) }
1123
+ } },
1124
+ "/api/integrity/keys": { get: {
1125
+ tags: ["integrity"],
1126
+ security: [],
1127
+ summary: "Public checkpoint verification keys as a JWKS (unauthenticated, CORS-open)",
1128
+ responses: { "200": okRef("Jwks") }
1129
+ } },
1130
+ "/api/overview": { get: {
1131
+ tags: ["tenants"],
1132
+ summary: "Dashboard counters, the 10 latest events across tenants, stream status",
1133
+ responses: {
1134
+ "200": okRef("Overview"),
1135
+ ...common
1136
+ }
1137
+ } },
1138
+ "/api/tenants": { get: {
1139
+ tags: ["tenants"],
1140
+ summary: "List tenants (created implicitly on their first event)",
1141
+ responses: {
1142
+ "200": jsonRes("Tenants", arrayOf("AuditTenant")),
1143
+ ...common
1144
+ }
1145
+ } },
1146
+ [tenantPath]: {
1147
+ parameters: [TENANT],
1148
+ get: {
1149
+ tags: ["tenants"],
1150
+ summary: "Get a tenant (chain head + retained count)",
1151
+ responses: {
1152
+ "200": okRef("AuditTenant"),
1153
+ "404": errorRes("Not found"),
1154
+ ...common
1155
+ }
1156
+ }
1157
+ },
1158
+ "/api/events": { get: {
1159
+ tags: ["events"],
1160
+ summary: "Search events across tenants (portal tokens: their tenant only)",
1161
+ parameters: [
1162
+ q("tenant", str),
1163
+ ...FILTER_PARAMS,
1164
+ ...PAGE_PARAMS
1165
+ ],
1166
+ responses: {
1167
+ "200": okRef("AuditPage"),
1168
+ "400": errorRes("Bad query or cursor"),
1169
+ ...common
1170
+ }
1171
+ } },
1172
+ [`${tenantPath}/events`]: {
1173
+ parameters: [TENANT],
1174
+ get: {
1175
+ tags: ["events"],
1176
+ summary: "Search a tenant's events",
1177
+ parameters: [...FILTER_PARAMS, ...PAGE_PARAMS],
1178
+ responses: {
1179
+ "200": okRef("AuditPage"),
1180
+ "400": errorRes("Bad query or cursor"),
1181
+ ...common
1182
+ }
1183
+ },
1184
+ post: {
1185
+ tags: ["events"],
1186
+ summary: "Record one event (object body) or a batch (array body)",
1187
+ requestBody: jsonBody({ oneOf: [ref("AuditEventInput"), arrayOf("AuditEventInput")] }),
1188
+ responses: {
1189
+ "201": jsonRes("Recorded", { oneOf: [ref("AuditEvent"), arrayOf("AuditEvent")] }),
1190
+ "409": errorRes("Same explicit id, different content"),
1191
+ "422": errorRes("Validation error"),
1192
+ ...mutating
1193
+ }
1194
+ }
1195
+ },
1196
+ [`${tenantPath}/events/{id}`]: {
1197
+ parameters: [TENANT, ID],
1198
+ get: {
1199
+ tags: ["events"],
1200
+ summary: "Get one event",
1201
+ responses: {
1202
+ "200": okRef("AuditEvent"),
1203
+ "404": errorRes("Not found"),
1204
+ ...common
1205
+ }
1206
+ }
1207
+ },
1208
+ [`${tenantPath}/events/{id}/erase`]: {
1209
+ parameters: [TENANT, ID],
1210
+ post: {
1211
+ tags: ["events"],
1212
+ summary: "Erase sections of an event (digests kept: the chain still verifies)",
1213
+ requestBody: jsonBody(ref("EraseInput"), false),
1214
+ responses: {
1215
+ "200": okRef("AuditEvent", "The erased event"),
1216
+ "404": errorRes("Not found"),
1217
+ "422": errorRes("Unknown section"),
1218
+ ...mutating
1219
+ }
1220
+ }
1221
+ },
1222
+ [`${tenantPath}/export`]: {
1223
+ parameters: [TENANT],
1224
+ get: {
1225
+ tags: ["events"],
1226
+ summary: "Stream an export (csv | json | jsonl, or the verifiable `bundle` of the whole chain)",
1227
+ parameters: [
1228
+ q("format", {
1229
+ type: "string",
1230
+ enum: [
1231
+ "csv",
1232
+ "json",
1233
+ "jsonl",
1234
+ "bundle"
1235
+ ],
1236
+ default: "csv"
1237
+ }),
1238
+ ...FILTER_PARAMS,
1239
+ PAGE_PARAMS[0]
1240
+ ],
1241
+ responses: {
1242
+ "200": {
1243
+ description: "The export, as an attachment (`content-disposition`)",
1244
+ content: {
1245
+ "text/csv": { schema: str },
1246
+ "application/json": { schema: arrayOf("AuditEvent") },
1247
+ "application/x-ndjson": { schema: str }
1248
+ }
1249
+ },
1250
+ "400": errorRes("Bad format or query"),
1251
+ ...common
1252
+ }
1253
+ }
1254
+ },
1255
+ [`${tenantPath}/verify`]: {
1256
+ parameters: [TENANT],
1257
+ get: {
1258
+ tags: ["integrity"],
1259
+ summary: "Verify the tenant's chain (whole retained range, or fromSeq..toSeq)",
1260
+ parameters: [q("fromSeq", int), q("toSeq", int)],
1261
+ responses: {
1262
+ "200": okRef("VerifyReport"),
1263
+ ...common
1264
+ }
1265
+ }
1266
+ },
1267
+ [`${tenantPath}/checkpoints`]: {
1268
+ parameters: [TENANT],
1269
+ get: {
1270
+ tags: ["integrity"],
1271
+ summary: "List signed checkpoints",
1272
+ responses: {
1273
+ "200": jsonRes("Checkpoints", arrayOf("AuditCheckpoint")),
1274
+ ...common
1275
+ }
1276
+ },
1277
+ post: {
1278
+ tags: ["integrity"],
1279
+ summary: "Sign the tenant's current chain head",
1280
+ responses: {
1281
+ "201": okRef("AuditCheckpoint", "Created"),
1282
+ "409": errorRes("No signer configured"),
1283
+ ...mutating
1284
+ }
1285
+ }
1286
+ },
1287
+ [`${tenantPath}/prune`]: {
1288
+ parameters: [TENANT],
1289
+ post: {
1290
+ tags: ["retention"],
1291
+ summary: "Apply the retention policy to one tenant",
1292
+ responses: {
1293
+ "200": okRef("PruneResult"),
1294
+ ...mutating
1295
+ }
1296
+ }
1297
+ },
1298
+ "/api/prune": { post: {
1299
+ tags: ["retention"],
1300
+ summary: "Apply the retention policy to every tenant",
1301
+ responses: {
1302
+ "200": jsonRes("Per-tenant results", arrayOf("PruneResult")),
1303
+ ...mutating
1304
+ }
1305
+ } },
1306
+ "/api/actions": { get: {
1307
+ tags: ["actions"],
1308
+ summary: "List the action catalog",
1309
+ responses: {
1310
+ "200": jsonRes("Actions", arrayOf("ActionDefinition")),
1311
+ ...common
1312
+ }
1313
+ } },
1314
+ "/api/actions/{name}": {
1315
+ parameters: [NAME],
1316
+ put: {
1317
+ tags: ["actions"],
1318
+ summary: "Create or update a catalog entry",
1319
+ requestBody: jsonBody(ref("ActionDefinition")),
1320
+ responses: {
1321
+ "200": okRef("ActionDefinition", "Saved"),
1322
+ "422": errorRes("Validation error"),
1323
+ ...mutating
1324
+ }
1325
+ },
1326
+ delete: {
1327
+ tags: ["actions"],
1328
+ summary: "Delete a UI-defined catalog entry",
1329
+ responses: {
1330
+ "204": noContent$1,
1331
+ "404": errorRes("Not found"),
1332
+ "409": errorRes("Defined in code"),
1333
+ ...mutating
1334
+ }
1335
+ }
1336
+ },
1337
+ "/api/streams": { get: {
1338
+ tags: ["streams"],
1339
+ summary: "Stream status: per-tenant cursor, lag, last error, next retry",
1340
+ responses: {
1341
+ "200": jsonRes("Streams", arrayOf("StreamStatus")),
1342
+ ...common
1343
+ }
1344
+ } },
1345
+ "/api/streams/{name}/retry": {
1346
+ parameters: [NAME],
1347
+ post: {
1348
+ tags: ["streams"],
1349
+ summary: "Clear a stream's backoff (one tenant with ?tenant=, else all)",
1350
+ parameters: [q("tenant", str)],
1351
+ responses: {
1352
+ "204": noContent$1,
1353
+ "404": errorRes("Unknown stream"),
1354
+ ...mutating
1355
+ }
1356
+ }
1357
+ }
1358
+ },
1359
+ components: {
1360
+ schemas,
1361
+ securitySchemes: {
1362
+ basicAuth: {
1363
+ type: "http",
1364
+ scheme: "basic"
1365
+ },
1366
+ bearerAuth: {
1367
+ type: "http",
1368
+ scheme: "bearer",
1369
+ description: "Portal tokens (audpt_…) or host-issued bearer credentials."
1370
+ }
1371
+ }
1372
+ }
1373
+ };
1374
+ }
1375
+ //#endregion
1376
+ //#region src/server/render-index-html.ts
1377
+ /**
1378
+ * Renders the SPA `index.html`: injects a `<base>` tag so relative asset URLs
1379
+ * resolve under any mount path, and a bootstrap `window.__AUDIT_CONFIG__`
1380
+ * blob. Falls back to a minimal built-in page when the UI bundle is absent
1381
+ * (e.g. before `bun run build:ui`, or in headless tests).
1382
+ *
1383
+ * @module
1384
+ */
1385
+ const escapeJson = (value) => JSON.stringify(value).replace(/</g, "\\u003c").replace(/>/g, "\\u003e");
1386
+ /** Build the `<base href>` value (always ends in `/`). */
1387
+ function baseHref(basePath) {
1388
+ return basePath === "" ? "/" : `${basePath}/`;
1389
+ }
1390
+ function injectInto(html, config) {
1391
+ const tags = `<base href="${baseHref(config.basePath)}"><script>window.__AUDIT_CONFIG__=${escapeJson(config)}<\/script>`;
1392
+ if (html.includes("<head>")) return html.replace("<head>", `<head>${tags}`);
1393
+ return tags + html;
1394
+ }
1395
+ /** Minimal page served when no built UI is present. */
1396
+ function fallbackHtml(config) {
1397
+ return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><base href="${baseHref(config.basePath)}"><title>${config.title}</title><script>window.__AUDIT_CONFIG__=${escapeJson(config)}<\/script></head><body style="font-family:system-ui;margin:0;padding:3rem;background:#0a0a0a;color:#e5e5e5"><h1 style="margin:0 0 .5rem">${config.title}</h1><p style="color:#a3a3a3">The admin UI bundle is not built. Run <code style="background:#1a1a1a;padding:2px 6px;border-radius:4px">bun run build:ui</code>. The JSON API at <code style="background:#1a1a1a;padding:2px 6px;border-radius:4px">api/</code> is fully available.</p></body></html>`;
1398
+ }
1399
+ /** Read, inject into, and return the SPA index HTML (or a fallback). */
1400
+ async function renderIndexHtml(uiDir, config) {
1401
+ try {
1402
+ return injectInto(await readFile(join(uiDir, "index.html"), "utf8"), config);
1403
+ } catch {
1404
+ return fallbackHtml(config);
1405
+ }
1406
+ }
1407
+ //#endregion
1408
+ //#region src/server/routes.ts
1409
+ const json = (data, status = 200, headers) => new Response(JSON.stringify(data), {
1410
+ status,
1411
+ headers: {
1412
+ "content-type": "application/json; charset=utf-8",
1413
+ ...headers
1414
+ }
1415
+ });
1416
+ const error = (status, message, extra) => json({
1417
+ error: message,
1418
+ ...extra
1419
+ }, status);
1420
+ const noContent = () => new Response(null, { status: 204 });
1421
+ const EMPTY_PAGE = {
1422
+ items: [],
1423
+ pageInfo: {
1424
+ hasNextPage: false,
1425
+ endCursor: null
1426
+ }
1427
+ };
1428
+ const EXPORT_FORMATS = [
1429
+ "csv",
1430
+ "json",
1431
+ "jsonl",
1432
+ "bundle"
1433
+ ];
1434
+ /** File extension per export format (the bundle is JSONL with a distinguishing suffix). */
1435
+ const EXPORT_EXTENSIONS = {
1436
+ csv: "csv",
1437
+ json: "json",
1438
+ jsonl: "jsonl",
1439
+ bundle: "bundle.jsonl"
1440
+ };
1441
+ /** Match `pattern` (with `:name` segments) against `path`. */
1442
+ function match(pattern, path) {
1443
+ const pp = pattern.split("/").filter(Boolean);
1444
+ const ap = path.split("/").filter(Boolean);
1445
+ if (pp.length !== ap.length) return null;
1446
+ const params = {};
1447
+ for (let i = 0; i < pp.length; i++) {
1448
+ const seg = pp[i];
1449
+ const val = ap[i];
1450
+ if (seg.startsWith(":")) try {
1451
+ params[seg.slice(1)] = decodeURIComponent(val);
1452
+ } catch {
1453
+ return null;
1454
+ }
1455
+ else if (seg !== val) return null;
1456
+ }
1457
+ return params;
1458
+ }
1459
+ /** The control-plane actor for a principal (hooks + self-audit attribution). */
1460
+ function actorFor(principal) {
1461
+ return {
1462
+ id: principal.id,
1463
+ ...principal.email !== void 0 ? { email: principal.email } : {},
1464
+ ...principal.name !== void 0 ? { name: principal.name } : {}
1465
+ };
1466
+ }
1467
+ /** Read a list param: repeated (`?a=x&a=y`) and/or comma-separated (`?a=x,y`). */
1468
+ function listParam(params, name) {
1469
+ const values = params.getAll(name).flatMap((v) => v.split(",")).map((v) => v.trim()).filter(Boolean);
1470
+ return values.length ? values : void 0;
1471
+ }
1472
+ /** Read an integer param; throws {@link QueryError} on a malformed value. */
1473
+ function intParam(params, name) {
1474
+ const raw = params.get(name);
1475
+ if (raw === null || raw === "") return void 0;
1476
+ const n = Number(raw);
1477
+ if (!Number.isInteger(n)) throw new QueryError(`Invalid ${name}: ${raw}`);
1478
+ return n;
1479
+ }
1480
+ /** The query model as URL parameters (docs/HTTP_API.md "Query parameters"). */
1481
+ function parseQueryParams(params) {
1482
+ const q = {};
1483
+ const actions = listParam(params, "actions");
1484
+ if (actions) q.actions = actions;
1485
+ const excludeActions = listParam(params, "excludeActions");
1486
+ if (excludeActions) q.excludeActions = excludeActions;
1487
+ for (const k of [
1488
+ "tenant",
1489
+ "actorId",
1490
+ "actorType",
1491
+ "targetType",
1492
+ "targetId"
1493
+ ]) {
1494
+ const v = params.get(k);
1495
+ if (v) q[k] = v;
1496
+ }
1497
+ const outcome = params.get("outcome");
1498
+ if (outcome) {
1499
+ if (outcome !== "success" && outcome !== "failure") throw new QueryError(`Invalid outcome: ${outcome}`);
1500
+ q.outcome = outcome;
1501
+ }
1502
+ for (const k of [
1503
+ "from",
1504
+ "to",
1505
+ "search",
1506
+ "cursor"
1507
+ ]) {
1508
+ const v = params.get(k);
1509
+ if (v) q[k] = v;
1510
+ }
1511
+ const order = params.get("order");
1512
+ if (order) {
1513
+ if (order !== "asc" && order !== "desc") throw new QueryError(`Invalid order: ${order}`);
1514
+ q.order = order;
1515
+ }
1516
+ const limit = intParam(params, "limit");
1517
+ if (limit !== void 0) {
1518
+ if (limit < 1 || limit > 500) throw new QueryError("Invalid limit: expected 1–500");
1519
+ q.limit = limit;
1520
+ }
1521
+ return q;
1522
+ }
1523
+ /** `attachment; filename="<tenant>-audit-<date>.<ext>"`, with a filesystem-safe tenant. */
1524
+ function exportFilename(tenant, format, now) {
1525
+ return `${tenant.replace(/[^a-zA-Z0-9._-]/g, "_")}-audit-${new Date(now).toISOString().slice(0, 10)}.${EXPORT_EXTENSIONS[format]}`;
1526
+ }
1527
+ /** Read an optional JSON body (empty body → `fallback`). */
1528
+ async function optionalBody(request, fallback) {
1529
+ const text = await request.text();
1530
+ if (!text.trim()) return fallback;
1531
+ return JSON.parse(text);
1532
+ }
1533
+ /**
1534
+ * Handle an API request. `path` is already base-path-stripped. Returns a
1535
+ * `Response` for API/config routes, or `null` if the path is not an API route.
1536
+ */
1537
+ async function handleApiRequest(request, path, ctx) {
1538
+ if (!(path === "/config" || path === "/api/config" || path === "/openapi.json" || path === "/api" || path.startsWith("/api/"))) return null;
1539
+ const method = request.method.toUpperCase();
1540
+ const url = new URL(request.url);
1541
+ if (path === "/api/openapi.json" || path === "/openapi.json") return json(buildOpenApiDocument({
1542
+ basePath: ctx.basePath,
1543
+ title: ctx.title
1544
+ }));
1545
+ if (path === "/api/integrity/keys" && method === "GET") return json(await ctx.core.jwks(), 200, {
1546
+ "access-control-allow-origin": "*",
1547
+ "cache-control": "public, max-age=300"
1548
+ });
1549
+ let principal = null;
1550
+ let grant = null;
1551
+ let portalAllow = /* @__PURE__ */ new Set();
1552
+ const bearer = request.headers.get("authorization");
1553
+ if (ctx.portal && bearer?.startsWith(`Bearer audpt_`)) {
1554
+ try {
1555
+ grant = await verifyPortalToken(ctx.portal.secret, bearer.slice(7));
1556
+ } catch (err) {
1557
+ return mapError(err);
1558
+ }
1559
+ principal = {
1560
+ id: `portal:${grant.tenant}`,
1561
+ metadata: {
1562
+ portal: true,
1563
+ tenant: grant.tenant,
1564
+ ...grant.filter ? { filter: grant.filter } : {}
1565
+ }
1566
+ };
1567
+ portalAllow = new Set(ctx.portal.allow ?? DEFAULT_PORTAL_ACTIONS);
1568
+ } else try {
1569
+ principal = await ctx.auth.authenticate(request);
1570
+ } catch (err) {
1571
+ return mapError(err);
1572
+ }
1573
+ /** Portal scoping: the token's tenant, its allowed actions, read-only global catalog. */
1574
+ const portalPermits = (action, resource) => {
1575
+ if (!grant || !portalAllow.has(action)) return false;
1576
+ switch (resource.type) {
1577
+ case "action": return action === "action:read";
1578
+ case "stream": return false;
1579
+ default: return resource.tenant === grant.tenant;
1580
+ }
1581
+ };
1582
+ const decide = async (action, resource) => {
1583
+ if (!principal) return false;
1584
+ if (grant) return portalPermits(action, resource);
1585
+ return ctx.authorization.authorize({
1586
+ principal,
1587
+ action,
1588
+ resource,
1589
+ request
1590
+ });
1591
+ };
1592
+ if (path === "/config" || path === "/api/config") {
1593
+ const allowed = [];
1594
+ for (const action of ALL_ACTIONS) {
1595
+ if (ctx.readonly && isMutatingAction(action)) continue;
1596
+ const resource = configResource(action, grant?.tenant);
1597
+ try {
1598
+ if (await decide(action, resource)) allowed.push(action);
1599
+ } catch {}
1600
+ }
1601
+ return json({
1602
+ title: ctx.title,
1603
+ basePath: ctx.basePath,
1604
+ readonly: ctx.readonly,
1605
+ ...ctx.logoUrl !== void 0 ? { logoUrl: ctx.logoUrl } : {},
1606
+ portal: grant !== null,
1607
+ ...grant ? { tenant: grant.tenant } : {},
1608
+ principal: principal ? {
1609
+ id: principal.id,
1610
+ ...principal.name !== void 0 ? { name: principal.name } : {},
1611
+ ...principal.email !== void 0 ? { email: principal.email } : {}
1612
+ } : null,
1613
+ allowed,
1614
+ features: {
1615
+ signer: ctx.core.options.signer !== void 0,
1616
+ streams: (ctx.streams?.streams.length ?? 0) > 0
1617
+ }
1618
+ });
1619
+ }
1620
+ if (principal === null) return ctx.auth.challenge?.(request) ?? error(401, "Unauthorized");
1621
+ const authorize = async (action, resource) => {
1622
+ if (ctx.readonly && isMutatingAction(action)) return error(423, "The audit panel is readonly", {
1623
+ code: "READONLY",
1624
+ action
1625
+ });
1626
+ return await decide(action, resource) ? null : error(403, "Forbidden", { action });
1627
+ };
1628
+ const actor = actorFor(principal);
1629
+ const opts = { actor };
1630
+ /** Run a (possibly portal-scoped) query. */
1631
+ const runQuery = async (query) => {
1632
+ if (!grant) return ctx.core.query(query);
1633
+ const scoped = scopeQueryToPortal(query, grant);
1634
+ return scoped.empty ? EMPTY_PAGE : ctx.core.query(scoped.query);
1635
+ };
1636
+ try {
1637
+ if (path === "/api/overview" && method === "GET") {
1638
+ const denied = await authorize("tenant:read", { type: "tenant" });
1639
+ if (denied) return denied;
1640
+ const tenants = await ctx.core.listTenants();
1641
+ const recent = await ctx.core.query({ limit: 10 });
1642
+ return json({
1643
+ tenants: tenants.length,
1644
+ events: tenants.reduce((sum, t) => sum + (t.count ?? 0), 0),
1645
+ recent: recent.items,
1646
+ streams: ctx.streams ? await ctx.streams.status() : []
1647
+ });
1648
+ }
1649
+ if (path === "/api/tenants" && method === "GET") {
1650
+ const denied = await authorize("tenant:read", { type: "tenant" });
1651
+ if (denied) return denied;
1652
+ return json(await ctx.core.listTenants());
1653
+ }
1654
+ let m = match("/api/tenants/:tenant", path);
1655
+ if (m && method === "GET") {
1656
+ const tenant = m.tenant;
1657
+ const denied = await authorize("tenant:read", {
1658
+ type: "tenant",
1659
+ tenant
1660
+ });
1661
+ if (denied) return denied;
1662
+ const head = await ctx.core.head(tenant);
1663
+ if (head.seq === 0) return error(404, `tenant "${tenant}" not found`);
1664
+ const count = grant?.filter ? void 0 : await ctx.core.count(tenant);
1665
+ return json({
1666
+ key: tenant,
1667
+ head,
1668
+ ...count !== void 0 ? { count } : {}
1669
+ });
1670
+ }
1671
+ if (path === "/api/events" && method === "GET") {
1672
+ const query = parseQueryParams(url.searchParams);
1673
+ const tenant = grant ? grant.tenant : query.tenant;
1674
+ const denied = await authorize("event:read", {
1675
+ type: "event",
1676
+ ...tenant !== void 0 ? { tenant } : {}
1677
+ });
1678
+ if (denied) return denied;
1679
+ return json(await runQuery(query));
1680
+ }
1681
+ m = match("/api/tenants/:tenant/events", path);
1682
+ if (m) {
1683
+ const tenant = m.tenant;
1684
+ if (method === "GET") {
1685
+ const denied = await authorize("event:read", {
1686
+ type: "event",
1687
+ tenant
1688
+ });
1689
+ if (denied) return denied;
1690
+ return json(await runQuery({
1691
+ ...parseQueryParams(url.searchParams),
1692
+ tenant
1693
+ }));
1694
+ }
1695
+ if (method === "POST") {
1696
+ const denied = await authorize("event:record", {
1697
+ type: "event",
1698
+ tenant
1699
+ });
1700
+ if (denied) return denied;
1701
+ const body = await request.json();
1702
+ const many = Array.isArray(body);
1703
+ const inputs = many ? body : [body];
1704
+ const issues = inputs.flatMap((input, i) => input === null || typeof input !== "object" || Array.isArray(input) ? [{
1705
+ path: many ? `[${i}]` : "event",
1706
+ message: "expected an object"
1707
+ }] : input.tenant !== void 0 && input.tenant !== tenant ? [{
1708
+ path: many ? `[${i}].tenant` : "event.tenant",
1709
+ message: `does not match the path tenant "${tenant}"`
1710
+ }] : []);
1711
+ if (issues.length) throw new ValidationError(issues);
1712
+ const prepared = inputs.map((input) => ({
1713
+ ...input,
1714
+ tenant,
1715
+ actor: input.actor ?? {
1716
+ ...actor,
1717
+ type: "api"
1718
+ }
1719
+ }));
1720
+ const events = many ? await ctx.core.recordMany(prepared) : [await ctx.core.record(prepared[0])];
1721
+ return json(many ? events : events[0], 201);
1722
+ }
1723
+ }
1724
+ m = match("/api/tenants/:tenant/events/:id", path);
1725
+ if (m && method === "GET") {
1726
+ const { tenant, id } = m;
1727
+ const denied = await authorize("event:read", {
1728
+ type: "event",
1729
+ tenant,
1730
+ eventId: id
1731
+ });
1732
+ if (denied) return denied;
1733
+ const event = await ctx.core.get(tenant, id);
1734
+ if (!event || grant && !portalCanSee(event, grant)) return error(404, `event "${id}" not found`);
1735
+ return json(event);
1736
+ }
1737
+ m = match("/api/tenants/:tenant/events/:id/erase", path);
1738
+ if (m && method === "POST") {
1739
+ const { tenant, id } = m;
1740
+ const denied = await authorize("event:erase", {
1741
+ type: "event",
1742
+ tenant,
1743
+ eventId: id
1744
+ });
1745
+ if (denied) return denied;
1746
+ const input = await optionalBody(request, {});
1747
+ return json(await ctx.core.erase(tenant, id, input, opts));
1748
+ }
1749
+ m = match("/api/tenants/:tenant/export", path);
1750
+ if (m && method === "GET") {
1751
+ const tenant = m.tenant;
1752
+ const denied = await authorize("event:export", {
1753
+ type: "event",
1754
+ tenant
1755
+ });
1756
+ if (denied) return denied;
1757
+ const params = new URLSearchParams(url.searchParams);
1758
+ const format = params.get("format") ?? "csv";
1759
+ if (!EXPORT_FORMATS.includes(format)) return error(400, `Invalid format: expected one of ${EXPORT_FORMATS.join(", ")}`);
1760
+ params.delete("format");
1761
+ let query = {
1762
+ ...parseQueryParams(params),
1763
+ tenant
1764
+ };
1765
+ delete query.cursor;
1766
+ delete query.limit;
1767
+ if (grant) {
1768
+ if (format === "bundle" && grant.filter) return error(403, "Bundle exports are not available to filtered portal tokens", { action: "event:export" });
1769
+ const scoped = scopeQueryToPortal(query, grant);
1770
+ query = scoped.query;
1771
+ if (scoped.empty) query = {
1772
+ ...query,
1773
+ from: (/* @__PURE__ */ new Date(0)).toISOString(),
1774
+ to: (/* @__PURE__ */ new Date(0)).toISOString()
1775
+ };
1776
+ }
1777
+ const stream = await exportEvents(ctx.core, query, {
1778
+ format,
1779
+ ...opts
1780
+ });
1781
+ return new Response(stream, {
1782
+ status: 200,
1783
+ headers: {
1784
+ "content-type": EXPORT_CONTENT_TYPES[format],
1785
+ "content-disposition": `attachment; filename="${exportFilename(tenant, format, ctx.core.options.now())}"`,
1786
+ "cache-control": "no-store"
1787
+ }
1788
+ });
1789
+ }
1790
+ m = match("/api/tenants/:tenant/verify", path);
1791
+ if (m && method === "GET") {
1792
+ const tenant = m.tenant;
1793
+ const denied = await authorize("integrity:read", {
1794
+ type: "integrity",
1795
+ tenant
1796
+ });
1797
+ if (denied) return denied;
1798
+ const fromSeq = intParam(url.searchParams, "fromSeq");
1799
+ const toSeq = intParam(url.searchParams, "toSeq");
1800
+ return json(await ctx.core.verify(tenant, {
1801
+ ...fromSeq !== void 0 ? { fromSeq } : {},
1802
+ ...toSeq !== void 0 ? { toSeq } : {}
1803
+ }));
1804
+ }
1805
+ m = match("/api/tenants/:tenant/checkpoints", path);
1806
+ if (m) {
1807
+ const tenant = m.tenant;
1808
+ if (method === "GET") {
1809
+ const denied = await authorize("integrity:read", {
1810
+ type: "integrity",
1811
+ tenant
1812
+ });
1813
+ if (denied) return denied;
1814
+ return json(await ctx.core.listCheckpoints(tenant));
1815
+ }
1816
+ if (method === "POST") {
1817
+ const denied = await authorize("integrity:checkpoint", {
1818
+ type: "integrity",
1819
+ tenant
1820
+ });
1821
+ if (denied) return denied;
1822
+ return json(await ctx.core.checkpoint(tenant, opts), 201);
1823
+ }
1824
+ }
1825
+ m = match("/api/tenants/:tenant/prune", path);
1826
+ if (m && method === "POST") {
1827
+ const tenant = m.tenant;
1828
+ const denied = await authorize("retention:prune", {
1829
+ type: "retention",
1830
+ tenant
1831
+ });
1832
+ if (denied) return denied;
1833
+ return json(await ctx.core.pruneTenant(tenant, opts));
1834
+ }
1835
+ if (path === "/api/prune" && method === "POST") {
1836
+ const denied = await authorize("retention:prune", { type: "retention" });
1837
+ if (denied) return denied;
1838
+ return json(await ctx.core.prune(opts));
1839
+ }
1840
+ if (path === "/api/actions" && method === "GET") {
1841
+ const denied = await authorize("action:read", { type: "action" });
1842
+ if (denied) return denied;
1843
+ return json(await ctx.core.listActions());
1844
+ }
1845
+ m = match("/api/actions/:name", path);
1846
+ if (m) {
1847
+ const name = m.name;
1848
+ if (method === "PUT") {
1849
+ const denied = await authorize("action:update", {
1850
+ type: "action",
1851
+ name
1852
+ });
1853
+ if (denied) return denied;
1854
+ const input = await request.json();
1855
+ if (input === null || typeof input !== "object" || Array.isArray(input)) throw new ValidationError([{
1856
+ path: "action",
1857
+ message: "expected an object"
1858
+ }]);
1859
+ return json(await ctx.core.upsertAction({
1860
+ ...input,
1861
+ name
1862
+ }, opts));
1863
+ }
1864
+ if (method === "DELETE") {
1865
+ const denied = await authorize("action:delete", {
1866
+ type: "action",
1867
+ name
1868
+ });
1869
+ if (denied) return denied;
1870
+ await ctx.core.deleteAction(name, opts);
1871
+ return noContent();
1872
+ }
1873
+ }
1874
+ if (path === "/api/streams" && method === "GET") {
1875
+ const denied = await authorize("stream:read", { type: "stream" });
1876
+ if (denied) return denied;
1877
+ return json(ctx.streams ? await ctx.streams.status() : []);
1878
+ }
1879
+ m = match("/api/streams/:name/retry", path);
1880
+ if (m && method === "POST") {
1881
+ const name = m.name;
1882
+ const denied = await authorize("stream:retry", {
1883
+ type: "stream",
1884
+ name
1885
+ });
1886
+ if (denied) return denied;
1887
+ if (!ctx.streams?.streams.some((s) => s.name === name)) return error(404, `stream "${name}" not found`);
1888
+ const tenant = url.searchParams.get("tenant") ?? void 0;
1889
+ await ctx.streams.retry(name, tenant);
1890
+ return noContent();
1891
+ }
1892
+ return error(404, "Not found");
1893
+ } catch (err) {
1894
+ return mapError(err);
1895
+ }
1896
+ }
1897
+ /**
1898
+ * The resource `/config` asks the authorization provider about for each
1899
+ * action: the "listing" resource (no tenant / name), the portal's tenant for
1900
+ * portal principals, and `tenant: "*"` for `integrity`, whose resource always
1901
+ * names a tenant.
1902
+ */
1903
+ function configResource(action, tenant) {
1904
+ const type = action.split(":")[0];
1905
+ switch (type) {
1906
+ case "integrity": return {
1907
+ type,
1908
+ tenant: tenant ?? "*"
1909
+ };
1910
+ case "action":
1911
+ case "stream": return { type };
1912
+ default: return tenant ? {
1913
+ type,
1914
+ tenant
1915
+ } : { type };
1916
+ }
1917
+ }
1918
+ /**
1919
+ * Cross-bundle error detection: `instanceof` first, `err.name` fallback. An
1920
+ * error thrown from a separate subpath bundle carries its own copy of the
1921
+ * class, so `instanceof` alone would mis-map it to 500.
1922
+ */
1923
+ function isNamed(err, ctor, name) {
1924
+ return err instanceof ctor || err instanceof Error && err.name === name;
1925
+ }
1926
+ /**
1927
+ * A hook denial, detected by `name` rather than `instanceof` (see
1928
+ * {@link isNamed}). Returns the status to respond with, or `null`.
1929
+ */
1930
+ function hookDeniedStatus(err) {
1931
+ if (err instanceof HookDeniedError) return err.status;
1932
+ if (err instanceof Error && err.name === "HookDeniedError") {
1933
+ const status = err.status;
1934
+ return typeof status === "number" ? status : 403;
1935
+ }
1936
+ return null;
1937
+ }
1938
+ /** Map domain errors to HTTP responses (docs/HTTP_API.md "Errors"). */
1939
+ function mapError(err) {
1940
+ if (isNamed(err, ReadonlyError, "ReadonlyError")) return error(423, err.message, { code: "READONLY" });
1941
+ const denied = hookDeniedStatus(err);
1942
+ if (denied !== null) return error(denied, err.message, { code: "HOOK_DENIED" });
1943
+ if (isNamed(err, PortalTokenError, "PortalTokenError")) return error(401, err.message, { code: "PORTAL_TOKEN" });
1944
+ if (isNamed(err, QueryError, "QueryError")) return error(400, err.message, { code: "BAD_QUERY" });
1945
+ if (isNamed(err, NotFoundError, "NotFoundError")) return error(404, err.message);
1946
+ if (isNamed(err, SignerRequiredError, "SignerRequiredError")) return error(409, err.message, { code: "SIGNER_REQUIRED" });
1947
+ if (isNamed(err, ConflictError, "ConflictError") || isNamed(err, ChainConflictError, "ChainConflictError")) return error(409, err.message, { code: "CONFLICT" });
1948
+ if (isNamed(err, ValidationError, "ValidationError")) {
1949
+ const errors = err.errors;
1950
+ return error(422, err.message, {
1951
+ code: "VALIDATION",
1952
+ errors: Array.isArray(errors) ? errors : []
1953
+ });
1954
+ }
1955
+ if (err instanceof SyntaxError) return error(400, "Invalid JSON body", { code: "BAD_JSON" });
1956
+ return error(500, err instanceof Error ? err.message : "Internal error");
1957
+ }
1958
+ //#endregion
1959
+ //#region src/server/static-assets.ts
1960
+ /**
1961
+ * Serves the bundled SPA's static assets from the UI output directory. Maps file
1962
+ * extensions to content types and guards against path traversal.
1963
+ *
1964
+ * @module
1965
+ */
1966
+ const CONTENT_TYPES = {
1967
+ ".html": "text/html; charset=utf-8",
1968
+ ".js": "text/javascript; charset=utf-8",
1969
+ ".mjs": "text/javascript; charset=utf-8",
1970
+ ".css": "text/css; charset=utf-8",
1971
+ ".json": "application/json; charset=utf-8",
1972
+ ".svg": "image/svg+xml",
1973
+ ".png": "image/png",
1974
+ ".jpg": "image/jpeg",
1975
+ ".jpeg": "image/jpeg",
1976
+ ".gif": "image/gif",
1977
+ ".webp": "image/webp",
1978
+ ".ico": "image/x-icon",
1979
+ ".woff": "font/woff",
1980
+ ".woff2": "font/woff2",
1981
+ ".ttf": "font/ttf",
1982
+ ".map": "application/json; charset=utf-8",
1983
+ ".txt": "text/plain; charset=utf-8"
1984
+ };
1985
+ function contentType(path) {
1986
+ const dot = path.lastIndexOf(".");
1987
+ return CONTENT_TYPES[dot >= 0 ? path.slice(dot).toLowerCase() : ""] ?? "application/octet-stream";
1988
+ }
1989
+ /** True if the path has a file extension (so a miss should 404 rather than fall through to the SPA). */
1990
+ function looksLikeAsset(path) {
1991
+ return (path.split("/").pop() ?? "").includes(".");
1992
+ }
1993
+ /**
1994
+ * Try to serve `path` (base-path-stripped, leading `/`) as a static file from
1995
+ * `uiDir`. Returns a `Response`, or `null` if the file does not exist.
1996
+ */
1997
+ async function serveStaticAsset(uiDir, path) {
1998
+ const rel = normalize(path).replace(/^(\.\.(\/|\\|$))+/, "");
1999
+ const full = join(uiDir, rel);
2000
+ if (!full.startsWith(normalize(uiDir))) return null;
2001
+ try {
2002
+ const data = await readFile(full);
2003
+ return new Response(new Uint8Array(data), {
2004
+ status: 200,
2005
+ headers: {
2006
+ "content-type": contentType(full),
2007
+ "cache-control": rel.includes("/assets/") ? "public, max-age=31536000, immutable" : "no-cache"
2008
+ }
2009
+ });
2010
+ } catch {
2011
+ return null;
2012
+ }
2013
+ }
2014
+ //#endregion
2015
+ //#region src/server/create-fetch-handler.ts
2016
+ /**
2017
+ * The web-standard fetch handler at the heart of every framework adapter and the
2018
+ * standalone app. Composes auth/authorization (plus portal-token scoping), the
2019
+ * JSON admin API, static-asset serving, and SPA fallback into a single
2020
+ * `(request: Request) => Promise<Response>` — and, by default, starts the
2021
+ * stream runner (when `streams` are declared) and the retention maintenance
2022
+ * timer, so mounting the panel is all it takes to operate the log.
2023
+ *
2024
+ * @module
2025
+ */
2026
+ var create_fetch_handler_exports = /* @__PURE__ */ __exportAll({ createFetchHandler: () => createFetchHandler });
2027
+ const defaultAuth = { authenticate: async () => ({ id: "anonymous" }) };
2028
+ const defaultAuthorization = { authorize: async () => true };
2029
+ /**
2030
+ * Locate the built admin SPA (`dist/ui`). When this module runs compiled (the
2031
+ * normal npm-consumer case) it lives in `dist/` and the bundle is the sibling
2032
+ * `./ui`. When it runs from TypeScript source (examples / dev against a
2033
+ * `file:`-linked checkout, where the runtime executes `src/server/*.ts`
2034
+ * directly), the bundle is instead at `<repo>/dist/ui` — i.e. `../../dist/ui`
2035
+ * relative to `src/server/`. Try the candidates and return the first that
2036
+ * exists, falling back to the compiled-layout path so the "build the UI" hint
2037
+ * still fires when nothing is built yet.
2038
+ */
2039
+ function defaultUiDir() {
2040
+ try {
2041
+ const candidates = [new URL("./ui", import.meta.url), new URL("../../dist/ui", import.meta.url)].map((u) => fileURLToPath(u));
2042
+ return candidates.find((p) => existsSync(p)) ?? candidates[0];
2043
+ } catch {
2044
+ return "./ui";
2045
+ }
2046
+ }
2047
+ /**
2048
+ * Build the panel fetch handler.
2049
+ *
2050
+ * @example
2051
+ * ```ts
2052
+ * import { createFetchHandler, ed25519Signer } from "@xtandard/audit";
2053
+ * import { createMemoryStorage } from "@xtandard/audit/storage/memory";
2054
+ *
2055
+ * const { fetch, core } = createFetchHandler({
2056
+ * storage: createMemoryStorage(),
2057
+ * basePath: "/audit",
2058
+ * title: "Acme Audit Log",
2059
+ * signer: await ed25519Signer(JSON.parse(process.env.AUDIT_SIGNING_KEY!)),
2060
+ * retention: { maxAge: "365d" },
2061
+ * });
2062
+ *
2063
+ * Bun.serve({ port: 3000, fetch });
2064
+ * // Elsewhere in the app:
2065
+ * await core.record({ tenant: "acme", action: "invoice.paid", actor: { id: "user_1" } });
2066
+ * ```
2067
+ */
2068
+ function createFetchHandler(options) {
2069
+ const basePath = normalizeBasePath(options.basePath);
2070
+ const readonly = options.readonly ?? false;
2071
+ const title = options.title ?? "@xtandard/audit";
2072
+ const uiDir = options.uiDir ?? defaultUiDir();
2073
+ if (!options.core && !options.storage) throw new Error("createFetchHandler requires either `storage` or a prebuilt `core`. Pass one.");
2074
+ const core = options.core ?? createAuditCore({
2075
+ storage: options.storage,
2076
+ readonly,
2077
+ ...options.hooks !== void 0 ? { hooks: options.hooks } : {},
2078
+ ...options.onHookError ? { onHookError: options.onHookError } : {},
2079
+ ...options.retention ? { retention: options.retention } : {},
2080
+ ...options.signer ? { signer: options.signer } : {},
2081
+ ...options.actions ? { actions: options.actions } : {},
2082
+ ...options.transforms ? { transforms: options.transforms } : {}
2083
+ });
2084
+ let streams = null;
2085
+ if (options.streams?.length) {
2086
+ streams = createStreamRunner(core, {
2087
+ ...options.streamRunner === false ? {} : options.streamRunner ?? {},
2088
+ streams: options.streams
2089
+ });
2090
+ if (options.streamRunner !== false) streams.start();
2091
+ }
2092
+ let maintenance = null;
2093
+ if (options.maintenance !== false && core.options.retention && !readonly) {
2094
+ const intervalMs = durationToMs(options.maintenance?.interval ?? "1h");
2095
+ maintenance = setInterval(() => {
2096
+ core.prune().catch((err) => {
2097
+ console.warn("[@xtandard/audit] scheduled prune failed:", err);
2098
+ });
2099
+ }, intervalMs);
2100
+ maintenance.unref?.();
2101
+ }
2102
+ const apiCtx = {
2103
+ core,
2104
+ auth: options.auth ?? defaultAuth,
2105
+ authorization: options.authorization ?? defaultAuthorization,
2106
+ title,
2107
+ readonly,
2108
+ basePath,
2109
+ streams,
2110
+ ...options.logoUrl !== void 0 ? { logoUrl: options.logoUrl } : {},
2111
+ ...options.portal ? { portal: options.portal } : {}
2112
+ };
2113
+ const cors = options.cors;
2114
+ async function fetch(request) {
2115
+ if (cors && request.method === "OPTIONS") return preflightResponse(request, cors);
2116
+ const response = await respond(request);
2117
+ return cors ? applyCorsHeaders(request, response, cors) : response;
2118
+ }
2119
+ async function respond(request) {
2120
+ const path = stripBasePath(new URL(request.url).pathname, basePath);
2121
+ const api = await handleApiRequest(request, path, apiCtx);
2122
+ if (api) return api;
2123
+ if (request.method !== "GET" && request.method !== "HEAD") return new Response("Method Not Allowed", { status: 405 });
2124
+ const asset = await serveStaticAsset(uiDir, path);
2125
+ if (asset) return asset;
2126
+ if (path !== "/" && looksLikeAsset(path)) return new Response("Not Found", { status: 404 });
2127
+ const html = await renderIndexHtml(uiDir, {
2128
+ title,
2129
+ basePath,
2130
+ readonly,
2131
+ ...options.logoUrl !== void 0 ? { logoUrl: options.logoUrl } : {}
2132
+ });
2133
+ return new Response(html, {
2134
+ status: 200,
2135
+ headers: { "content-type": "text/html; charset=utf-8" }
2136
+ });
2137
+ }
2138
+ return {
2139
+ fetch,
2140
+ core,
2141
+ streams,
2142
+ openapi: () => buildOpenApiDocument({
2143
+ basePath,
2144
+ title
2145
+ }),
2146
+ async close() {
2147
+ if (maintenance) clearInterval(maintenance);
2148
+ maintenance = null;
2149
+ await streams?.stop();
2150
+ }
2151
+ };
2152
+ }
2153
+ //#endregion
2154
+ export { PORTAL_TOKEN_PREFIX as a, intersectActions as c, verifyPortalToken as d, callbackSink as f, DEFAULT_PORTAL_ACTIONS as i, portalCanSee as l, create_fetch_handler_exports as n, PortalTokenError as o, createStreamRunner as p, buildOpenApiDocument as r, createPortalToken as s, createFetchHandler as t, scopeQueryToPortal as u };
2155
+
2156
+ //# sourceMappingURL=create-fetch-handler-BwQQ_IWf.mjs.map