@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,2351 @@
1
+ // src/core/schema-builder.ts
2
+ import { fromJSONSchema } from "@bajustone/fetcher/openapi";
3
+ import { date as fDate, datetime as fDatetime, email as fEmail, time as fTime, url as fUrl, uuid as fUuid } from "@bajustone/fetcher/schema";
4
+ function collectRefNames(schema, acc) {
5
+ if (!schema || typeof schema !== "object")
6
+ return acc;
7
+ if (typeof schema.$ref === "string") {
8
+ const i = schema.$ref.lastIndexOf("/");
9
+ acc.add(i >= 0 ? schema.$ref.slice(i + 1) : schema.$ref);
10
+ }
11
+ if (schema.properties) {
12
+ for (const key of Object.keys(schema.properties))
13
+ collectRefNames(schema.properties[key], acc);
14
+ }
15
+ collectRefNames(schema.items, acc);
16
+ for (const key of ["oneOf", "anyOf", "allOf"]) {
17
+ const variants = schema[key];
18
+ if (variants) {
19
+ for (const variant of variants)
20
+ collectRefNames(variant, acc);
21
+ }
22
+ }
23
+ if (schema.additionalProperties && typeof schema.additionalProperties === "object")
24
+ collectRefNames(schema.additionalProperties, acc);
25
+ return acc;
26
+ }
27
+ var refDefinitionContexts = /* @__PURE__ */ new WeakMap();
28
+ function refName(refPath) {
29
+ const i = refPath.lastIndexOf("/");
30
+ return i >= 0 ? refPath.slice(i + 1) : refPath;
31
+ }
32
+ var COMPONENT_NAME_RE = /^[\w.-]+$/;
33
+ function assertComponentName(name) {
34
+ if (!COMPONENT_NAME_RE.test(name))
35
+ throw new Error(`Invalid OpenAPI component name '${name}'`);
36
+ }
37
+ function resolveRefDefs(schema) {
38
+ if (collectRefNames(schema, /* @__PURE__ */ new Set()).size === 0)
39
+ return void 0;
40
+ const defs = /* @__PURE__ */ Object.create(null);
41
+ const unresolved = /* @__PURE__ */ new Set();
42
+ const hasOwn = (value, key) => Object.hasOwn(value, key);
43
+ const visit = (node, inherited) => {
44
+ if (!node || typeof node !== "object")
45
+ return;
46
+ const context = refDefinitionContexts.get(node) ?? inherited;
47
+ if (typeof node.$ref === "string") {
48
+ const name = refName(node.$ref);
49
+ const component = context && hasOwn(context, name) ? context[name] : void 0;
50
+ if (component) {
51
+ if (hasOwn(defs, name) && !unresolved.has(name) && defs[name] !== component) {
52
+ throw new Error(`Conflicting component definitions for $ref '${name}'`);
53
+ }
54
+ const firstResolution = !hasOwn(defs, name) || unresolved.delete(name);
55
+ defs[name] = component;
56
+ if (firstResolution)
57
+ visit(component, context);
58
+ } else if (!hasOwn(defs, name)) {
59
+ defs[name] = {};
60
+ unresolved.add(name);
61
+ }
62
+ }
63
+ if (node.properties) {
64
+ for (const child of Object.values(node.properties))
65
+ visit(child, context);
66
+ }
67
+ visit(node.items, context);
68
+ for (const key of ["oneOf", "anyOf", "allOf"]) {
69
+ for (const child of node[key] ?? [])
70
+ visit(child, context);
71
+ }
72
+ if (node.additionalProperties && typeof node.additionalProperties === "object")
73
+ visit(node.additionalProperties, context);
74
+ };
75
+ visit(schema);
76
+ return defs;
77
+ }
78
+ function createStandardProps(schema) {
79
+ let validateFn;
80
+ return {
81
+ version: 1,
82
+ vendor: "fortress",
83
+ validate(value) {
84
+ if (!validateFn) {
85
+ const defs = resolveRefDefs(schema);
86
+ validateFn = fromJSONSchema(schema, defs)["~standard"].validate;
87
+ }
88
+ return validateFn(value);
89
+ }
90
+ };
91
+ }
92
+ function createExactOneOfProps(schemas) {
93
+ const validate = (value) => {
94
+ const results = schemas.map((schema) => schema["~standard"].validate(value));
95
+ if (results.some((result) => result instanceof Promise)) {
96
+ return Promise.all(results).then((resolved) => exactOneResult(resolved));
97
+ }
98
+ return exactOneResult(results);
99
+ };
100
+ return {
101
+ version: 1,
102
+ vendor: "fortress",
103
+ validate
104
+ };
105
+ }
106
+ function exactOneResult(results) {
107
+ const successes = results.filter((result) => !result.issues);
108
+ if (successes.length === 1)
109
+ return { value: successes[0].value };
110
+ return {
111
+ issues: [{
112
+ message: successes.length === 0 ? "Value must match exactly one oneOf variant" : "Value must match exactly one oneOf variant; multiple variants matched"
113
+ }]
114
+ };
115
+ }
116
+ function toFortressSchema(schema, refDefinitions, standardProps) {
117
+ if (refDefinitions)
118
+ refDefinitionContexts.set(schema, refDefinitions);
119
+ return Object.assign(schema, {
120
+ "~standard": standardProps ?? createStandardProps(schema)
121
+ });
122
+ }
123
+ function str(opts) {
124
+ const o = typeof opts === "string" ? { description: opts } : opts ?? {};
125
+ const s = { type: "string" };
126
+ if (o.description)
127
+ s.description = o.description;
128
+ if (o.min !== void 0)
129
+ s.minLength = o.min;
130
+ if (o.max !== void 0)
131
+ s.maxLength = o.max;
132
+ if (o.pattern !== void 0)
133
+ s.pattern = o.pattern;
134
+ if (o.format !== void 0)
135
+ s.format = o.format;
136
+ return toFortressSchema(s);
137
+ }
138
+ function int(opts) {
139
+ const o = typeof opts === "string" ? { description: opts } : opts ?? {};
140
+ const s = { type: "integer" };
141
+ if (o.description)
142
+ s.description = o.description;
143
+ if (o.min !== void 0)
144
+ s.minimum = o.min;
145
+ if (o.max !== void 0)
146
+ s.maximum = o.max;
147
+ return toFortressSchema(s);
148
+ }
149
+ function id(description) {
150
+ const s = { type: "string", minLength: 1 };
151
+ if (description)
152
+ s.description = description;
153
+ return toFortressSchema(s);
154
+ }
155
+ function bool(description) {
156
+ const s = { type: "boolean" };
157
+ if (description)
158
+ s.description = description;
159
+ return toFortressSchema(s);
160
+ }
161
+ function arr(items, description) {
162
+ const s = { type: "array", items };
163
+ if (description)
164
+ s.description = description;
165
+ return toFortressSchema(s);
166
+ }
167
+ function obj(properties, ...required) {
168
+ const s = { type: "object", properties };
169
+ if (required.length > 0)
170
+ s.required = required;
171
+ return toFortressSchema(s);
172
+ }
173
+ function nullable(schema) {
174
+ if (typeof schema.$ref === "string")
175
+ return toFortressSchema({ oneOf: [schema, { type: "null" }] });
176
+ const s = { ...schema, nullable: true };
177
+ return toFortressSchema(s, refDefinitionContexts.get(schema));
178
+ }
179
+ function oneOf(...schemas) {
180
+ const schema = { oneOf: schemas };
181
+ return toFortressSchema(
182
+ schema,
183
+ void 0,
184
+ createExactOneOfProps(schemas)
185
+ );
186
+ }
187
+ function defineComponents(components) {
188
+ for (const name of Object.keys(components))
189
+ assertComponentName(name);
190
+ const definitions = Object.assign(
191
+ /* @__PURE__ */ Object.create(null),
192
+ components
193
+ );
194
+ return {
195
+ components,
196
+ ref: (name) => {
197
+ assertComponentName(name);
198
+ return toFortressSchema(
199
+ { $ref: `#/components/schemas/${String(name)}` },
200
+ definitions
201
+ );
202
+ }
203
+ };
204
+ }
205
+ function enums(...values) {
206
+ return toFortressSchema({ enum: values });
207
+ }
208
+ function strFormat(format, description) {
209
+ const s = { type: "string", format };
210
+ if (description)
211
+ s.description = description;
212
+ return toFortressSchema(s);
213
+ }
214
+ function nullType() {
215
+ return toFortressSchema({ type: "null" });
216
+ }
217
+ function record(description) {
218
+ const s = { type: "object", additionalProperties: true };
219
+ if (description)
220
+ s.description = description;
221
+ return toFortressSchema(s);
222
+ }
223
+ function recordOf(valueSchema, description) {
224
+ const s = { type: "object", additionalProperties: valueSchema };
225
+ if (description)
226
+ s.description = description;
227
+ return toFortressSchema(s);
228
+ }
229
+ function makeFormatBuilder(factory) {
230
+ const f = factory();
231
+ return (description) => {
232
+ const s = { type: "string" };
233
+ if (f.format)
234
+ s.format = f.format;
235
+ if (f.pattern)
236
+ s.pattern = f.pattern;
237
+ if (description)
238
+ s.description = description;
239
+ return toFortressSchema(s);
240
+ };
241
+ }
242
+ var email = makeFormatBuilder(fEmail);
243
+ var uuid = makeFormatBuilder(fUuid);
244
+ var url = makeFormatBuilder(fUrl);
245
+ var datetime = makeFormatBuilder(fDatetime);
246
+ var date = makeFormatBuilder(fDate);
247
+ var time = makeFormatBuilder(fTime);
248
+ function isStandardSchema(value) {
249
+ return typeof value === "object" && value !== null && "~standard" in value && typeof value["~standard"]?.validate === "function";
250
+ }
251
+ function isFortressSchema(value) {
252
+ return isStandardSchema(value) && value["~standard"].vendor === "fortress" && ("type" in value || "$ref" in value || "oneOf" in value || "anyOf" in value);
253
+ }
254
+ var JSON_SCHEMA_TYPES = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "object", "array", "null"]);
255
+ function hasJsonSchemaShape(value) {
256
+ if (typeof value !== "object" || value === null)
257
+ return false;
258
+ const v = value;
259
+ if ("$ref" in v || "oneOf" in v || "anyOf" in v || "allOf" in v)
260
+ return true;
261
+ if (typeof v.type === "string" && JSON_SCHEMA_TYPES.has(v.type))
262
+ return true;
263
+ if (Array.isArray(v.type) && v.type.every((t) => typeof t === "string" && JSON_SCHEMA_TYPES.has(t)))
264
+ return true;
265
+ return false;
266
+ }
267
+ function extractJsonSchema(schema) {
268
+ if (isFortressSchema(schema)) {
269
+ return schema;
270
+ }
271
+ if (isStandardSchema(schema)) {
272
+ const std = schema["~standard"];
273
+ if (std?.jsonSchema?.input) {
274
+ return std.jsonSchema.input({ target: "draft-2020-12" });
275
+ }
276
+ if (hasJsonSchemaShape(schema)) {
277
+ return schema;
278
+ }
279
+ }
280
+ return {};
281
+ }
282
+ var ErrorEnvelope = obj({
283
+ code: str("Machine-readable error code"),
284
+ message: str("Human-readable error message"),
285
+ statusCode: int("HTTP status code"),
286
+ details: toFortressSchema({ description: "Optional structured error details" })
287
+ }, "code", "message", "statusCode");
288
+ var EndpointBuilder = class {
289
+ _method;
290
+ _path;
291
+ _handler = "";
292
+ _summary = "";
293
+ _description;
294
+ _tags = [];
295
+ _security = [];
296
+ _deprecated = false;
297
+ _permission;
298
+ _body;
299
+ _query;
300
+ _params;
301
+ _responses = {};
302
+ constructor(method, path) {
303
+ this._method = method;
304
+ this._path = path;
305
+ }
306
+ summary(s) {
307
+ this._summary = s;
308
+ return this;
309
+ }
310
+ description(s) {
311
+ this._description = s;
312
+ return this;
313
+ }
314
+ tags(...t) {
315
+ this._tags.push(...t);
316
+ return this;
317
+ }
318
+ security(...s) {
319
+ this._security.push(...s);
320
+ return this;
321
+ }
322
+ deprecated() {
323
+ this._deprecated = true;
324
+ return this;
325
+ }
326
+ permission(resource, action) {
327
+ this._permission = { resource, action };
328
+ return this;
329
+ }
330
+ body(schema) {
331
+ this._body = schema;
332
+ return this;
333
+ }
334
+ query(schema) {
335
+ this._query = schema;
336
+ return this;
337
+ }
338
+ params(schema) {
339
+ this._params = schema;
340
+ return this;
341
+ }
342
+ response(status, description, schema) {
343
+ const stored = { description };
344
+ if (schema !== void 0) {
345
+ stored.schema = isStandardSchema(schema) ? extractJsonSchema(schema) : schema;
346
+ }
347
+ this._responses[status] = stored;
348
+ return this;
349
+ }
350
+ /**
351
+ * Declare an error response that returns the canonical {@link ErrorEnvelope}
352
+ * body. Shorthand for `.response(status, description, ErrorEnvelope)`.
353
+ *
354
+ * Aligns host endpoint error responses with what Fortress's own routes
355
+ * emit, so a single client-side error parser works everywhere.
356
+ *
357
+ * ```ts
358
+ * endpoint('GET', '/schools/:id')
359
+ * .summary('Get a school')
360
+ * .params(obj({ id: str() }, 'id'))
361
+ * .response(200, 'OK', SchoolEnvelope)
362
+ * .errorResponse(404, 'School not found')
363
+ * .errorResponse(403, 'Forbidden')
364
+ * .build();
365
+ * ```
366
+ */
367
+ errorResponse(status, description) {
368
+ return this.response(status, description, ErrorEnvelope);
369
+ }
370
+ handler(name) {
371
+ this._handler = name;
372
+ return this;
373
+ }
374
+ build() {
375
+ const def = {
376
+ method: this._method,
377
+ path: this._path,
378
+ handler: this._handler
379
+ };
380
+ if (this._summary || this._tags.length > 0 || this._security.length > 0 || this._description || this._deprecated || this._permission) {
381
+ def.meta = {
382
+ summary: this._summary,
383
+ ...this._description && { description: this._description },
384
+ ...this._tags.length > 0 && { tags: this._tags },
385
+ ...this._security.length > 0 && { security: this._security },
386
+ ...this._deprecated && { deprecated: true },
387
+ ...this._permission && { permission: this._permission }
388
+ };
389
+ }
390
+ if (this._body || this._query || this._params) {
391
+ def.input = {};
392
+ if (this._body) {
393
+ def.input.body = extractJsonSchema(this._body);
394
+ if (isStandardSchema(this._body))
395
+ def.input.bodySchema = this._body;
396
+ }
397
+ if (this._query) {
398
+ def.input.query = extractJsonSchema(this._query);
399
+ if (isStandardSchema(this._query))
400
+ def.input.querySchema = this._query;
401
+ }
402
+ if (this._params) {
403
+ def.input.params = extractJsonSchema(this._params);
404
+ if (isStandardSchema(this._params))
405
+ def.input.paramsSchema = this._params;
406
+ }
407
+ }
408
+ if (Object.keys(this._responses).length > 0) {
409
+ def.responses = this._responses;
410
+ }
411
+ return def;
412
+ }
413
+ };
414
+ function endpoint(method, path) {
415
+ return new EndpointBuilder(method, path);
416
+ }
417
+
418
+ // src/core/auth/auth-endpoints.ts
419
+ var User = obj(
420
+ {
421
+ id: id("User ID"),
422
+ email: strFormat("email", "User email"),
423
+ name: str("Display name"),
424
+ isActive: bool("Account active status"),
425
+ emailVerified: bool("Email verification status"),
426
+ createdAt: strFormat("date-time", "Creation timestamp"),
427
+ updatedAt: strFormat("date-time", "Last update timestamp")
428
+ },
429
+ "id",
430
+ "email",
431
+ "name",
432
+ "isActive",
433
+ "createdAt",
434
+ "updatedAt"
435
+ );
436
+ var AuthChallenge = obj(
437
+ {
438
+ reason: enums("two-factor", "webauthn", "email-verification", "magic-link"),
439
+ continuationToken: str("Single-use post-auth continuation token")
440
+ },
441
+ "reason",
442
+ "continuationToken"
443
+ );
444
+ var AuthResult = oneOf(
445
+ obj(
446
+ {
447
+ status: enums("success"),
448
+ user: User,
449
+ method: enums("password", "refresh", "two-factor", "webauthn", "magic-link", "impersonation"),
450
+ accessToken: str("JWT access token"),
451
+ refreshToken: str("Refresh token for rotation"),
452
+ pluginData: record()
453
+ },
454
+ "status",
455
+ "user",
456
+ "method",
457
+ "accessToken",
458
+ "refreshToken"
459
+ ),
460
+ obj(
461
+ {
462
+ status: enums("pending"),
463
+ user: User,
464
+ pending: AuthChallenge,
465
+ pluginData: record()
466
+ },
467
+ "status",
468
+ "user",
469
+ "pending"
470
+ ),
471
+ obj(
472
+ {
473
+ status: enums("impersonation"),
474
+ user: User,
475
+ accessToken: str("JWT access token"),
476
+ refreshToken: nullType(),
477
+ pluginData: record()
478
+ },
479
+ "status",
480
+ "user",
481
+ "accessToken",
482
+ "refreshToken"
483
+ )
484
+ );
485
+ var AuthTokenPair = obj(
486
+ {
487
+ accessToken: str("JWT access token"),
488
+ refreshToken: str("New refresh token")
489
+ },
490
+ "accessToken",
491
+ "refreshToken"
492
+ );
493
+ var SessionInfo = obj(
494
+ {
495
+ id: id("Token ID"),
496
+ ipAddress: nullable(str("Client IP address")),
497
+ userAgent: nullable(str("Client user agent")),
498
+ deviceName: nullable(str("Device name")),
499
+ createdAt: strFormat("date-time", "Session creation time"),
500
+ lastActiveAt: nullable(strFormat("date-time", "Last activity time"))
501
+ },
502
+ "id",
503
+ "createdAt"
504
+ );
505
+ var CreateUserInput = obj(
506
+ {
507
+ email: email("User email"),
508
+ // enforced format (ReDoS-safe pattern), not annotation-only
509
+ name: str("Display name"),
510
+ password: str("User password"),
511
+ isActive: bool("Set active status (default true)")
512
+ },
513
+ "email",
514
+ "name"
515
+ );
516
+ var ErrorResponse = obj(
517
+ {
518
+ code: str("Error code (e.g. UNAUTHORIZED)"),
519
+ message: str("Human-readable message"),
520
+ statusCode: int("HTTP status code")
521
+ },
522
+ "code",
523
+ "message",
524
+ "statusCode"
525
+ );
526
+ var LoginIdentifier = obj(
527
+ {
528
+ id: id("Identifier ID"),
529
+ userId: id("User ID"),
530
+ type: enums("email", "phone", "username"),
531
+ value: str("Identifier value")
532
+ },
533
+ "id",
534
+ "userId",
535
+ "type",
536
+ "value"
537
+ );
538
+ var authComponents = defineComponents({
539
+ User,
540
+ AuthChallenge,
541
+ AuthResult,
542
+ AuthTokenPair,
543
+ SessionInfo,
544
+ CreateUserInput,
545
+ ErrorResponse,
546
+ LoginIdentifier
547
+ });
548
+ var authComponentSchemas = authComponents.components;
549
+ var authRef = authComponents.ref;
550
+ var authEndpoints = {
551
+ login: endpoint("POST", "/auth/login").summary("Login with credentials").tags("Auth").security("none").body(obj(
552
+ {
553
+ identifier: str("Email, username, or phone"),
554
+ password: str("User password"),
555
+ trustedDeviceToken: str("Opaque trusted-device token previously returned after two-factor verification")
556
+ },
557
+ "identifier",
558
+ "password"
559
+ )).response(200, "Login successful", authRef("AuthResult")).response(401, "Invalid credentials", authRef("ErrorResponse")).handler("login").build(),
560
+ verifyTwoFactor: endpoint("POST", "/auth/2fa/verify").summary("Complete a pending two-factor challenge").tags("Auth", "Two-Factor").security("none").body(obj(
561
+ {
562
+ continuationToken: str("Single-use auth continuation token"),
563
+ code: str("TOTP or backup code"),
564
+ rememberDevice: bool("Issue an opaque trusted-device token after successful verification")
565
+ },
566
+ "continuationToken",
567
+ "code"
568
+ )).response(200, "Authentication result", authRef("AuthResult")).response(400, "Two-factor plugin unavailable", authRef("ErrorResponse")).response(401, "Invalid continuation or verification code", authRef("ErrorResponse")).handler("verifyTwoFactor").build(),
569
+ verifyMagicLink: endpoint("POST", "/auth/magic-link/verify").summary("Verify a magic-link token").tags("Auth", "Magic Link").security("none").body(obj({ token: str("Raw magic-link token") }, "token")).response(200, "Authentication result", authRef("AuthResult")).response(400, "Magic-link plugin unavailable", authRef("ErrorResponse")).response(404, "Invalid or expired magic link", authRef("ErrorResponse")).handler("verifyMagicLink").build(),
570
+ createUser: endpoint("POST", "/auth/register").summary("Create a new user").tags("Auth").security("none").body(CreateUserInput).response(201, "User created", authRef("User")).response(409, "Email already exists", authRef("ErrorResponse")).handler("createUser").build(),
571
+ refresh: endpoint("POST", "/auth/refresh").summary("Refresh access token").tags("Auth").security("none").body(obj({ refreshToken: str("Current refresh token") }, "refreshToken")).response(200, "Tokens refreshed", authRef("AuthTokenPair")).response(401, "Invalid or expired refresh token", authRef("ErrorResponse")).handler("refresh").build(),
572
+ logout: endpoint("POST", "/auth/logout").summary("Logout and revoke refresh token").tags("Auth").security("none").body(obj({ refreshToken: str("Refresh token to revoke") }, "refreshToken")).response(200, "Logged out", obj({ ok: bool() }, "ok")).handler("logout").build(),
573
+ me: endpoint("GET", "/auth/me").summary("Get current user profile").tags("Auth").security("bearer").response(200, "Current user", authRef("User")).response(401, "Not authenticated", authRef("ErrorResponse")).handler("me").build(),
574
+ listSessions: endpoint("GET", "/auth/sessions").summary("List active sessions").tags("Auth").security("bearer").response(200, "Active sessions", arr(authRef("SessionInfo"))).response(401, "Not authenticated", authRef("ErrorResponse")).handler("listSessions").build(),
575
+ revokeSession: endpoint("DELETE", "/auth/sessions/:id").summary("Revoke a specific session").tags("Auth").security("bearer").params(obj({ id: id("Session/token ID") }, "id")).response(200, "Session revoked", obj({ ok: bool() }, "ok")).response(401, "Not authenticated", authRef("ErrorResponse")).handler("revokeSession").build(),
576
+ revokeAllOtherSessions: endpoint("DELETE", "/auth/sessions").summary("Revoke all other sessions").description("Revokes all active sessions except the current one. Requires the current token ID.").tags("Auth").security("bearer").body(obj({ currentTokenId: id("Current token ID to keep") }, "currentTokenId")).response(200, "Other sessions revoked", obj({ ok: bool() }, "ok")).response(401, "Not authenticated", authRef("ErrorResponse")).handler("revokeAllOtherSessions").build(),
577
+ addLoginIdentifier: endpoint("POST", "/auth/identifiers").summary("Add a login identifier").tags("Auth").security("bearer").body(obj(
578
+ {
579
+ type: enums("email", "phone", "username"),
580
+ value: str("Identifier value")
581
+ },
582
+ "type",
583
+ "value"
584
+ )).response(200, "Identifier added", obj({ ok: bool() }, "ok")).response(401, "Not authenticated", authRef("ErrorResponse")).handler("addLoginIdentifier").build(),
585
+ removeLoginIdentifier: endpoint("DELETE", "/auth/identifiers").summary("Remove a login identifier").tags("Auth").security("bearer").body(obj(
586
+ {
587
+ type: enums("email", "phone", "username"),
588
+ value: str("Identifier value")
589
+ },
590
+ "type",
591
+ "value"
592
+ )).response(200, "Identifier removed", obj({ ok: bool() }, "ok")).response(401, "Not authenticated", authRef("ErrorResponse")).handler("removeLoginIdentifier").build(),
593
+ getLoginIdentifiers: endpoint("GET", "/auth/identifiers").summary("List login identifiers").tags("Auth").security("bearer").response(200, "Login identifiers", arr(authRef("LoginIdentifier"))).response(401, "Not authenticated", authRef("ErrorResponse")).handler("getLoginIdentifiers").build(),
594
+ impersonate: endpoint("POST", "/auth/impersonate").summary("Impersonate a user").description("Issue a short-lived, non-renewable token to act as another user. Requires fortress:impersonate permission.").tags("Auth").security("bearer").permission("fortress", "impersonate").body(obj(
595
+ {
596
+ targetUserId: id("User to impersonate"),
597
+ reason: str("Reason for impersonation"),
598
+ expirySeconds: int("Token expiry in seconds (default 3600)")
599
+ },
600
+ "targetUserId"
601
+ )).response(200, "Impersonation token issued", authRef("AuthResult")).response(401, "Not authenticated", authRef("ErrorResponse")).response(404, "Target user not found", authRef("ErrorResponse")).handler("impersonate").build()
602
+ };
603
+
604
+ // src/core/errors.ts
605
+ var FortressError = class extends Error {
606
+ code;
607
+ statusCode;
608
+ retryAfter;
609
+ details;
610
+ /** RFC 6749 §5.2 / §4.1.2.1 machine code. Set by `Errors.oauth()`. */
611
+ oauthError;
612
+ /** Human-readable description for the OAuth `error_description` field. */
613
+ oauthDescription;
614
+ /** Optional URI for the OAuth `error_uri` field (§5.2). */
615
+ oauthErrorUri;
616
+ constructor(code, message, statusCode, options) {
617
+ super(message, { cause: options?.cause });
618
+ this.code = code;
619
+ this.statusCode = statusCode;
620
+ this.retryAfter = options?.retryAfter;
621
+ this.details = options?.details;
622
+ this.oauthError = options?.oauthError;
623
+ this.oauthDescription = options?.oauthDescription;
624
+ this.oauthErrorUri = options?.oauthErrorUri;
625
+ }
626
+ toJSON() {
627
+ return {
628
+ code: this.code,
629
+ message: this.message,
630
+ statusCode: this.statusCode,
631
+ ...this.details !== void 0 && { details: this.details }
632
+ };
633
+ }
634
+ };
635
+ var Errors = {
636
+ unauthorized: (message = "Unauthorized") => new FortressError("UNAUTHORIZED", message, 401),
637
+ tokenReuse: () => new FortressError("TOKEN_REUSE", "Token reuse detected", 401),
638
+ sessionIdleTimeout: () => new FortressError("SESSION_IDLE_TIMEOUT", "Session idle timeout exceeded", 401),
639
+ sessionAbsoluteTimeout: () => new FortressError("SESSION_ABSOLUTE_TIMEOUT", "Session absolute timeout exceeded", 401),
640
+ forbidden: (message = "Forbidden") => new FortressError("FORBIDDEN", message, 403),
641
+ badRequest: (message = "Bad request") => new FortressError("BAD_REQUEST", message, 400),
642
+ notFound: (message = "Not found") => new FortressError("NOT_FOUND", message, 404),
643
+ conflict: (message = "Conflict", options) => new FortressError("CONFLICT", message, 409, options),
644
+ unprocessable: (message = "Unprocessable entity", options) => new FortressError("UNPROCESSABLE_ENTITY", message, 422, options),
645
+ rateLimited: (retryAfter) => new FortressError("RATE_LIMITED", "Too many requests", 429, { retryAfter }),
646
+ database: (message = "Database error", cause) => new FortressError("DATABASE_ERROR", message, 500, { cause }),
647
+ serviceUnavailable: (message = "Service unavailable", options) => new FortressError("SERVICE_UNAVAILABLE", message, 503, options),
648
+ validationError: (issues) => new FortressError("VALIDATION_ERROR", "Validation failed", 422, { details: issues }),
649
+ /**
650
+ * RFC 6749 §5.2 / §4.1.2.1 OAuth error.
651
+ *
652
+ * The HTTP error mapper detects `oauthError` and emits the OAuth-spec
653
+ * JSON body `{ error, error_description, error_uri? }` instead of the
654
+ * default fortress `{ code, message }` shape, so strict OAuth clients
655
+ * (Moodle, openid-client, Spring Security, etc.) can switch behaviour
656
+ * on the machine-readable `error` field.
657
+ *
658
+ * Status is inferred from the OAuth code per the spec table:
659
+ * - `invalid_client` → 401
660
+ * - everything else → 400
661
+ */
662
+ oauth: (error, description, options) => {
663
+ const status = options?.status ?? (error === "invalid_client" ? 401 : 400);
664
+ const code = status === 401 ? "UNAUTHORIZED" : "BAD_REQUEST";
665
+ return new FortressError(code, description ?? error, status, {
666
+ oauthError: error,
667
+ oauthDescription: description,
668
+ oauthErrorUri: options?.errorUri,
669
+ cause: options?.cause
670
+ });
671
+ },
672
+ /**
673
+ * Reconstruct a {@link FortressError} from a JSON error body emitted by
674
+ * `errorToResponse`. Used by the in-process `fortress.call.*` client to
675
+ * convert non-2xx responses into typed throws that mirror what a direct
676
+ * service-method call would produce.
677
+ *
678
+ * Maps by HTTP status when the body doesn't carry a recognizable
679
+ * `{ code, message }` payload, so network errors and opaque upstream
680
+ * failures still become structured `FortressError`s.
681
+ */
682
+ fromHttpResponse: (status, body) => {
683
+ const payload = body && typeof body === "object" ? body : {};
684
+ const message = typeof payload.message === "string" ? payload.message : `HTTP ${status}`;
685
+ const code = typeof payload.code === "string" && isFortressErrorCode(payload.code) ? payload.code : statusToErrorCode(status);
686
+ return new FortressError(code, message, status, { details: payload.details });
687
+ }
688
+ };
689
+ function isFortressErrorCode(code) {
690
+ 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";
691
+ }
692
+ function statusToErrorCode(status) {
693
+ if (status === 401)
694
+ return "UNAUTHORIZED";
695
+ if (status === 403)
696
+ return "FORBIDDEN";
697
+ if (status === 404)
698
+ return "NOT_FOUND";
699
+ if (status === 409)
700
+ return "CONFLICT";
701
+ if (status === 422)
702
+ return "UNPROCESSABLE_ENTITY";
703
+ if (status === 429)
704
+ return "RATE_LIMITED";
705
+ if (status === 503)
706
+ return "SERVICE_UNAVAILABLE";
707
+ if (status >= 500)
708
+ return "DATABASE_ERROR";
709
+ return "BAD_REQUEST";
710
+ }
711
+
712
+ // src/core/iam/iam-endpoints.ts
713
+ var Role = obj(
714
+ {
715
+ id: id("Role ID"),
716
+ name: str("Role name"),
717
+ description: nullable(str("Role description")),
718
+ isSystem: bool("Whether this is a system role")
719
+ },
720
+ "id",
721
+ "name"
722
+ );
723
+ var Group = obj(
724
+ {
725
+ id: id("Group ID"),
726
+ name: str("Group name"),
727
+ description: nullable(str("Group description"))
728
+ },
729
+ "id",
730
+ "name"
731
+ );
732
+ var Permission = obj(
733
+ {
734
+ id: id("Permission ID"),
735
+ resource: str("Resource name"),
736
+ action: str("Action name"),
737
+ effect: enums("ALLOW", "DENY"),
738
+ conditions: arr(obj({
739
+ field: str("Condition field"),
740
+ operator: enums("eq", "neq", "in", "startsWith"),
741
+ value: str("Condition value")
742
+ }), "Permission conditions"),
743
+ description: nullable(str("Permission description"))
744
+ },
745
+ "id",
746
+ "resource",
747
+ "action",
748
+ "effect"
749
+ );
750
+ var PermissionInput = obj(
751
+ {
752
+ resource: str("Resource name"),
753
+ action: str("Action name"),
754
+ effect: enums("ALLOW", "DENY"),
755
+ conditions: arr(obj({
756
+ field: str("Condition field"),
757
+ operator: enums("eq", "neq", "in", "startsWith"),
758
+ value: str("Condition value")
759
+ }))
760
+ },
761
+ "resource",
762
+ "action"
763
+ );
764
+ var ServiceAccount = obj(
765
+ {
766
+ id: id("Service account ID"),
767
+ name: str("Machine identifier \u2014 immutable after creation"),
768
+ displayName: nullable(str("Human-readable label")),
769
+ description: nullable(str("Free-form description")),
770
+ isActive: bool("Whether the account can authenticate and resolve permissions"),
771
+ createdAt: str("ISO 8601 creation timestamp"),
772
+ updatedAt: str("ISO 8601 update timestamp")
773
+ },
774
+ "id",
775
+ "name",
776
+ "isActive"
777
+ );
778
+ var iamComponents = defineComponents({
779
+ Role,
780
+ Group,
781
+ Permission,
782
+ PermissionInput,
783
+ ServiceAccount
784
+ });
785
+ var iamComponentSchemas = iamComponents.components;
786
+ var iamRef = iamComponents.ref;
787
+ var iamEndpoints = {
788
+ // ── Resources ──
789
+ getResources: endpoint("GET", "/iam/resources").summary("List all available resources").tags("IAM", "Resources").security("bearer").permission("fortress", "viewResources").response(200, "Available resources with their actions", obj({
790
+ resources: recordOf(obj({
791
+ actions: arr(str("Action name"), "Available actions"),
792
+ description: str("Resource description")
793
+ }), "Map of resource name to definition")
794
+ }, "resources")).response(401, "Not authenticated", authRef("ErrorResponse")).handler("getResources").build(),
795
+ // ── Roles ──
796
+ getRoles: endpoint("GET", "/iam/roles").summary("List all roles").tags("IAM", "Roles").security("bearer").permission("fortress", "viewRoles").response(200, "All roles", arr(iamRef("Role"))).response(401, "Not authenticated", authRef("ErrorResponse")).handler("getRoles").build(),
797
+ createRole: endpoint("POST", "/iam/roles").summary("Create a role").tags("IAM", "Roles").security("bearer").permission("fortress", "createRole").body(obj(
798
+ {
799
+ name: str("Role name"),
800
+ permissions: arr(iamRef("PermissionInput"), "Permissions to assign"),
801
+ description: str("Role description")
802
+ },
803
+ "name",
804
+ "permissions"
805
+ )).response(201, "Role created", iamRef("Role")).response(401, "Not authenticated", authRef("ErrorResponse")).handler("createRole").build(),
806
+ deleteRole: endpoint("DELETE", "/iam/roles/:id").summary("Delete a role").tags("IAM", "Roles").security("bearer").permission("fortress", "deleteRole").params(obj({ id: id("Role ID") }, "id")).response(200, "Role deleted", obj({ ok: bool() }, "ok")).response(400, "Cannot delete system role", authRef("ErrorResponse")).response(401, "Not authenticated", authRef("ErrorResponse")).handler("deleteRole").build(),
807
+ // ── Role Bindings ──
808
+ bindRoleToUser: endpoint("POST", "/iam/roles/:id/bind/user").summary("Bind role to a user").tags("IAM", "Roles").security("bearer").permission("fortress", "bindRole").params(obj({ id: id("Role ID") }, "id")).body(obj(
809
+ { userId: id("User ID"), tenantId: str("Tenant ID (optional)") },
810
+ "userId"
811
+ )).response(200, "Role bound to user", obj({ ok: bool() }, "ok")).response(401, "Not authenticated", authRef("ErrorResponse")).handler("bindRoleToUser").build(),
812
+ bindRoleToGroup: endpoint("POST", "/iam/roles/:id/bind/group").summary("Bind role to a group").tags("IAM", "Roles").security("bearer").permission("fortress", "bindRole").params(obj({ id: id("Role ID") }, "id")).body(obj(
813
+ { groupId: id("Group ID"), tenantId: str("Tenant ID (optional)") },
814
+ "groupId"
815
+ )).response(200, "Role bound to group", obj({ ok: bool() }, "ok")).response(401, "Not authenticated", authRef("ErrorResponse")).handler("bindRoleToGroup").build(),
816
+ unbindRole: endpoint("DELETE", "/iam/roles/:id/bind").summary("Unbind a role").tags("IAM", "Roles").security("bearer").permission("fortress", "unbindRole").params(obj({ id: id("Role ID") }, "id")).body(obj(
817
+ {
818
+ subjectType: enums("USER", "GROUP", "SERVICE_ACCOUNT"),
819
+ subjectId: id("Subject ID"),
820
+ tenantId: str("Tenant ID (optional)")
821
+ },
822
+ "subjectType",
823
+ "subjectId"
824
+ )).response(200, "Role unbound", obj({ ok: bool() }, "ok")).response(401, "Not authenticated", authRef("ErrorResponse")).handler("unbindRole").build(),
825
+ // ── Groups ──
826
+ createGroup: endpoint("POST", "/iam/groups").summary("Create a group").tags("IAM", "Groups").security("bearer").permission("fortress", "createGroup").body(obj(
827
+ { name: str("Group name"), description: str("Group description") },
828
+ "name"
829
+ )).response(201, "Group created", iamRef("Group")).response(401, "Not authenticated", authRef("ErrorResponse")).handler("createGroup").build(),
830
+ addUserToGroup: endpoint("POST", "/iam/groups/:id/users").summary("Add user to group").tags("IAM", "Groups").security("bearer").permission("fortress", "manageGroup").params(obj({ id: id("Group ID") }, "id")).body(obj({ userId: id("User ID") }, "userId")).response(200, "User added to group", obj({ ok: bool() }, "ok")).response(401, "Not authenticated", authRef("ErrorResponse")).handler("addUserToGroup").build(),
831
+ removeUserFromGroup: endpoint("DELETE", "/iam/groups/:id/users/:userId").summary("Remove user from group").tags("IAM", "Groups").security("bearer").permission("fortress", "manageGroup").params(obj({ id: id("Group ID"), userId: id("User ID") }, "id", "userId")).response(200, "User removed from group", obj({ ok: bool() }, "ok")).response(401, "Not authenticated", authRef("ErrorResponse")).handler("removeUserFromGroup").build(),
832
+ // ── Permissions ──
833
+ getUserPermissions: endpoint("GET", "/iam/users/:id/permissions").summary("Get user permissions").tags("IAM", "Permissions").security("bearer").permission("fortress", "viewPermissions").params(obj({ id: id("User ID") }, "id")).query(obj({ tenantId: str("Tenant ID (optional)") })).response(200, "User permissions", arr(iamRef("Permission"))).response(401, "Not authenticated", authRef("ErrorResponse")).handler("getUserPermissions").build(),
834
+ checkPermission: endpoint("POST", "/iam/check").summary("Check if user has permission").tags("IAM", "Permissions").security("bearer").permission("fortress", "viewPermissions").body(obj(
835
+ {
836
+ userId: id("User ID"),
837
+ resource: str("Resource name"),
838
+ action: str("Action name"),
839
+ context: record("Permission context")
840
+ },
841
+ "userId",
842
+ "resource",
843
+ "action"
844
+ )).response(200, "Permission check result", obj({ allowed: bool("Whether permission is granted") }, "allowed")).response(401, "Not authenticated", authRef("ErrorResponse")).handler("checkPermission").build(),
845
+ bindPermissionToUser: endpoint("POST", "/iam/permissions/bind/user").summary("Bind permission directly to a user").tags("IAM", "Permissions").security("bearer").permission("fortress", "managePermissions").body(obj(
846
+ {
847
+ userId: id("User ID"),
848
+ permission: iamRef("PermissionInput"),
849
+ tenantId: str("Tenant ID (optional)")
850
+ },
851
+ "userId",
852
+ "permission"
853
+ )).response(200, "Permission bound", obj({ ok: bool() }, "ok")).response(401, "Not authenticated", authRef("ErrorResponse")).handler("bindPermissionToUser").build(),
854
+ bindPermissionToGroup: endpoint("POST", "/iam/permissions/bind/group").summary("Bind permission directly to a group").tags("IAM", "Permissions").security("bearer").permission("fortress", "managePermissions").body(obj(
855
+ {
856
+ groupId: id("Group ID"),
857
+ permission: iamRef("PermissionInput"),
858
+ tenantId: str("Tenant ID (optional)")
859
+ },
860
+ "groupId",
861
+ "permission"
862
+ )).response(200, "Permission bound", obj({ ok: bool() }, "ok")).response(401, "Not authenticated", authRef("ErrorResponse")).handler("bindPermissionToGroup").build(),
863
+ unbindPermissionFromUser: endpoint("DELETE", "/iam/permissions/bind/user").summary("Unbind permission from a user").tags("IAM", "Permissions").security("bearer").permission("fortress", "managePermissions").body(obj(
864
+ {
865
+ userId: id("User ID"),
866
+ permissionId: id("Permission ID"),
867
+ tenantId: str("Tenant ID (optional)")
868
+ },
869
+ "userId",
870
+ "permissionId"
871
+ )).response(200, "Permission unbound", obj({ ok: bool() }, "ok")).response(401, "Not authenticated", authRef("ErrorResponse")).handler("unbindPermissionFromUser").build(),
872
+ unbindPermissionFromGroup: endpoint("DELETE", "/iam/permissions/bind/group").summary("Unbind permission from a group").tags("IAM", "Permissions").security("bearer").permission("fortress", "managePermissions").body(obj(
873
+ {
874
+ groupId: id("Group ID"),
875
+ permissionId: id("Permission ID"),
876
+ tenantId: str("Tenant ID (optional)")
877
+ },
878
+ "groupId",
879
+ "permissionId"
880
+ )).response(200, "Permission unbound", obj({ ok: bool() }, "ok")).response(401, "Not authenticated", authRef("ErrorResponse")).handler("unbindPermissionFromGroup").build(),
881
+ // ── Service Accounts ──
882
+ createServiceAccount: endpoint("POST", "/iam/service-accounts").summary("Create a service account").description("Create a non-human IAM principal. Service accounts hold roles and direct permissions just like users, but have no sessions, passwords, or group memberships. The `name` is immutable after creation.").tags("IAM", "Service Accounts").security("bearer").permission("fortress", "createServiceAccount").body(obj(
883
+ {
884
+ name: str("Machine identifier (immutable)"),
885
+ displayName: str("Human-readable label"),
886
+ description: str("Free-form description")
887
+ },
888
+ "name"
889
+ )).response(201, "Service account created", iamRef("ServiceAccount")).response(400, "Bad request", authRef("ErrorResponse")).response(401, "Not authenticated", authRef("ErrorResponse")).handler("createServiceAccount").build(),
890
+ listServiceAccounts: endpoint("GET", "/iam/service-accounts").summary("List service accounts").tags("IAM", "Service Accounts").security("bearer").permission("fortress", "viewServiceAccounts").query(obj({
891
+ limit: int("Page size (default 50)"),
892
+ offset: int("Offset from the start of the list")
893
+ })).response(200, "Service accounts", obj({
894
+ serviceAccounts: arr(iamRef("ServiceAccount")),
895
+ total: int("Total service accounts")
896
+ }, "serviceAccounts", "total")).response(401, "Not authenticated", authRef("ErrorResponse")).handler("listServiceAccounts").build(),
897
+ getServiceAccount: endpoint("GET", "/iam/service-accounts/:id").summary("Get a service account by ID").tags("IAM", "Service Accounts").security("bearer").permission("fortress", "viewServiceAccounts").params(obj({ id: id("Service account ID") }, "id")).response(200, "Service account", iamRef("ServiceAccount")).response(401, "Not authenticated", authRef("ErrorResponse")).response(404, "Not found", authRef("ErrorResponse")).handler("getServiceAccount").build(),
898
+ updateServiceAccount: endpoint("PATCH", "/iam/service-accounts/:id").summary("Update a service account").description("Update displayName, description, or isActive. The `name` field is immutable \u2014 to rename, delete and recreate.").tags("IAM", "Service Accounts").security("bearer").permission("fortress", "manageServiceAccount").params(obj({ id: id("Service account ID") }, "id")).body(obj({
899
+ displayName: nullable(str("New human-readable label")),
900
+ description: nullable(str("New description")),
901
+ isActive: bool("Whether the account is active")
902
+ })).response(200, "Service account updated", iamRef("ServiceAccount")).response(401, "Not authenticated", authRef("ErrorResponse")).response(404, "Not found", authRef("ErrorResponse")).handler("updateServiceAccount").build(),
903
+ deleteServiceAccount: endpoint("DELETE", "/iam/service-accounts/:id").summary("Delete a service account").description("Hard-deletes the service account and cascades to role bindings, direct permission bindings, and (via plugin observer) api keys owned by the account.").tags("IAM", "Service Accounts").security("bearer").permission("fortress", "manageServiceAccount").params(obj({ id: id("Service account ID") }, "id")).response(200, "Service account deleted", obj({ ok: bool() }, "ok")).response(401, "Not authenticated", authRef("ErrorResponse")).response(404, "Not found", authRef("ErrorResponse")).handler("deleteServiceAccount").build(),
904
+ getServiceAccountPermissions: endpoint("GET", "/iam/service-accounts/:id/permissions").summary("Get effective permissions for a service account").tags("IAM", "Service Accounts", "Permissions").security("bearer").permission("fortress", "viewPermissions").params(obj({ id: id("Service account ID") }, "id")).query(obj({ tenantId: str("Tenant ID (optional)") })).response(200, "Service account permissions", arr(iamRef("Permission"))).response(401, "Not authenticated", authRef("ErrorResponse")).handler("getServiceAccountPermissions").build(),
905
+ bindRoleToServiceAccount: endpoint("POST", "/iam/roles/:id/bind/service-account").summary("Bind role to a service account").tags("IAM", "Roles", "Service Accounts").security("bearer").permission("fortress", "bindRole").params(obj({ id: id("Role ID") }, "id")).body(obj(
906
+ { serviceAccountId: id("Service account ID"), tenantId: str("Tenant ID (optional)") },
907
+ "serviceAccountId"
908
+ )).response(200, "Role bound to service account", obj({ ok: bool() }, "ok")).response(401, "Not authenticated", authRef("ErrorResponse")).handler("bindRoleToServiceAccount").build(),
909
+ unbindRoleFromServiceAccount: endpoint("DELETE", "/iam/roles/:id/bind/service-account").summary("Unbind role from a service account").tags("IAM", "Roles", "Service Accounts").security("bearer").permission("fortress", "unbindRole").params(obj({ id: id("Role ID") }, "id")).body(obj(
910
+ { serviceAccountId: id("Service account ID"), tenantId: str("Tenant ID (optional)") },
911
+ "serviceAccountId"
912
+ )).response(200, "Role unbound", obj({ ok: bool() }, "ok")).response(401, "Not authenticated", authRef("ErrorResponse")).handler("unbindRoleFromServiceAccount").build(),
913
+ bindPermissionToServiceAccount: endpoint("POST", "/iam/permissions/bind/service-account").summary("Bind permission directly to a service account").tags("IAM", "Permissions", "Service Accounts").security("bearer").permission("fortress", "managePermissions").body(obj(
914
+ {
915
+ serviceAccountId: id("Service account ID"),
916
+ permission: iamRef("PermissionInput"),
917
+ tenantId: str("Tenant ID (optional)")
918
+ },
919
+ "serviceAccountId",
920
+ "permission"
921
+ )).response(200, "Permission bound", obj({ ok: bool() }, "ok")).response(401, "Not authenticated", authRef("ErrorResponse")).handler("bindPermissionToServiceAccount").build(),
922
+ unbindPermissionFromServiceAccount: endpoint("DELETE", "/iam/permissions/bind/service-account").summary("Unbind permission from a service account").tags("IAM", "Permissions", "Service Accounts").security("bearer").permission("fortress", "managePermissions").body(obj(
923
+ {
924
+ serviceAccountId: id("Service account ID"),
925
+ permissionId: id("Permission ID"),
926
+ tenantId: str("Tenant ID (optional)")
927
+ },
928
+ "serviceAccountId",
929
+ "permissionId"
930
+ )).response(200, "Permission unbound", obj({ ok: bool() }, "ok")).response(401, "Not authenticated", authRef("ErrorResponse")).handler("unbindPermissionFromServiceAccount").build()
931
+ };
932
+
933
+ // src/core/iam/resource-sync.ts
934
+ async function pullResources(db) {
935
+ const resources = await db.findMany({
936
+ model: "resource",
937
+ sortBy: { field: "name", direction: "asc" }
938
+ });
939
+ const result = { resources: {} };
940
+ for (const resource of resources) {
941
+ const permissions = await db.findMany({
942
+ model: "permission",
943
+ where: [{ field: "resource", operator: "=", value: resource.name }],
944
+ sortBy: { field: "id", direction: "asc" }
945
+ });
946
+ result.resources[resource.name] = {
947
+ actions: permissions.map((p) => p.action),
948
+ ...resource.description ? { description: resource.description } : {}
949
+ };
950
+ }
951
+ return result;
952
+ }
953
+
954
+ // src/plugins/api-key/core.ts
955
+ function toInfo(r) {
956
+ return {
957
+ id: r.id,
958
+ name: r.name,
959
+ keyPrefix: r.keyPrefix,
960
+ scopes: r.scopes ? JSON.parse(r.scopes) : null,
961
+ expiresAt: r.expiresAt,
962
+ lastUsedAt: r.lastUsedAt,
963
+ createdAt: r.createdAt
964
+ };
965
+ }
966
+ function subjectWhere(subject) {
967
+ return [
968
+ { field: "subjectType", operator: "=", value: subject.type },
969
+ { field: "subjectId", operator: "=", value: subject.id }
970
+ ];
971
+ }
972
+ async function listKeysForSubject(db, subject) {
973
+ const records = await db.findMany({
974
+ model: "api_key",
975
+ where: [
976
+ ...subjectWhere(subject),
977
+ { field: "isRevoked", operator: "=", value: false }
978
+ ]
979
+ });
980
+ return records.map(toInfo);
981
+ }
982
+ async function revokeKeyAsAdmin(db, keyId) {
983
+ const record2 = await db.findOne({
984
+ model: "api_key",
985
+ where: [{ field: "id", operator: "=", value: keyId }]
986
+ });
987
+ if (!record2)
988
+ throw Errors.notFound("API key not found");
989
+ await db.update({
990
+ model: "api_key",
991
+ where: [{ field: "id", operator: "=", value: keyId }],
992
+ data: { isRevoked: true }
993
+ });
994
+ }
995
+
996
+ // src/plugins/admin/index.ts
997
+ function collectPermissions(endpoints) {
998
+ const seen = /* @__PURE__ */ new Set();
999
+ const result = [];
1000
+ for (const ep of endpoints) {
1001
+ const perm = ep.meta?.permission;
1002
+ if (!perm)
1003
+ continue;
1004
+ const key = `${perm.resource}:${perm.action}`;
1005
+ if (seen.has(key))
1006
+ continue;
1007
+ seen.add(key);
1008
+ result.push(perm);
1009
+ }
1010
+ return result;
1011
+ }
1012
+ var userRef = { $ref: "#/components/schemas/User" };
1013
+ var permissionRef = { $ref: "#/components/schemas/Permission" };
1014
+ var permissionInputRef = { $ref: "#/components/schemas/PermissionInput" };
1015
+ var errorRef = { $ref: "#/components/schemas/ErrorResponse" };
1016
+ function intSchema(desc) {
1017
+ return { type: "integer", description: desc };
1018
+ }
1019
+ function strSchema(desc) {
1020
+ return { type: "string", description: desc };
1021
+ }
1022
+ function boolSchema(desc) {
1023
+ return { type: "boolean", description: desc };
1024
+ }
1025
+ var encoder = new TextEncoder();
1026
+ function timingSafeEqual(a, b) {
1027
+ const left = encoder.encode(a);
1028
+ const right = encoder.encode(b);
1029
+ const len = Math.max(left.length, right.length);
1030
+ let diff = left.length ^ right.length;
1031
+ for (let i = 0; i < len; i++)
1032
+ diff |= (left[i] ?? 0) ^ (right[i] ?? 0);
1033
+ return diff === 0;
1034
+ }
1035
+ function requireId(v, name) {
1036
+ if (v == null || v === "")
1037
+ throw Errors.badRequest(`${name} is required`);
1038
+ if (typeof v === "string")
1039
+ return v;
1040
+ if (typeof v === "number" && Number.isFinite(v))
1041
+ return String(v);
1042
+ throw Errors.badRequest(`${name} must be a string or number`);
1043
+ }
1044
+ var adminAuthEndpoints = [
1045
+ // GET /auth/users — list users (paginated, searchable)
1046
+ {
1047
+ method: "GET",
1048
+ path: "/auth/users",
1049
+ handler: "listUsers",
1050
+ meta: {
1051
+ summary: "List users",
1052
+ description: "List all users with pagination and optional search",
1053
+ tags: ["Auth", "Admin"],
1054
+ security: ["bearer"],
1055
+ permission: { resource: "fortress", action: "viewUsers" }
1056
+ },
1057
+ input: {
1058
+ query: {
1059
+ type: "object",
1060
+ properties: {
1061
+ limit: intSchema("Max results (default 50)"),
1062
+ offset: intSchema("Skip results (default 0)"),
1063
+ search: strSchema("Search by email"),
1064
+ sortBy: strSchema("Sort field (default: id)"),
1065
+ sortDirection: { type: "string", enum: ["asc", "desc"], description: "Sort direction" }
1066
+ }
1067
+ }
1068
+ },
1069
+ responses: {
1070
+ 200: {
1071
+ description: "User list",
1072
+ schema: {
1073
+ type: "object",
1074
+ properties: {
1075
+ users: { type: "array", items: userRef, description: "List of users" },
1076
+ total: intSchema("Total number of users")
1077
+ },
1078
+ required: ["users", "total"]
1079
+ }
1080
+ },
1081
+ 401: { description: "Not authenticated" },
1082
+ 403: { description: "Insufficient permissions" }
1083
+ }
1084
+ },
1085
+ // GET /auth/users/:id — get user by ID
1086
+ {
1087
+ method: "GET",
1088
+ path: "/auth/users/:id",
1089
+ handler: "getUserById",
1090
+ meta: {
1091
+ summary: "Get user by ID",
1092
+ tags: ["Auth", "Admin"],
1093
+ security: ["bearer"],
1094
+ permission: { resource: "fortress", action: "viewUsers" }
1095
+ },
1096
+ input: {
1097
+ params: {
1098
+ type: "object",
1099
+ properties: { id: intSchema("User ID") },
1100
+ required: ["id"]
1101
+ }
1102
+ },
1103
+ responses: {
1104
+ 200: { description: "User details", schema: userRef },
1105
+ 401: { description: "Not authenticated" },
1106
+ 403: { description: "Insufficient permissions" },
1107
+ 404: { description: "User not found", schema: errorRef }
1108
+ }
1109
+ },
1110
+ // PUT /auth/users/:id — update user
1111
+ {
1112
+ method: "PUT",
1113
+ path: "/auth/users/:id",
1114
+ handler: "updateUser",
1115
+ meta: {
1116
+ summary: "Update user",
1117
+ tags: ["Auth", "Admin"],
1118
+ security: ["bearer"],
1119
+ permission: { resource: "fortress", action: "manageUsers" }
1120
+ },
1121
+ input: {
1122
+ params: {
1123
+ type: "object",
1124
+ properties: { id: intSchema("User ID") },
1125
+ required: ["id"]
1126
+ },
1127
+ body: {
1128
+ type: "object",
1129
+ properties: {
1130
+ name: strSchema("Display name"),
1131
+ email: { type: "string", format: "email", description: "User email" },
1132
+ isActive: boolSchema("Account active status"),
1133
+ password: strSchema("New password (will be hashed)")
1134
+ }
1135
+ }
1136
+ },
1137
+ responses: {
1138
+ 200: { description: "Updated user", schema: userRef },
1139
+ 401: { description: "Not authenticated" },
1140
+ 403: { description: "Insufficient permissions" },
1141
+ 404: { description: "User not found", schema: errorRef },
1142
+ 409: { description: "Email already in use", schema: errorRef }
1143
+ }
1144
+ },
1145
+ // DELETE /auth/users/:id — delete user
1146
+ {
1147
+ method: "DELETE",
1148
+ path: "/auth/users/:id",
1149
+ handler: "deleteUser",
1150
+ meta: {
1151
+ summary: "Delete user",
1152
+ tags: ["Auth", "Admin"],
1153
+ security: ["bearer"],
1154
+ permission: { resource: "fortress", action: "manageUsers" }
1155
+ },
1156
+ input: {
1157
+ params: {
1158
+ type: "object",
1159
+ properties: { id: intSchema("User ID") },
1160
+ required: ["id"]
1161
+ }
1162
+ },
1163
+ responses: {
1164
+ 200: { description: "User deleted", schema: { type: "object", properties: { ok: boolSchema("Success") } } },
1165
+ 401: { description: "Not authenticated" },
1166
+ 403: { description: "Insufficient permissions" },
1167
+ 404: { description: "User not found", schema: errorRef }
1168
+ }
1169
+ },
1170
+ // POST /auth/users — admin-initiated user creation
1171
+ {
1172
+ method: "POST",
1173
+ path: "/auth/users",
1174
+ handler: "createUser",
1175
+ meta: {
1176
+ summary: "Create a user (admin)",
1177
+ description: "Admin-initiated user creation. Unlike /auth/register, requires authentication and manageUsers permission.",
1178
+ tags: ["Auth", "Admin"],
1179
+ security: ["bearer"],
1180
+ permission: { resource: "fortress", action: "manageUsers" }
1181
+ },
1182
+ input: {
1183
+ body: {
1184
+ type: "object",
1185
+ properties: {
1186
+ email: { type: "string", format: "email", description: "User email" },
1187
+ name: strSchema("Display name"),
1188
+ password: strSchema("User password"),
1189
+ isActive: boolSchema("Set active status (default true)")
1190
+ },
1191
+ required: ["email", "name"]
1192
+ }
1193
+ },
1194
+ responses: {
1195
+ 201: { description: "User created", schema: userRef },
1196
+ 401: { description: "Not authenticated" },
1197
+ 403: { description: "Insufficient permissions" },
1198
+ 409: { description: "Email already exists", schema: errorRef }
1199
+ }
1200
+ }
1201
+ ];
1202
+ var adminIamEndpoints = [
1203
+ // GET /iam/roles/:id — get role with permissions
1204
+ {
1205
+ method: "GET",
1206
+ path: "/iam/roles/:id",
1207
+ handler: "getRole",
1208
+ meta: {
1209
+ summary: "Get role with permissions",
1210
+ tags: ["IAM", "Admin"],
1211
+ security: ["bearer"],
1212
+ permission: { resource: "fortress", action: "viewRoles" }
1213
+ },
1214
+ input: {
1215
+ params: {
1216
+ type: "object",
1217
+ properties: { id: intSchema("Role ID") },
1218
+ required: ["id"]
1219
+ }
1220
+ },
1221
+ responses: {
1222
+ 200: {
1223
+ description: "Role with permissions",
1224
+ schema: {
1225
+ type: "object",
1226
+ properties: {
1227
+ id: intSchema("Role ID"),
1228
+ name: strSchema("Role name"),
1229
+ description: { type: "string", nullable: true, description: "Role description" },
1230
+ isSystem: boolSchema("Whether this is a system role"),
1231
+ permissions: { type: "array", items: permissionRef, description: "Role permissions" }
1232
+ },
1233
+ required: ["id", "name", "permissions"]
1234
+ }
1235
+ },
1236
+ 404: { description: "Role not found", schema: errorRef }
1237
+ }
1238
+ },
1239
+ // PUT /iam/roles/:id — update role
1240
+ {
1241
+ method: "PUT",
1242
+ path: "/iam/roles/:id",
1243
+ handler: "updateRole",
1244
+ meta: {
1245
+ summary: "Update role",
1246
+ tags: ["IAM", "Admin"],
1247
+ security: ["bearer"],
1248
+ permission: { resource: "fortress", action: "manageRoles" }
1249
+ },
1250
+ input: {
1251
+ params: {
1252
+ type: "object",
1253
+ properties: { id: intSchema("Role ID") },
1254
+ required: ["id"]
1255
+ },
1256
+ body: {
1257
+ type: "object",
1258
+ properties: {
1259
+ name: strSchema("Role name"),
1260
+ description: strSchema("Role description")
1261
+ }
1262
+ }
1263
+ },
1264
+ responses: {
1265
+ 200: { description: "Updated role", schema: { $ref: "#/components/schemas/Role" } },
1266
+ 400: { description: "Cannot update system role", schema: errorRef },
1267
+ 404: { description: "Role not found", schema: errorRef }
1268
+ }
1269
+ },
1270
+ // GET /iam/groups — list groups (paginated)
1271
+ {
1272
+ method: "GET",
1273
+ path: "/iam/groups",
1274
+ handler: "listGroups",
1275
+ meta: {
1276
+ summary: "List groups",
1277
+ tags: ["IAM", "Admin"],
1278
+ security: ["bearer"],
1279
+ permission: { resource: "fortress", action: "viewGroups" }
1280
+ },
1281
+ input: {
1282
+ query: {
1283
+ type: "object",
1284
+ properties: {
1285
+ limit: intSchema("Max results (default 50)"),
1286
+ offset: intSchema("Skip results (default 0)")
1287
+ }
1288
+ }
1289
+ },
1290
+ responses: {
1291
+ 200: {
1292
+ description: "Group list",
1293
+ schema: {
1294
+ type: "object",
1295
+ properties: {
1296
+ groups: { type: "array", items: { $ref: "#/components/schemas/Group" }, description: "List of groups" },
1297
+ total: intSchema("Total number of groups")
1298
+ },
1299
+ required: ["groups", "total"]
1300
+ }
1301
+ }
1302
+ }
1303
+ },
1304
+ // GET /iam/groups/:id — get group with members
1305
+ {
1306
+ method: "GET",
1307
+ path: "/iam/groups/:id",
1308
+ handler: "getGroup",
1309
+ meta: {
1310
+ summary: "Get group with members",
1311
+ tags: ["IAM", "Admin"],
1312
+ security: ["bearer"],
1313
+ permission: { resource: "fortress", action: "viewGroups" }
1314
+ },
1315
+ input: {
1316
+ params: {
1317
+ type: "object",
1318
+ properties: { id: intSchema("Group ID") },
1319
+ required: ["id"]
1320
+ }
1321
+ },
1322
+ responses: {
1323
+ 200: {
1324
+ description: "Group with members",
1325
+ schema: {
1326
+ type: "object",
1327
+ properties: {
1328
+ id: intSchema("Group ID"),
1329
+ name: strSchema("Group name"),
1330
+ description: { type: "string", nullable: true, description: "Group description" },
1331
+ users: { type: "array", items: userRef, description: "Group members" }
1332
+ },
1333
+ required: ["id", "name", "users"]
1334
+ }
1335
+ },
1336
+ 404: { description: "Group not found", schema: errorRef }
1337
+ }
1338
+ },
1339
+ // PUT /iam/groups/:id — update group
1340
+ {
1341
+ method: "PUT",
1342
+ path: "/iam/groups/:id",
1343
+ handler: "updateGroup",
1344
+ meta: {
1345
+ summary: "Update group",
1346
+ tags: ["IAM", "Admin"],
1347
+ security: ["bearer"],
1348
+ permission: { resource: "fortress", action: "manageGroup" }
1349
+ },
1350
+ input: {
1351
+ params: {
1352
+ type: "object",
1353
+ properties: { id: intSchema("Group ID") },
1354
+ required: ["id"]
1355
+ },
1356
+ body: {
1357
+ type: "object",
1358
+ properties: {
1359
+ name: strSchema("Group name"),
1360
+ description: strSchema("Group description")
1361
+ }
1362
+ }
1363
+ },
1364
+ responses: {
1365
+ 200: { description: "Updated group", schema: { $ref: "#/components/schemas/Group" } },
1366
+ 404: { description: "Group not found", schema: errorRef }
1367
+ }
1368
+ },
1369
+ // DELETE /iam/groups/:id — delete group
1370
+ {
1371
+ method: "DELETE",
1372
+ path: "/iam/groups/:id",
1373
+ handler: "deleteGroup",
1374
+ meta: {
1375
+ summary: "Delete group",
1376
+ tags: ["IAM", "Admin"],
1377
+ security: ["bearer"],
1378
+ permission: { resource: "fortress", action: "manageGroup" }
1379
+ },
1380
+ input: {
1381
+ params: {
1382
+ type: "object",
1383
+ properties: { id: intSchema("Group ID") },
1384
+ required: ["id"]
1385
+ }
1386
+ },
1387
+ responses: {
1388
+ 200: { description: "Group deleted", schema: { type: "object", properties: { ok: boolSchema("Success") } } },
1389
+ 404: { description: "Group not found", schema: errorRef }
1390
+ }
1391
+ },
1392
+ // GET /iam/groups/:id/users — list group members
1393
+ {
1394
+ method: "GET",
1395
+ path: "/iam/groups/:id/users",
1396
+ handler: "getGroupUsers",
1397
+ meta: {
1398
+ summary: "List group members",
1399
+ tags: ["IAM", "Admin"],
1400
+ security: ["bearer"],
1401
+ permission: { resource: "fortress", action: "viewGroups" }
1402
+ },
1403
+ input: {
1404
+ params: {
1405
+ type: "object",
1406
+ properties: { id: intSchema("Group ID") },
1407
+ required: ["id"]
1408
+ }
1409
+ },
1410
+ responses: {
1411
+ 200: {
1412
+ description: "Group members",
1413
+ schema: { type: "array", items: userRef }
1414
+ }
1415
+ }
1416
+ },
1417
+ // GET /iam/permissions — list all permissions
1418
+ {
1419
+ method: "GET",
1420
+ path: "/iam/permissions",
1421
+ handler: "listPermissions",
1422
+ meta: {
1423
+ summary: "List permissions",
1424
+ tags: ["IAM", "Admin"],
1425
+ security: ["bearer"],
1426
+ permission: { resource: "fortress", action: "viewPermissions" }
1427
+ },
1428
+ input: {
1429
+ query: {
1430
+ type: "object",
1431
+ properties: {
1432
+ resource: strSchema("Filter by resource name")
1433
+ }
1434
+ }
1435
+ },
1436
+ responses: {
1437
+ 200: {
1438
+ description: "Permission list",
1439
+ schema: { type: "array", items: permissionRef }
1440
+ }
1441
+ }
1442
+ },
1443
+ // POST /iam/permissions — create permission
1444
+ {
1445
+ method: "POST",
1446
+ path: "/iam/permissions",
1447
+ handler: "createPermission",
1448
+ meta: {
1449
+ summary: "Create permission",
1450
+ tags: ["IAM", "Admin"],
1451
+ security: ["bearer"],
1452
+ permission: { resource: "fortress", action: "managePermissions" }
1453
+ },
1454
+ input: {
1455
+ body: permissionInputRef
1456
+ },
1457
+ responses: {
1458
+ 200: { description: "Created permission", schema: permissionRef }
1459
+ }
1460
+ },
1461
+ // DELETE /iam/permissions/:id — delete permission
1462
+ {
1463
+ method: "DELETE",
1464
+ path: "/iam/permissions/:id",
1465
+ handler: "deletePermission",
1466
+ meta: {
1467
+ summary: "Delete permission",
1468
+ tags: ["IAM", "Admin"],
1469
+ security: ["bearer"],
1470
+ permission: { resource: "fortress", action: "managePermissions" }
1471
+ },
1472
+ input: {
1473
+ params: {
1474
+ type: "object",
1475
+ properties: { id: intSchema("Permission ID") },
1476
+ required: ["id"]
1477
+ }
1478
+ },
1479
+ responses: {
1480
+ 200: { description: "Permission deleted", schema: { type: "object", properties: { ok: boolSchema("Success") } } },
1481
+ 404: { description: "Permission not found", schema: errorRef }
1482
+ }
1483
+ },
1484
+ // POST /iam/roles/:id/permissions — add permission to role
1485
+ {
1486
+ method: "POST",
1487
+ path: "/iam/roles/:id/permissions",
1488
+ handler: "addPermissionToRole",
1489
+ meta: {
1490
+ summary: "Add permission to role",
1491
+ tags: ["IAM", "Admin"],
1492
+ security: ["bearer"],
1493
+ permission: { resource: "fortress", action: "manageRoles" }
1494
+ },
1495
+ input: {
1496
+ params: {
1497
+ type: "object",
1498
+ properties: { id: intSchema("Role ID") },
1499
+ required: ["id"]
1500
+ },
1501
+ body: permissionInputRef
1502
+ },
1503
+ responses: {
1504
+ 200: { description: "Permission added", schema: { type: "object", properties: { ok: boolSchema("Success") } } },
1505
+ 404: { description: "Role not found", schema: errorRef }
1506
+ }
1507
+ }
1508
+ ];
1509
+ var syncEndpoint = {
1510
+ method: "POST",
1511
+ path: "/iam/sync",
1512
+ handler: "syncResources",
1513
+ meta: {
1514
+ summary: "Sync IAM resources",
1515
+ description: "Push or pull resource definitions to/from the resource file",
1516
+ tags: ["IAM", "Admin"],
1517
+ security: ["bearer"],
1518
+ permission: { resource: "fortress", action: "managePermissions" }
1519
+ },
1520
+ input: {
1521
+ body: {
1522
+ type: "object",
1523
+ properties: {
1524
+ direction: { type: "string", enum: ["push", "pull"], description: "Sync direction" },
1525
+ filePath: strSchema("Resource file path (optional)")
1526
+ },
1527
+ required: ["direction"]
1528
+ }
1529
+ },
1530
+ responses: {
1531
+ 200: { description: "Sync complete", schema: { type: "object", properties: { ok: boolSchema("Success") } } },
1532
+ 401: { description: "Not authenticated" },
1533
+ 403: { description: "Insufficient permissions" }
1534
+ }
1535
+ };
1536
+ var bootstrapEndpoint = {
1537
+ method: "POST",
1538
+ path: "/iam/admin/bootstrap",
1539
+ handler: "bootstrap",
1540
+ meta: {
1541
+ summary: "Bootstrap admin user",
1542
+ description: "Opt-in emergency bootstrap. Assigns all fortress admin permissions only while zero fortress-admin bindings exist and only when the caller presents the one-time bootstrap secret. Creates the fortress resource and permissions if they do not exist.",
1543
+ tags: ["IAM", "Admin"],
1544
+ security: ["bearer"]
1545
+ },
1546
+ input: {
1547
+ body: {
1548
+ type: "object",
1549
+ properties: {
1550
+ userId: { type: "integer", description: "Target user ID. Defaults to the authenticated caller." },
1551
+ secret: { type: "string", description: "One-time bootstrap secret" }
1552
+ }
1553
+ }
1554
+ },
1555
+ responses: {
1556
+ 200: { description: "Admin bootstrapped", schema: { type: "object", properties: { ok: { type: "boolean" }, role: { type: "object" } } } },
1557
+ 401: { description: "Not authenticated" },
1558
+ 403: { description: "Bootstrap disabled, bad secret, or already bootstrapped" }
1559
+ }
1560
+ };
1561
+ var apiKeyInfoSchema = {
1562
+ type: "object",
1563
+ properties: {
1564
+ id: intSchema("Database id"),
1565
+ name: strSchema("Key label"),
1566
+ keyPrefix: strSchema("First 12 characters of the key, for identification"),
1567
+ scopes: { type: "array", items: { type: "string" }, nullable: true },
1568
+ expiresAt: { type: "string", format: "date-time", nullable: true },
1569
+ lastUsedAt: { type: "string", format: "date-time", nullable: true },
1570
+ createdAt: { type: "string", format: "date-time" }
1571
+ },
1572
+ required: ["id", "name", "keyPrefix", "createdAt"]
1573
+ };
1574
+ var createKeyBodySchema = {
1575
+ type: "object",
1576
+ properties: {
1577
+ name: strSchema("Human-readable key label"),
1578
+ scopes: { type: "array", items: { type: "string" }, description: "Optional permission scopes attached to the key" },
1579
+ expiresAt: { type: "string", description: "Optional expiry (ISO 8601 string)" }
1580
+ },
1581
+ required: ["name"]
1582
+ };
1583
+ var createKeyResponseSchema = {
1584
+ type: "object",
1585
+ properties: {
1586
+ key: strSchema("Raw API key \u2014 shown exactly once, store it immediately"),
1587
+ id: intSchema("Database id of the key")
1588
+ },
1589
+ required: ["key", "id"]
1590
+ };
1591
+ var adminApiKeyEndpoints = [
1592
+ // ── User-scoped admin api-key management ──────────────────────
1593
+ {
1594
+ method: "POST",
1595
+ path: "/admin/users/:userId/api-keys",
1596
+ handler: "adminCreateUserApiKey",
1597
+ meta: {
1598
+ summary: "Mint an API key for any user",
1599
+ description: "Create a new API key owned by any user, bypassing the self-service `maxKeysPerSubject` check is NOT done \u2014 the same limit applies. The raw key is returned exactly once and cannot be retrieved later. Requires the `apiKey:manage` permission. Typical use: provisioning keys during tenant onboarding or replacing a lost key on a user's behalf.",
1600
+ tags: ["Admin", "API Keys"],
1601
+ security: ["bearer"],
1602
+ permission: { resource: "apiKey", action: "manage" }
1603
+ },
1604
+ input: {
1605
+ params: {
1606
+ type: "object",
1607
+ properties: { userId: intSchema("Target user ID") },
1608
+ required: ["userId"]
1609
+ },
1610
+ body: createKeyBodySchema
1611
+ },
1612
+ responses: {
1613
+ 201: { description: "Key created", schema: createKeyResponseSchema },
1614
+ 400: { description: "Bad request", schema: errorRef },
1615
+ 401: { description: "Not authenticated", schema: errorRef },
1616
+ 403: { description: "Forbidden", schema: errorRef },
1617
+ 404: { description: "User not found", schema: errorRef }
1618
+ }
1619
+ },
1620
+ {
1621
+ method: "GET",
1622
+ path: "/admin/users/:userId/api-keys",
1623
+ handler: "adminListUserApiKeys",
1624
+ meta: {
1625
+ summary: "List a user's API keys",
1626
+ description: "Return the active (non-revoked) API keys belonging to any user. Raw keys and hashes are never returned. Requires the `apiKey:manage` permission.",
1627
+ tags: ["Admin", "API Keys"],
1628
+ security: ["bearer"],
1629
+ permission: { resource: "apiKey", action: "manage" }
1630
+ },
1631
+ input: {
1632
+ params: {
1633
+ type: "object",
1634
+ properties: { userId: intSchema("Target user ID") },
1635
+ required: ["userId"]
1636
+ }
1637
+ },
1638
+ responses: {
1639
+ 200: {
1640
+ description: "Keys",
1641
+ schema: {
1642
+ type: "object",
1643
+ properties: {
1644
+ keys: { type: "array", items: apiKeyInfoSchema }
1645
+ },
1646
+ required: ["keys"]
1647
+ }
1648
+ },
1649
+ 401: { description: "Not authenticated", schema: errorRef },
1650
+ 403: { description: "Forbidden", schema: errorRef }
1651
+ }
1652
+ },
1653
+ {
1654
+ method: "DELETE",
1655
+ path: "/admin/users/:userId/api-keys/:id",
1656
+ handler: "adminRevokeUserApiKey",
1657
+ meta: {
1658
+ summary: "Revoke a user's API key",
1659
+ description: "Revoke any API key by id, bypassing the self-service ownership check. Requires the `apiKey:manage` permission. Typically used to respond to leaked keys or compromised accounts.",
1660
+ tags: ["Admin", "API Keys"],
1661
+ security: ["bearer"],
1662
+ permission: { resource: "apiKey", action: "manage" }
1663
+ },
1664
+ input: {
1665
+ params: {
1666
+ type: "object",
1667
+ properties: {
1668
+ userId: intSchema("Target user ID (for URL namespacing; ownership is not enforced)"),
1669
+ id: intSchema("Key id to revoke")
1670
+ },
1671
+ required: ["userId", "id"]
1672
+ }
1673
+ },
1674
+ responses: {
1675
+ 200: {
1676
+ description: "Revoked",
1677
+ schema: {
1678
+ type: "object",
1679
+ properties: { ok: boolSchema("Success") },
1680
+ required: ["ok"]
1681
+ }
1682
+ },
1683
+ 401: { description: "Not authenticated", schema: errorRef },
1684
+ 403: { description: "Forbidden", schema: errorRef },
1685
+ 404: { description: "Not found", schema: errorRef }
1686
+ }
1687
+ },
1688
+ // ── Service-account-scoped admin api-key management ───────────
1689
+ //
1690
+ // Service accounts have no login path — they can't self-mint their
1691
+ // first key. These endpoints are the only supported way to bootstrap
1692
+ // a service account's credentials.
1693
+ {
1694
+ method: "POST",
1695
+ path: "/admin/service-accounts/:id/api-keys",
1696
+ handler: "adminCreateServiceAccountApiKey",
1697
+ meta: {
1698
+ summary: "Mint an API key for a service account",
1699
+ description: "Create a new API key owned by a service account. This is the primary entry point for bootstrapping a service account's credentials \u2014 a fresh service account has no way to authenticate until an admin mints its first key. The raw key is returned exactly once and cannot be retrieved later. Requires the `apiKey:manage` permission.",
1700
+ tags: ["Admin", "API Keys", "Service Accounts"],
1701
+ security: ["bearer"],
1702
+ permission: { resource: "apiKey", action: "manage" }
1703
+ },
1704
+ input: {
1705
+ params: {
1706
+ type: "object",
1707
+ properties: { id: intSchema("Target service account ID") },
1708
+ required: ["id"]
1709
+ },
1710
+ body: createKeyBodySchema
1711
+ },
1712
+ responses: {
1713
+ 201: { description: "Key created", schema: createKeyResponseSchema },
1714
+ 400: { description: "Bad request", schema: errorRef },
1715
+ 401: { description: "Not authenticated", schema: errorRef },
1716
+ 403: { description: "Forbidden", schema: errorRef },
1717
+ 404: { description: "Service account not found", schema: errorRef }
1718
+ }
1719
+ },
1720
+ {
1721
+ method: "GET",
1722
+ path: "/admin/service-accounts/:id/api-keys",
1723
+ handler: "adminListServiceAccountApiKeys",
1724
+ meta: {
1725
+ summary: "List a service account's API keys",
1726
+ description: "Return the active (non-revoked) API keys owned by a service account. Raw keys and hashes are never returned. Requires the `apiKey:manage` permission.",
1727
+ tags: ["Admin", "API Keys", "Service Accounts"],
1728
+ security: ["bearer"],
1729
+ permission: { resource: "apiKey", action: "manage" }
1730
+ },
1731
+ input: {
1732
+ params: {
1733
+ type: "object",
1734
+ properties: { id: intSchema("Target service account ID") },
1735
+ required: ["id"]
1736
+ }
1737
+ },
1738
+ responses: {
1739
+ 200: {
1740
+ description: "Keys",
1741
+ schema: {
1742
+ type: "object",
1743
+ properties: {
1744
+ keys: { type: "array", items: apiKeyInfoSchema }
1745
+ },
1746
+ required: ["keys"]
1747
+ }
1748
+ },
1749
+ 401: { description: "Not authenticated", schema: errorRef },
1750
+ 403: { description: "Forbidden", schema: errorRef }
1751
+ }
1752
+ },
1753
+ {
1754
+ method: "DELETE",
1755
+ path: "/admin/service-accounts/:id/api-keys/:keyId",
1756
+ handler: "adminRevokeServiceAccountApiKey",
1757
+ meta: {
1758
+ summary: "Revoke a service account's API key",
1759
+ description: "Revoke any API key by id, bypassing the self-service ownership check. Requires the `apiKey:manage` permission.",
1760
+ tags: ["Admin", "API Keys", "Service Accounts"],
1761
+ security: ["bearer"],
1762
+ permission: { resource: "apiKey", action: "manage" }
1763
+ },
1764
+ input: {
1765
+ params: {
1766
+ type: "object",
1767
+ properties: {
1768
+ id: intSchema("Target service account ID (for URL namespacing; ownership is not enforced)"),
1769
+ keyId: intSchema("Key id to revoke")
1770
+ },
1771
+ required: ["id", "keyId"]
1772
+ }
1773
+ },
1774
+ responses: {
1775
+ 200: {
1776
+ description: "Revoked",
1777
+ schema: {
1778
+ type: "object",
1779
+ properties: { ok: boolSchema("Success") },
1780
+ required: ["ok"]
1781
+ }
1782
+ },
1783
+ 401: { description: "Not authenticated", schema: errorRef },
1784
+ 403: { description: "Forbidden", schema: errorRef },
1785
+ 404: { description: "Not found", schema: errorRef }
1786
+ }
1787
+ }
1788
+ ];
1789
+ function admin(options = {}) {
1790
+ const mountApiKeyRoutes = options.apiKeyRoutes === true;
1791
+ const mountBootstrap = options.bootstrap?.enabled === true;
1792
+ const bootstrapSecret = options.bootstrap?.secret ?? process.env.FORTRESS_ADMIN_BOOTSTRAP_SECRET;
1793
+ return {
1794
+ name: "admin",
1795
+ // Admin routes are aggregated from several internal arrays into a
1796
+ // record keyed by `${method}_${path}` so collisions with core handler
1797
+ // names (e.g. `createUser` exists in both auth-endpoints.ts and admin)
1798
+ // are impossible. Admin routes exist for default-deny protection and
1799
+ // aren't exposed via the typed `fortress.call.*` surface.
1800
+ routes: Object.fromEntries(
1801
+ [
1802
+ ...mountBootstrap ? [bootstrapEndpoint] : [],
1803
+ syncEndpoint,
1804
+ ...adminAuthEndpoints,
1805
+ ...adminIamEndpoints,
1806
+ ...Object.values(iamEndpoints),
1807
+ ...mountApiKeyRoutes ? adminApiKeyEndpoints : []
1808
+ ].map((ep) => [`${ep.method}_${ep.path}`, ep])
1809
+ ),
1810
+ methods: (ctx) => ({
1811
+ async getResources() {
1812
+ return pullResources(ctx.db);
1813
+ },
1814
+ async bootstrap(body, routeCtx) {
1815
+ if (!mountBootstrap)
1816
+ throw Errors.notFound("Admin bootstrap route is disabled");
1817
+ if (!bootstrapSecret)
1818
+ throw Errors.forbidden("Admin bootstrap secret is not configured");
1819
+ if (!body.secret || !timingSafeEqual(body.secret, bootstrapSecret))
1820
+ throw Errors.forbidden("Invalid admin bootstrap secret");
1821
+ const callerId = routeCtx?.userId;
1822
+ const userId = body.userId ?? callerId;
1823
+ if (userId == null)
1824
+ throw Errors.unauthorized("User not authenticated");
1825
+ const db = ctx.db;
1826
+ return db.transaction(async (tx) => {
1827
+ if (tx.dialect === "pg" && tx.rawQuery)
1828
+ await tx.rawQuery("SELECT pg_advisory_xact_lock(hashtext(?))", ["fortress-admin-bootstrap"]);
1829
+ const user = await tx.findOne({
1830
+ model: "user",
1831
+ where: [{ field: "id", operator: "=", value: userId }]
1832
+ });
1833
+ if (!user) {
1834
+ throw Errors.notFound("User not found");
1835
+ }
1836
+ const existingRole = await tx.findOne({
1837
+ model: "role",
1838
+ where: [{ field: "name", operator: "=", value: "fortress-admin" }]
1839
+ });
1840
+ if (existingRole) {
1841
+ const existingAdmins = await tx.count({
1842
+ model: "role_binding",
1843
+ where: [{ field: "roleId", operator: "=", value: existingRole.id }]
1844
+ });
1845
+ if (existingAdmins > 0)
1846
+ throw Errors.forbidden("Admin already bootstrapped");
1847
+ }
1848
+ const plugins = ctx.config.plugins ?? [];
1849
+ const pluginEndpoints = [];
1850
+ for (const plugin of plugins) {
1851
+ if (plugin.routes)
1852
+ pluginEndpoints.push(...Object.values(plugin.routes));
1853
+ }
1854
+ const allEndpoints = [
1855
+ ...Object.values(authEndpoints),
1856
+ ...Object.values(iamEndpoints),
1857
+ ...pluginEndpoints
1858
+ ];
1859
+ const declaredPermissions = collectPermissions(allEndpoints);
1860
+ const resources = new Set(declaredPermissions.map((p) => p.resource));
1861
+ for (const resource of resources) {
1862
+ const existing = await tx.findOne({
1863
+ model: "resource",
1864
+ where: [{ field: "name", operator: "=", value: resource }]
1865
+ });
1866
+ if (!existing) {
1867
+ await tx.create({ model: "resource", data: { name: resource, description: `Auto-registered by admin plugin` } });
1868
+ }
1869
+ }
1870
+ const permissionIds = [];
1871
+ for (const perm of declaredPermissions) {
1872
+ let existing = await tx.findOne({
1873
+ model: "permission",
1874
+ where: [
1875
+ { field: "resource", operator: "=", value: perm.resource },
1876
+ { field: "action", operator: "=", value: perm.action }
1877
+ ]
1878
+ });
1879
+ if (!existing) {
1880
+ existing = await tx.create({
1881
+ model: "permission",
1882
+ data: {
1883
+ resource: perm.resource,
1884
+ action: perm.action,
1885
+ effect: "ALLOW",
1886
+ description: `${perm.action} ${perm.resource}`
1887
+ }
1888
+ });
1889
+ }
1890
+ permissionIds.push(existing.id);
1891
+ }
1892
+ let adminRole = existingRole;
1893
+ if (!adminRole) {
1894
+ adminRole = await tx.create({
1895
+ model: "role",
1896
+ data: { name: "fortress-admin", description: "Full fortress administration", isSystem: true }
1897
+ });
1898
+ }
1899
+ for (const permId of permissionIds) {
1900
+ const existingLink = await tx.findOne({
1901
+ model: "role_permission",
1902
+ where: [
1903
+ { field: "roleId", operator: "=", value: adminRole.id },
1904
+ { field: "permissionId", operator: "=", value: permId }
1905
+ ]
1906
+ });
1907
+ if (!existingLink) {
1908
+ await tx.create({ model: "role_permission", data: { roleId: adminRole.id, permissionId: permId } });
1909
+ }
1910
+ }
1911
+ const existingBinding = await tx.findOne({
1912
+ model: "role_binding",
1913
+ where: [
1914
+ { field: "roleId", operator: "=", value: adminRole.id },
1915
+ { field: "subjectType", operator: "=", value: "USER" },
1916
+ { field: "subjectId", operator: "=", value: userId }
1917
+ ]
1918
+ });
1919
+ if (!existingBinding) {
1920
+ await tx.create({
1921
+ model: "role_binding",
1922
+ data: { roleId: adminRole.id, subjectType: "USER", subjectId: userId, tenantId: null }
1923
+ });
1924
+ }
1925
+ return { ok: true, role: adminRole };
1926
+ });
1927
+ },
1928
+ // ── Auth admin — delegates to core auth service ──────────
1929
+ async listUsers(body) {
1930
+ if (!ctx.auth)
1931
+ throw Errors.database("Auth service not available");
1932
+ return ctx.auth.listUsers({
1933
+ limit: body.limit ? Number(body.limit) : void 0,
1934
+ offset: body.offset ? Number(body.offset) : void 0,
1935
+ search: body.search,
1936
+ sortBy: body.sortBy,
1937
+ sortDirection: body.sortDirection
1938
+ });
1939
+ },
1940
+ async getUserById(body) {
1941
+ if (!ctx.auth)
1942
+ throw Errors.database("Auth service not available");
1943
+ return ctx.auth.getUserById(requireId(body.id, "id"));
1944
+ },
1945
+ async createUser(body) {
1946
+ if (!ctx.auth)
1947
+ throw Errors.database("Auth service not available");
1948
+ return ctx.auth.createUser({
1949
+ email: body.email,
1950
+ name: body.name,
1951
+ password: body.password,
1952
+ isActive: body.isActive
1953
+ });
1954
+ },
1955
+ async updateUser(body) {
1956
+ if (!ctx.auth)
1957
+ throw Errors.database("Auth service not available");
1958
+ const { id: id2, ...data } = body;
1959
+ return ctx.auth.updateUser(requireId(id2, "id"), data);
1960
+ },
1961
+ async deleteUser(body) {
1962
+ if (!ctx.auth)
1963
+ throw Errors.database("Auth service not available");
1964
+ await ctx.auth.deleteUser(requireId(body.id, "id"));
1965
+ return { ok: true };
1966
+ },
1967
+ // ── IAM admin — delegates to core IAM service ────────────
1968
+ async getRole(body) {
1969
+ if (!ctx.iam)
1970
+ throw Errors.database("IAM service not available");
1971
+ return ctx.iam.getRole(requireId(body.id, "id"));
1972
+ },
1973
+ async updateRole(body) {
1974
+ if (!ctx.iam)
1975
+ throw Errors.database("IAM service not available");
1976
+ const { id: id2, ...data } = body;
1977
+ return ctx.iam.updateRole(requireId(id2, "id"), data);
1978
+ },
1979
+ async listGroups(body) {
1980
+ if (!ctx.iam)
1981
+ throw Errors.database("IAM service not available");
1982
+ return ctx.iam.listGroups({
1983
+ limit: body.limit ? Number(body.limit) : void 0,
1984
+ offset: body.offset ? Number(body.offset) : void 0
1985
+ });
1986
+ },
1987
+ async getGroup(body) {
1988
+ if (!ctx.iam)
1989
+ throw Errors.database("IAM service not available");
1990
+ return ctx.iam.getGroup(requireId(body.id, "id"));
1991
+ },
1992
+ async updateGroup(body) {
1993
+ if (!ctx.iam)
1994
+ throw Errors.database("IAM service not available");
1995
+ const { id: id2, ...data } = body;
1996
+ return ctx.iam.updateGroup(requireId(id2, "id"), data);
1997
+ },
1998
+ async deleteGroup(body) {
1999
+ if (!ctx.iam)
2000
+ throw Errors.database("IAM service not available");
2001
+ await ctx.iam.deleteGroup(requireId(body.id, "id"));
2002
+ return { ok: true };
2003
+ },
2004
+ async getGroupUsers(body) {
2005
+ if (!ctx.iam)
2006
+ throw Errors.database("IAM service not available");
2007
+ return ctx.iam.getGroupUsers(requireId(body.id, "id"));
2008
+ },
2009
+ async listPermissions(body) {
2010
+ if (!ctx.iam)
2011
+ throw Errors.database("IAM service not available");
2012
+ return ctx.iam.listPermissions({
2013
+ resource: body.resource || void 0
2014
+ });
2015
+ },
2016
+ async createPermission(body) {
2017
+ if (!ctx.iam)
2018
+ throw Errors.database("IAM service not available");
2019
+ return ctx.iam.createPermission(body);
2020
+ },
2021
+ async deletePermission(body) {
2022
+ if (!ctx.iam)
2023
+ throw Errors.database("IAM service not available");
2024
+ await ctx.iam.deletePermission(requireId(body.id, "id"));
2025
+ return { ok: true };
2026
+ },
2027
+ async addPermissionToRole(body) {
2028
+ if (!ctx.iam)
2029
+ throw Errors.database("IAM service not available");
2030
+ const { id: id2, ...permission } = body;
2031
+ await ctx.iam.addPermissionToRole(requireId(id2, "id"), permission);
2032
+ return { ok: true };
2033
+ },
2034
+ // ── Core IAM operations — previously spec-only ─────────────
2035
+ async getRoles() {
2036
+ if (!ctx.iam)
2037
+ throw Errors.database("IAM service not available");
2038
+ return ctx.iam.getRoles();
2039
+ },
2040
+ async createRole(body) {
2041
+ if (!ctx.iam)
2042
+ throw Errors.database("IAM service not available");
2043
+ return ctx.iam.createRole(
2044
+ body.name,
2045
+ body.permissions ?? [],
2046
+ body.description
2047
+ );
2048
+ },
2049
+ async deleteRole(body) {
2050
+ if (!ctx.iam)
2051
+ throw Errors.database("IAM service not available");
2052
+ await ctx.iam.deleteRole(requireId(body.id, "id"));
2053
+ return { ok: true };
2054
+ },
2055
+ async bindRoleToUser(body) {
2056
+ if (!ctx.iam)
2057
+ throw Errors.database("IAM service not available");
2058
+ await ctx.iam.bindRoleToUser(
2059
+ requireId(body.userId, "userId"),
2060
+ requireId(body.id, "id"),
2061
+ body.tenantId
2062
+ );
2063
+ return { ok: true };
2064
+ },
2065
+ async bindRoleToGroup(body) {
2066
+ if (!ctx.iam)
2067
+ throw Errors.database("IAM service not available");
2068
+ await ctx.iam.bindRoleToGroup(
2069
+ requireId(body.groupId, "groupId"),
2070
+ requireId(body.id, "id"),
2071
+ body.tenantId
2072
+ );
2073
+ return { ok: true };
2074
+ },
2075
+ async unbindRole(body) {
2076
+ if (!ctx.iam)
2077
+ throw Errors.database("IAM service not available");
2078
+ await ctx.iam.unbindRole(
2079
+ body.subjectType,
2080
+ requireId(body.subjectId, "subjectId"),
2081
+ requireId(body.id, "id"),
2082
+ body.tenantId
2083
+ );
2084
+ return { ok: true };
2085
+ },
2086
+ async createGroup(body) {
2087
+ if (!ctx.iam)
2088
+ throw Errors.database("IAM service not available");
2089
+ return ctx.iam.createGroup(
2090
+ body.name,
2091
+ body.description
2092
+ );
2093
+ },
2094
+ async addUserToGroup(body) {
2095
+ if (!ctx.iam)
2096
+ throw Errors.database("IAM service not available");
2097
+ await ctx.iam.addUserToGroup(
2098
+ requireId(body.id, "id"),
2099
+ requireId(body.userId, "userId")
2100
+ );
2101
+ return { ok: true };
2102
+ },
2103
+ async removeUserFromGroup(body) {
2104
+ if (!ctx.iam)
2105
+ throw Errors.database("IAM service not available");
2106
+ await ctx.iam.removeUserFromGroup(
2107
+ requireId(body.id, "id"),
2108
+ requireId(body.userId, "userId")
2109
+ );
2110
+ return { ok: true };
2111
+ },
2112
+ async getUserPermissions(body) {
2113
+ if (!ctx.iam)
2114
+ throw Errors.database("IAM service not available");
2115
+ return ctx.iam.getPermissionsForSubject(
2116
+ { type: "USER", id: requireId(body.id, "id") },
2117
+ body.tenantId
2118
+ );
2119
+ },
2120
+ async checkPermission(body) {
2121
+ if (!ctx.iam)
2122
+ throw Errors.database("IAM service not available");
2123
+ const allowed = await ctx.iam.checkPermission(
2124
+ { type: "USER", id: requireId(body.userId, "userId") },
2125
+ body.resource,
2126
+ body.action,
2127
+ body.context
2128
+ );
2129
+ return { allowed };
2130
+ },
2131
+ async bindPermissionToUser(body) {
2132
+ if (!ctx.iam)
2133
+ throw Errors.database("IAM service not available");
2134
+ await ctx.iam.bindPermissionToUser(
2135
+ requireId(body.userId, "userId"),
2136
+ body.permission,
2137
+ body.tenantId
2138
+ );
2139
+ return { ok: true };
2140
+ },
2141
+ async bindPermissionToGroup(body) {
2142
+ if (!ctx.iam)
2143
+ throw Errors.database("IAM service not available");
2144
+ await ctx.iam.bindPermissionToGroup(
2145
+ requireId(body.groupId, "groupId"),
2146
+ body.permission,
2147
+ body.tenantId
2148
+ );
2149
+ return { ok: true };
2150
+ },
2151
+ async unbindPermissionFromUser(body) {
2152
+ if (!ctx.iam)
2153
+ throw Errors.database("IAM service not available");
2154
+ await ctx.iam.unbindPermissionFromUser(
2155
+ requireId(body.userId, "userId"),
2156
+ requireId(body.permissionId, "permissionId"),
2157
+ body.tenantId
2158
+ );
2159
+ return { ok: true };
2160
+ },
2161
+ async unbindPermissionFromGroup(body) {
2162
+ if (!ctx.iam)
2163
+ throw Errors.database("IAM service not available");
2164
+ await ctx.iam.unbindPermissionFromGroup(
2165
+ requireId(body.groupId, "groupId"),
2166
+ requireId(body.permissionId, "permissionId"),
2167
+ body.tenantId
2168
+ );
2169
+ return { ok: true };
2170
+ },
2171
+ // ── Service-account IAM proxies ────────────────────────────
2172
+ //
2173
+ // The admin plugin re-exports `iamEndpoints` on its own `routes` so
2174
+ // that IAM routes get dispatched through `dispatchPlugin`. That
2175
+ // means every IAM handler referenced by those endpoint definitions
2176
+ // must exist on this plugin's methods object — thin proxies that
2177
+ // delegate to `ctx.iam`. Without these, hitting any
2178
+ // `/iam/service-accounts/*` route through an instance that has the
2179
+ // admin plugin registered returns a 404 from the dispatcher.
2180
+ async createServiceAccount(body) {
2181
+ if (!ctx.iam)
2182
+ throw Errors.database("IAM service not available");
2183
+ return ctx.iam.createServiceAccount({
2184
+ name: String(body.name ?? ""),
2185
+ displayName: body.displayName,
2186
+ description: body.description
2187
+ });
2188
+ },
2189
+ async listServiceAccounts(body) {
2190
+ if (!ctx.iam)
2191
+ throw Errors.database("IAM service not available");
2192
+ return ctx.iam.listServiceAccounts({
2193
+ limit: body.limit != null ? Number(body.limit) : void 0,
2194
+ offset: body.offset != null ? Number(body.offset) : void 0
2195
+ });
2196
+ },
2197
+ async getServiceAccount(body) {
2198
+ if (!ctx.iam)
2199
+ throw Errors.database("IAM service not available");
2200
+ return ctx.iam.getServiceAccount(requireId(body.id, "id"));
2201
+ },
2202
+ async updateServiceAccount(body) {
2203
+ if (!ctx.iam)
2204
+ throw Errors.database("IAM service not available");
2205
+ return ctx.iam.updateServiceAccount(requireId(body.id, "id"), {
2206
+ displayName: body.displayName,
2207
+ description: body.description,
2208
+ isActive: body.isActive
2209
+ });
2210
+ },
2211
+ async deleteServiceAccount(body) {
2212
+ if (!ctx.iam)
2213
+ throw Errors.database("IAM service not available");
2214
+ await ctx.iam.deleteServiceAccount(requireId(body.id, "id"));
2215
+ return { ok: true };
2216
+ },
2217
+ async getServiceAccountPermissions(body) {
2218
+ if (!ctx.iam)
2219
+ throw Errors.database("IAM service not available");
2220
+ return ctx.iam.getPermissionsForSubject(
2221
+ { type: "SERVICE_ACCOUNT", id: requireId(body.id, "id") },
2222
+ body.tenantId
2223
+ );
2224
+ },
2225
+ async bindRoleToServiceAccount(body) {
2226
+ if (!ctx.iam)
2227
+ throw Errors.database("IAM service not available");
2228
+ await ctx.iam.bindRoleToServiceAccount(
2229
+ requireId(body.serviceAccountId, "serviceAccountId"),
2230
+ requireId(body.id, "id"),
2231
+ body.tenantId
2232
+ );
2233
+ return { ok: true };
2234
+ },
2235
+ async unbindRoleFromServiceAccount(body) {
2236
+ if (!ctx.iam)
2237
+ throw Errors.database("IAM service not available");
2238
+ await ctx.iam.unbindRoleFromServiceAccount(
2239
+ requireId(body.serviceAccountId, "serviceAccountId"),
2240
+ requireId(body.id, "id"),
2241
+ body.tenantId
2242
+ );
2243
+ return { ok: true };
2244
+ },
2245
+ async bindPermissionToServiceAccount(body) {
2246
+ if (!ctx.iam)
2247
+ throw Errors.database("IAM service not available");
2248
+ await ctx.iam.bindPermissionToServiceAccount(
2249
+ requireId(body.serviceAccountId, "serviceAccountId"),
2250
+ body.permission,
2251
+ body.tenantId
2252
+ );
2253
+ return { ok: true };
2254
+ },
2255
+ async unbindPermissionFromServiceAccount(body) {
2256
+ if (!ctx.iam)
2257
+ throw Errors.database("IAM service not available");
2258
+ await ctx.iam.unbindPermissionFromServiceAccount(
2259
+ requireId(body.serviceAccountId, "serviceAccountId"),
2260
+ requireId(body.permissionId, "permissionId"),
2261
+ body.tenantId
2262
+ );
2263
+ return { ok: true };
2264
+ },
2265
+ // ── Admin api-key management ───────────────────────────────
2266
+ //
2267
+ // Read/delete delegate to the stateless helpers in `api-key/core.ts`.
2268
+ // Create re-enters the api-key plugin's `methods` factory so the
2269
+ // configured knobs (prefix, maxKeysPerSubject, defaultExpirySeconds)
2270
+ // apply to admin-minted keys exactly as they do to self-service
2271
+ // keys — no duplicate config. All of these are available as
2272
+ // programmatic methods regardless of the `apiKeyRoutes` flag — only
2273
+ // the HTTP mounting is gated. Requires the `api-key` plugin to be
2274
+ // registered (for the `api_key` model).
2275
+ async adminCreateUserApiKey(body) {
2276
+ const userId = requireId(body.userId, "userId");
2277
+ const user = await ctx.db.findOne({
2278
+ model: "user",
2279
+ where: [{ field: "id", operator: "=", value: userId }]
2280
+ });
2281
+ if (!user)
2282
+ throw Errors.notFound("User not found");
2283
+ const apiKeyMethods = getApiKeyMethods(ctx);
2284
+ return apiKeyMethods.createKey({
2285
+ subject: { type: "USER", id: userId },
2286
+ name: String(body.name ?? ""),
2287
+ scopes: Array.isArray(body.scopes) ? body.scopes.map(String) : void 0,
2288
+ expiresAt: body.expiresAt
2289
+ });
2290
+ },
2291
+ async adminListUserApiKeys(body) {
2292
+ const keys = await listKeysForSubject(ctx.db, {
2293
+ type: "USER",
2294
+ id: requireId(body.userId, "userId")
2295
+ });
2296
+ return { keys };
2297
+ },
2298
+ async adminRevokeUserApiKey(body) {
2299
+ await revokeKeyAsAdmin(ctx.db, requireId(body.id, "id"));
2300
+ return { ok: true };
2301
+ },
2302
+ // ── Service-account-scoped admin api-key handlers ─────────
2303
+ async adminCreateServiceAccountApiKey(body) {
2304
+ const serviceAccountId = requireId(body.id, "id");
2305
+ const sa = await ctx.db.findOne({
2306
+ model: "service_account",
2307
+ where: [{ field: "id", operator: "=", value: serviceAccountId }]
2308
+ });
2309
+ if (!sa)
2310
+ throw Errors.notFound("Service account not found");
2311
+ const apiKeyMethods = getApiKeyMethods(ctx);
2312
+ return apiKeyMethods.createKey({
2313
+ subject: { type: "SERVICE_ACCOUNT", id: serviceAccountId },
2314
+ name: String(body.name ?? ""),
2315
+ scopes: Array.isArray(body.scopes) ? body.scopes.map(String) : void 0,
2316
+ expiresAt: body.expiresAt
2317
+ });
2318
+ },
2319
+ async adminListServiceAccountApiKeys(body) {
2320
+ const keys = await listKeysForSubject(ctx.db, {
2321
+ type: "SERVICE_ACCOUNT",
2322
+ id: requireId(body.id, "id")
2323
+ });
2324
+ return { keys };
2325
+ },
2326
+ async adminRevokeServiceAccountApiKey(body) {
2327
+ await revokeKeyAsAdmin(ctx.db, requireId(body.keyId, "keyId"));
2328
+ return { ok: true };
2329
+ },
2330
+ // ── Resource sync ──────────────────────────────────────────
2331
+ async syncResources(body) {
2332
+ if (!ctx.iam)
2333
+ throw Errors.database("IAM service not available");
2334
+ await ctx.iam.syncResources(
2335
+ body.direction,
2336
+ body.filePath
2337
+ );
2338
+ return { ok: true };
2339
+ }
2340
+ })
2341
+ };
2342
+ }
2343
+ function getApiKeyMethods(ctx) {
2344
+ const apiKeyPlugin = (ctx.config.plugins ?? []).find((p) => p.name === "api-key");
2345
+ if (!apiKeyPlugin?.methods)
2346
+ throw Errors.database("api-key plugin is not registered");
2347
+ return apiKeyPlugin.methods(ctx);
2348
+ }
2349
+ export {
2350
+ admin
2351
+ };