@kayjs/auth 0.0.0-stage → 1.104.2

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 (407) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +78 -2
  3. package/llms/admin-and-organizations.md +70 -0
  4. package/llms/admin-pages.md +30 -0
  5. package/llms/grouped-methods.md +106 -0
  6. package/llms/hardening-and-testing.md +108 -0
  7. package/llms/oauth-passkeys-two-factor.md +111 -0
  8. package/llms/oauth-providers.md +28 -0
  9. package/llms/oauth-server-and-tokens.md +76 -0
  10. package/llms/organization-pages.md +20 -0
  11. package/llms/passwords-and-mails.md +129 -0
  12. package/llms/sessions-and-guards.md +51 -0
  13. package/llms/setup.md +122 -0
  14. package/llms/signed-in-components.md +59 -0
  15. package/llms.txt +28 -0
  16. package/package.json +85 -4
  17. package/src/access.ts +31 -0
  18. package/src/account.ts +198 -0
  19. package/src/add.ts +70 -0
  20. package/src/address.ts +51 -0
  21. package/src/admin.ts +361 -0
  22. package/src/auditWording.ts +153 -0
  23. package/src/auth.ts +219 -0
  24. package/src/authorize/clients.ts +160 -0
  25. package/src/authorize/grants.ts +44 -0
  26. package/src/authorize/metadata.ts +72 -0
  27. package/src/authorize/register.ts +38 -0
  28. package/src/authorize/reply.ts +9 -0
  29. package/src/authorize/request.ts +253 -0
  30. package/src/authorize/resource.ts +34 -0
  31. package/src/authorize/revoke.ts +36 -0
  32. package/src/authorize/routes.ts +87 -0
  33. package/src/authorize/token.ts +213 -0
  34. package/src/authorize/uris.ts +76 -0
  35. package/src/bearer.ts +208 -0
  36. package/src/bearerHeader.ts +11 -0
  37. package/src/breached.ts +47 -0
  38. package/src/browser.ts +59 -0
  39. package/src/captcha.ts +196 -0
  40. package/src/cbor.ts +129 -0
  41. package/src/components/deletion-banner.kay +20 -0
  42. package/src/components/impersonation-banner.kay +21 -0
  43. package/src/components/signed-in.kay +8 -0
  44. package/src/components/signed-out.kay +6 -0
  45. package/src/components/user-menu.kay +21 -0
  46. package/src/context.ts +5 -0
  47. package/src/core.ts +308 -0
  48. package/src/createUserCommand.ts +217 -0
  49. package/src/decide.ts +45 -0
  50. package/src/deletion.ts +80 -0
  51. package/src/devTool.ts +104 -0
  52. package/src/device.ts +37 -0
  53. package/src/email.ts +594 -0
  54. package/src/erase.ts +237 -0
  55. package/src/events.ts +297 -0
  56. package/src/export.ts +101 -0
  57. package/src/failure.ts +63 -0
  58. package/src/forwardAuth.ts +55 -0
  59. package/src/forwardRoutes.ts +68 -0
  60. package/src/gate.ts +104 -0
  61. package/src/guard.ts +22 -0
  62. package/src/guards.ts +72 -0
  63. package/src/guesses.ts +99 -0
  64. package/src/index.ts +46 -0
  65. package/src/keys.ts +51 -0
  66. package/src/limits.ts +182 -0
  67. package/src/load.ts +18 -0
  68. package/src/locale.ts +15 -0
  69. package/src/log.ts +4 -0
  70. package/src/mail.ts +225 -0
  71. package/src/memoryStore.ts +599 -0
  72. package/src/messages/fr.ts +357 -0
  73. package/src/methods/account.ts +80 -0
  74. package/src/methods/admin.ts +63 -0
  75. package/src/methods/audit.ts +15 -0
  76. package/src/methods/email.ts +39 -0
  77. package/src/methods/magicLink.ts +32 -0
  78. package/src/methods/oauth.ts +35 -0
  79. package/src/methods/oauthServer.ts +31 -0
  80. package/src/methods/organizations.ts +96 -0
  81. package/src/methods/passkeys.ts +61 -0
  82. package/src/methods/password.ts +53 -0
  83. package/src/methods/sessions.ts +18 -0
  84. package/src/methods/tokens.ts +24 -0
  85. package/src/methods/twoFactor.ts +62 -0
  86. package/src/oauth/client.ts +324 -0
  87. package/src/oauth/flow.ts +350 -0
  88. package/src/oauth/index.ts +5 -0
  89. package/src/oauth/pkce.ts +20 -0
  90. package/src/oauth/providers.ts +490 -0
  91. package/src/oauth/refresher.ts +177 -0
  92. package/src/oauth/timeout.ts +2 -0
  93. package/src/oauth/types.ts +78 -0
  94. package/src/oauthTest.ts +112 -0
  95. package/src/organizations.ts +675 -0
  96. package/src/organizationsCore.ts +60 -0
  97. package/src/own.ts +313 -0
  98. package/src/pages/components/captcha.kay +16 -0
  99. package/src/pages/components/frame.kay +11 -0
  100. package/src/pages/components/message.kay +8 -0
  101. package/src/pages/components/panel.kay +12 -0
  102. package/src/pages/components/passkey-add.kay +48 -0
  103. package/src/pages/components/passkey-sign-in.kay +34 -0
  104. package/src/pages/components/passkey-two-factor.kay +33 -0
  105. package/src/pages/components/proof.kay +15 -0
  106. package/src/pages/components/provider-buttons.kay +25 -0
  107. package/src/pages/components/recovery-codes.kay +13 -0
  108. package/src/pages/components/separator.kay +4 -0
  109. package/src/pages/english.ts +82 -0
  110. package/src/pages/forms.ts +185 -0
  111. package/src/pages/index.ts +361 -0
  112. package/src/pages/organizationPage.ts +12 -0
  113. package/src/pages/routes/account/_guard.ts +15 -0
  114. package/src/pages/routes/account/_layout.kay +37 -0
  115. package/src/pages/routes/account/clients.kay +33 -0
  116. package/src/pages/routes/account/connections.kay +57 -0
  117. package/src/pages/routes/account/data.kay +106 -0
  118. package/src/pages/routes/account/index.kay +109 -0
  119. package/src/pages/routes/account/organizations/[org].kay +188 -0
  120. package/src/pages/routes/account/organizations/_guard.ts +8 -0
  121. package/src/pages/routes/account/organizations/index.kay +86 -0
  122. package/src/pages/routes/account/security.kay +164 -0
  123. package/src/pages/routes/account/sessions.kay +51 -0
  124. package/src/pages/routes/account/tokens.kay +84 -0
  125. package/src/pages/routes/admin/_layout.kay +43 -0
  126. package/src/pages/routes/admin/audit.kay +43 -0
  127. package/src/pages/routes/admin/index.kay +60 -0
  128. package/src/pages/routes/admin/users/[id].kay +181 -0
  129. package/src/pages/routes/confirm-email.kay +39 -0
  130. package/src/pages/routes/invitation.kay +104 -0
  131. package/src/pages/routes/magic-link.kay +42 -0
  132. package/src/pages/routes/oauth/authorize.kay +80 -0
  133. package/src/pages/routes/register.kay +83 -0
  134. package/src/pages/routes/reset-password.kay +73 -0
  135. package/src/pages/routes/sign-in.kay +128 -0
  136. package/src/pages/routes/two-factor.kay +61 -0
  137. package/src/pages/routes/verify-email.kay +83 -0
  138. package/src/passkeys.ts +373 -0
  139. package/src/password.ts +316 -0
  140. package/src/payloads.ts +22 -0
  141. package/src/pg.ts +705 -0
  142. package/src/profile.ts +43 -0
  143. package/src/proof.ts +110 -0
  144. package/src/prune.ts +123 -0
  145. package/src/rates.ts +82 -0
  146. package/src/request.ts +712 -0
  147. package/src/requiredTwoFactor.ts +71 -0
  148. package/src/requirement.ts +23 -0
  149. package/src/roles.ts +18 -0
  150. package/src/routes.ts +202 -0
  151. package/src/rules-check.ts +37 -0
  152. package/src/rules.ts +108 -0
  153. package/src/securityNotice.ts +45 -0
  154. package/src/sessions.ts +184 -0
  155. package/src/setup.ts +417 -0
  156. package/src/signInOptions.ts +9 -0
  157. package/src/state.ts +34 -0
  158. package/src/store.ts +410 -0
  159. package/src/storeHelpers.ts +23 -0
  160. package/src/test.ts +46 -0
  161. package/src/testCookies.ts +9 -0
  162. package/src/testHelpers.ts +58 -0
  163. package/src/testing.ts +113 -0
  164. package/src/text.ts +6 -0
  165. package/src/totp.ts +120 -0
  166. package/src/twoFactor.ts +200 -0
  167. package/src/types.ts +23 -0
  168. package/src/userData.ts +47 -0
  169. package/src/viewer-layout/_layout.kay +11 -0
  170. package/src/viewer.ts +116 -0
  171. package/src/wayIn.ts +40 -0
  172. package/src/webauthn.ts +375 -0
  173. package/src/wsAuth.ts +53 -0
  174. package/types/access.d.ts +12 -0
  175. package/types/access.d.ts.map +1 -0
  176. package/types/account.d.ts +32 -0
  177. package/types/account.d.ts.map +1 -0
  178. package/types/add.d.ts +29 -0
  179. package/types/add.d.ts.map +1 -0
  180. package/types/address.d.ts +2 -0
  181. package/types/address.d.ts.map +1 -0
  182. package/types/admin.d.ts +84 -0
  183. package/types/admin.d.ts.map +1 -0
  184. package/types/auditWording.d.ts +9 -0
  185. package/types/auditWording.d.ts.map +1 -0
  186. package/types/auth.d.ts +3475 -0
  187. package/types/auth.d.ts.map +1 -0
  188. package/types/authorize/clients.d.ts +15 -0
  189. package/types/authorize/clients.d.ts.map +1 -0
  190. package/types/authorize/grants.d.ts +15 -0
  191. package/types/authorize/grants.d.ts.map +1 -0
  192. package/types/authorize/metadata.d.ts +20 -0
  193. package/types/authorize/metadata.d.ts.map +1 -0
  194. package/types/authorize/register.d.ts +4 -0
  195. package/types/authorize/register.d.ts.map +1 -0
  196. package/types/authorize/reply.d.ts +6 -0
  197. package/types/authorize/reply.d.ts.map +1 -0
  198. package/types/authorize/request.d.ts +48 -0
  199. package/types/authorize/request.d.ts.map +1 -0
  200. package/types/authorize/resource.d.ts +4 -0
  201. package/types/authorize/resource.d.ts.map +1 -0
  202. package/types/authorize/revoke.d.ts +4 -0
  203. package/types/authorize/revoke.d.ts.map +1 -0
  204. package/types/authorize/routes.d.ts +5 -0
  205. package/types/authorize/routes.d.ts.map +1 -0
  206. package/types/authorize/token.d.ts +7 -0
  207. package/types/authorize/token.d.ts.map +1 -0
  208. package/types/authorize/uris.d.ts +5 -0
  209. package/types/authorize/uris.d.ts.map +1 -0
  210. package/types/bearer.d.ts +45 -0
  211. package/types/bearer.d.ts.map +1 -0
  212. package/types/bearerHeader.d.ts +3 -0
  213. package/types/bearerHeader.d.ts.map +1 -0
  214. package/types/breached.d.ts +5 -0
  215. package/types/breached.d.ts.map +1 -0
  216. package/types/browser.d.ts +11 -0
  217. package/types/browser.d.ts.map +1 -0
  218. package/types/captcha.d.ts +42 -0
  219. package/types/captcha.d.ts.map +1 -0
  220. package/types/cbor.d.ts +4 -0
  221. package/types/cbor.d.ts.map +1 -0
  222. package/types/context.d.ts +3 -0
  223. package/types/context.d.ts.map +1 -0
  224. package/types/core.d.ts +180 -0
  225. package/types/core.d.ts.map +1 -0
  226. package/types/createUserCommand.d.ts +11 -0
  227. package/types/createUserCommand.d.ts.map +1 -0
  228. package/types/decide.d.ts +12 -0
  229. package/types/decide.d.ts.map +1 -0
  230. package/types/deletion.d.ts +17 -0
  231. package/types/deletion.d.ts.map +1 -0
  232. package/types/devTool.d.ts +3 -0
  233. package/types/devTool.d.ts.map +1 -0
  234. package/types/device.d.ts +7 -0
  235. package/types/device.d.ts.map +1 -0
  236. package/types/email.d.ts +73 -0
  237. package/types/email.d.ts.map +1 -0
  238. package/types/erase.d.ts +31 -0
  239. package/types/erase.d.ts.map +1 -0
  240. package/types/events.d.ts +139 -0
  241. package/types/events.d.ts.map +1 -0
  242. package/types/export.d.ts +54 -0
  243. package/types/export.d.ts.map +1 -0
  244. package/types/failure.d.ts +19 -0
  245. package/types/failure.d.ts.map +1 -0
  246. package/types/forwardAuth.d.ts +12 -0
  247. package/types/forwardAuth.d.ts.map +1 -0
  248. package/types/forwardRoutes.d.ts +11 -0
  249. package/types/forwardRoutes.d.ts.map +1 -0
  250. package/types/gate.d.ts +31 -0
  251. package/types/gate.d.ts.map +1 -0
  252. package/types/guard.d.ts +10 -0
  253. package/types/guard.d.ts.map +1 -0
  254. package/types/guards.d.ts +37 -0
  255. package/types/guards.d.ts.map +1 -0
  256. package/types/guesses.d.ts +18 -0
  257. package/types/guesses.d.ts.map +1 -0
  258. package/types/index.d.ts +47 -0
  259. package/types/index.d.ts.map +1 -0
  260. package/types/keys.d.ts +11 -0
  261. package/types/keys.d.ts.map +1 -0
  262. package/types/limits.d.ts +133 -0
  263. package/types/limits.d.ts.map +1 -0
  264. package/types/load.d.ts +18 -0
  265. package/types/load.d.ts.map +1 -0
  266. package/types/locale.d.ts +4 -0
  267. package/types/locale.d.ts.map +1 -0
  268. package/types/log.d.ts +2 -0
  269. package/types/log.d.ts.map +1 -0
  270. package/types/mail.d.ts +51 -0
  271. package/types/mail.d.ts.map +1 -0
  272. package/types/memoryStore.d.ts +3 -0
  273. package/types/memoryStore.d.ts.map +1 -0
  274. package/types/messages/fr.d.ts +409 -0
  275. package/types/messages/fr.d.ts.map +1 -0
  276. package/types/methods/account.d.ts +24 -0
  277. package/types/methods/account.d.ts.map +1 -0
  278. package/types/methods/admin.d.ts +30 -0
  279. package/types/methods/admin.d.ts.map +1 -0
  280. package/types/methods/audit.d.ts +11 -0
  281. package/types/methods/audit.d.ts.map +1 -0
  282. package/types/methods/email.d.ts +14 -0
  283. package/types/methods/email.d.ts.map +1 -0
  284. package/types/methods/magicLink.d.ts +12 -0
  285. package/types/methods/magicLink.d.ts.map +1 -0
  286. package/types/methods/oauth.d.ts +16 -0
  287. package/types/methods/oauth.d.ts.map +1 -0
  288. package/types/methods/oauthServer.d.ts +13 -0
  289. package/types/methods/oauthServer.d.ts.map +1 -0
  290. package/types/methods/organizations.d.ts +30 -0
  291. package/types/methods/organizations.d.ts.map +1 -0
  292. package/types/methods/passkeys.d.ts +19 -0
  293. package/types/methods/passkeys.d.ts.map +1 -0
  294. package/types/methods/password.d.ts +17 -0
  295. package/types/methods/password.d.ts.map +1 -0
  296. package/types/methods/sessions.d.ts +9 -0
  297. package/types/methods/sessions.d.ts.map +1 -0
  298. package/types/methods/tokens.d.ts +11 -0
  299. package/types/methods/tokens.d.ts.map +1 -0
  300. package/types/methods/twoFactor.d.ts +20 -0
  301. package/types/methods/twoFactor.d.ts.map +1 -0
  302. package/types/oauth/client.d.ts +39 -0
  303. package/types/oauth/client.d.ts.map +1 -0
  304. package/types/oauth/flow.d.ts +38 -0
  305. package/types/oauth/flow.d.ts.map +1 -0
  306. package/types/oauth/index.d.ts +6 -0
  307. package/types/oauth/index.d.ts.map +1 -0
  308. package/types/oauth/pkce.d.ts +10 -0
  309. package/types/oauth/pkce.d.ts.map +1 -0
  310. package/types/oauth/providers.d.ts +100 -0
  311. package/types/oauth/providers.d.ts.map +1 -0
  312. package/types/oauth/refresher.d.ts +55 -0
  313. package/types/oauth/refresher.d.ts.map +1 -0
  314. package/types/oauth/timeout.d.ts +2 -0
  315. package/types/oauth/timeout.d.ts.map +1 -0
  316. package/types/oauth/types.d.ts +75 -0
  317. package/types/oauth/types.d.ts.map +1 -0
  318. package/types/oauthTest.d.ts +23 -0
  319. package/types/oauthTest.d.ts.map +1 -0
  320. package/types/organizations.d.ts +111 -0
  321. package/types/organizations.d.ts.map +1 -0
  322. package/types/organizationsCore.d.ts +29 -0
  323. package/types/organizationsCore.d.ts.map +1 -0
  324. package/types/own.d.ts +55 -0
  325. package/types/own.d.ts.map +1 -0
  326. package/types/pages/english.d.ts +80 -0
  327. package/types/pages/english.d.ts.map +1 -0
  328. package/types/pages/forms.d.ts +204 -0
  329. package/types/pages/forms.d.ts.map +1 -0
  330. package/types/pages/index.d.ts +166 -0
  331. package/types/pages/index.d.ts.map +1 -0
  332. package/types/pages/organizationPage.d.ts +7 -0
  333. package/types/pages/organizationPage.d.ts.map +1 -0
  334. package/types/pages/routes/account/_guard.d.ts +3 -0
  335. package/types/pages/routes/account/_guard.d.ts.map +1 -0
  336. package/types/pages/routes/account/organizations/_guard.d.ts +3 -0
  337. package/types/pages/routes/account/organizations/_guard.d.ts.map +1 -0
  338. package/types/passkeys.d.ts +61 -0
  339. package/types/passkeys.d.ts.map +1 -0
  340. package/types/password.d.ts +49 -0
  341. package/types/password.d.ts.map +1 -0
  342. package/types/payloads.d.ts +4 -0
  343. package/types/payloads.d.ts.map +1 -0
  344. package/types/pg.d.ts +303 -0
  345. package/types/pg.d.ts.map +1 -0
  346. package/types/profile.d.ts +11 -0
  347. package/types/profile.d.ts.map +1 -0
  348. package/types/proof.d.ts +33 -0
  349. package/types/proof.d.ts.map +1 -0
  350. package/types/prune.d.ts +5 -0
  351. package/types/prune.d.ts.map +1 -0
  352. package/types/rates.d.ts +15 -0
  353. package/types/rates.d.ts.map +1 -0
  354. package/types/request.d.ts +119 -0
  355. package/types/request.d.ts.map +1 -0
  356. package/types/requiredTwoFactor.d.ts +16 -0
  357. package/types/requiredTwoFactor.d.ts.map +1 -0
  358. package/types/requirement.d.ts +4 -0
  359. package/types/requirement.d.ts.map +1 -0
  360. package/types/roles.d.ts +9 -0
  361. package/types/roles.d.ts.map +1 -0
  362. package/types/routes.d.ts +31 -0
  363. package/types/routes.d.ts.map +1 -0
  364. package/types/rules-check.d.ts +3 -0
  365. package/types/rules-check.d.ts.map +1 -0
  366. package/types/rules.d.ts +38 -0
  367. package/types/rules.d.ts.map +1 -0
  368. package/types/securityNotice.d.ts +7 -0
  369. package/types/securityNotice.d.ts.map +1 -0
  370. package/types/sessions.d.ts +32 -0
  371. package/types/sessions.d.ts.map +1 -0
  372. package/types/setup.d.ts +18 -0
  373. package/types/setup.d.ts.map +1 -0
  374. package/types/signInOptions.d.ts +6 -0
  375. package/types/signInOptions.d.ts.map +1 -0
  376. package/types/state.d.ts +25 -0
  377. package/types/state.d.ts.map +1 -0
  378. package/types/store.d.ts +295 -0
  379. package/types/store.d.ts.map +1 -0
  380. package/types/storeHelpers.d.ts +4 -0
  381. package/types/storeHelpers.d.ts.map +1 -0
  382. package/types/test.d.ts +21 -0
  383. package/types/test.d.ts.map +1 -0
  384. package/types/testCookies.d.ts +3 -0
  385. package/types/testCookies.d.ts.map +1 -0
  386. package/types/testHelpers.d.ts +34 -0
  387. package/types/testHelpers.d.ts.map +1 -0
  388. package/types/testing.d.ts +12 -0
  389. package/types/testing.d.ts.map +1 -0
  390. package/types/text.d.ts +2 -0
  391. package/types/text.d.ts.map +1 -0
  392. package/types/totp.d.ts +12 -0
  393. package/types/totp.d.ts.map +1 -0
  394. package/types/twoFactor.d.ts +41 -0
  395. package/types/twoFactor.d.ts.map +1 -0
  396. package/types/types.d.ts +17 -0
  397. package/types/types.d.ts.map +1 -0
  398. package/types/userData.d.ts +9 -0
  399. package/types/userData.d.ts.map +1 -0
  400. package/types/viewer.d.ts +23 -0
  401. package/types/viewer.d.ts.map +1 -0
  402. package/types/wayIn.d.ts +12 -0
  403. package/types/wayIn.d.ts.map +1 -0
  404. package/types/webauthn.d.ts +111 -0
  405. package/types/webauthn.d.ts.map +1 -0
  406. package/types/wsAuth.d.ts +14 -0
  407. package/types/wsAuth.d.ts.map +1 -0
