@hilbras/keystone 1.1.0

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 (786) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/LICENSE +21 -0
  3. package/README.md +691 -0
  4. package/dist/cli.d.ts +3 -0
  5. package/dist/cli.d.ts.map +1 -0
  6. package/dist/cli.js +144 -0
  7. package/dist/cli.js.map +1 -0
  8. package/dist/config.d.ts +68 -0
  9. package/dist/config.d.ts.map +1 -0
  10. package/dist/config.js +118 -0
  11. package/dist/config.js.map +1 -0
  12. package/dist/container.d.ts +27 -0
  13. package/dist/container.d.ts.map +1 -0
  14. package/dist/container.js +14 -0
  15. package/dist/container.js.map +1 -0
  16. package/dist/db/index.d.ts +17 -0
  17. package/dist/db/index.d.ts.map +1 -0
  18. package/dist/db/index.js +46 -0
  19. package/dist/db/index.js.map +1 -0
  20. package/dist/db/migrations/0000_skinny_ben_parker.sql +553 -0
  21. package/dist/db/migrations/0001_brief_joseph.sql +10 -0
  22. package/dist/db/migrations/0002_add_account_lockout.sql +3 -0
  23. package/dist/db/migrations/0003_steep_rachel_grey.sql +1 -0
  24. package/dist/db/migrations/0004_clever_bill_hollister.sql +20 -0
  25. package/dist/db/migrations/0005_steep_the_call.sql +2 -0
  26. package/dist/db/migrations/0006_ambitious_boomer.sql +17 -0
  27. package/dist/db/migrations/0007_greedy_vindicator.sql +40 -0
  28. package/dist/db/migrations/meta/0000_snapshot.json +2964 -0
  29. package/dist/db/migrations/meta/0001_snapshot.json +3031 -0
  30. package/dist/db/migrations/meta/0003_snapshot.json +3051 -0
  31. package/dist/db/migrations/meta/0004_snapshot.json +3163 -0
  32. package/dist/db/migrations/meta/0005_snapshot.json +3177 -0
  33. package/dist/db/migrations/meta/0006_snapshot.json +3270 -0
  34. package/dist/db/migrations/meta/0007_snapshot.json +3489 -0
  35. package/dist/db/migrations/meta/_journal.json +62 -0
  36. package/dist/db/schema.d.ts +3671 -0
  37. package/dist/db/schema.d.ts.map +1 -0
  38. package/dist/db/schema.js +475 -0
  39. package/dist/db/schema.js.map +1 -0
  40. package/dist/db/seed.d.ts +2 -0
  41. package/dist/db/seed.d.ts.map +1 -0
  42. package/dist/db/seed.js +139 -0
  43. package/dist/db/seed.js.map +1 -0
  44. package/dist/di.d.ts +12 -0
  45. package/dist/di.d.ts.map +1 -0
  46. package/dist/di.js +56 -0
  47. package/dist/di.js.map +1 -0
  48. package/dist/index.d.ts +3 -0
  49. package/dist/index.d.ts.map +1 -0
  50. package/dist/index.js +295 -0
  51. package/dist/index.js.map +1 -0
  52. package/dist/lib/errors.d.ts +46 -0
  53. package/dist/lib/errors.d.ts.map +1 -0
  54. package/dist/lib/errors.js +78 -0
  55. package/dist/lib/errors.js.map +1 -0
  56. package/dist/lib/result.d.ts +21 -0
  57. package/dist/lib/result.d.ts.map +1 -0
  58. package/dist/lib/result.js +22 -0
  59. package/dist/lib/result.js.map +1 -0
  60. package/dist/lib/webhookSignature.d.ts +11 -0
  61. package/dist/lib/webhookSignature.d.ts.map +1 -0
  62. package/dist/lib/webhookSignature.js +35 -0
  63. package/dist/lib/webhookSignature.js.map +1 -0
  64. package/dist/plugins/appContext.d.ts +4 -0
  65. package/dist/plugins/appContext.d.ts.map +1 -0
  66. package/dist/plugins/appContext.js +63 -0
  67. package/dist/plugins/appContext.js.map +1 -0
  68. package/dist/plugins/audit.d.ts +11 -0
  69. package/dist/plugins/audit.d.ts.map +1 -0
  70. package/dist/plugins/audit.js +23 -0
  71. package/dist/plugins/audit.js.map +1 -0
  72. package/dist/plugins/auth.d.ts +21 -0
  73. package/dist/plugins/auth.d.ts.map +1 -0
  74. package/dist/plugins/auth.js +190 -0
  75. package/dist/plugins/auth.js.map +1 -0
  76. package/dist/plugins/metrics.d.ts +8 -0
  77. package/dist/plugins/metrics.d.ts.map +1 -0
  78. package/dist/plugins/metrics.js +36 -0
  79. package/dist/plugins/metrics.js.map +1 -0
  80. package/dist/plugins/mtls.d.ts +14 -0
  81. package/dist/plugins/mtls.d.ts.map +1 -0
  82. package/dist/plugins/mtls.js +76 -0
  83. package/dist/plugins/mtls.js.map +1 -0
  84. package/dist/plugins/permissions.d.ts +9 -0
  85. package/dist/plugins/permissions.d.ts.map +1 -0
  86. package/dist/plugins/permissions.js +20 -0
  87. package/dist/plugins/permissions.js.map +1 -0
  88. package/dist/plugins/rateLimit.d.ts +20 -0
  89. package/dist/plugins/rateLimit.d.ts.map +1 -0
  90. package/dist/plugins/rateLimit.js +101 -0
  91. package/dist/plugins/rateLimit.js.map +1 -0
  92. package/dist/plugins/requestLogger.d.ts +4 -0
  93. package/dist/plugins/requestLogger.d.ts.map +1 -0
  94. package/dist/plugins/requestLogger.js +20 -0
  95. package/dist/plugins/requestLogger.js.map +1 -0
  96. package/dist/plugins/tracing.d.ts +3 -0
  97. package/dist/plugins/tracing.d.ts.map +1 -0
  98. package/dist/plugins/tracing.js +21 -0
  99. package/dist/plugins/tracing.js.map +1 -0
  100. package/dist/repositories/apiKey.d.ts +40 -0
  101. package/dist/repositories/apiKey.d.ts.map +1 -0
  102. package/dist/repositories/apiKey.js +122 -0
  103. package/dist/repositories/apiKey.js.map +1 -0
  104. package/dist/repositories/application.d.ts +13 -0
  105. package/dist/repositories/application.d.ts.map +1 -0
  106. package/dist/repositories/application.js +57 -0
  107. package/dist/repositories/application.js.map +1 -0
  108. package/dist/repositories/audit.d.ts +13 -0
  109. package/dist/repositories/audit.d.ts.map +1 -0
  110. package/dist/repositories/audit.js +26 -0
  111. package/dist/repositories/audit.js.map +1 -0
  112. package/dist/repositories/index.d.ts +10 -0
  113. package/dist/repositories/index.d.ts.map +1 -0
  114. package/dist/repositories/index.js +10 -0
  115. package/dist/repositories/index.js.map +1 -0
  116. package/dist/repositories/oidcConnection.d.ts +131 -0
  117. package/dist/repositories/oidcConnection.d.ts.map +1 -0
  118. package/dist/repositories/oidcConnection.js +59 -0
  119. package/dist/repositories/oidcConnection.js.map +1 -0
  120. package/dist/repositories/organization.d.ts +44 -0
  121. package/dist/repositories/organization.d.ts.map +1 -0
  122. package/dist/repositories/organization.js +145 -0
  123. package/dist/repositories/organization.js.map +1 -0
  124. package/dist/repositories/permission.d.ts +24 -0
  125. package/dist/repositories/permission.d.ts.map +1 -0
  126. package/dist/repositories/permission.js +133 -0
  127. package/dist/repositories/permission.js.map +1 -0
  128. package/dist/repositories/samlConnection.d.ts +107 -0
  129. package/dist/repositories/samlConnection.d.ts.map +1 -0
  130. package/dist/repositories/samlConnection.js +53 -0
  131. package/dist/repositories/samlConnection.js.map +1 -0
  132. package/dist/repositories/session.d.ts +73 -0
  133. package/dist/repositories/session.d.ts.map +1 -0
  134. package/dist/repositories/session.js +68 -0
  135. package/dist/repositories/session.js.map +1 -0
  136. package/dist/repositories/types.d.ts +155 -0
  137. package/dist/repositories/types.d.ts.map +1 -0
  138. package/dist/repositories/types.js +2 -0
  139. package/dist/repositories/types.js.map +1 -0
  140. package/dist/repositories/user.d.ts +40 -0
  141. package/dist/repositories/user.d.ts.map +1 -0
  142. package/dist/repositories/user.js +135 -0
  143. package/dist/repositories/user.js.map +1 -0
  144. package/dist/routes/admin/billing.d.ts +3 -0
  145. package/dist/routes/admin/billing.d.ts.map +1 -0
  146. package/dist/routes/admin/billing.js +31 -0
  147. package/dist/routes/admin/billing.js.map +1 -0
  148. package/dist/routes/admin/helpers.d.ts +36 -0
  149. package/dist/routes/admin/helpers.d.ts.map +1 -0
  150. package/dist/routes/admin/helpers.js +45 -0
  151. package/dist/routes/admin/helpers.js.map +1 -0
  152. package/dist/routes/admin/index.d.ts +3 -0
  153. package/dist/routes/admin/index.d.ts.map +1 -0
  154. package/dist/routes/admin/index.js +15 -0
  155. package/dist/routes/admin/index.js.map +1 -0
  156. package/dist/routes/admin/organizations.d.ts +3 -0
  157. package/dist/routes/admin/organizations.d.ts.map +1 -0
  158. package/dist/routes/admin/organizations.js +222 -0
  159. package/dist/routes/admin/organizations.js.map +1 -0
  160. package/dist/routes/admin/permissions.d.ts +3 -0
  161. package/dist/routes/admin/permissions.d.ts.map +1 -0
  162. package/dist/routes/admin/permissions.js +63 -0
  163. package/dist/routes/admin/permissions.js.map +1 -0
  164. package/dist/routes/admin/platform.d.ts +3 -0
  165. package/dist/routes/admin/platform.d.ts.map +1 -0
  166. package/dist/routes/admin/platform.js +294 -0
  167. package/dist/routes/admin/platform.js.map +1 -0
  168. package/dist/routes/admin/sso.d.ts +3 -0
  169. package/dist/routes/admin/sso.d.ts.map +1 -0
  170. package/dist/routes/admin/sso.js +97 -0
  171. package/dist/routes/admin/sso.js.map +1 -0
  172. package/dist/routes/admin/webhooks.d.ts +3 -0
  173. package/dist/routes/admin/webhooks.d.ts.map +1 -0
  174. package/dist/routes/admin/webhooks.js +68 -0
  175. package/dist/routes/admin/webhooks.js.map +1 -0
  176. package/dist/routes/admin.d.ts +2 -0
  177. package/dist/routes/admin.d.ts.map +1 -0
  178. package/dist/routes/admin.js +2 -0
  179. package/dist/routes/admin.js.map +1 -0
  180. package/dist/routes/apiKeys.d.ts +3 -0
  181. package/dist/routes/apiKeys.d.ts.map +1 -0
  182. package/dist/routes/apiKeys.js +50 -0
  183. package/dist/routes/apiKeys.js.map +1 -0
  184. package/dist/routes/auth.d.ts +3 -0
  185. package/dist/routes/auth.d.ts.map +1 -0
  186. package/dist/routes/auth.js +174 -0
  187. package/dist/routes/auth.js.map +1 -0
  188. package/dist/routes/authz.d.ts +3 -0
  189. package/dist/routes/authz.d.ts.map +1 -0
  190. package/dist/routes/authz.js +28 -0
  191. package/dist/routes/authz.js.map +1 -0
  192. package/dist/routes/config.d.ts +3 -0
  193. package/dist/routes/config.d.ts.map +1 -0
  194. package/dist/routes/config.js +63 -0
  195. package/dist/routes/config.js.map +1 -0
  196. package/dist/routes/emailVerification.d.ts +3 -0
  197. package/dist/routes/emailVerification.d.ts.map +1 -0
  198. package/dist/routes/emailVerification.js +64 -0
  199. package/dist/routes/emailVerification.js.map +1 -0
  200. package/dist/routes/federation.d.ts +3 -0
  201. package/dist/routes/federation.d.ts.map +1 -0
  202. package/dist/routes/federation.js +133 -0
  203. package/dist/routes/federation.js.map +1 -0
  204. package/dist/routes/helpers.d.ts +14 -0
  205. package/dist/routes/helpers.d.ts.map +1 -0
  206. package/dist/routes/helpers.js +15 -0
  207. package/dist/routes/helpers.js.map +1 -0
  208. package/dist/routes/magicLinks.d.ts +3 -0
  209. package/dist/routes/magicLinks.d.ts.map +1 -0
  210. package/dist/routes/magicLinks.js +82 -0
  211. package/dist/routes/magicLinks.js.map +1 -0
  212. package/dist/routes/oauth.d.ts +3 -0
  213. package/dist/routes/oauth.d.ts.map +1 -0
  214. package/dist/routes/oauth.js +146 -0
  215. package/dist/routes/oauth.js.map +1 -0
  216. package/dist/routes/oauth2.d.ts +3 -0
  217. package/dist/routes/oauth2.d.ts.map +1 -0
  218. package/dist/routes/oauth2.js +219 -0
  219. package/dist/routes/oauth2.js.map +1 -0
  220. package/dist/routes/oidcEnterprise.d.ts +3 -0
  221. package/dist/routes/oidcEnterprise.d.ts.map +1 -0
  222. package/dist/routes/oidcEnterprise.js +119 -0
  223. package/dist/routes/oidcEnterprise.js.map +1 -0
  224. package/dist/routes/password.d.ts +3 -0
  225. package/dist/routes/password.d.ts.map +1 -0
  226. package/dist/routes/password.js +83 -0
  227. package/dist/routes/password.js.map +1 -0
  228. package/dist/routes/profile.d.ts +3 -0
  229. package/dist/routes/profile.d.ts.map +1 -0
  230. package/dist/routes/profile.js +43 -0
  231. package/dist/routes/profile.js.map +1 -0
  232. package/dist/routes/saml.d.ts +3 -0
  233. package/dist/routes/saml.d.ts.map +1 -0
  234. package/dist/routes/saml.js +164 -0
  235. package/dist/routes/saml.js.map +1 -0
  236. package/dist/routes/scim.d.ts +3 -0
  237. package/dist/routes/scim.d.ts.map +1 -0
  238. package/dist/routes/scim.js +175 -0
  239. package/dist/routes/scim.js.map +1 -0
  240. package/dist/routes/sdk.d.ts +3 -0
  241. package/dist/routes/sdk.d.ts.map +1 -0
  242. package/dist/routes/sdk.js +129 -0
  243. package/dist/routes/sdk.js.map +1 -0
  244. package/dist/routes/serviceAccounts.d.ts +3 -0
  245. package/dist/routes/serviceAccounts.d.ts.map +1 -0
  246. package/dist/routes/serviceAccounts.js +82 -0
  247. package/dist/routes/serviceAccounts.js.map +1 -0
  248. package/dist/routes/sessions.d.ts +3 -0
  249. package/dist/routes/sessions.d.ts.map +1 -0
  250. package/dist/routes/sessions.js +55 -0
  251. package/dist/routes/sessions.js.map +1 -0
  252. package/dist/routes/setup.d.ts +3 -0
  253. package/dist/routes/setup.d.ts.map +1 -0
  254. package/dist/routes/setup.js +304 -0
  255. package/dist/routes/setup.js.map +1 -0
  256. package/dist/routes/smsOtp.d.ts +3 -0
  257. package/dist/routes/smsOtp.d.ts.map +1 -0
  258. package/dist/routes/smsOtp.js +50 -0
  259. package/dist/routes/smsOtp.js.map +1 -0
  260. package/dist/routes/totp.d.ts +3 -0
  261. package/dist/routes/totp.d.ts.map +1 -0
  262. package/dist/routes/totp.js +78 -0
  263. package/dist/routes/totp.js.map +1 -0
  264. package/dist/routes/webauthn.d.ts +3 -0
  265. package/dist/routes/webauthn.d.ts.map +1 -0
  266. package/dist/routes/webauthn.js +100 -0
  267. package/dist/routes/webauthn.js.map +1 -0
  268. package/dist/routes/workflows.d.ts +3 -0
  269. package/dist/routes/workflows.d.ts.map +1 -0
  270. package/dist/routes/workflows.js +140 -0
  271. package/dist/routes/workflows.js.map +1 -0
  272. package/dist/sdk/index.d.ts +5 -0
  273. package/dist/sdk/index.d.ts.map +1 -0
  274. package/dist/sdk/index.js +125 -0
  275. package/dist/sdk/index.js.map +1 -0
  276. package/dist/sdk/types.d.ts +110 -0
  277. package/dist/sdk/types.d.ts.map +1 -0
  278. package/dist/sdk/types.js +2 -0
  279. package/dist/sdk/types.js.map +1 -0
  280. package/dist/services/anomalyDetection.d.ts +14 -0
  281. package/dist/services/anomalyDetection.d.ts.map +1 -0
  282. package/dist/services/anomalyDetection.js +68 -0
  283. package/dist/services/anomalyDetection.js.map +1 -0
  284. package/dist/services/application/authentication.d.ts +38 -0
  285. package/dist/services/application/authentication.d.ts.map +1 -0
  286. package/dist/services/application/authentication.js +48 -0
  287. package/dist/services/application/authentication.js.map +1 -0
  288. package/dist/services/application/identity.d.ts +34 -0
  289. package/dist/services/application/identity.d.ts.map +1 -0
  290. package/dist/services/application/identity.js +34 -0
  291. package/dist/services/application/identity.js.map +1 -0
  292. package/dist/services/application/index.d.ts +4 -0
  293. package/dist/services/application/index.d.ts.map +1 -0
  294. package/dist/services/application/index.js +4 -0
  295. package/dist/services/application/index.js.map +1 -0
  296. package/dist/services/application/organization.d.ts +44 -0
  297. package/dist/services/application/organization.d.ts.map +1 -0
  298. package/dist/services/application/organization.js +53 -0
  299. package/dist/services/application/organization.js.map +1 -0
  300. package/dist/services/applications.d.ts +25 -0
  301. package/dist/services/applications.d.ts.map +1 -0
  302. package/dist/services/applications.js +64 -0
  303. package/dist/services/applications.js.map +1 -0
  304. package/dist/services/audit.d.ts +16 -0
  305. package/dist/services/audit.d.ts.map +1 -0
  306. package/dist/services/audit.js +28 -0
  307. package/dist/services/audit.js.map +1 -0
  308. package/dist/services/auditExport.d.ts +17 -0
  309. package/dist/services/auditExport.d.ts.map +1 -0
  310. package/dist/services/auditExport.js +37 -0
  311. package/dist/services/auditExport.js.map +1 -0
  312. package/dist/services/billing.d.ts +23 -0
  313. package/dist/services/billing.d.ts.map +1 -0
  314. package/dist/services/billing.js +67 -0
  315. package/dist/services/billing.js.map +1 -0
  316. package/dist/services/cache.d.ts +23 -0
  317. package/dist/services/cache.d.ts.map +1 -0
  318. package/dist/services/cache.js +114 -0
  319. package/dist/services/cache.js.map +1 -0
  320. package/dist/services/configuration/profiles.d.ts +13 -0
  321. package/dist/services/configuration/profiles.d.ts.map +1 -0
  322. package/dist/services/configuration/profiles.js +108 -0
  323. package/dist/services/configuration/profiles.js.map +1 -0
  324. package/dist/services/configuration.d.ts +50 -0
  325. package/dist/services/configuration.d.ts.map +1 -0
  326. package/dist/services/configuration.js +74 -0
  327. package/dist/services/configuration.js.map +1 -0
  328. package/dist/services/connectors/google.d.ts +17 -0
  329. package/dist/services/connectors/google.d.ts.map +1 -0
  330. package/dist/services/connectors/google.js +81 -0
  331. package/dist/services/connectors/google.js.map +1 -0
  332. package/dist/services/connectors/oidc.d.ts +14 -0
  333. package/dist/services/connectors/oidc.d.ts.map +1 -0
  334. package/dist/services/connectors/oidc.js +100 -0
  335. package/dist/services/connectors/oidc.js.map +1 -0
  336. package/dist/services/connectors/registry.d.ts +13 -0
  337. package/dist/services/connectors/registry.d.ts.map +1 -0
  338. package/dist/services/connectors/registry.js +109 -0
  339. package/dist/services/connectors/registry.js.map +1 -0
  340. package/dist/services/connectors/types.d.ts +36 -0
  341. package/dist/services/connectors/types.d.ts.map +1 -0
  342. package/dist/services/connectors/types.js +2 -0
  343. package/dist/services/connectors/types.js.map +1 -0
  344. package/dist/services/connectors/zitadel.d.ts +14 -0
  345. package/dist/services/connectors/zitadel.d.ts.map +1 -0
  346. package/dist/services/connectors/zitadel.js +70 -0
  347. package/dist/services/connectors/zitadel.js.map +1 -0
  348. package/dist/services/devices.d.ts +4 -0
  349. package/dist/services/devices.d.ts.map +1 -0
  350. package/dist/services/devices.js +59 -0
  351. package/dist/services/devices.js.map +1 -0
  352. package/dist/services/domain/authentication.d.ts +51 -0
  353. package/dist/services/domain/authentication.d.ts.map +1 -0
  354. package/dist/services/domain/authentication.js +218 -0
  355. package/dist/services/domain/authentication.js.map +1 -0
  356. package/dist/services/domain/authorization.d.ts +20 -0
  357. package/dist/services/domain/authorization.d.ts.map +1 -0
  358. package/dist/services/domain/authorization.js +36 -0
  359. package/dist/services/domain/authorization.js.map +1 -0
  360. package/dist/services/domain/identity.d.ts +43 -0
  361. package/dist/services/domain/identity.d.ts.map +1 -0
  362. package/dist/services/domain/identity.js +75 -0
  363. package/dist/services/domain/identity.js.map +1 -0
  364. package/dist/services/domain/index.d.ts +5 -0
  365. package/dist/services/domain/index.d.ts.map +1 -0
  366. package/dist/services/domain/index.js +5 -0
  367. package/dist/services/domain/index.js.map +1 -0
  368. package/dist/services/domain/organization.d.ts +60 -0
  369. package/dist/services/domain/organization.d.ts.map +1 -0
  370. package/dist/services/domain/organization.js +87 -0
  371. package/dist/services/domain/organization.js.map +1 -0
  372. package/dist/services/email.d.ts +24 -0
  373. package/dist/services/email.d.ts.map +1 -0
  374. package/dist/services/email.js +127 -0
  375. package/dist/services/email.js.map +1 -0
  376. package/dist/services/emailVerification.d.ts +20 -0
  377. package/dist/services/emailVerification.d.ts.map +1 -0
  378. package/dist/services/emailVerification.js +58 -0
  379. package/dist/services/emailVerification.js.map +1 -0
  380. package/dist/services/enterpriseSso.d.ts +34 -0
  381. package/dist/services/enterpriseSso.d.ts.map +1 -0
  382. package/dist/services/enterpriseSso.js +40 -0
  383. package/dist/services/enterpriseSso.js.map +1 -0
  384. package/dist/services/events/bus.d.ts +9 -0
  385. package/dist/services/events/bus.d.ts.map +1 -0
  386. package/dist/services/events/bus.js +36 -0
  387. package/dist/services/events/bus.js.map +1 -0
  388. package/dist/services/events/subscribers/anomaly.d.ts +3 -0
  389. package/dist/services/events/subscribers/anomaly.d.ts.map +1 -0
  390. package/dist/services/events/subscribers/anomaly.js +13 -0
  391. package/dist/services/events/subscribers/anomaly.js.map +1 -0
  392. package/dist/services/events/subscribers/auditLog.d.ts +3 -0
  393. package/dist/services/events/subscribers/auditLog.d.ts.map +1 -0
  394. package/dist/services/events/subscribers/auditLog.js +21 -0
  395. package/dist/services/events/subscribers/auditLog.js.map +1 -0
  396. package/dist/services/events/subscribers/webhook.d.ts +3 -0
  397. package/dist/services/events/subscribers/webhook.d.ts.map +1 -0
  398. package/dist/services/events/subscribers/webhook.js +36 -0
  399. package/dist/services/events/subscribers/webhook.js.map +1 -0
  400. package/dist/services/events/subscribers/webhookDispatch.d.ts +7 -0
  401. package/dist/services/events/subscribers/webhookDispatch.d.ts.map +1 -0
  402. package/dist/services/events/subscribers/webhookDispatch.js +14 -0
  403. package/dist/services/events/subscribers/webhookDispatch.js.map +1 -0
  404. package/dist/services/events/types.d.ts +21 -0
  405. package/dist/services/events/types.d.ts.map +1 -0
  406. package/dist/services/events/types.js +8 -0
  407. package/dist/services/events/types.js.map +1 -0
  408. package/dist/services/events/validate.d.ts +9 -0
  409. package/dist/services/events/validate.d.ts.map +1 -0
  410. package/dist/services/events/validate.js +103 -0
  411. package/dist/services/events/validate.js.map +1 -0
  412. package/dist/services/featureFlags.d.ts +15 -0
  413. package/dist/services/featureFlags.d.ts.map +1 -0
  414. package/dist/services/featureFlags.js +74 -0
  415. package/dist/services/featureFlags.js.map +1 -0
  416. package/dist/services/features.d.ts +12 -0
  417. package/dist/services/features.d.ts.map +1 -0
  418. package/dist/services/features.js +17 -0
  419. package/dist/services/features.js.map +1 -0
  420. package/dist/services/federation.d.ts +12 -0
  421. package/dist/services/federation.d.ts.map +1 -0
  422. package/dist/services/federation.js +22 -0
  423. package/dist/services/federation.js.map +1 -0
  424. package/dist/services/hibp.d.ts +2 -0
  425. package/dist/services/hibp.d.ts.map +1 -0
  426. package/dist/services/hibp.js +29 -0
  427. package/dist/services/hibp.js.map +1 -0
  428. package/dist/services/ipControls.d.ts +7 -0
  429. package/dist/services/ipControls.d.ts.map +1 -0
  430. package/dist/services/ipControls.js +92 -0
  431. package/dist/services/ipControls.js.map +1 -0
  432. package/dist/services/magicLinks.d.ts +16 -0
  433. package/dist/services/magicLinks.d.ts.map +1 -0
  434. package/dist/services/magicLinks.js +39 -0
  435. package/dist/services/magicLinks.js.map +1 -0
  436. package/dist/services/oauth2.d.ts +58 -0
  437. package/dist/services/oauth2.d.ts.map +1 -0
  438. package/dist/services/oauth2.js +144 -0
  439. package/dist/services/oauth2.js.map +1 -0
  440. package/dist/services/organizations.d.ts +39 -0
  441. package/dist/services/organizations.d.ts.map +1 -0
  442. package/dist/services/organizations.js +135 -0
  443. package/dist/services/organizations.js.map +1 -0
  444. package/dist/services/permissions.d.ts +19 -0
  445. package/dist/services/permissions.d.ts.map +1 -0
  446. package/dist/services/permissions.js +119 -0
  447. package/dist/services/permissions.js.map +1 -0
  448. package/dist/services/plugins/registry.d.ts +17 -0
  449. package/dist/services/plugins/registry.d.ts.map +1 -0
  450. package/dist/services/plugins/registry.js +196 -0
  451. package/dist/services/plugins/registry.js.map +1 -0
  452. package/dist/services/plugins/types.d.ts +86 -0
  453. package/dist/services/plugins/types.d.ts.map +1 -0
  454. package/dist/services/plugins/types.js +2 -0
  455. package/dist/services/plugins/types.js.map +1 -0
  456. package/dist/services/queue/bullmq.d.ts +16 -0
  457. package/dist/services/queue/bullmq.d.ts.map +1 -0
  458. package/dist/services/queue/bullmq.js +89 -0
  459. package/dist/services/queue/bullmq.js.map +1 -0
  460. package/dist/services/queue/inProcess.d.ts +15 -0
  461. package/dist/services/queue/inProcess.d.ts.map +1 -0
  462. package/dist/services/queue/inProcess.js +63 -0
  463. package/dist/services/queue/inProcess.js.map +1 -0
  464. package/dist/services/queue/index.d.ts +7 -0
  465. package/dist/services/queue/index.d.ts.map +1 -0
  466. package/dist/services/queue/index.js +19 -0
  467. package/dist/services/queue/index.js.map +1 -0
  468. package/dist/services/queue/types.d.ts +24 -0
  469. package/dist/services/queue/types.d.ts.map +1 -0
  470. package/dist/services/queue/types.js +2 -0
  471. package/dist/services/queue/types.js.map +1 -0
  472. package/dist/services/redis.d.ts +9 -0
  473. package/dist/services/redis.d.ts.map +1 -0
  474. package/dist/services/redis.js +15 -0
  475. package/dist/services/redis.js.map +1 -0
  476. package/dist/services/secrets/awsKms.d.ts +41 -0
  477. package/dist/services/secrets/awsKms.d.ts.map +1 -0
  478. package/dist/services/secrets/awsKms.js +81 -0
  479. package/dist/services/secrets/awsKms.js.map +1 -0
  480. package/dist/services/secrets/azureKeyVault.d.ts +44 -0
  481. package/dist/services/secrets/azureKeyVault.d.ts.map +1 -0
  482. package/dist/services/secrets/azureKeyVault.js +152 -0
  483. package/dist/services/secrets/azureKeyVault.js.map +1 -0
  484. package/dist/services/secrets/database.d.ts +29 -0
  485. package/dist/services/secrets/database.d.ts.map +1 -0
  486. package/dist/services/secrets/database.js +138 -0
  487. package/dist/services/secrets/database.js.map +1 -0
  488. package/dist/services/secrets/environment.d.ts +27 -0
  489. package/dist/services/secrets/environment.d.ts.map +1 -0
  490. package/dist/services/secrets/environment.js +102 -0
  491. package/dist/services/secrets/environment.js.map +1 -0
  492. package/dist/services/secrets/index.d.ts +30 -0
  493. package/dist/services/secrets/index.d.ts.map +1 -0
  494. package/dist/services/secrets/index.js +46 -0
  495. package/dist/services/secrets/index.js.map +1 -0
  496. package/dist/services/secrets/password.d.ts +10 -0
  497. package/dist/services/secrets/password.d.ts.map +1 -0
  498. package/dist/services/secrets/password.js +62 -0
  499. package/dist/services/secrets/password.js.map +1 -0
  500. package/dist/services/secrets/provider.d.ts +36 -0
  501. package/dist/services/secrets/provider.d.ts.map +1 -0
  502. package/dist/services/secrets/provider.js +2 -0
  503. package/dist/services/secrets/provider.js.map +1 -0
  504. package/dist/services/secrets/vault.d.ts +41 -0
  505. package/dist/services/secrets/vault.d.ts.map +1 -0
  506. package/dist/services/secrets/vault.js +133 -0
  507. package/dist/services/secrets/vault.js.map +1 -0
  508. package/dist/services/secrets.d.ts +2 -0
  509. package/dist/services/secrets.d.ts.map +1 -0
  510. package/dist/services/secrets.js +3 -0
  511. package/dist/services/secrets.js.map +1 -0
  512. package/dist/services/serviceAccounts.d.ts +24 -0
  513. package/dist/services/serviceAccounts.d.ts.map +1 -0
  514. package/dist/services/serviceAccounts.js +53 -0
  515. package/dist/services/serviceAccounts.js.map +1 -0
  516. package/dist/services/setup/configWriter.d.ts +18 -0
  517. package/dist/services/setup/configWriter.d.ts.map +1 -0
  518. package/dist/services/setup/configWriter.js +192 -0
  519. package/dist/services/setup/configWriter.js.map +1 -0
  520. package/dist/services/setup/diagnostics.d.ts +7 -0
  521. package/dist/services/setup/diagnostics.d.ts.map +1 -0
  522. package/dist/services/setup/diagnostics.js +73 -0
  523. package/dist/services/setup/diagnostics.js.map +1 -0
  524. package/dist/services/setup/token.d.ts +5 -0
  525. package/dist/services/setup/token.d.ts.map +1 -0
  526. package/dist/services/setup/token.js +37 -0
  527. package/dist/services/setup/token.js.map +1 -0
  528. package/dist/services/setup/types.d.ts +35 -0
  529. package/dist/services/setup/types.d.ts.map +1 -0
  530. package/dist/services/setup/types.js +2 -0
  531. package/dist/services/setup/types.js.map +1 -0
  532. package/dist/services/setup/validation.d.ts +7 -0
  533. package/dist/services/setup/validation.d.ts.map +1 -0
  534. package/dist/services/setup/validation.js +198 -0
  535. package/dist/services/setup/validation.js.map +1 -0
  536. package/dist/services/sms.d.ts +10 -0
  537. package/dist/services/sms.d.ts.map +1 -0
  538. package/dist/services/sms.js +62 -0
  539. package/dist/services/sms.js.map +1 -0
  540. package/dist/services/smsOtp.d.ts +7 -0
  541. package/dist/services/smsOtp.d.ts.map +1 -0
  542. package/dist/services/smsOtp.js +56 -0
  543. package/dist/services/smsOtp.js.map +1 -0
  544. package/dist/services/tokens.d.ts +66 -0
  545. package/dist/services/tokens.d.ts.map +1 -0
  546. package/dist/services/tokens.js +205 -0
  547. package/dist/services/tokens.js.map +1 -0
  548. package/dist/services/totp.d.ts +16 -0
  549. package/dist/services/totp.d.ts.map +1 -0
  550. package/dist/services/totp.js +96 -0
  551. package/dist/services/totp.js.map +1 -0
  552. package/dist/services/users.d.ts +39 -0
  553. package/dist/services/users.d.ts.map +1 -0
  554. package/dist/services/users.js +181 -0
  555. package/dist/services/users.js.map +1 -0
  556. package/dist/services/webauthn.d.ts +45 -0
  557. package/dist/services/webauthn.d.ts.map +1 -0
  558. package/dist/services/webauthn.js +147 -0
  559. package/dist/services/webauthn.js.map +1 -0
  560. package/dist/services/webhooks.d.ts +86 -0
  561. package/dist/services/webhooks.d.ts.map +1 -0
  562. package/dist/services/webhooks.js +164 -0
  563. package/dist/services/webhooks.js.map +1 -0
  564. package/dist/services/workflows/engine.d.ts +18 -0
  565. package/dist/services/workflows/engine.d.ts.map +1 -0
  566. package/dist/services/workflows/engine.js +104 -0
  567. package/dist/services/workflows/engine.js.map +1 -0
  568. package/dist/services/workflows/steps.d.ts +17 -0
  569. package/dist/services/workflows/steps.d.ts.map +1 -0
  570. package/dist/services/workflows/steps.js +109 -0
  571. package/dist/services/workflows/steps.js.map +1 -0
  572. package/dist/services/zitadel.d.ts +21 -0
  573. package/dist/services/zitadel.d.ts.map +1 -0
  574. package/dist/services/zitadel.js +228 -0
  575. package/dist/services/zitadel.js.map +1 -0
  576. package/dist/setup-server.d.ts +2 -0
  577. package/dist/setup-server.d.ts.map +1 -0
  578. package/dist/setup-server.js +63 -0
  579. package/dist/setup-server.js.map +1 -0
  580. package/dist/tests/errors.test.d.ts +2 -0
  581. package/dist/tests/errors.test.d.ts.map +1 -0
  582. package/dist/tests/errors.test.js +64 -0
  583. package/dist/tests/errors.test.js.map +1 -0
  584. package/dist/tests/events.test.d.ts +2 -0
  585. package/dist/tests/events.test.d.ts.map +1 -0
  586. package/dist/tests/events.test.js +45 -0
  587. package/dist/tests/events.test.js.map +1 -0
  588. package/dist/tests/featureFlags.test.d.ts +2 -0
  589. package/dist/tests/featureFlags.test.d.ts.map +1 -0
  590. package/dist/tests/featureFlags.test.js +24 -0
  591. package/dist/tests/featureFlags.test.js.map +1 -0
  592. package/dist/tests/integration/queue.test.d.ts +2 -0
  593. package/dist/tests/integration/queue.test.d.ts.map +1 -0
  594. package/dist/tests/integration/queue.test.js +49 -0
  595. package/dist/tests/integration/queue.test.js.map +1 -0
  596. package/dist/tests/plugins.test.d.ts +2 -0
  597. package/dist/tests/plugins.test.d.ts.map +1 -0
  598. package/dist/tests/plugins.test.js +56 -0
  599. package/dist/tests/plugins.test.js.map +1 -0
  600. package/dist/tests/result.test.d.ts +2 -0
  601. package/dist/tests/result.test.d.ts.map +1 -0
  602. package/dist/tests/result.test.js +46 -0
  603. package/dist/tests/result.test.js.map +1 -0
  604. package/dist/tests/setup/configWriter.test.d.ts +2 -0
  605. package/dist/tests/setup/configWriter.test.d.ts.map +1 -0
  606. package/dist/tests/setup/configWriter.test.js +55 -0
  607. package/dist/tests/setup/configWriter.test.js.map +1 -0
  608. package/dist/tests/setup/validation.test.d.ts +2 -0
  609. package/dist/tests/setup/validation.test.d.ts.map +1 -0
  610. package/dist/tests/setup/validation.test.js +26 -0
  611. package/dist/tests/setup/validation.test.js.map +1 -0
  612. package/dist/tests/smoke.test.d.ts +2 -0
  613. package/dist/tests/smoke.test.d.ts.map +1 -0
  614. package/dist/tests/smoke.test.js +124 -0
  615. package/dist/tests/smoke.test.js.map +1 -0
  616. package/dist/types.d.ts +50 -0
  617. package/dist/types.d.ts.map +1 -0
  618. package/dist/types.js +17 -0
  619. package/dist/types.js.map +1 -0
  620. package/package.json +69 -0
  621. package/src/cli.ts +172 -0
  622. package/src/config.ts +143 -0
  623. package/src/container.ts +48 -0
  624. package/src/db/index.ts +53 -0
  625. package/src/db/migrations/0000_skinny_ben_parker.sql +553 -0
  626. package/src/db/migrations/0001_brief_joseph.sql +10 -0
  627. package/src/db/migrations/0002_add_account_lockout.sql +3 -0
  628. package/src/db/migrations/0003_steep_rachel_grey.sql +1 -0
  629. package/src/db/migrations/0004_clever_bill_hollister.sql +20 -0
  630. package/src/db/migrations/0005_steep_the_call.sql +2 -0
  631. package/src/db/migrations/0006_ambitious_boomer.sql +17 -0
  632. package/src/db/migrations/0007_greedy_vindicator.sql +40 -0
  633. package/src/db/migrations/meta/0000_snapshot.json +2964 -0
  634. package/src/db/migrations/meta/0001_snapshot.json +3031 -0
  635. package/src/db/migrations/meta/0003_snapshot.json +3051 -0
  636. package/src/db/migrations/meta/0004_snapshot.json +3163 -0
  637. package/src/db/migrations/meta/0005_snapshot.json +3177 -0
  638. package/src/db/migrations/meta/0006_snapshot.json +3270 -0
  639. package/src/db/migrations/meta/0007_snapshot.json +3489 -0
  640. package/src/db/migrations/meta/_journal.json +62 -0
  641. package/src/db/schema.ts +676 -0
  642. package/src/db/seed.ts +146 -0
  643. package/src/di.ts +81 -0
  644. package/src/index.ts +326 -0
  645. package/src/lib/errors.ts +139 -0
  646. package/src/lib/result.ts +44 -0
  647. package/src/lib/webhookSignature.ts +41 -0
  648. package/src/plugins/appContext.ts +76 -0
  649. package/src/plugins/audit.ts +42 -0
  650. package/src/plugins/auth.ts +230 -0
  651. package/src/plugins/metrics.ts +41 -0
  652. package/src/plugins/mtls.ts +94 -0
  653. package/src/plugins/permissions.ts +29 -0
  654. package/src/plugins/rateLimit.ts +133 -0
  655. package/src/plugins/requestLogger.ts +25 -0
  656. package/src/plugins/tracing.ts +22 -0
  657. package/src/repositories/apiKey.ts +158 -0
  658. package/src/repositories/application.ts +70 -0
  659. package/src/repositories/audit.ts +32 -0
  660. package/src/repositories/index.ts +9 -0
  661. package/src/repositories/oidcConnection.ts +111 -0
  662. package/src/repositories/organization.ts +167 -0
  663. package/src/repositories/permission.ts +153 -0
  664. package/src/repositories/samlConnection.ts +96 -0
  665. package/src/repositories/session.ts +86 -0
  666. package/src/repositories/types.ts +134 -0
  667. package/src/repositories/user.ts +161 -0
  668. package/src/routes/admin/billing.ts +48 -0
  669. package/src/routes/admin/helpers.ts +50 -0
  670. package/src/routes/admin/index.ts +16 -0
  671. package/src/routes/admin/organizations.ts +299 -0
  672. package/src/routes/admin/permissions.ts +80 -0
  673. package/src/routes/admin/platform.ts +335 -0
  674. package/src/routes/admin/sso.ts +138 -0
  675. package/src/routes/admin/webhooks.ts +73 -0
  676. package/src/routes/admin.ts +1 -0
  677. package/src/routes/apiKeys.ts +60 -0
  678. package/src/routes/auth.ts +214 -0
  679. package/src/routes/authz.ts +38 -0
  680. package/src/routes/config.ts +67 -0
  681. package/src/routes/emailVerification.ts +73 -0
  682. package/src/routes/federation.ts +156 -0
  683. package/src/routes/helpers.ts +17 -0
  684. package/src/routes/magicLinks.ts +107 -0
  685. package/src/routes/oauth.ts +167 -0
  686. package/src/routes/oauth2.ts +284 -0
  687. package/src/routes/oidcEnterprise.ts +166 -0
  688. package/src/routes/password.ts +90 -0
  689. package/src/routes/profile.ts +44 -0
  690. package/src/routes/saml.ts +209 -0
  691. package/src/routes/scim.ts +199 -0
  692. package/src/routes/sdk.ts +141 -0
  693. package/src/routes/serviceAccounts.ts +124 -0
  694. package/src/routes/sessions.ts +62 -0
  695. package/src/routes/setup.ts +315 -0
  696. package/src/routes/smsOtp.ts +67 -0
  697. package/src/routes/totp.ts +122 -0
  698. package/src/routes/webauthn.ts +147 -0
  699. package/src/routes/workflows.ts +157 -0
  700. package/src/sdk/index.ts +152 -0
  701. package/src/sdk/types.ts +54 -0
  702. package/src/services/anomalyDetection.ts +73 -0
  703. package/src/services/application/authentication.ts +75 -0
  704. package/src/services/application/identity.ts +56 -0
  705. package/src/services/application/index.ts +3 -0
  706. package/src/services/application/organization.ts +77 -0
  707. package/src/services/applications.ts +89 -0
  708. package/src/services/audit.ts +41 -0
  709. package/src/services/auditExport.ts +59 -0
  710. package/src/services/billing.ts +87 -0
  711. package/src/services/cache.ts +131 -0
  712. package/src/services/configuration/profiles.ts +115 -0
  713. package/src/services/configuration.ts +120 -0
  714. package/src/services/connectors/google.ts +92 -0
  715. package/src/services/connectors/oidc.ts +111 -0
  716. package/src/services/connectors/registry.ts +124 -0
  717. package/src/services/connectors/types.ts +38 -0
  718. package/src/services/connectors/zitadel.ts +77 -0
  719. package/src/services/devices.ts +76 -0
  720. package/src/services/domain/authentication.ts +279 -0
  721. package/src/services/domain/authorization.ts +49 -0
  722. package/src/services/domain/identity.ts +108 -0
  723. package/src/services/domain/index.ts +4 -0
  724. package/src/services/domain/organization.ts +114 -0
  725. package/src/services/email.ts +167 -0
  726. package/src/services/emailVerification.ts +75 -0
  727. package/src/services/enterpriseSso.ts +58 -0
  728. package/src/services/events/bus.ts +43 -0
  729. package/src/services/events/subscribers/anomaly.ts +13 -0
  730. package/src/services/events/subscribers/auditLog.ts +21 -0
  731. package/src/services/events/subscribers/webhook.ts +39 -0
  732. package/src/services/events/subscribers/webhookDispatch.ts +14 -0
  733. package/src/services/events/types.ts +106 -0
  734. package/src/services/events/validate.ts +118 -0
  735. package/src/services/featureFlags.ts +90 -0
  736. package/src/services/features.ts +22 -0
  737. package/src/services/federation.ts +30 -0
  738. package/src/services/hibp.ts +28 -0
  739. package/src/services/ipControls.ts +99 -0
  740. package/src/services/magicLinks.ts +51 -0
  741. package/src/services/oauth2.ts +216 -0
  742. package/src/services/organizations.ts +171 -0
  743. package/src/services/permissions.ts +146 -0
  744. package/src/services/plugins/registry.ts +242 -0
  745. package/src/services/plugins/types.ts +98 -0
  746. package/src/services/queue/bullmq.ts +104 -0
  747. package/src/services/queue/inProcess.ts +75 -0
  748. package/src/services/queue/index.ts +19 -0
  749. package/src/services/queue/types.ts +26 -0
  750. package/src/services/redis.ts +16 -0
  751. package/src/services/secrets/awsKms.ts +97 -0
  752. package/src/services/secrets/azureKeyVault.ts +171 -0
  753. package/src/services/secrets/database.ts +166 -0
  754. package/src/services/secrets/environment.ts +117 -0
  755. package/src/services/secrets/index.ts +50 -0
  756. package/src/services/secrets/password.ts +73 -0
  757. package/src/services/secrets/provider.ts +38 -0
  758. package/src/services/secrets/vault.ts +149 -0
  759. package/src/services/secrets.ts +2 -0
  760. package/src/services/serviceAccounts.ts +74 -0
  761. package/src/services/setup/configWriter.ts +200 -0
  762. package/src/services/setup/diagnostics.ts +76 -0
  763. package/src/services/setup/token.ts +42 -0
  764. package/src/services/setup/types.ts +40 -0
  765. package/src/services/setup/validation.ts +205 -0
  766. package/src/services/sms.ts +81 -0
  767. package/src/services/smsOtp.ts +74 -0
  768. package/src/services/tokens.ts +288 -0
  769. package/src/services/totp.ts +113 -0
  770. package/src/services/users.ts +239 -0
  771. package/src/services/webauthn.ts +193 -0
  772. package/src/services/webhooks.ts +190 -0
  773. package/src/services/workflows/engine.ts +125 -0
  774. package/src/services/workflows/steps.ts +129 -0
  775. package/src/services/zitadel.ts +277 -0
  776. package/src/setup-server.ts +71 -0
  777. package/src/tests/errors.test.ts +74 -0
  778. package/src/tests/events.test.ts +52 -0
  779. package/src/tests/featureFlags.test.ts +26 -0
  780. package/src/tests/integration/queue.test.ts +54 -0
  781. package/src/tests/plugins.test.ts +73 -0
  782. package/src/tests/result.test.ts +52 -0
  783. package/src/tests/setup/configWriter.test.ts +69 -0
  784. package/src/tests/setup/validation.test.ts +29 -0
  785. package/src/tests/smoke.test.ts +136 -0
  786. package/src/types.ts +70 -0
