@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
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { BareUser, Core, SignedIn } from './core'
|
|
2
|
+
import type { RequestState } from './state'
|
|
3
|
+
import type { PolicyContext } from './types'
|
|
4
|
+
import { localPath } from 'kay'
|
|
5
|
+
import { isNavigation, withBack } from './core'
|
|
6
|
+
|
|
7
|
+
export interface TwoFactorAsk {
|
|
8
|
+
// true asks every user, as a guard's own `twoFactor: true`; else the `twoFactor.require` of the app decides by the user's roles.
|
|
9
|
+
wanted?: true | undefined
|
|
10
|
+
// The path asked for: the security page, the second-factor page and the sign-out route are never held back, so a user lacking two-factor can always turn it on.
|
|
11
|
+
path?: string | undefined
|
|
12
|
+
// The locale the page is served in, whose prefix the path may carry.
|
|
13
|
+
locale?: string | undefined
|
|
14
|
+
ctx?: PolicyContext | undefined
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// The pages and routes a user lacking two-factor must still reach: exactly those paths, bare or under the prefix of the locale being served, never a route that merely ends like one.
|
|
18
|
+
function exempt(core: Core, path: string, locale?: string): boolean {
|
|
19
|
+
const bare = withoutSlash(path)
|
|
20
|
+
|
|
21
|
+
// The locale is matched as kay's routing matches it, the segment equal to the tag.
|
|
22
|
+
return [core.securityPage, core.twoFactorPage, `${core.prefix}/sign-out`].some((given) => {
|
|
23
|
+
const page = given === undefined ? undefined : withoutSlash(given)
|
|
24
|
+
|
|
25
|
+
return page !== undefined && (bare === page || (locale !== undefined && bare === `/${locale}${page}`))
|
|
26
|
+
})
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// A path with no trailing slash, whether the site serves its pages with one or not.
|
|
30
|
+
function withoutSlash(path: string): string {
|
|
31
|
+
return path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Whether the second factor is satisfied: it is on, or the sign-in was a passkey (user verification makes it two factors), or an admin acting as the user, who proved theirs to start.
|
|
35
|
+
function satisfied(user: BareUser, signedIn: SignedIn | undefined): boolean {
|
|
36
|
+
return user.twoFactor || signedIn?.passkey === true || signedIn?.impersonator !== undefined
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Whether `user` must have two-factor and does not. A guest and a session or OAuth sign-in with no authenticator app lack it; a throwing predicate in `twoFactor.require` throws, so the request fails closed. Off with `twoFactor: false`.
|
|
40
|
+
export async function lacksTwoFactor(state: RequestState, user: BareUser, ask: TwoFactorAsk = {}): Promise<boolean> {
|
|
41
|
+
const { core } = state
|
|
42
|
+
|
|
43
|
+
if (!core.switches.twoFactor || user.twoFactor || (ask.path !== undefined && exempt(core, ask.path, ask.locale)))
|
|
44
|
+
return false
|
|
45
|
+
|
|
46
|
+
if (satisfied(user, await state.session.get('auth')))
|
|
47
|
+
return false
|
|
48
|
+
|
|
49
|
+
if (ask.wanted === true)
|
|
50
|
+
return true
|
|
51
|
+
|
|
52
|
+
return core.twoFactorRequire !== undefined && core.access.authorize(user, core.twoFactorRequire, 'write', ask.ctx ?? {})
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// What `ctx.redirect` and `ctx.deny` are in a guard, a page or an action.
|
|
56
|
+
export interface Stoppers {
|
|
57
|
+
redirect: (location: string) => never
|
|
58
|
+
deny: (status?: number, message?: string) => never
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// A page opening goes to the security page to turn two-factor on, coming back after; anything else, and an app with no such page, gets the 403.
|
|
62
|
+
export function sendToEnrolment(core: Core, request: Request, { redirect, deny }: Stoppers): never {
|
|
63
|
+
if (core.securityPage !== undefined && isNavigation(request)) {
|
|
64
|
+
const here = new URL(request.url)
|
|
65
|
+
|
|
66
|
+
// kay-allow external-redirect: the app's own security page, the visited path rides in its query
|
|
67
|
+
redirect(withBack(core.securityPage, localPath(here.pathname + here.search, '/')))
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
return deny(403, 'Two-factor authentication is required')
|
|
71
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { PolicyContext, Requirement } from './types'
|
|
2
|
+
|
|
3
|
+
/** Whether any rule of a requirement passes: an array passes on any entry, a predicate on its answer, and a grant on what `granted` says of it. */
|
|
4
|
+
export async function meetsRequirement<P, G extends string>(
|
|
5
|
+
principal: P,
|
|
6
|
+
requirement: Requirement<P, G>,
|
|
7
|
+
ctx: PolicyContext,
|
|
8
|
+
granted: (grant: Exclude<Requirement<P, G>, ((...args: never[]) => unknown) | unknown[]>) => boolean | Promise<boolean>,
|
|
9
|
+
): Promise<boolean> {
|
|
10
|
+
if (Array.isArray(requirement)) {
|
|
11
|
+
for (const rule of requirement) {
|
|
12
|
+
if (await meetsRequirement(principal, rule, ctx, granted))
|
|
13
|
+
return true
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
return false
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
if (typeof requirement === 'function')
|
|
20
|
+
return Boolean(await requirement(principal, ctx))
|
|
21
|
+
|
|
22
|
+
return granted(requirement as Parameters<typeof granted>[0])
|
|
23
|
+
}
|
package/src/roles.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Predicate, Principal } from './types'
|
|
2
|
+
import { declareIsGranted } from '@kaynooo/utils'
|
|
3
|
+
|
|
4
|
+
/** Parent role -> the roles it inherits (Symfony-style role hierarchy). */
|
|
5
|
+
export type RoleHierarchy<R extends string> = Record<R, R[]>
|
|
6
|
+
|
|
7
|
+
/** Role-hierarchy checker plus a `Requirement` bridge: `isGranted` walks the hierarchy, `hasRole` wraps it as a `Predicate` for `auth:`. `getRoles` projects a principal's roles. */
|
|
8
|
+
export function roleHierarchy<P, R extends string>(
|
|
9
|
+
hierarchy: RoleHierarchy<R>,
|
|
10
|
+
getRoles: (principal: P) => R[],
|
|
11
|
+
) {
|
|
12
|
+
const isGranted = declareIsGranted(hierarchy)
|
|
13
|
+
|
|
14
|
+
const hasRole = (required: R): Predicate<P> =>
|
|
15
|
+
(principal: Principal<P>) => principal != null && isGranted(required, getRoles(principal))
|
|
16
|
+
|
|
17
|
+
return { isGranted, hasRole }
|
|
18
|
+
}
|
package/src/routes.ts
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import type { Elysia } from 'elysia'
|
|
2
|
+
import type { Core } from './core'
|
|
3
|
+
import type { OAuthFailure } from './oauth/flow'
|
|
4
|
+
import type { Auth } from './request'
|
|
5
|
+
import { localPath } from 'kay'
|
|
6
|
+
import { configError, keepCookiesPrivate, underKayDev } from 'kay/library'
|
|
7
|
+
import { crossSiteResponse } from 'kay/server'
|
|
8
|
+
import { rootUsable } from './authorize/metadata'
|
|
9
|
+
import { serveOAuthServer } from './authorize/routes'
|
|
10
|
+
import { backOf, homeOf, withBack, withQuery } from './core'
|
|
11
|
+
import { returnTarget } from './forwardAuth'
|
|
12
|
+
import { load } from './load'
|
|
13
|
+
import { STATE, TAKE_COOKIES } from './request'
|
|
14
|
+
|
|
15
|
+
// Where `kay dev` answers the dev tool's Auth tab with the session's user.
|
|
16
|
+
const DEV_PATH = '/_kay/auth'
|
|
17
|
+
// What a provider posting back to the callback may say, carried over to the GET.
|
|
18
|
+
const FORM_POST_FIELDS = ['code', 'state', 'error', 'user']
|
|
19
|
+
const UNSAFE_FILE_NAME = /[^\w.-]/g
|
|
20
|
+
|
|
21
|
+
// What the routes read of Elysia's context.
|
|
22
|
+
interface RouteContext {
|
|
23
|
+
auth: Pick<Auth, typeof STATE | 'account' | 'signOut' | 'admin'>
|
|
24
|
+
request: Request
|
|
25
|
+
body: unknown
|
|
26
|
+
query: Record<string, unknown>
|
|
27
|
+
params: Record<string, string | undefined>
|
|
28
|
+
set: { headers: Record<string, unknown> }
|
|
29
|
+
redirect: (url: string, status: 303) => Response
|
|
30
|
+
status: (code: 401 | 403 | 404 | 429, body: string) => unknown
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// A query value as text: a name repeated in the URL arrives as a list, which no flow takes.
|
|
34
|
+
function text(value: unknown): string | undefined {
|
|
35
|
+
return typeof value === 'string' ? value : undefined
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Where a failed OAuth sign-in goes: the sign-in page with why, keeping the page the visitor asked for, so they come back to it once they sign in another way; the `failurePage` the app gave instead, saying nothing.
|
|
39
|
+
function failed(core: Core, failurePage: string | undefined, error: OAuthFailure, redirect?: string | null): string {
|
|
40
|
+
const back = backOf(core, redirect)
|
|
41
|
+
const page = withQuery(core.signInPage, `error=${error}`)
|
|
42
|
+
|
|
43
|
+
return failurePage ?? (back === null ? page : withBack(page, back))
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// The cookies a sign-in or a sign-out adds, on the response the route built or on Elysia's own, as the session plugin's cookie is.
|
|
47
|
+
export function sendCookies(context: { set: { headers: Record<string, unknown> } }): void {
|
|
48
|
+
const cookies = (context as unknown as { auth?: Auth }).auth?.[TAKE_COOKIES]() ?? []
|
|
49
|
+
|
|
50
|
+
if (cookies.length === 0)
|
|
51
|
+
return
|
|
52
|
+
|
|
53
|
+
const response = (context as { responseValue?: unknown }).responseValue
|
|
54
|
+
|
|
55
|
+
if (response instanceof Response) {
|
|
56
|
+
for (const cookie of cookies)
|
|
57
|
+
response.headers.append('set-cookie', cookie)
|
|
58
|
+
|
|
59
|
+
keepCookiesPrivate(context.set, response)
|
|
60
|
+
|
|
61
|
+
return
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
context.set.headers['set-cookie'] = [context.set.headers['set-cookie'] ?? []].flat().concat(cookies)
|
|
65
|
+
keepCookiesPrivate(context.set)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// The signed-in user's data as a JSON download, linked from their account page.
|
|
69
|
+
export async function exportRoute({ auth, set, status }: RouteContext, core: Core) {
|
|
70
|
+
const exported = await auth.account.export()
|
|
71
|
+
|
|
72
|
+
if (!exported.ok) {
|
|
73
|
+
if (exported.error.code === 'limited')
|
|
74
|
+
return status(429, 'Too many exports; try again later')
|
|
75
|
+
|
|
76
|
+
if (exported.error.code === 'impersonating')
|
|
77
|
+
return status(403, 'Not while acting as the user')
|
|
78
|
+
|
|
79
|
+
return exported.error.code === 'stale' ? status(403, 'Sign in again to continue') : status(401, 'Sign in to continue')
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
set.headers['content-disposition'] = `attachment; filename="${core.name.replaceAll(UNSAFE_FILE_NAME, '-')}-data.json"`
|
|
83
|
+
set.headers['cache-control'] = 'no-store'
|
|
84
|
+
|
|
85
|
+
return exported.data
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Where a form's `redirect` field sends: a path of the site, else the pages' home.
|
|
89
|
+
function afterwards(body: unknown, core: Core): string {
|
|
90
|
+
return localPath(text((body as Record<string, unknown> | undefined)?.redirect), homeOf(core))
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// The sign-out button of any page: a form posting here, with `redirect` for where to go after, a path of the site, else the pages' home or `/`. A post only, so a link or a prefetch signs no one out, and a cross-site one is refused with a 403.
|
|
94
|
+
export async function signOutRoute({ auth, body, redirect }: RouteContext, core: Core) {
|
|
95
|
+
await auth.signOut()
|
|
96
|
+
|
|
97
|
+
return redirect(afterwards(body, core), 303)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// The impersonation banner's button: a form posting here signs the admin back in as themselves, then goes to `redirect`, a path of the site, else the pages' home. A post only, as sign-out is, and a cross-site one is refused with a 403.
|
|
101
|
+
export async function stopImpersonatingRoute({ auth, body, redirect, request }: RouteContext, core: Core) {
|
|
102
|
+
if (auth[STATE].crossSite())
|
|
103
|
+
return crossSiteResponse(request, 'request', core.url)
|
|
104
|
+
|
|
105
|
+
await auth.admin.stopImpersonating()
|
|
106
|
+
|
|
107
|
+
return redirect(afterwards(body, core), 303)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// The deletion banner's button: a form posting here takes the pending deletion off the signed-in user's account, then goes to `redirect`, a path of the site, else the pages' home. A post only, and a cross-site one is refused with a 403.
|
|
111
|
+
export async function cancelDeletionRoute({ auth, body, redirect, request }: RouteContext, core: Core) {
|
|
112
|
+
if (auth[STATE].crossSite())
|
|
113
|
+
return crossSiteResponse(request, 'request', core.url)
|
|
114
|
+
|
|
115
|
+
await auth.account.cancelDeletion()
|
|
116
|
+
|
|
117
|
+
return redirect(afterwards(body, core), 303)
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// A GET, so a sign-in link works without JavaScript: give it `data-no-prefetch` so a hover starts nothing.
|
|
121
|
+
export async function startOAuthRoute({ auth, params: { provider = '' }, query, redirect, status }: RouteContext, core: Core, failurePage: string | undefined) {
|
|
122
|
+
const started = !core.oauth.has(provider) ? undefined : await (await load.flow()).startOAuth(auth[STATE], provider, { redirect: text(query.redirect), remember: query.remember === undefined ? undefined : query.remember === '1' })
|
|
123
|
+
|
|
124
|
+
if (started === undefined)
|
|
125
|
+
return status(404, 'Not Found')
|
|
126
|
+
|
|
127
|
+
// kay-allow external-redirect: the provider's authorize URL, else a sign-in page of this site
|
|
128
|
+
return redirect(typeof started === 'string' ? started : failed(core, failurePage, started.error, text(query.redirect)), 303)
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export async function callbackRoute({ auth, params: { provider = '' }, query, redirect }: RouteContext, core: Core, failurePage: string | undefined) {
|
|
132
|
+
// The flow is read once here and handed to `finishOAuth`. A provider the app lacks still spends a pending flow its state matches, so the flow is not left in the session and its redirect is kept; with none pending, nothing loads.
|
|
133
|
+
const flow = await auth[STATE].session.get('authOAuth')
|
|
134
|
+
|
|
135
|
+
if (!core.oauth.has(provider) && flow === undefined)
|
|
136
|
+
return redirect(failed(core, failurePage, 'oauth'), 303)
|
|
137
|
+
|
|
138
|
+
const outcome = await (await load.flow()).finishOAuth(auth[STATE], provider, { code: text(query.code), state: text(query.state), error: text(query.error), user: text(query.user) }, flow)
|
|
139
|
+
|
|
140
|
+
// kay-allow external-redirect: the flow's own redirect, checked when it started
|
|
141
|
+
return redirect('error' in outcome ? failed(core, failurePage, outcome.error, outcome.redirect) : outcome.redirect, 303)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// Apple, or any provider asked for `response_mode=form_post`, comes back with a cross-site POST, which a SameSite=Lax session cookie does not ride on: the GET it is turned into does.
|
|
145
|
+
export function formPostRoute({ params: { provider = '' }, body, redirect, status }: Omit<RouteContext, 'auth'>, core: Core) {
|
|
146
|
+
if (!core.oauth.has(provider))
|
|
147
|
+
return status(404, 'Not Found')
|
|
148
|
+
|
|
149
|
+
const form = (body ?? {}) as Record<string, unknown>
|
|
150
|
+
const query = new URLSearchParams()
|
|
151
|
+
|
|
152
|
+
// Not the ID token Apple posts too: the one the token endpoint answers is the one checked.
|
|
153
|
+
for (const name of FORM_POST_FIELDS) {
|
|
154
|
+
const value = form[name]
|
|
155
|
+
|
|
156
|
+
if (typeof value === 'string')
|
|
157
|
+
query.set(name, value)
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return redirect(`${core.prefix}/${provider}/callback?${query}`, 303)
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// The routes no link of the app's names, so they stay out of the plugin's type: the OAuth server's, the dev tool's and forward auth's.
|
|
164
|
+
export function serveUntypedRoutes(plugin: Elysia, core: Core): void {
|
|
165
|
+
if (core.oauthServer)
|
|
166
|
+
serveOAuthServer(plugin, core, ctx => (ctx as { auth: Auth }).auth[STATE])
|
|
167
|
+
|
|
168
|
+
// Under `kay dev` alone: the dev tool's Auth tab reads the session here, and signs out at the sign-out route.
|
|
169
|
+
if (underKayDev()) {
|
|
170
|
+
plugin.get(DEV_PATH, async (ctx) => {
|
|
171
|
+
const { auth } = ctx as unknown as { auth: Auth }
|
|
172
|
+
const [user, via] = await Promise.all([auth.bareUser(), auth.via()])
|
|
173
|
+
|
|
174
|
+
ctx.set.headers['cache-control'] = 'no-store'
|
|
175
|
+
|
|
176
|
+
return { user, via, signOut: `${core.prefix}/sign-out` }
|
|
177
|
+
})
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
if (!core.forward)
|
|
181
|
+
return
|
|
182
|
+
|
|
183
|
+
if (!rootUsable(core))
|
|
184
|
+
throw configError('auth', 'forwardAuth', 'forwardAuth sends visitors to the sign-in page by its full URL: set `site` in kay.config.ts, SITE_URL or in authCore')
|
|
185
|
+
|
|
186
|
+
const forward = core.forward
|
|
187
|
+
const route = `${core.prefix}/forward`
|
|
188
|
+
|
|
189
|
+
// The route a reverse proxy asks before it lets a request through to a site it guards, and the one a sign-in comes back through to that site.
|
|
190
|
+
plugin
|
|
191
|
+
.get(route, async (ctx) => {
|
|
192
|
+
const answer = (await import('./forwardRoutes')).answerForward
|
|
193
|
+
|
|
194
|
+
const { auth } = ctx as unknown as { auth: Auth }
|
|
195
|
+
const { lacksTwoFactor } = await import('./requiredTwoFactor')
|
|
196
|
+
|
|
197
|
+
return answer(ctx, core, forward, auth, (role, user) => core.access.isGranted(role, user.roles), async user => lacksTwoFactor(auth[STATE], user, { wanted: forward.requireTwoFactor ? true : undefined }))
|
|
198
|
+
})
|
|
199
|
+
// Back from signing in to the guarded site, if it is on the domains the app allows, else home.
|
|
200
|
+
// kay-allow external-redirect: `returnTarget` keeps only an https URL on the allowed domains
|
|
201
|
+
.get(`${route}/return`, ({ query, redirect }) => redirect(returnTarget(typeof query.to === 'string' ? query.to : undefined, forward.domains) ?? homeOf(core), 303))
|
|
202
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { CredentialRules, ResolvedRules } from './rules'
|
|
2
|
+
import { configError } from 'kay/library'
|
|
3
|
+
import { PASSWORD_MAX_LENGTH, PASSWORD_MIN_LENGTH, USERNAME_MAX_LENGTH, USERNAME_MIN_LENGTH } from './rules'
|
|
4
|
+
|
|
5
|
+
// What the prebuilt pages' forms take at most, so a ceiling above never meets a refusal from the form first.
|
|
6
|
+
const FORM_PASSWORD_MAX = 1024
|
|
7
|
+
const FORM_USERNAME_MAX = 128
|
|
8
|
+
|
|
9
|
+
function limit(value: number | undefined, fallback: number, name: string): number {
|
|
10
|
+
if (value === undefined)
|
|
11
|
+
return fallback
|
|
12
|
+
|
|
13
|
+
if (!Number.isInteger(value) || value < 1)
|
|
14
|
+
throw configError('auth', 'rules', `rules.${name} is ${value}, a whole number of at least 1`)
|
|
15
|
+
|
|
16
|
+
return value
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// The rules with the defaults filled in, refusing a range that no value fits.
|
|
20
|
+
export function resolveRules(rules: CredentialRules = {}): ResolvedRules {
|
|
21
|
+
const password = { min: limit(rules.password?.min, PASSWORD_MIN_LENGTH, 'password.min'), max: limit(rules.password?.max, PASSWORD_MAX_LENGTH, 'password.max'), check: rules.password?.check }
|
|
22
|
+
const username = { min: limit(rules.username?.min, USERNAME_MIN_LENGTH, 'username.min'), max: limit(rules.username?.max, USERNAME_MAX_LENGTH, 'username.max') }
|
|
23
|
+
|
|
24
|
+
if (password.max > FORM_PASSWORD_MAX)
|
|
25
|
+
throw configError('auth', 'rules', `rules.password.max is ${password.max}, over the ${FORM_PASSWORD_MAX} the prebuilt pages post`)
|
|
26
|
+
|
|
27
|
+
if (username.max > FORM_USERNAME_MAX)
|
|
28
|
+
throw configError('auth', 'rules', `rules.username.max is ${username.max}, over the ${FORM_USERNAME_MAX} the prebuilt pages post`)
|
|
29
|
+
|
|
30
|
+
if (password.min > password.max)
|
|
31
|
+
throw configError('auth', 'rules', `rules.password.min is ${password.min}, over rules.password.max ${password.max}`)
|
|
32
|
+
|
|
33
|
+
if (username.min > username.max)
|
|
34
|
+
throw configError('auth', 'rules', `rules.username.min is ${username.min}, over rules.username.max ${username.max}`)
|
|
35
|
+
|
|
36
|
+
return { password, username }
|
|
37
|
+
}
|
package/src/rules.ts
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// The credential rules, stated once so a form and the server agree. Browser-safe: an island imports them from `@kayjs/auth/rules` to refuse before posting, and the server checks every one again.
|
|
2
|
+
|
|
3
|
+
import { isEmail } from 'kay'
|
|
4
|
+
|
|
5
|
+
export const PASSWORD_MIN_LENGTH = 10
|
|
6
|
+
// Argon2id has no ceiling of its own, and an unbounded field is free CPU for whoever posts it.
|
|
7
|
+
export const PASSWORD_MAX_LENGTH = 128
|
|
8
|
+
export const USERNAME_MIN_LENGTH = 2
|
|
9
|
+
export const USERNAME_MAX_LENGTH = 32
|
|
10
|
+
|
|
11
|
+
// Letters and digits in any script, with spaces, dots, hyphens and underscores inside only.
|
|
12
|
+
const USERNAME = /^[\p{L}\p{N}](?:[\p{L}\p{N} ._-]*[\p{L}\p{N}])?$/u
|
|
13
|
+
const WHITESPACE = /\s+/g
|
|
14
|
+
// The scripts a look-alike name reaches for: Latin, and the two that mimic it most.
|
|
15
|
+
const CONFUSABLE_SCRIPTS = [/\p{Script=Latin}/u, /\p{Script=Cyrillic}/u, /\p{Script=Greek}/u]
|
|
16
|
+
|
|
17
|
+
export type EmailProblem = 'invalid'
|
|
18
|
+
// `too-short`, `too-long`, or the code or message an app's `check` returned.
|
|
19
|
+
export type PasswordProblem = 'too-short' | 'too-long' | (string & {})
|
|
20
|
+
export type UsernameProblem = 'length' | 'characters' | 'mixed-scripts'
|
|
21
|
+
|
|
22
|
+
// The form an email is stored, compared and looked up in.
|
|
23
|
+
export function normalizeEmail(email: string): string {
|
|
24
|
+
return email.normalize('NFKC').trim().toLowerCase()
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// The form a username is stored, compared and looked up in.
|
|
28
|
+
export function normalizeUsername(username: string): string {
|
|
29
|
+
return username.normalize('NFKC').trim().replace(WHITESPACE, ' ')
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// A name mixing Latin with Cyrillic or Greek, such as a Cyrillic `а` in `аlice`, would pass for another user's.
|
|
33
|
+
export function mixesConfusableScripts(value: string): boolean {
|
|
34
|
+
return CONFUSABLE_SCRIPTS.filter(script => script.test(value)).length > 1
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function emailProblem(email: string): EmailProblem | undefined {
|
|
38
|
+
const normalized = normalizeEmail(email)
|
|
39
|
+
|
|
40
|
+
return isEmail(normalized) && !mixesConfusableScripts(normalized.slice(0, normalized.lastIndexOf('@'))) ? undefined : 'invalid'
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// What an app sets over the defaults, in the `rules` option of `authCore`, and the same object an island passes to `passwordProblem` and `usernameProblem`.
|
|
44
|
+
export interface CredentialRules {
|
|
45
|
+
password?: {
|
|
46
|
+
// 10 by default.
|
|
47
|
+
min?: number | undefined
|
|
48
|
+
// 128 by default: Argon2id has no ceiling of its own.
|
|
49
|
+
max?: number | undefined
|
|
50
|
+
// An extra rule on top of the length ones, returning a problem code or a message for what it refuses, such as `p => /\d/.test(p) ? undefined : 'Add a digit.'`. The prebuilt pages show what it returns as it is.
|
|
51
|
+
check?: ((password: string) => string | undefined) | undefined
|
|
52
|
+
} | undefined
|
|
53
|
+
username?: {
|
|
54
|
+
// 2 by default.
|
|
55
|
+
min?: number | undefined
|
|
56
|
+
// 32 by default.
|
|
57
|
+
max?: number | undefined
|
|
58
|
+
} | undefined
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// The rules with every limit set, as `features().rules` hands them to a page or an island.
|
|
62
|
+
export interface ResolvedRules {
|
|
63
|
+
password: { min: number, max: number, check?: ((password: string) => string | undefined) | undefined }
|
|
64
|
+
username: { min: number, max: number }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export const DEFAULT_RULES: ResolvedRules = { password: { min: PASSWORD_MIN_LENGTH, max: PASSWORD_MAX_LENGTH }, username: { min: USERNAME_MIN_LENGTH, max: USERNAME_MAX_LENGTH } }
|
|
68
|
+
|
|
69
|
+
// The rules with the defaults filled in, no range checked: `resolveRules` of the server refuses one that no value fits.
|
|
70
|
+
function filled(rules: CredentialRules): ResolvedRules {
|
|
71
|
+
return { password: { min: rules.password?.min ?? PASSWORD_MIN_LENGTH, max: rules.password?.max ?? PASSWORD_MAX_LENGTH, check: rules.password?.check }, username: { min: rules.username?.min ?? USERNAME_MIN_LENGTH, max: rules.username?.max ?? USERNAME_MAX_LENGTH } }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// An already resolved set, such as the core's, is used as it is.
|
|
75
|
+
function resolved(rules: CredentialRules): ResolvedRules {
|
|
76
|
+
return rules === DEFAULT_RULES || (typeof rules.password?.min === 'number' && typeof rules.password.max === 'number' && typeof rules.username?.min === 'number' && typeof rules.username.max === 'number') ? rules as ResolvedRules : filled(rules)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// The rules an app set, over the defaults when none are given: an island passes `features().rules` it was handed, or the object the app gave `authCore`.
|
|
80
|
+
export function passwordProblem(password: string, rules: CredentialRules = DEFAULT_RULES): PasswordProblem | undefined {
|
|
81
|
+
const { min, max, check } = resolved(rules).password
|
|
82
|
+
|
|
83
|
+
if (password.length < min)
|
|
84
|
+
return 'too-short'
|
|
85
|
+
|
|
86
|
+
if (password.length > max)
|
|
87
|
+
return 'too-long'
|
|
88
|
+
|
|
89
|
+
const problem = check?.(password)
|
|
90
|
+
|
|
91
|
+
return problem === '' ? undefined : problem
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function usernameProblem(username: string, rules: CredentialRules = DEFAULT_RULES): UsernameProblem | undefined {
|
|
95
|
+
const name = normalizeUsername(username)
|
|
96
|
+
const { min, max } = resolved(rules).username
|
|
97
|
+
|
|
98
|
+
if (name.length < min || name.length > max)
|
|
99
|
+
return 'length'
|
|
100
|
+
|
|
101
|
+
if (!USERNAME.test(name))
|
|
102
|
+
return 'characters'
|
|
103
|
+
|
|
104
|
+
return mixesConfusableScripts(name) ? 'mixed-scripts' : undefined
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// The longest a profile field of the account page holds unless it says otherwise.
|
|
108
|
+
export const PROFILE_MAX_LENGTH = 500
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { SecurityEvent } from './mail'
|
|
2
|
+
import type { RequestState } from './state'
|
|
3
|
+
import type { UserRecord } from './store'
|
|
4
|
+
import { report } from './events'
|
|
5
|
+
import { sendAside, writing } from './mail'
|
|
6
|
+
|
|
7
|
+
// Tells the user and the app of a change to what protects the account; mail goes to a verified address only, so a typo never warns a stranger.
|
|
8
|
+
// The mail leaves off the request's path, so a slow relay never delays the response and a failure is only logged.
|
|
9
|
+
export async function securityNotice(state: RequestState, record: UserRecord, event: SecurityEvent, detail?: string, to = record.emailVerifiedAt === null ? null : record.email, actor?: UserRecord): Promise<void> {
|
|
10
|
+
const { core } = state
|
|
11
|
+
|
|
12
|
+
await report(state, record, event, detail, actor)
|
|
13
|
+
|
|
14
|
+
// A new sign-in links to where the user ends the sessions they do not know.
|
|
15
|
+
const url = event === 'new-sign-in' && core.sessionsPage !== undefined ? `${core.url}${core.sessionsPage}` : undefined
|
|
16
|
+
|
|
17
|
+
mailNotice(core, state.languages, record, event, detail, to, url)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// The mail half of `securityNotice`, for a notice outside a request: `languages` are the ones to write in after the user's own.
|
|
21
|
+
export function mailNotice(core: RequestState['core'], languages: readonly string[], record: UserRecord, event: SecurityEvent, detail?: string, to = record.emailVerifiedAt === null ? null : record.email, url?: string): void {
|
|
22
|
+
const mail = core.email
|
|
23
|
+
|
|
24
|
+
if (!mail || to === null)
|
|
25
|
+
return
|
|
26
|
+
|
|
27
|
+
const { locale, templates } = writing(mail, [record.locale, ...languages])
|
|
28
|
+
|
|
29
|
+
sendAside(mail, () => ({ to, kind: event, name: core.name, locale, ...url === undefined ? {} : { url }, ...detail === undefined ? {} : { detail }, ...templates[event]({ name: core.name, email: to, detail, url, locale }) }), event)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Mails a sign-in from a device or network the account has not used before, then remembers this one.
|
|
33
|
+
export async function noteSignIn(state: RequestState, record: UserRecord): Promise<void> {
|
|
34
|
+
const { core } = state
|
|
35
|
+
const fingerprint = core.keys.fingerprint(`${state.client}\n${state.userAgent}`)
|
|
36
|
+
|
|
37
|
+
if (record.lastSignIn === fingerprint)
|
|
38
|
+
return
|
|
39
|
+
|
|
40
|
+
await core.store.users.update(record.id, { lastSignIn: fingerprint })
|
|
41
|
+
|
|
42
|
+
// The first sign-in has nothing to compare against.
|
|
43
|
+
if (record.lastSignIn !== null)
|
|
44
|
+
await securityNotice(state, record, 'new-sign-in')
|
|
45
|
+
}
|