@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,217 @@
1
+ // `kay auth create-user`: makes a user from the terminal, asking the password without echo, for a site with `signUp: false` whose first user has no page to register on.
2
+ import type { KayCommand } from 'kay/library'
3
+ import type { UserMaker } from './pages'
4
+ import process from 'node:process'
5
+ import { setSite, siteWithBase } from 'kay/library'
6
+ import { CHECK_USER, LOAD_AUTH } from './pages'
7
+
8
+ const END_OF_INPUT = '\u0004'
9
+ const INTERRUPT = '\u0003'
10
+ const BACKSPACE = new Set(['\u007F', '\b'])
11
+ // eslint-disable-next-line no-control-regex
12
+ const ESCAPE_SEQUENCE = /\u001B(?:\[[0-9;]*[A-Za-z~]|O[A-Za-z])?/g
13
+ const LINE_END = new Set(['\r', '\n'])
14
+
15
+ // What a terminal in raw mode typed so far after `chunk`: backspace erases, Enter or Ctrl+D finishes, Ctrl+C cancels, and no other control character is kept.
16
+ export function typedSecret(value: string, chunk: string): { value: string, end?: 'done' | 'cancelled' } {
17
+ let typed = value
18
+
19
+ // An arrow or function key sends an escape sequence, which is no part of a password.
20
+ for (const char of chunk.replaceAll(ESCAPE_SEQUENCE, '')) {
21
+ if (LINE_END.has(char) || char === END_OF_INPUT)
22
+ return { value: typed, end: 'done' }
23
+
24
+ if (char === INTERRUPT)
25
+ return { value: typed, end: 'cancelled' }
26
+
27
+ if (BACKSPACE.has(char))
28
+ typed = [...typed].slice(0, -1).join('')
29
+ else if (char >= ' ')
30
+ typed += char
31
+ }
32
+
33
+ return { value: typed }
34
+ }
35
+
36
+ // One line typed without an echo, the label written on stderr so a piped stdout stays clean. Cancelled with Ctrl+C, or when the input ends, closes or fails (a terminal that went away reads as an EIO error): undefined. The terminal is restored on SIGTERM too, which raw mode would otherwise leave typing without an echo.
37
+ export async function readFromTerminal(label: string): Promise<string | undefined> {
38
+ const { stdin } = process
39
+ const restore = () => {
40
+ // A terminal that went away refuses to leave raw mode.
41
+ try {
42
+ stdin.setRawMode(false)
43
+ }
44
+ catch {}
45
+
46
+ stdin.pause()
47
+ process.stderr.write('\n')
48
+ }
49
+ const onTerminate = () => {
50
+ restore()
51
+ process.exit(143)
52
+ }
53
+
54
+ // Taken before the prompt shows, so a termination once it is asked puts the terminal back.
55
+ process.once('SIGTERM', onTerminate)
56
+ process.stderr.write(label)
57
+
58
+ // A terminal that went away before the first read refuses raw mode.
59
+ try {
60
+ stdin.setRawMode(true)
61
+ }
62
+ catch {
63
+ process.off('SIGTERM', onTerminate)
64
+ process.stderr.write('\n')
65
+
66
+ return undefined
67
+ }
68
+
69
+ stdin.setEncoding('utf8')
70
+ stdin.resume()
71
+
72
+ let finish: (typed: string | undefined) => void = () => undefined
73
+ let value = ''
74
+ const onData = (chunk: string) => {
75
+ const typed = typedSecret(value, chunk)
76
+
77
+ value = typed.value
78
+
79
+ if (typed.end !== undefined)
80
+ finish(typed.end === 'done' ? value : undefined)
81
+ }
82
+ const onEnd = () => finish(undefined)
83
+
84
+ try {
85
+ return await new Promise<string | undefined>((resolve) => {
86
+ finish = resolve
87
+ stdin.on('data', onData)
88
+ stdin.once('end', onEnd)
89
+ stdin.once('close', onEnd)
90
+ stdin.once('error', onEnd)
91
+ })
92
+ }
93
+ finally {
94
+ stdin.off('data', onData)
95
+ stdin.off('end', onEnd)
96
+ stdin.off('close', onEnd)
97
+ stdin.off('error', onEnd)
98
+ process.off('SIGTERM', onTerminate)
99
+ restore()
100
+ }
101
+ }
102
+
103
+ // The first line of a piped stdin, as `echo "$PASSWORD" | kay auth create-user ada`.
104
+ async function readFromPipe(): Promise<string> {
105
+ const [line = ''] = (await Bun.stdin.text()).split('\n')
106
+
107
+ return line.endsWith('\r') ? line.slice(0, -1) : line
108
+ }
109
+
110
+ // Asks for the password twice on a terminal, as a typo nobody sees would lock the user out, or reads one line of a pipe. Undefined when cancelled or the two differ.
111
+ export async function readPassword(): Promise<string | undefined> {
112
+ if (!process.stdin.isTTY)
113
+ return readFromPipe()
114
+
115
+ const first = await readFromTerminal('Password: ')
116
+
117
+ if (first === undefined)
118
+ return undefined
119
+
120
+ const second = await readFromTerminal('Again: ')
121
+
122
+ if (second !== first && second !== undefined)
123
+ console.error('kay auth create-user: the two passwords differ')
124
+
125
+ return second === first ? first : undefined
126
+ }
127
+
128
+ export function createUserCommand(ask: () => Promise<string | undefined>): KayCommand {
129
+ return {
130
+ usage: 'auth create-user <email or username> [--email <address>] [--username <name>] [--role <role>]... [--no-password]',
131
+ options: {
132
+ 'email': { type: 'string' },
133
+ 'username': { type: 'string' },
134
+ 'role': { type: 'string', multiple: true },
135
+ 'no-password': { type: 'boolean' },
136
+ },
137
+ positionals: 1,
138
+ run: async ({ values, positionals: [login] }, refuse, { config, root, fail, format, quiet, dryRun, result }) => {
139
+ if (login === undefined || login === '')
140
+ return refuse('auth create-user needs the email or the username to sign in with')
141
+
142
+ const isEmail = login.normalize('NFKC').includes('@')
143
+
144
+ if (isEmail && values.email !== undefined)
145
+ return refuse('auth create-user was given two emails: the one to sign in with, and --email')
146
+
147
+ if (!isEmail && values.username !== undefined)
148
+ return refuse('auth create-user was given two usernames: the one to sign in with, and --username')
149
+
150
+ const loader = (config.extensions ?? []).map(extension => (extension as { [LOAD_AUTH]?: (root: string, extensions: string[], database?: string, dryRun?: boolean) => Promise<UserMaker> })[LOAD_AUTH]).find(load => load !== undefined)
151
+
152
+ if (loader === undefined)
153
+ return fail('kay.config.ts lists no auth() to find the app\'s auth through')
154
+
155
+ const email = isEmail ? login : values.email as string | undefined
156
+ const username = isEmail ? values.username as string | undefined : login
157
+ const roles = values.role as string[] | undefined
158
+
159
+ // The site the app's auth reads while it loads, as the server sets it before it does.
160
+ // A site or base the server refuses is refused here too, through the same reading.
161
+ try {
162
+ const site = siteWithBase(config.site, config.base)
163
+
164
+ if (site !== undefined)
165
+ setSite(site, config.trailingSlash)
166
+ }
167
+ catch (error) {
168
+ return fail(error instanceof Error ? error.message : String(error))
169
+ }
170
+
171
+ try {
172
+ // The app's auth loads, and the login is checked, before a password is asked twice for a user that cannot be made.
173
+ const auth = await loader(root, (config.extensions ?? []).map(extension => extension.name), config.store?.database, dryRun)
174
+ const problems = await auth[CHECK_USER]({ ...email !== undefined && { email }, ...username !== undefined && { username }, ...roles && { roles } })
175
+
176
+ if (Object.keys(problems).length > 0)
177
+ return fail(`refused: ${Object.entries(problems).map(([field, code]) => `${field} ${code}`).join(', ')}`)
178
+
179
+ // With --dry-run auth() loads over an empty in-memory store, so no database is created: the login is checked for its form and roles, not for being taken, and no password is asked.
180
+ if (dryRun) {
181
+ result({ dryRun: true, email, username, roles: roles ?? [] })
182
+
183
+ if (!quiet && format === 'text')
184
+ console.log(`Would create ${username ?? email}${roles && roles.length > 0 ? ` (${roles.join(', ')})` : ''}.`)
185
+
186
+ return 0
187
+ }
188
+
189
+ const password = values['no-password'] === true ? undefined : await ask()
190
+
191
+ if (password === undefined && values['no-password'] !== true)
192
+ return 1
193
+
194
+ if (password === '')
195
+ return fail('no password given; pass --no-password for a user who signs in another way')
196
+
197
+ // An address the operator types is vouched for: the user cannot receive a verification mail before they can sign in.
198
+ const created = await auth.admin.createUser({ ...email !== undefined && { email, emailVerified: true }, ...username !== undefined && { username }, ...password !== undefined && { password }, ...roles && { roles } })
199
+
200
+ if (!created.ok)
201
+ return fail(`refused: ${Object.entries(created.errors).map(([field, code]) => `${field} ${code}`).join(', ')}`)
202
+
203
+ result({ id: created.user.id, email: created.user.email, username: created.user.username, roles: created.user.roles })
204
+
205
+ if (!quiet && format === 'text')
206
+ console.log(`Created ${created.user.username ?? created.user.email ?? created.user.id}${created.user.roles.length > 0 ? ` (${created.user.roles.join(', ')})` : ''}.`)
207
+
208
+ return 0
209
+ }
210
+ catch (error) {
211
+ return fail(error instanceof Error ? error.message : String(error), null)
212
+ }
213
+ },
214
+ }
215
+ }
216
+
217
+ export default createUserCommand(readPassword)
package/src/decide.ts ADDED
@@ -0,0 +1,45 @@
1
+ import type { Level, PolicyContext, Principal, Requirement } from './types'
2
+ import { meetsRequirement } from './requirement'
3
+
4
+ /** Injected grant lookups the decision needs. No built-in super-user: model it as a role (`hasRole('ROLE_SUPER_ADMIN')`). */
5
+ export interface GrantStore<P, G extends string> {
6
+ /** Whether the principal currently holds a live credential (e.g. a valid OAuth token). */
7
+ hasCredential: (principal: P) => boolean
8
+ /** The key a grant is looked up by (e.g. a Discord id). */
9
+ subjectId: (principal: P) => string
10
+ getPermission: (subjectId: string, type: G, resourceId?: number | null) => Promise<Level | null>
11
+ }
12
+
13
+ /** App-wide authorization decision: requires a live credential, then evaluates the requirement against the grant store. */
14
+ export async function decide<P, G extends string>(
15
+ store: GrantStore<P, G>,
16
+ principal: Principal<P>,
17
+ requirement: Requirement<P, G>,
18
+ level: Level,
19
+ ctx: PolicyContext = {},
20
+ ): Promise<boolean> {
21
+ if (principal == null || !store.hasCredential(principal))
22
+ return false
23
+
24
+ return evaluate(store, principal, requirement, level, ctx)
25
+ }
26
+
27
+ async function evaluate<P, G extends string>(
28
+ store: GrantStore<P, G>,
29
+ principal: P,
30
+ requirement: Requirement<P, G>,
31
+ level: Level,
32
+ ctx: PolicyContext,
33
+ ): Promise<boolean> {
34
+ return meetsRequirement(principal, requirement, ctx, async (grant) => {
35
+ const type = typeof grant === 'string' ? grant : grant.type
36
+ const resourceId = typeof grant === 'string' ? undefined : grant.resourceId
37
+
38
+ const permission = await store.getPermission(store.subjectId(principal), type, resourceId)
39
+
40
+ if (!permission)
41
+ return false
42
+
43
+ return level === 'read' || permission === 'write'
44
+ })
45
+ }
@@ -0,0 +1,80 @@
1
+ import type { Duration } from 'kay'
2
+ import type { Core } from './core'
3
+ import type { AuthFailed } from './failure'
4
+ import type { RequestState } from './state'
5
+ import type { UserRecord } from './store'
6
+ import { report } from './events'
7
+ import { failed } from './failure'
8
+ import { sendAside, writing } from './mail'
9
+ import { pagePaths } from './pages'
10
+ import { securityNotice } from './securityNotice'
11
+
12
+ export interface AccountOptions {
13
+ // How long `account.delete` leaves an account pending before it is deleted: a string such as '14d'. The user can cancel until then, and `beforeDelete`, the audit log and the account-deleted mail follow the deletion itself. Left out, the deletion is immediate.
14
+ deleteAfter?: Duration | undefined
15
+ // The page the mailed link to cancel opens, which cancels through `account.cancelDeletion()`: the prebuilt account data page by default.
16
+ cancelPage?: string | undefined
17
+ }
18
+
19
+ export type CancelDeletionResult = { ok: true } | AuthFailed<'signed-out' | 'not-pending'>
20
+
21
+ // Where the mailed link leads: the app's own page, else the prebuilt account data page.
22
+ function cancelPageOf(core: Core): string {
23
+ return core.deletion?.cancelPage ?? pagePaths(core.pages?.prefix ?? core.prefix).data
24
+ }
25
+
26
+ // Marks the user pending deletion until the grace period ends and mails them the way to cancel; an account pending already keeps its first deadline.
27
+ export async function scheduleDeletion(state: RequestState, record: UserRecord): Promise<{ ok: true, deleteAt: Date }> {
28
+ const { core } = state
29
+
30
+ if (record.deleteAt != null)
31
+ return { ok: true, deleteAt: record.deleteAt }
32
+
33
+ const deleteAt = new Date(Date.now() + core.deletion!.after * 1000)
34
+
35
+ // Only the request that sets the mark mails and reports: of two together, the other keeps the first deadline.
36
+ if (!await core.store.users.markForDeletion!(record.id, deleteAt))
37
+ return { ok: true, deleteAt: (await core.store.users.get(record.id))?.deleteAt ?? deleteAt }
38
+
39
+ const updated = await core.store.users.get(record.id) ?? { ...record, deleteAt }
40
+
41
+ state.adopt(updated)
42
+ await report(state, updated, 'account-deletion-scheduled', deleteAt.toISOString())
43
+ mailCancelLink(state, updated, deleteAt)
44
+
45
+ return { ok: true, deleteAt }
46
+ }
47
+
48
+ // The mail half, to a verified address only and off the request's path.
49
+ function mailCancelLink(state: RequestState, record: UserRecord, deleteAt: Date): void {
50
+ const { core } = state
51
+ const mail = core.email
52
+ const to = record.emailVerifiedAt === null ? null : record.email
53
+
54
+ if (!mail || to === null)
55
+ return
56
+
57
+ const { locale, templates } = writing(mail, [record.locale, ...state.languages])
58
+ const url = `${core.url}${cancelPageOf(core)}`
59
+ const detail = new Intl.DateTimeFormat(locale, { dateStyle: 'long' }).format(deleteAt)
60
+
61
+ sendAside(mail, () => ({ to, kind: 'cancel-deletion', name: core.name, locale, url, detail, ...templates['cancel-deletion']({ name: core.name, email: to, url, detail, locale }) }), 'cancel-deletion')
62
+ }
63
+
64
+ // Takes the pending mark off the signed-in user, and tells them.
65
+ export async function cancelDeletion(state: RequestState): Promise<CancelDeletionResult> {
66
+ const record = await state.current()
67
+
68
+ if (!record)
69
+ return failed('signed-out')
70
+
71
+ if (record.deleteAt == null)
72
+ return failed('not-pending')
73
+
74
+ const updated = await state.core.store.users.update(record.id, { deleteAt: null }) ?? { ...record, deleteAt: null }
75
+
76
+ state.adopt(updated)
77
+ await securityNotice(state, updated, 'account-deletion-cancelled')
78
+
79
+ return { ok: true }
80
+ }
package/src/devTool.ts ADDED
@@ -0,0 +1,104 @@
1
+ import type { DevTool } from 'kay/dev-tool'
2
+
3
+ // The dev tool's Auth tab, a browser module kay loads on dev pages: who the session is, with a sign-out.
4
+ const SESSION_URL = '/_kay/auth'
5
+
6
+ interface DevSession {
7
+ user: { id: string, email: string | null, emailVerified: boolean, username: string | null, roles: string[], hasPassword: boolean, twoFactor: boolean, locale: string | null, guest: boolean } | null
8
+ via: 'session' | 'bearer' | null
9
+ signOut: string
10
+ }
11
+
12
+ function base(): string {
13
+ return document.querySelector<HTMLMetaElement>('meta[name=kay-base]')?.content ?? ''
14
+ }
15
+
16
+ export default function authDevTool(tool: DevTool): void {
17
+ let asked = 0
18
+ const tab = tool.tab({ id: 'auth', label: 'Auth', icon: 'user-round', shown: () => void show() })
19
+ const empty = (text: string) => {
20
+ tab.count(0)
21
+ tab.panel.replaceChildren(tool.make('div', 'empty', text))
22
+ }
23
+
24
+ async function show(): Promise<void> {
25
+ const ask = ++asked
26
+ let session: DevSession
27
+
28
+ try {
29
+ const response = await fetch(SESSION_URL, { cache: 'no-store' })
30
+
31
+ if (response.status === 404) {
32
+ if (ask === asked)
33
+ empty('kayjs-auth answers here under `kay dev` alone.')
34
+
35
+ return
36
+ }
37
+
38
+ if (!response.ok)
39
+ throw new Error(`the server answered ${response.status}`)
40
+
41
+ session = await response.json() as DevSession
42
+ }
43
+ catch (error) {
44
+ if (ask === asked)
45
+ empty(`Could not read the session: ${error instanceof Error ? error.message : String(error)}`)
46
+
47
+ return
48
+ }
49
+
50
+ if (ask !== asked)
51
+ return
52
+
53
+ const { user } = session
54
+
55
+ tab.count(user === null ? 0 : 1)
56
+
57
+ if (user === null) {
58
+ empty('Nobody is signed in.')
59
+
60
+ return
61
+ }
62
+
63
+ const facts = tool.make('dl', 'facts')
64
+ const rows: [string, string][] = [
65
+ ['User', user.id],
66
+ ['Email', user.email === null ? 'none' : `${user.email}${user.emailVerified ? '' : ' (not verified)'}`],
67
+ ['Username', user.username ?? 'none'],
68
+ ['Roles', user.roles.length === 0 ? 'none' : user.roles.join(', ')],
69
+ ['Signed in by', session.via ?? 'nothing'],
70
+ ['Password', user.hasPassword ? 'set' : 'none'],
71
+ ['Two-factor', user.twoFactor ? 'on' : 'off'],
72
+ ['Locale', user.locale ?? 'none'],
73
+ ['Guest', user.guest ? 'yes' : 'no'],
74
+ ]
75
+
76
+ for (const [name, value] of rows)
77
+ facts.append(tool.make('dt', '', name), tool.make('dd', 'mono', value))
78
+
79
+ const out = tool.make('button', 'tool', 'Sign out')
80
+ const actions = tool.make('div', 'actions')
81
+ const leave = async () => {
82
+ out.disabled = true
83
+
84
+ try {
85
+ // The route answers with a redirect, which the page reloads past.
86
+ const response = await fetch(`${base()}${session.signOut}`, { method: 'POST', redirect: 'manual' })
87
+
88
+ if (!response.ok && response.type !== 'opaqueredirect')
89
+ throw new Error(`the server answered ${response.status}`)
90
+
91
+ location.reload()
92
+ }
93
+ catch (error) {
94
+ out.disabled = false
95
+ actions.append(tool.make('span', 'error', `Could not sign out: ${error instanceof Error ? error.message : String(error)}`))
96
+ }
97
+ }
98
+
99
+ out.type = 'button'
100
+ out.addEventListener('click', () => void leave())
101
+ actions.append(out)
102
+ tab.panel.replaceChildren(actions, facts)
103
+ }
104
+ }
package/src/device.ts ADDED
@@ -0,0 +1,37 @@
1
+ // A user agent read as a person would name it, for a list of where they are signed in: `Firefox on Windows`.
2
+ export interface Device {
3
+ browser: string | null
4
+ os: string | null
5
+ mobile: boolean
6
+ }
7
+
8
+ // Checked in order: Edge, Opera and Samsung's browser all say Chrome too, and Chrome says Safari.
9
+ const BROWSERS: [RegExp, string][] = [
10
+ [/\bEdg(?:e|A|iOS)?\//, 'Edge'],
11
+ [/\b(?:OPR|Opera)\//, 'Opera'],
12
+ [/\bSamsungBrowser\//, 'Samsung Internet'],
13
+ [/\bVivaldi\//, 'Vivaldi'],
14
+ [/\b(?:Firefox|FxiOS)\//, 'Firefox'],
15
+ [/\b(?:Chrome|CriOS|Chromium)\//, 'Chrome'],
16
+ [/\bVersion\/[\d.].*Safari\//, 'Safari'],
17
+ ]
18
+
19
+ const SYSTEMS: [RegExp, string][] = [
20
+ [/\biPad\b/, 'iPadOS'],
21
+ [/\b(?:iPhone|iPod)\b/, 'iOS'],
22
+ [/\bAndroid\b/, 'Android'],
23
+ [/\bCrOS\b/, 'ChromeOS'],
24
+ [/\bWindows\b/, 'Windows'],
25
+ [/\bMac OS X\b|\bMacintosh\b/, 'macOS'],
26
+ [/\bLinux\b/, 'Linux'],
27
+ ]
28
+
29
+ const MOBILE = /\bMobi|\biPhone\b|\biPad\b|\bAndroid\b/
30
+
31
+ export function readDevice(userAgent: string): Device {
32
+ return {
33
+ browser: BROWSERS.find(([pattern]) => pattern.test(userAgent))?.[1] ?? null,
34
+ os: SYSTEMS.find(([pattern]) => pattern.test(userAgent))?.[1] ?? null,
35
+ mobile: MOBILE.test(userAgent),
36
+ }
37
+ }