package/src/pg.ts ADDED
@@ -0,0 +1,705 @@
1
+ import type { Database, InferEntity } from '@kaynooo/pg-orm'
2
+ import type { AuditRecord, AuthStore, BearerTokenRecord, IdentityRecord, InvitationRecord, MemberRecord, OAuthClientRecord, OAuthCodeRecord, OAuthGrantRecord, OAuthRefreshRecord, OrganizationRecord, PasskeyRecord, PruneLimits, SessionRecord, TokenRecord, TokenType, UserRecord } from './store'
3
+ import { defineTable } from '@kaynooo/pg-orm'
4
+ import { durationSeconds } from 'kay/library'
5
+ import { log } from './log'
6
+
7
+ // Each table keeps the `renamedFrom` of its pre-1.71 `auth_*` name for good, unlike a deprecated form: an app jumping several minors at once still gets its users renamed rather than empty tables beside them, and a rename finding no old table does nothing.
8
+ export const AuthUsers = defineTable('kay_users', t => ({
9
+ id: t.text().primaryKey(),
10
+ email: t.text().nullable().unique(),
11
+ email_verified_at: t.timestamptz().nullable(),
12
+ username: t.text().nullable(),
13
+ // The username lowercased, so two names differing in case only cannot both exist.
14
+ username_key: t.text().nullable().unique(),
15
+ password_hash: t.text().nullable(),
16
+ totp_secret: t.text().nullable(),
17
+ totp_enabled_at: t.timestamptz().nullable(),
18
+ totp_last_step: t.int4().notNull().default(0),
19
+ roles: t.array(t.text()).notNull().default([]),
20
+ session_version: t.int4().notNull().default(0),
21
+ last_sign_in: t.text().nullable(),
22
+ locale: t.text().nullable(),
23
+ guest: t.bool().notNull().default(false),
24
+ banned_at: t.timestamptz().nullable(),
25
+ banned_until: t.timestamptz().nullable(),
26
+ ban_reason: t.text().nullable(),
27
+ // When the account's grace period ends and the prune deletes it; null for an account not pending deletion, and for users stored before this column.
28
+ delete_at: t.timestamptz().nullable(),
29
+ // The app's own data on the user, from the `user` option.
30
+ data: t.jsonb<Record<string, unknown>>().notNull().default({}),
31
+ created_at: t.timestamptz().notNull(),
32
+ })).renamedFrom('auth_user').withIndexes([{ columns: ['created_at'] }, { columns: ['guest', 'created_at'] }, { columns: ['delete_at'] }])
33
+
34
+ const userId = () => AuthUsers
35
+
36
+ export const AuthIdentities = defineTable('kay_identities', t => ({
37
+ id: t.serial().primaryKey(),
38
+ provider: t.text().notNull(),
39
+ provider_id: t.text().notNull(),
40
+ user_id: t.text().notNull().references(userId, 'id', { onDelete: 'cascade' }),
41
+ access_token: t.text().nullable(),
42
+ refresh_token: t.text().nullable(),
43
+ token_expires_at: t.timestamptz().nullable(),
44
+ created_at: t.timestamptz().notNull(),
45
+ })).renamedFrom('auth_identity').withIndexes([{ columns: ['provider', 'provider_id'], unique: true }, { columns: ['user_id'] }])
46
+
47
+ export const AuthTokens = defineTable('kay_tokens', t => ({
48
+ digest: t.text().primaryKey(),
49
+ type: t.text().notNull(),
50
+ user_id: t.text().notNull().references(userId, 'id', { onDelete: 'cascade' }),
51
+ email: t.text().notNull(),
52
+ redirect: t.text().nullable(),
53
+ expires_at: t.timestamptz().notNull(),
54
+ })).renamedFrom('auth_token').withIndexes([{ columns: ['user_id', 'type'] }, { columns: ['expires_at'] }])
55
+
56
+ export const AuthRecoveryCodes = defineTable('kay_recovery_codes', t => ({
57
+ id: t.serial().primaryKey(),
58
+ user_id: t.text().notNull().references(userId, 'id', { onDelete: 'cascade' }),
59
+ digest: t.text().notNull(),
60
+ })).renamedFrom('auth_recovery_code').withIndexes([{ columns: ['user_id', 'digest'], unique: true }])
61
+
62
+ export const AuthBearerTokens = defineTable('kay_bearer_tokens', t => ({
63
+ id: t.text().primaryKey(),
64
+ user_id: t.text().notNull().references(userId, 'id', { onDelete: 'cascade' }),
65
+ label: t.text().notNull(),
66
+ digest: t.text().notNull().unique(),
67
+ scopes: t.array(t.text()).nullable(),
68
+ created_at: t.timestamptz().notNull(),
69
+ last_used_at: t.timestamptz().nullable(),
70
+ expires_at: t.timestamptz().nullable(),
71
+ // Set on a token an OAuth client was given.
72
+ oauth_client: t.text().nullable(),
73
+ oauth_family: t.text().nullable(),
74
+ // The resource (RFC 8707) the token is bound to; null for none, and for tokens stored before this column.
75
+ oauth_resource: t.text().nullable(),
76
+ })).renamedFrom('auth_bearer_token').withIndexes([{ columns: ['user_id'] }, { columns: ['expires_at'] }, { columns: ['user_id', 'oauth_client'] }, { columns: ['user_id', 'oauth_family'] }])
77
+
78
+ export const AuthSessions = defineTable('kay_auth_sessions', t => ({
79
+ id: t.text().primaryKey(),
80
+ user_id: t.text().notNull().references(userId, 'id', { onDelete: 'cascade' }),
81
+ version: t.int4().notNull(),
82
+ user_agent: t.text().notNull(),
83
+ ip: t.text().notNull(),
84
+ created_at: t.timestamptz().notNull(),
85
+ last_seen_at: t.timestamptz().notNull(),
86
+ max_age: t.int4().nullable(),
87
+ })).renamedFrom('auth_session').withIndexes([{ columns: ['user_id'] }, { columns: ['last_seen_at'] }, { columns: ['created_at'] }])
88
+
89
+ export const AuthPasskeys = defineTable('kay_passkeys', t => ({
90
+ id: t.text().primaryKey(),
91
+ user_id: t.text().notNull().references(userId, 'id', { onDelete: 'cascade' }),
92
+ name: t.text().notNull(),
93
+ public_key: t.text().notNull(),
94
+ // A uint32, past what int4 holds.
95
+ counter: t.int8().notNull(),
96
+ transports: t.array(t.text()).notNull(),
97
+ multi_device: t.bool().notNull(),
98
+ backed_up: t.bool().notNull(),
99
+ // Passkeys stored before this column are unproven until one sign-in with user verification.
100
+ user_verified: t.bool().notNull().default(false),
101
+ created_at: t.timestamptz().notNull(),
102
+ last_used_at: t.timestamptz().nullable(),
103
+ })).renamedFrom('auth_passkey').withIndexes([{ columns: ['user_id'] }])
104
+
105
+ // No reference to the user: the log outlives them.
106
+ export const AuthAudit = defineTable('kay_audits', t => ({
107
+ id: t.text().primaryKey(),
108
+ user_id: t.text().notNull(),
109
+ event: t.text().notNull(),
110
+ detail: t.text().nullable(),
111
+ ip: t.text().notNull(),
112
+ user_agent: t.text().notNull(),
113
+ actor_id: t.text().nullable(),
114
+ at: t.timestamptz().notNull(),
115
+ })).renamedFrom('auth_audit').withIndexes([{ columns: ['user_id', 'at'] }, { columns: ['at'] }, { columns: ['actor_id'] }])
116
+
117
+ export const AuthOrganizations = defineTable('kay_organizations', t => ({
118
+ id: t.text().primaryKey(),
119
+ name: t.text().notNull(),
120
+ slug: t.text().nullable().unique(),
121
+ created_at: t.timestamptz().notNull(),
122
+ })).renamedFrom('auth_organization')
123
+
124
+ const organizationId = () => AuthOrganizations
125
+
126
+ export const AuthMembers = defineTable('kay_members', t => ({
127
+ id: t.serial().primaryKey(),
128
+ organization_id: t.text().notNull().references(organizationId, 'id', { onDelete: 'cascade' }),
129
+ user_id: t.text().notNull().references(userId, 'id', { onDelete: 'cascade' }),
130
+ roles: t.array(t.text()).notNull(),
131
+ created_at: t.timestamptz().notNull(),
132
+ })).renamedFrom('auth_member').withIndexes([{ columns: ['organization_id', 'user_id'], unique: true }, { columns: ['user_id'] }])
133
+
134
+ export const AuthInvitations = defineTable('kay_invitations', t => ({
135
+ id: t.text().primaryKey(),
136
+ organization_id: t.text().notNull().references(organizationId, 'id', { onDelete: 'cascade' }),
137
+ email: t.text().notNull(),
138
+ roles: t.array(t.text()).notNull(),
139
+ invited_by: t.text().nullable().references(userId, 'id', { onDelete: 'set null' }),
140
+ created_at: t.timestamptz().notNull(),
141
+ expires_at: t.timestamptz().notNull(),
142
+ })).renamedFrom('auth_invitation').withIndexes([{ columns: ['organization_id'] }, { columns: ['email'] }, { columns: ['expires_at'] }])
143
+
144
+ export const AuthOAuthClients = defineTable('kay_oauth_clients', t => ({
145
+ id: t.text().primaryKey(),
146
+ name: t.text().notNull(),
147
+ redirect_uris: t.array(t.text()).notNull(),
148
+ created_at: t.timestamptz().notNull(),
149
+ })).renamedFrom('auth_oauth_client').withIndexes([{ columns: ['created_at'] }])
150
+
151
+ export const AuthOAuthGrants = defineTable('kay_oauth_grants', t => ({
152
+ id: t.serial().primaryKey(),
153
+ user_id: t.text().notNull().references(userId, 'id', { onDelete: 'cascade' }),
154
+ client_id: t.text().notNull(),
155
+ client_name: t.text().notNull(),
156
+ scopes: t.array(t.text()).nullable(),
157
+ created_at: t.timestamptz().notNull(),
158
+ last_used_at: t.timestamptz().nullable(),
159
+ })).renamedFrom('auth_oauth_grant').withIndexes([{ columns: ['user_id', 'client_id'], unique: true }, { columns: ['client_id'] }])
160
+
161
+ export const AuthOAuthCodes = defineTable('kay_oauth_codes', t => ({
162
+ digest: t.text().primaryKey(),
163
+ user_id: t.text().notNull().references(userId, 'id', { onDelete: 'cascade' }),
164
+ client_id: t.text().notNull(),
165
+ redirect_uri: t.text().notNull(),
166
+ challenge: t.text().notNull(),
167
+ scopes: t.array(t.text()).nullable(),
168
+ family: t.text().notNull(),
169
+ // The resource (RFC 8707) asked at authorize; null for none, and for codes stored before this column.
170
+ resource: t.text().nullable(),
171
+ created_at: t.timestamptz().notNull(),
172
+ expires_at: t.timestamptz().notNull(),
173
+ used_at: t.timestamptz().nullable(),
174
+ })).renamedFrom('auth_oauth_code').withIndexes([{ columns: ['expires_at'] }, { columns: ['user_id'] }])
175
+
176
+ export const AuthOAuthRefresh = defineTable('kay_oauth_refresh_tokens', t => ({
177
+ digest: t.text().primaryKey(),
178
+ user_id: t.text().notNull().references(userId, 'id', { onDelete: 'cascade' }),
179
+ client_id: t.text().notNull(),
180
+ scopes: t.array(t.text()).nullable(),
181
+ family: t.text().notNull(),
182
+ // The resource (RFC 8707) the family is bound to; null for none, and for tokens stored before this column.
183
+ resource: t.text().nullable(),
184
+ created_at: t.timestamptz().notNull(),
185
+ expires_at: t.timestamptz().notNull(),
186
+ used_at: t.timestamptz().nullable(),
187
+ })).renamedFrom('auth_oauth_refresh').withIndexes([{ columns: ['user_id', 'family'] }, { columns: ['user_id', 'client_id'] }, { columns: ['expires_at'] }])
188
+
189
+ export const AuthAttempts = defineTable('kay_attempts', t => ({
190
+ key: t.text().primaryKey(),
191
+ count: t.int4().notNull(),
192
+ reset_at: t.timestamptz().notNull(),
193
+ })).renamedFrom('auth_attempt').withIndexes([{ columns: ['reset_at'] }])
194
+
195
+ // The tables to list in the app's `new Database({ tables })`, so `db.sync()` creates them.
196
+ export const authTables = [AuthUsers, AuthIdentities, AuthTokens, AuthRecoveryCodes, AuthBearerTokens, AuthSessions, AuthPasskeys, AuthAudit, AuthOrganizations, AuthMembers, AuthInvitations, AuthAttempts, AuthOAuthClients, AuthOAuthGrants, AuthOAuthCodes, AuthOAuthRefresh] as const
197
+
198
+ type UserRow = InferEntity<typeof AuthUsers>
199
+
200
+ // A client that registered itself and that nobody approved is dropped after this long.
201
+ const UNUSED_CLIENT_MS = 24 * 60 * 60 * 1000
202
+
203
+ // kayjs-auth's data in the app's Postgres or SQLite database, through pg-orm: list `authTables` in the database's tables.
204
+ export function pgAuth(db: Database): AuthStore {
205
+ if (typeof (db as Partial<Database> | null)?.repo !== 'function')
206
+ throw new TypeError('kayjs-auth: pgAuth takes a pg-orm `Database` listing `authTables`, not a connection URL or a Bun `SQL`: give `auth({ store: { url } })` for a URL')
207
+
208
+ const users = db.repo(AuthUsers)
209
+ const identities = db.repo(AuthIdentities)
210
+ const tokens = db.repo(AuthTokens)
211
+ const recoveryCodes = db.repo(AuthRecoveryCodes)
212
+ const bearerTokens = db.repo(AuthBearerTokens)
213
+ const sessions = db.repo(AuthSessions)
214
+ const passkeys = db.repo(AuthPasskeys)
215
+ const audit = db.repo(AuthAudit)
216
+ const organizations = db.repo(AuthOrganizations)
217
+ const members = db.repo(AuthMembers)
218
+ const invitations = db.repo(AuthInvitations)
219
+ const attempts = db.repo(AuthAttempts)
220
+ const oauthClients = db.repo(AuthOAuthClients)
221
+ const oauthGrants = db.repo(AuthOAuthGrants)
222
+ const oauthCodes = db.repo(AuthOAuthCodes)
223
+ const oauthRefresh = db.repo(AuthOAuthRefresh)
224
+
225
+ return {
226
+ users: {
227
+ get: async id => toUser(await users.read.findById(id)),
228
+ getMany: async ids => (await users.read.findMany({ id: { in: ids } })).map(row => toUser(row)!),
229
+ findByEmail: async email => toUser(await users.read.findOne({ email })),
230
+ findByUsername: async username => toUser(await users.read.findOne({ username_key: username.toLowerCase() })),
231
+ async create(user) {
232
+ await users.write.insertOne(fromUser(user))
233
+ },
234
+ async update(id, patch) {
235
+ const row = fromUser(patch)
236
+
237
+ return toUser(isEmpty(row) ? await users.read.findById(id) : await users.write.updateById(id, row))
238
+ },
239
+ async staleGuests(createdBefore, limit) {
240
+ const rows = await db.raw<{ id: string }>`
241
+ SELECT "id" FROM "kay_users"
242
+ WHERE "guest" = ${true} AND "created_at" < ${createdBefore} AND NOT EXISTS (SELECT 1 FROM "kay_auth_sessions" WHERE "kay_auth_sessions"."user_id" = "kay_users"."id")
243
+ ORDER BY "created_at" LIMIT ${limit}`
244
+
245
+ return rows.length === 0 ? [] : (await users.read.findMany(q => q.where({ id: { in: rows.map(row => row.id) } }).orderBy('created_at', 'asc'))).map(row => toUser(row)!)
246
+ },
247
+ async staleUnverified(createdBefore, limit) {
248
+ const rows = await db.raw<{ id: string }>`
249
+ SELECT "id" FROM "kay_users"
250
+ WHERE "guest" = ${false} AND "email" IS NOT NULL AND "email_verified_at" IS NULL AND "created_at" < ${createdBefore}
251
+ AND NOT EXISTS (SELECT 1 FROM "kay_auth_sessions" WHERE "kay_auth_sessions"."user_id" = "kay_users"."id")
252
+ AND NOT EXISTS (SELECT 1 FROM "kay_identities" WHERE "kay_identities"."user_id" = "kay_users"."id")
253
+ ORDER BY "created_at" LIMIT ${limit}`
254
+
255
+ return rows.length === 0 ? [] : (await users.read.findMany(q => q.where({ id: { in: rows.map(row => row.id) } }).orderBy('created_at', 'asc'))).map(row => toUser(row)!)
256
+ },
257
+ markForDeletion: async (id, deleteAt) => (await users.write.updateMany({ delete_at: deleteAt }, e => e.and(e.eq('id', id), e.isNull('delete_at')), { pk: true })).length > 0,
258
+ dueForDeletion: async (now, limit) => (await users.read.findMany(q => q.where({ delete_at: { lte: now } }).orderBy('delete_at', 'asc').limit(limit))).map(row => toUser(row)!),
259
+ delete: async id => await users.write.deleteById(id) !== null,
260
+ async list({ search, offset, limit, total: counted = true }) {
261
+ const [rows, total] = await Promise.all([
262
+ users.read.findMany(q => q.andWhere(search !== undefined && (e => e.or(e.eq('id', search), e.iContains('email', search), e.iContains('username', search)))).orderBy('created_at', 'desc').orderBy('id', 'desc').offset(offset).limit(limit)),
263
+ counted ? users.read.count(search !== undefined && (e => e.or(e.eq('id', search), e.iContains('email', search), e.iContains('username', search)))) : 0,
264
+ ])
265
+
266
+ return { users: rows.map(row => toUser(row)!), total }
267
+ },
268
+ // updateMany on the key, as updateOne's LIMIT 1 subquery is not rechecked against a concurrent step: two codes for one step would both pass.
269
+ advanceTotpStep: async (id, step) => (await users.write.updateMany({ totp_last_step: step }, e => e.and(e.eq('id', id), e.lt('totp_last_step', step)), { pk: true })).length > 0,
270
+ },
271
+ identities: {
272
+ find: async (provider, providerId) => toIdentity(await identities.read.findOne({ provider, provider_id: providerId })),
273
+ listByUser: async userId => (await identities.read.findMany({ user_id: userId })).map(row => toIdentity(row)!),
274
+ async create(identity) {
275
+ await identities.write.insertOne({ provider: identity.provider, provider_id: identity.providerId, user_id: identity.userId, access_token: identity.accessToken, refresh_token: identity.refreshToken, token_expires_at: identity.tokenExpiresAt, created_at: identity.createdAt })
276
+ },
277
+ async update(provider, providerId, patch) {
278
+ const row = withoutUndefined({ access_token: patch.accessToken, refresh_token: patch.refreshToken, token_expires_at: patch.tokenExpiresAt })
279
+
280
+ if (!isEmpty(row))
281
+ await identities.write.updateOne(row, { provider, provider_id: providerId })
282
+ },
283
+ delete: async (provider, providerId) => (await identities.write.deleteMany({ provider, provider_id: providerId }, { pk: true })).length > 0,
284
+ erase: async userId => (await identities.write.deleteMany({ user_id: userId }, { pk: true })).length,
285
+ },
286
+ tokens: {
287
+ async create(token) {
288
+ await tokens.write.insertOne({ digest: token.digest, type: token.type, user_id: token.userId, email: token.email, redirect: token.redirect, expires_at: token.expiresAt })
289
+ },
290
+ async consume(digest, type) {
291
+ // One DELETE ... RETURNING, so of two requests spending the token only one gets it back.
292
+ const row = await tokens.write.deleteOne({ digest, type })
293
+
294
+ return row && row.expires_at.getTime() > Date.now() ? toToken(row) : undefined
295
+ },
296
+ erase: async (userId, type) => (await tokens.write.deleteMany(type === undefined ? { user_id: userId } : { user_id: userId, type }, { pk: true })).length,
297
+ },
298
+ sessions: {
299
+ async create(session) {
300
+ await sessions.write.insertOne({ id: session.id, user_id: session.userId, version: session.version, user_agent: session.userAgent, ip: session.ip, created_at: session.createdAt, last_seen_at: session.lastSeenAt, max_age: session.maxAge })
301
+ },
302
+ get: async id => toSession(await sessions.read.findById(id)),
303
+ listByUser: async userId => (await sessions.read.findMany(q => q.where({ user_id: userId }).orderBy('created_at', 'asc'))).map(row => toSession(row)!),
304
+ async update(id, patch) {
305
+ await whenFilled(withoutUndefined({ version: patch.version, ip: patch.ip, last_seen_at: patch.lastSeenAt }), async row => sessions.write.updateById(id, row))
306
+ },
307
+ delete: async (userId, id) => await sessions.write.deleteOne({ id, user_id: userId }) !== null,
308
+ },
309
+ passkeys: {
310
+ async create(passkey) {
311
+ await passkeys.write.insertOne({ id: passkey.id, user_id: passkey.userId, name: passkey.name, public_key: passkey.publicKey, counter: BigInt(passkey.counter), transports: passkey.transports, multi_device: passkey.multiDevice, backed_up: passkey.backedUp, user_verified: passkey.userVerified, created_at: passkey.createdAt, last_used_at: passkey.lastUsedAt })
312
+ },
313
+ get: async id => toPasskey(await passkeys.read.findById(id)),
314
+ listByUser: async userId => (await passkeys.read.findMany(q => q.where({ user_id: userId }).orderBy('created_at', 'asc'))).map(row => toPasskey(row)!),
315
+ async update(id, patch) {
316
+ await whenFilled(withoutUndefined({ name: patch.name, counter: patch.counter === undefined ? undefined : BigInt(patch.counter), backed_up: patch.backedUp, user_verified: patch.userVerified, last_used_at: patch.lastUsedAt }), async row => passkeys.write.updateById(id, row))
317
+ },
318
+ delete: async (userId, id) => await passkeys.write.deleteOne({ id, user_id: userId }) !== null,
319
+ },
320
+ audit: {
321
+ async add(entry) {
322
+ await audit.write.insertOne({ id: entry.id, user_id: entry.userId, event: entry.event, detail: entry.detail, ip: entry.ip, user_agent: entry.userAgent, actor_id: entry.actorId, at: entry.at })
323
+ },
324
+ list: async ({ userId, before, limit }) => (await audit.read.findMany(q => q.andWhere(userId !== undefined && { user_id: userId }).andWhere(before !== undefined && (e => before instanceof Date ? e.lt('at', before) : e.or(e.lt('at', before.at), e.and(e.eq('at', before.at), e.lt('id', before.id))))).orderBy('at', 'desc').orderBy('id', 'desc').limit(limit))).map(row => toAudit(row)),
325
+ prune: async before => (await audit.write.deleteMany({ at: { lt: before } }, { pk: true })).length,
326
+ async erase(userId, pseudonym) {
327
+ const own = await audit.write.updateMany({ user_id: pseudonym, detail: null, ip: '', user_agent: '' }, { user_id: userId }, { pk: true })
328
+ const acted = await audit.write.updateMany({ actor_id: pseudonym, ip: '', user_agent: '' }, { actor_id: userId }, { pk: true })
329
+
330
+ return own.length + acted.length
331
+ },
332
+ },
333
+ organizations: {
334
+ async create(organization) {
335
+ await organizations.write.insertOne({ id: organization.id, name: organization.name, slug: organization.slug, created_at: organization.createdAt })
336
+ },
337
+ get: async id => toOrganization(await organizations.read.findById(id)),
338
+ getMany: async ids => (await organizations.read.findMany({ id: { in: ids } })).map(row => toOrganization(row)!),
339
+ findBySlug: async slug => toOrganization(await organizations.read.findOne({ slug })),
340
+ async update(id, patch) {
341
+ const row = withoutUndefined({ name: patch.name, slug: patch.slug })
342
+
343
+ return toOrganization(isEmpty(row) ? await organizations.read.findById(id) : await organizations.write.updateById(id, row))
344
+ },
345
+ delete: async id => await organizations.write.deleteById(id) !== null,
346
+ },
347
+ members: {
348
+ async add(member) {
349
+ await members.write.insertOne({ organization_id: member.organizationId, user_id: member.userId, roles: member.roles, created_at: member.createdAt })
350
+ },
351
+ get: async (organizationId, userId) => toMember(await members.read.findOne({ organization_id: organizationId, user_id: userId })),
352
+ listByOrganization: async organizationId => (await members.read.findMany(q => q.where({ organization_id: organizationId }).orderBy('created_at', 'asc').orderBy('id', 'asc'))).map(row => toMember(row)!),
353
+ listByUser: async userId => (await members.read.findMany(q => q.where({ user_id: userId }).orderBy('created_at', 'asc').orderBy('id', 'asc'))).map(row => toMember(row)!),
354
+ update: async (organizationId, userId, patch) => toMember(await members.write.updateOne({ roles: patch.roles }, { organization_id: organizationId, user_id: userId })),
355
+ delete: async (organizationId, userId) => await members.write.deleteOne({ organization_id: organizationId, user_id: userId }) !== null,
356
+ },
357
+ invitations: {
358
+ async create(invitation) {
359
+ await invitations.write.insertOne({ id: invitation.id, organization_id: invitation.organizationId, email: invitation.email, roles: invitation.roles, invited_by: invitation.invitedBy, created_at: invitation.createdAt, expires_at: invitation.expiresAt })
360
+ },
361
+ get: async id => toInvitation(await invitations.read.findById(id)),
362
+ listByOrganization: async organizationId => (await invitations.read.findMany(q => q.where({ organization_id: organizationId }).orderBy('created_at', 'asc'))).map(row => toInvitation(row)!),
363
+ listByEmail: async email => (await invitations.read.findMany(q => q.where({ email }).orderBy('created_at', 'asc'))).map(row => toInvitation(row)!),
364
+ delete: async id => await invitations.write.deleteById(id) !== null,
365
+ },
366
+ bearerTokens: {
367
+ async create(token) {
368
+ await bearerTokens.write.insertOne({ id: token.id, user_id: token.userId, label: token.label, digest: token.digest, scopes: token.scopes, created_at: token.createdAt, last_used_at: token.lastUsedAt, expires_at: token.expiresAt, oauth_client: token.oauth?.clientId ?? null, oauth_family: token.oauth?.family ?? null, oauth_resource: token.oauth?.resource ?? null })
369
+ },
370
+ findByDigest: async digest => toBearerToken(await bearerTokens.read.findOne({ digest })),
371
+ async findByDigestWithUser(digest) {
372
+ // eslint-disable-next-line ts/no-unsafe-call, ts/no-unsafe-member-access, ts/no-unsafe-return -- joinedUser's query is untyped, as it says
373
+ const [row] = await bearerTokens.read.findMany(q => joinedUser(q).where({ digest }).limit(1)) as unknown as (InferEntity<typeof AuthBearerTokens> & Record<string, unknown>)[]
374
+
375
+ return row && { token: toBearerToken(row)!, user: toUser(userOf(row))! }
376
+ },
377
+ listByUser: async userId => (await bearerTokens.read.findMany(q => q.where({ user_id: userId }).orderBy('created_at', 'asc'))).map(row => toBearerToken(row)!),
378
+ async touch(id, at) {
379
+ await bearerTokens.write.updateById(id, { last_used_at: at })
380
+ },
381
+ delete: async (userId, id) => await bearerTokens.write.deleteOne({ id, user_id: userId }) !== null,
382
+ erase: async userId => (await bearerTokens.write.deleteMany({ user_id: userId }, { pk: true })).length,
383
+ },
384
+ oauth: {
385
+ clients: {
386
+ async create(client) {
387
+ await oauthClients.write.insertOne({ id: client.id, name: client.name, redirect_uris: client.redirectUris, created_at: client.createdAt })
388
+ },
389
+ get: async id => toOAuthClient(await oauthClients.read.findById(id)),
390
+ },
391
+ grants: {
392
+ get: async (userId, clientId) => toOAuthGrant(await oauthGrants.read.findOne({ user_id: userId, client_id: clientId })),
393
+ async upsert(grant) {
394
+ await oauthGrants.write.upsertOne({ user_id: grant.userId, client_id: grant.clientId, client_name: grant.clientName, scopes: grant.scopes, created_at: grant.createdAt, last_used_at: grant.lastUsedAt }, ['user_id', 'client_id'], ['client_name', 'scopes', 'last_used_at'])
395
+ },
396
+ async touch(userId, clientId, at) {
397
+ await oauthGrants.write.updateMany({ last_used_at: at }, { user_id: userId, client_id: clientId }, { pk: true })
398
+ },
399
+ listByUser: async userId => (await oauthGrants.read.findMany(q => q.where({ user_id: userId }).orderBy('created_at', 'asc').orderBy('id', 'asc'))).map(row => toOAuthGrant(row)!),
400
+ async revoke(userId, clientId) {
401
+ return db.transaction(async (tx) => {
402
+ await oauthRefresh.using(tx).write.deleteMany({ user_id: userId, client_id: clientId })
403
+ await bearerTokens.using(tx).write.deleteMany({ user_id: userId, oauth_client: clientId })
404
+
405
+ return await oauthGrants.using(tx).write.deleteOne({ user_id: userId, client_id: clientId }) !== null
406
+ })
407
+ },
408
+ },
409
+ codes: {
410
+ async create(code) {
411
+ await oauthCodes.write.insertOne({ digest: code.digest, user_id: code.userId, client_id: code.clientId, redirect_uri: code.redirectUri, challenge: code.challenge, scopes: code.scopes, family: code.family, resource: code.resource ?? null, created_at: code.createdAt, expires_at: code.expiresAt, used_at: code.usedAt })
412
+ },
413
+ async get(digest) {
414
+ const row = await oauthCodes.read.findById(digest)
415
+
416
+ return row ? toOAuthCode(row) : undefined
417
+ },
418
+ async use(digest, at) {
419
+ // One UPDATE on the unspent row, so of two requests spending the code only one finds it unspent.
420
+ const [spent] = await oauthCodes.write.updateMany({ used_at: at }, e => e.and(e.eq('digest', digest), e.isNull('used_at')))
421
+
422
+ if (spent)
423
+ return { code: toOAuthCode(spent), reused: false }
424
+
425
+ const row = await oauthCodes.read.findById(digest)
426
+
427
+ return row ? { code: toOAuthCode(row), reused: true } : undefined
428
+ },
429
+ },
430
+ refresh: {
431
+ async create(token) {
432
+ await oauthRefresh.write.insertOne({ digest: token.digest, user_id: token.userId, client_id: token.clientId, scopes: token.scopes, family: token.family, resource: token.resource ?? null, created_at: token.createdAt, expires_at: token.expiresAt, used_at: token.usedAt })
433
+ },
434
+ async get(digest) {
435
+ const row = await oauthRefresh.read.findById(digest)
436
+
437
+ return row ? toOAuthRefresh(row) : undefined
438
+ },
439
+ async use(digest, at) {
440
+ const [spent] = await oauthRefresh.write.updateMany({ used_at: at }, e => e.and(e.eq('digest', digest), e.isNull('used_at')))
441
+
442
+ if (spent)
443
+ return { token: toOAuthRefresh(spent), reused: false }
444
+
445
+ const row = await oauthRefresh.read.findById(digest)
446
+
447
+ return row ? { token: toOAuthRefresh(row), reused: true } : undefined
448
+ },
449
+ async revokeFamily(userId, family) {
450
+ await db.transaction(async (tx) => {
451
+ await oauthRefresh.using(tx).write.deleteMany({ user_id: userId, family })
452
+ await bearerTokens.using(tx).write.deleteMany({ user_id: userId, oauth_family: family })
453
+ })
454
+ },
455
+ async erase(userId) {
456
+ return await withoutMissingOAuthTables(async () => (await oauthRefresh.write.deleteMany({ user_id: userId }, { pk: true })).length) ?? 0
457
+ },
458
+ },
459
+ },
460
+ recoveryCodes: {
461
+ async replace(userId, digests) {
462
+ await db.transaction(async (tx) => {
463
+ const codes = recoveryCodes.using(tx)
464
+
465
+ await codes.write.deleteMany({ user_id: userId })
466
+
467
+ if (digests.length > 0)
468
+ await codes.write.insertMany(digests.map(digest => ({ user_id: userId, digest })))
469
+ })
470
+ },
471
+ consume: async (userId, digest) => await recoveryCodes.write.deleteOne({ user_id: userId, digest }) !== null,
472
+ count: async userId => recoveryCodes.read.count({ user_id: userId }),
473
+ },
474
+ rates: {
475
+ async peek(key) {
476
+ const row = await attempts.read.findById(key)
477
+
478
+ return row && row.reset_at.getTime() > Date.now() ? { count: row.count, resetAt: row.reset_at.getTime() } : undefined
479
+ },
480
+ async hit(key, window, weight = 1) {
481
+ const now = new Date()
482
+
483
+ // One statement, so two attempts at once both count: a window still open is raised, an ended one starts over.
484
+ const [row] = await db.raw<{ count: number, reset_at: Date | string | number }>`
485
+ INSERT INTO "kay_attempts" ("key", "count", "reset_at") VALUES (${key}, ${weight}, ${new Date(now.getTime() + window)})
486
+ ON CONFLICT ("key") DO UPDATE SET
487
+ "count" = CASE WHEN "kay_attempts"."reset_at" > ${now} THEN "kay_attempts"."count" + ${weight} ELSE ${weight} END,
488
+ "reset_at" = CASE WHEN "kay_attempts"."reset_at" > ${now} THEN "kay_attempts"."reset_at" ELSE EXCLUDED."reset_at" END
489
+ RETURNING "count", "reset_at"`
490
+
491
+ return { count: Number(row!.count), resetAt: new Date(row!.reset_at).getTime() }
492
+ },
493
+ async reset(key) {
494
+ await attempts.write.deleteMany({ key })
495
+ },
496
+ },
497
+ async prune({ now, bearerExpiredBefore, sessionMaxAge, sessionAbsoluteMaxAge }: PruneLimits) {
498
+ await Promise.all([
499
+ withoutMissingOAuthTables(async () => Promise.all([
500
+ oauthCodes.write.deleteMany({ expires_at: { lte: now } }),
501
+ oauthRefresh.write.deleteMany({ expires_at: { lte: now } }),
502
+ // A client that registered itself and that nobody approved within `UNUSED_CLIENT_MS`, a day.
503
+ db.raw`DELETE FROM "kay_oauth_clients" WHERE "created_at" < ${new Date(now.getTime() - UNUSED_CLIENT_MS)} AND NOT EXISTS (SELECT 1 FROM "kay_oauth_grants" WHERE "kay_oauth_grants"."client_id" = "kay_oauth_clients"."id")`,
504
+ ])),
505
+ tokens.write.deleteMany({ expires_at: { lte: now } }),
506
+ invitations.write.deleteMany({ expires_at: { lte: now } }),
507
+ bearerTokens.write.deleteMany({ expires_at: { lt: bearerExpiredBefore } }),
508
+ attempts.write.deleteMany({ reset_at: { lte: now } }),
509
+ sessions.write.deleteMany({ last_seen_at: { lt: new Date(now.getTime() - durationSeconds(sessionMaxAge, 'sessionMaxAge') * 1000) } }),
510
+ sessions.write.deleteMany({ created_at: { lt: new Date(now.getTime() - durationSeconds(sessionAbsoluteMaxAge, 'sessionAbsoluteMaxAge') * 1000) } }),
511
+ // A session the user's version moved past is already refused, so its row goes too.
512
+ db.raw`DELETE FROM "kay_auth_sessions" WHERE "version" < (SELECT "session_version" FROM "kay_users" WHERE "kay_users"."id" = "kay_auth_sessions"."user_id")`,
513
+ ])
514
+ },
515
+ }
516
+ }
517
+
518
+ // Postgres code 42P01 on pg-orm's error, on its Postgres cause or on a raw query's error; SQLite words it as `no such table`.
519
+ function isMissingTable(error: unknown): boolean {
520
+ const { code, errno, cause, message } = (error ?? {}) as { code?: unknown, errno?: unknown, cause?: unknown, message?: unknown }
521
+
522
+ return code === '42P01' || errno === '42P01' || (cause !== undefined && cause !== error && isMissingTable(cause)) || (typeof message === 'string' && message.includes('no such table'))
523
+ }
524
+
525
+ let warnedMissingOAuthTables = false
526
+
527
+ // An app whose migrations predate the OAuth server has no OAuth tables yet: what only the OAuth server needs is skipped with one warning, so sign-in, magic links and password resets still work. Any other failure is thrown.
528
+ async function withoutMissingOAuthTables(run: () => Promise<unknown>): Promise<void> {
529
+ try {
530
+ await run()
531
+ }
532
+ catch (error) {
533
+ if (!isMissingTable(error))
534
+ throw error
535
+
536
+ if (!warnedMissingOAuthTables) {
537
+ warnedMissingOAuthTables = true
538
+ log.warn('the kay_oauth_* tables are missing, so the OAuth server is skipped: generate a migration with `bunx pg-orm generate` (or run db.sync())')
539
+ }
540
+ }
541
+ }
542
+
543
+ // A bearer token's query with its user's columns joined on as `u.<column>`.
544
+ const JOINED_COLUMNS = [...Object.keys(AuthBearerTokens.columns), ...Object.keys(AuthUsers.columns).map(column => `u.${column}`)]
545
+
546
+ /* eslint-disable ts/no-explicit-any, ts/no-unsafe-call, ts/no-unsafe-member-access, ts/no-unsafe-return -- untyped because pg-orm types a `pick` by its column names, which these are built from at run time */
547
+ function joinedUser(q: any) {
548
+ return q.join(AuthUsers, 'u', (e: any) => e.eq('user_id', e.ref('u.id'))).pick(...JOINED_COLUMNS)
549
+ }
550
+ /* eslint-enable ts/no-explicit-any, ts/no-unsafe-call, ts/no-unsafe-member-access, ts/no-unsafe-return */
551
+
552
+ // The user columns holding a date.
553
+ const DATE_COLUMNS = new Set(['email_verified_at', 'totp_enabled_at', 'banned_at', 'banned_until', 'delete_at', 'created_at'])
554
+
555
+ // One user column's value as the user alone gives it: anything but null or what is typed already is converted as pg-orm converts it for SQLite.
556
+ function decoded(column: string, value: unknown): unknown {
557
+ if (value === null || value === undefined)
558
+ return value
559
+
560
+ if ((column === 'roles' || column === 'data') && typeof value === 'string') {
561
+ try {
562
+ return JSON.parse(value)
563
+ }
564
+ catch {
565
+ return value
566
+ }
567
+ }
568
+
569
+ if (column === 'guest' && typeof value !== 'boolean')
570
+ return Boolean(value)
571
+
572
+ return DATE_COLUMNS.has(column) && !(value instanceof Date) ? new Date(value as string | number) : value
573
+ }
574
+
575
+ // The user a joined row holds, its columns typed as a read of the user alone gives them: Postgres types them as it reads, SQLite hands a date as text, an array or an object as JSON text and a boolean as 0 or 1.
576
+ function userOf(row: Record<string, unknown>): UserRow {
577
+ const user: Record<string, unknown> = {}
578
+
579
+ for (const column of Object.keys(AuthUsers.columns)) {
580
+ const value = row[`u.${column}`]
581
+
582
+ user[column] = decoded(column, value)
583
+ }
584
+
585
+ return user as UserRow
586
+ }
587
+
588
+ function toUser(row: UserRow | null): UserRecord | undefined {
589
+ return row
590
+ ? {
591
+ id: row.id,
592
+ email: row.email,
593
+ emailVerifiedAt: row.email_verified_at,
594
+ username: row.username,
595
+ passwordHash: row.password_hash,
596
+ totpSecret: row.totp_secret,
597
+ totpEnabledAt: row.totp_enabled_at,
598
+ totpLastStep: row.totp_last_step,
599
+ roles: row.roles,
600
+ sessionVersion: row.session_version,
601
+ lastSignIn: row.last_sign_in,
602
+ locale: row.locale,
603
+ guest: row.guest,
604
+ bannedAt: row.banned_at,
605
+ bannedUntil: row.banned_until,
606
+ banReason: row.ban_reason,
607
+ deleteAt: row.delete_at ?? null,
608
+ data: row.data ?? {},
609
+ createdAt: row.created_at,
610
+ }
611
+ : undefined
612
+ }
613
+
614
+ function fromUser(user: Partial<UserRecord>) {
615
+ return withoutUndefined({
616
+ id: user.id,
617
+ email: user.email,
618
+ email_verified_at: user.emailVerifiedAt,
619
+ username: user.username,
620
+ username_key: user.username === undefined ? undefined : user.username?.toLowerCase() ?? null,
621
+ password_hash: user.passwordHash,
622
+ totp_secret: user.totpSecret,
623
+ totp_enabled_at: user.totpEnabledAt,
624
+ totp_last_step: user.totpLastStep,
625
+ roles: user.roles,
626
+ session_version: user.sessionVersion,
627
+ last_sign_in: user.lastSignIn,
628
+ locale: user.locale,
629
+ guest: user.guest,
630
+ banned_at: user.bannedAt,
631
+ banned_until: user.bannedUntil,
632
+ ban_reason: user.banReason,
633
+ delete_at: user.deleteAt,
634
+ data: user.data,
635
+ created_at: user.createdAt,
636
+ })
637
+ }
638
+
639
+ function toIdentity(row: InferEntity<typeof AuthIdentities> | null): IdentityRecord | undefined {
640
+ return row ? { provider: row.provider, providerId: row.provider_id, userId: row.user_id, accessToken: row.access_token, refreshToken: row.refresh_token, tokenExpiresAt: row.token_expires_at, createdAt: row.created_at } : undefined
641
+ }
642
+
643
+ function toToken(row: InferEntity<typeof AuthTokens>): TokenRecord {
644
+ return { digest: row.digest, type: row.type as TokenType, userId: row.user_id, email: row.email, redirect: row.redirect, expiresAt: row.expires_at }
645
+ }
646
+
647
+ function toBearerToken(row: InferEntity<typeof AuthBearerTokens> | null): BearerTokenRecord | undefined {
648
+ return row ? { id: row.id, userId: row.user_id, label: row.label, digest: row.digest, scopes: row.scopes, createdAt: row.created_at, lastUsedAt: row.last_used_at, expiresAt: row.expires_at, ...row.oauth_client != null && row.oauth_family != null && { oauth: { clientId: row.oauth_client, family: row.oauth_family, resource: row.oauth_resource } } } : undefined
649
+ }
650
+
651
+ function toOAuthClient(row: InferEntity<typeof AuthOAuthClients> | null): OAuthClientRecord | undefined {
652
+ return row ? { id: row.id, name: row.name, redirectUris: row.redirect_uris, createdAt: row.created_at } : undefined
653
+ }
654
+
655
+ function toOAuthGrant(row: InferEntity<typeof AuthOAuthGrants> | null): OAuthGrantRecord | undefined {
656
+ return row ? { userId: row.user_id, clientId: row.client_id, clientName: row.client_name, scopes: row.scopes, createdAt: row.created_at, lastUsedAt: row.last_used_at } : undefined
657
+ }
658
+
659
+ function toOAuthCode(row: InferEntity<typeof AuthOAuthCodes>): OAuthCodeRecord {
660
+ return { digest: row.digest, userId: row.user_id, clientId: row.client_id, redirectUri: row.redirect_uri, challenge: row.challenge, scopes: row.scopes, family: row.family, resource: row.resource, createdAt: row.created_at, expiresAt: row.expires_at, usedAt: row.used_at }
661
+ }
662
+
663
+ function toOAuthRefresh(row: InferEntity<typeof AuthOAuthRefresh>): OAuthRefreshRecord {
664
+ return { digest: row.digest, userId: row.user_id, clientId: row.client_id, scopes: row.scopes, family: row.family, resource: row.resource, createdAt: row.created_at, expiresAt: row.expires_at, usedAt: row.used_at }
665
+ }
666
+
667
+ function toSession(row: InferEntity<typeof AuthSessions> | null): SessionRecord | undefined {
668
+ return row ? { id: row.id, userId: row.user_id, version: row.version, userAgent: row.user_agent, ip: row.ip, createdAt: row.created_at, lastSeenAt: row.last_seen_at, maxAge: row.max_age } : undefined
669
+ }
670
+
671
+ function toOrganization(row: InferEntity<typeof AuthOrganizations> | null): OrganizationRecord | undefined {
672
+ return row ? { id: row.id, name: row.name, slug: row.slug, createdAt: row.created_at } : undefined
673
+ }
674
+
675
+ function toMember(row: InferEntity<typeof AuthMembers> | number | null): MemberRecord | undefined {
676
+ return row !== null && typeof row === 'object' ? { organizationId: row.organization_id, userId: row.user_id, roles: row.roles, createdAt: row.created_at } : undefined
677
+ }
678
+
679
+ function toInvitation(row: InferEntity<typeof AuthInvitations> | null): InvitationRecord | undefined {
680
+ return row ? { id: row.id, organizationId: row.organization_id, email: row.email, roles: row.roles, invitedBy: row.invited_by, createdAt: row.created_at, expiresAt: row.expires_at } : undefined
681
+ }
682
+
683
+ function toAudit(row: InferEntity<typeof AuthAudit>): AuditRecord {
684
+ return { id: row.id, userId: row.user_id, event: row.event, detail: row.detail, ip: row.ip, userAgent: row.user_agent, actorId: row.actor_id, at: row.at }
685
+ }
686
+
687
+ function toPasskey(row: InferEntity<typeof AuthPasskeys> | null): PasskeyRecord | undefined {
688
+ return row ? { id: row.id, userId: row.user_id, name: row.name, publicKey: row.public_key, counter: Number(row.counter), transports: row.transports, multiDevice: row.multi_device, backedUp: row.backed_up, userVerified: row.user_verified, createdAt: row.created_at, lastUsedAt: row.last_used_at } : undefined
689
+ }
690
+
691
+ // pg-orm refuses an update with nothing to set, so an empty patch skips it.
692
+ function isEmpty(row: object): boolean {
693
+ return Object.keys(row).length === 0
694
+ }
695
+
696
+ // Writes a patch unless it names no field.
697
+ async function whenFilled<T extends object>(row: T, write: (row: T) => Promise<unknown>): Promise<void> {
698
+ if (!isEmpty(row))
699
+ await write(row)
700
+ }
701
+
702
+ // pg-orm refuses an `undefined` value, so a patch names only the fields it changes.
703
+ function withoutUndefined<T extends object>(row: T): { [Key in keyof T]: Exclude<T[Key], undefined> } {
704
+ return Object.fromEntries(Object.entries(row).filter(([, value]) => value !== undefined)) as { [Key in keyof T]: Exclude<T[Key], undefined> }
705
+ }