@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/email.ts
ADDED
|
@@ -0,0 +1,594 @@
|
|
|
1
|
+
import type { Duration } from 'kay'
|
|
2
|
+
import type { Core } from './core'
|
|
3
|
+
import type { AuthFailed, AuthRejected } from './failure'
|
|
4
|
+
import type { AuthMailer, MailData, Templates } from './mail'
|
|
5
|
+
import type { Proof, ProofFailure } from './proof'
|
|
6
|
+
import type { EmailProblem, PasswordProblem } from './rules'
|
|
7
|
+
import type { RequestState } from './state'
|
|
8
|
+
import type { CodeType, LinkType, TokenType, UserRecord } from './store'
|
|
9
|
+
import { hashPassword, nanoid } from '@kaynooo/utils'
|
|
10
|
+
import { localPath } from 'kay'
|
|
11
|
+
import { trackDetached } from 'kay/library'
|
|
12
|
+
import { newPasswordProblem } from './breached'
|
|
13
|
+
import { admit } from './captcha'
|
|
14
|
+
import { backOf, banned, homeOf, withBack } from './core'
|
|
15
|
+
import { failed, rejected } from './failure'
|
|
16
|
+
import { failGuess, forgive, passwordMatches, startGuess } from './guesses'
|
|
17
|
+
import { digest, randomToken } from './keys'
|
|
18
|
+
import { spend, typedKey, windowOf } from './limits'
|
|
19
|
+
import { log } from './log'
|
|
20
|
+
import { sendAside, writing } from './mail'
|
|
21
|
+
import { reprove } from './proof'
|
|
22
|
+
import { emailProblem, normalizeEmail } from './rules'
|
|
23
|
+
import { securityNotice } from './securityNotice'
|
|
24
|
+
import { endOtherSessions, removeIdentities, revokeBearerTokens } from './sessions'
|
|
25
|
+
|
|
26
|
+
const CODE_LENGTH = 6
|
|
27
|
+
// Wrong guesses one code takes before it dies, whatever the limits leave.
|
|
28
|
+
const CODE_MISSES = 5
|
|
29
|
+
const DIGITS = '0123456789'
|
|
30
|
+
const NOT_DIGITS = /\D/g
|
|
31
|
+
|
|
32
|
+
// The mails that can carry a code, and the code each carries.
|
|
33
|
+
export type CodedLink = 'magic-link' | 'verify-email'
|
|
34
|
+
const CODE_OF: Record<CodedLink, CodeType> = { 'magic-link': 'sign-in-code', 'verify-email': 'verify-code' }
|
|
35
|
+
const LINK_OF: Record<CodeType, CodedLink> = { 'sign-in-code': 'magic-link', 'verify-code': 'verify-email' }
|
|
36
|
+
|
|
37
|
+
// What a sign-in or verification mail carries: a link, a code typed on the device that asked for it, or both.
|
|
38
|
+
export type CodeMode = 'link' | 'code' | 'both'
|
|
39
|
+
|
|
40
|
+
export interface EmailOptions {
|
|
41
|
+
mailer: AuthMailer
|
|
42
|
+
// The app's page each link opens, the token in `?token=`, the prebuilt one by default with `pages`. Each shows a button, or the new password's form, posting the token to an action, so a mail scanner opening the link spends nothing.
|
|
43
|
+
links?: Partial<Record<LinkType, string>> | undefined
|
|
44
|
+
// Over kayjs-auth's own templates in every language.
|
|
45
|
+
templates?: Partial<Templates> | undefined
|
|
46
|
+
// The languages mails are written in, the first for a user whose language is none of them: `['en', 'fr']`. The site's `i18n.locales` by default, English where it has none; kayjs-auth writes English and French, `translations` any other.
|
|
47
|
+
locales?: string[] | undefined
|
|
48
|
+
// Templates by language, over `templates`: `{ de: germanTemplates }`.
|
|
49
|
+
translations?: Record<string, Partial<Templates>> | undefined
|
|
50
|
+
// Refuses password sign-in until the address is verified, and signs no one in on registering, so registering answers alike whether or not the address is held. On by default; `false` signs in on registering and answers `'taken'` for a held address.
|
|
51
|
+
requireVerified?: boolean | undefined
|
|
52
|
+
// How long an account registered and never verified is kept before it is deleted, `onDelete` first: a string such as '7d'. 30 days by default with `requireVerified`; without it accounts are kept unless this is set, as an unverified one may be in use.
|
|
53
|
+
unverifiedMaxAge?: Duration | undefined
|
|
54
|
+
// How long each link and code works, over the defaults: `{ 'verify-email': '7d' }` for invited users. The keys are the four links, `verify-email`, `reset-password`, `magic-link` and `change-email`, and the two codes, `sign-in-code` and `verify-code`; the mails state what is set.
|
|
55
|
+
maxAge?: Partial<Record<TokenType, Duration>> | undefined
|
|
56
|
+
// Whether magic links and verification mails carry a code, for both kinds at once or for each: `'both'`, `{ 'magic-link': 'code' }`. A link only by default.
|
|
57
|
+
codes?: CodeMode | Partial<Record<CodedLink, CodeMode>> | undefined
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export type EmailCore = Required<Omit<EmailOptions, 'links' | 'templates' | 'requireVerified' | 'unverifiedMaxAge' | 'codes' | 'locales' | 'translations' | 'maxAge'>> & { maxAge: Record<TokenType, number>, links: Record<LinkType, string>, requireVerified: boolean, locales: string[], templates: Record<string, Templates>, codes: Record<CodedLink, CodeMode> }
|
|
61
|
+
|
|
62
|
+
// A code waiting in the session that asked for it, which alone can spend it.
|
|
63
|
+
export interface PendingCode {
|
|
64
|
+
type: CodeType
|
|
65
|
+
email: string
|
|
66
|
+
// Mixed into the code's digest, so the code works in this session only.
|
|
67
|
+
nonce: string
|
|
68
|
+
expires: number
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export type CodeResult = { ok: true, redirect: string } | AuthFailed<'invalid' | 'expired' | 'limited' | 'banned'>
|
|
72
|
+
|
|
73
|
+
// Sent whether or not an account has that address, so the answer tells nothing of which ones exist.
|
|
74
|
+
export type MailRequestResult = { ok: true } | AuthFailed<'limited' | 'captcha' | 'unavailable'>
|
|
75
|
+
|
|
76
|
+
export type LinkResult = { ok: true, redirect: string } | AuthFailed<'invalid' | 'limited' | 'banned'>
|
|
77
|
+
|
|
78
|
+
export type VerifyEmailResult = LinkResult | AuthFailed<'confirm'>
|
|
79
|
+
|
|
80
|
+
export type ResetPasswordResult = LinkResult | AuthRejected<{ password: PasswordProblem | 'breached' }>
|
|
81
|
+
|
|
82
|
+
export type ChangeEmailResult = { ok: true } | AuthFailed<ProofFailure | 'unavailable'> | AuthRejected<{ email: EmailProblem | 'taken' | 'unchanged' }>
|
|
83
|
+
|
|
84
|
+
export type SendVerificationResult = MailRequestResult | AuthFailed<'signed-out' | 'verified'>
|
|
85
|
+
|
|
86
|
+
// Mails a new verification link to the signed-in user or, with nobody signed in, off the response's path to the account this browser registered or proved the password of.
|
|
87
|
+
export async function sendVerification(state: RequestState): Promise<SendVerificationResult> {
|
|
88
|
+
const current = await state.current()
|
|
89
|
+
const registered = current ? undefined : await state.session.get('authRegistered')
|
|
90
|
+
const record = current ?? (registered === undefined ? undefined : await state.core.store.users.get(registered))
|
|
91
|
+
// Registered here for an address another account holds: answered as a new account's resend is, mailing no one.
|
|
92
|
+
const held = record ? undefined : await state.session.get('authHeld')
|
|
93
|
+
const email = record?.email ?? held
|
|
94
|
+
|
|
95
|
+
if (email == null || email === '')
|
|
96
|
+
return failed('signed-out')
|
|
97
|
+
|
|
98
|
+
if (record && record.emailVerifiedAt !== null)
|
|
99
|
+
return failed('verified')
|
|
100
|
+
|
|
101
|
+
if (!state.core.email)
|
|
102
|
+
return failed('unavailable')
|
|
103
|
+
|
|
104
|
+
const refused = await spendResend(state, record?.id ?? typedKey(state.core, 'held', email), 'resend')
|
|
105
|
+
|
|
106
|
+
if (refused)
|
|
107
|
+
return refused
|
|
108
|
+
|
|
109
|
+
const nonce = await bindCode(state, 'verify-email', email)
|
|
110
|
+
const back = await state.session.get('authBack') ?? null
|
|
111
|
+
|
|
112
|
+
// The signed-in user's own address tells nothing, so a failing mailer fails the call.
|
|
113
|
+
if (current)
|
|
114
|
+
await issue(state, current, 'verify-email', email, back, nonce)
|
|
115
|
+
else if (record)
|
|
116
|
+
trackDetached(issueQuietly(state, record, 'verify-email', email, back, nonce))
|
|
117
|
+
|
|
118
|
+
return { ok: true }
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Verifies the address for the browser signed in as the account, the one that registered it or the one that proved its password; any other must give the account's password, since whoever opens the mail may be confirming an account a stranger registered with their address, which verified would stay the stranger's.
|
|
122
|
+
// Never signs in. Refused, the link stays usable where it can be confirmed.
|
|
123
|
+
export async function verifyEmail(state: RequestState, token: string, password?: string): Promise<VerifyEmailResult> {
|
|
124
|
+
const spent = await spendLink(state, token, 'verify-email')
|
|
125
|
+
|
|
126
|
+
if (!spent.ok)
|
|
127
|
+
return spent
|
|
128
|
+
|
|
129
|
+
const { record } = spent
|
|
130
|
+
const current = await state.current()
|
|
131
|
+
const ours = current?.id === record.id || await state.session.get('authRegistered') === record.id
|
|
132
|
+
|
|
133
|
+
if (!ours) {
|
|
134
|
+
const proved = await holdsPassword(state, record, password)
|
|
135
|
+
|
|
136
|
+
if (proved !== true) {
|
|
137
|
+
await state.core.store.tokens.create(spent.token)
|
|
138
|
+
|
|
139
|
+
return failed(proved)
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
await dropCode(state, record, 'verify-email')
|
|
144
|
+
await state.core.store.users.update(record.id, { emailVerifiedAt: new Date() })
|
|
145
|
+
|
|
146
|
+
return { ok: true, redirect: afterVerifying(state, current?.id === record.id, spent.token.redirect) }
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// Where the browser goes once an address is verified: on to the page the visitor asked for when signed in, else to sign in and then to it.
|
|
150
|
+
function afterVerifying(state: RequestState, signedIn: boolean, back: string | null): string {
|
|
151
|
+
const home = homeOf(state.core)
|
|
152
|
+
const page = backOf(state.core, back)
|
|
153
|
+
|
|
154
|
+
if (signedIn)
|
|
155
|
+
return page ?? home
|
|
156
|
+
|
|
157
|
+
return page === null ? state.core.signInPage : withBack(state.core.signInPage, page)
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// Counted as a sign-in attempt on the account, since it is one.
|
|
161
|
+
async function holdsPassword(state: RequestState, record: UserRecord, password: string | undefined): Promise<true | 'confirm' | 'limited'> {
|
|
162
|
+
if (password === undefined)
|
|
163
|
+
return 'confirm'
|
|
164
|
+
|
|
165
|
+
const guess = await startGuess(state, record, '')
|
|
166
|
+
|
|
167
|
+
if (guess === 'limited')
|
|
168
|
+
return 'limited'
|
|
169
|
+
|
|
170
|
+
// An account without a password is checked against a decoy, so the time does not tell it has none.
|
|
171
|
+
if (!await passwordMatches(record, password)) {
|
|
172
|
+
await failGuess(state, guess)
|
|
173
|
+
|
|
174
|
+
return 'confirm'
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
await forgive(state, guess)
|
|
178
|
+
|
|
179
|
+
return true
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export async function requestPasswordReset(state: RequestState, email: string, captcha?: string, redirect?: string): Promise<MailRequestResult> {
|
|
183
|
+
return mailByAddress(state, email, 'reset-password', backOf(state.core, redirect), captcha)
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// Sets the password the link was sent for and ends every other session the user held.
|
|
187
|
+
export async function resetPassword(state: RequestState, token: string, password: string): Promise<ResetPasswordResult> {
|
|
188
|
+
// Counted before the breached-password service is asked, so forged links cannot make the server call it without end.
|
|
189
|
+
if (await spend(state.core.rates, `link:${state.client}`, state.core.limits.link))
|
|
190
|
+
return failed('limited')
|
|
191
|
+
|
|
192
|
+
const problem = await newPasswordProblem(state.core, password)
|
|
193
|
+
|
|
194
|
+
// Checked before the token is spent, so a refused password leaves the link usable.
|
|
195
|
+
if (problem !== undefined)
|
|
196
|
+
return rejected({ password: problem })
|
|
197
|
+
|
|
198
|
+
const spent = await spendLink(state, token, 'reset-password', true)
|
|
199
|
+
|
|
200
|
+
if (!spent.ok)
|
|
201
|
+
return spent
|
|
202
|
+
|
|
203
|
+
// Before the password changes: a banned user keeps the account as the admin left it.
|
|
204
|
+
if (banned(spent.record))
|
|
205
|
+
return failed('banned')
|
|
206
|
+
|
|
207
|
+
const { store } = state.core
|
|
208
|
+
const record = await store.users.update(spent.record.id, {
|
|
209
|
+
...await claim(state.core, spent.record),
|
|
210
|
+
passwordHash: await hashPassword(password),
|
|
211
|
+
// The mail reached that inbox, so the address is proved too.
|
|
212
|
+
emailVerifiedAt: spent.record.emailVerifiedAt ?? new Date(),
|
|
213
|
+
sessionVersion: spent.record.sessionVersion + 1,
|
|
214
|
+
}) ?? spent.record
|
|
215
|
+
|
|
216
|
+
// Recovering an account ends every way into it the user did not just prove, devices included.
|
|
217
|
+
await store.tokens.erase(record.id)
|
|
218
|
+
await revokeBearerTokens(state.core, record.id)
|
|
219
|
+
await securityNotice(state, record, 'password-changed')
|
|
220
|
+
|
|
221
|
+
return state.complete(record, spent.token.redirect ?? homeOf(state.core), 'reset-password')
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export async function requestMagicLink(state: RequestState, email: string, redirect?: string, captcha?: string): Promise<MailRequestResult> {
|
|
225
|
+
return mailByAddress(state, email, 'magic-link', localPath(redirect, homeOf(state.core)), captcha)
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
export async function signInWithMagicLink(state: RequestState, token: string): Promise<LinkResult> {
|
|
229
|
+
const spent = await spendLink(state, token, 'magic-link')
|
|
230
|
+
|
|
231
|
+
if (!spent.ok)
|
|
232
|
+
return spent
|
|
233
|
+
|
|
234
|
+
await dropCode(state, spent.record, 'magic-link')
|
|
235
|
+
|
|
236
|
+
const record = spent.record.emailVerifiedAt === null
|
|
237
|
+
? await state.core.store.users.update(spent.record.id, { ...await claim(state.core, spent.record), emailVerifiedAt: new Date() }) ?? spent.record
|
|
238
|
+
: spent.record
|
|
239
|
+
|
|
240
|
+
// The browser opening the link signs in as the one that asked for it chose, which a link opened elsewhere would otherwise lose.
|
|
241
|
+
if (spent.remember !== undefined)
|
|
242
|
+
await state.session.set('authRemember', spent.remember)
|
|
243
|
+
|
|
244
|
+
return state.complete(record, spent.token.redirect ?? homeOf(state.core), 'magic-link')
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// Mails the new address a link confirming it; the account keeps the old one until then.
|
|
248
|
+
export async function changeEmail(state: RequestState, proof: Proof, email: string): Promise<ChangeEmailResult> {
|
|
249
|
+
const proved = await reprove(state, proof, { secondFactor: true })
|
|
250
|
+
|
|
251
|
+
if (!proved.ok)
|
|
252
|
+
return proved
|
|
253
|
+
|
|
254
|
+
const { record } = proved
|
|
255
|
+
const address = normalizeEmail(email)
|
|
256
|
+
const problem = emailProblem(address)
|
|
257
|
+
|
|
258
|
+
if (problem)
|
|
259
|
+
return rejected({ email: problem })
|
|
260
|
+
|
|
261
|
+
if (address === record.email)
|
|
262
|
+
return rejected({ email: 'unchanged' })
|
|
263
|
+
|
|
264
|
+
if (await state.core.store.users.findByEmail(address))
|
|
265
|
+
return rejected({ email: 'taken' })
|
|
266
|
+
|
|
267
|
+
const sent = await mailFor(state, record, 'change-email', address, null)
|
|
268
|
+
|
|
269
|
+
// The address the account is leaving hears of it now, while its owner can still react, not only once the new one confirms.
|
|
270
|
+
if (sent.ok)
|
|
271
|
+
await securityNotice(state, record, 'email-change-requested', address)
|
|
272
|
+
|
|
273
|
+
return sent
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// Moves the account to the address the link was sent to, and ends the user's other sessions.
|
|
277
|
+
export async function confirmEmailChange(state: RequestState, token: string): Promise<LinkResult> {
|
|
278
|
+
const spent = await spendLink(state, token, 'change-email')
|
|
279
|
+
|
|
280
|
+
if (!spent.ok)
|
|
281
|
+
return spent
|
|
282
|
+
|
|
283
|
+
const { store } = state.core
|
|
284
|
+
|
|
285
|
+
if (await store.users.findByEmail(spent.token.email))
|
|
286
|
+
return failed('invalid')
|
|
287
|
+
|
|
288
|
+
let record: UserRecord | undefined
|
|
289
|
+
|
|
290
|
+
try {
|
|
291
|
+
record = await endOtherSessions(state, spent.record, { email: spent.token.email, emailVerifiedAt: new Date() })
|
|
292
|
+
}
|
|
293
|
+
// Another request took the address between the read and the write; any other failure is the store's.
|
|
294
|
+
catch (error) {
|
|
295
|
+
const taker = await store.users.findByEmail(spent.token.email)
|
|
296
|
+
|
|
297
|
+
if (taker && taker.id !== spent.record.id)
|
|
298
|
+
return failed('invalid')
|
|
299
|
+
|
|
300
|
+
throw error
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
if (!record)
|
|
304
|
+
return failed('invalid')
|
|
305
|
+
|
|
306
|
+
await store.tokens.erase(record.id)
|
|
307
|
+
// To the address the account left, which is the one a thief would want silent.
|
|
308
|
+
await securityNotice(state, record, 'email-changed', record.email!, spent.record.emailVerifiedAt === null ? null : spent.record.email)
|
|
309
|
+
|
|
310
|
+
return { ok: true, redirect: homeOf(state.core) }
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// On registering: the verification mail, when the app sends mail.
|
|
314
|
+
export async function welcome(state: RequestState, record: UserRecord, back: string | null): Promise<void> {
|
|
315
|
+
if (state.core.email && record.email !== null && record.email !== '')
|
|
316
|
+
trackDetached(issueQuietly(state, record, 'verify-email', record.email, back, await bindCode(state, 'verify-email', record.email)))
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// A registration for an address an account holds already, where registering signs no one in: this session is left as a new account's would be, and the holder is told, off the response's path and at most a few times an hour.
|
|
320
|
+
export async function warnHolder(state: RequestState, holder: UserRecord): Promise<void> {
|
|
321
|
+
const { core } = state
|
|
322
|
+
const mail = core.email
|
|
323
|
+
const email = holder.email
|
|
324
|
+
|
|
325
|
+
if (!mail || email === null || email === '')
|
|
326
|
+
return
|
|
327
|
+
|
|
328
|
+
await bindCode(state, 'verify-email', email)
|
|
329
|
+
|
|
330
|
+
if (await spend(core.rates, `account-exists:${holder.id}`, core.limits.resendAccount))
|
|
331
|
+
return
|
|
332
|
+
|
|
333
|
+
const { locale, templates } = writing(mail, [holder.locale, ...state.languages])
|
|
334
|
+
const url = `${core.url}${core.signInPage}`
|
|
335
|
+
|
|
336
|
+
sendAside(mail, () => ({ to: email, kind: 'account-exists', name: core.name, locale, url, ...templates['account-exists']({ name: core.name, email, url, locale }) }), 'account-exists')
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// Signs in with the code a magic link mail carried, in the session that asked for it.
|
|
340
|
+
export async function signInWithEmailCode(state: RequestState, code: string): Promise<CodeResult> {
|
|
341
|
+
const spent = await spendCode(state, 'sign-in-code', code)
|
|
342
|
+
|
|
343
|
+
if (!spent.ok)
|
|
344
|
+
return spent
|
|
345
|
+
|
|
346
|
+
const record = spent.record.emailVerifiedAt === null
|
|
347
|
+
? await state.core.store.users.update(spent.record.id, { ...await claim(state.core, spent.record), emailVerifiedAt: new Date() }) ?? spent.record
|
|
348
|
+
: spent.record
|
|
349
|
+
|
|
350
|
+
return state.complete(record, spent.token.redirect ?? homeOf(state.core), 'email-code')
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// Verifies the address with the code its verification mail carried, in the session that asked for it, which registered the account or is signed in as it.
|
|
354
|
+
export async function verifyEmailCode(state: RequestState, code: string): Promise<CodeResult> {
|
|
355
|
+
const spent = await spendCode(state, 'verify-code', code)
|
|
356
|
+
|
|
357
|
+
if (!spent.ok)
|
|
358
|
+
return spent
|
|
359
|
+
|
|
360
|
+
await state.core.store.users.update(spent.record.id, { emailVerifiedAt: new Date() })
|
|
361
|
+
|
|
362
|
+
return { ok: true, redirect: afterVerifying(state, (await state.current())?.id === spent.record.id, spent.token.redirect) }
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
export type PendingEmailCode = { type: 'sign-in' | 'verify', email: string } | null
|
|
366
|
+
|
|
367
|
+
// The code this session waits for, for the page that asks for it.
|
|
368
|
+
export async function pendingCode(state: RequestState): Promise<PendingEmailCode> {
|
|
369
|
+
const pending = await state.session.get('authEmailCode')
|
|
370
|
+
|
|
371
|
+
if (!pending || pending.expires < Date.now())
|
|
372
|
+
return null
|
|
373
|
+
|
|
374
|
+
return { type: pending.type === 'sign-in-code' ? 'sign-in' : 'verify', email: pending.email }
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
// Parks the code a mail is about to carry in this session, answering the nonce bound into it; undefined when the app sends links only.
|
|
378
|
+
async function bindCode(state: RequestState, type: LinkType, email: string): Promise<string | undefined> {
|
|
379
|
+
if (!(type in CODE_OF) || state.core.email?.codes[type as CodedLink] === 'link')
|
|
380
|
+
return undefined
|
|
381
|
+
|
|
382
|
+
const nonce = randomToken()
|
|
383
|
+
const codeType = CODE_OF[type as CodedLink]
|
|
384
|
+
|
|
385
|
+
await state.session.set('authEmailCode', { type: codeType, email, nonce, expires: Date.now() + state.core.email!.maxAge[codeType] * 1000 })
|
|
386
|
+
|
|
387
|
+
return nonce
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
// Spends the code this session waits for; a code dies after a few misses, and the guesses count per client and per address.
|
|
391
|
+
async function spendCode(state: RequestState, type: CodeType, code: string) {
|
|
392
|
+
const { core } = state
|
|
393
|
+
const pending = await state.session.get('authEmailCode')
|
|
394
|
+
|
|
395
|
+
if (!pending || pending.type !== type || pending.expires < Date.now())
|
|
396
|
+
return failed('expired')
|
|
397
|
+
|
|
398
|
+
if (await spend(core.rates, `email-code:${state.client}`, core.limits.emailCode) || await spend(core.rates, typedKey(core, 'email-code', pending.email), core.limits.emailCodeAccount))
|
|
399
|
+
return failed('limited')
|
|
400
|
+
|
|
401
|
+
const spent = await core.store.tokens.consume(codeDigest(state.core, pending.nonce, code.replace(NOT_DIGITS, '')), type)
|
|
402
|
+
const record = spent && await core.store.users.get(spent.userId)
|
|
403
|
+
|
|
404
|
+
if (!spent || !record || record.email !== spent.email) {
|
|
405
|
+
if ((await core.rates(windowOf(core.email!.maxAge[type] * 1000)).hit(`email-code-miss:${pending.nonce}`)).count < CODE_MISSES)
|
|
406
|
+
return failed('invalid')
|
|
407
|
+
|
|
408
|
+
// Only this session's pending code is dropped: the holder's live code may be one another session asked for, and it is unreachable from here anyway, since its digest binds that session's nonce.
|
|
409
|
+
await state.session.unset('authEmailCode')
|
|
410
|
+
|
|
411
|
+
return failed('expired')
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
await state.session.unset('authEmailCode')
|
|
415
|
+
// The link the same mail carried is spent with it.
|
|
416
|
+
await core.store.tokens.erase(record.id, LINK_OF[type])
|
|
417
|
+
|
|
418
|
+
return { ok: true, token: spent, record } as const
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// Keyed, since six digits are no secret to whoever reads a plain digest out of the store.
|
|
422
|
+
function codeDigest(core: Core, nonce: string, code: string): string {
|
|
423
|
+
return core.keys.fingerprint(`email-code\n${nonce}\n${code}`)
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
// Counted by address whether or not an account has it, and mailed off the response's path, so neither the answer nor its time tells which addresses exist.
|
|
427
|
+
async function mailByAddress(state: RequestState, email: string, type: 'reset-password' | 'magic-link', redirect: string | null, captcha: string | undefined): Promise<MailRequestResult> {
|
|
428
|
+
const { core } = state
|
|
429
|
+
|
|
430
|
+
if (!core.email)
|
|
431
|
+
return failed('unavailable')
|
|
432
|
+
|
|
433
|
+
const address = normalizeEmail(email)
|
|
434
|
+
const limit = type === 'magic-link' ? 'magicLink' : 'forgot'
|
|
435
|
+
const refused = await admit(state, type === 'magic-link' ? 'magic-link' : 'reset', captcha)
|
|
436
|
+
|
|
437
|
+
if (refused)
|
|
438
|
+
return failed(refused)
|
|
439
|
+
|
|
440
|
+
if (await spend(core.rates, typedKey(core, limit, address), core.limits[`${limit}Account`]))
|
|
441
|
+
return failed('limited')
|
|
442
|
+
|
|
443
|
+
// Parked whether or not an account has the address, so this session looks the same either way.
|
|
444
|
+
const nonce = await bindCode(state, type, address)
|
|
445
|
+
const record = emailProblem(address) ? undefined : await core.store.users.findByEmail(address)
|
|
446
|
+
|
|
447
|
+
if (record)
|
|
448
|
+
trackDetached(issueQuietly(state, record, type, address, redirect, nonce))
|
|
449
|
+
|
|
450
|
+
return { ok: true }
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// Off the response's path, where no one is left to answer a failure to: logged.
|
|
454
|
+
async function issueQuietly(state: RequestState, record: UserRecord, type: LinkType, email: string, redirect: string | null, nonce: string | undefined): Promise<void> {
|
|
455
|
+
try {
|
|
456
|
+
await issue(state, record, type, email, redirect, nonce)
|
|
457
|
+
}
|
|
458
|
+
catch (error) {
|
|
459
|
+
log.error(`mailing a ${type} link failed`, error)
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
async function mailFor(state: RequestState, record: UserRecord, type: LinkType, email: string, redirect: string | null): Promise<{ ok: true } | AuthFailed<'limited' | 'unavailable'>> {
|
|
464
|
+
const { core } = state
|
|
465
|
+
|
|
466
|
+
if (!core.email)
|
|
467
|
+
return failed('unavailable')
|
|
468
|
+
|
|
469
|
+
const refused = await spendResend(state, record.id, 'emailChange')
|
|
470
|
+
|
|
471
|
+
if (refused)
|
|
472
|
+
return refused
|
|
473
|
+
|
|
474
|
+
await issue(state, record, type, email, redirect, await bindCode(state, type, email))
|
|
475
|
+
|
|
476
|
+
return { ok: true }
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
// Counted per client and per account, so neither one sender nor many can flood an inbox.
|
|
480
|
+
async function spendResend(state: RequestState, id: string, limit: 'resend' | 'emailChange'): Promise<AuthFailed<'limited'> | undefined> {
|
|
481
|
+
const { core } = state
|
|
482
|
+
|
|
483
|
+
if (await spend(core.rates, `${limit}:${state.client}`, core.limits[limit]) || await spend(core.rates, `${limit}:${id}`, core.limits[`${limit}Account`]))
|
|
484
|
+
return failed('limited')
|
|
485
|
+
|
|
486
|
+
return undefined
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
// How long the link and the code of a mail work, for the ones it carries.
|
|
490
|
+
function lifetimesOf(mail: EmailCore, type: LinkType, content: { url?: string, code?: string }): MailData['maxAge'] {
|
|
491
|
+
return { ...content.url === undefined ? {} : { link: `${mail.maxAge[type]}s` }, ...content.code === undefined ? {} : { code: `${mail.maxAge[CODE_OF[type as CodedLink]]}s` } }
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
// One live link and code per kind and user: a new one replaces the last. A code goes only with the nonce of the session that asked for it.
|
|
495
|
+
// Written in the user's language, else the browser's.
|
|
496
|
+
async function issue(state: RequestState, record: UserRecord, type: LinkType, email: string, redirect: string | null, nonce: string | undefined): Promise<void> {
|
|
497
|
+
const { core } = state
|
|
498
|
+
const mail = core.email!
|
|
499
|
+
const mode = type in CODE_OF ? mail.codes[type as CodedLink] : 'link'
|
|
500
|
+
const content: { url?: string, code?: string } = {}
|
|
501
|
+
|
|
502
|
+
await core.store.tokens.erase(record.id, type)
|
|
503
|
+
|
|
504
|
+
if (mode !== 'code') {
|
|
505
|
+
const token = randomToken() + await rememberMark(state, type)
|
|
506
|
+
|
|
507
|
+
content.url = `${core.url}${mail.links[type]}?token=${token}`
|
|
508
|
+
await core.store.tokens.create({ digest: digest(type === 'magic-link' ? unmarked(token) : token), type, userId: record.id, email, redirect, expiresAt: new Date(Date.now() + mail.maxAge[type] * 1000) })
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
if (mode !== 'link' && nonce !== undefined) {
|
|
512
|
+
const codeType = CODE_OF[type as CodedLink]
|
|
513
|
+
const code = nanoid(CODE_LENGTH, DIGITS)
|
|
514
|
+
|
|
515
|
+
content.code = code
|
|
516
|
+
await core.store.tokens.erase(record.id, codeType)
|
|
517
|
+
await core.store.tokens.create({ digest: codeDigest(core, nonce, code), type: codeType, userId: record.id, email, redirect, expiresAt: new Date(Date.now() + mail.maxAge[codeType] * 1000) })
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
const { locale, templates } = writing(mail, [record.locale, ...state.languages])
|
|
521
|
+
|
|
522
|
+
const maxAge = lifetimesOf(mail, type, content)
|
|
523
|
+
|
|
524
|
+
await mail.mailer.send({ to: email, kind: type, name: core.name, locale, ...content, maxAge, ...templates[type]({ name: core.name, email, locale, ...content, maxAge }) })
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
// The code the same mail carried is spent with its link, once the link is used: a link refused leaves both.
|
|
528
|
+
async function dropCode(state: RequestState, record: UserRecord, type: CodedLink): Promise<void> {
|
|
529
|
+
await state.core.store.tokens.erase(record.id, CODE_OF[type])
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
// The token's user, once the token is spent; a link for an address the account no longer has is spent for nothing.
|
|
533
|
+
async function spendLink(state: RequestState, token: string, type: LinkType, counted = false) {
|
|
534
|
+
const { store, limits } = state.core
|
|
535
|
+
|
|
536
|
+
if (!counted && await spend(state.core.rates, `link:${state.client}`, limits.link))
|
|
537
|
+
return failed('limited')
|
|
538
|
+
|
|
539
|
+
const spent = await store.tokens.consume(digest(type === 'magic-link' ? unmarked(token) : token), type)
|
|
540
|
+
const record = spent && await store.users.get(spent.userId)
|
|
541
|
+
|
|
542
|
+
if (!spent || !record || (type !== 'change-email' && record.email !== spent.email))
|
|
543
|
+
return failed('invalid')
|
|
544
|
+
|
|
545
|
+
return { ok: true, token: spent, record, remember: type === 'magic-link' ? rememberOf(token) : undefined } as const
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// A magic link carries the remember choice of the browser that asked for it as a suffix of its token, so the browser opening it, perhaps another, signs in as chosen. The store keeps the digest of the token without it; stripping or adding one changes only the link holder's own session.
|
|
549
|
+
const REMEMBER_MARK = '.r'
|
|
550
|
+
const FORGET_MARK = '.b'
|
|
551
|
+
|
|
552
|
+
async function rememberMark(state: RequestState, type: LinkType): Promise<string> {
|
|
553
|
+
if (type !== 'magic-link')
|
|
554
|
+
return ''
|
|
555
|
+
|
|
556
|
+
const remember = await state.session.get('authRemember')
|
|
557
|
+
|
|
558
|
+
if (remember === undefined)
|
|
559
|
+
return ''
|
|
560
|
+
|
|
561
|
+
return remember ? REMEMBER_MARK : FORGET_MARK
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
function unmarked(token: string): string {
|
|
565
|
+
return token.endsWith(REMEMBER_MARK) || token.endsWith(FORGET_MARK) ? token.slice(0, -2) : token
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
function rememberOf(token: string): boolean | undefined {
|
|
569
|
+
if (token.endsWith(REMEMBER_MARK))
|
|
570
|
+
return true
|
|
571
|
+
|
|
572
|
+
if (token.endsWith(FORGET_MARK))
|
|
573
|
+
return false
|
|
574
|
+
|
|
575
|
+
return undefined
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
// An address proved for the first time by a link its owner asked for: whatever was set on the account before, perhaps by a stranger who registered the address first, is dropped, so the owner gets the account clean.
|
|
579
|
+
async function claim(core: Core, record: UserRecord): Promise<Partial<UserRecord>> {
|
|
580
|
+
if (record.emailVerifiedAt !== null)
|
|
581
|
+
return {}
|
|
582
|
+
|
|
583
|
+
await removeIdentities(core, record.id)
|
|
584
|
+
|
|
585
|
+
for (const passkey of await core.store.passkeys.listByUser(record.id))
|
|
586
|
+
await core.store.passkeys.delete(record.id, passkey.id)
|
|
587
|
+
|
|
588
|
+
await core.store.recoveryCodes.replace(record.id, [])
|
|
589
|
+
await revokeBearerTokens(core, record.id)
|
|
590
|
+
// A link the stranger asked for before, such as moving the account to their own address, would take it back.
|
|
591
|
+
await core.store.tokens.erase(record.id)
|
|
592
|
+
|
|
593
|
+
return { passwordHash: null, totpSecret: null, totpEnabledAt: null, sessionVersion: record.sessionVersion + 1 }
|
|
594
|
+
}
|