@@ -0,0 +1,124 @@
1
+ import { z } from "zod";
2
+ import type { FastifyInstance, FastifyRequest, FastifyReply } from "fastify";
3
+ import {
4
+ createServiceAccount,
5
+ findServiceAccountsByOrgId,
6
+ findServiceAccountById,
7
+ updateServiceAccount,
8
+ listServiceAccountApiKeys,
9
+ } from "../services/serviceAccounts.js";
10
+ import { generateApiKey, hashApiKey } from "../services/tokens.js";
11
+
12
+ const CreateSchema = z.object({
13
+ name: z.string().min(1).max(100),
14
+ description: z.string().max(500).optional(),
15
+ });
16
+
17
+ const UpdateSchema = z.object({
18
+ name: z.string().min(1).max(100).optional(),
19
+ description: z.string().max(500).optional(),
20
+ isActive: z.boolean().optional(),
21
+ });
22
+
23
+ const CreateKeySchema = z.object({
24
+ name: z.string().min(1).max(100),
25
+ scopes: z.array(z.string()).optional(),
26
+ expiresAt: z.string().datetime().optional(),
27
+ });
28
+
29
+ export default async function serviceAccountRoutes(app: FastifyInstance) {
30
+ app.post(
31
+ "/organizations/:id/service-accounts",
32
+ { preHandler: [app.requirePermission("service_account", "create")] },
33
+ async (request: FastifyRequest, reply: FastifyReply) => {
34
+ const { id } = request.params as { id: string };
35
+ const body = CreateSchema.parse(request.body);
36
+
37
+ const record = await createServiceAccount({
38
+ orgId: id,
39
+ name: body.name,
40
+ description: body.description,
41
+ });
42
+
43
+ await request.audit("service_account_created", { orgId: id, serviceAccountId: record.id });
44
+ return reply.status(201).send(record);
45
+ }
46
+ );
47
+
48
+ app.get(
49
+ "/organizations/:id/service-accounts",
50
+ { preHandler: [app.requirePermission("service_account", "read")] },
51
+ async (request: FastifyRequest) => {
52
+ const { id } = request.params as { id: string };
53
+ const accounts = await findServiceAccountsByOrgId(id);
54
+ return { serviceAccounts: accounts };
55
+ }
56
+ );
57
+
58
+ app.get(
59
+ "/organizations/:id/service-accounts/:accountId",
60
+ { preHandler: [app.requirePermission("service_account", "read")] },
61
+ async (request: FastifyRequest, reply: FastifyReply) => {
62
+ const { id, accountId } = request.params as { id: string; accountId: string };
63
+ const record = await findServiceAccountById(accountId, id);
64
+ if (!record) {
65
+ return reply.status(404).send({ error: "Service account not found" });
66
+ }
67
+ const keys = await listServiceAccountApiKeys(accountId);
68
+ return { ...record, apiKeys: keys };
69
+ }
70
+ );
71
+
72
+ app.patch(
73
+ "/organizations/:id/service-accounts/:accountId",
74
+ { preHandler: [app.requirePermission("service_account", "update")] },
75
+ async (request: FastifyRequest, reply: FastifyReply) => {
76
+ const { id, accountId } = request.params as { id: string; accountId: string };
77
+ const body = UpdateSchema.parse(request.body);
78
+
79
+ const updated = await updateServiceAccount(accountId, id, body);
80
+ if (!updated) {
81
+ return reply.status(404).send({ error: "Service account not found" });
82
+ }
83
+
84
+ await request.audit("service_account_updated", {
85
+ orgId: id,
86
+ serviceAccountId: updated.id,
87
+ });
88
+ return updated;
89
+ }
90
+ );
91
+
92
+ app.post(
93
+ "/organizations/:id/service-accounts/:accountId/api-keys",
94
+ { preHandler: [app.requirePermission("api_key", "create")] },
95
+ async (request: FastifyRequest, reply: FastifyReply) => {
96
+ const { id, accountId } = request.params as { id: string; accountId: string };
97
+ const body = CreateKeySchema.parse(request.body);
98
+
99
+ const account = await findServiceAccountById(accountId, id);
100
+ if (!account) {
101
+ return reply.status(404).send({ error: "Service account not found" });
102
+ }
103
+
104
+ const { key, prefix } = generateApiKey();
105
+ const record = await app.container.apiKeyRepository.create({
106
+ serviceAccountId: account.id,
107
+ orgId: id,
108
+ name: body.name,
109
+ prefix,
110
+ keyHash: hashApiKey(key),
111
+ scopes: body.scopes?.length ? body.scopes : ["api:read"],
112
+ expiresAt: body.expiresAt ? new Date(body.expiresAt) : null,
113
+ });
114
+
115
+ await request.audit("api_key_created", {
116
+ orgId: id,
117
+ serviceAccountId: account.id,
118
+ keyId: record.id,
119
+ });
120
+
121
+ return { key, apiKey: record };
122
+ }
123
+ );
124
+ }
@@ -0,0 +1,62 @@
1
+ import crypto from "node:crypto";
2
+ import type { FastifyInstance, FastifyRequest, FastifyReply } from "fastify";
3
+ import { config } from "../config.js";
4
+ import { SessionRepository } from "../repositories/session.js";
5
+
6
+ const sessions = new SessionRepository();
7
+
8
+ function hashToken(token: string): string {
9
+ return crypto.createHash("sha256").update(token).digest("hex");
10
+ }
11
+
12
+ export default async function sessionRoutes(app: FastifyInstance) {
13
+ app.get("/sessions", { preHandler: [app.authenticate] }, async (request: FastifyRequest) => {
14
+ const userId = request.user?.id;
15
+ if (!userId) return { sessions: [] };
16
+ const list = await sessions.listByUser(userId);
17
+ return {
18
+ sessions: list.map((s) => ({
19
+ id: s.id,
20
+ deviceFingerprint: s.deviceFingerprint,
21
+ ipAddress: s.ipAddress,
22
+ userAgent: s.userAgent,
23
+ lastSeenAt: s.lastSeenAt,
24
+ expiresAt: s.expiresAt,
25
+ createdAt: s.createdAt,
26
+ })),
27
+ };
28
+ });
29
+
30
+ app.delete("/sessions/:id", { preHandler: [app.authenticate] }, async (request: FastifyRequest, reply: FastifyReply) => {
31
+ const userId = request.user?.id;
32
+ const { id } = request.params as { id: string };
33
+ if (!userId) return reply.status(401).send({ error: "Unauthorized" });
34
+
35
+ const session = await sessions.findById(id);
36
+ if (!session || session.userId !== userId) {
37
+ return reply.status(404).send({ error: "Session not found" });
38
+ }
39
+
40
+ await sessions.revokeRefreshToken(session.refreshTokenId);
41
+ await sessions.deleteById(id, userId);
42
+
43
+ await request.audit("session_revoked", { sessionId: id });
44
+ return { success: true };
45
+ });
46
+
47
+ app.post("/sessions/revoke-all", { preHandler: [app.authenticate] }, async (request: FastifyRequest, reply: FastifyReply) => {
48
+ const userId = request.user?.id;
49
+ if (!userId) return reply.status(401).send({ error: "Unauthorized" });
50
+
51
+ const currentRefreshToken = request.cookies?.[config.COOKIE_NAME];
52
+ let currentRefreshTokenId: string | undefined;
53
+ if (currentRefreshToken) {
54
+ const row = await sessions.findRefreshTokenByHash(hashToken(currentRefreshToken));
55
+ currentRefreshTokenId = row?.id;
56
+ }
57
+
58
+ await sessions.deleteAllForUser(userId, currentRefreshTokenId);
59
+ await request.audit("sessions_revoked_all", { exceptSessionId: currentRefreshTokenId });
60
+ return { success: true };
61
+ });
62
+ }
@@ -0,0 +1,315 @@
1
+ import { z } from "zod";
2
+ import type { FastifyInstance, FastifyRequest, FastifyReply } from "fastify";
3
+ import { eq, count } from "drizzle-orm";
4
+ import { migrate } from "drizzle-orm/postgres-js/migrator";
5
+ import fs from "node:fs/promises";
6
+ import path from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import { db, initDb } from "../db/index.js";
9
+ import { users } from "../db/schema.js";
10
+ import { AuthenticationDomainService } from "../services/domain/authentication.js";
11
+ import { DrizzleUserRepository, DrizzleApplicationRepository } from "../repositories/index.js";
12
+ import { validateDatabase, validateRedis, validateEmail, validateSms } from "../services/setup/validation.js";
13
+ import { createConfigWriter } from "../services/setup/configWriter.js";
14
+ import { getSetupToken, validateSetupToken } from "../services/setup/token.js";
15
+ import { runSetupDiagnostics } from "../services/setup/diagnostics.js";
16
+ import { queue } from "../services/queue/index.js";
17
+
18
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
19
+ const SETUP_MARKER_PATH = path.resolve(__dirname, "../../.keystone-setup-complete");
20
+
21
+ const SetupInitSchema = z.object({
22
+ email: z.string().email(),
23
+ password: z.string().min(8),
24
+ name: z.string().optional(),
25
+ username: z.string().optional(),
26
+ });
27
+
28
+ const ValidateDatabaseSchema = z.object({
29
+ databaseUrl: z.string().min(1),
30
+ });
31
+
32
+ const ValidateRedisSchema = z.object({
33
+ redisUrl: z.string().min(1),
34
+ });
35
+
36
+ const ValidateEmailSchema = z.object({
37
+ provider: z.enum(["none", "console", "smtp", "sendgrid", "mailgun"]),
38
+ from: z.string().email(),
39
+ smtpHost: z.string().optional(),
40
+ smtpPort: z.coerce.number().optional(),
41
+ smtpUser: z.string().optional(),
42
+ smtpPass: z.string().optional(),
43
+ smtpSecure: z.boolean().optional(),
44
+ sendgridApiKey: z.string().optional(),
45
+ mailgunApiKey: z.string().optional(),
46
+ mailgunDomain: z.string().optional(),
47
+ to: z.string().email(),
48
+ });
49
+
50
+ const ValidateSmsSchema = z.object({
51
+ provider: z.enum(["none", "console", "twilio"]),
52
+ twilioAccountSid: z.string().optional(),
53
+ twilioAuthToken: z.string().optional(),
54
+ twilioFromNumber: z.string().optional(),
55
+ twilioMessagingServiceSid: z.string().optional(),
56
+ to: z.string().min(1),
57
+ });
58
+
59
+ const SetupConfigSchema = z.object({
60
+ env: z.record(z.string()),
61
+ });
62
+
63
+ function parseBody<T>(schema: z.ZodSchema<T>, body: unknown, reply: FastifyReply): T | null {
64
+ const result = schema.safeParse(body);
65
+ if (!result.success) {
66
+ const issues = result.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ");
67
+ reply.status(400).send({ error: `Invalid input: ${issues}`, code: "VALIDATION_ERROR" });
68
+ return null;
69
+ }
70
+ return result.data;
71
+ }
72
+
73
+ async function hasNoUsers(): Promise<boolean> {
74
+ if (!db) return true;
75
+ try {
76
+ const [result] = await db.select({ total: count() }).from(users);
77
+ return (result?.total ?? 0) === 0;
78
+ } catch {
79
+ // Database exists but migrations have not run yet; setup is still required.
80
+ return true;
81
+ }
82
+ }
83
+
84
+ async function hasNoOwners(): Promise<boolean> {
85
+ if (!db) return true;
86
+ try {
87
+ const [result] = await db.select({ total: count() }).from(users).where(eq(users.role, "owner"));
88
+ return (result?.total ?? 0) === 0;
89
+ } catch {
90
+ return true;
91
+ }
92
+ }
93
+
94
+ async function ensureDbInitialized(request: FastifyRequest, reply: FastifyReply): Promise<boolean> {
95
+ if (db) return true;
96
+ try {
97
+ const writer = createConfigWriter();
98
+ const values = await writer.read();
99
+ const databaseUrl = values.DATABASE_URL;
100
+ if (!databaseUrl) {
101
+ request.log.warn({ configKeys: Object.keys(values) }, "DATABASE_URL missing when initializing database");
102
+ reply.status(400).send({ error: "DATABASE_URL is not configured. Apply configuration first.", code: "DATABASE_URL_MISSING" });
103
+ return false;
104
+ }
105
+ process.env.DATABASE_URL = databaseUrl;
106
+ initDb();
107
+ return true;
108
+ } catch (err) {
109
+ const message = err instanceof Error ? err.message : String(err);
110
+ request.log.error({ err }, "Database initialization failed");
111
+ reply.status(500).send({ error: message, code: "DB_INIT_FAILED" });
112
+ return false;
113
+ }
114
+ }
115
+
116
+ function assertSetupToken(request: FastifyRequest, reply: FastifyReply): boolean {
117
+ const token = request.headers["x-setup-token"] as string | undefined;
118
+ if (!validateSetupToken(token)) {
119
+ request.log.warn(
120
+ { hasToken: Boolean(token), tokenLength: token?.length, expectedLength: getSetupToken()?.length },
121
+ "Invalid or missing setup token"
122
+ );
123
+ reply.status(401).send({ error: "Invalid or missing setup token" });
124
+ return false;
125
+ }
126
+ return true;
127
+ }
128
+
129
+ export default async function setupRoutes(app: FastifyInstance) {
130
+ app.get("/status", async () => {
131
+ return {
132
+ needsSetup: await hasNoOwners(),
133
+ setupToken: Boolean(getSetupToken()),
134
+ };
135
+ });
136
+
137
+ app.get("/diagnostics", async (request: FastifyRequest, reply: FastifyReply) => {
138
+ if (!assertSetupToken(request, reply)) return;
139
+ const checks = await runSetupDiagnostics();
140
+ return { checks, ready: checks.every((c) => c.status === "ok" || c.status === "skipped") };
141
+ });
142
+
143
+ app.post("/config/dry-run", async (request: FastifyRequest, reply: FastifyReply) => {
144
+ if (!assertSetupToken(request, reply)) return;
145
+ const body = parseBody(SetupConfigSchema, request.body, reply);
146
+ if (!body) return;
147
+
148
+ const writer = createConfigWriter();
149
+ const existing = await writer.read();
150
+ const merged = { ...existing, ...body.env };
151
+
152
+ const validationErrors: string[] = [];
153
+ if (!merged.DATABASE_URL) validationErrors.push("DATABASE_URL is required");
154
+ if (!merged.REDIS_URL) validationErrors.push("REDIS_URL is required");
155
+ if (!merged.AUTH_API_PUBLIC_URL) validationErrors.push("AUTH_API_PUBLIC_URL is required");
156
+
157
+ return {
158
+ ok: validationErrors.length === 0,
159
+ validationErrors,
160
+ wouldWrite: Object.keys(body.env),
161
+ mergedPreview: Object.fromEntries(
162
+ Object.entries(merged).map(([k, v]) => [k, k.includes("KEY") || k.includes("SECRET") || k.includes("PASS") ? "***" : v])
163
+ ),
164
+ };
165
+ });
166
+
167
+ app.post("/validate/db", async (request: FastifyRequest, reply: FastifyReply) => {
168
+ if (!assertSetupToken(request, reply)) return;
169
+ const body = parseBody(ValidateDatabaseSchema, request.body, reply);
170
+ if (!body) return;
171
+ const result = await validateDatabase(body);
172
+ if (!result.success) {
173
+ request.log.warn({ code: result.error.code, message: result.error.message }, "Database validation failed");
174
+ return reply.status(result.error.statusCode || 400).send({ error: result.error.message, code: result.error.code });
175
+ }
176
+ return { ok: true };
177
+ });
178
+
179
+ app.post("/validate/redis", async (request: FastifyRequest, reply: FastifyReply) => {
180
+ if (!assertSetupToken(request, reply)) return;
181
+ const body = parseBody(ValidateRedisSchema, request.body, reply);
182
+ if (!body) return;
183
+ const result = await validateRedis(body);
184
+ if (!result.success) {
185
+ request.log.warn({ code: result.error.code, message: result.error.message }, "Redis validation failed");
186
+ return reply.status(result.error.statusCode || 400).send({ error: result.error.message, code: result.error.code });
187
+ }
188
+ return { ok: true };
189
+ });
190
+
191
+ app.post("/validate/email", async (request: FastifyRequest, reply: FastifyReply) => {
192
+ if (!assertSetupToken(request, reply)) return;
193
+ const body = parseBody(ValidateEmailSchema, request.body, reply);
194
+ if (!body) return;
195
+ const { to, ...input } = body;
196
+ const result = await validateEmail(input, to);
197
+ if (!result.success) {
198
+ return reply.status(result.error.statusCode || 400).send({ error: result.error.message, code: result.error.code });
199
+ }
200
+ return { ok: true };
201
+ });
202
+
203
+ app.post("/validate/sms", async (request: FastifyRequest, reply: FastifyReply) => {
204
+ if (!assertSetupToken(request, reply)) return;
205
+ const body = parseBody(ValidateSmsSchema, request.body, reply);
206
+ if (!body) return;
207
+ const { to, ...input } = body;
208
+ const result = await validateSms(input, to);
209
+ if (!result.success) {
210
+ return reply.status(result.error.statusCode || 400).send({ error: result.error.message, code: result.error.code });
211
+ }
212
+ return { ok: true };
213
+ });
214
+
215
+ app.post("/config", async (request: FastifyRequest, reply: FastifyReply) => {
216
+ if (!assertSetupToken(request, reply)) return;
217
+
218
+ const body = parseBody(SetupConfigSchema, request.body, reply);
219
+ if (!body) return;
220
+ const writer = createConfigWriter();
221
+
222
+ const backup = await writer.backup();
223
+ if (!backup.success) {
224
+ return reply.status(backup.error.statusCode || 500).send({ error: backup.error.message, code: backup.error.code });
225
+ }
226
+
227
+ const writeResult = await writer.write(body.env);
228
+ if (!writeResult.success) {
229
+ return reply.status(writeResult.error.statusCode || 500).send({ error: writeResult.error.message, code: writeResult.error.code });
230
+ }
231
+
232
+ return { ok: true, backupPath: backup.data || undefined };
233
+ });
234
+
235
+ app.post("/migrate", async (request: FastifyRequest, reply: FastifyReply) => {
236
+ if (!assertSetupToken(request, reply)) return;
237
+ if (!(await ensureDbInitialized(request, reply))) return;
238
+ try {
239
+ await migrate(db, { migrationsFolder: path.resolve(__dirname, "../db/migrations") });
240
+ return { ok: true };
241
+ } catch (err) {
242
+ request.log.error({ err }, "Migration failed");
243
+ const message = err instanceof Error ? err.message : String(err);
244
+ return reply.status(500).send({ error: message, code: "MIGRATION_FAILED" });
245
+ }
246
+ });
247
+
248
+ app.post("/restart", async (request: FastifyRequest, reply: FastifyReply) => {
249
+ if (!assertSetupToken(request, reply)) return;
250
+ reply.status(202).send({ ok: true, message: "Server is restarting" });
251
+ try {
252
+ await queue.close?.();
253
+ } catch {
254
+ // ignore
255
+ }
256
+ setTimeout(() => process.exit(0), 500);
257
+ });
258
+
259
+ app.post("/init", async (request: FastifyRequest, reply: FastifyReply) => {
260
+ if (!assertSetupToken(request, reply)) return;
261
+ if (!(await ensureDbInitialized(request, reply))) return;
262
+ if (!(await hasNoOwners())) {
263
+ return reply.status(403).send({ error: "Setup has already been completed" });
264
+ }
265
+
266
+ const body = parseBody(SetupInitSchema, request.body, reply);
267
+ if (!body) return;
268
+
269
+ // If a user with this email already exists (e.g. from an interrupted setup),
270
+ // promote them to owner instead of failing with a duplicate-key error.
271
+ const [existing] = await db.select().from(users).where(eq(users.email, body.email)).limit(1);
272
+
273
+ let ownerUser;
274
+ if (existing) {
275
+ await db.update(users).set({ role: "owner" }).where(eq(users.id, existing.id));
276
+ ownerUser = existing;
277
+ } else {
278
+ const authService = new AuthenticationDomainService(new DrizzleUserRepository(), new DrizzleApplicationRepository());
279
+ const result = await authService.register({
280
+ email: body.email,
281
+ password: body.password,
282
+ name: body.name,
283
+ username:
284
+ body.username ||
285
+ body.email
286
+ .split("@")[0]
287
+ .toLowerCase()
288
+ .replace(/[^a-z0-9_-]/g, "-")
289
+ .slice(0, 32),
290
+ });
291
+
292
+ if (!result.success) {
293
+ return reply.status(400).send({ error: result.error.message });
294
+ }
295
+
296
+ await db.update(users).set({ role: "owner" }).where(eq(users.id, result.data.user.id));
297
+ ownerUser = result.data.user;
298
+ }
299
+
300
+ try {
301
+ await fs.writeFile(SETUP_MARKER_PATH, new Date().toISOString(), "utf-8");
302
+ } catch (err) {
303
+ request.log.warn({ err }, "Could not write setup completion marker");
304
+ }
305
+
306
+ return {
307
+ user: {
308
+ id: ownerUser.id,
309
+ email: ownerUser.email,
310
+ username: ownerUser.username,
311
+ role: "owner",
312
+ },
313
+ };
314
+ });
315
+ }
@@ -0,0 +1,67 @@
1
+ import { z } from "zod";
2
+ import type { FastifyInstance, FastifyRequest, FastifyReply } from "fastify";
3
+ import { sendSmsOtp, verifySmsOtp, markPhoneVerified } from "../services/smsOtp.js";
4
+ import { rateLimit } from "../plugins/rateLimit.js";
5
+
6
+ const SendSchema = z.object({
7
+ phoneNumber: z.string().min(5).max(32),
8
+ });
9
+
10
+ const VerifySchema = z.object({
11
+ phoneNumber: z.string().min(5).max(32),
12
+ code: z.string().min(4).max(8),
13
+ });
14
+
15
+ export default async function smsOtpRoutes(app: FastifyInstance) {
16
+ app.post(
17
+ "/sms-otp/send",
18
+ {
19
+ preHandler: [
20
+ app.authenticate,
21
+ rateLimit({
22
+ keyPrefix: "sms-otp-send",
23
+ maxAttempts: 3,
24
+ windowSeconds: 300,
25
+ }),
26
+ ],
27
+ },
28
+ async (request: FastifyRequest, reply: FastifyReply) => {
29
+ const user = request.user!;
30
+ const body = SendSchema.parse(request.body);
31
+
32
+ await sendSmsOtp(user, body.phoneNumber);
33
+ await request.audit("sms_otp_sent", { userId: user.id, phoneNumber: body.phoneNumber });
34
+
35
+ return { success: true };
36
+ }
37
+ );
38
+
39
+ app.post(
40
+ "/sms-otp/verify",
41
+ {
42
+ preHandler: [
43
+ app.authenticate,
44
+ rateLimit({
45
+ keyPrefix: "sms-otp-verify",
46
+ maxAttempts: 5,
47
+ windowSeconds: 300,
48
+ }),
49
+ ],
50
+ },
51
+ async (request: FastifyRequest, reply: FastifyReply) => {
52
+ const user = request.user!;
53
+ const body = VerifySchema.parse(request.body);
54
+
55
+ const valid = await verifySmsOtp(user.id, body.code);
56
+ if (!valid) {
57
+ await request.audit("sms_otp_verify_failed", { userId: user.id });
58
+ return reply.status(400).send({ error: "Invalid or expired code" });
59
+ }
60
+
61
+ await markPhoneVerified(user.id, body.phoneNumber);
62
+ await request.audit("sms_otp_verified", { userId: user.id, phoneNumber: body.phoneNumber });
63
+
64
+ return { success: true };
65
+ }
66
+ );
67
+ }
@@ -0,0 +1,122 @@
1
+ import { z } from "zod";
2
+ import type { FastifyInstance, FastifyRequest, FastifyReply } from "fastify";
3
+ import { config } from "../config.js";
4
+ import {
5
+ generateSecret,
6
+ buildProvisioningUri,
7
+ verifyTOTP,
8
+ encryptSecret,
9
+ decryptSecret,
10
+ generateBackupCodes,
11
+ storeBackupCodes,
12
+ verifyBackupCode,
13
+ } from "../services/totp.js";
14
+
15
+ const CodeSchema = z.object({
16
+ code: z.string().min(6).max(8),
17
+ });
18
+
19
+ const BackupCodeSchema = z.object({
20
+ code: z.string().min(8).max(16),
21
+ });
22
+
23
+ export default async function totpRoutes(app: FastifyInstance) {
24
+ app.post(
25
+ "/totp/enroll",
26
+ { preHandler: [app.authenticate] },
27
+ async (request: FastifyRequest, reply: FastifyReply) => {
28
+ const user = request.user!;
29
+ if (user.totpEnabled) {
30
+ return reply.status(409).send({ error: "TOTP already enrolled" });
31
+ }
32
+
33
+ const secret = generateSecret();
34
+ const encrypted = encryptSecret(secret);
35
+ const { codes, hashes } = generateBackupCodes();
36
+
37
+ await app.container.userRepository.setTotpSecret(user.id, encrypted);
38
+ await storeBackupCodes(user.id, hashes);
39
+
40
+ const provisioningUri = buildProvisioningUri({
41
+ secret,
42
+ email: user.email,
43
+ issuer: config.TOTP_ISSUER,
44
+ });
45
+
46
+ await request.audit("totp_enrolled", { userId: user.id });
47
+
48
+ return {
49
+ secret,
50
+ provisioningUri,
51
+ backupCodes: codes,
52
+ };
53
+ }
54
+ );
55
+
56
+ app.post(
57
+ "/totp/backup",
58
+ { preHandler: [app.authenticate] },
59
+ async (request: FastifyRequest, reply: FastifyReply) => {
60
+ const user = request.user!;
61
+ if (!user.totpSecret || !user.totpEnabled) {
62
+ return reply.status(400).send({ error: "TOTP not enabled" });
63
+ }
64
+
65
+ const body = BackupCodeSchema.parse(request.body);
66
+ const valid = await verifyBackupCode(user.id, body.code);
67
+ if (!valid) {
68
+ await request.audit("totp_verify_failed", { userId: user.id, method: "backup_code" });
69
+ return reply.status(400).send({ error: "Invalid backup code" });
70
+ }
71
+
72
+ await request.audit("totp_enabled", { userId: user.id, method: "backup_code" });
73
+ return { success: true };
74
+ }
75
+ );
76
+
77
+ app.post(
78
+ "/totp/verify",
79
+ { preHandler: [app.authenticate] },
80
+ async (request: FastifyRequest, reply: FastifyReply) => {
81
+ const user = request.user!;
82
+ if (!user.totpSecret) {
83
+ return reply.status(400).send({ error: "TOTP not enrolled" });
84
+ }
85
+
86
+ const body = CodeSchema.parse(request.body);
87
+ const secret = decryptSecret(user.totpSecret);
88
+ if (!verifyTOTP(secret, body.code)) {
89
+ await request.audit("totp_verify_failed", { userId: user.id });
90
+ return reply.status(400).send({ error: "Invalid code" });
91
+ }
92
+
93
+ await app.container.userRepository.enableTotp(user.id);
94
+ await request.audit("totp_enabled", { userId: user.id });
95
+
96
+ return { success: true };
97
+ }
98
+ );
99
+
100
+ app.post(
101
+ "/totp/disable",
102
+ { preHandler: [app.authenticate] },
103
+ async (request: FastifyRequest, reply: FastifyReply) => {
104
+ const user = request.user!;
105
+ if (!user.totpSecret || !user.totpEnabled) {
106
+ return reply.status(400).send({ error: "TOTP not enabled" });
107
+ }
108
+
109
+ const body = CodeSchema.parse(request.body);
110
+ const secret = decryptSecret(user.totpSecret);
111
+ if (!verifyTOTP(secret, body.code)) {
112
+ await request.audit("totp_disable_failed", { userId: user.id });
113
+ return reply.status(400).send({ error: "Invalid code" });
114
+ }
115
+
116
+ await app.container.userRepository.disableTotp(user.id);
117
+ await request.audit("totp_disabled", { userId: user.id });
118
+
119
+ return { success: true };
120
+ }
121
+ );
122
+ }