@bajustone/fortress 1.0.0-rc.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 (465) hide show
  1. package/CHANGELOG.md +1011 -0
  2. package/LICENSE +21 -0
  3. package/README.md +760 -0
  4. package/SECURITY.md +197 -0
  5. package/bin/fortress.ts +667 -0
  6. package/dist/auth-service-BcyQ2PuZ.d.cts +307 -0
  7. package/dist/auth-service-BkzZkWfH.d.ts +307 -0
  8. package/dist/config-B2366s_G.d.ts +665 -0
  9. package/dist/config-GtlVt6ZD.d.cts +665 -0
  10. package/dist/convert-routes-BLCQT57f.d.ts +72 -0
  11. package/dist/convert-routes-BdMvP2_X.d.cts +72 -0
  12. package/dist/crypto.cjs +61 -0
  13. package/dist/crypto.d.cts +36 -0
  14. package/dist/crypto.d.ts +36 -0
  15. package/dist/crypto.js +35 -0
  16. package/dist/drift-BT1wtMDJ.d.cts +22 -0
  17. package/dist/drift-k9LiYpRP.d.ts +22 -0
  18. package/dist/drizzle/pg.cjs +481 -0
  19. package/dist/drizzle/pg.d.cts +15 -0
  20. package/dist/drizzle/pg.d.ts +15 -0
  21. package/dist/drizzle/pg.js +454 -0
  22. package/dist/drizzle.cjs +1442 -0
  23. package/dist/drizzle.d.cts +85 -0
  24. package/dist/drizzle.d.ts +85 -0
  25. package/dist/drizzle.js +1411 -0
  26. package/dist/express.cjs +1357 -0
  27. package/dist/express.d.cts +333 -0
  28. package/dist/express.d.ts +333 -0
  29. package/dist/express.js +1314 -0
  30. package/dist/fetcher.cjs +77 -0
  31. package/dist/fetcher.d.cts +7 -0
  32. package/dist/fetcher.d.ts +7 -0
  33. package/dist/fetcher.js +41 -0
  34. package/dist/fortress-BmSvFfqK.d.cts +1089 -0
  35. package/dist/fortress-uA-_cheR.d.ts +1089 -0
  36. package/dist/hono.cjs +1530 -0
  37. package/dist/hono.d.cts +514 -0
  38. package/dist/hono.d.ts +514 -0
  39. package/dist/hono.js +1483 -0
  40. package/dist/index-CxEkfCA0.d.cts +77 -0
  41. package/dist/index-CxEkfCA0.d.ts +77 -0
  42. package/dist/index-D054pcb-.d.cts +146 -0
  43. package/dist/index-jAMbbUAY.d.ts +146 -0
  44. package/dist/index.cjs +9046 -0
  45. package/dist/index.d.cts +717 -0
  46. package/dist/index.d.ts +717 -0
  47. package/dist/index.js +8935 -0
  48. package/dist/jwt.cjs +255 -0
  49. package/dist/jwt.d.cts +90 -0
  50. package/dist/jwt.d.ts +90 -0
  51. package/dist/jwt.js +227 -0
  52. package/dist/otel.cjs +108 -0
  53. package/dist/otel.d.cts +62 -0
  54. package/dist/otel.d.ts +62 -0
  55. package/dist/otel.js +73 -0
  56. package/dist/plugins/account-lockout.cjs +322 -0
  57. package/dist/plugins/account-lockout.d.cts +42 -0
  58. package/dist/plugins/account-lockout.d.ts +42 -0
  59. package/dist/plugins/account-lockout.js +295 -0
  60. package/dist/plugins/admin.cjs +2378 -0
  61. package/dist/plugins/admin.d.cts +72 -0
  62. package/dist/plugins/admin.d.ts +72 -0
  63. package/dist/plugins/admin.js +2351 -0
  64. package/dist/plugins/api-key.cjs +792 -0
  65. package/dist/plugins/api-key.d.cts +121 -0
  66. package/dist/plugins/api-key.d.ts +121 -0
  67. package/dist/plugins/api-key.js +765 -0
  68. package/dist/plugins/audit-log.cjs +493 -0
  69. package/dist/plugins/audit-log.d.cts +86 -0
  70. package/dist/plugins/audit-log.d.ts +86 -0
  71. package/dist/plugins/audit-log.js +468 -0
  72. package/dist/plugins/data-isolation.cjs +211 -0
  73. package/dist/plugins/data-isolation.d.cts +49 -0
  74. package/dist/plugins/data-isolation.d.ts +49 -0
  75. package/dist/plugins/data-isolation.js +186 -0
  76. package/dist/plugins/email-verification.cjs +273 -0
  77. package/dist/plugins/email-verification.d.cts +44 -0
  78. package/dist/plugins/email-verification.d.ts +44 -0
  79. package/dist/plugins/email-verification.js +246 -0
  80. package/dist/plugins/magic-link.cjs +231 -0
  81. package/dist/plugins/magic-link.d.cts +39 -0
  82. package/dist/plugins/magic-link.d.ts +39 -0
  83. package/dist/plugins/magic-link.js +204 -0
  84. package/dist/plugins/oauth.cjs +1696 -0
  85. package/dist/plugins/oauth.d.cts +406 -0
  86. package/dist/plugins/oauth.d.ts +406 -0
  87. package/dist/plugins/oauth.js +1669 -0
  88. package/dist/plugins/openapi.cjs +1185 -0
  89. package/dist/plugins/openapi.d.cts +6 -0
  90. package/dist/plugins/openapi.d.ts +6 -0
  91. package/dist/plugins/openapi.js +1158 -0
  92. package/dist/plugins/rate-limit/express.cjs +55 -0
  93. package/dist/plugins/rate-limit/express.d.cts +64 -0
  94. package/dist/plugins/rate-limit/express.d.ts +64 -0
  95. package/dist/plugins/rate-limit/express.js +30 -0
  96. package/dist/plugins/rate-limit/hono.cjs +51 -0
  97. package/dist/plugins/rate-limit/hono.d.cts +59 -0
  98. package/dist/plugins/rate-limit/hono.d.ts +59 -0
  99. package/dist/plugins/rate-limit/hono.js +26 -0
  100. package/dist/plugins/rate-limit/sveltekit.cjs +49 -0
  101. package/dist/plugins/rate-limit/sveltekit.d.cts +59 -0
  102. package/dist/plugins/rate-limit/sveltekit.d.ts +59 -0
  103. package/dist/plugins/rate-limit/sveltekit.js +24 -0
  104. package/dist/plugins/rate-limit.cjs +354 -0
  105. package/dist/plugins/rate-limit.d.cts +140 -0
  106. package/dist/plugins/rate-limit.d.ts +140 -0
  107. package/dist/plugins/rate-limit.js +325 -0
  108. package/dist/plugins/social-login.cjs +905 -0
  109. package/dist/plugins/social-login.d.cts +114 -0
  110. package/dist/plugins/social-login.d.ts +114 -0
  111. package/dist/plugins/social-login.js +880 -0
  112. package/dist/plugins/tenancy.cjs +780 -0
  113. package/dist/plugins/tenancy.d.cts +108 -0
  114. package/dist/plugins/tenancy.d.ts +108 -0
  115. package/dist/plugins/tenancy.js +753 -0
  116. package/dist/plugins/two-factor.cjs +555 -0
  117. package/dist/plugins/two-factor.d.cts +67 -0
  118. package/dist/plugins/two-factor.d.ts +67 -0
  119. package/dist/plugins/two-factor.js +526 -0
  120. package/dist/plugins/webauthn.cjs +786 -0
  121. package/dist/plugins/webauthn.d.cts +72 -0
  122. package/dist/plugins/webauthn.d.ts +72 -0
  123. package/dist/plugins/webauthn.js +766 -0
  124. package/dist/plugins/webhook.cjs +819 -0
  125. package/dist/plugins/webhook.d.cts +254 -0
  126. package/dist/plugins/webhook.d.ts +254 -0
  127. package/dist/plugins/webhook.js +789 -0
  128. package/dist/protect-D1v_0upK.d.cts +123 -0
  129. package/dist/protect-DsxV_-dJ.d.ts +123 -0
  130. package/dist/sveltekit.cjs +1258 -0
  131. package/dist/sveltekit.d.cts +420 -0
  132. package/dist/sveltekit.d.ts +420 -0
  133. package/dist/sveltekit.js +1207 -0
  134. package/dist/testing.cjs +4294 -0
  135. package/dist/testing.d.cts +197 -0
  136. package/dist/testing.d.ts +197 -0
  137. package/dist/testing.js +4264 -0
  138. package/dist/types-et0R8tsC.d.cts +217 -0
  139. package/dist/types-et0R8tsC.d.ts +217 -0
  140. package/docs/adapter-typed-helpers.md +192 -0
  141. package/docs/admin-recipes.md +227 -0
  142. package/docs/architecture.md +434 -0
  143. package/docs/ci/github-actions.yml +59 -0
  144. package/docs/ci.md +109 -0
  145. package/docs/compatibility.md +115 -0
  146. package/docs/deployment.md +305 -0
  147. package/docs/hardening.md +118 -0
  148. package/docs/host-owned-routes.md +154 -0
  149. package/docs/migrations/0001-schema-version.md +54 -0
  150. package/docs/migrations/0002-initial-schema.md +84 -0
  151. package/docs/migrations/upgrade-guide.md +160 -0
  152. package/docs/observability.md +394 -0
  153. package/docs/plugins/account-lockout.md +131 -0
  154. package/docs/plugins/admin.md +402 -0
  155. package/docs/plugins/api-key.md +327 -0
  156. package/docs/plugins/audit-log.md +261 -0
  157. package/docs/plugins/data-isolation.md +186 -0
  158. package/docs/plugins/email-verification.md +121 -0
  159. package/docs/plugins/magic-link.md +123 -0
  160. package/docs/plugins/oauth.md +544 -0
  161. package/docs/plugins/openapi.md +250 -0
  162. package/docs/plugins/rate-limit.md +223 -0
  163. package/docs/plugins/social-login.md +337 -0
  164. package/docs/plugins/tenancy.md +122 -0
  165. package/docs/plugins/two-factor.md +191 -0
  166. package/docs/plugins/webauthn.md +188 -0
  167. package/docs/plugins/webhook.md +242 -0
  168. package/docs/policy-as-code.md +156 -0
  169. package/docs/route-manifest.md +46 -0
  170. package/docs/security.md +261 -0
  171. package/docs/threat-model.md +161 -0
  172. package/examples/README.md +119 -0
  173. package/examples/express-app/index.ts +747 -0
  174. package/examples/hono-app/docker-compose.yml +14 -0
  175. package/examples/hono-app/index.ts +1009 -0
  176. package/examples/policy/fortress.policy.json +47 -0
  177. package/examples/sveltekit-app/README.md +125 -0
  178. package/examples/sveltekit-app/src/app.d.ts +16 -0
  179. package/examples/sveltekit-app/src/hooks.server.ts +23 -0
  180. package/examples/sveltekit-app/src/lib/server/fortress.ts +81 -0
  181. package/examples/sveltekit-app/src/routes/api/echo/[id]/+server.ts +32 -0
  182. package/examples/sveltekit-app/src/routes/api/fortress/[...path]/+server.ts +15 -0
  183. package/examples/sveltekit-app/src/routes/dashboard/+page.server.ts +20 -0
  184. package/examples/sveltekit-app/src/routes/login/+page.server.ts +48 -0
  185. package/examples/sveltekit-app/src/routes/oauth/consent/+page.server.ts +69 -0
  186. package/examples/sveltekit-app/src/routes/oauth/consent/+page.svelte +83 -0
  187. package/migrations/pg/0001_schema_version.down.sql +2 -0
  188. package/migrations/pg/0001_schema_version.sql +8 -0
  189. package/migrations/pg/0002_initial_schema.down.sql +36 -0
  190. package/migrations/pg/0002_initial_schema.sql +376 -0
  191. package/migrations/pg/0003_auth_continuation.down.sql +6 -0
  192. package/migrations/pg/0003_auth_continuation.sql +30 -0
  193. package/migrations/pg/0004_tenant_default_unique.down.sql +1 -0
  194. package/migrations/pg/0004_tenant_default_unique.sql +14 -0
  195. package/migrations/pg/0005_hot_indexes_timestamptz.down.sql +71 -0
  196. package/migrations/pg/0005_hot_indexes_timestamptz.sql +71 -0
  197. package/migrations/pg/0006_canonical_email.down.sql +3 -0
  198. package/migrations/pg/0006_canonical_email.sql +8 -0
  199. package/migrations/pg/0007_audit_chain_anchor.down.sql +1 -0
  200. package/migrations/pg/0007_audit_chain_anchor.sql +8 -0
  201. package/migrations/pg/0008_two_factor_hardening.down.sql +8 -0
  202. package/migrations/pg/0008_two_factor_hardening.sql +8 -0
  203. package/migrations/pg/0009_encrypt_totp_secrets.down.sql +2 -0
  204. package/migrations/pg/0009_encrypt_totp_secrets.sql +5 -0
  205. package/migrations/pg/0010_bigint_append_only_ids.down.sql +2 -0
  206. package/migrations/pg/0010_bigint_append_only_ids.sql +23 -0
  207. package/migrations/sqlite/0001_schema_version.down.sql +2 -0
  208. package/migrations/sqlite/0001_schema_version.sql +8 -0
  209. package/migrations/sqlite/0002_initial_schema.down.sql +36 -0
  210. package/migrations/sqlite/0002_initial_schema.sql +376 -0
  211. package/migrations/sqlite/0003_auth_continuation.down.sql +27 -0
  212. package/migrations/sqlite/0003_auth_continuation.sql +45 -0
  213. package/migrations/sqlite/0004_tenant_default_unique.down.sql +1 -0
  214. package/migrations/sqlite/0004_tenant_default_unique.sql +13 -0
  215. package/migrations/sqlite/0005_hot_indexes_timestamptz.down.sql +10 -0
  216. package/migrations/sqlite/0005_hot_indexes_timestamptz.sql +10 -0
  217. package/migrations/sqlite/0006_canonical_email.down.sql +3 -0
  218. package/migrations/sqlite/0006_canonical_email.sql +8 -0
  219. package/migrations/sqlite/0007_audit_chain_anchor.down.sql +1 -0
  220. package/migrations/sqlite/0007_audit_chain_anchor.sql +8 -0
  221. package/migrations/sqlite/0008_two_factor_hardening.down.sql +14 -0
  222. package/migrations/sqlite/0008_two_factor_hardening.sql +7 -0
  223. package/migrations/sqlite/0009_encrypt_totp_secrets.down.sql +2 -0
  224. package/migrations/sqlite/0009_encrypt_totp_secrets.sql +5 -0
  225. package/migrations/sqlite/0010_bigint_append_only_ids.down.sql +1 -0
  226. package/migrations/sqlite/0010_bigint_append_only_ids.sql +2 -0
  227. package/package.json +398 -0
  228. package/src/adapters/database/index.ts +63 -0
  229. package/src/adapters/database/types.ts +22 -0
  230. package/src/changelog-script.test.ts +21 -0
  231. package/src/cli.test.ts +79 -0
  232. package/src/core/auth/auth-admin.test.ts +247 -0
  233. package/src/core/auth/auth-endpoints.ts +558 -0
  234. package/src/core/auth/auth-observer.test.ts +191 -0
  235. package/src/core/auth/auth-service.ts +1464 -0
  236. package/src/core/auth/email.test.ts +17 -0
  237. package/src/core/auth/email.ts +11 -0
  238. package/src/core/auth/hooks.test.ts +251 -0
  239. package/src/core/auth/impersonation.test.ts +179 -0
  240. package/src/core/auth/jwt.test.ts +184 -0
  241. package/src/core/auth/jwt.ts +239 -0
  242. package/src/core/auth/login-timing.test.ts +77 -0
  243. package/src/core/auth/password-policy.test.ts +253 -0
  244. package/src/core/auth/password-policy.ts +220 -0
  245. package/src/core/auth/password.test.ts +42 -0
  246. package/src/core/auth/password.ts +62 -0
  247. package/src/core/auth/post-auth-gate.test.ts +258 -0
  248. package/src/core/auth/post-auth-gate.ts +228 -0
  249. package/src/core/auth/refresh-token.test.ts +86 -0
  250. package/src/core/auth/refresh-token.ts +105 -0
  251. package/src/core/auth/timing-safe.ts +23 -0
  252. package/src/core/config.ts +212 -0
  253. package/src/core/endpoint.ts +149 -0
  254. package/src/core/errors.ts +199 -0
  255. package/src/core/fetcher-interop.test.ts +106 -0
  256. package/src/core/fortress.test.ts +354 -0
  257. package/src/core/fortress.ts +550 -0
  258. package/src/core/http/call.test.ts +148 -0
  259. package/src/core/http/call.ts +149 -0
  260. package/src/core/http/cookie-serialize.test.ts +198 -0
  261. package/src/core/http/cookie-serialize.ts +107 -0
  262. package/src/core/http/csrf.test.ts +140 -0
  263. package/src/core/http/csrf.ts +173 -0
  264. package/src/core/http/dispatch.ts +652 -0
  265. package/src/core/http/error-response.test.ts +69 -0
  266. package/src/core/http/error-response.ts +93 -0
  267. package/src/core/http/fortress-rbac.test.ts +43 -0
  268. package/src/core/http/fortress-rbac.ts +127 -0
  269. package/src/core/http/handle-request.test.ts +441 -0
  270. package/src/core/http/handle-request.ts +354 -0
  271. package/src/core/http/match.test.ts +122 -0
  272. package/src/core/http/match.ts +126 -0
  273. package/src/core/http/outbound.test.ts +34 -0
  274. package/src/core/http/outbound.ts +105 -0
  275. package/src/core/http/plugin-middleware.ts +67 -0
  276. package/src/core/http/principal.test.ts +345 -0
  277. package/src/core/http/principal.ts +86 -0
  278. package/src/core/http/protect.test.ts +220 -0
  279. package/src/core/http/protect.ts +394 -0
  280. package/src/core/http/token-extraction.test.ts +59 -0
  281. package/src/core/http/token-extraction.ts +53 -0
  282. package/src/core/iam/explain.test.ts +177 -0
  283. package/src/core/iam/explain.ts +302 -0
  284. package/src/core/iam/iam-endpoints.ts +779 -0
  285. package/src/core/iam/iam-service.test.ts +829 -0
  286. package/src/core/iam/iam-service.ts +1137 -0
  287. package/src/core/iam/permission-cache.test.ts +115 -0
  288. package/src/core/iam/permission-cache.ts +71 -0
  289. package/src/core/iam/permission-check-observer.test.ts +90 -0
  290. package/src/core/iam/permission-evaluator.test.ts +291 -0
  291. package/src/core/iam/permission-evaluator.ts +198 -0
  292. package/src/core/iam/permission-sync.test.ts +166 -0
  293. package/src/core/iam/permission-sync.ts +192 -0
  294. package/src/core/iam/resource-sync.test.ts +70 -0
  295. package/src/core/iam/resource-sync.ts +182 -0
  296. package/src/core/iam/service-account-http.test.ts +529 -0
  297. package/src/core/iam/service-account.test.ts +282 -0
  298. package/src/core/internal-adapter.test.ts +389 -0
  299. package/src/core/internal-adapter.ts +435 -0
  300. package/src/core/json-schema.ts +50 -0
  301. package/src/core/manifest/__snapshots__/route-manifest.test.ts.snap +192 -0
  302. package/src/core/manifest/drift.ts +103 -0
  303. package/src/core/manifest/route-manifest.test.ts +142 -0
  304. package/src/core/manifest/route-manifest.ts +154 -0
  305. package/src/core/migrate.test.ts +72 -0
  306. package/src/core/migrations/engine.test.ts +308 -0
  307. package/src/core/migrations/engine.ts +548 -0
  308. package/src/core/migrations/migrations.ts +1771 -0
  309. package/src/core/migrations/pg-migration.integration-test.ts +353 -0
  310. package/src/core/migrations/upgrade-fixture.test.ts +378 -0
  311. package/src/core/observability/db-instrumentation.ts +205 -0
  312. package/src/core/observability/listener-list.test.ts +124 -0
  313. package/src/core/observability/listener-list.ts +73 -0
  314. package/src/core/observability/logger.test.ts +43 -0
  315. package/src/core/observability/logger.ts +49 -0
  316. package/src/core/observability/spans.test.ts +193 -0
  317. package/src/core/observability/types.ts +80 -0
  318. package/src/core/openapi-drift.test.ts +41 -0
  319. package/src/core/openapi.ts +47 -0
  320. package/src/core/plugin-methods-map.ts +75 -0
  321. package/src/core/plugin-runner.test.ts +233 -0
  322. package/src/core/plugin-runner.ts +276 -0
  323. package/src/core/plugin.ts +210 -0
  324. package/src/core/policy/apply.ts +272 -0
  325. package/src/core/policy/diff.ts +288 -0
  326. package/src/core/policy/loader.test.ts +63 -0
  327. package/src/core/policy/loader.ts +214 -0
  328. package/src/core/policy/policy.test.ts +232 -0
  329. package/src/core/policy/types.ts +105 -0
  330. package/src/core/schema-builder.test.ts +660 -0
  331. package/src/core/schema-builder.ts +881 -0
  332. package/src/core/standard-schema.ts +56 -0
  333. package/src/core/types.ts +258 -0
  334. package/src/core/validation.test.ts +195 -0
  335. package/src/core/validation.ts +192 -0
  336. package/src/drizzle/adapter.test.ts +425 -0
  337. package/src/drizzle/adapter.ts +474 -0
  338. package/src/drizzle/index.ts +31 -0
  339. package/src/drizzle/pg/adapter.integration-test.ts +456 -0
  340. package/src/drizzle/pg/index.ts +13 -0
  341. package/src/drizzle/pg/pg.integration-test.ts +1539 -0
  342. package/src/drizzle/pg/schema.ts +539 -0
  343. package/src/drizzle/pg-error-map.test.ts +218 -0
  344. package/src/drizzle/pg-error-map.ts +151 -0
  345. package/src/drizzle/schema.ts +544 -0
  346. package/src/drizzle/sqlite-serialization.test.ts +106 -0
  347. package/src/express/express-api-key-user-routes.test.ts +241 -0
  348. package/src/express/express.test.ts +442 -0
  349. package/src/express/handle.ts +191 -0
  350. package/src/express/index.ts +62 -0
  351. package/src/express/middleware.ts +551 -0
  352. package/src/express/protect.ts +154 -0
  353. package/src/express/validated.test.ts +86 -0
  354. package/src/express/validated.ts +99 -0
  355. package/src/fetcher/index.ts +81 -0
  356. package/src/hono/convert-routes.test.ts +220 -0
  357. package/src/hono/convert-routes.ts +196 -0
  358. package/src/hono/converters.test.ts +50 -0
  359. package/src/hono/converters.ts +43 -0
  360. package/src/hono/handle.ts +79 -0
  361. package/src/hono/helpers.ts +2 -0
  362. package/src/hono/hono-api-key-user-routes.test.ts +225 -0
  363. package/src/hono/hono-handlers.test.ts +861 -0
  364. package/src/hono/hono.test.ts +454 -0
  365. package/src/hono/index.ts +101 -0
  366. package/src/hono/middleware/auth.ts +236 -0
  367. package/src/hono/middleware/auth.types.test.ts +94 -0
  368. package/src/hono/middleware/csrf.test.ts +127 -0
  369. package/src/hono/middleware/csrf.ts +68 -0
  370. package/src/hono/middleware/error-handler.ts +12 -0
  371. package/src/hono/middleware/plugin-middleware.ts +35 -0
  372. package/src/hono/middleware/rbac.ts +131 -0
  373. package/src/hono/middleware/security-headers.test.ts +88 -0
  374. package/src/hono/middleware/security-headers.ts +68 -0
  375. package/src/hono/openapi.ts +237 -0
  376. package/src/hono/protect.ts +87 -0
  377. package/src/hono/validated.test.ts +123 -0
  378. package/src/hono/validated.ts +62 -0
  379. package/src/index.ts +309 -0
  380. package/src/integration.test.ts +718 -0
  381. package/src/internal/changelog.ts +56 -0
  382. package/src/otel/index.ts +158 -0
  383. package/src/otel/otel-types.test.ts +35 -0
  384. package/src/otel/otel.test.ts +235 -0
  385. package/src/plugins/account-lockout/account-lockout.test.ts +367 -0
  386. package/src/plugins/account-lockout/index.ts +267 -0
  387. package/src/plugins/admin/admin-api-key.test.ts +438 -0
  388. package/src/plugins/admin/index.ts +1612 -0
  389. package/src/plugins/api-key/api-key.test.ts +684 -0
  390. package/src/plugins/api-key/core.ts +336 -0
  391. package/src/plugins/api-key/index.ts +315 -0
  392. package/src/plugins/audit-log/audit-log.test.ts +749 -0
  393. package/src/plugins/audit-log/index.ts +680 -0
  394. package/src/plugins/data-isolation/data-isolation.test.ts +197 -0
  395. package/src/plugins/data-isolation/index.ts +157 -0
  396. package/src/plugins/email-verification/email-verification.test.ts +199 -0
  397. package/src/plugins/email-verification/index.ts +190 -0
  398. package/src/plugins/magic-link/index.ts +129 -0
  399. package/src/plugins/magic-link/magic-link.test.ts +156 -0
  400. package/src/plugins/oauth/id-token.ts +86 -0
  401. package/src/plugins/oauth/index.ts +2145 -0
  402. package/src/plugins/oauth/jwks.test.ts +32 -0
  403. package/src/plugins/oauth/jwks.ts +182 -0
  404. package/src/plugins/oauth/oauth.test.ts +2220 -0
  405. package/src/plugins/oauth/pkce.ts +58 -0
  406. package/src/plugins/openapi/index.ts +298 -0
  407. package/src/plugins/openapi/openapi.test.ts +425 -0
  408. package/src/plugins/openapi/spec-builder.ts +287 -0
  409. package/src/plugins/rate-limit/express.test.ts +89 -0
  410. package/src/plugins/rate-limit/express.ts +86 -0
  411. package/src/plugins/rate-limit/hono.test.ts +60 -0
  412. package/src/plugins/rate-limit/hono.ts +74 -0
  413. package/src/plugins/rate-limit/index.ts +383 -0
  414. package/src/plugins/rate-limit/memory-store.ts +61 -0
  415. package/src/plugins/rate-limit/rate-limit.test.ts +756 -0
  416. package/src/plugins/rate-limit/sveltekit.test.ts +58 -0
  417. package/src/plugins/rate-limit/sveltekit.ts +66 -0
  418. package/src/plugins/social-login/index.ts +715 -0
  419. package/src/plugins/social-login/providers/apple.ts +34 -0
  420. package/src/plugins/social-login/providers/discord.ts +26 -0
  421. package/src/plugins/social-login/providers/github.ts +54 -0
  422. package/src/plugins/social-login/providers/google.ts +23 -0
  423. package/src/plugins/social-login/providers/index.ts +22 -0
  424. package/src/plugins/social-login/providers/microsoft.ts +35 -0
  425. package/src/plugins/social-login/providers/oidc.ts +37 -0
  426. package/src/plugins/social-login/providers/providers.test.ts +211 -0
  427. package/src/plugins/social-login/social-login.test.ts +675 -0
  428. package/src/plugins/social-login/types.ts +80 -0
  429. package/src/plugins/tenancy/index.ts +544 -0
  430. package/src/plugins/tenancy/tenancy.test.ts +323 -0
  431. package/src/plugins/two-factor/index.ts +569 -0
  432. package/src/plugins/two-factor/two-factor.test.ts +235 -0
  433. package/src/plugins/webauthn/index.ts +554 -0
  434. package/src/plugins/webauthn/webauthn.test.ts +472 -0
  435. package/src/plugins/webhook/builtin-events.ts +29 -0
  436. package/src/plugins/webhook/delivery.test.ts +51 -0
  437. package/src/plugins/webhook/delivery.ts +154 -0
  438. package/src/plugins/webhook/hooks.ts +89 -0
  439. package/src/plugins/webhook/index.ts +445 -0
  440. package/src/plugins/webhook/queue/database.ts +67 -0
  441. package/src/plugins/webhook/queue/in-memory.test.ts +48 -0
  442. package/src/plugins/webhook/queue/in-memory.ts +71 -0
  443. package/src/plugins/webhook/queue/types.ts +51 -0
  444. package/src/plugins/webhook/registry.test.ts +48 -0
  445. package/src/plugins/webhook/registry.ts +64 -0
  446. package/src/plugins/webhook/signing.ts +45 -0
  447. package/src/plugins/webhook/ssrf.ts +198 -0
  448. package/src/plugins/webhook/types.ts +138 -0
  449. package/src/plugins/webhook/webhook.test.ts +324 -0
  450. package/src/sveltekit/actions.ts +233 -0
  451. package/src/sveltekit/catch-all.ts +43 -0
  452. package/src/sveltekit/cookies.ts +136 -0
  453. package/src/sveltekit/handle.ts +356 -0
  454. package/src/sveltekit/helpers.ts +69 -0
  455. package/src/sveltekit/index.ts +74 -0
  456. package/src/sveltekit/protect.ts +80 -0
  457. package/src/sveltekit/sveltekit-types.test.ts +31 -0
  458. package/src/sveltekit/sveltekit.test.ts +799 -0
  459. package/src/sveltekit/types.ts +134 -0
  460. package/src/sveltekit/validated.test.ts +117 -0
  461. package/src/sveltekit/validated.ts +78 -0
  462. package/src/testing/adapter-conformance.test.ts +408 -0
  463. package/src/testing/checks.test.ts +124 -0
  464. package/src/testing/checks.ts +304 -0
  465. package/src/testing/index.ts +107 -0
