@kayjs/auth 0.0.0-stage → 1.104.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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,164 @@
1
+ --- server
2
+ import { action, localPath } from 'kay'
3
+ import { formatDate } from 'kay/i18n'
4
+ import { wording } from 'kay/words'
5
+ import Message from '../../components/message.kay'
6
+ import PasskeyAdd from '../../components/passkey-add.kay'
7
+ import Proof from '../../components/proof.kay'
8
+ import RecoveryCodes from '../../components/recovery-codes.kay'
9
+ import { failure, issue, proofOf, schemas } from '../../forms'
10
+ import Badge from '@kayjs/ui/badge.kay'
11
+ import Button from '@kayjs/ui/button.kay'
12
+ import CardRow from '@kayjs/ui/card-row.kay'
13
+ import EmptyState from '@kayjs/ui/empty-state.kay'
14
+ import FormField from '@kayjs/ui/form-field.kay'
15
+ import PageSection from '@kayjs/ui/page-section.kay'
16
+ import QrCode from '@kayjs/ui/qr-code.kay'
17
+
18
+ export const changePassword = action(schemas.changePassword, async (input, ctx) => {
19
+ const result = await ctx.locals.auth.password.change(proofOf(input), input.newPassword)
20
+
21
+ if (!result.ok)
22
+ return ctx.fail(400, 'errors' in result ? { password: result.errors.password } : { error: result.error.code })
23
+
24
+ return 'saved'
25
+ })
26
+
27
+ // Only the URI comes back: the page draws its QR code and reads the key off it.
28
+ export const setUp = action(schemas.proof, async (input, ctx) => {
29
+ const result = await ctx.locals.auth.twoFactor.setUp(proofOf(input))
30
+
31
+ return result.ok ? result.setup.uri : ctx.fail(400, { error: result.error.code })
32
+ })
33
+
34
+ // Posts the URI back with the code, so a wrong code shows the same QR code again.
35
+ export const enable = action(schemas.enableTwoFactor, async ({ code }, ctx) => {
36
+ const result = await ctx.locals.auth.twoFactor.enable(code)
37
+
38
+ return result.ok ? result.recoveryCodes : ctx.fail(400, { error: result.error.code === 'invalid' ? 'code' : result.error.code })
39
+ })
40
+
41
+ export const regenerate = action(schemas.proof, async (input, ctx) => {
42
+ const result = await ctx.locals.auth.twoFactor.regenerateRecoveryCodes(proofOf(input))
43
+
44
+ return result.ok ? result.recoveryCodes : ctx.fail(400, { error: result.error.code })
45
+ })
46
+
47
+ export const disable = action(schemas.proof, async (input, ctx) => {
48
+ const result = await ctx.locals.auth.twoFactor.disable(proofOf(input))
49
+
50
+ return result.ok ? 'disabled' : ctx.fail(400, { error: result.error.code })
51
+ })
52
+
53
+ export const passkeyOptions = action(schemas.proof, async (input, ctx) => {
54
+ const result = await ctx.locals.auth.passkeys.registrationOptions(proofOf(input))
55
+
56
+ return result.ok ? result.options : ctx.fail(400, { error: result.error.code })
57
+ })
58
+
59
+ export const addPasskey = action(schemas.registerPasskey, async (input, ctx) => {
60
+ const result = await ctx.locals.auth.passkeys.register(input.response, input.name)
61
+
62
+ return result.ok ? result.passkey.id : ctx.fail(400, { error: result.error.code })
63
+ })
64
+
65
+ export const renamePasskey = action(schemas.renamePasskey, async ({ id, name }, ctx) => {
66
+ return (await ctx.locals.auth.passkeys.rename(id, name)).ok ? name : ctx.fail(404, { error: 'not-found' })
67
+ })
68
+
69
+ export const removePasskey = action(schemas.removePasskey, async (input, ctx) => {
70
+ const result = await ctx.locals.auth.passkeys.revoke(input.id, proofOf(input))
71
+
72
+ return result.ok ? 'removed' : ctx.fail(400, { error: result.error.code, id: input.id })
73
+ })
74
+
75
+ const auth = ctx.locals.auth
76
+ const user = await auth.requireUser()
77
+ const features = auth.features()
78
+ const passwordSaved = changePassword.succeeded() !== undefined
79
+ const passwordRefused = changePassword.failed()?.data
80
+ const setupUri = setUp.succeeded()?.data ?? enable.failed()?.values.uri
81
+ const setupKey = setupUri && new URL(setupUri).searchParams.get('secret')
82
+ const twoFactorError = setUp.failed()?.data?.error ?? enable.failed()?.data?.error ?? regenerate.failed()?.data?.error ?? disable.failed()?.data?.error
83
+ const recoveryCodes = enable.succeeded()?.data ?? regenerate.succeeded()?.data
84
+ // Where a guard sent the user from to turn two-factor on: back there once it is on and its recovery codes were seen.
85
+ const back = localPath(ctx.url.searchParams.get('redirect'), '')
86
+
87
+ if (back !== '' && user.twoFactor && !recoveryCodes)
88
+ ctx.redirect(back)
89
+
90
+ const codesLeft = user.twoFactor ? await auth.twoFactor.recoveryCodesLeft() : 0
91
+ const passkeys = features.passkeys ? await auth.passkeys.list() : []
92
+ const removeRefused = removePasskey.failed()?.data
93
+ const passkeyErrors = Object.fromEntries((['proof', 'stale', 'limited', 'impersonating', 'expired', 'invalid', 'signed-out'] as const).map(code => [code, failure(code)]))
94
+ ---
95
+ if features.password
96
+ PageSection(title={wording('auth.account.password.title', 'Password')})
97
+ form.flex.flex-col.gap-3(action={changePassword})
98
+ if !user.hasPassword
99
+ p {wording('auth.account.password.none', 'You sign in without a password. Set one to sign in with your address too.')}
100
+ Proof(user={user})
101
+ FormField(label={wording('auth.newPassword', 'New password')} hint={wording('auth.passwordHint', 'At least {min} characters', { min: features.rules.password.min })} issue={passwordRefused && 'password' in passwordRefused ? issue('password', passwordRefused.password, features.rules) : undefined} required)
102
+ input(name="newPassword" type="password" autocomplete="new-password" minlength={features.rules.password.min} required)
103
+ if passwordSaved
104
+ Message(tone="success" text={wording('auth.account.password.changed', 'Your password is saved. Your other sessions were signed out.')})
105
+ if passwordRefused && 'error' in passwordRefused
106
+ Message(text={failure(passwordRefused.error)})
107
+ Button(type="submit" label={user.hasPassword ? wording('auth.account.password.change', 'Change the password') : wording('auth.account.password.set', 'Set a password')})
108
+ if features.twoFactor || user.twoFactor
109
+ PageSection(title={wording('auth.account.twoFactor.title', 'Two-step verification')})
110
+ @actions
111
+ Badge(label={user.twoFactor ? wording('auth.account.twoFactor.on', 'On') : wording('auth.account.twoFactor.off', 'Off')} tone={user.twoFactor ? 'success' : 'neutral'})
112
+ .flex.flex-col.gap-3
113
+ if recoveryCodes
114
+ RecoveryCodes(codes={recoveryCodes})
115
+ if back !== ''
116
+ a(href={back}) {wording('auth.account.twoFactor.continue', 'Continue')}
117
+ if twoFactorError
118
+ Message(text={failure(twoFactorError)})
119
+ if user.twoFactor
120
+ p#kauth-codes-left {wording('auth.account.twoFactor.codesLeft', codesLeft === 0 ? 'No recovery code left' : codesLeft === 1 ? '{count} recovery code left' : '{count} recovery codes left', { count: codesLeft })}
121
+ form.flex.flex-col.gap-3(action={regenerate})
122
+ Proof(user={user} secondFactor)
123
+ Button(type="submit" label={wording('auth.account.twoFactor.regenerate', 'Make new recovery codes')})
124
+ form.flex.flex-col.gap-3(action={disable})
125
+ Proof(user={user} secondFactor)
126
+ Button(type="submit" tone="danger" label={wording('auth.account.twoFactor.disable', 'Turn off')})
127
+ else if setupUri && features.twoFactor
128
+ p {wording('auth.account.twoFactor.scan', 'Scan this code with your authenticator app, or type the key, then type the code it shows.')}
129
+ QrCode(value={setupUri} label={wording('auth.account.twoFactor.qr', 'QR code for your authenticator app')} pixels={192})
130
+ if setupKey
131
+ p
132
+ | {wording('auth.account.twoFactor.key', 'Key')}: #[code#kauth-key {setupKey}]
133
+ form.flex.flex-col.gap-3(action={enable})
134
+ input(type="hidden" name="uri" value={setupUri})
135
+ FormField(label={wording('auth.code', 'Code')} required)
136
+ input(name="code" inputmode="numeric" autocomplete="one-time-code" required)
137
+ Button(type="submit" tone="accent" label={wording('auth.account.twoFactor.enable', 'Turn on')})
138
+ else if features.twoFactor
139
+ form.flex.flex-col.gap-3(action={setUp})
140
+ p {wording('auth.account.twoFactor.intro', 'Ask for a code from an authenticator app at each sign-in.')}
141
+ Proof(user={user})
142
+ Button(type="submit" tone="accent" label={wording('auth.account.twoFactor.setUp', 'Set up two-step verification')})
143
+ if features.passkeys
144
+ PageSection(title={wording('auth.account.passkeys.title', 'Passkeys')})
145
+ .flex.flex-col.gap-3
146
+ p {wording('auth.account.passkeys.intro', 'Sign in with your fingerprint, face or device PIN instead of a password.')}
147
+ for passkey of passkeys key={passkey.id}
148
+ CardRow
149
+ form.flex.flex-wrap.items-end.gap-2(action={renamePasskey})
150
+ input(type="hidden" name="id" value={passkey.id})
151
+ FormField(label={wording('auth.account.passkeys.name', 'Name')})
152
+ input(name="name" value={passkey.name} required)
153
+ Button(type="submit" label={wording('auth.account.passkeys.rename', 'Rename')} aria-label={`${wording('auth.account.passkeys.rename', 'Rename')}: ${passkey.name}`})
154
+ p.text-muted
155
+ | {wording('auth.account.passkeys.created', 'Added {date}', { date: formatDate(passkey.createdAt, { dateStyle: 'medium' }) })}
156
+ form.flex.flex-wrap.items-end.gap-2(action={removePasskey})
157
+ input(type="hidden" name="id" value={passkey.id})
158
+ Proof(user={user})
159
+ if removeRefused?.id === passkey.id
160
+ Message(text={failure(removeRefused.error)})
161
+ Button(type="submit" tone="danger" label={wording('auth.account.passkeys.remove', 'Remove')} aria-label={`${wording('auth.account.passkeys.remove', 'Remove')}: ${passkey.name}`})
162
+ else
163
+ EmptyState(title={wording('auth.account.passkeys.none', 'No passkey yet.')})
164
+ PasskeyAdd(user={{ hasPassword: user.hasPassword, twoFactor: user.twoFactor }} label={wording('auth.account.passkeys.add', 'Add a passkey')} nameLabel={wording('auth.account.passkeys.name', 'Name')} passwordLabel={wording('auth.proof.password', 'Current password')} codeLabel={wording('auth.proof.code', 'Code from your authenticator app')} unsupported={wording('auth.account.passkeys.unsupported', 'This browser cannot make passkeys.')} failed={wording('auth.account.passkeys.failed', 'The passkey was not added.')} errors={passkeyErrors})
@@ -0,0 +1,51 @@
1
+ --- server
2
+ import { action } from 'kay'
3
+ import { formatRelativeTime, localize } from 'kay/i18n'
4
+ import { wording } from 'kay/words'
5
+ import { schemas } from '../../forms'
6
+ import Badge from '@kayjs/ui/badge.kay'
7
+ import Button from '@kayjs/ui/button.kay'
8
+ import CardRow from '@kayjs/ui/card-row.kay'
9
+ import PageSection from '@kayjs/ui/page-section.kay'
10
+
11
+ // Ending this device's own session signs it out, so it leaves the account pages.
12
+ export const end = action(schemas.id, async ({ id }, ctx) => {
13
+ const auth = ctx.locals.auth
14
+ const current = (await auth.sessions.list()).find(session => session.current)?.id === id
15
+
16
+ await auth.sessions.revoke(id)
17
+
18
+ return current ? ctx.redirect(localize(auth.features().pages?.home ?? '/')) : 'ended'
19
+ })
20
+
21
+ export const endOthers = action(async (ctx) => {
22
+ await ctx.locals.auth.signOutEverywhere({ keepThisOne: true })
23
+
24
+ return 'ended'
25
+ })
26
+
27
+ const sessions = await ctx.locals.auth.sessions.list()
28
+ const describe = (session: (typeof sessions)[number]) => [session.device.browser, session.device.os].filter(Boolean).join(', ') || wording('auth.account.sessions.unknown', 'Unknown device')
29
+ ---
30
+ PageSection(title={wording('auth.account.sessions.title', 'Where you are signed in')})
31
+ @actions
32
+ if sessions.length > 1
33
+ form(action={endOthers})
34
+ Button(type="submit" label={wording('auth.account.sessions.endOthers', 'Sign out everywhere else')})
35
+ .flex.flex-col.gap-2
36
+ for session of sessions key={session.id}
37
+ CardRow(data-session={session.id})
38
+ @right
39
+ form(action={end})
40
+ input(type="hidden" name="id" value={session.id})
41
+ Button(type="submit" label={wording('auth.account.sessions.end', 'Sign out')} aria-label={`${wording('auth.account.sessions.end', 'Sign out')}: ${describe(session)}`})
42
+ .flex.flex-col
43
+ span.flex.flex-wrap.items-center.gap-2
44
+ strong {describe(session)}
45
+ if session.device.mobile
46
+ span.text-muted {wording('auth.account.sessions.mobile', 'mobile')}
47
+ if session.current
48
+ Badge(label={wording('auth.account.sessions.current', 'This device')} tone="accent")
49
+ span.text-muted
50
+ | {[session.place, session.ip].filter(Boolean).join(' · ')}
51
+ span.text-muted {wording('auth.account.sessions.lastSeen', 'Last seen {date}', { date: formatRelativeTime(session.lastSeenAt) })}
@@ -0,0 +1,84 @@
1
+ --- server
2
+ import { action } from 'kay'
3
+ import { formatDate } from 'kay/i18n'
4
+ import { wording } from 'kay/words'
5
+ import Message from '../../components/message.kay'
6
+ import Proof from '../../components/proof.kay'
7
+ import { failure, proofOf, schemas, scopeLabel } from '../../forms'
8
+ import Badge from '@kayjs/ui/badge.kay'
9
+ import Button from '@kayjs/ui/button.kay'
10
+ import CardRow from '@kayjs/ui/card-row.kay'
11
+ import CopyButton from '@kayjs/ui/copy-button.kay'
12
+ import EmptyState from '@kayjs/ui/empty-state.kay'
13
+ import FormField from '@kayjs/ui/form-field.kay'
14
+ import PageSection from '@kayjs/ui/page-section.kay'
15
+
16
+ const EXPIRIES = [30, 90, 365]
17
+
18
+ // Left out is the default, 0 is the form's "Never".
19
+ const expiry = (days: number | undefined) => days === undefined ? undefined : days === 0 ? null : `${days}d` as const
20
+
21
+ // The plain token comes back once, for the page to show it this one time.
22
+ export const create = action(schemas.createToken, async (input, ctx) => {
23
+ // The app's scopes are its own type, which this page cannot name: tokens.create refuses any it does not declare.
24
+ const result = await ctx.locals.auth.tokens.create(proofOf(input), input.label, { scopes: input.scopes?.length ? input.scopes as never[] : undefined, maxAge: expiry(input.days) })
25
+
26
+ return result.ok ? result.token : ctx.fail(400, { error: result.error.code })
27
+ })
28
+
29
+ export const revoke = action(schemas.id, async ({ id }, ctx) => {
30
+ return (await ctx.locals.auth.tokens.revoke(id)).ok ? 'revoked' : ctx.fail(404, { error: 'not-found' })
31
+ })
32
+
33
+ const auth = ctx.locals.auth
34
+ const user = await auth.requireUser()
35
+ const features = auth.features()
36
+ const tokens = await auth.tokens.list()
37
+ const created = create.succeeded()?.data
38
+ const refused = create.failed()?.data?.error
39
+ const date = (value: Date) => formatDate(value, { dateStyle: 'medium' })
40
+ ---
41
+ PageSection(title={wording('auth.account.tokens.title', 'Access tokens')})
42
+ .flex.flex-col.gap-2
43
+ p {wording('auth.account.tokens.intro', 'Tokens let scripts and other apps use your account through the API.')}
44
+ if created
45
+ Message(tone="success" text={wording('auth.account.tokens.created', 'Copy this token now: it will not be shown again.')})
46
+ code#kauth-token.break-all {created}
47
+ CopyButton(text={created} label={wording('auth.account.tokens.copy', 'Copy the token')})
48
+ for token of tokens key={token.id}
49
+ CardRow(data-token={token.id})
50
+ @right
51
+ form(action={revoke})
52
+ input(type="hidden" name="id" value={token.id})
53
+ Button(type="submit" tone="danger" label={wording('auth.account.tokens.revoke', 'Revoke')} aria-label={`${wording('auth.account.tokens.revoke', 'Revoke')}: ${token.label}`})
54
+ .flex.flex-col
55
+ span.flex.flex-wrap.items-center.gap-2
56
+ strong {token.label}
57
+ if token.expired
58
+ Badge(label={wording('auth.account.tokens.expired', 'Expired')} tone="warning")
59
+ span.text-muted {token.scopes ? token.scopes.map(scopeLabel).join(', ') : wording('auth.account.tokens.allScopes', 'Everything')}
60
+ span.text-muted
61
+ | {token.lastUsedAt ? wording('auth.account.tokens.lastUsed', 'Last used {date}', { date: date(token.lastUsedAt) }) : wording('auth.account.tokens.neverUsed', 'Never used')}
62
+ if token.expiresAt && !token.expired
63
+ | · {wording('auth.account.tokens.expires', 'Expires {date}', { date: date(token.expiresAt) })}
64
+ else
65
+ EmptyState(title={wording('auth.account.tokens.none', 'No token yet.')})
66
+ PageSection(title={wording('auth.account.tokens.create', 'Create a token')})
67
+ form.flex.flex-col.gap-3(action={create})
68
+ FormField(label={wording('auth.account.tokens.label', 'Name')} required)
69
+ input(name="label" maxlength="100" required)
70
+ if features.scopes.length > 0
71
+ FormField(label={wording('auth.account.tokens.scopes', 'Allowed to')} group)
72
+ for scope of features.scopes key={scope}
73
+ label.flex.items-center.gap-2
74
+ input(type="checkbox" name="scopes" value={scope})
75
+ | {scopeLabel(scope)}
76
+ FormField(label={wording('auth.account.tokens.expiresIn', 'Expires')})
77
+ select(name="days")
78
+ option(value="0") {wording('auth.account.tokens.never', 'Never')}
79
+ for days of EXPIRIES key={days}
80
+ option(value={String(days)} selected={days === 90}) {wording('auth.account.tokens.days', days === 1 ? 'In {count} day' : 'In {count} days', { count: days })}
81
+ Proof(user={user})
82
+ if refused
83
+ Message(text={failure(refused)})
84
+ Button(type="submit" tone="accent" label={wording('auth.account.tokens.create', 'Create a token')})
@@ -0,0 +1,43 @@
1
+ --- server
2
+ import { localize } from 'kay/i18n'
3
+ import { wording } from 'kay/words'
4
+ import Notice from '@kayjs/ui/notice.kay'
5
+ import TabNav from '@kayjs/ui/tab-nav.kay'
6
+ import ImpersonationBanner from '../../../components/impersonation-banner.kay'
7
+ import UserMenu from '../../../components/user-menu.kay'
8
+ import Frame from '../../components/frame.kay'
9
+ import { loadViewer } from '../../../viewer'
10
+
11
+ const features = ctx.locals.auth.features()
12
+ // An admin acting as a user is refused with a 403 too, but sees the way back rather than a bare error.
13
+ const acting = features.admin ? await ctx.locals.auth.impersonator() : null
14
+
15
+ // Only the admin as themselves passes: a visitor is sent to sign in, anyone else gets a 403, and a site naming no admin a 404.
16
+ if (acting)
17
+ ctx.status(403)
18
+ else
19
+ await ctx.locals.auth.requireAdmin()
20
+
21
+ await loadViewer(ctx.request)
22
+
23
+ const current = ctx.url.pathname
24
+ const base = localize(`${features.pages?.prefix ?? features.prefix}/admin`)
25
+ const links = [
26
+ { href: base, label: wording('auth.admin.nav.users', 'Users') },
27
+ ...features.audit ? [{ href: `${base}/audit`, label: wording('auth.admin.nav.audit', 'Audit log') }] : [],
28
+ ]
29
+ const here = links.find(link => link.href.replace(/\/$/, '') === current.replace(/\/$/, ''))
30
+ const title = `${here?.label ?? wording('auth.admin.nav.users', 'Users')} - ${wording('auth.admin.title', 'Administration')}`
31
+ ---
32
+ head
33
+ title {title}
34
+ Frame(size="max-w-4xl" gap="gap-6" landmark={features.pages?.main !== false})
35
+ .flex.flex-wrap.items-center.justify-between.gap-4
36
+ h1.kui-heading-section {wording('auth.admin.title', 'Administration')}
37
+ UserMenu
38
+ if acting
39
+ ImpersonationBanner
40
+ Notice(tone="warning") {wording('auth.admin.acting', 'Go back to your account to use the administration.')}
41
+ else
42
+ TabNav(links={links} current={current} label={wording('auth.admin.nav.label', 'Administration')})
43
+ slot
@@ -0,0 +1,43 @@
1
+ --- server
2
+ import { formatDate, localize } from 'kay/i18n'
3
+ import { wording } from 'kay/words'
4
+ import { describeAuditEntry } from '../../../auditWording'
5
+ import EmptyState from '@kayjs/ui/empty-state.kay'
6
+ import CardRow from '@kayjs/ui/card-row.kay'
7
+ import PageSection from '@kayjs/ui/page-section.kay'
8
+
9
+ const PAGE_SIZE = 50
10
+ const CURSOR_MAX = 2000
11
+
12
+ // The cursor a page links older entries with: the last entry of the page as JSON, which the log reads whatever it holds.
13
+ function cursorOf(value: string | null): unknown {
14
+ if (value === null || value.length > CURSOR_MAX)
15
+ return undefined
16
+
17
+ try {
18
+ return JSON.parse(value)
19
+ }
20
+ catch {
21
+ return undefined
22
+ }
23
+ }
24
+
25
+ const auth = ctx.locals.auth
26
+ const features = auth.features()
27
+ const before = cursorOf(ctx.url.searchParams.get('before'))
28
+ const log = await auth.admin.auditLog({ ...before !== undefined && { before: before as never }, limit: PAGE_SIZE })
29
+ const entries = log.ok ? log.entries : []
30
+ const older = entries.length === PAGE_SIZE ? `${localize(`${features.pages?.prefix ?? features.prefix}/admin/audit`)}?before=${encodeURIComponent(JSON.stringify({ at: entries.at(-1)!.at, id: entries.at(-1)!.id }))}` : undefined
31
+ const dateTime = (value: Date) => formatDate(value, { dateStyle: 'medium', timeStyle: 'short' })
32
+ const locale = ctx.locale
33
+ ---
34
+ PageSection(title={wording('auth.admin.audit.title', 'Audit log')})
35
+ .flex.flex-col.gap-2
36
+ for entry of entries key={entry.id}
37
+ CardRow
38
+ span {describeAuditEntry(entry, { locale })}
39
+ span.text-muted {dateTime(entry.at)}
40
+ else
41
+ EmptyState(title={features.audit ? wording('auth.admin.audit.none', 'No entry.') : wording('auth.admin.audit.off', 'The audit log is off: set the audit option to keep one.')})
42
+ if older
43
+ a(href={older} rel="next") {wording('auth.admin.audit.older', 'Older entries')}
@@ -0,0 +1,60 @@
1
+ --- server
2
+ import { formatDate, localize } from 'kay/i18n'
3
+ import { wording } from 'kay/words'
4
+ import Badge from '@kayjs/ui/badge.kay'
5
+ import Button from '@kayjs/ui/button.kay'
6
+ import CardRow from '@kayjs/ui/card-row.kay'
7
+ import EmptyState from '@kayjs/ui/empty-state.kay'
8
+ import FormField from '@kayjs/ui/form-field.kay'
9
+ import Pagination from '@kayjs/ui/pagination.kay'
10
+ import PageSection from '@kayjs/ui/page-section.kay'
11
+
12
+ const PAGE_SIZE = 25
13
+ const PAGE_MAX = 100_000
14
+ const SEARCH_MAX = 100
15
+
16
+ // A page number from the query: anything but a whole number from 1 is the first page, and one past the ends is the last.
17
+ function pageOf(value: string | null): number {
18
+ const page = Number(value)
19
+
20
+ return Number.isInteger(page) && page >= 1 ? Math.min(page, PAGE_MAX) : 1
21
+ }
22
+
23
+ const auth = ctx.locals.auth
24
+ const features = auth.features()
25
+ const search = (ctx.url.searchParams.get('q') ?? '').trim().slice(0, SEARCH_MAX)
26
+ const requested = pageOf(ctx.url.searchParams.get('page'))
27
+ const first = await auth.admin.listUsers({ search, offset: (requested - 1) * PAGE_SIZE, limit: PAGE_SIZE })
28
+ const total = first.ok ? first.total : 0
29
+ const pages = Math.max(1, Math.ceil(total / PAGE_SIZE))
30
+ const shown = Math.min(requested, pages)
31
+ // A page past the end shows the last one.
32
+ const found = shown === requested ? first : await auth.admin.listUsers({ search, offset: (shown - 1) * PAGE_SIZE, limit: PAGE_SIZE })
33
+ const users = found.ok ? found.users : []
34
+ const base = localize(`${features.pages?.prefix ?? features.prefix}/admin`)
35
+ const date = (value: Date) => formatDate(value, { dateStyle: 'medium' })
36
+ const url = ctx.url
37
+ ---
38
+ PageSection(title={wording('auth.admin.nav.users', 'Users')})
39
+ form.flex.flex-wrap.items-end.gap-3(method="get" action={base} role="search")
40
+ FormField(label={wording('auth.admin.users.searchLabel', 'Email, username or id')})
41
+ input(type="search" name="q" value={search} maxlength={String(SEARCH_MAX)})
42
+ Button(type="submit" label={wording('auth.admin.users.search', 'Search')})
43
+ p.text-muted {wording('auth.admin.users.total', total === 1 ? '{count} user' : '{count} users', { count: total })}
44
+ .flex.flex-col.gap-2
45
+ for user of users key={user.id}
46
+ CardRow(data-user={user.id})
47
+ .flex.flex-col
48
+ span.flex.flex-wrap.items-center.gap-2
49
+ a(href={`${base}/users/${encodeURIComponent(user.id)}`}) {user.username ?? user.email ?? wording('auth.admin.users.noName', 'No address')}
50
+ if user.ban
51
+ Badge(label={wording('auth.admin.users.banned', 'Suspended')} tone="danger")
52
+ if user.guest
53
+ Badge(label={wording('auth.admin.users.guest', 'Guest')})
54
+ for role of user.roles key={role}
55
+ Badge(label={role} tone="accent")
56
+ span.text-muted
57
+ | {[user.username ? user.email : undefined, wording('auth.admin.users.joined', 'Joined {date}', { date: date(user.createdAt) })].filter(Boolean).join(' · ')}
58
+ else
59
+ EmptyState(title={wording('auth.admin.users.none', 'No user found.')})
60
+ Pagination(page={shown} pages={pages} url={url} label={wording('auth.admin.users.pagination', 'User pages')})
@@ -0,0 +1,181 @@
1
+ --- server
2
+ import { action } from 'kay'
3
+ import { formatDate, localize } from 'kay/i18n'
4
+ import { wording } from 'kay/words'
5
+ import { describeAuditEntry } from '../../../../auditWording'
6
+ import Message from '../../../components/message.kay'
7
+ import { failure, schemas } from '../../../forms'
8
+ import Badge from '@kayjs/ui/badge.kay'
9
+ import Button from '@kayjs/ui/button.kay'
10
+ import CardRow from '@kayjs/ui/card-row.kay'
11
+ import FormField from '@kayjs/ui/form-field.kay'
12
+ import PageSection from '@kayjs/ui/page-section.kay'
13
+
14
+ const ISO_DAY = /^\d{4}-\d{2}-\d{2}$/
15
+
16
+ // The ban ends at the close of the day the form names; no date is for good, and one that is no date or already past is `until`.
17
+ function endOf(day: string | undefined): Date | null | 'until' {
18
+ if (day === undefined || day === '')
19
+ return null
20
+
21
+ const end = ISO_DAY.test(day) ? new Date(`${day}T23:59:59Z`) : new Date(Number.NaN)
22
+
23
+ return Number.isNaN(end.getTime()) || end.getTime() <= Date.now() ? 'until' : end
24
+ }
25
+
26
+ // Every action answers about the user the route names, never one the input names.
27
+ export const grant = action(schemas.adminRole, async ({ role }, ctx) => {
28
+ const result = await ctx.locals.auth.admin.grantRole(String(ctx.params.id), role as never)
29
+
30
+ return result.ok ? 'done' : ctx.fail(400, { error: result.error.code })
31
+ })
32
+
33
+ export const revoke = action(schemas.adminRole, async ({ role }, ctx) => {
34
+ const result = await ctx.locals.auth.admin.revokeRole(String(ctx.params.id), role as never)
35
+
36
+ return result.ok ? 'done' : ctx.fail(400, { error: result.error.code })
37
+ })
38
+
39
+ export const ban = action(schemas.adminBan, async ({ reason, until }, ctx) => {
40
+ const end = endOf(until)
41
+
42
+ if (end === 'until')
43
+ return ctx.fail(400, { error: 'until' })
44
+
45
+ const result = await ctx.locals.auth.admin.ban(String(ctx.params.id), { ...reason?.trim() && { reason: reason.trim() }, ...end && { until: end } })
46
+
47
+ return result.ok ? 'done' : ctx.fail(400, { error: result.error.code })
48
+ })
49
+
50
+ export const unban = action(async (ctx) => {
51
+ const result = await ctx.locals.auth.admin.unban(String(ctx.params.id))
52
+
53
+ return result.ok ? 'done' : ctx.fail(400, { error: result.error.code })
54
+ })
55
+
56
+ export const remove = action(schemas.adminDelete, async ({ confirm }, ctx) => {
57
+ if (confirm !== true)
58
+ return ctx.fail(400, { error: 'form' })
59
+
60
+ const result = await ctx.locals.auth.admin.deleteUser(String(ctx.params.id))
61
+
62
+ if (!result.ok)
63
+ return ctx.fail(400, { error: result.error.code })
64
+
65
+ const { pages, prefix } = ctx.locals.auth.features()
66
+
67
+ return ctx.redirect(localize(`${pages?.prefix ?? prefix}/admin`))
68
+ })
69
+
70
+ export const impersonate = action(async (ctx) => {
71
+ const result = await ctx.locals.auth.admin.impersonate(String(ctx.params.id))
72
+
73
+ return result.ok ? ctx.redirect(localize(ctx.locals.auth.features().pages?.home ?? '/')) : ctx.fail(400, { error: result.error.code })
74
+ })
75
+
76
+ // An admin who signed in long ago signs in again and comes back to this user.
77
+ export const signInAgain = action(async (ctx) => {
78
+ const { signInPage, pages, prefix } = ctx.locals.auth.features()
79
+ const signIn = localize(signInPage)
80
+
81
+ await ctx.locals.auth.signOut()
82
+
83
+ return ctx.redirect(`${signIn}${signIn.includes('?') ? '&' : '?'}redirect=${encodeURIComponent(localize(`${pages?.prefix ?? prefix}/admin/users/${encodeURIComponent(String(ctx.params.id))}`))}`)
84
+ })
85
+
86
+ const auth = ctx.locals.auth
87
+ const features = auth.features()
88
+ const found = await auth.admin.getUser(String(ctx.params.id))
89
+
90
+ // Only an admin acting as a user is refused, and the admin index shows them the way back.
91
+ if (!found.ok) {
92
+ if (found.error.code === 'not-found')
93
+ ctx.notFound()
94
+
95
+ ctx.redirect(localize(`${features.pages?.prefix ?? features.prefix}/admin`))
96
+ }
97
+
98
+ const user = found.user
99
+ const me = await auth.user()
100
+ const own = me?.id === user.id
101
+ const base = localize(`${features.pages?.prefix ?? features.prefix}/admin`)
102
+ const declared = auth.admin.roles()
103
+ const grantable = declared.filter(role => !user.roles.includes(role))
104
+ const log = await auth.admin.auditLog({ userId: user.id, limit: 20 })
105
+ const entries = log.ok ? log.entries : []
106
+ const refused = [grant, revoke, ban, unban, remove, impersonate].map(form => form.failed()?.data?.error).find(error => error !== undefined)
107
+ const date = (value: Date) => formatDate(value, { dateStyle: 'medium' })
108
+ const dateTime = (value: Date) => formatDate(value, { dateStyle: 'medium', timeStyle: 'short' })
109
+ const locale = ctx.locale
110
+ ---
111
+ head
112
+ title {`${user.username ?? user.email ?? user.id} - ${wording('auth.admin.title', 'Administration')}`}
113
+ PageSection(title={user.username ?? user.email ?? user.id})
114
+ @actions
115
+ a(href={base}) {wording('auth.admin.user.back', 'All users')}
116
+ .flex.flex-col.gap-2
117
+ if user.email
118
+ span {user.email}
119
+ span.flex.flex-wrap.items-center.gap-2
120
+ for role of user.roles key={role}
121
+ Badge(label={role} tone="accent")
122
+ if user.roles.length === 0
123
+ span.text-muted {wording('auth.admin.user.noRoles', 'No role.')}
124
+ if user.guest
125
+ Badge(label={wording('auth.admin.users.guest', 'Guest')})
126
+ span.text-muted {wording('auth.admin.users.joined', 'Joined {date}', { date: date(user.createdAt) })}
127
+ if refused
128
+ Message(text={failure(refused)})
129
+ if refused === 'stale'
130
+ form(action={signInAgain})
131
+ Button(type="submit" label={wording('auth.admin.user.signInAgain', 'Sign in again')})
132
+ PageSection(title={wording('auth.admin.user.roles', 'Roles')})
133
+ .flex.flex-col.gap-2
134
+ for role of user.roles key={role}
135
+ CardRow(data-role={role})
136
+ @right
137
+ form(action={revoke})
138
+ input(type="hidden" name="role" value={role})
139
+ Button(type="submit" tone="danger" label={wording('auth.admin.user.revoke', 'Take back')} aria-label={`${wording('auth.admin.user.revoke', 'Take back')}: ${role}`})
140
+ strong {role}
141
+ if grantable.length > 0
142
+ form.flex.flex-wrap.items-end.gap-3(action={grant})
143
+ FormField(label={wording('auth.admin.user.grantRole', 'Role')})
144
+ select(name="role")
145
+ for role of grantable key={role}
146
+ option(value={role}) {role}
147
+ Button(type="submit" label={wording('auth.admin.user.grant', 'Give the role')})
148
+ // An admin is neither banned, acted as nor deleted from here, as the methods refuse it; a ban set before the role came stays liftable.
149
+ if !own && (!found.admin || user.ban)
150
+ PageSection(title={wording('auth.admin.user.ban', 'Suspend the account')})
151
+ if user.ban
152
+ p {user.ban.until ? wording('auth.admin.user.bannedUntil', 'Suspended until {date}.', { date: date(user.ban.until) }) : wording('auth.admin.user.banned', 'Suspended since {date}.', { date: date(user.ban.bannedAt) })}
153
+ if user.ban.reason
154
+ p.text-muted {user.ban.reason}
155
+ form(action={unban})
156
+ Button(type="submit" label={wording('auth.admin.user.unban', 'Lift the suspension')})
157
+ else if !found.admin
158
+ form.flex.flex-col.gap-3(action={ban})
159
+ FormField(label={wording('auth.admin.user.banReason', 'Reason')})
160
+ input(name="reason" maxlength="500")
161
+ FormField(label={wording('auth.admin.user.banUntil', 'Until')} hint={wording('auth.admin.user.banUntilHint', 'The suspension ends at the close of that day, UTC. Leave empty to suspend for good.')})
162
+ input(type="date" name="until")
163
+ Button(type="submit" tone="danger" label={wording('auth.admin.user.ban', 'Suspend the account')})
164
+ if !found.admin
165
+ PageSection(title={wording('auth.admin.user.impersonate', 'Act as this user')})
166
+ form(action={impersonate})
167
+ Button(type="submit" label={wording('auth.admin.user.impersonate', 'Act as this user')})
168
+ PageSection(title={wording('auth.admin.user.delete', 'Delete the account')})
169
+ form.flex.flex-col.gap-3(action={remove})
170
+ p {wording('auth.admin.user.deleteIntro', 'The account and everything tied to it are deleted for good. This cannot be undone.')}
171
+ label.flex.items-center.gap-2
172
+ input(type="checkbox" name="confirm" required)
173
+ | {wording('auth.admin.user.deleteConfirm', 'I understand')}
174
+ Button(type="submit" tone="danger" label={wording('auth.admin.user.delete', 'Delete the account')})
175
+ if entries.length > 0
176
+ PageSection(title={wording('auth.admin.user.activity', 'Recent activity')})
177
+ .flex.flex-col.gap-2
178
+ for entry of entries key={entry.id}
179
+ CardRow
180
+ span {describeAuditEntry(entry, { locale })}
181
+ span.text-muted {dateTime(entry.at)}