@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,60 @@
1
+ import type { Duration } from 'kay'
2
+ import type { Access } from './access'
3
+ import type { BareUser } from './core'
4
+ import type { Requirement } from './types'
5
+ import { durationSeconds } from 'kay/library'
6
+ import { roleHierarchy } from './roles'
7
+
8
+ const DEFAULT_INVITATION_MAX_AGE = '7d'
9
+
10
+ export interface OrganizationsOptions<OrgRole extends string, Role extends string> {
11
+ // Each organization role and the roles it includes, as `roles` is for the site: `{ owner: ['admin'], admin: ['member'], member: [] }`.
12
+ roles: Record<OrgRole, NoInfer<OrgRole>[]>
13
+ // The role of whoever creates an organization: one holding it may delete it, and the last member holding it cannot leave or lose it.
14
+ owner: NoInfer<OrgRole>
15
+ // What a member needs to rename the organization, invite, remove members and change their roles; `owner` by default.
16
+ manage?: NoInfer<OrgRole> | undefined
17
+ // What an invitation naming no roles gives, such as `['member']`; none by default, a plain membership.
18
+ defaultRoles?: NoInfer<OrgRole>[] | undefined
19
+ // Who may create an organization, a site role or a predicate; anyone signed in by default.
20
+ create?: Requirement<BareUser, NoInfer<Role>> | undefined
21
+ // The app's page an invitation link opens, the invitation's id in `?invitation=`: it shows `organizations.invitation(id)` and accepts it. The prebuilt pages' own `/auth/invitation` by default; inviting answers 'unavailable' without either.
22
+ invitationPage?: string | undefined
23
+ // How long an invitation lasts, `invitations: { maxAge: '7d' }`, a week by default.
24
+ invitations?: { maxAge?: Duration | undefined } | undefined
25
+ // The route param naming the organization a route is about, by id or slug, for `memberOf`: `org` by default.
26
+ param?: string | undefined
27
+ }
28
+
29
+ // What the `organizations` option settles, as kayjs-auth works with it.
30
+ export interface OrganizationsCore {
31
+ roles: Set<string>
32
+ // Whether `held` includes `required`, through the hierarchy.
33
+ isGranted: (required: string, held: string[]) => boolean
34
+ owner: string
35
+ manage: string
36
+ defaultRoles: string[]
37
+ param: string
38
+ invitationPage?: string | undefined
39
+ invitationMaxAge: number
40
+ // Whether a user may create an organization; anyone signed in without it.
41
+ create?: ((user: BareUser) => Promise<boolean>) | undefined
42
+ }
43
+
44
+ // `create` asks the app's `authorize`, through `access`.
45
+ export function organizationsCore<OrgRole extends string, Role extends string>(options: OrganizationsOptions<OrgRole, Role>, access: Access<Role>): OrganizationsCore {
46
+ const { isGranted } = roleHierarchy<BareUser, OrgRole>(options.roles, user => user.roles as OrgRole[])
47
+ const create = options.create
48
+
49
+ return {
50
+ ...create !== undefined && { create: async user => access.authorize(user, create, 'write', {}) },
51
+ roles: new Set(Object.keys(options.roles)),
52
+ isGranted: (required, held) => isGranted(required, held),
53
+ owner: options.owner,
54
+ manage: options.manage ?? options.owner,
55
+ defaultRoles: [...options.defaultRoles ?? []],
56
+ param: options.param ?? 'org',
57
+ invitationPage: options.invitationPage,
58
+ invitationMaxAge: durationSeconds(options.invitations?.maxAge ?? DEFAULT_INVITATION_MAX_AGE, 'organizations.invitations.maxAge'),
59
+ }
60
+ }
package/src/own.ts ADDED
@@ -0,0 +1,313 @@
1
+ import type { ExtensionApp, PluginInput } from 'kay/server'
2
+ import type { AuthOptions, authCore as CreateAuth } from './auth'
3
+ import type { AuthSessionData, OAuthApp } from './core'
4
+ import type { EmailOptions } from './email'
5
+ import type { AuthMailer } from './mail'
6
+ import type { ProviderOptions } from './oauth/providers'
7
+ import type { AuthPagesConfig, AuthPagesOptions, UserMaker } from './pages'
8
+ import type { AuthStore } from './store'
9
+ import type { OwnTest } from './test'
10
+ import { existsSync } from 'node:fs'
11
+ import { normalize, resolve } from 'node:path'
12
+ import process from 'node:process'
13
+ import { s } from 'kay'
14
+ import { appStore, configError } from 'kay/library'
15
+ import { session } from 'kay/server'
16
+ import { log } from './log'
17
+ import { memoryAuth } from './memoryStore'
18
+ import { discordProvider, facebookProvider, githubProvider, gitlabProvider, googleProvider, linkedinProvider, microsoftProvider, slackProvider, twitchProvider, xProvider } from './oauth/providers'
19
+
20
+ /** What a provider preset takes beside its credentials, which the environment supplies when they are left out. */
21
+ export interface PresetApp extends ProviderOptions {
22
+ // Read from `<NAME>_CLIENT_ID` (`GITHUB_CLIENT_ID`) when left out.
23
+ clientId?: string | undefined
24
+ // Read from `<NAME>_CLIENT_SECRET` when left out.
25
+ clientSecret?: string | undefined
26
+ label?: string | undefined
27
+ keepTokens?: boolean | undefined
28
+ // The Graph API version of the `facebook` preset.
29
+ version?: string | undefined
30
+ }
31
+
32
+ // The providers `oauth: { github: true }` names, each over its preset.
33
+ const PRESETS = {
34
+ github: githubProvider,
35
+ discord: discordProvider,
36
+ google: googleProvider,
37
+ microsoft: microsoftProvider,
38
+ gitlab: gitlabProvider,
39
+ linkedin: linkedinProvider,
40
+ facebook: facebookProvider,
41
+ twitch: twitchProvider,
42
+ slack: slackProvider,
43
+ x: xProvider,
44
+ } as unknown as Record<string, (options: ProviderOptions) => OAuthApp['provider']>
45
+
46
+ /** The hooks an app keeps in `src/auth.ts` as `export const hooks`, or hands to `auth({ hooks })`. */
47
+ export type AuthHooks = Partial<Pick<AuthOptions<AuthSessionData, string>, 'allow' | 'authorize' | 'exportData' | 'locate' | 'onEvent' | 'beforeDelete' | 'onSignUp' | 'profileFields'>>
48
+
49
+ /** Where kayjs-auth keeps its data when `store` is left out: a pg-orm database at `url`, the database of the app's `store` in kay.config.ts when it names one, else a SQLite file `data/auth.sqlite` (`data/auth.db` where an app already has it). */
50
+ export interface StoreUrl {
51
+ url: string
52
+ }
53
+
54
+ type StoreOption = AuthStore | StoreUrl | (() => AuthStore | Promise<AuthStore>)
55
+
56
+ type Inherited = 'sessions' | 'store' | 'oauth' | 'pages' | 'prefix' | 'email'
57
+
58
+ /** The options of `auth()` with no module: `authCore`'s own, with the session, the store, the mailer and the OAuth credentials found by convention. */
59
+ export interface OwnOptions<Role extends string = string, Prefix extends string = '/auth', Scope extends string = never, OrgRole extends string = never, UserData extends object = Record<string, never>> extends Omit<AuthOptions<AuthSessionData, Role, Prefix, Scope, OrgRole, UserData>, Inherited>, AuthPagesOptions {
60
+ module?: undefined
61
+ server?: undefined
62
+ // Where the OAuth and page routes live, `/auth` by default.
63
+ prefix?: Prefix | undefined
64
+ // The prebuilt pages are served by default; `false` leaves them out, an object tunes them (`remember`, `profile`). Left out they are served.
65
+ pages?: false | Pick<AuthPagesConfig, 'profile' | 'remember' | 'main'> | undefined
66
+ // The session cookie's name, `kay_session` by default; kay names it `__Host-` first over https unless `forwardAuth` shares it under a domain.
67
+ cookie?: string | undefined
68
+ // Providers by the name their routes take: `{ github: true }` reads `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET` (a preset: github, discord, google, microsoft, gitlab, linkedin, facebook, twitch, slack or x), an object adds options to a preset, and a full `OAuthApp` is an app of any provider.
69
+ oauth?: Record<string, true | PresetApp | OAuthApp> | undefined
70
+ // The users' data: a pg-orm database at `{ url }`, the store itself, or a function building it. `AUTH_DATABASE_URL` when set, else the database of the app's `store` (`sqliteData(path)`, `pgData(url)`), else `data/auth.sqlite` (SQLite; `data/auth.db` where it exists).
71
+ store?: StoreOption | undefined
72
+ // Mail for verification, resets and magic links. Left out, `src/mail.ts` exporting kayjs-mail's `mail` sends them; `false` sends none.
73
+ email?: EmailOptions | false | undefined
74
+ // The hooks as a module the app loads, `() => import('./src/auth')`, in place of `src/auth.ts` exporting `hooks`, which kay reads by convention, bakes into an executable and reloads under `kay dev`.
75
+ hooks?: (() => Promise<{ hooks: AuthHooks }>) | undefined
76
+ // As with a module: templates read `ctx.user` and `ctx.can(role)` with no option, and `true` also reads the user ahead of every page.
77
+ viewer?: boolean | undefined
78
+ }
79
+
80
+ export type OwnPlugin<Role extends string, Prefix extends string, Scope extends string, OrgRole extends string, UserData extends object> = ReturnType<typeof CreateAuth<AuthSessionData, Role, Prefix, Scope, OrgRole, UserData>>['plugin']
81
+
82
+ // The name kayjs-mail's `mail()` extension lists itself by.
83
+ export const MAIL_EXTENSION = '@kayjs/mail'
84
+ // A relative SQLite path: `sqlite://data/auth.sqlite`, not `sqlite:///srv/auth.db` or `sqlite://:memory:`.
85
+ const SQLITE_FILE = /^sqlite:(?:\/\/)?(?![/:])([^?]+)$/
86
+
87
+ function isPreset(app: true | PresetApp | OAuthApp): app is true | PresetApp {
88
+ return app === true || !('provider' in app)
89
+ }
90
+
91
+ /** The environment variables an `auth()` with no module reads, for `kay env` to list: the database url and the credentials of the providers asked by name. */
92
+ export function ownEnv(options: Pick<OwnOptions, 'oauth' | 'store'>) {
93
+ const names = Object.entries(options.oauth ?? {}).filter(([, app]) => isPreset(app) && (app === true || app.clientId === undefined || app.clientSecret === undefined)).map(([name]) => name)
94
+
95
+ return s.Object({
96
+ ...options.store === undefined && { AUTH_DATABASE_URL: s.Optional(s.String({ description: 'the database kayjs-auth keeps its users in, a Postgres or SQLite url; the one of the app\'s store, else data/auth.sqlite (SQLite; data/auth.db where it exists), when unset' })) },
97
+ ...Object.fromEntries(names.flatMap(name => [
98
+ [`${name.toUpperCase()}_CLIENT_ID`, s.String({ description: `the ${name} OAuth app's client id`, requiredInProduction: true })],
99
+ [`${name.toUpperCase()}_CLIENT_SECRET`, s.String({ description: `the ${name} OAuth app's client secret`, requiredInProduction: true })],
100
+ ])),
101
+ })
102
+ }
103
+
104
+ function appOf(name: string, given: true | PresetApp | OAuthApp): OAuthApp {
105
+ if (!isPreset(given))
106
+ return given
107
+
108
+ const preset = PRESETS[name]
109
+
110
+ if (!preset)
111
+ throw configError('auth', 'oauth', `oauth.${name} is \`true\` or has no \`provider\`, and only ${Object.keys(PRESETS).join(', ')} are presets: give \`{ provider, clientId, clientSecret }\``)
112
+
113
+ const { clientId, clientSecret, label, keepTokens, ...options } = given === true ? {} as PresetApp : given
114
+ const key = name.toUpperCase()
115
+ const id = clientId ?? process.env[`${key}_CLIENT_ID`]
116
+ const secret = clientSecret ?? process.env[`${key}_CLIENT_SECRET`]
117
+
118
+ if (id === undefined || id === '' || secret === undefined || secret === '')
119
+ throw configError('auth', 'oauth', `oauth.${name} needs ${key}_CLIENT_ID and ${key}_CLIENT_SECRET in the environment, or \`clientId\` and \`clientSecret\``)
120
+
121
+ return { provider: preset(options), clientId: id, clientSecret: secret, ...label !== undefined && { label }, ...keepTokens !== undefined && { keepTokens } }
122
+ }
123
+
124
+ // The database url: `AUTH_DATABASE_URL`, empty as `.env.example` lists it counting as unset.
125
+ function databaseUrlFromEnv(): string | undefined {
126
+ return filled(process.env.AUTH_DATABASE_URL)
127
+ }
128
+
129
+ function filled(value: string | undefined): string | undefined {
130
+ return value === '' ? undefined : value
131
+ }
132
+
133
+ function isStore(store: AuthStore | StoreUrl): store is AuthStore {
134
+ return 'users' in store
135
+ }
136
+
137
+ // A SQLite file named by a relative path is kept under the project root, wherever the process runs.
138
+ function underRoot(url: string, root: string): string {
139
+ const file = SQLITE_FILE.exec(url)?.[1]
140
+
141
+ return file === undefined ? url : `sqlite://${resolve(root, file)}`
142
+ }
143
+
144
+ const ABSOLUTE_SQLITE = /^sqlite:\/\/(\/.*)$/
145
+
146
+ // The same database written two ways (a relative path, or an absolute one) is the same url once resolved under the root.
147
+ function sameDatabase(a: string, b: string, root: string): boolean {
148
+ const resolved = (url: string) => underRoot(url, root).replace(ABSOLUTE_SQLITE, (_, file: string) => `sqlite://${normalize(file)}`)
149
+
150
+ return resolved(a) === resolved(b)
151
+ }
152
+
153
+ // Every table of the database that is not kayjs-auth's own, which sharing the app's database must leave alone: pg-orm's sync would drop them.
154
+ function foreignTables(names: readonly string[]): RegExp {
155
+ return new RegExp(`^(?!(?:${names.join('|')})$)`)
156
+ }
157
+
158
+ const OWN_FILE = 'data/auth.sqlite'
159
+ // What the file was called before 1.88 gave every default data file the `.sqlite` extension: an app whose users are in it keeps it.
160
+ const LEGACY_OWN_FILE = 'data/auth.db'
161
+ const warned = new Set<string>()
162
+
163
+ async function storeOf(store: StoreOption | undefined, root: string, shared: string | undefined, exporting: boolean | undefined): Promise<AuthStore> {
164
+ if (typeof store === 'function')
165
+ return store()
166
+
167
+ if (store !== undefined && isStore(store))
168
+ return store
169
+
170
+ // An empty value, as .env.example lists it, is not a url.
171
+ const given = store?.url ?? databaseUrlFromEnv()
172
+
173
+ // Tests start from no users each run, as a file kept between them would not, and a static export reads none and creates or migrates no table.
174
+ if (exporting || (given === undefined && process.env.NODE_ENV === 'test'))
175
+ return memoryAuth()
176
+
177
+ // The database of the app's own `store` when it names one, so `sqliteData` or `pgData(url)` in kay.config.ts is the only place to say where the data lives.
178
+ // An app whose users are already in `data/auth.db` keeps them there, so an upgrade loses no one.
179
+ const file = existsSync(resolve(root, LEGACY_OWN_FILE)) ? LEGACY_OWN_FILE : OWN_FILE
180
+ const kept = given === undefined && shared !== undefined && existsSync(resolve(root, file))
181
+ const url = kept ? undefined : given ?? shared
182
+
183
+ if (kept && !warned.has(root)) {
184
+ warned.add(root)
185
+ log.warn(`auth() keeps its users in ${file}, which exists, though the app's store names a database: to use that database, move the users into it and set AUTH_DATABASE_URL to its url (or delete the file when it holds none)`)
186
+ }
187
+
188
+ let orm: typeof import('@kaynooo/pg-orm')
189
+ let pg: typeof import('./pg')
190
+
191
+ try {
192
+ orm = await import('@kaynooo/pg-orm')
193
+ pg = await import('./pg')
194
+ }
195
+ catch (error) {
196
+ throw configError('auth', 'store', 'the store of auth() is a pg-orm database, and @kaynooo/pg-orm is not installed: install it, or give `store` an AuthStore', { cause: error })
197
+ }
198
+
199
+ const db = new orm.Database({ url: underRoot(url ?? `sqlite://${file}`, root), tables: [...pg.authTables] })
200
+
201
+ await db.sync(!kept && url !== undefined && shared !== undefined && sameDatabase(url, shared, root) ? { ignoreTables: [foreignTables(pg.authTables.map(table => table.name))] } : undefined)
202
+
203
+ return pg.pgAuth(db)
204
+ }
205
+
206
+ // The hooks of `src/auth.ts`, which an app mounting its own `authCore` result from there has not meant for this.
207
+ function conventionalHooks(loaded: Record<string, unknown> | undefined): AuthHooks | undefined {
208
+ const own = loaded?.auth
209
+
210
+ if (typeof own === 'object' && own !== null && 'plugin' in own)
211
+ throw configError('auth', 'module', 'src/auth.ts exports `auth`, a authCore result, while auth() builds its own: give `auth({ module: \'./src/auth\' })` for kay to mount it, or `auth({ server: false })` if you mount it by hand')
212
+
213
+ return loaded?.hooks as AuthHooks | undefined
214
+ }
215
+
216
+ interface MailModule { enqueue?: (message: never) => unknown, send?: (message: never) => unknown, erase?: AuthMailer['erase'], subscriptions?: AuthMailer['subscriptions'] }
217
+
218
+ // `email` with the mail module's erase and export of an address on its mailer, unless the mailer has its own, so an erased account takes its mailing lists with it whichever way the app wrote `email`.
219
+ function withPrivacy(email: EmailOptions, mail: MailModule | undefined): EmailOptions {
220
+ const erase = email.mailer.erase === undefined && typeof mail?.erase === 'function' ? mail.erase.bind(mail) : undefined
221
+ const subscriptions = email.mailer.subscriptions === undefined && typeof mail?.subscriptions === 'function' ? mail.subscriptions.bind(mail) : undefined
222
+
223
+ if (erase === undefined && subscriptions === undefined)
224
+ return email
225
+
226
+ // The app's mailer stays the prototype, so a method of it reading `this` still works.
227
+ return { ...email, mailer: Object.create(email.mailer, { ...erase && { erase: { value: erase, enumerable: true } }, ...subscriptions && { subscriptions: { value: subscriptions, enumerable: true } } }) as AuthMailer }
228
+ }
229
+
230
+ // The mailer `mail()` of kay.config.ts built with no module, which an app with no `src/mail.ts` sends through.
231
+ async function registeredMailer(app: ExtensionApp): Promise<unknown> {
232
+ if (!app.extensions.includes(MAIL_EXTENSION))
233
+ return undefined
234
+
235
+ let mail: typeof import('@kayjs/mail')
236
+
237
+ try {
238
+ mail = await import('@kayjs/mail')
239
+ }
240
+ catch {
241
+ return undefined
242
+ }
243
+
244
+ // A failure of the registered loader is the app's to see.
245
+ return mail.registeredMailer()
246
+ }
247
+
248
+ export async function emailOf(email: OwnOptions['email'], app: ExtensionApp): Promise<EmailOptions | undefined> {
249
+ if (email === false)
250
+ return undefined
251
+
252
+ const mail = (app.modules.mail?.mail ?? await registeredMailer(app)) as MailModule | undefined
253
+
254
+ if (email !== undefined)
255
+ return withPrivacy(email, mail)
256
+
257
+ const send = mail?.enqueue ?? mail?.send
258
+
259
+ if (send === undefined)
260
+ return undefined
261
+
262
+ // kayjs-mail registered in kay.config.ts brings its wording, views and theme to the mails, as `kay add auth` writes it.
263
+ if (!app.extensions.includes(MAIL_EXTENSION))
264
+ return withPrivacy({ mailer: { send: send as never } }, mail)
265
+
266
+ try {
267
+ const { authMailer } = await import('@kayjs/mail')
268
+
269
+ return withPrivacy({ mailer: authMailer(send as never) }, mail)
270
+ }
271
+ catch {
272
+ return withPrivacy({ mailer: { send: send as never } }, mail)
273
+ }
274
+ }
275
+
276
+ // The auth each test site's `auth()` with no module built, by the site's cookies, which `authTest` signs that site in through.
277
+ const builtFor = new WeakMap<Bun.CookieMap, OwnTest>()
278
+
279
+ export function builtOwn(site: { cookies: Bun.CookieMap }): OwnTest | undefined {
280
+ return builtFor.get(site.cookies)
281
+ }
282
+
283
+ /** The `authCore` an `auth()` with no module makes as the server starts: kay's session, the store, the mailer and the hooks found, the pages on. */
284
+ export async function buildOwn(options: OwnOptions, app: ExtensionApp): Promise<UserMaker & { plugin: PluginInput }> {
285
+ const { authCore } = await import('./auth')
286
+ const { hooks: loadHooks, store, oauth, email, pages, prefix, home, cookie, ...rest } = options
287
+ const hooks = loadHooks ? (await loadHooks()).hooks : conventionalHooks(app.modules.hooks)
288
+ const mailer = await emailOf(email, app)
289
+
290
+ if (store === undefined && app.database === undefined && process.env.NODE_ENV === 'production' && databaseUrlFromEnv() === undefined) {
291
+ const file = existsSync(resolve(app.root, LEGACY_OWN_FILE)) ? LEGACY_OWN_FILE : OWN_FILE
292
+
293
+ log.warn(appStore()?.sql === undefined
294
+ ? `auth() keeps its users in ${file}, a SQLite file: set the app's \`store\` (\`sqliteData\` or \`pgData\`) in kay.config.ts, AUTH_DATABASE_URL, or auth's \`store\`, for a database that outlives a deploy`
295
+ : `auth() keeps its users in ${file}, a SQLite file, because pgData was given a connection and names no url: set AUTH_DATABASE_URL or pass auth({ store: pgAuth(db) }) for a database that outlives a deploy`)
296
+ }
297
+
298
+ const made = authCore({
299
+ ...hooks,
300
+ ...rest,
301
+ ...prefix !== undefined && { prefix },
302
+ sessions: session<AuthSessionData>(cookie === undefined ? {} : { cookie }),
303
+ store: await storeOf(store, app.root, app.database, app.exporting),
304
+ ...oauth && { oauth: Object.fromEntries(Object.entries(oauth).map(([name, app]) => [name, appOf(name, app)])) },
305
+ ...mailer && { email: mailer },
306
+ pages: pages === false ? undefined : { prefix: prefix ?? '/auth', home: home ?? '/', ...typeof pages === 'object' && pages },
307
+ })
308
+
309
+ if (app.testCookies)
310
+ builtFor.set(app.testCookies, made)
311
+
312
+ return made as unknown as UserMaker & { plugin: PluginInput }
313
+ }
@@ -0,0 +1,16 @@
1
+ ---
2
+ import type { CaptchaAction, CaptchaWidget } from '../../captcha'
3
+ import { wording } from 'kay/words'
4
+
5
+ const { widget, challenge = null, action } = props<{ widget: CaptchaWidget | 'proof-of-work', challenge?: string | null, action: CaptchaAction }>()
6
+ ---
7
+ // Kay's script solves the challenge while the form is filled in and posts the solution in this field's place; without JavaScript it posts empty.
8
+ if widget === 'proof-of-work'
9
+ if challenge
10
+ input(type="hidden" name="kayjs-captcha" data-kay-work={challenge})
11
+ noscript
12
+ p.text-sm {wording('auth.errors.captchaScript', 'This form runs a check in your browser, which needs JavaScript: turn it on, then send it again.')}
13
+ else
14
+ // The provider's script fills the element and adds the field its token posts as; Turnstile hands the action back, which the check compares.
15
+ div(class={widget.class} data-sitekey={widget.siteKey} data-action={action})
16
+ script(src={widget.script} async defer)
@@ -0,0 +1,11 @@
1
+ ---
2
+ const { size, gap, landmark = true } = props<{ size: string, gap: string, landmark?: boolean }>()
3
+ const classes = `kayjs-auth mx-auto flex w-full ${size} flex-col ${gap} px-4 py-8`
4
+ ---
5
+ // A prebuilt page's frame: a `main` landmark unless `pages.main` is false, for an app whose layout writes one.
6
+ if landmark
7
+ main(class={classes})
8
+ slot
9
+ else
10
+ div(class={classes})
11
+ slot
@@ -0,0 +1,8 @@
1
+ ---
2
+ const { text, tone = 'error' } = props<{ text: string, tone?: 'error' | 'success' }>()
3
+ ---
4
+ // An error is announced at once, a confirmation when the reader gets to it.
5
+ if tone === 'error'
6
+ p.kauth-error.text-danger(role="alert") {text}
7
+ else
8
+ p.kauth-success.text-success(role="status") {text}
@@ -0,0 +1,12 @@
1
+ ---
2
+ import Card from '@kayjs/ui/card.kay'
3
+ import Frame from './frame.kay'
4
+
5
+ const { title, landmark = true } = props<{ title: string, landmark?: boolean }>()
6
+ ---
7
+ // A sign-in page's frame: one card, its title the page's heading.
8
+ Frame(size="max-w-md" gap="gap-4" landmark={landmark})
9
+ h1.kui-heading-section {title}
10
+ Card
11
+ .flex.flex-col.gap-4
12
+ slot
@@ -0,0 +1,48 @@
1
+ ---
2
+ import type { User } from '../../core'
3
+ import { onMount, signal } from 'kay'
4
+ import Button from '@kayjs/ui/button.kay'
5
+ import FormField from '@kayjs/ui/form-field.kay'
6
+ import { canMakePasskey, makePasskey, passkeyFailure } from '../../browser'
7
+ import { addPasskey, passkeyOptions } from '../routes/account/security.kay'
8
+ import Proof from './proof.kay'
9
+
10
+ const { user, label, nameLabel, passwordLabel, codeLabel, unsupported, failed, errors } = props<{ user: Pick<User, 'hasPassword' | 'twoFactor'>, label: string, nameLabel: string, passwordLabel: string, codeLabel: string, unsupported: string, failed: string, errors: Record<string, string> }>()
11
+
12
+ const supported = signal<boolean>()
13
+ const error = signal('')
14
+ const name = signal('')
15
+
16
+ onMount(() => supported = canMakePasskey())
17
+
18
+ async function add(event: SubmitEvent) {
19
+ event.preventDefault()
20
+ error = ''
21
+
22
+ try {
23
+ const proof = new FormData(event.currentTarget as HTMLFormElement)
24
+
25
+ proof.delete('name')
26
+
27
+ const options = await passkeyOptions(proof, { refresh: false })
28
+ const response = await makePasskey(options)
29
+
30
+ if (response)
31
+ await addPasskey({ response, ...(name() ? { name: name() } : {}) })
32
+ }
33
+ catch (caught) {
34
+ error = passkeyFailure(caught, errors, failed)
35
+ }
36
+ }
37
+ ---
38
+ // A passkey needs script, so the form shows once the browser proves it can make one.
39
+ if supported() === false
40
+ p.text-muted {unsupported}
41
+ else if supported()
42
+ form.flex.flex-col.gap-3(onSubmit={add} novalidate)
43
+ FormField(label={nameLabel})
44
+ input(name="name" bind:value={name})
45
+ Proof(user={user} secondFactor passwordLabel={passwordLabel} codeLabel={codeLabel})
46
+ if error()
47
+ p.kauth-error.text-danger(role="alert") {error()}
48
+ Button(type="submit" label={label} busy={passkeyOptions.pending() || addPasskey.pending()})
@@ -0,0 +1,34 @@
1
+ ---
2
+ import { onMount, signal } from 'kay'
3
+ import Button from '@kayjs/ui/button.kay'
4
+ import { askPasskey, canAskPasskey, passkeyFailure, rememberChoice } from '../../browser'
5
+ import { passkey, passkeyOptions } from '../routes/sign-in.kay'
6
+
7
+ const { redirect, label, failed } = props<{ redirect: string, label: string, failed: string }>()
8
+
9
+ const supported = signal(false)
10
+ const error = signal('')
11
+
12
+ // Shown once the browser proves it can, since a passkey needs script.
13
+ onMount(() => supported = canAskPasskey())
14
+
15
+ async function signIn() {
16
+ error = ''
17
+
18
+ try {
19
+ const options = await passkeyOptions({}, { refresh: false })
20
+ const response = await askPasskey(options)
21
+ const remember = rememberChoice()
22
+
23
+ if (response)
24
+ await passkey({ response, redirect, ...(remember === undefined ? {} : { remember }) })
25
+ }
26
+ catch (caught) {
27
+ error = passkeyFailure(caught, {}, failed)
28
+ }
29
+ }
30
+ ---
31
+ if supported()
32
+ Button(label={label} onClick={signIn} busy={passkey.pending()})
33
+ if error()
34
+ p.kauth-error.text-danger(role="alert") {error()}
@@ -0,0 +1,33 @@
1
+ ---
2
+ import { onMount, signal } from 'kay'
3
+ import Button from '@kayjs/ui/button.kay'
4
+ import { askPasskey, canAskPasskey, passkeyFailure } from '../../browser'
5
+ import { passkey, passkeyOptions } from '../routes/two-factor.kay'
6
+
7
+ const { label, failed } = props<{ label: string, failed: string }>()
8
+
9
+ const supported = signal(false)
10
+ const error = signal('')
11
+
12
+ // Shown once the browser proves it can, since a passkey needs script.
13
+ onMount(() => supported = canAskPasskey())
14
+
15
+ async function verify() {
16
+ error = ''
17
+
18
+ try {
19
+ const options = await passkeyOptions({}, { refresh: false })
20
+ const response = await askPasskey(options)
21
+
22
+ if (response)
23
+ await passkey({ response })
24
+ }
25
+ catch (caught) {
26
+ error = passkeyFailure(caught, {}, failed)
27
+ }
28
+ }
29
+ ---
30
+ if supported()
31
+ Button(label={label} onClick={verify} busy={passkey.pending()})
32
+ if error()
33
+ p.kauth-error.text-danger(role="alert") {error()}
@@ -0,0 +1,15 @@
1
+ ---
2
+ import type { User } from '../../core'
3
+ import { wording } from 'kay/words'
4
+ import FormField from '@kayjs/ui/form-field.kay'
5
+
6
+ // An island renders it with the labels its page gives, as the messages only its server render or its own source name reach the browser.
7
+ const { user, secondFactor = false, passwordLabel = wording('auth.proof.password', 'Current password'), codeLabel = wording('auth.proof.code', 'Code from your authenticator app') } = props<{ user: Pick<User, 'hasPassword' | 'twoFactor'>, secondFactor?: boolean, passwordLabel?: string, codeLabel?: string }>()
8
+ ---
9
+ // What proves it is still the user: their password, or a code where they have none or the change asks for the second factor while it is on. An account with neither proves it by a recent sign-in.
10
+ if user.hasPassword && !(secondFactor && user.twoFactor)
11
+ FormField(label={passwordLabel} required)
12
+ input(name="password" type="password" autocomplete="current-password" required)
13
+ else if user.twoFactor
14
+ FormField(label={codeLabel} required)
15
+ input(name="code" autocomplete="one-time-code" autocapitalize="off" spellcheck="false" required)
@@ -0,0 +1,25 @@
1
+ ---
2
+ import Button from '@kayjs/ui/button.kay'
3
+ import { rememberChoice } from '../../browser'
4
+
5
+ const { providers } = props<{ providers: { name: string, label: string, href: string }[] }>()
6
+
7
+ // The links carry `remember` as the page's setting leaves it; a press sets it from the box first, which needs script, as a box beside a link does.
8
+ function carryRemember(event: Event) {
9
+ const link = (event.target as Element).closest<HTMLAnchorElement>('a[data-provider]')
10
+
11
+ const chosen = rememberChoice()
12
+
13
+ if (!link || chosen === undefined)
14
+ return
15
+
16
+ const url = new URL(link.href)
17
+
18
+ url.searchParams.set('remember', chosen ? '1' : '0')
19
+ link.href = url.pathname + url.search
20
+ }
21
+ ---
22
+ // kay-allow unreachable-click
23
+ .flex.flex-col.gap-2(onClick={carryRemember} onAuxClick={carryRemember})
24
+ for provider of providers key={provider.name}
25
+ Button(href={provider.href} label={provider.label} data-provider={provider.name} data-no-prefetch)
@@ -0,0 +1,13 @@
1
+ ---
2
+ import { wording } from 'kay/words'
3
+ import CopyButton from '@kayjs/ui/copy-button.kay'
4
+
5
+ const { codes } = props<{ codes: string[] }>()
6
+ ---
7
+ .flex.flex-col.gap-2
8
+ strong {wording('auth.account.twoFactor.recoveryCodes', 'Recovery codes')}
9
+ p {wording('auth.account.twoFactor.recoveryIntro', 'Keep these somewhere safe: each one signs you in once if you lose your authenticator. They are shown only now.')}
10
+ ul#kauth-recovery-codes.grid.grid-cols-2.gap-1.font-mono
11
+ for code of codes key={code}
12
+ li {code}
13
+ CopyButton(text={codes.join('\n')} label={wording('auth.account.twoFactor.copy', 'Copy the codes')})
@@ -0,0 +1,4 @@
1
+ ---
2
+ import { wording } from 'kay/words'
3
+ ---
4
+ p.text-center.text-muted {wording('auth.or', 'or')}