@@ -0,0 +1,1442 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/drizzle/index.ts
21
+ var drizzle_exports = {};
22
+ __export(drizzle_exports, {
23
+ createDrizzleAdapter: () => createDrizzleAdapter,
24
+ findSqlstate: () => findSqlstate,
25
+ fortressPgSchema: () => fortressPgSchema,
26
+ fortressSchema: () => fortressSchema,
27
+ rethrowDbError: () => rethrowDbError
28
+ });
29
+ module.exports = __toCommonJS(drizzle_exports);
30
+
31
+ // src/drizzle/adapter.ts
32
+ var import_node_async_hooks = require("async_hooks");
33
+ var import_drizzle_orm3 = require("drizzle-orm");
34
+
35
+ // src/core/errors.ts
36
+ var FortressError = class extends Error {
37
+ code;
38
+ statusCode;
39
+ retryAfter;
40
+ details;
41
+ /** RFC 6749 §5.2 / §4.1.2.1 machine code. Set by `Errors.oauth()`. */
42
+ oauthError;
43
+ /** Human-readable description for the OAuth `error_description` field. */
44
+ oauthDescription;
45
+ /** Optional URI for the OAuth `error_uri` field (§5.2). */
46
+ oauthErrorUri;
47
+ constructor(code, message, statusCode, options) {
48
+ super(message, { cause: options?.cause });
49
+ this.code = code;
50
+ this.statusCode = statusCode;
51
+ this.retryAfter = options?.retryAfter;
52
+ this.details = options?.details;
53
+ this.oauthError = options?.oauthError;
54
+ this.oauthDescription = options?.oauthDescription;
55
+ this.oauthErrorUri = options?.oauthErrorUri;
56
+ }
57
+ toJSON() {
58
+ return {
59
+ code: this.code,
60
+ message: this.message,
61
+ statusCode: this.statusCode,
62
+ ...this.details !== void 0 && { details: this.details }
63
+ };
64
+ }
65
+ };
66
+ var Errors = {
67
+ unauthorized: (message = "Unauthorized") => new FortressError("UNAUTHORIZED", message, 401),
68
+ tokenReuse: () => new FortressError("TOKEN_REUSE", "Token reuse detected", 401),
69
+ sessionIdleTimeout: () => new FortressError("SESSION_IDLE_TIMEOUT", "Session idle timeout exceeded", 401),
70
+ sessionAbsoluteTimeout: () => new FortressError("SESSION_ABSOLUTE_TIMEOUT", "Session absolute timeout exceeded", 401),
71
+ forbidden: (message = "Forbidden") => new FortressError("FORBIDDEN", message, 403),
72
+ badRequest: (message = "Bad request") => new FortressError("BAD_REQUEST", message, 400),
73
+ notFound: (message = "Not found") => new FortressError("NOT_FOUND", message, 404),
74
+ conflict: (message = "Conflict", options) => new FortressError("CONFLICT", message, 409, options),
75
+ unprocessable: (message = "Unprocessable entity", options) => new FortressError("UNPROCESSABLE_ENTITY", message, 422, options),
76
+ rateLimited: (retryAfter) => new FortressError("RATE_LIMITED", "Too many requests", 429, { retryAfter }),
77
+ database: (message = "Database error", cause) => new FortressError("DATABASE_ERROR", message, 500, { cause }),
78
+ serviceUnavailable: (message = "Service unavailable", options) => new FortressError("SERVICE_UNAVAILABLE", message, 503, options),
79
+ validationError: (issues) => new FortressError("VALIDATION_ERROR", "Validation failed", 422, { details: issues }),
80
+ /**
81
+ * RFC 6749 §5.2 / §4.1.2.1 OAuth error.
82
+ *
83
+ * The HTTP error mapper detects `oauthError` and emits the OAuth-spec
84
+ * JSON body `{ error, error_description, error_uri? }` instead of the
85
+ * default fortress `{ code, message }` shape, so strict OAuth clients
86
+ * (Moodle, openid-client, Spring Security, etc.) can switch behaviour
87
+ * on the machine-readable `error` field.
88
+ *
89
+ * Status is inferred from the OAuth code per the spec table:
90
+ * - `invalid_client` → 401
91
+ * - everything else → 400
92
+ */
93
+ oauth: (error, description, options) => {
94
+ const status = options?.status ?? (error === "invalid_client" ? 401 : 400);
95
+ const code = status === 401 ? "UNAUTHORIZED" : "BAD_REQUEST";
96
+ return new FortressError(code, description ?? error, status, {
97
+ oauthError: error,
98
+ oauthDescription: description,
99
+ oauthErrorUri: options?.errorUri,
100
+ cause: options?.cause
101
+ });
102
+ },
103
+ /**
104
+ * Reconstruct a {@link FortressError} from a JSON error body emitted by
105
+ * `errorToResponse`. Used by the in-process `fortress.call.*` client to
106
+ * convert non-2xx responses into typed throws that mirror what a direct
107
+ * service-method call would produce.
108
+ *
109
+ * Maps by HTTP status when the body doesn't carry a recognizable
110
+ * `{ code, message }` payload, so network errors and opaque upstream
111
+ * failures still become structured `FortressError`s.
112
+ */
113
+ fromHttpResponse: (status, body) => {
114
+ const payload = body && typeof body === "object" ? body : {};
115
+ const message = typeof payload.message === "string" ? payload.message : `HTTP ${status}`;
116
+ const code = typeof payload.code === "string" && isFortressErrorCode(payload.code) ? payload.code : statusToErrorCode(status);
117
+ return new FortressError(code, message, status, { details: payload.details });
118
+ }
119
+ };
120
+ function isFortressErrorCode(code) {
121
+ return code === "UNAUTHORIZED" || code === "TOKEN_REUSE" || code === "SESSION_IDLE_TIMEOUT" || code === "SESSION_ABSOLUTE_TIMEOUT" || code === "FORBIDDEN" || code === "BAD_REQUEST" || code === "NOT_FOUND" || code === "CONFLICT" || code === "UNPROCESSABLE_ENTITY" || code === "RATE_LIMITED" || code === "DATABASE_ERROR" || code === "VALIDATION_ERROR" || code === "SERVICE_UNAVAILABLE";
122
+ }
123
+ function statusToErrorCode(status) {
124
+ if (status === 401)
125
+ return "UNAUTHORIZED";
126
+ if (status === 403)
127
+ return "FORBIDDEN";
128
+ if (status === 404)
129
+ return "NOT_FOUND";
130
+ if (status === 409)
131
+ return "CONFLICT";
132
+ if (status === 422)
133
+ return "UNPROCESSABLE_ENTITY";
134
+ if (status === 429)
135
+ return "RATE_LIMITED";
136
+ if (status === 503)
137
+ return "SERVICE_UNAVAILABLE";
138
+ if (status >= 500)
139
+ return "DATABASE_ERROR";
140
+ return "BAD_REQUEST";
141
+ }
142
+
143
+ // src/drizzle/pg-error-map.ts
144
+ var MAX_CAUSE_DEPTH = 6;
145
+ var SQLSTATE_PATTERN = /^[0-9A-Z]{5}$/;
146
+ var PG_SQLSTATE_MAP = {
147
+ "23505": (cause) => Errors.conflict("Resource already exists", { cause }),
148
+ "23503": (cause) => Errors.unprocessable("Referenced resource does not exist", { cause }),
149
+ "23502": (_cause) => Errors.badRequest("Required field is missing"),
150
+ "23514": (cause) => Errors.unprocessable("Constraint check failed", { cause }),
151
+ "40001": (cause) => Errors.conflict("Serialization failure, retry the request", { cause }),
152
+ "40P01": (cause) => Errors.conflict("Deadlock detected, retry the request", { cause }),
153
+ "57014": (cause) => Errors.serviceUnavailable("Query canceled", { cause })
154
+ };
155
+ var SQLITE_CONSTRAINT_MAP = [
156
+ {
157
+ match: /SQLITE_CONSTRAINT_(?:UNIQUE|PRIMARYKEY)|UNIQUE constraint failed/i,
158
+ factory: (cause) => Errors.conflict("Resource already exists", { cause })
159
+ },
160
+ {
161
+ match: /SQLITE_CONSTRAINT_FOREIGNKEY|FOREIGN KEY constraint failed/i,
162
+ factory: (cause) => Errors.unprocessable("Referenced resource does not exist", { cause })
163
+ },
164
+ {
165
+ match: /SQLITE_CONSTRAINT_NOTNULL|NOT NULL constraint failed/i,
166
+ factory: (_cause) => Errors.badRequest("Required field is missing")
167
+ }
168
+ ];
169
+ function mapSqliteConstraint(err) {
170
+ let current = err;
171
+ for (let i = 0; i < MAX_CAUSE_DEPTH; i++) {
172
+ if (current === null || typeof current !== "object")
173
+ return null;
174
+ const coded = current;
175
+ const code = typeof coded.code === "string" ? coded.code : "";
176
+ const message = typeof coded.message === "string" ? coded.message : "";
177
+ const haystack = `${code} ${message}`;
178
+ for (const { match, factory } of SQLITE_CONSTRAINT_MAP) {
179
+ if (match.test(haystack))
180
+ return factory(err);
181
+ }
182
+ current = coded.cause;
183
+ }
184
+ return null;
185
+ }
186
+ function findSqlstate(err) {
187
+ let current = err;
188
+ for (let i = 0; i < MAX_CAUSE_DEPTH; i++) {
189
+ if (current === null || typeof current !== "object")
190
+ return null;
191
+ const candidate = current.code;
192
+ if (typeof candidate === "string" && SQLSTATE_PATTERN.test(candidate))
193
+ return candidate;
194
+ current = current.cause;
195
+ }
196
+ return null;
197
+ }
198
+ function rethrowDbError(err, dialect) {
199
+ if (dialect === "pg") {
200
+ const sqlstate = findSqlstate(err);
201
+ const factory = sqlstate ? PG_SQLSTATE_MAP[sqlstate] : void 0;
202
+ if (factory)
203
+ throw factory(err);
204
+ throw err;
205
+ }
206
+ if (dialect === "sqlite") {
207
+ const mapped = mapSqliteConstraint(err);
208
+ if (mapped)
209
+ throw mapped;
210
+ throw err;
211
+ }
212
+ throw err;
213
+ }
214
+
215
+ // src/drizzle/pg/schema.ts
216
+ var import_drizzle_orm = require("drizzle-orm");
217
+ var import_pg_core = require("drizzle-orm/pg-core");
218
+ var schemaVersion = (0, import_pg_core.pgTable)("fortress_schema_version", {
219
+ id: (0, import_pg_core.integer)("id").primaryKey().default(1),
220
+ version: (0, import_pg_core.integer)("version").notNull(),
221
+ appliedAt: (0, import_pg_core.timestamp)("applied_at", { withTimezone: true }).notNull().defaultNow()
222
+ });
223
+ var users = (0, import_pg_core.pgTable)("fortress_user", {
224
+ id: (0, import_pg_core.serial)("id").primaryKey(),
225
+ email: (0, import_pg_core.varchar)("email", { length: 255 }).notNull().unique(),
226
+ name: (0, import_pg_core.varchar)("name", { length: 255 }).notNull(),
227
+ passwordHash: (0, import_pg_core.text)("password_hash"),
228
+ isActive: (0, import_pg_core.boolean)("is_active").notNull().default(true),
229
+ emailVerified: (0, import_pg_core.boolean)("email_verified").notNull().default(false),
230
+ createdAt: (0, import_pg_core.timestamp)("created_at", { withTimezone: true }).notNull().defaultNow(),
231
+ updatedAt: (0, import_pg_core.timestamp)("updated_at", { withTimezone: true }).notNull().defaultNow()
232
+ }, (table) => [
233
+ (0, import_pg_core.uniqueIndex)("user_email_ci_unique").on(import_drizzle_orm.sql`lower(${table.email})`)
234
+ ]);
235
+ var loginIdentifiers = (0, import_pg_core.pgTable)("fortress_login_identifier", {
236
+ id: (0, import_pg_core.serial)("id").primaryKey(),
237
+ userId: (0, import_pg_core.integer)("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
238
+ type: (0, import_pg_core.varchar)("type", { length: 20 }).notNull(),
239
+ // 'email' | 'phone' | 'username'
240
+ value: (0, import_pg_core.varchar)("value", { length: 255 }).notNull().unique()
241
+ }, (table) => [
242
+ (0, import_pg_core.uniqueIndex)("login_identifier_email_ci_unique").on(import_drizzle_orm.sql`lower(${table.value})`).where(import_drizzle_orm.sql`${table.type} = 'email'`)
243
+ ]);
244
+ var refreshTokens = (0, import_pg_core.pgTable)("fortress_refresh_token", {
245
+ id: (0, import_pg_core.bigserial)("id", { mode: "number" }).primaryKey(),
246
+ userId: (0, import_pg_core.integer)("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
247
+ tokenHash: (0, import_pg_core.varchar)("token_hash", { length: 64 }).notNull().unique(),
248
+ tokenFamily: (0, import_pg_core.varchar)("token_family", { length: 64 }).notNull(),
249
+ familyCreatedAt: (0, import_pg_core.timestamp)("family_created_at", { withTimezone: true }).notNull().defaultNow(),
250
+ successorTokenHash: (0, import_pg_core.varchar)("successor_token_hash", { length: 64 }),
251
+ rotatedAt: (0, import_pg_core.timestamp)("rotated_at", { withTimezone: true }),
252
+ isRevoked: (0, import_pg_core.boolean)("is_revoked").notNull().default(false),
253
+ expiresAt: (0, import_pg_core.timestamp)("expires_at", { withTimezone: true }).notNull(),
254
+ ipAddress: (0, import_pg_core.varchar)("ip_address", { length: 45 }),
255
+ userAgent: (0, import_pg_core.text)("user_agent"),
256
+ deviceName: (0, import_pg_core.text)("device_name"),
257
+ lastActiveAt: (0, import_pg_core.timestamp)("last_active_at", { withTimezone: true }),
258
+ fingerprintHash: (0, import_pg_core.varchar)("fingerprint_hash", { length: 64 }),
259
+ createdAt: (0, import_pg_core.timestamp)("created_at", { withTimezone: true }).notNull().defaultNow()
260
+ }, (table) => [
261
+ (0, import_pg_core.index)("refresh_token_family_idx").on(table.tokenFamily),
262
+ (0, import_pg_core.index)("refresh_token_user_idx").on(table.userId)
263
+ ]);
264
+ var authContinuations = (0, import_pg_core.pgTable)("fortress_auth_continuation", {
265
+ id: (0, import_pg_core.bigserial)("id", { mode: "number" }).primaryKey(),
266
+ userId: (0, import_pg_core.integer)("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
267
+ tokenHash: (0, import_pg_core.varchar)("token_hash", { length: 64 }).notNull().unique(),
268
+ reason: (0, import_pg_core.varchar)("reason", { length: 32 }).notNull(),
269
+ expiresAt: (0, import_pg_core.timestamp)("expires_at", { withTimezone: true }).notNull(),
270
+ consumedAt: (0, import_pg_core.timestamp)("consumed_at", { withTimezone: true }),
271
+ failedAttempts: (0, import_pg_core.integer)("failed_attempts").notNull().default(0),
272
+ lastFailedAt: (0, import_pg_core.timestamp)("last_failed_at", { withTimezone: true }),
273
+ invalidatedAt: (0, import_pg_core.timestamp)("invalidated_at", { withTimezone: true }),
274
+ maxAttempts: (0, import_pg_core.integer)("max_attempts").notNull().default(5),
275
+ cooldownSeconds: (0, import_pg_core.integer)("cooldown_seconds").notNull().default(1),
276
+ createdAt: (0, import_pg_core.timestamp)("created_at", { withTimezone: true }).notNull().defaultNow()
277
+ }, (table) => [
278
+ (0, import_pg_core.index)("auth_continuation_failure_idx").on(table.userId, table.reason, table.lastFailedAt)
279
+ ]);
280
+ var groups = (0, import_pg_core.pgTable)("fortress_group", {
281
+ id: (0, import_pg_core.serial)("id").primaryKey(),
282
+ name: (0, import_pg_core.varchar)("name", { length: 100 }).notNull().unique(),
283
+ description: (0, import_pg_core.text)("description")
284
+ });
285
+ var groupUsers = (0, import_pg_core.pgTable)(
286
+ "fortress_group_user",
287
+ {
288
+ groupId: (0, import_pg_core.integer)("group_id").notNull().references(() => groups.id, { onDelete: "cascade" }),
289
+ userId: (0, import_pg_core.integer)("user_id").notNull().references(() => users.id, { onDelete: "cascade" })
290
+ },
291
+ (table) => [(0, import_pg_core.primaryKey)({ columns: [table.groupId, table.userId] })]
292
+ );
293
+ var serviceAccounts = (0, import_pg_core.pgTable)("fortress_service_account", {
294
+ id: (0, import_pg_core.serial)("id").primaryKey(),
295
+ name: (0, import_pg_core.varchar)("name", { length: 100 }).notNull().unique(),
296
+ displayName: (0, import_pg_core.varchar)("display_name", { length: 255 }),
297
+ description: (0, import_pg_core.text)("description"),
298
+ isActive: (0, import_pg_core.boolean)("is_active").notNull().default(true),
299
+ createdAt: (0, import_pg_core.timestamp)("created_at", { withTimezone: true }).notNull().defaultNow(),
300
+ updatedAt: (0, import_pg_core.timestamp)("updated_at", { withTimezone: true }).notNull().defaultNow()
301
+ });
302
+ var resources = (0, import_pg_core.pgTable)("fortress_resource", {
303
+ name: (0, import_pg_core.varchar)("name", { length: 100 }).primaryKey(),
304
+ description: (0, import_pg_core.text)("description")
305
+ });
306
+ var permissions = (0, import_pg_core.pgTable)("fortress_permission", {
307
+ id: (0, import_pg_core.serial)("id").primaryKey(),
308
+ resource: (0, import_pg_core.varchar)("resource", { length: 100 }).notNull().references(() => resources.name, { onDelete: "cascade" }),
309
+ action: (0, import_pg_core.varchar)("action", { length: 100 }).notNull(),
310
+ effect: (0, import_pg_core.varchar)("effect", { length: 10 }).notNull().default("ALLOW"),
311
+ // 'ALLOW' | 'DENY'
312
+ conditions: (0, import_pg_core.jsonb)("conditions"),
313
+ // PermissionCondition[] as JSONB
314
+ description: (0, import_pg_core.text)("description")
315
+ }, (table) => [
316
+ // M8 fix — same split-index pattern as role/direct-permission bindings
317
+ // so concurrent findOrCreatePermission can't insert duplicate rows when
318
+ // conditions is NULL (a plain UNIQUE treats NULLs as distinct).
319
+ (0, import_pg_core.uniqueIndex)("uniq_permission_no_conditions").on(table.resource, table.action, table.effect).where(import_drizzle_orm.sql`${table.conditions} is null`),
320
+ (0, import_pg_core.uniqueIndex)("uniq_permission_with_conditions").on(table.resource, table.action, table.effect, table.conditions).where(import_drizzle_orm.sql`${table.conditions} is not null`)
321
+ ]);
322
+ var roles = (0, import_pg_core.pgTable)("fortress_role", {
323
+ id: (0, import_pg_core.serial)("id").primaryKey(),
324
+ name: (0, import_pg_core.varchar)("name", { length: 100 }).notNull().unique(),
325
+ description: (0, import_pg_core.text)("description"),
326
+ isSystem: (0, import_pg_core.boolean)("is_system").notNull().default(false)
327
+ });
328
+ var rolePermissions = (0, import_pg_core.pgTable)(
329
+ "fortress_role_permission",
330
+ {
331
+ roleId: (0, import_pg_core.integer)("role_id").notNull().references(() => roles.id, { onDelete: "cascade" }),
332
+ permissionId: (0, import_pg_core.integer)("permission_id").notNull().references(() => permissions.id, { onDelete: "cascade" })
333
+ },
334
+ (table) => [(0, import_pg_core.primaryKey)({ columns: [table.roleId, table.permissionId] })]
335
+ );
336
+ var roleBindings = (0, import_pg_core.pgTable)("fortress_role_binding", {
337
+ id: (0, import_pg_core.serial)("id").primaryKey(),
338
+ roleId: (0, import_pg_core.integer)("role_id").notNull().references(() => roles.id, { onDelete: "cascade" }),
339
+ subjectType: (0, import_pg_core.varchar)("subject_type", { length: 20 }).notNull(),
340
+ // 'USER' | 'GROUP' | 'SERVICE_ACCOUNT'
341
+ subjectId: (0, import_pg_core.integer)("subject_id").notNull(),
342
+ tenantId: (0, import_pg_core.varchar)("tenant_id", { length: 100 })
343
+ }, (table) => [
344
+ (0, import_pg_core.unique)().on(table.roleId, table.subjectType, table.subjectId, table.tenantId),
345
+ (0, import_pg_core.uniqueIndex)("uniq_role_binding_global").on(table.roleId, table.subjectType, table.subjectId).where(import_drizzle_orm.sql`${table.tenantId} is null`),
346
+ (0, import_pg_core.uniqueIndex)("uniq_role_binding_tenant").on(table.roleId, table.subjectType, table.subjectId, table.tenantId).where(import_drizzle_orm.sql`${table.tenantId} is not null`),
347
+ (0, import_pg_core.index)("role_binding_subject_idx").on(table.subjectType, table.subjectId)
348
+ ]);
349
+ var directPermissionBindings = (0, import_pg_core.pgTable)("fortress_direct_permission_binding", {
350
+ id: (0, import_pg_core.serial)("id").primaryKey(),
351
+ permissionId: (0, import_pg_core.integer)("permission_id").notNull().references(() => permissions.id, { onDelete: "cascade" }),
352
+ subjectType: (0, import_pg_core.varchar)("subject_type", { length: 20 }).notNull(),
353
+ // 'USER' | 'GROUP' | 'SERVICE_ACCOUNT'
354
+ subjectId: (0, import_pg_core.integer)("subject_id").notNull(),
355
+ tenantId: (0, import_pg_core.varchar)("tenant_id", { length: 100 })
356
+ }, (table) => [
357
+ (0, import_pg_core.unique)().on(table.permissionId, table.subjectType, table.subjectId, table.tenantId),
358
+ (0, import_pg_core.uniqueIndex)("uniq_direct_permission_binding_global").on(table.permissionId, table.subjectType, table.subjectId).where(import_drizzle_orm.sql`${table.tenantId} is null`),
359
+ (0, import_pg_core.uniqueIndex)("uniq_direct_permission_binding_tenant").on(table.permissionId, table.subjectType, table.subjectId, table.tenantId).where(import_drizzle_orm.sql`${table.tenantId} is not null`),
360
+ (0, import_pg_core.index)("direct_permission_binding_subject_idx").on(table.subjectType, table.subjectId)
361
+ ]);
362
+ var emailVerificationTokens = (0, import_pg_core.pgTable)("fortress_email_verification_token", {
363
+ id: (0, import_pg_core.bigserial)("id", { mode: "number" }).primaryKey(),
364
+ userId: (0, import_pg_core.integer)("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
365
+ token: (0, import_pg_core.text)("token").notNull(),
366
+ email: (0, import_pg_core.varchar)("email", { length: 255 }).notNull(),
367
+ expiresAt: (0, import_pg_core.timestamp)("expires_at", { withTimezone: true }).notNull(),
368
+ usedAt: (0, import_pg_core.timestamp)("used_at", { withTimezone: true }),
369
+ createdAt: (0, import_pg_core.timestamp)("created_at", { withTimezone: true }).notNull().defaultNow()
370
+ }, (table) => [(0, import_pg_core.index)("email_verification_token_token_idx").on(table.token)]);
371
+ var magicLinkTokens = (0, import_pg_core.pgTable)("fortress_magic_link_token", {
372
+ id: (0, import_pg_core.bigserial)("id", { mode: "number" }).primaryKey(),
373
+ email: (0, import_pg_core.varchar)("email", { length: 255 }).notNull(),
374
+ token: (0, import_pg_core.varchar)("token", { length: 64 }).notNull(),
375
+ expiresAt: (0, import_pg_core.timestamp)("expires_at", { withTimezone: true }).notNull(),
376
+ usedAt: (0, import_pg_core.timestamp)("used_at", { withTimezone: true }),
377
+ createdAt: (0, import_pg_core.timestamp)("created_at", { withTimezone: true }).notNull().defaultNow()
378
+ }, (table) => [(0, import_pg_core.index)("magic_link_token_token_idx").on(table.token)]);
379
+ var apiKeys = (0, import_pg_core.pgTable)("fortress_api_key", {
380
+ id: (0, import_pg_core.serial)("id").primaryKey(),
381
+ subjectType: (0, import_pg_core.varchar)("subject_type", { length: 20 }).notNull(),
382
+ // 'USER' | 'SERVICE_ACCOUNT' — polymorphic owner
383
+ subjectId: (0, import_pg_core.integer)("subject_id").notNull(),
384
+ name: (0, import_pg_core.varchar)("name", { length: 255 }).notNull(),
385
+ keyHash: (0, import_pg_core.varchar)("key_hash", { length: 64 }).notNull().unique(),
386
+ keyPrefix: (0, import_pg_core.varchar)("key_prefix", { length: 20 }).notNull(),
387
+ scopes: (0, import_pg_core.text)("scopes"),
388
+ // JSON array of "resource:action" strings
389
+ expiresAt: (0, import_pg_core.timestamp)("expires_at", { withTimezone: true }),
390
+ lastUsedAt: (0, import_pg_core.timestamp)("last_used_at", { withTimezone: true }),
391
+ isRevoked: (0, import_pg_core.boolean)("is_revoked").notNull().default(false),
392
+ createdAt: (0, import_pg_core.timestamp)("created_at", { withTimezone: true }).notNull().defaultNow()
393
+ }, (table) => [(0, import_pg_core.index)("api_key_subject_idx").on(table.subjectType, table.subjectId)]);
394
+ var twoFactorSecrets = (0, import_pg_core.pgTable)("fortress_two_factor_secret", {
395
+ id: (0, import_pg_core.serial)("id").primaryKey(),
396
+ userId: (0, import_pg_core.integer)("user_id").notNull().unique().references(() => users.id, { onDelete: "cascade" }),
397
+ secret: (0, import_pg_core.text)("secret").notNull(),
398
+ // Versioned AES-GCM envelope containing the TOTP seed
399
+ isEnabled: (0, import_pg_core.boolean)("is_enabled").notNull().default(false),
400
+ lastUsedCounter: (0, import_pg_core.integer)("last_used_counter"),
401
+ createdAt: (0, import_pg_core.timestamp)("created_at", { withTimezone: true }).notNull().defaultNow()
402
+ });
403
+ var backupCodes = (0, import_pg_core.pgTable)("fortress_backup_code", {
404
+ id: (0, import_pg_core.serial)("id").primaryKey(),
405
+ userId: (0, import_pg_core.integer)("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
406
+ codeHash: (0, import_pg_core.text)("code_hash").notNull(),
407
+ isUsed: (0, import_pg_core.boolean)("is_used").notNull().default(false),
408
+ createdAt: (0, import_pg_core.timestamp)("created_at", { withTimezone: true }).notNull().defaultNow()
409
+ }, (table) => [(0, import_pg_core.index)("backup_code_user_idx").on(table.userId)]);
410
+ var trustedDevices = (0, import_pg_core.pgTable)("fortress_trusted_device", {
411
+ id: (0, import_pg_core.serial)("id").primaryKey(),
412
+ userId: (0, import_pg_core.integer)("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
413
+ /** SHA-256 hash of the server-issued trusted-device secret (never raw token). */
414
+ deviceHash: (0, import_pg_core.varchar)("device_hash", { length: 64 }).notNull(),
415
+ expiresAt: (0, import_pg_core.timestamp)("expires_at", { withTimezone: true }).notNull(),
416
+ lastUsedAt: (0, import_pg_core.timestamp)("last_used_at", { withTimezone: true }).notNull(),
417
+ createdAt: (0, import_pg_core.timestamp)("created_at", { withTimezone: true }).notNull().defaultNow()
418
+ }, (table) => [(0, import_pg_core.index)("trusted_device_user_idx").on(table.userId)]);
419
+ var socialAccounts = (0, import_pg_core.pgTable)("fortress_social_account", {
420
+ id: (0, import_pg_core.serial)("id").primaryKey(),
421
+ userId: (0, import_pg_core.integer)("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
422
+ provider: (0, import_pg_core.varchar)("provider", { length: 50 }).notNull(),
423
+ providerAccountId: (0, import_pg_core.varchar)("provider_account_id", { length: 255 }).notNull(),
424
+ email: (0, import_pg_core.varchar)("email", { length: 255 }),
425
+ accessToken: (0, import_pg_core.text)("access_token"),
426
+ // Encrypted
427
+ refreshToken: (0, import_pg_core.text)("refresh_token"),
428
+ // Encrypted
429
+ tokenExpiresAt: (0, import_pg_core.timestamp)("token_expires_at", { withTimezone: true }),
430
+ profile: (0, import_pg_core.jsonb)("profile"),
431
+ // JSON
432
+ createdAt: (0, import_pg_core.timestamp)("created_at", { withTimezone: true }).notNull().defaultNow(),
433
+ updatedAt: (0, import_pg_core.timestamp)("updated_at", { withTimezone: true }).notNull().defaultNow()
434
+ }, (table) => [
435
+ (0, import_pg_core.unique)().on(table.userId, table.provider),
436
+ (0, import_pg_core.unique)().on(table.provider, table.providerAccountId)
437
+ ]);
438
+ var tenants = (0, import_pg_core.pgTable)("fortress_tenant", {
439
+ id: (0, import_pg_core.serial)("id").primaryKey(),
440
+ name: (0, import_pg_core.varchar)("name", { length: 255 }).notNull(),
441
+ taxId: (0, import_pg_core.varchar)("tax_id", { length: 100 }).notNull().unique(),
442
+ description: (0, import_pg_core.text)("description"),
443
+ createdAt: (0, import_pg_core.timestamp)("created_at", { withTimezone: true }).notNull().defaultNow(),
444
+ updatedAt: (0, import_pg_core.timestamp)("updated_at", { withTimezone: true }).notNull().defaultNow()
445
+ });
446
+ var tenantUsers = (0, import_pg_core.pgTable)(
447
+ "fortress_tenant_user",
448
+ {
449
+ tenantId: (0, import_pg_core.integer)("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }),
450
+ userId: (0, import_pg_core.integer)("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
451
+ isDefault: (0, import_pg_core.boolean)("is_default").notNull().default(false)
452
+ },
453
+ (table) => [
454
+ (0, import_pg_core.primaryKey)({ columns: [table.tenantId, table.userId] }),
455
+ (0, import_pg_core.uniqueIndex)("fortress_tenant_user_one_default_idx").on(table.userId).where(import_drizzle_orm.sql`${table.isDefault} = true`)
456
+ ]
457
+ );
458
+ var oauthClients = (0, import_pg_core.pgTable)("fortress_oauth_client", {
459
+ id: (0, import_pg_core.serial)("id").primaryKey(),
460
+ clientId: (0, import_pg_core.varchar)("client_id", { length: 255 }).notNull().unique(),
461
+ clientSecretHash: (0, import_pg_core.text)("client_secret_hash").notNull(),
462
+ name: (0, import_pg_core.varchar)("name", { length: 255 }).notNull(),
463
+ redirectUris: (0, import_pg_core.text)("redirect_uris").notNull(),
464
+ // JSON array
465
+ grantTypes: (0, import_pg_core.text)("grant_types").notNull(),
466
+ // JSON array
467
+ // RFC 6749 §3.3 / RFC 9700 §2.2.1 per-client scope allow-list (JSON array,
468
+ // nullable for legacy v0 clients).
469
+ allowedScopes: (0, import_pg_core.text)("allowed_scopes"),
470
+ // RFC 6749 §2.1 client authentication method ('client_secret_basic' |
471
+ // 'client_secret_post' | 'none' for RFC 8252 public clients).
472
+ tokenEndpointAuthMethod: (0, import_pg_core.text)("token_endpoint_auth_method"),
473
+ createdAt: (0, import_pg_core.timestamp)("created_at", { withTimezone: true }).notNull().defaultNow()
474
+ });
475
+ var oauthAuthorizationCodes = (0, import_pg_core.pgTable)("fortress_oauth_authorization_code", {
476
+ id: (0, import_pg_core.bigserial)("id", { mode: "number" }).primaryKey(),
477
+ code: (0, import_pg_core.varchar)("code", { length: 255 }).notNull().unique(),
478
+ clientId: (0, import_pg_core.varchar)("client_id", { length: 255 }).notNull(),
479
+ userId: (0, import_pg_core.integer)("user_id").notNull(),
480
+ redirectUri: (0, import_pg_core.text)("redirect_uri").notNull(),
481
+ scope: (0, import_pg_core.text)("scope"),
482
+ codeChallenge: (0, import_pg_core.text)("code_challenge"),
483
+ codeChallengeMethod: (0, import_pg_core.varchar)("code_challenge_method", { length: 10 }),
484
+ // OIDC Core §3.1.2.1 / §2 — echoed into the id_token if present.
485
+ nonce: (0, import_pg_core.text)("nonce"),
486
+ authTime: (0, import_pg_core.integer)("auth_time"),
487
+ expiresAt: (0, import_pg_core.timestamp)("expires_at", { withTimezone: true }).notNull(),
488
+ usedAt: (0, import_pg_core.timestamp)("used_at", { withTimezone: true }),
489
+ createdAt: (0, import_pg_core.timestamp)("created_at", { withTimezone: true }).notNull().defaultNow()
490
+ });
491
+ var oauthAccessTokens = (0, import_pg_core.pgTable)("fortress_oauth_access_token", {
492
+ id: (0, import_pg_core.bigserial)("id", { mode: "number" }).primaryKey(),
493
+ token: (0, import_pg_core.varchar)("token", { length: 255 }).notNull().unique(),
494
+ clientId: (0, import_pg_core.varchar)("client_id", { length: 255 }).notNull(),
495
+ userId: (0, import_pg_core.integer)("user_id"),
496
+ scope: (0, import_pg_core.text)("scope"),
497
+ expiresAt: (0, import_pg_core.timestamp)("expires_at", { withTimezone: true }).notNull(),
498
+ createdAt: (0, import_pg_core.timestamp)("created_at", { withTimezone: true }).notNull().defaultNow()
499
+ });
500
+ var oauthRefreshTokens = (0, import_pg_core.pgTable)("fortress_oauth_refresh_token", {
501
+ id: (0, import_pg_core.bigserial)("id", { mode: "number" }).primaryKey(),
502
+ token: (0, import_pg_core.varchar)("token", { length: 255 }).notNull().unique(),
503
+ familyId: (0, import_pg_core.varchar)("family_id", { length: 64 }).notNull(),
504
+ clientId: (0, import_pg_core.varchar)("client_id", { length: 255 }).notNull(),
505
+ userId: (0, import_pg_core.integer)("user_id").notNull(),
506
+ scope: (0, import_pg_core.text)("scope"),
507
+ issuedAt: (0, import_pg_core.timestamp)("issued_at", { withTimezone: true }).notNull(),
508
+ expiresAt: (0, import_pg_core.timestamp)("expires_at", { withTimezone: true }).notNull(),
509
+ usedAt: (0, import_pg_core.timestamp)("used_at", { withTimezone: true }),
510
+ parentId: (0, import_pg_core.integer)("parent_id"),
511
+ createdAt: (0, import_pg_core.timestamp)("created_at", { withTimezone: true }).notNull().defaultNow()
512
+ });
513
+ var oauthPendingFlows = (0, import_pg_core.pgTable)("fortress_oauth_pending_flow", {
514
+ id: (0, import_pg_core.bigserial)("id", { mode: "number" }).primaryKey(),
515
+ flowId: (0, import_pg_core.text)("flow_id").notNull().unique(),
516
+ clientId: (0, import_pg_core.varchar)("client_id", { length: 255 }).notNull(),
517
+ redirectUri: (0, import_pg_core.text)("redirect_uri").notNull(),
518
+ scope: (0, import_pg_core.text)("scope"),
519
+ state: (0, import_pg_core.varchar)("state", { length: 255 }).notNull(),
520
+ codeChallenge: (0, import_pg_core.text)("code_challenge"),
521
+ codeChallengeMethod: (0, import_pg_core.varchar)("code_challenge_method", { length: 10 }),
522
+ nonce: (0, import_pg_core.text)("nonce"),
523
+ // H6 fix: subject the flow is bound to (TOFU-claimed on first
524
+ // authenticated touch).
525
+ userId: (0, import_pg_core.integer)("user_id"),
526
+ // Single-use approval/denial claim used by the OAuth consent API.
527
+ usedAt: (0, import_pg_core.timestamp)("used_at", { withTimezone: true }),
528
+ expiresAt: (0, import_pg_core.timestamp)("expires_at", { withTimezone: true }).notNull(),
529
+ createdAt: (0, import_pg_core.timestamp)("created_at", { withTimezone: true }).notNull().defaultNow()
530
+ });
531
+ var oauthSigningKeys = (0, import_pg_core.pgTable)("fortress_oauth_signing_key", {
532
+ id: (0, import_pg_core.serial)("id").primaryKey(),
533
+ kid: (0, import_pg_core.varchar)("kid", { length: 64 }).notNull().unique(),
534
+ alg: (0, import_pg_core.varchar)("alg", { length: 16 }).notNull(),
535
+ publicJwk: (0, import_pg_core.text)("public_jwk").notNull(),
536
+ privateJwk: (0, import_pg_core.text)("private_jwk").notNull(),
537
+ rotatedAt: (0, import_pg_core.timestamp)("rotated_at", { withTimezone: true }),
538
+ createdAt: (0, import_pg_core.timestamp)("created_at", { withTimezone: true }).notNull().defaultNow()
539
+ });
540
+ var userScopeAssignments = (0, import_pg_core.pgTable)("fortress_user_scope_assignment", {
541
+ id: (0, import_pg_core.serial)("id").primaryKey(),
542
+ userId: (0, import_pg_core.integer)("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
543
+ scopeName: (0, import_pg_core.varchar)("scope_name", { length: 100 }).notNull(),
544
+ scopeValue: (0, import_pg_core.varchar)("scope_value", { length: 255 }).notNull(),
545
+ createdAt: (0, import_pg_core.timestamp)("created_at", { withTimezone: true }).notNull().defaultNow()
546
+ });
547
+ var accountLockouts = (0, import_pg_core.pgTable)("fortress_account_lockout", {
548
+ id: (0, import_pg_core.serial)("id").primaryKey(),
549
+ identifier: (0, import_pg_core.varchar)("identifier", { length: 255 }).notNull().unique(),
550
+ failedAttempts: (0, import_pg_core.integer)("failed_attempts").notNull().default(0),
551
+ lastFailedAt: (0, import_pg_core.timestamp)("last_failed_at", { withTimezone: true }),
552
+ lockedUntil: (0, import_pg_core.timestamp)("locked_until", { withTimezone: true }),
553
+ lockoutCount: (0, import_pg_core.integer)("lockout_count").notNull().default(0),
554
+ createdAt: (0, import_pg_core.timestamp)("created_at", { withTimezone: true }).notNull().defaultNow()
555
+ });
556
+ var auditLogs = (0, import_pg_core.pgTable)("fortress_audit_log", {
557
+ id: (0, import_pg_core.bigserial)("id", { mode: "number" }).primaryKey(),
558
+ timestamp: (0, import_pg_core.timestamp)("timestamp", { withTimezone: true }).notNull().defaultNow(),
559
+ eventType: (0, import_pg_core.varchar)("event_type", { length: 100 }).notNull(),
560
+ actorId: (0, import_pg_core.integer)("actor_id"),
561
+ actorType: (0, import_pg_core.varchar)("actor_type", { length: 20 }).notNull().default("USER"),
562
+ targetId: (0, import_pg_core.integer)("target_id"),
563
+ targetType: (0, import_pg_core.varchar)("target_type", { length: 50 }),
564
+ ipAddress: (0, import_pg_core.varchar)("ip_address", { length: 45 }),
565
+ userAgent: (0, import_pg_core.text)("user_agent"),
566
+ outcome: (0, import_pg_core.varchar)("outcome", { length: 20 }).notNull().default("SUCCESS"),
567
+ metadata: (0, import_pg_core.jsonb)("metadata"),
568
+ previousHash: (0, import_pg_core.text)("previous_hash"),
569
+ createdAt: (0, import_pg_core.timestamp)("created_at", { withTimezone: true }).notNull().defaultNow()
570
+ }, (table) => [(0, import_pg_core.index)("audit_log_timestamp_idx").on(table.timestamp)]);
571
+ var auditChainState = (0, import_pg_core.pgTable)("fortress_audit_chain_state", {
572
+ id: (0, import_pg_core.integer)("id").primaryKey(),
573
+ lastHash: (0, import_pg_core.varchar)("last_hash", { length: 64 }),
574
+ entryCount: (0, import_pg_core.integer)("entry_count").notNull(),
575
+ updatedAt: (0, import_pg_core.timestamp)("updated_at", { withTimezone: true }).notNull().defaultNow()
576
+ });
577
+ var webhookEndpoints = (0, import_pg_core.pgTable)("fortress_webhook_endpoint", {
578
+ id: (0, import_pg_core.serial)("id").primaryKey(),
579
+ url: (0, import_pg_core.text)("url").notNull(),
580
+ events: (0, import_pg_core.text)("events").notNull(),
581
+ // JSON array
582
+ secret: (0, import_pg_core.text)("secret").notNull(),
583
+ isActive: (0, import_pg_core.boolean)("is_active").notNull().default(true),
584
+ deactivatedReason: (0, import_pg_core.text)("deactivated_reason"),
585
+ consecutiveFailures: (0, import_pg_core.integer)("consecutive_failures").notNull().default(0),
586
+ createdAt: (0, import_pg_core.timestamp)("created_at", { withTimezone: true }).notNull().defaultNow()
587
+ });
588
+ var webhookDeliveries = (0, import_pg_core.pgTable)("fortress_webhook_delivery", {
589
+ id: (0, import_pg_core.bigserial)("id", { mode: "number" }).primaryKey(),
590
+ endpointId: (0, import_pg_core.integer)("endpoint_id").notNull().references(() => webhookEndpoints.id, { onDelete: "cascade" }),
591
+ eventType: (0, import_pg_core.varchar)("event_type", { length: 100 }).notNull(),
592
+ payload: (0, import_pg_core.text)("payload").notNull(),
593
+ // JSON
594
+ status: (0, import_pg_core.varchar)("status", { length: 20 }).notNull().default("pending"),
595
+ // pending | success | failed
596
+ attempts: (0, import_pg_core.integer)("attempts").notNull().default(0),
597
+ idempotencyKey: (0, import_pg_core.text)("idempotency_key"),
598
+ lastAttemptAt: (0, import_pg_core.timestamp)("last_attempt_at", { withTimezone: true }),
599
+ nextRetryAt: (0, import_pg_core.timestamp)("next_retry_at", { withTimezone: true }),
600
+ responseStatus: (0, import_pg_core.integer)("response_status"),
601
+ responseBody: (0, import_pg_core.text)("response_body"),
602
+ errorKind: (0, import_pg_core.text)("error_kind"),
603
+ createdAt: (0, import_pg_core.timestamp)("created_at", { withTimezone: true }).notNull().defaultNow()
604
+ }, (table) => [
605
+ (0, import_pg_core.uniqueIndex)("uniq_webhook_delivery_idempotency").on(table.endpointId, table.idempotencyKey).where(import_drizzle_orm.sql`${table.idempotencyKey} is not null`),
606
+ (0, import_pg_core.index)("webhook_delivery_retry_idx").on(table.status, table.nextRetryAt)
607
+ ]);
608
+ var webauthnCredentials = (0, import_pg_core.pgTable)("fortress_webauthn_credential", {
609
+ id: (0, import_pg_core.serial)("id").primaryKey(),
610
+ userId: (0, import_pg_core.integer)("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
611
+ credentialId: (0, import_pg_core.text)("credential_id").notNull().unique(),
612
+ publicKey: (0, import_pg_core.text)("public_key").notNull(),
613
+ counter: (0, import_pg_core.integer)("counter").notNull().default(0),
614
+ deviceType: (0, import_pg_core.varchar)("device_type", { length: 20 }).notNull(),
615
+ backedUp: (0, import_pg_core.boolean)("backed_up").notNull().default(false),
616
+ transports: (0, import_pg_core.text)("transports"),
617
+ // JSON array
618
+ createdAt: (0, import_pg_core.timestamp)("created_at", { withTimezone: true }).notNull().defaultNow()
619
+ });
620
+ var webauthnChallenges = (0, import_pg_core.pgTable)("fortress_webauthn_challenge", {
621
+ id: (0, import_pg_core.bigserial)("id", { mode: "number" }).primaryKey(),
622
+ challenge: (0, import_pg_core.text)("challenge").notNull().unique(),
623
+ userId: (0, import_pg_core.integer)("user_id"),
624
+ expiresAt: (0, import_pg_core.timestamp)("expires_at", { withTimezone: true }).notNull(),
625
+ createdAt: (0, import_pg_core.timestamp)("created_at", { withTimezone: true }).notNull().defaultNow()
626
+ });
627
+ var fortressPgSchema = {
628
+ schemaVersion,
629
+ users,
630
+ loginIdentifiers,
631
+ refreshTokens,
632
+ authContinuations,
633
+ groups,
634
+ groupUsers,
635
+ serviceAccounts,
636
+ resources,
637
+ permissions,
638
+ roles,
639
+ rolePermissions,
640
+ roleBindings,
641
+ directPermissionBindings,
642
+ emailVerificationTokens,
643
+ magicLinkTokens,
644
+ apiKeys,
645
+ twoFactorSecrets,
646
+ backupCodes,
647
+ trustedDevices,
648
+ socialAccounts,
649
+ tenants,
650
+ tenantUsers,
651
+ oauthClients,
652
+ oauthAuthorizationCodes,
653
+ oauthAccessTokens,
654
+ oauthRefreshTokens,
655
+ oauthPendingFlows,
656
+ oauthSigningKeys,
657
+ userScopeAssignments,
658
+ accountLockouts,
659
+ auditLogs,
660
+ auditChainState,
661
+ webhookEndpoints,
662
+ webhookDeliveries,
663
+ webauthnCredentials,
664
+ webauthnChallenges
665
+ };
666
+
667
+ // src/drizzle/schema.ts
668
+ var import_drizzle_orm2 = require("drizzle-orm");
669
+ var import_sqlite_core = require("drizzle-orm/sqlite-core");
670
+ var schemaVersion2 = (0, import_sqlite_core.sqliteTable)("fortress_schema_version", {
671
+ id: (0, import_sqlite_core.integer)("id").primaryKey().default(1),
672
+ version: (0, import_sqlite_core.integer)("version").notNull(),
673
+ appliedAt: (0, import_sqlite_core.integer)("applied_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
674
+ });
675
+ var users2 = (0, import_sqlite_core.sqliteTable)("fortress_user", {
676
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
677
+ email: (0, import_sqlite_core.text)("email").notNull().unique(),
678
+ name: (0, import_sqlite_core.text)("name").notNull(),
679
+ passwordHash: (0, import_sqlite_core.text)("password_hash"),
680
+ isActive: (0, import_sqlite_core.integer)("is_active", { mode: "boolean" }).notNull().default(true),
681
+ emailVerified: (0, import_sqlite_core.integer)("email_verified", { mode: "boolean" }).notNull().default(false),
682
+ createdAt: (0, import_sqlite_core.integer)("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date()),
683
+ updatedAt: (0, import_sqlite_core.integer)("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
684
+ }, (table) => [
685
+ (0, import_sqlite_core.uniqueIndex)("user_email_ci_unique").on(import_drizzle_orm2.sql`${table.email} COLLATE NOCASE`)
686
+ ]);
687
+ var loginIdentifiers2 = (0, import_sqlite_core.sqliteTable)("fortress_login_identifier", {
688
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
689
+ userId: (0, import_sqlite_core.integer)("user_id").notNull().references(() => users2.id, { onDelete: "cascade" }),
690
+ type: (0, import_sqlite_core.text)("type").notNull(),
691
+ // 'email' | 'phone' | 'username'
692
+ value: (0, import_sqlite_core.text)("value").notNull().unique()
693
+ }, (table) => [
694
+ (0, import_sqlite_core.uniqueIndex)("login_identifier_email_ci_unique").on(import_drizzle_orm2.sql`${table.value} COLLATE NOCASE`).where(import_drizzle_orm2.sql`${table.type} = 'email'`)
695
+ ]);
696
+ var refreshTokens2 = (0, import_sqlite_core.sqliteTable)("fortress_refresh_token", {
697
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
698
+ userId: (0, import_sqlite_core.integer)("user_id").notNull().references(() => users2.id, { onDelete: "cascade" }),
699
+ tokenHash: (0, import_sqlite_core.text)("token_hash").notNull().unique(),
700
+ tokenFamily: (0, import_sqlite_core.text)("token_family").notNull(),
701
+ familyCreatedAt: (0, import_sqlite_core.integer)("family_created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date()),
702
+ successorTokenHash: (0, import_sqlite_core.text)("successor_token_hash"),
703
+ rotatedAt: (0, import_sqlite_core.integer)("rotated_at", { mode: "timestamp" }),
704
+ isRevoked: (0, import_sqlite_core.integer)("is_revoked", { mode: "boolean" }).notNull().default(false),
705
+ expiresAt: (0, import_sqlite_core.integer)("expires_at", { mode: "timestamp" }).notNull(),
706
+ ipAddress: (0, import_sqlite_core.text)("ip_address"),
707
+ userAgent: (0, import_sqlite_core.text)("user_agent"),
708
+ deviceName: (0, import_sqlite_core.text)("device_name"),
709
+ lastActiveAt: (0, import_sqlite_core.integer)("last_active_at", { mode: "timestamp" }),
710
+ fingerprintHash: (0, import_sqlite_core.text)("fingerprint_hash"),
711
+ createdAt: (0, import_sqlite_core.integer)("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
712
+ }, (table) => [
713
+ (0, import_sqlite_core.index)("refresh_token_family_idx").on(table.tokenFamily),
714
+ (0, import_sqlite_core.index)("refresh_token_user_idx").on(table.userId)
715
+ ]);
716
+ var authContinuations2 = (0, import_sqlite_core.sqliteTable)("fortress_auth_continuation", {
717
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
718
+ userId: (0, import_sqlite_core.integer)("user_id").notNull().references(() => users2.id, { onDelete: "cascade" }),
719
+ tokenHash: (0, import_sqlite_core.text)("token_hash").notNull().unique(),
720
+ reason: (0, import_sqlite_core.text)("reason").notNull(),
721
+ expiresAt: (0, import_sqlite_core.integer)("expires_at", { mode: "timestamp" }).notNull(),
722
+ consumedAt: (0, import_sqlite_core.integer)("consumed_at", { mode: "timestamp" }),
723
+ failedAttempts: (0, import_sqlite_core.integer)("failed_attempts").notNull().default(0),
724
+ lastFailedAt: (0, import_sqlite_core.integer)("last_failed_at", { mode: "timestamp" }),
725
+ invalidatedAt: (0, import_sqlite_core.integer)("invalidated_at", { mode: "timestamp" }),
726
+ maxAttempts: (0, import_sqlite_core.integer)("max_attempts").notNull().default(5),
727
+ cooldownSeconds: (0, import_sqlite_core.integer)("cooldown_seconds").notNull().default(1),
728
+ createdAt: (0, import_sqlite_core.integer)("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
729
+ }, (table) => [
730
+ (0, import_sqlite_core.index)("auth_continuation_failure_idx").on(table.userId, table.reason, table.lastFailedAt)
731
+ ]);
732
+ var groups2 = (0, import_sqlite_core.sqliteTable)("fortress_group", {
733
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
734
+ name: (0, import_sqlite_core.text)("name").notNull().unique(),
735
+ description: (0, import_sqlite_core.text)("description")
736
+ });
737
+ var groupUsers2 = (0, import_sqlite_core.sqliteTable)(
738
+ "fortress_group_user",
739
+ {
740
+ groupId: (0, import_sqlite_core.integer)("group_id").notNull().references(() => groups2.id, { onDelete: "cascade" }),
741
+ userId: (0, import_sqlite_core.integer)("user_id").notNull().references(() => users2.id, { onDelete: "cascade" })
742
+ },
743
+ (table) => [(0, import_sqlite_core.primaryKey)({ columns: [table.groupId, table.userId] })]
744
+ );
745
+ var serviceAccounts2 = (0, import_sqlite_core.sqliteTable)("fortress_service_account", {
746
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
747
+ name: (0, import_sqlite_core.text)("name").notNull().unique(),
748
+ displayName: (0, import_sqlite_core.text)("display_name"),
749
+ description: (0, import_sqlite_core.text)("description"),
750
+ isActive: (0, import_sqlite_core.integer)("is_active", { mode: "boolean" }).notNull().default(true),
751
+ createdAt: (0, import_sqlite_core.integer)("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date()),
752
+ updatedAt: (0, import_sqlite_core.integer)("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
753
+ });
754
+ var resources2 = (0, import_sqlite_core.sqliteTable)("fortress_resource", {
755
+ name: (0, import_sqlite_core.text)("name").primaryKey(),
756
+ description: (0, import_sqlite_core.text)("description")
757
+ });
758
+ var permissions2 = (0, import_sqlite_core.sqliteTable)("fortress_permission", {
759
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
760
+ resource: (0, import_sqlite_core.text)("resource").notNull().references(() => resources2.name, { onDelete: "cascade" }),
761
+ action: (0, import_sqlite_core.text)("action").notNull(),
762
+ effect: (0, import_sqlite_core.text)("effect").notNull().default("ALLOW"),
763
+ // 'ALLOW' | 'DENY'
764
+ conditions: (0, import_sqlite_core.text)("conditions"),
765
+ // JSON string of PermissionCondition[]
766
+ description: (0, import_sqlite_core.text)("description")
767
+ }, (table) => [
768
+ // M8 fix: SQL UNIQUE treats two NULL `conditions` as distinct, so the
769
+ // plain unique() above lets `findOrCreatePermission` insert duplicate
770
+ // rows for the same (resource, action, effect, conditions=NULL) tuple
771
+ // under concurrency. Mirror the split-index pattern used for role /
772
+ // direct-permission bindings.
773
+ (0, import_sqlite_core.uniqueIndex)("uniq_permission_no_conditions").on(table.resource, table.action, table.effect).where(import_drizzle_orm2.sql`${table.conditions} is null`),
774
+ (0, import_sqlite_core.uniqueIndex)("uniq_permission_with_conditions").on(table.resource, table.action, table.effect, table.conditions).where(import_drizzle_orm2.sql`${table.conditions} is not null`)
775
+ ]);
776
+ var roles2 = (0, import_sqlite_core.sqliteTable)("fortress_role", {
777
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
778
+ name: (0, import_sqlite_core.text)("name").notNull().unique(),
779
+ description: (0, import_sqlite_core.text)("description"),
780
+ isSystem: (0, import_sqlite_core.integer)("is_system", { mode: "boolean" }).notNull().default(false)
781
+ });
782
+ var rolePermissions2 = (0, import_sqlite_core.sqliteTable)(
783
+ "fortress_role_permission",
784
+ {
785
+ roleId: (0, import_sqlite_core.integer)("role_id").notNull().references(() => roles2.id, { onDelete: "cascade" }),
786
+ permissionId: (0, import_sqlite_core.integer)("permission_id").notNull().references(() => permissions2.id, { onDelete: "cascade" })
787
+ },
788
+ (table) => [(0, import_sqlite_core.primaryKey)({ columns: [table.roleId, table.permissionId] })]
789
+ );
790
+ var roleBindings2 = (0, import_sqlite_core.sqliteTable)("fortress_role_binding", {
791
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
792
+ roleId: (0, import_sqlite_core.integer)("role_id").notNull().references(() => roles2.id, { onDelete: "cascade" }),
793
+ subjectType: (0, import_sqlite_core.text)("subject_type").notNull(),
794
+ // 'USER' | 'GROUP' | 'SERVICE_ACCOUNT'
795
+ subjectId: (0, import_sqlite_core.integer)("subject_id").notNull(),
796
+ tenantId: (0, import_sqlite_core.text)("tenant_id")
797
+ }, (table) => [
798
+ (0, import_sqlite_core.unique)().on(table.roleId, table.subjectType, table.subjectId, table.tenantId),
799
+ (0, import_sqlite_core.uniqueIndex)("uniq_role_binding_global").on(table.roleId, table.subjectType, table.subjectId).where(import_drizzle_orm2.sql`${table.tenantId} is null`),
800
+ (0, import_sqlite_core.uniqueIndex)("uniq_role_binding_tenant").on(table.roleId, table.subjectType, table.subjectId, table.tenantId).where(import_drizzle_orm2.sql`${table.tenantId} is not null`),
801
+ (0, import_sqlite_core.index)("role_binding_subject_idx").on(table.subjectType, table.subjectId)
802
+ ]);
803
+ var directPermissionBindings2 = (0, import_sqlite_core.sqliteTable)("fortress_direct_permission_binding", {
804
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
805
+ permissionId: (0, import_sqlite_core.integer)("permission_id").notNull().references(() => permissions2.id, { onDelete: "cascade" }),
806
+ subjectType: (0, import_sqlite_core.text)("subject_type").notNull(),
807
+ // 'USER' | 'GROUP' | 'SERVICE_ACCOUNT'
808
+ subjectId: (0, import_sqlite_core.integer)("subject_id").notNull(),
809
+ tenantId: (0, import_sqlite_core.text)("tenant_id")
810
+ }, (table) => [
811
+ (0, import_sqlite_core.unique)().on(table.permissionId, table.subjectType, table.subjectId, table.tenantId),
812
+ (0, import_sqlite_core.uniqueIndex)("uniq_direct_permission_binding_global").on(table.permissionId, table.subjectType, table.subjectId).where(import_drizzle_orm2.sql`${table.tenantId} is null`),
813
+ (0, import_sqlite_core.uniqueIndex)("uniq_direct_permission_binding_tenant").on(table.permissionId, table.subjectType, table.subjectId, table.tenantId).where(import_drizzle_orm2.sql`${table.tenantId} is not null`),
814
+ (0, import_sqlite_core.index)("direct_permission_binding_subject_idx").on(table.subjectType, table.subjectId)
815
+ ]);
816
+ var emailVerificationTokens2 = (0, import_sqlite_core.sqliteTable)("fortress_email_verification_token", {
817
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
818
+ userId: (0, import_sqlite_core.integer)("user_id").notNull().references(() => users2.id, { onDelete: "cascade" }),
819
+ token: (0, import_sqlite_core.text)("token").notNull(),
820
+ email: (0, import_sqlite_core.text)("email").notNull(),
821
+ expiresAt: (0, import_sqlite_core.integer)("expires_at", { mode: "timestamp" }).notNull(),
822
+ usedAt: (0, import_sqlite_core.integer)("used_at", { mode: "timestamp" }),
823
+ createdAt: (0, import_sqlite_core.integer)("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
824
+ }, (table) => [(0, import_sqlite_core.index)("email_verification_token_token_idx").on(table.token)]);
825
+ var magicLinkTokens2 = (0, import_sqlite_core.sqliteTable)("fortress_magic_link_token", {
826
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
827
+ email: (0, import_sqlite_core.text)("email").notNull(),
828
+ token: (0, import_sqlite_core.text)("token").notNull(),
829
+ expiresAt: (0, import_sqlite_core.integer)("expires_at", { mode: "timestamp" }).notNull(),
830
+ usedAt: (0, import_sqlite_core.integer)("used_at", { mode: "timestamp" }),
831
+ createdAt: (0, import_sqlite_core.integer)("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
832
+ }, (table) => [(0, import_sqlite_core.index)("magic_link_token_token_idx").on(table.token)]);
833
+ var apiKeys2 = (0, import_sqlite_core.sqliteTable)("fortress_api_key", {
834
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
835
+ subjectType: (0, import_sqlite_core.text)("subject_type").notNull(),
836
+ // 'USER' | 'SERVICE_ACCOUNT' — polymorphic owner
837
+ subjectId: (0, import_sqlite_core.integer)("subject_id").notNull(),
838
+ name: (0, import_sqlite_core.text)("name").notNull(),
839
+ keyHash: (0, import_sqlite_core.text)("key_hash").notNull().unique(),
840
+ keyPrefix: (0, import_sqlite_core.text)("key_prefix").notNull(),
841
+ scopes: (0, import_sqlite_core.text)("scopes"),
842
+ // JSON array of "resource:action" strings
843
+ expiresAt: (0, import_sqlite_core.integer)("expires_at", { mode: "timestamp" }),
844
+ lastUsedAt: (0, import_sqlite_core.integer)("last_used_at", { mode: "timestamp" }),
845
+ isRevoked: (0, import_sqlite_core.integer)("is_revoked", { mode: "boolean" }).notNull().default(false),
846
+ createdAt: (0, import_sqlite_core.integer)("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
847
+ }, (table) => [(0, import_sqlite_core.index)("api_key_subject_idx").on(table.subjectType, table.subjectId)]);
848
+ var twoFactorSecrets2 = (0, import_sqlite_core.sqliteTable)("fortress_two_factor_secret", {
849
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
850
+ userId: (0, import_sqlite_core.integer)("user_id").notNull().unique().references(() => users2.id, { onDelete: "cascade" }),
851
+ secret: (0, import_sqlite_core.text)("secret").notNull(),
852
+ // Versioned AES-GCM envelope containing the TOTP seed
853
+ isEnabled: (0, import_sqlite_core.integer)("is_enabled", { mode: "boolean" }).notNull().default(false),
854
+ lastUsedCounter: (0, import_sqlite_core.integer)("last_used_counter"),
855
+ createdAt: (0, import_sqlite_core.integer)("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
856
+ });
857
+ var backupCodes2 = (0, import_sqlite_core.sqliteTable)("fortress_backup_code", {
858
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
859
+ userId: (0, import_sqlite_core.integer)("user_id").notNull().references(() => users2.id, { onDelete: "cascade" }),
860
+ codeHash: (0, import_sqlite_core.text)("code_hash").notNull(),
861
+ isUsed: (0, import_sqlite_core.integer)("is_used", { mode: "boolean" }).notNull().default(false),
862
+ createdAt: (0, import_sqlite_core.integer)("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
863
+ }, (table) => [(0, import_sqlite_core.index)("backup_code_user_idx").on(table.userId)]);
864
+ var trustedDevices2 = (0, import_sqlite_core.sqliteTable)("fortress_trusted_device", {
865
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
866
+ userId: (0, import_sqlite_core.integer)("user_id").notNull().references(() => users2.id, { onDelete: "cascade" }),
867
+ /** SHA-256 hash of the server-issued trusted-device secret (never raw token). */
868
+ deviceHash: (0, import_sqlite_core.text)("device_hash").notNull(),
869
+ expiresAt: (0, import_sqlite_core.integer)("expires_at", { mode: "timestamp" }).notNull(),
870
+ lastUsedAt: (0, import_sqlite_core.integer)("last_used_at", { mode: "timestamp" }).notNull(),
871
+ createdAt: (0, import_sqlite_core.integer)("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
872
+ }, (table) => [(0, import_sqlite_core.index)("trusted_device_user_idx").on(table.userId)]);
873
+ var socialAccounts2 = (0, import_sqlite_core.sqliteTable)("fortress_social_account", {
874
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
875
+ userId: (0, import_sqlite_core.integer)("user_id").notNull().references(() => users2.id, { onDelete: "cascade" }),
876
+ provider: (0, import_sqlite_core.text)("provider").notNull(),
877
+ providerAccountId: (0, import_sqlite_core.text)("provider_account_id").notNull(),
878
+ email: (0, import_sqlite_core.text)("email"),
879
+ accessToken: (0, import_sqlite_core.text)("access_token"),
880
+ // Encrypted
881
+ refreshToken: (0, import_sqlite_core.text)("refresh_token"),
882
+ // Encrypted
883
+ tokenExpiresAt: (0, import_sqlite_core.integer)("token_expires_at", { mode: "timestamp" }),
884
+ profile: (0, import_sqlite_core.text)("profile"),
885
+ // JSON
886
+ createdAt: (0, import_sqlite_core.integer)("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date()),
887
+ updatedAt: (0, import_sqlite_core.integer)("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
888
+ }, (table) => [
889
+ (0, import_sqlite_core.unique)().on(table.userId, table.provider),
890
+ (0, import_sqlite_core.unique)().on(table.provider, table.providerAccountId)
891
+ ]);
892
+ var tenants2 = (0, import_sqlite_core.sqliteTable)("fortress_tenant", {
893
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
894
+ name: (0, import_sqlite_core.text)("name").notNull(),
895
+ taxId: (0, import_sqlite_core.text)("tax_id").notNull().unique(),
896
+ description: (0, import_sqlite_core.text)("description"),
897
+ createdAt: (0, import_sqlite_core.integer)("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date()),
898
+ updatedAt: (0, import_sqlite_core.integer)("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
899
+ });
900
+ var tenantUsers2 = (0, import_sqlite_core.sqliteTable)(
901
+ "fortress_tenant_user",
902
+ {
903
+ tenantId: (0, import_sqlite_core.integer)("tenant_id").notNull().references(() => tenants2.id, { onDelete: "cascade" }),
904
+ userId: (0, import_sqlite_core.integer)("user_id").notNull().references(() => users2.id, { onDelete: "cascade" }),
905
+ isDefault: (0, import_sqlite_core.integer)("is_default", { mode: "boolean" }).notNull().default(false)
906
+ },
907
+ (table) => [
908
+ (0, import_sqlite_core.primaryKey)({ columns: [table.tenantId, table.userId] }),
909
+ (0, import_sqlite_core.uniqueIndex)("fortress_tenant_user_one_default_idx").on(table.userId).where(import_drizzle_orm2.sql`${table.isDefault} = true`)
910
+ ]
911
+ );
912
+ var oauthClients2 = (0, import_sqlite_core.sqliteTable)("fortress_oauth_client", {
913
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
914
+ clientId: (0, import_sqlite_core.text)("client_id").notNull().unique(),
915
+ clientSecretHash: (0, import_sqlite_core.text)("client_secret_hash").notNull(),
916
+ name: (0, import_sqlite_core.text)("name").notNull(),
917
+ redirectUris: (0, import_sqlite_core.text)("redirect_uris").notNull(),
918
+ // JSON array
919
+ grantTypes: (0, import_sqlite_core.text)("grant_types").notNull(),
920
+ // JSON array
921
+ // RFC 6749 §3.3 / RFC 9700 §2.2.1 per-client scope allow-list (JSON array,
922
+ // nullable for legacy v0 clients).
923
+ allowedScopes: (0, import_sqlite_core.text)("allowed_scopes"),
924
+ // RFC 6749 §2.1 client authentication method ('client_secret_basic' |
925
+ // 'client_secret_post' | 'none' for RFC 8252 public clients).
926
+ tokenEndpointAuthMethod: (0, import_sqlite_core.text)("token_endpoint_auth_method"),
927
+ createdAt: (0, import_sqlite_core.integer)("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
928
+ });
929
+ var oauthAuthorizationCodes2 = (0, import_sqlite_core.sqliteTable)("fortress_oauth_authorization_code", {
930
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
931
+ code: (0, import_sqlite_core.text)("code").notNull().unique(),
932
+ clientId: (0, import_sqlite_core.text)("client_id").notNull(),
933
+ userId: (0, import_sqlite_core.integer)("user_id").notNull(),
934
+ redirectUri: (0, import_sqlite_core.text)("redirect_uri").notNull(),
935
+ scope: (0, import_sqlite_core.text)("scope"),
936
+ codeChallenge: (0, import_sqlite_core.text)("code_challenge"),
937
+ codeChallengeMethod: (0, import_sqlite_core.text)("code_challenge_method"),
938
+ // OIDC Core §3.1.2.1 / §2 — echoed into the id_token if present.
939
+ nonce: (0, import_sqlite_core.text)("nonce"),
940
+ authTime: (0, import_sqlite_core.integer)("auth_time"),
941
+ expiresAt: (0, import_sqlite_core.integer)("expires_at", { mode: "timestamp" }).notNull(),
942
+ usedAt: (0, import_sqlite_core.integer)("used_at", { mode: "timestamp" }),
943
+ createdAt: (0, import_sqlite_core.integer)("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
944
+ });
945
+ var oauthAccessTokens2 = (0, import_sqlite_core.sqliteTable)("fortress_oauth_access_token", {
946
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
947
+ token: (0, import_sqlite_core.text)("token").notNull().unique(),
948
+ clientId: (0, import_sqlite_core.text)("client_id").notNull(),
949
+ userId: (0, import_sqlite_core.integer)("user_id"),
950
+ scope: (0, import_sqlite_core.text)("scope"),
951
+ expiresAt: (0, import_sqlite_core.integer)("expires_at", { mode: "timestamp" }).notNull(),
952
+ createdAt: (0, import_sqlite_core.integer)("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
953
+ });
954
+ var oauthRefreshTokens2 = (0, import_sqlite_core.sqliteTable)("fortress_oauth_refresh_token", {
955
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
956
+ token: (0, import_sqlite_core.text)("token").notNull().unique(),
957
+ familyId: (0, import_sqlite_core.text)("family_id").notNull(),
958
+ clientId: (0, import_sqlite_core.text)("client_id").notNull(),
959
+ userId: (0, import_sqlite_core.integer)("user_id").notNull(),
960
+ scope: (0, import_sqlite_core.text)("scope"),
961
+ issuedAt: (0, import_sqlite_core.integer)("issued_at", { mode: "timestamp" }).notNull(),
962
+ expiresAt: (0, import_sqlite_core.integer)("expires_at", { mode: "timestamp" }).notNull(),
963
+ usedAt: (0, import_sqlite_core.integer)("used_at", { mode: "timestamp" }),
964
+ parentId: (0, import_sqlite_core.integer)("parent_id"),
965
+ createdAt: (0, import_sqlite_core.integer)("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
966
+ });
967
+ var oauthPendingFlows2 = (0, import_sqlite_core.sqliteTable)("fortress_oauth_pending_flow", {
968
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
969
+ flowId: (0, import_sqlite_core.text)("flow_id").notNull().unique(),
970
+ clientId: (0, import_sqlite_core.text)("client_id").notNull(),
971
+ redirectUri: (0, import_sqlite_core.text)("redirect_uri").notNull(),
972
+ scope: (0, import_sqlite_core.text)("scope"),
973
+ state: (0, import_sqlite_core.text)("state").notNull(),
974
+ codeChallenge: (0, import_sqlite_core.text)("code_challenge"),
975
+ codeChallengeMethod: (0, import_sqlite_core.text)("code_challenge_method"),
976
+ nonce: (0, import_sqlite_core.text)("nonce"),
977
+ // H6 fix: subject the flow is bound to. Nullable for the
978
+ // login-redirect path which can't know the user up front — the
979
+ // first authenticated GetFlow / Approve claims it.
980
+ userId: (0, import_sqlite_core.integer)("user_id"),
981
+ // Single-use approval/denial claim used by the OAuth consent API.
982
+ usedAt: (0, import_sqlite_core.integer)("used_at", { mode: "timestamp" }),
983
+ expiresAt: (0, import_sqlite_core.integer)("expires_at", { mode: "timestamp" }).notNull(),
984
+ createdAt: (0, import_sqlite_core.integer)("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
985
+ });
986
+ var oauthSigningKeys2 = (0, import_sqlite_core.sqliteTable)("fortress_oauth_signing_key", {
987
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
988
+ kid: (0, import_sqlite_core.text)("kid").notNull().unique(),
989
+ alg: (0, import_sqlite_core.text)("alg").notNull(),
990
+ publicJwk: (0, import_sqlite_core.text)("public_jwk").notNull(),
991
+ privateJwk: (0, import_sqlite_core.text)("private_jwk").notNull(),
992
+ rotatedAt: (0, import_sqlite_core.integer)("rotated_at", { mode: "timestamp" }),
993
+ createdAt: (0, import_sqlite_core.integer)("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
994
+ });
995
+ var userScopeAssignments2 = (0, import_sqlite_core.sqliteTable)("fortress_user_scope_assignment", {
996
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
997
+ userId: (0, import_sqlite_core.integer)("user_id").notNull().references(() => users2.id, { onDelete: "cascade" }),
998
+ scopeName: (0, import_sqlite_core.text)("scope_name").notNull(),
999
+ scopeValue: (0, import_sqlite_core.text)("scope_value").notNull(),
1000
+ createdAt: (0, import_sqlite_core.integer)("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
1001
+ });
1002
+ var accountLockouts2 = (0, import_sqlite_core.sqliteTable)("fortress_account_lockout", {
1003
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
1004
+ identifier: (0, import_sqlite_core.text)("identifier").notNull().unique(),
1005
+ failedAttempts: (0, import_sqlite_core.integer)("failed_attempts").notNull().default(0),
1006
+ lastFailedAt: (0, import_sqlite_core.integer)("last_failed_at", { mode: "timestamp" }),
1007
+ lockedUntil: (0, import_sqlite_core.integer)("locked_until", { mode: "timestamp" }),
1008
+ lockoutCount: (0, import_sqlite_core.integer)("lockout_count").notNull().default(0),
1009
+ createdAt: (0, import_sqlite_core.integer)("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
1010
+ });
1011
+ var auditLogs2 = (0, import_sqlite_core.sqliteTable)("fortress_audit_log", {
1012
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
1013
+ timestamp: (0, import_sqlite_core.integer)("timestamp", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date()),
1014
+ eventType: (0, import_sqlite_core.text)("event_type").notNull(),
1015
+ actorId: (0, import_sqlite_core.integer)("actor_id"),
1016
+ actorType: (0, import_sqlite_core.text)("actor_type").notNull().default("USER"),
1017
+ targetId: (0, import_sqlite_core.integer)("target_id"),
1018
+ targetType: (0, import_sqlite_core.text)("target_type"),
1019
+ ipAddress: (0, import_sqlite_core.text)("ip_address"),
1020
+ userAgent: (0, import_sqlite_core.text)("user_agent"),
1021
+ outcome: (0, import_sqlite_core.text)("outcome").notNull().default("SUCCESS"),
1022
+ metadata: (0, import_sqlite_core.text)("metadata"),
1023
+ previousHash: (0, import_sqlite_core.text)("previous_hash"),
1024
+ createdAt: (0, import_sqlite_core.integer)("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
1025
+ }, (table) => [(0, import_sqlite_core.index)("audit_log_timestamp_idx").on(table.timestamp)]);
1026
+ var auditChainState2 = (0, import_sqlite_core.sqliteTable)("fortress_audit_chain_state", {
1027
+ id: (0, import_sqlite_core.integer)("id").primaryKey(),
1028
+ lastHash: (0, import_sqlite_core.text)("last_hash"),
1029
+ entryCount: (0, import_sqlite_core.integer)("entry_count").notNull(),
1030
+ updatedAt: (0, import_sqlite_core.integer)("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
1031
+ });
1032
+ var webhookEndpoints2 = (0, import_sqlite_core.sqliteTable)("fortress_webhook_endpoint", {
1033
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
1034
+ url: (0, import_sqlite_core.text)("url").notNull(),
1035
+ events: (0, import_sqlite_core.text)("events").notNull(),
1036
+ // JSON array
1037
+ secret: (0, import_sqlite_core.text)("secret").notNull(),
1038
+ isActive: (0, import_sqlite_core.integer)("is_active", { mode: "boolean" }).notNull().default(true),
1039
+ deactivatedReason: (0, import_sqlite_core.text)("deactivated_reason"),
1040
+ consecutiveFailures: (0, import_sqlite_core.integer)("consecutive_failures").notNull().default(0),
1041
+ createdAt: (0, import_sqlite_core.integer)("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
1042
+ });
1043
+ var webhookDeliveries2 = (0, import_sqlite_core.sqliteTable)("fortress_webhook_delivery", {
1044
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
1045
+ endpointId: (0, import_sqlite_core.integer)("endpoint_id").notNull().references(() => webhookEndpoints2.id, { onDelete: "cascade" }),
1046
+ eventType: (0, import_sqlite_core.text)("event_type").notNull(),
1047
+ payload: (0, import_sqlite_core.text)("payload").notNull(),
1048
+ // JSON
1049
+ status: (0, import_sqlite_core.text)("status").notNull().default("pending"),
1050
+ // pending | success | failed
1051
+ attempts: (0, import_sqlite_core.integer)("attempts").notNull().default(0),
1052
+ idempotencyKey: (0, import_sqlite_core.text)("idempotency_key"),
1053
+ lastAttemptAt: (0, import_sqlite_core.integer)("last_attempt_at", { mode: "timestamp" }),
1054
+ nextRetryAt: (0, import_sqlite_core.integer)("next_retry_at", { mode: "timestamp" }),
1055
+ responseStatus: (0, import_sqlite_core.integer)("response_status"),
1056
+ responseBody: (0, import_sqlite_core.text)("response_body"),
1057
+ errorKind: (0, import_sqlite_core.text)("error_kind"),
1058
+ createdAt: (0, import_sqlite_core.integer)("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
1059
+ }, (table) => [
1060
+ (0, import_sqlite_core.uniqueIndex)("uniq_webhook_delivery_idempotency").on(table.endpointId, table.idempotencyKey).where(import_drizzle_orm2.sql`${table.idempotencyKey} is not null`),
1061
+ (0, import_sqlite_core.index)("webhook_delivery_retry_idx").on(table.status, table.nextRetryAt)
1062
+ ]);
1063
+ var webauthnCredentials2 = (0, import_sqlite_core.sqliteTable)("fortress_webauthn_credential", {
1064
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
1065
+ userId: (0, import_sqlite_core.integer)("user_id").notNull().references(() => users2.id, { onDelete: "cascade" }),
1066
+ credentialId: (0, import_sqlite_core.text)("credential_id").notNull().unique(),
1067
+ publicKey: (0, import_sqlite_core.text)("public_key").notNull(),
1068
+ counter: (0, import_sqlite_core.integer)("counter").notNull().default(0),
1069
+ deviceType: (0, import_sqlite_core.text)("device_type").notNull(),
1070
+ backedUp: (0, import_sqlite_core.integer)("backed_up", { mode: "boolean" }).notNull().default(false),
1071
+ transports: (0, import_sqlite_core.text)("transports"),
1072
+ // JSON array
1073
+ createdAt: (0, import_sqlite_core.integer)("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
1074
+ });
1075
+ var webauthnChallenges2 = (0, import_sqlite_core.sqliteTable)("fortress_webauthn_challenge", {
1076
+ id: (0, import_sqlite_core.integer)("id").primaryKey({ autoIncrement: true }),
1077
+ challenge: (0, import_sqlite_core.text)("challenge").notNull().unique(),
1078
+ userId: (0, import_sqlite_core.integer)("user_id"),
1079
+ expiresAt: (0, import_sqlite_core.integer)("expires_at", { mode: "timestamp" }).notNull(),
1080
+ createdAt: (0, import_sqlite_core.integer)("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
1081
+ });
1082
+ var fortressSchema = {
1083
+ schemaVersion: schemaVersion2,
1084
+ users: users2,
1085
+ loginIdentifiers: loginIdentifiers2,
1086
+ refreshTokens: refreshTokens2,
1087
+ authContinuations: authContinuations2,
1088
+ groups: groups2,
1089
+ groupUsers: groupUsers2,
1090
+ serviceAccounts: serviceAccounts2,
1091
+ resources: resources2,
1092
+ permissions: permissions2,
1093
+ roles: roles2,
1094
+ rolePermissions: rolePermissions2,
1095
+ roleBindings: roleBindings2,
1096
+ directPermissionBindings: directPermissionBindings2,
1097
+ emailVerificationTokens: emailVerificationTokens2,
1098
+ magicLinkTokens: magicLinkTokens2,
1099
+ apiKeys: apiKeys2,
1100
+ twoFactorSecrets: twoFactorSecrets2,
1101
+ backupCodes: backupCodes2,
1102
+ trustedDevices: trustedDevices2,
1103
+ socialAccounts: socialAccounts2,
1104
+ tenants: tenants2,
1105
+ tenantUsers: tenantUsers2,
1106
+ oauthClients: oauthClients2,
1107
+ oauthAuthorizationCodes: oauthAuthorizationCodes2,
1108
+ oauthAccessTokens: oauthAccessTokens2,
1109
+ oauthRefreshTokens: oauthRefreshTokens2,
1110
+ oauthPendingFlows: oauthPendingFlows2,
1111
+ oauthSigningKeys: oauthSigningKeys2,
1112
+ userScopeAssignments: userScopeAssignments2,
1113
+ accountLockouts: accountLockouts2,
1114
+ auditLogs: auditLogs2,
1115
+ auditChainState: auditChainState2,
1116
+ webhookEndpoints: webhookEndpoints2,
1117
+ webhookDeliveries: webhookDeliveries2,
1118
+ webauthnCredentials: webauthnCredentials2,
1119
+ webauthnChallenges: webauthnChallenges2
1120
+ };
1121
+
1122
+ // src/drizzle/adapter.ts
1123
+ function buildTableMap(schema) {
1124
+ return {
1125
+ schema_version: schema.schemaVersion,
1126
+ user: schema.users,
1127
+ login_identifier: schema.loginIdentifiers,
1128
+ refresh_token: schema.refreshTokens,
1129
+ auth_continuation: schema.authContinuations,
1130
+ group: schema.groups,
1131
+ group_user: schema.groupUsers,
1132
+ service_account: schema.serviceAccounts,
1133
+ resource: schema.resources,
1134
+ permission: schema.permissions,
1135
+ role: schema.roles,
1136
+ role_permission: schema.rolePermissions,
1137
+ role_binding: schema.roleBindings,
1138
+ direct_permission_binding: schema.directPermissionBindings,
1139
+ email_verification_token: schema.emailVerificationTokens,
1140
+ magic_link_token: schema.magicLinkTokens,
1141
+ api_key: schema.apiKeys,
1142
+ two_factor_secret: schema.twoFactorSecrets,
1143
+ backup_code: schema.backupCodes,
1144
+ trusted_device: schema.trustedDevices,
1145
+ social_account: schema.socialAccounts,
1146
+ tenant: schema.tenants,
1147
+ tenant_user: schema.tenantUsers,
1148
+ oauth_client: schema.oauthClients,
1149
+ oauth_authorization_code: schema.oauthAuthorizationCodes,
1150
+ oauth_access_token: schema.oauthAccessTokens,
1151
+ oauth_refresh_token: schema.oauthRefreshTokens,
1152
+ oauth_pending_flow: schema.oauthPendingFlows,
1153
+ oauth_signing_key: schema.oauthSigningKeys,
1154
+ user_scope_assignment: schema.userScopeAssignments,
1155
+ account_lockout: schema.accountLockouts,
1156
+ audit_log: schema.auditLogs,
1157
+ audit_chain_state: schema.auditChainState,
1158
+ webhook_endpoint: schema.webhookEndpoints,
1159
+ webhook_delivery: schema.webhookDeliveries,
1160
+ webauthn_credential: schema.webauthnCredentials,
1161
+ webauthn_challenge: schema.webauthnChallenges
1162
+ };
1163
+ }
1164
+ var SQLITE_DEFAULT_TABLE_MAP = buildTableMap(fortressSchema);
1165
+ var PG_DEFAULT_TABLE_MAP = buildTableMap(fortressPgSchema);
1166
+ function getColumn(table, field) {
1167
+ const columns = (0, import_drizzle_orm3.getTableColumns)(table);
1168
+ if (columns[field])
1169
+ return columns[field];
1170
+ const camelCase = field.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
1171
+ if (columns[camelCase])
1172
+ return columns[camelCase];
1173
+ throw Errors.badRequest(`Unknown field: ${field} on table`);
1174
+ }
1175
+ function buildWhereCondition(table, where) {
1176
+ if (where.length === 0)
1177
+ throw Errors.badRequest("A non-empty where clause is required (empty where would match all rows)");
1178
+ const conditions = where.map((clause) => {
1179
+ const column = getColumn(table, clause.field);
1180
+ switch (clause.operator) {
1181
+ case "=":
1182
+ return (0, import_drizzle_orm3.eq)(column, clause.value);
1183
+ case "!=":
1184
+ return (0, import_drizzle_orm3.ne)(column, clause.value);
1185
+ case "in":
1186
+ return (0, import_drizzle_orm3.inArray)(column, clause.value);
1187
+ case "gt":
1188
+ return (0, import_drizzle_orm3.gt)(column, clause.value);
1189
+ case "lt":
1190
+ return (0, import_drizzle_orm3.lt)(column, clause.value);
1191
+ case "gte":
1192
+ return (0, import_drizzle_orm3.gte)(column, clause.value);
1193
+ case "lte":
1194
+ return (0, import_drizzle_orm3.lte)(column, clause.value);
1195
+ case "like":
1196
+ return (0, import_drizzle_orm3.like)(column, clause.value);
1197
+ case "isNull":
1198
+ return (0, import_drizzle_orm3.isNull)(column);
1199
+ default:
1200
+ throw Errors.badRequest(`Unsupported operator: ${clause.operator}`);
1201
+ }
1202
+ });
1203
+ return conditions.length === 1 ? conditions[0] : (0, import_drizzle_orm3.and)(...conditions);
1204
+ }
1205
+ function sanitizeData(data) {
1206
+ const result = {};
1207
+ for (const [key, value] of Object.entries(data)) {
1208
+ result[key] = value === void 0 ? null : value;
1209
+ }
1210
+ return result;
1211
+ }
1212
+ var ID_FIELD_RE = /[a-z]Id$/;
1213
+ function isIdField(key) {
1214
+ return key === "id" || ID_FIELD_RE.test(key);
1215
+ }
1216
+ function stringifyIds(row) {
1217
+ if (row == null || typeof row !== "object")
1218
+ return row;
1219
+ if (Array.isArray(row))
1220
+ return row.map(stringifyIds);
1221
+ const out = {};
1222
+ for (const [key, value] of Object.entries(row)) {
1223
+ if (isIdField(key) && (typeof value === "number" || typeof value === "bigint")) {
1224
+ out[key] = String(value);
1225
+ } else if (value && typeof value === "object" && !(value instanceof Date)) {
1226
+ out[key] = stringifyIds(value);
1227
+ } else {
1228
+ out[key] = value;
1229
+ }
1230
+ }
1231
+ return out;
1232
+ }
1233
+ function buildRawSql(sqlText, params = []) {
1234
+ if (params.length === 0)
1235
+ return import_drizzle_orm3.sql.raw(sqlText);
1236
+ if (sqlText.includes("?")) {
1237
+ const parts = sqlText.split("?");
1238
+ if (parts.length - 1 !== params.length) {
1239
+ throw Errors.badRequest(`rawQuery placeholder count (${parts.length - 1}) does not match params (${params.length})`);
1240
+ }
1241
+ let query = import_drizzle_orm3.sql.raw(parts[0]);
1242
+ for (let i = 0; i < params.length; i++) {
1243
+ query = import_drizzle_orm3.sql`${query}${params[i]}${import_drizzle_orm3.sql.raw(parts[i + 1])}`;
1244
+ }
1245
+ return query;
1246
+ }
1247
+ throw Errors.badRequest(
1248
+ "rawQuery uses ? positional placeholders on every dialect; params were provided but no ? placeholders were found"
1249
+ );
1250
+ }
1251
+ function normalizeRawRows(result) {
1252
+ if (Array.isArray(result))
1253
+ return result;
1254
+ const rows = result?.rows;
1255
+ if (Array.isArray(rows))
1256
+ return rows;
1257
+ return [];
1258
+ }
1259
+ function sqliteStatementReturnsRows(sqlText) {
1260
+ const normalized = sqlText.trimStart().toLowerCase();
1261
+ return normalized.startsWith("select") || normalized.startsWith("with") || normalized.startsWith("pragma") || normalized.includes(" returning ");
1262
+ }
1263
+ function createDrizzleAdapter(db, options) {
1264
+ const dialect = options?.dialect ?? "sqlite";
1265
+ const defaults = dialect === "pg" ? PG_DEFAULT_TABLE_MAP : SQLITE_DEFAULT_TABLE_MAP;
1266
+ const tableMap = { ...defaults, ...options?.tables };
1267
+ const isSqlite = dialect === "sqlite";
1268
+ let sqliteTxChain = Promise.resolve();
1269
+ const sqliteTxContext = new import_node_async_hooks.AsyncLocalStorage();
1270
+ function serializeSqlite(op) {
1271
+ if (!isSqlite || sqliteTxContext.getStore())
1272
+ return op();
1273
+ const result = sqliteTxChain.then(op, op);
1274
+ sqliteTxChain = result.catch(() => void 0);
1275
+ return result;
1276
+ }
1277
+ async function execOne(query) {
1278
+ const row = isSqlite ? query.get() : (await query)[0];
1279
+ return row === void 0 ? void 0 : stringifyIds(row);
1280
+ }
1281
+ async function execMany(query) {
1282
+ const rows = isSqlite ? query.all() : await query;
1283
+ return rows.map(stringifyIds);
1284
+ }
1285
+ async function execRun(query) {
1286
+ if (isSqlite) {
1287
+ query.run();
1288
+ return;
1289
+ }
1290
+ await query;
1291
+ }
1292
+ function getTable(model) {
1293
+ const table = tableMap[model];
1294
+ if (!table) {
1295
+ throw Errors.badRequest(`Unknown model: ${model}`);
1296
+ }
1297
+ return table;
1298
+ }
1299
+ function buildAdapter(drizzle) {
1300
+ const self = {
1301
+ get dialect() {
1302
+ return dialect;
1303
+ },
1304
+ async create(params) {
1305
+ return serializeSqlite(async () => {
1306
+ const table = getTable(params.model);
1307
+ try {
1308
+ const result = await execOne(drizzle.insert(table).values(sanitizeData(params.data)).returning());
1309
+ return result;
1310
+ } catch (err) {
1311
+ rethrowDbError(err, dialect);
1312
+ }
1313
+ });
1314
+ },
1315
+ async findOne(params) {
1316
+ return serializeSqlite(async () => {
1317
+ const table = getTable(params.model);
1318
+ const condition = buildWhereCondition(table, params.where);
1319
+ const result = await execOne(drizzle.select().from(table).where(condition).limit(1));
1320
+ return result ?? null;
1321
+ });
1322
+ },
1323
+ async findMany(params) {
1324
+ return serializeSqlite(async () => {
1325
+ const table = getTable(params.model);
1326
+ let query = drizzle.select().from(table).$dynamic();
1327
+ if (params.where && params.where.length > 0) {
1328
+ const condition = buildWhereCondition(table, params.where);
1329
+ query = query.where(condition);
1330
+ }
1331
+ if (params.sortBy) {
1332
+ const column = getColumn(table, params.sortBy.field);
1333
+ query = query.orderBy(
1334
+ params.sortBy.direction === "desc" ? import_drizzle_orm3.sql`${column} desc` : import_drizzle_orm3.sql`${column} asc`
1335
+ );
1336
+ }
1337
+ if (params.limit) {
1338
+ query = query.limit(params.limit);
1339
+ }
1340
+ if (params.offset) {
1341
+ query = query.offset(params.offset);
1342
+ }
1343
+ return execMany(query);
1344
+ });
1345
+ },
1346
+ async update(params) {
1347
+ return serializeSqlite(async () => {
1348
+ const table = getTable(params.model);
1349
+ const condition = buildWhereCondition(table, params.where);
1350
+ const query = drizzle.update(table).set(sanitizeData(params.data)).where(condition).returning();
1351
+ try {
1352
+ if (isSqlite) {
1353
+ const rows = query.all().map(stringifyIds);
1354
+ return rows[0] ?? null;
1355
+ }
1356
+ const result = await execOne(query);
1357
+ return result ?? null;
1358
+ } catch (err) {
1359
+ rethrowDbError(err, dialect);
1360
+ }
1361
+ });
1362
+ },
1363
+ async delete(params) {
1364
+ return serializeSqlite(async () => {
1365
+ const table = getTable(params.model);
1366
+ const condition = buildWhereCondition(table, params.where);
1367
+ try {
1368
+ await execRun(drizzle.delete(table).where(condition));
1369
+ } catch (err) {
1370
+ rethrowDbError(err, dialect);
1371
+ }
1372
+ });
1373
+ },
1374
+ async count(params) {
1375
+ return serializeSqlite(async () => {
1376
+ const table = getTable(params.model);
1377
+ let query = drizzle.select({ count: import_drizzle_orm3.sql`count(*)` }).from(table).$dynamic();
1378
+ if (params.where && params.where.length > 0) {
1379
+ const condition = buildWhereCondition(table, params.where);
1380
+ query = query.where(condition);
1381
+ }
1382
+ const result = await execOne(query);
1383
+ return Number(result?.count) || 0;
1384
+ });
1385
+ },
1386
+ async rawQuery(sqlText, params) {
1387
+ return serializeSqlite(async () => {
1388
+ const query = buildRawSql(sqlText, params ?? []);
1389
+ if (isSqlite) {
1390
+ if (typeof drizzle.all === "function" && sqliteStatementReturnsRows(sqlText))
1391
+ return normalizeRawRows(drizzle.all(query)).map(stringifyIds);
1392
+ if (typeof drizzle.run === "function") {
1393
+ drizzle.run(query);
1394
+ return [];
1395
+ }
1396
+ if (typeof drizzle.execute === "function")
1397
+ return normalizeRawRows(await drizzle.execute(query)).map(stringifyIds);
1398
+ throw Errors.badRequest("rawQuery is not supported by this SQLite Drizzle driver");
1399
+ }
1400
+ if (typeof drizzle.execute !== "function")
1401
+ throw Errors.badRequest("rawQuery is not supported by this Drizzle driver");
1402
+ return normalizeRawRows(await drizzle.execute(query)).map(stringifyIds);
1403
+ });
1404
+ },
1405
+ async transaction(fn) {
1406
+ if (dialect === "sqlite") {
1407
+ if (sqliteTxContext.getStore()) {
1408
+ throw Errors.badRequest("Nested transactions are not supported by the SQLite Drizzle adapter");
1409
+ }
1410
+ const run = async () => {
1411
+ drizzle.run(import_drizzle_orm3.sql`BEGIN IMMEDIATE`);
1412
+ try {
1413
+ const result2 = await sqliteTxContext.run(true, () => fn(self));
1414
+ drizzle.run(import_drizzle_orm3.sql`COMMIT`);
1415
+ return result2;
1416
+ } catch (error) {
1417
+ drizzle.run(import_drizzle_orm3.sql`ROLLBACK`);
1418
+ throw error;
1419
+ }
1420
+ };
1421
+ const result = sqliteTxChain.then(run, run);
1422
+ sqliteTxChain = result.catch(() => void 0);
1423
+ return result;
1424
+ }
1425
+ return drizzle.transaction(async (tx) => {
1426
+ const txAdapter = buildAdapter(tx);
1427
+ return fn(txAdapter);
1428
+ });
1429
+ }
1430
+ };
1431
+ return self;
1432
+ }
1433
+ return buildAdapter(db);
1434
+ }
1435
+ // Annotate the CommonJS export names for ESM import in node:
1436
+ 0 && (module.exports = {
1437
+ createDrizzleAdapter,
1438
+ findSqlstate,
1439
+ fortressPgSchema,
1440
+ fortressSchema,
1441
+ rethrowDbError
1442
+ });