@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
@@ -0,0 +1,316 @@
1
+ import type { BareUser, Core } from './core'
2
+ import type { AuthFailed, AuthRejected } from './failure'
3
+ import type { EmailProblem, PasswordProblem, UsernameProblem } from './rules'
4
+ import type { SignInOptions } from './signInOptions'
5
+ import type { RequestState } from './state'
6
+ import type { UserRecord } from './store'
7
+ import { hashPassword, passwordNeedsRehash } from '@kaynooo/utils'
8
+ import { localPath } from 'kay'
9
+ import { newPasswordProblem } from './breached'
10
+ import { admit } from './captcha'
11
+ import { backOf, homeOf, newUserRecord, publicUser, unlinked } from './core'
12
+ import { afterResponse, report } from './events'
13
+ import { failed, rejected } from './failure'
14
+ import { failGuess, forgive, passwordMatches, startGuess } from './guesses'
15
+ import { validLocale } from './locale'
16
+ import { emailProblem, normalizeEmail, normalizeUsername, PASSWORD_MAX_LENGTH, usernameProblem } from './rules'
17
+
18
+ export interface RegisterInput {
19
+ email: string
20
+ password: string
21
+ username?: string
22
+ // The language the user reads, for their mails; the browser's by default.
23
+ locale?: string | undefined
24
+ }
25
+
26
+ // Why a field was refused, by field, as codes a form turns into messages in its own words and language.
27
+ export interface RegisterErrors {
28
+ email?: EmailProblem | 'taken' | undefined
29
+ // `breached` when the app checks for passwords known from a breach.
30
+ password?: PasswordProblem | 'breached' | undefined
31
+ username?: UsernameProblem | 'taken' | undefined
32
+ }
33
+
34
+ // `signedIn` is false, with no user, when the app wants the address verified first: the same answer whether the address was free or held, its holder mailed instead. `off` with `signUp: false`.
35
+ export type RegisterResult = { ok: true, user: BareUser, signedIn: true } | { ok: true, signedIn: false } | AuthRejected<RegisterErrors> | AuthFailed<'limited' | 'captcha' | 'off'>
36
+
37
+ export interface CreateUserInput {
38
+ // At least one of the two, the user signing in with either.
39
+ email?: string | undefined
40
+ username?: string | undefined
41
+ // Without one the user signs in by provider, mailed link or passkey alone.
42
+ password?: string | undefined
43
+ // Given beside `defaultRoles`.
44
+ roles?: string[] | undefined
45
+ // Whether the address counts as verified, as when the app knows it is theirs: false by default.
46
+ emailVerified?: boolean | undefined
47
+ locale?: string | undefined
48
+ }
49
+
50
+ export type CreateUserResult = { ok: true, user: BareUser } | AuthRejected<RegisterErrors>
51
+
52
+ export interface PasswordSignInInput {
53
+ // An email, or a username when it holds no `@`.
54
+ identifier: string
55
+ password: string
56
+ }
57
+
58
+ // `invalid` whether no account matches or the password is wrong, so the answer tells nothing of which accounts exist.
59
+ // `unverified` once the password is right, when the app wants the address verified first.
60
+ export type PasswordSignInResult = { ok: true, redirect: string } | AuthFailed<'invalid' | 'limited' | 'captcha' | 'unverified' | 'banned'>
61
+
62
+ // A new user with a password, signed in on this session; a guest signed in becomes it, keeping their id.
63
+ export async function register(state: RequestState, input: RegisterInput, options: Pick<SignInOptions, 'redirect' | 'captcha'> = {}): Promise<RegisterResult> {
64
+ const { store } = state.core
65
+
66
+ if (!state.core.signUp)
67
+ return failed('off')
68
+
69
+ const refused = await admit(state, 'register', options.captcha)
70
+
71
+ if (refused)
72
+ return failed(refused)
73
+
74
+ const email = normalizeEmail(input.email)
75
+ const username = input.username === undefined ? null : normalizeUsername(input.username)
76
+ const errors: RegisterErrors = {
77
+ email: emailProblem(email),
78
+ password: await newPasswordProblem(state.core, input.password),
79
+ username: username === null ? undefined : usernameProblem(username, state.core.rules),
80
+ }
81
+
82
+ const holder = errors.email ? undefined : await store.users.findByEmail(email)
83
+ const requireVerified = state.core.email?.requireVerified ?? false
84
+ // An address registered and never verified, where unverified accounts cannot sign in, holds nothing worth keeping: registering again replaces it, so no one can squat an address they do not own. An account given roles beyond the default ones was set up on purpose, as by an admin inviting someone, and stays.
85
+ const unclaimed = holder !== undefined && requireVerified && holder.emailVerifiedAt === null && holder.roles.every(role => state.core.defaultRoles.includes(role)) && (await store.identities.listByUser(holder.id)).length === 0
86
+
87
+ // Where registering signs no one in, an address already held is answered as a new one is, so the answer tells nothing of which addresses exist.
88
+ if (holder && !unclaimed && !requireVerified)
89
+ errors.email = 'taken'
90
+
91
+ // The unclaimed holder's own name is free with its address.
92
+ if (username !== null && !errors.username) {
93
+ const named = await store.users.findByUsername(username)
94
+
95
+ if (named && !(unclaimed && named.id === holder?.id))
96
+ errors.username = 'taken'
97
+ }
98
+
99
+ if (errors.email !== undefined || errors.password !== undefined || errors.username !== undefined)
100
+ return rejected(withoutUndefined(errors))
101
+
102
+ if (holder && !unclaimed)
103
+ return answerHeld(state, holder, input.password)
104
+
105
+ if (holder)
106
+ await replaceUnclaimed(state, holder)
107
+
108
+ const current = await state.current()
109
+ const guest = current?.guest && state.via() === 'session' ? current : undefined
110
+ const locale = input.locale !== undefined && validLocale(input.locale) ? input.locale : guest?.locale ?? state.languages[0] ?? null
111
+ const fields = { email, username, passwordHash: await hashPassword(input.password), locale, guest: false }
112
+ let record = guest ? { ...guest, ...fields } : newUserRecord({ ...fields, roles: [...state.core.defaultRoles] })
113
+
114
+ try {
115
+ record = guest ? await store.users.update(guest.id, fields) ?? record : (await store.users.create(record)) ?? record
116
+ }
117
+ // Another request took the email or the name in between; any other failure is the store's.
118
+ catch (error) {
119
+ const taken = await store.users.findByEmail(email)
120
+
121
+ if (taken && requireVerified)
122
+ return answerHeld(state, taken, null)
123
+
124
+ if (taken)
125
+ return rejected({ email: 'taken' })
126
+
127
+ if (username !== null && await store.users.findByUsername(username))
128
+ return rejected({ username: 'taken' })
129
+
130
+ throw error
131
+ }
132
+
133
+ const user = publicUser(record)
134
+
135
+ // A guest's records exist already. Where registering signs no one in, the app's hook runs off the response's path, as a held address runs none and its time would tell.
136
+ if (!guest && state.core.onSignUp) {
137
+ const { onSignUp } = state.core
138
+
139
+ if (requireVerified)
140
+ await afterResponse('onSignUp', async () => onSignUp(unlinked(user), undefined))
141
+ else
142
+ await onSignUp(unlinked(user), undefined)
143
+ }
144
+
145
+ // This browser may verify the address without signing in, as with `requireVerified` it cannot.
146
+ await state.session.set('authRegistered', record.id)
147
+ await state.session.unset('authHeld')
148
+ await keepBack(state, options.redirect)
149
+
150
+ if (state.core.email)
151
+ await (await import('./email')).welcome(state, record, backOf(state.core, options.redirect))
152
+
153
+ // A guest stays signed in: the account was theirs already.
154
+ if (requireVerified && !guest)
155
+ return { ok: true, signedIn: false }
156
+
157
+ await state.complete(record, homeOf(state.core), 'register')
158
+
159
+ return { ok: true, user, signedIn: true }
160
+ }
161
+
162
+ // What `createUser` would refuse `input` for, without making anyone, so the terminal command can say so before it asks a password; empty when it would go through.
163
+ export async function userProblems(core: Core, input: CreateUserInput): Promise<RegisterErrors> {
164
+ const email = input.email === undefined ? null : normalizeEmail(input.email)
165
+ const username = input.username === undefined ? null : normalizeUsername(input.username)
166
+
167
+ if (email === null && username === null)
168
+ throw new Error('kayjs-auth: createUser needs an email or a username to sign in with')
169
+
170
+ const undeclared = core.roles && input.roles?.find(role => !core.roles!.has(role))
171
+
172
+ if (undeclared !== undefined)
173
+ throw new Error(`kayjs-auth: createUser was given the role '${undeclared}', which the \`roles\` option does not declare`)
174
+
175
+ const errors: RegisterErrors = {
176
+ email: email === null ? undefined : emailProblem(email),
177
+ password: input.password === undefined ? undefined : await newPasswordProblem(core, input.password),
178
+ username: username === null ? undefined : usernameProblem(username, core.rules),
179
+ }
180
+
181
+ if (email !== null && !errors.email && await core.store.users.findByEmail(email))
182
+ errors.email = 'taken'
183
+
184
+ if (username !== null && !errors.username && await core.store.users.findByUsername(username))
185
+ errors.username = 'taken'
186
+
187
+ return withoutUndefined(errors)
188
+ }
189
+
190
+ // A user made by the app, checked as registering is but signing no one in and mailing no one, open with `signUp: false` too.
191
+ export async function createUser(core: Core, input: CreateUserInput): Promise<CreateUserResult> {
192
+ const errors = await userProblems(core, input)
193
+
194
+ if (Object.keys(errors).length > 0)
195
+ return rejected(errors)
196
+
197
+ const email = input.email === undefined ? null : normalizeEmail(input.email)
198
+ const username = input.username === undefined ? null : normalizeUsername(input.username)
199
+
200
+ let record = newUserRecord({
201
+ email,
202
+ emailVerifiedAt: email !== null && input.emailVerified === true ? new Date() : null,
203
+ username,
204
+ passwordHash: input.password === undefined ? null : await hashPassword(input.password),
205
+ roles: [...new Set([...core.defaultRoles, ...input.roles ?? []])],
206
+ locale: input.locale !== undefined && validLocale(input.locale) ? input.locale : null,
207
+ })
208
+
209
+ try {
210
+ record = (await core.store.users.create(record)) ?? record
211
+ }
212
+ // Another request took the email or the name in between; any other failure is the store's.
213
+ catch (error) {
214
+ if (email !== null && await core.store.users.findByEmail(email))
215
+ return rejected({ email: 'taken' })
216
+
217
+ if (username !== null && await core.store.users.findByUsername(username))
218
+ return rejected({ username: 'taken' })
219
+
220
+ throw error
221
+ }
222
+
223
+ const user = publicUser(record)
224
+
225
+ await core.onSignUp?.(unlinked(user), undefined)
226
+
227
+ return { ok: true, user }
228
+ }
229
+
230
+ // Frees the address and the name at once, under a placeholder address, and erases the account, `onDelete` included, off the response's path where registering signs no one in: a held address erases nothing, and the time the hook takes would tell it was unverified.
231
+ async function replaceUnclaimed(state: RequestState, holder: UserRecord): Promise<void> {
232
+ if (!state.core.email?.requireVerified) {
233
+ await (await import('./erase')).eraseUser(state.core, holder)
234
+
235
+ return
236
+ }
237
+
238
+ // The placeholder address keeps the account listed as unverified, so the stale sweep erases it should this erase fail or never run.
239
+ await state.core.store.users.update(holder.id, { email: `replaced+${holder.id}@invalid`, username: null })
240
+ await afterResponse('erasing the account a registration replaced', async () => (await import('./erase')).eraseUser(state.core, holder))
241
+ }
242
+
243
+ // Spends the time hashing a new password takes, so a held address answers no faster than a free one, and leaves this session as a new account's, which `email.sendVerification` answers alike, mailing no one.
244
+ async function answerHeld(state: RequestState, holder: UserRecord, password: string | null): Promise<RegisterResult> {
245
+ if (password !== null)
246
+ await hashPassword(password)
247
+
248
+ await state.session.unset('authRegistered')
249
+ await state.session.set('authHeld', holder.email!)
250
+
251
+ if (state.core.email)
252
+ await (await import('./email')).warnHolder(state, holder)
253
+
254
+ return { ok: true, signedIn: false }
255
+ }
256
+
257
+ // Parks the page a visitor asked for beside the account they may have verified, for the mail a resend sends.
258
+ async function keepBack(state: RequestState, redirect: string | undefined): Promise<void> {
259
+ const back = backOf(state.core, redirect)
260
+
261
+ if (back === null)
262
+ await state.session.unset('authBack')
263
+ else
264
+ await state.session.set('authBack', back)
265
+ }
266
+
267
+ export async function signInWithPassword(state: RequestState, input: PasswordSignInInput, options: Pick<SignInOptions, 'redirect' | 'captcha'>): Promise<PasswordSignInResult> {
268
+ const { store } = state.core
269
+ // Registration reads the address NFKC-normalised, so a fullwidth at sign names an email here too.
270
+ const byEmail = input.identifier.normalize('NFKC').includes('@')
271
+ const identifier = byEmail ? normalizeEmail(input.identifier) : normalizeUsername(input.identifier)
272
+
273
+ const refused = await admit(state, 'sign-in', options.captcha)
274
+
275
+ if (refused)
276
+ return failed(refused)
277
+
278
+ // No password this long was ever accepted, and hashing it would cost the server for nothing. A ceiling the app lowered later still lets an older, longer one sign in.
279
+ const tooLong = input.password.length > Math.max(PASSWORD_MAX_LENGTH, state.core.rules.password.max)
280
+ const record = tooLong ? undefined : await (byEmail ? store.users.findByEmail(identifier) : store.users.findByUsername(identifier))
281
+ // Counted before the password is checked, against the account so its email and every spelling of its name share one count.
282
+ const guess = await startGuess(state, record, identifier)
283
+
284
+ if (guess === 'limited')
285
+ return failed('limited')
286
+
287
+ if (tooLong || !(await passwordMatches(record, input.password))) {
288
+ await failGuess(state, guess)
289
+
290
+ // Off the response's path: the hooks and the audit log run for a held address only, and their time would tell it.
291
+ if (record)
292
+ await afterResponse('reporting a failed sign-in', async () => report(state, record, 'sign-in-failed', 'password'))
293
+
294
+ return failed('invalid')
295
+ }
296
+
297
+ await forgive(state, guess)
298
+
299
+ if (state.core.email?.requireVerified && record!.emailVerifiedAt === null) {
300
+ // The password is proven: this browser may have the verification link resent, and confirm it, as the one that registered.
301
+ await state.session.set('authRegistered', record!.id)
302
+ await keepBack(state, options.redirect)
303
+
304
+ return failed('unverified')
305
+ }
306
+
307
+ // Hashed with weaker settings, or by bcrypt in an older app: rehashed while the password is at hand.
308
+ if (passwordNeedsRehash(record!.passwordHash!))
309
+ await store.users.update(record!.id, { passwordHash: await hashPassword(input.password) })
310
+
311
+ return state.complete(record!, localPath(options.redirect, homeOf(state.core)), 'password')
312
+ }
313
+
314
+ function withoutUndefined(errors: RegisterErrors): RegisterErrors {
315
+ return Object.fromEntries(Object.entries(errors).filter(([, value]) => value !== undefined))
316
+ }
@@ -0,0 +1,22 @@
1
+ import type { AuthenticationResponseJSON, RegistrationResponseJSON } from './webauthn'
2
+ import { t } from 'elysia'
3
+
4
+ // The parts of a browser's answer a ceremony reads, as `credential.toJSON()` writes them: a post that lacks one is refused here, and the signature and challenge are the ceremony's to check.
5
+ const PART_MAX = 32_768
6
+ const part = t.String({ maxLength: PART_MAX })
7
+ // A credential id is up to 1023 bytes, 1364 characters in base64url.
8
+ const ID_MAX = 1366
9
+ const credential = { id: t.String({ maxLength: ID_MAX }), rawId: t.String({ maxLength: ID_MAX }), type: t.Literal('public-key'), clientExtensionResults: t.Object({}, { additionalProperties: true }) }
10
+ const transports = t.Optional(t.Array(t.String({ maxLength: 32 }), { maxItems: 16 }))
11
+
12
+ // The answer to `passkeys.signInOptions()`, `twoFactor.passkeyOptions()` or `passkeys.proofOptions()`, for the schema of an action calling `passkeys.signIn`, `twoFactor.verifyPasskey` or a proof.
13
+ export const passkeyAssertion = t.Unsafe<AuthenticationResponseJSON>(t.Object({
14
+ ...credential,
15
+ response: t.Object({ clientDataJSON: part, authenticatorData: part, signature: part, userHandle: t.Optional(part) }, { additionalProperties: true }),
16
+ }, { additionalProperties: true }))
17
+
18
+ // The answer to `passkeys.registrationOptions()`, for the schema of an action calling `passkeys.register`.
19
+ export const passkeyAttestation = t.Unsafe<RegistrationResponseJSON>(t.Object({
20
+ ...credential,
21
+ response: t.Object({ clientDataJSON: part, attestationObject: part, transports }, { additionalProperties: true }),
22
+ }, { additionalProperties: true }))