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