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