@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.
- package/LICENSE +21 -0
- package/README.md +78 -2
- package/llms/admin-and-organizations.md +70 -0
- package/llms/admin-pages.md +30 -0
- package/llms/grouped-methods.md +106 -0
- package/llms/hardening-and-testing.md +108 -0
- package/llms/oauth-passkeys-two-factor.md +111 -0
- package/llms/oauth-providers.md +28 -0
- package/llms/oauth-server-and-tokens.md +76 -0
- package/llms/organization-pages.md +20 -0
- package/llms/passwords-and-mails.md +129 -0
- package/llms/sessions-and-guards.md +51 -0
- package/llms/setup.md +122 -0
- package/llms/signed-in-components.md +59 -0
- package/llms.txt +28 -0
- package/package.json +85 -4
- package/src/access.ts +31 -0
- package/src/account.ts +198 -0
- package/src/add.ts +70 -0
- package/src/address.ts +51 -0
- package/src/admin.ts +361 -0
- package/src/auditWording.ts +153 -0
- package/src/auth.ts +219 -0
- package/src/authorize/clients.ts +160 -0
- package/src/authorize/grants.ts +44 -0
- package/src/authorize/metadata.ts +72 -0
- package/src/authorize/register.ts +38 -0
- package/src/authorize/reply.ts +9 -0
- package/src/authorize/request.ts +253 -0
- package/src/authorize/resource.ts +34 -0
- package/src/authorize/revoke.ts +36 -0
- package/src/authorize/routes.ts +87 -0
- package/src/authorize/token.ts +213 -0
- package/src/authorize/uris.ts +76 -0
- package/src/bearer.ts +208 -0
- package/src/bearerHeader.ts +11 -0
- package/src/breached.ts +47 -0
- package/src/browser.ts +59 -0
- package/src/captcha.ts +196 -0
- package/src/cbor.ts +129 -0
- package/src/components/deletion-banner.kay +20 -0
- package/src/components/impersonation-banner.kay +21 -0
- package/src/components/signed-in.kay +8 -0
- package/src/components/signed-out.kay +6 -0
- package/src/components/user-menu.kay +21 -0
- package/src/context.ts +5 -0
- package/src/core.ts +308 -0
- package/src/createUserCommand.ts +217 -0
- package/src/decide.ts +45 -0
- package/src/deletion.ts +80 -0
- package/src/devTool.ts +104 -0
- package/src/device.ts +37 -0
- package/src/email.ts +594 -0
- package/src/erase.ts +237 -0
- package/src/events.ts +297 -0
- package/src/export.ts +101 -0
- package/src/failure.ts +63 -0
- package/src/forwardAuth.ts +55 -0
- package/src/forwardRoutes.ts +68 -0
- package/src/gate.ts +104 -0
- package/src/guard.ts +22 -0
- package/src/guards.ts +72 -0
- package/src/guesses.ts +99 -0
- package/src/index.ts +46 -0
- package/src/keys.ts +51 -0
- package/src/limits.ts +182 -0
- package/src/load.ts +18 -0
- package/src/locale.ts +15 -0
- package/src/log.ts +4 -0
- package/src/mail.ts +225 -0
- package/src/memoryStore.ts +599 -0
- package/src/messages/fr.ts +357 -0
- package/src/methods/account.ts +80 -0
- package/src/methods/admin.ts +63 -0
- package/src/methods/audit.ts +15 -0
- package/src/methods/email.ts +39 -0
- package/src/methods/magicLink.ts +32 -0
- package/src/methods/oauth.ts +35 -0
- package/src/methods/oauthServer.ts +31 -0
- package/src/methods/organizations.ts +96 -0
- package/src/methods/passkeys.ts +61 -0
- package/src/methods/password.ts +53 -0
- package/src/methods/sessions.ts +18 -0
- package/src/methods/tokens.ts +24 -0
- package/src/methods/twoFactor.ts +62 -0
- package/src/oauth/client.ts +324 -0
- package/src/oauth/flow.ts +350 -0
- package/src/oauth/index.ts +5 -0
- package/src/oauth/pkce.ts +20 -0
- package/src/oauth/providers.ts +490 -0
- package/src/oauth/refresher.ts +177 -0
- package/src/oauth/timeout.ts +2 -0
- package/src/oauth/types.ts +78 -0
- package/src/oauthTest.ts +112 -0
- package/src/organizations.ts +675 -0
- package/src/organizationsCore.ts +60 -0
- package/src/own.ts +313 -0
- package/src/pages/components/captcha.kay +16 -0
- package/src/pages/components/frame.kay +11 -0
- package/src/pages/components/message.kay +8 -0
- package/src/pages/components/panel.kay +12 -0
- package/src/pages/components/passkey-add.kay +48 -0
- package/src/pages/components/passkey-sign-in.kay +34 -0
- package/src/pages/components/passkey-two-factor.kay +33 -0
- package/src/pages/components/proof.kay +15 -0
- package/src/pages/components/provider-buttons.kay +25 -0
- package/src/pages/components/recovery-codes.kay +13 -0
- package/src/pages/components/separator.kay +4 -0
- package/src/pages/english.ts +82 -0
- package/src/pages/forms.ts +185 -0
- package/src/pages/index.ts +361 -0
- package/src/pages/organizationPage.ts +12 -0
- package/src/pages/routes/account/_guard.ts +15 -0
- package/src/pages/routes/account/_layout.kay +37 -0
- package/src/pages/routes/account/clients.kay +33 -0
- package/src/pages/routes/account/connections.kay +57 -0
- package/src/pages/routes/account/data.kay +106 -0
- package/src/pages/routes/account/index.kay +109 -0
- package/src/pages/routes/account/organizations/[org].kay +188 -0
- package/src/pages/routes/account/organizations/_guard.ts +8 -0
- package/src/pages/routes/account/organizations/index.kay +86 -0
- package/src/pages/routes/account/security.kay +164 -0
- package/src/pages/routes/account/sessions.kay +51 -0
- package/src/pages/routes/account/tokens.kay +84 -0
- package/src/pages/routes/admin/_layout.kay +43 -0
- package/src/pages/routes/admin/audit.kay +43 -0
- package/src/pages/routes/admin/index.kay +60 -0
- package/src/pages/routes/admin/users/[id].kay +181 -0
- package/src/pages/routes/confirm-email.kay +39 -0
- package/src/pages/routes/invitation.kay +104 -0
- package/src/pages/routes/magic-link.kay +42 -0
- package/src/pages/routes/oauth/authorize.kay +80 -0
- package/src/pages/routes/register.kay +83 -0
- package/src/pages/routes/reset-password.kay +73 -0
- package/src/pages/routes/sign-in.kay +128 -0
- package/src/pages/routes/two-factor.kay +61 -0
- package/src/pages/routes/verify-email.kay +83 -0
- package/src/passkeys.ts +373 -0
- package/src/password.ts +316 -0
- package/src/payloads.ts +22 -0
- package/src/pg.ts +705 -0
- package/src/profile.ts +43 -0
- package/src/proof.ts +110 -0
- package/src/prune.ts +123 -0
- package/src/rates.ts +82 -0
- package/src/request.ts +712 -0
- package/src/requiredTwoFactor.ts +71 -0
- package/src/requirement.ts +23 -0
- package/src/roles.ts +18 -0
- package/src/routes.ts +202 -0
- package/src/rules-check.ts +37 -0
- package/src/rules.ts +108 -0
- package/src/securityNotice.ts +45 -0
- package/src/sessions.ts +184 -0
- package/src/setup.ts +417 -0
- package/src/signInOptions.ts +9 -0
- package/src/state.ts +34 -0
- package/src/store.ts +410 -0
- package/src/storeHelpers.ts +23 -0
- package/src/test.ts +46 -0
- package/src/testCookies.ts +9 -0
- package/src/testHelpers.ts +58 -0
- package/src/testing.ts +113 -0
- package/src/text.ts +6 -0
- package/src/totp.ts +120 -0
- package/src/twoFactor.ts +200 -0
- package/src/types.ts +23 -0
- package/src/userData.ts +47 -0
- package/src/viewer-layout/_layout.kay +11 -0
- package/src/viewer.ts +116 -0
- package/src/wayIn.ts +40 -0
- package/src/webauthn.ts +375 -0
- package/src/wsAuth.ts +53 -0
- package/types/access.d.ts +12 -0
- package/types/access.d.ts.map +1 -0
- package/types/account.d.ts +32 -0
- package/types/account.d.ts.map +1 -0
- package/types/add.d.ts +29 -0
- package/types/add.d.ts.map +1 -0
- package/types/address.d.ts +2 -0
- package/types/address.d.ts.map +1 -0
- package/types/admin.d.ts +84 -0
- package/types/admin.d.ts.map +1 -0
- package/types/auditWording.d.ts +9 -0
- package/types/auditWording.d.ts.map +1 -0
- package/types/auth.d.ts +3475 -0
- package/types/auth.d.ts.map +1 -0
- package/types/authorize/clients.d.ts +15 -0
- package/types/authorize/clients.d.ts.map +1 -0
- package/types/authorize/grants.d.ts +15 -0
- package/types/authorize/grants.d.ts.map +1 -0
- package/types/authorize/metadata.d.ts +20 -0
- package/types/authorize/metadata.d.ts.map +1 -0
- package/types/authorize/register.d.ts +4 -0
- package/types/authorize/register.d.ts.map +1 -0
- package/types/authorize/reply.d.ts +6 -0
- package/types/authorize/reply.d.ts.map +1 -0
- package/types/authorize/request.d.ts +48 -0
- package/types/authorize/request.d.ts.map +1 -0
- package/types/authorize/resource.d.ts +4 -0
- package/types/authorize/resource.d.ts.map +1 -0
- package/types/authorize/revoke.d.ts +4 -0
- package/types/authorize/revoke.d.ts.map +1 -0
- package/types/authorize/routes.d.ts +5 -0
- package/types/authorize/routes.d.ts.map +1 -0
- package/types/authorize/token.d.ts +7 -0
- package/types/authorize/token.d.ts.map +1 -0
- package/types/authorize/uris.d.ts +5 -0
- package/types/authorize/uris.d.ts.map +1 -0
- package/types/bearer.d.ts +45 -0
- package/types/bearer.d.ts.map +1 -0
- package/types/bearerHeader.d.ts +3 -0
- package/types/bearerHeader.d.ts.map +1 -0
- package/types/breached.d.ts +5 -0
- package/types/breached.d.ts.map +1 -0
- package/types/browser.d.ts +11 -0
- package/types/browser.d.ts.map +1 -0
- package/types/captcha.d.ts +42 -0
- package/types/captcha.d.ts.map +1 -0
- package/types/cbor.d.ts +4 -0
- package/types/cbor.d.ts.map +1 -0
- package/types/context.d.ts +3 -0
- package/types/context.d.ts.map +1 -0
- package/types/core.d.ts +180 -0
- package/types/core.d.ts.map +1 -0
- package/types/createUserCommand.d.ts +11 -0
- package/types/createUserCommand.d.ts.map +1 -0
- package/types/decide.d.ts +12 -0
- package/types/decide.d.ts.map +1 -0
- package/types/deletion.d.ts +17 -0
- package/types/deletion.d.ts.map +1 -0
- package/types/devTool.d.ts +3 -0
- package/types/devTool.d.ts.map +1 -0
- package/types/device.d.ts +7 -0
- package/types/device.d.ts.map +1 -0
- package/types/email.d.ts +73 -0
- package/types/email.d.ts.map +1 -0
- package/types/erase.d.ts +31 -0
- package/types/erase.d.ts.map +1 -0
- package/types/events.d.ts +139 -0
- package/types/events.d.ts.map +1 -0
- package/types/export.d.ts +54 -0
- package/types/export.d.ts.map +1 -0
- package/types/failure.d.ts +19 -0
- package/types/failure.d.ts.map +1 -0
- package/types/forwardAuth.d.ts +12 -0
- package/types/forwardAuth.d.ts.map +1 -0
- package/types/forwardRoutes.d.ts +11 -0
- package/types/forwardRoutes.d.ts.map +1 -0
- package/types/gate.d.ts +31 -0
- package/types/gate.d.ts.map +1 -0
- package/types/guard.d.ts +10 -0
- package/types/guard.d.ts.map +1 -0
- package/types/guards.d.ts +37 -0
- package/types/guards.d.ts.map +1 -0
- package/types/guesses.d.ts +18 -0
- package/types/guesses.d.ts.map +1 -0
- package/types/index.d.ts +47 -0
- package/types/index.d.ts.map +1 -0
- package/types/keys.d.ts +11 -0
- package/types/keys.d.ts.map +1 -0
- package/types/limits.d.ts +133 -0
- package/types/limits.d.ts.map +1 -0
- package/types/load.d.ts +18 -0
- package/types/load.d.ts.map +1 -0
- package/types/locale.d.ts +4 -0
- package/types/locale.d.ts.map +1 -0
- package/types/log.d.ts +2 -0
- package/types/log.d.ts.map +1 -0
- package/types/mail.d.ts +51 -0
- package/types/mail.d.ts.map +1 -0
- package/types/memoryStore.d.ts +3 -0
- package/types/memoryStore.d.ts.map +1 -0
- package/types/messages/fr.d.ts +409 -0
- package/types/messages/fr.d.ts.map +1 -0
- package/types/methods/account.d.ts +24 -0
- package/types/methods/account.d.ts.map +1 -0
- package/types/methods/admin.d.ts +30 -0
- package/types/methods/admin.d.ts.map +1 -0
- package/types/methods/audit.d.ts +11 -0
- package/types/methods/audit.d.ts.map +1 -0
- package/types/methods/email.d.ts +14 -0
- package/types/methods/email.d.ts.map +1 -0
- package/types/methods/magicLink.d.ts +12 -0
- package/types/methods/magicLink.d.ts.map +1 -0
- package/types/methods/oauth.d.ts +16 -0
- package/types/methods/oauth.d.ts.map +1 -0
- package/types/methods/oauthServer.d.ts +13 -0
- package/types/methods/oauthServer.d.ts.map +1 -0
- package/types/methods/organizations.d.ts +30 -0
- package/types/methods/organizations.d.ts.map +1 -0
- package/types/methods/passkeys.d.ts +19 -0
- package/types/methods/passkeys.d.ts.map +1 -0
- package/types/methods/password.d.ts +17 -0
- package/types/methods/password.d.ts.map +1 -0
- package/types/methods/sessions.d.ts +9 -0
- package/types/methods/sessions.d.ts.map +1 -0
- package/types/methods/tokens.d.ts +11 -0
- package/types/methods/tokens.d.ts.map +1 -0
- package/types/methods/twoFactor.d.ts +20 -0
- package/types/methods/twoFactor.d.ts.map +1 -0
- package/types/oauth/client.d.ts +39 -0
- package/types/oauth/client.d.ts.map +1 -0
- package/types/oauth/flow.d.ts +38 -0
- package/types/oauth/flow.d.ts.map +1 -0
- package/types/oauth/index.d.ts +6 -0
- package/types/oauth/index.d.ts.map +1 -0
- package/types/oauth/pkce.d.ts +10 -0
- package/types/oauth/pkce.d.ts.map +1 -0
- package/types/oauth/providers.d.ts +100 -0
- package/types/oauth/providers.d.ts.map +1 -0
- package/types/oauth/refresher.d.ts +55 -0
- package/types/oauth/refresher.d.ts.map +1 -0
- package/types/oauth/timeout.d.ts +2 -0
- package/types/oauth/timeout.d.ts.map +1 -0
- package/types/oauth/types.d.ts +75 -0
- package/types/oauth/types.d.ts.map +1 -0
- package/types/oauthTest.d.ts +23 -0
- package/types/oauthTest.d.ts.map +1 -0
- package/types/organizations.d.ts +111 -0
- package/types/organizations.d.ts.map +1 -0
- package/types/organizationsCore.d.ts +29 -0
- package/types/organizationsCore.d.ts.map +1 -0
- package/types/own.d.ts +55 -0
- package/types/own.d.ts.map +1 -0
- package/types/pages/english.d.ts +80 -0
- package/types/pages/english.d.ts.map +1 -0
- package/types/pages/forms.d.ts +204 -0
- package/types/pages/forms.d.ts.map +1 -0
- package/types/pages/index.d.ts +166 -0
- package/types/pages/index.d.ts.map +1 -0
- package/types/pages/organizationPage.d.ts +7 -0
- package/types/pages/organizationPage.d.ts.map +1 -0
- package/types/pages/routes/account/_guard.d.ts +3 -0
- package/types/pages/routes/account/_guard.d.ts.map +1 -0
- package/types/pages/routes/account/organizations/_guard.d.ts +3 -0
- package/types/pages/routes/account/organizations/_guard.d.ts.map +1 -0
- package/types/passkeys.d.ts +61 -0
- package/types/passkeys.d.ts.map +1 -0
- package/types/password.d.ts +49 -0
- package/types/password.d.ts.map +1 -0
- package/types/payloads.d.ts +4 -0
- package/types/payloads.d.ts.map +1 -0
- package/types/pg.d.ts +303 -0
- package/types/pg.d.ts.map +1 -0
- package/types/profile.d.ts +11 -0
- package/types/profile.d.ts.map +1 -0
- package/types/proof.d.ts +33 -0
- package/types/proof.d.ts.map +1 -0
- package/types/prune.d.ts +5 -0
- package/types/prune.d.ts.map +1 -0
- package/types/rates.d.ts +15 -0
- package/types/rates.d.ts.map +1 -0
- package/types/request.d.ts +119 -0
- package/types/request.d.ts.map +1 -0
- package/types/requiredTwoFactor.d.ts +16 -0
- package/types/requiredTwoFactor.d.ts.map +1 -0
- package/types/requirement.d.ts +4 -0
- package/types/requirement.d.ts.map +1 -0
- package/types/roles.d.ts +9 -0
- package/types/roles.d.ts.map +1 -0
- package/types/routes.d.ts +31 -0
- package/types/routes.d.ts.map +1 -0
- package/types/rules-check.d.ts +3 -0
- package/types/rules-check.d.ts.map +1 -0
- package/types/rules.d.ts +38 -0
- package/types/rules.d.ts.map +1 -0
- package/types/securityNotice.d.ts +7 -0
- package/types/securityNotice.d.ts.map +1 -0
- package/types/sessions.d.ts +32 -0
- package/types/sessions.d.ts.map +1 -0
- package/types/setup.d.ts +18 -0
- package/types/setup.d.ts.map +1 -0
- package/types/signInOptions.d.ts +6 -0
- package/types/signInOptions.d.ts.map +1 -0
- package/types/state.d.ts +25 -0
- package/types/state.d.ts.map +1 -0
- package/types/store.d.ts +295 -0
- package/types/store.d.ts.map +1 -0
- package/types/storeHelpers.d.ts +4 -0
- package/types/storeHelpers.d.ts.map +1 -0
- package/types/test.d.ts +21 -0
- package/types/test.d.ts.map +1 -0
- package/types/testCookies.d.ts +3 -0
- package/types/testCookies.d.ts.map +1 -0
- package/types/testHelpers.d.ts +34 -0
- package/types/testHelpers.d.ts.map +1 -0
- package/types/testing.d.ts +12 -0
- package/types/testing.d.ts.map +1 -0
- package/types/text.d.ts +2 -0
- package/types/text.d.ts.map +1 -0
- package/types/totp.d.ts +12 -0
- package/types/totp.d.ts.map +1 -0
- package/types/twoFactor.d.ts +41 -0
- package/types/twoFactor.d.ts.map +1 -0
- package/types/types.d.ts +17 -0
- package/types/types.d.ts.map +1 -0
- package/types/userData.d.ts +9 -0
- package/types/userData.d.ts.map +1 -0
- package/types/viewer.d.ts +23 -0
- package/types/viewer.d.ts.map +1 -0
- package/types/wayIn.d.ts +12 -0
- package/types/wayIn.d.ts.map +1 -0
- package/types/webauthn.d.ts +111 -0
- package/types/webauthn.d.ts.map +1 -0
- package/types/wsAuth.d.ts +14 -0
- package/types/wsAuth.d.ts.map +1 -0
package/src/profile.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { BareUser } from './core'
|
|
2
|
+
import type { AuthFailed, AuthRejected } from './failure'
|
|
3
|
+
import type { ProfileFieldView, ProfileOptions, ProfileProblem } from './pages'
|
|
4
|
+
import { rejected } from './failure'
|
|
5
|
+
import { profileLabel, profileValue } from './pages'
|
|
6
|
+
import { PROFILE_MAX_LENGTH } from './rules'
|
|
7
|
+
|
|
8
|
+
export type SaveProfileResult = { ok: true } | AuthFailed<'signed-out'> | AuthRejected<Record<string, ProfileProblem>>
|
|
9
|
+
|
|
10
|
+
// The fields of the profile form with what `user` holds in each.
|
|
11
|
+
export async function profileFields(profile: ProfileOptions, user: BareUser, locale: string | undefined): Promise<ProfileFieldView[]> {
|
|
12
|
+
const held = await profile.load(user)
|
|
13
|
+
|
|
14
|
+
return Object.entries(profile.fields).map(([name, field]) => ({ ...field, label: profileLabel(field.label, locale), name, maxLength: field.maxLength ?? PROFILE_MAX_LENGTH, value: profileValue(name, Object.hasOwn(held, name) ? held[name] : undefined) }))
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// The values posted from the form, trimmed and checked against each field's `required` and `maxLength`; nothing is stored while any field is refused.
|
|
18
|
+
export async function saveProfile(profile: ProfileOptions, user: BareUser, values: Record<string, unknown>): Promise<{ ok: true } | AuthRejected<Record<string, ProfileProblem>>> {
|
|
19
|
+
const clean: Record<string, string> = {}
|
|
20
|
+
const errors: Record<string, ProfileProblem> = {}
|
|
21
|
+
|
|
22
|
+
for (const [name, field] of Object.entries(profile.fields)) {
|
|
23
|
+
const raw = Object.hasOwn(values, name) ? values[name] : undefined
|
|
24
|
+
const value = typeof raw === 'string' ? raw.trim() : ''
|
|
25
|
+
|
|
26
|
+
clean[name] = value
|
|
27
|
+
|
|
28
|
+
if (value === '' && field.required)
|
|
29
|
+
errors[name] = 'required'
|
|
30
|
+
else if (value.length > (field.maxLength ?? PROFILE_MAX_LENGTH))
|
|
31
|
+
errors[name] = 'too-long'
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
if (Object.keys(errors).length > 0)
|
|
35
|
+
return rejected(errors)
|
|
36
|
+
|
|
37
|
+
const refused = await profile.save(user, clean)
|
|
38
|
+
|
|
39
|
+
if (!refused)
|
|
40
|
+
return { ok: true }
|
|
41
|
+
|
|
42
|
+
return rejected(Object.fromEntries(Object.entries(refused.errors).flatMap(([name, message]) => typeof message === 'string' && Object.hasOwn(profile.fields, name) ? [[name, { message }]] : [])))
|
|
43
|
+
}
|
package/src/proof.ts
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import type { AuthFailed } from './failure'
|
|
2
|
+
import type { RequestState } from './state'
|
|
3
|
+
import type { UserRecord } from './store'
|
|
4
|
+
import type { AuthenticationResponseJSON } from './webauthn'
|
|
5
|
+
import { comparePasswords } from '@kaynooo/utils'
|
|
6
|
+
import { backOf, banned, withBack } from './core'
|
|
7
|
+
import { failed } from './failure'
|
|
8
|
+
import { forget, spend } from './limits'
|
|
9
|
+
|
|
10
|
+
const CHALLENGE_MAX_AGE_MS = 10 * 60 * 1000
|
|
11
|
+
// How long a sign-in or a re-proof counts as proved: for an account with neither a password nor a second factor, and for an admin's changes to other users.
|
|
12
|
+
const FRESH_SIGN_IN_MS = 10 * 60 * 1000
|
|
13
|
+
|
|
14
|
+
// What re-proves the user behind a live session: their password, or with none their second factor, or one of their passkeys.
|
|
15
|
+
export interface Proof {
|
|
16
|
+
password?: string
|
|
17
|
+
// An authenticator code, or a recovery code.
|
|
18
|
+
code?: string
|
|
19
|
+
// A passkey's answer to `passkeys.proofOptions`, which stands for the password and the second factor both.
|
|
20
|
+
passkey?: AuthenticationResponseJSON
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// `proof` when the proof was wrong or missing; `stale` when the account has neither a password nor a second factor and was signed into too long ago, so the user signs in again first; `impersonating` when an admin acts as the user, who proves nothing for them.
|
|
24
|
+
export type ProofFailure = 'signed-out' | 'proof' | 'stale' | 'limited' | 'impersonating'
|
|
25
|
+
|
|
26
|
+
export type ReproveResult = { ok: true } | AuthFailed<ProofFailure>
|
|
27
|
+
|
|
28
|
+
// What a sign-in waiting for its second factor keeps in the session.
|
|
29
|
+
export interface Challenge {
|
|
30
|
+
user: string
|
|
31
|
+
version: number
|
|
32
|
+
redirect: string
|
|
33
|
+
// How the first factor was proved, for the `signed-in` event.
|
|
34
|
+
method?: string
|
|
35
|
+
expires: number
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Signs `record` in, or when it has a second factor parks the sign-in until the code, and answers where the browser goes next.
|
|
39
|
+
export async function completeSignIn(state: RequestState, record: UserRecord, redirect: string, method: string, signIn: (record: UserRecord, method: string) => Promise<void>): Promise<{ ok: true, redirect: string } | AuthFailed<'banned'>> {
|
|
40
|
+
if (banned(record))
|
|
41
|
+
return failed('banned')
|
|
42
|
+
|
|
43
|
+
if (record.totpEnabledAt === null) {
|
|
44
|
+
await signIn(record, method)
|
|
45
|
+
|
|
46
|
+
return { ok: true, redirect }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
await state.session.set('authChallenge', { user: record.id, version: record.sessionVersion, redirect, method, expires: Date.now() + CHALLENGE_MAX_AGE_MS })
|
|
50
|
+
|
|
51
|
+
// The code page carries the page asked for too, for the link back to sign-in when the challenge is gone by the time the code is typed.
|
|
52
|
+
const back = backOf(state.core, redirect)
|
|
53
|
+
|
|
54
|
+
return { ok: true, redirect: back === null ? state.core.twoFactorPage : withBack(state.core.twoFactorPage, back) }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Whether this session holds a sign-in waiting for its second factor.
|
|
58
|
+
export async function challenged(state: RequestState): Promise<boolean> {
|
|
59
|
+
const challenge = await state.session.get('authChallenge')
|
|
60
|
+
|
|
61
|
+
return challenge !== undefined && challenge.expires > Date.now()
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// The user signed in on a session (never a bearer token), once `proof` re-proves them, so a stolen session alone cannot change what protects the account.
|
|
65
|
+
// With `secondFactor`, an account with 2FA on proves it with a code, password or not, since a password alone must not turn off or replace what stands behind it.
|
|
66
|
+
export async function reprove(state: RequestState, proof: Proof, options: { secondFactor?: boolean } = {}): Promise<{ ok: true, record: UserRecord } | AuthFailed<ProofFailure>> {
|
|
67
|
+
const record = await state.current()
|
|
68
|
+
|
|
69
|
+
if (!record || state.via() !== 'session')
|
|
70
|
+
return failed('signed-out')
|
|
71
|
+
|
|
72
|
+
if ((await state.session.get('auth'))?.impersonator)
|
|
73
|
+
return failed('impersonating')
|
|
74
|
+
|
|
75
|
+
const twoFactor = record.totpEnabledAt !== null
|
|
76
|
+
|
|
77
|
+
if (proof.passkey === undefined && record.passwordHash === null && !twoFactor)
|
|
78
|
+
return await provedLately(state) ? { ok: true, record } : failed('stale')
|
|
79
|
+
|
|
80
|
+
if (await spend(state.core.rates, `reprove:${record.id}`, state.core.limits.reprove))
|
|
81
|
+
return failed('limited')
|
|
82
|
+
|
|
83
|
+
let proved: boolean
|
|
84
|
+
|
|
85
|
+
if (proof.passkey !== undefined)
|
|
86
|
+
proved = await (await import('./passkeys')).provePasskey(state, record, proof.passkey)
|
|
87
|
+
else if (record.passwordHash !== null && !(options.secondFactor && twoFactor))
|
|
88
|
+
proved = await comparePasswords(proof.password ?? '', record.passwordHash)
|
|
89
|
+
else
|
|
90
|
+
proved = (await (await import('./twoFactor')).spendSecondFactor(state, record, proof.code ?? '')) !== undefined
|
|
91
|
+
|
|
92
|
+
if (!proved)
|
|
93
|
+
return failed('proof')
|
|
94
|
+
|
|
95
|
+
await forget(state.core.rates, `reprove:${record.id}`, state.core.limits.reprove)
|
|
96
|
+
|
|
97
|
+
const signedIn = await state.session.get('auth')
|
|
98
|
+
|
|
99
|
+
if (signedIn?.user === record.id)
|
|
100
|
+
await state.session.set('auth', { ...signedIn, at: Date.now() })
|
|
101
|
+
|
|
102
|
+
return { ok: true, record }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Whether this session signed in or re-proved its user in the last ten minutes.
|
|
106
|
+
export async function provedLately(state: RequestState): Promise<boolean> {
|
|
107
|
+
const signedIn = await state.session.get('auth')
|
|
108
|
+
|
|
109
|
+
return signedIn !== undefined && Date.now() - signedIn.at < FRESH_SIGN_IN_MS
|
|
110
|
+
}
|
package/src/prune.ts
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import type { SessionSettings } from 'kay/server'
|
|
2
|
+
import type { Core } from './core'
|
|
3
|
+
import { durationSeconds, maintenance } from 'kay/library'
|
|
4
|
+
import { log } from './log'
|
|
5
|
+
|
|
6
|
+
// What expired is deleted at most this often.
|
|
7
|
+
export const PRUNE_EVERY_MS = 60 * 60 * 1000
|
|
8
|
+
const BEARER_EXPIRED_KEPT_MS = 30 * 24 * 60 * 60 * 1000
|
|
9
|
+
// Accounts listed at once, and the most batches one run goes through; a larger backlog goes on with the next run.
|
|
10
|
+
const STALE_PER_BATCH = 500
|
|
11
|
+
const STALE_BATCHES_PER_RUN = 20
|
|
12
|
+
|
|
13
|
+
// Starts the store's pruning when it is due, without making the request wait for it; the run is a maintenance, locked across processes, counted with the schedules and tracked as detached work, so a test's `runJobs()` waits for it. A failure is logged, and the next try is an hour away.
|
|
14
|
+
export function pruneWhenDue(core: Core, settings: SessionSettings): void {
|
|
15
|
+
const now = Date.now()
|
|
16
|
+
|
|
17
|
+
if ((!core.store.prune && !staleKept(core)) || now - core.pruned.at < PRUNE_EVERY_MS)
|
|
18
|
+
return
|
|
19
|
+
|
|
20
|
+
core.pruned.at = now
|
|
21
|
+
core.pruned.settings = settings
|
|
22
|
+
core.pruned.sweep ??= maintenance('auth-prune', PRUNE_EVERY_MS, async () => prune(core, core.pruned.settings!, Date.now()))
|
|
23
|
+
void core.pruned.sweep.run()
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async function prune(core: Core, settings: SessionSettings, now: number): Promise<void> {
|
|
27
|
+
try {
|
|
28
|
+
await core.store.prune?.({ now: new Date(now), bearerExpiredBefore: new Date(now - BEARER_EXPIRED_KEPT_MS), sessionMaxAge: `${Math.max(durationSeconds(settings.maxAge, 'the session maxAge'), core.rememberMaxAge, durationSeconds(settings.browserMaxAge, 'the session browserMaxAge'))}s`, sessionAbsoluteMaxAge: settings.absoluteMaxAge })
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
log.error('pruning what expired failed', error)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
await pruneStale(core, now, 'guest')
|
|
35
|
+
await pruneStale(core, now, 'unverified')
|
|
36
|
+
await pruneStale(core, now, 'pending')
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function staleKept(core: Core): boolean {
|
|
40
|
+
return core.store.users.staleGuests !== undefined || core.deletion !== undefined || (core.unverifiedMaxAge !== undefined && core.store.users.staleUnverified !== undefined)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
type StaleKind = 'guest' | 'unverified' | 'pending'
|
|
44
|
+
|
|
45
|
+
// The listing of a kind of account, and the instant it asks it at: guests and unverified accounts older than their max age, accounts pending deletion whose period ended by now.
|
|
46
|
+
function listing(core: Core, now: number, kind: StaleKind): { list: NonNullable<Core['store']['users']['dueForDeletion']>, at: Date } | undefined {
|
|
47
|
+
if (kind === 'pending')
|
|
48
|
+
return core.deletion && core.store.users.dueForDeletion ? { list: core.store.users.dueForDeletion, at: new Date(now) } : undefined
|
|
49
|
+
|
|
50
|
+
const maxAge = kind === 'guest' ? core.guestMaxAge : core.unverifiedMaxAge
|
|
51
|
+
const list = kind === 'guest' ? core.store.users.staleGuests : core.store.users.staleUnverified
|
|
52
|
+
|
|
53
|
+
return maxAge === undefined || !list ? undefined : { list, at: new Date(now - maxAge * 1000) }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Guests older than `guests.maxAge` whose sessions ended, with `requireVerified` the accounts registered and never verified for `email.unverifiedMaxAge`, and the accounts whose `account.deleteAfter` period ended, go as any deleted user does, `beforeDelete` first; the last ones also report the deletion and mail the notice. One whose `beforeDelete` fails stays, to be tried again the next run, and the run goes on past it and past any that is kept.
|
|
57
|
+
async function pruneStale(core: Core, now: number, kind: StaleKind): Promise<void> {
|
|
58
|
+
const found = listing(core, now, kind)
|
|
59
|
+
|
|
60
|
+
if (!found)
|
|
61
|
+
return
|
|
62
|
+
|
|
63
|
+
const { list, at } = found
|
|
64
|
+
const what = kind === 'pending' ? 'an account pending deletion' : `a stale ${kind}`
|
|
65
|
+
|
|
66
|
+
// The listing is oldest first and cannot skip, so what a run keeps (a role beyond the default ones, a failed `onDelete`) is listed again each batch: the batch grows by that many and the kept ones are left out, to reach the accounts behind them.
|
|
67
|
+
const kept = new Set<string>()
|
|
68
|
+
|
|
69
|
+
try {
|
|
70
|
+
for (let batch = 0; batch < STALE_BATCHES_PER_RUN; batch++) {
|
|
71
|
+
const size = STALE_PER_BATCH + kept.size
|
|
72
|
+
const listed = await list(at, size)
|
|
73
|
+
|
|
74
|
+
let deleted = 0
|
|
75
|
+
let failed = 0
|
|
76
|
+
|
|
77
|
+
for (const account of listed) {
|
|
78
|
+
if (kept.has(account.id))
|
|
79
|
+
continue
|
|
80
|
+
|
|
81
|
+
try {
|
|
82
|
+
if (await stillStale(core, account.id, kind, now)) {
|
|
83
|
+
const erase = await import('./erase')
|
|
84
|
+
|
|
85
|
+
await (kind === 'pending' ? erase.eraseDue(core, account) : erase.eraseUser(core, account))
|
|
86
|
+
deleted++
|
|
87
|
+
|
|
88
|
+
continue
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
log.error(`deleting ${what} failed`, error)
|
|
93
|
+
failed++
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
kept.add(account.id)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// A short list is the end of them, and a batch whose erases all failed means a hook or store is down: the next run tries again.
|
|
100
|
+
if (listed.length < size || (deleted === 0 && failed > 0))
|
|
101
|
+
return
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
log.error(`listing the ${kind} accounts to delete failed`, error)
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// Read again just before the erase: a guest registered since the list was read is a real account, an unverified one given a role beyond the default ones was set up on purpose, as registering again does not replace it, and a deletion cancelled since stays cancelled.
|
|
110
|
+
async function stillStale(core: Core, id: string, kind: StaleKind, now: number): Promise<boolean> {
|
|
111
|
+
const current = await core.store.users.get(id)
|
|
112
|
+
|
|
113
|
+
if (!current)
|
|
114
|
+
return false
|
|
115
|
+
|
|
116
|
+
if (kind === 'pending')
|
|
117
|
+
return current.deleteAt != null && current.deleteAt.getTime() <= now
|
|
118
|
+
|
|
119
|
+
if (kind === 'guest')
|
|
120
|
+
return current.guest
|
|
121
|
+
|
|
122
|
+
return !current.guest && current.emailVerifiedAt === null && current.roles.every(role => core.defaultRoles.includes(role))
|
|
123
|
+
}
|
package/src/rates.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import type { RateStore, RateWindow } from 'kay'
|
|
2
|
+
import type { Limiter } from 'kay/library'
|
|
3
|
+
import type { AuthRateLimit } from './limits'
|
|
4
|
+
import type { AuthStore } from './store'
|
|
5
|
+
import { limiter } from 'kay/library'
|
|
6
|
+
|
|
7
|
+
const SWEEP_EVERY = 1000
|
|
8
|
+
|
|
9
|
+
// Where kayjs-auth counts attempts: kay's `RateStore`. Its `peek` and `reset` are optional, as kay derives them for a store without.
|
|
10
|
+
export type AuthRates = RateStore
|
|
11
|
+
|
|
12
|
+
// Answered at once, as memory needs no promise; `sweep` drops the windows ended by `now`.
|
|
13
|
+
export interface MemoryAuthRates {
|
|
14
|
+
hit: (key: string, windowMs: number, weight?: number) => RateWindow
|
|
15
|
+
peek: (key: string) => RateWindow | undefined
|
|
16
|
+
reset: (key: string) => void
|
|
17
|
+
sweep: (now: number) => void
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Windows in this process's memory, swept every so many hits so memory follows the clients that keep trying. Unlike kay's `memoryRates` it drops no open window when many are open, so a flood of keys cannot evict an account's lockout.
|
|
21
|
+
export function memoryAuthRates(): MemoryAuthRates {
|
|
22
|
+
const windows = new Map<string, RateWindow>()
|
|
23
|
+
let hits = 0
|
|
24
|
+
|
|
25
|
+
const sweep = (now: number) => {
|
|
26
|
+
for (const [key, window] of windows) {
|
|
27
|
+
if (window.resetAt <= now)
|
|
28
|
+
windows.delete(key)
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
return {
|
|
33
|
+
peek(key) {
|
|
34
|
+
const window = windows.get(key)
|
|
35
|
+
|
|
36
|
+
return window && window.resetAt > Date.now() ? { ...window } : undefined
|
|
37
|
+
},
|
|
38
|
+
hit(key, length, weight = 1) {
|
|
39
|
+
const now = Date.now()
|
|
40
|
+
const open = windows.get(key)
|
|
41
|
+
const window = open && open.resetAt > now ? { ...open, count: open.count + weight } : { count: weight, resetAt: now + length }
|
|
42
|
+
|
|
43
|
+
if (++hits % SWEEP_EVERY === 0)
|
|
44
|
+
sweep(now)
|
|
45
|
+
|
|
46
|
+
windows.set(key, window)
|
|
47
|
+
|
|
48
|
+
return { ...window }
|
|
49
|
+
},
|
|
50
|
+
reset(key) {
|
|
51
|
+
windows.delete(key)
|
|
52
|
+
},
|
|
53
|
+
sweep,
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// The limiter of a limit, counted in the store's own `rates`, else the app's `store.rates` from kay.config.ts, else this process's memory, its keys apart from kay's own limits and other libraries'.
|
|
58
|
+
// The app's store is read on each count, as kay sets it up after `authCore` may have run. A store that fails or hangs counts in memory meanwhile, as kay's own limits do.
|
|
59
|
+
export type AuthLimiters = (limit: AuthRateLimit) => Limiter
|
|
60
|
+
|
|
61
|
+
export function authLimiters(store: AuthStore): AuthLimiters {
|
|
62
|
+
const made = new Map<string, Limiter>()
|
|
63
|
+
const ofStore = new WeakMap<RateStore, Map<string, Limiter>>()
|
|
64
|
+
const memory = memoryAuthRates()
|
|
65
|
+
|
|
66
|
+
return ({ max, window, store: own }) => {
|
|
67
|
+
const id = `${max} ${window}`
|
|
68
|
+
let cache = made
|
|
69
|
+
|
|
70
|
+
if (own) {
|
|
71
|
+
cache = ofStore.get(own) ?? new Map()
|
|
72
|
+
ofStore.set(own, cache)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
let found = cache.get(id)
|
|
76
|
+
|
|
77
|
+
if (!found)
|
|
78
|
+
cache.set(id, found = limiter({ max, window, store: own ?? store.rates, name: 'kayjs-auth', memory }))
|
|
79
|
+
|
|
80
|
+
return found
|
|
81
|
+
}
|
|
82
|
+
}
|