@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,350 @@
|
|
|
1
|
+
import type { Core, Profile } from '../core'
|
|
2
|
+
import type { AuthFailed } from '../failure'
|
|
3
|
+
import type { Proof, ProofFailure } from '../proof'
|
|
4
|
+
import type { RequestState } from '../state'
|
|
5
|
+
import type { IdentityRecord, UserRecord } from '../store'
|
|
6
|
+
import type { OAuthTokens } from './types'
|
|
7
|
+
import { localPath } from 'kay'
|
|
8
|
+
import { homeOf, linkedUser, newUserRecord, sameText } from '../core'
|
|
9
|
+
import { report } from '../events'
|
|
10
|
+
import { failed } from '../failure'
|
|
11
|
+
import { randomToken } from '../keys'
|
|
12
|
+
import { log } from '../log'
|
|
13
|
+
import { reprove } from '../proof'
|
|
14
|
+
import { normalizeEmail, normalizeUsername, usernameProblem } from '../rules'
|
|
15
|
+
import { securityNotice } from '../securityNotice'
|
|
16
|
+
import { chooseRemember } from '../sessions'
|
|
17
|
+
import { mergedData } from '../userData'
|
|
18
|
+
import { OAuthExchangeError } from './client'
|
|
19
|
+
import { challengeOf, createPkcePair } from './pkce'
|
|
20
|
+
|
|
21
|
+
const FLOW_MAX_AGE_MS = 10 * 60 * 1000
|
|
22
|
+
|
|
23
|
+
// Why an OAuth sign-in failed, sent to the sign-in page as `?error=`.
|
|
24
|
+
export type OAuthFailure = 'oauth' | 'cancelled' | 'refused' | 'taken' | 'unavailable' | 'signed-out' | 'banned'
|
|
25
|
+
|
|
26
|
+
// What a sign-in in progress keeps in the session between leaving for the provider and coming back.
|
|
27
|
+
export interface OAuthFlow {
|
|
28
|
+
provider: string
|
|
29
|
+
state: string
|
|
30
|
+
verifier: string
|
|
31
|
+
// Found again in an OpenID Connect provider's ID token, so one minted for another sign-in is refused.
|
|
32
|
+
nonce: string
|
|
33
|
+
redirect: string
|
|
34
|
+
// The user adding a provider to their account, null for a sign-in.
|
|
35
|
+
link: string | null
|
|
36
|
+
expires: number
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export type LinkProviderResult = { ok: true, url: string } | AuthFailed<ProofFailure | 'not-found' | 'unavailable'>
|
|
40
|
+
|
|
41
|
+
// The provider's authorize URL for a sign-in, the flow parked in the session; undefined for a provider the app has not configured.
|
|
42
|
+
export async function startOAuth(state: RequestState, provider: string, options: { redirect?: string | undefined, remember?: boolean | undefined }): Promise<string | { error: OAuthFailure } | undefined> {
|
|
43
|
+
if (!state.core.oauth.has(provider))
|
|
44
|
+
return undefined
|
|
45
|
+
|
|
46
|
+
const live = await liveFlow(state)
|
|
47
|
+
|
|
48
|
+
// A provider link in flight is the signed-in user's own, proved by `linkProvider`: a GET, which any page can make the browser send, never replaces it.
|
|
49
|
+
if (live && live.link !== null && live.link !== '' && live.link === (await state.current())?.id)
|
|
50
|
+
return { error: 'oauth' }
|
|
51
|
+
|
|
52
|
+
// The same sign-in asked for again, by a double click, a prefetch or a page loading the link, goes on with the one in flight rather than breaking it.
|
|
53
|
+
const resume = live && live.provider === provider && live.redirect === localPath(options.redirect, homeOf(state.core)) ? live : undefined
|
|
54
|
+
const url = await leave(state, provider, options.redirect, null, resume)
|
|
55
|
+
|
|
56
|
+
if (typeof url === 'string')
|
|
57
|
+
await chooseRemember(state, options.remember)
|
|
58
|
+
|
|
59
|
+
return url
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// The provider's authorize URL for linking it to the signed-in user, once `proof` re-proves them.
|
|
63
|
+
// A linked provider is a way in that outlives every sign-out, so a stolen session alone may not add one, and the second factor proves it when it is on.
|
|
64
|
+
export async function startLink(state: RequestState, provider: string, proof: Proof, redirect: string | undefined): Promise<LinkProviderResult> {
|
|
65
|
+
if (!state.core.oauth.has(provider))
|
|
66
|
+
return failed('not-found')
|
|
67
|
+
|
|
68
|
+
if (!(await state.current()) || state.via() !== 'session')
|
|
69
|
+
return failed('signed-out')
|
|
70
|
+
|
|
71
|
+
const proved = await reprove(state, proof, { secondFactor: true })
|
|
72
|
+
|
|
73
|
+
if (!proved.ok)
|
|
74
|
+
return proved
|
|
75
|
+
|
|
76
|
+
const url = await leave(state, provider, redirect, proved.record.id)
|
|
77
|
+
|
|
78
|
+
return typeof url === 'string' ? { ok: true, url } : failed('unavailable')
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// The flow this session has in progress, unless it ran out.
|
|
82
|
+
async function liveFlow(state: RequestState): Promise<OAuthFlow | undefined> {
|
|
83
|
+
const flow = await state.session.get('authOAuth')
|
|
84
|
+
|
|
85
|
+
return flow && flow.expires > Date.now() ? flow : undefined
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Parks the flow in the session and answers where the browser goes to meet the provider.
|
|
89
|
+
async function leave(state: RequestState, provider: string, redirect: string | undefined, link: string | null, resume?: OAuthFlow): Promise<string | { error: 'unavailable' }> {
|
|
90
|
+
const entry = state.core.oauth.get(provider)!
|
|
91
|
+
const pkce = resume ? { verifier: resume.verifier, challenge: await challengeOf(resume.verifier) } : await createPkcePair()
|
|
92
|
+
const flowState = resume?.state ?? randomToken()
|
|
93
|
+
const nonce = resume?.nonce ?? randomToken()
|
|
94
|
+
let url: string
|
|
95
|
+
|
|
96
|
+
try {
|
|
97
|
+
url = await entry.client.authorizeUrl({ state: flowState, codeChallenge: pkce.challenge, nonce })
|
|
98
|
+
}
|
|
99
|
+
// An OpenID Connect provider whose discovery document is out of reach.
|
|
100
|
+
catch (error) {
|
|
101
|
+
if (error instanceof OAuthExchangeError)
|
|
102
|
+
return { error: 'unavailable' }
|
|
103
|
+
|
|
104
|
+
throw error
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
if (resume)
|
|
108
|
+
return url
|
|
109
|
+
|
|
110
|
+
await state.session.set('authOAuth', { provider, state: flowState, verifier: pkce.verifier, nonce, redirect: localPath(redirect, homeOf(state.core)), link, expires: Date.now() + FLOW_MAX_AGE_MS })
|
|
111
|
+
|
|
112
|
+
return url
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Where to send the browser once the provider sent it back with `query`, `flow` being the pending one the route read: the flow is spent by the callback carrying its `state`, so a callback URL replayed later finds none.
|
|
116
|
+
// A callback whose `state` is wrong or missing leaves the flow in place, so a page on another site loading the callback URL cannot kill a sign-in in flight.
|
|
117
|
+
export async function finishOAuth(state: RequestState, provider: string, query: Record<string, string | undefined>, flow: OAuthFlow | undefined): Promise<{ redirect: string } | { error: OAuthFailure, redirect?: string }> {
|
|
118
|
+
const { core } = state
|
|
119
|
+
|
|
120
|
+
if (!flow || query.state === undefined || query.state === '' || !sameText(query.state, flow.state))
|
|
121
|
+
return { error: 'oauth' }
|
|
122
|
+
|
|
123
|
+
await state.session.unset('authOAuth')
|
|
124
|
+
|
|
125
|
+
const entry = core.oauth.get(provider)
|
|
126
|
+
|
|
127
|
+
if (!entry || flow.provider !== provider || flow.expires < Date.now())
|
|
128
|
+
return { error: 'oauth', redirect: flow.redirect }
|
|
129
|
+
|
|
130
|
+
if (query.error !== undefined || query.code === undefined || query.code === '')
|
|
131
|
+
return { error: query.error === 'access_denied' ? 'cancelled' : 'oauth', redirect: flow.redirect }
|
|
132
|
+
|
|
133
|
+
let tokens: OAuthTokens
|
|
134
|
+
let profile: Profile
|
|
135
|
+
|
|
136
|
+
try {
|
|
137
|
+
tokens = await entry.client.exchangeCode(query.code, { codeVerifier: flow.verifier })
|
|
138
|
+
profile = { ...await entry.client.readUser(tokens, { nonce: flow.nonce, callback: callbackParams(query) }), provider }
|
|
139
|
+
}
|
|
140
|
+
catch (error) {
|
|
141
|
+
if (error instanceof OAuthExchangeError) {
|
|
142
|
+
log.warn(`the ${provider} sign-in failed: ${error.message}`)
|
|
143
|
+
|
|
144
|
+
return { error: error.status >= 500 ? 'unavailable' : 'oauth', redirect: flow.redirect }
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
throw error
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// A provider answering without an id would put every such sign-in in one shared account.
|
|
151
|
+
if (typeof profile.providerId !== 'string' || profile.providerId === '')
|
|
152
|
+
return { error: 'oauth', redirect: flow.redirect }
|
|
153
|
+
|
|
154
|
+
if (core.allow && !(await core.allow(profile)))
|
|
155
|
+
return { error: 'refused', redirect: flow.redirect }
|
|
156
|
+
|
|
157
|
+
const identity = await core.store.identities.find(provider, profile.providerId)
|
|
158
|
+
|
|
159
|
+
if (flow.link !== null && flow.link !== '') {
|
|
160
|
+
const current = await state.current()
|
|
161
|
+
|
|
162
|
+
// The provider joins the account that asked for it, never one signed in since in the same browser.
|
|
163
|
+
if (current?.id !== flow.link)
|
|
164
|
+
return { error: 'signed-out', redirect: flow.redirect }
|
|
165
|
+
|
|
166
|
+
if (identity && identity.userId !== current.id) {
|
|
167
|
+
await report(state, current, 'sign-in-failed', 'oauth')
|
|
168
|
+
|
|
169
|
+
return { error: 'taken', redirect: flow.redirect }
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
await saveIdentity(core, identity, current.id, profile, tokens)
|
|
173
|
+
const linked = await adoptEmail(core, current, profile)
|
|
174
|
+
|
|
175
|
+
if (!identity)
|
|
176
|
+
await securityNotice(state, current, 'provider-linked', provider)
|
|
177
|
+
|
|
178
|
+
await heardProfile(core, linked, profile)
|
|
179
|
+
|
|
180
|
+
return { redirect: flow.redirect }
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
let record = identity && await core.store.users.get(identity.userId)
|
|
184
|
+
|
|
185
|
+
if (record) {
|
|
186
|
+
await saveIdentity(core, identity, record.id, profile, tokens)
|
|
187
|
+
record = await adoptEmail(core, record, profile)
|
|
188
|
+
}
|
|
189
|
+
else {
|
|
190
|
+
const current = await state.current()
|
|
191
|
+
// A guest becomes the provider account's user, keeping what the app holds for them.
|
|
192
|
+
const guest = current?.guest && state.via() === 'session' ? current : undefined
|
|
193
|
+
|
|
194
|
+
// Refused as `allow` refuses, before any user or identity is kept.
|
|
195
|
+
if (!core.signUp)
|
|
196
|
+
return { error: 'refused', redirect: flow.redirect }
|
|
197
|
+
|
|
198
|
+
record = await signUp(core, profile, state.languages[0] ?? null, guest)
|
|
199
|
+
// An identity left by a deleted user is replaced.
|
|
200
|
+
await saveIdentity(core, undefined, record.id, profile, tokens, identity !== undefined)
|
|
201
|
+
|
|
202
|
+
if (!guest)
|
|
203
|
+
await core.onSignUp?.(await linkedUser(core, record), profile)
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
await heardProfile(core, record, profile)
|
|
207
|
+
|
|
208
|
+
const done = await state.complete(record, flow.redirect, `oauth:${provider}`)
|
|
209
|
+
|
|
210
|
+
if (!done.ok)
|
|
211
|
+
await report(state, record, 'sign-in-failed', 'oauth')
|
|
212
|
+
|
|
213
|
+
return done.ok ? { redirect: done.redirect } : { error: done.error.code, redirect: flow.redirect }
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// What else the provider came back with, such as Apple's `user` naming the user on their first sign-in.
|
|
217
|
+
function callbackParams(query: Record<string, string | undefined>): Record<string, string> {
|
|
218
|
+
const params: Record<string, string> = {}
|
|
219
|
+
|
|
220
|
+
for (const [name, value] of Object.entries(query)) {
|
|
221
|
+
if (value !== undefined && name !== 'code' && name !== 'state')
|
|
222
|
+
params[name] = value
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
return params
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// A failure is logged, not thrown: refreshing what the app keeps from a profile must not fail a sign-in the provider vouched for.
|
|
229
|
+
// What the callback returns is laid over the user's `data`, kept only when it fits the `user` schema.
|
|
230
|
+
async function heardProfile(core: Core, record: UserRecord, profile: Profile): Promise<void> {
|
|
231
|
+
try {
|
|
232
|
+
const given = await core.onProviderProfile?.(await linkedUser(core, record), profile)
|
|
233
|
+
|
|
234
|
+
if (given === undefined || given === null || !core.userData)
|
|
235
|
+
return
|
|
236
|
+
|
|
237
|
+
const data = mergedData(core.userData, record.data, given)
|
|
238
|
+
|
|
239
|
+
if (data === undefined)
|
|
240
|
+
log.error(`onProviderProfile for ${profile.provider} returned data the \`user\` schema does not accept, so it was not kept`)
|
|
241
|
+
else
|
|
242
|
+
await core.store.users.update(record.id, { data })
|
|
243
|
+
}
|
|
244
|
+
catch (error) {
|
|
245
|
+
log.error(`onProviderProfile failed for ${profile.provider}`, error)
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// A fresh access token to call the provider with for the signed-in user, refreshed when it is about to expire; null without one.
|
|
250
|
+
export async function providerToken(state: RequestState, provider: string): Promise<string | null> {
|
|
251
|
+
const { core } = state
|
|
252
|
+
const current = await state.current()
|
|
253
|
+
const refresher = core.refreshers.get(provider)
|
|
254
|
+
|
|
255
|
+
if (!current || !refresher)
|
|
256
|
+
return null
|
|
257
|
+
|
|
258
|
+
const identity = (await core.store.identities.listByUser(current.id)).find(entry => entry.provider === provider)
|
|
259
|
+
|
|
260
|
+
if (identity === undefined || identity.accessToken === null || identity.accessToken === '')
|
|
261
|
+
return null
|
|
262
|
+
|
|
263
|
+
const context = identityContext(identity.provider, identity.providerId)
|
|
264
|
+
|
|
265
|
+
return refresher.getValidToken({
|
|
266
|
+
identity,
|
|
267
|
+
credential: {
|
|
268
|
+
accessToken: core.keys.decrypt(identity.accessToken, context),
|
|
269
|
+
refreshToken: identity.refreshToken === null ? null : core.keys.decrypt(identity.refreshToken, context),
|
|
270
|
+
expiresAt: identity.tokenExpiresAt,
|
|
271
|
+
},
|
|
272
|
+
})
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// Ends the provider's grant held in `identity`, its refresh token first as that is the grant's root. Logged, not thrown: a provider out of reach must not keep a user from unlinking or leaving, and one without a revocation endpoint leaves it to the user.
|
|
276
|
+
export async function revokeUpstream(core: Core, identity: IdentityRecord): Promise<void> {
|
|
277
|
+
const client = core.oauth.get(identity.provider)?.client
|
|
278
|
+
const sealed = identity.refreshToken ?? identity.accessToken
|
|
279
|
+
const token = !client || sealed === null || sealed === '' ? undefined : core.keys.decrypt(sealed, identityContext(identity.provider, identity.providerId))
|
|
280
|
+
|
|
281
|
+
if (!client || token === undefined)
|
|
282
|
+
return
|
|
283
|
+
|
|
284
|
+
try {
|
|
285
|
+
await client.revokeToken(token)
|
|
286
|
+
}
|
|
287
|
+
catch (error) {
|
|
288
|
+
log.error(`revoking a ${identity.provider} token failed`, error)
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// What a provider's tokens are encrypted against, so they open for that identity only.
|
|
293
|
+
export function identityContext(provider: string, providerId: string): string {
|
|
294
|
+
return `identity:${provider}:${providerId}`
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
export function sealTokens(core: Core, provider: string, providerId: string, tokens: OAuthTokens | null): Pick<IdentityRecord, 'accessToken' | 'refreshToken' | 'tokenExpiresAt'> {
|
|
298
|
+
const context = identityContext(provider, providerId)
|
|
299
|
+
|
|
300
|
+
return {
|
|
301
|
+
accessToken: tokens ? core.keys.encrypt(tokens.accessToken, context) : null,
|
|
302
|
+
refreshToken: tokens?.refreshToken === undefined ? null : core.keys.encrypt(tokens.refreshToken, context),
|
|
303
|
+
// A provider written before 1.88 may still give epoch milliseconds, which `new Date` reads as it does a date.
|
|
304
|
+
tokenExpiresAt: tokens?.expiresAt === undefined ? null : new Date(tokens.expiresAt),
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
async function saveIdentity(core: Core, identity: IdentityRecord | undefined, userId: string, profile: Profile, tokens: OAuthTokens, replace = false): Promise<void> {
|
|
309
|
+
const sealed = sealTokens(core, profile.provider, profile.providerId, core.oauth.get(profile.provider)?.app.keepTokens === true ? tokens : null)
|
|
310
|
+
|
|
311
|
+
if (identity && !replace) {
|
|
312
|
+
await core.store.identities.update(profile.provider, profile.providerId, sealed)
|
|
313
|
+
|
|
314
|
+
return
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
if (replace)
|
|
318
|
+
await core.store.identities.delete(profile.provider, profile.providerId)
|
|
319
|
+
|
|
320
|
+
await core.store.identities.create({ provider: profile.provider, providerId: profile.providerId, userId, ...sealed, createdAt: new Date() })
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// A new user from a provider account, or `guest` made one: its verified email and its name are taken only when no other user has them, so no account is ever merged into another by email.
|
|
324
|
+
async function signUp(core: Core, profile: Profile, locale: string | null, guest?: UserRecord): Promise<UserRecord> {
|
|
325
|
+
const email = profile.email == null || profile.email === '' ? undefined : normalizeEmail(profile.email)
|
|
326
|
+
const name = normalizeUsername(profile.username)
|
|
327
|
+
const freeEmail = email !== undefined && !(await core.store.users.findByEmail(email)) ? email : null
|
|
328
|
+
// A name these rules refuse is left out too: the user picks one later.
|
|
329
|
+
const freeName = !usernameProblem(name, core.rules) && !(await core.store.users.findByUsername(name)) ? name : null
|
|
330
|
+
|
|
331
|
+
if (guest) {
|
|
332
|
+
const patch = { email: freeEmail, emailVerifiedAt: freeEmail === null ? null : new Date(), username: guest.username ?? freeName, guest: false }
|
|
333
|
+
|
|
334
|
+
return await core.store.users.update(guest.id, patch) ?? { ...guest, ...patch }
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
const record = newUserRecord({ email: freeEmail, emailVerifiedAt: freeEmail === null ? null : new Date(), username: freeName, roles: [...core.defaultRoles], locale })
|
|
338
|
+
|
|
339
|
+
return (await core.store.users.create(record)) ?? record
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
// Gives a user without an email the provider's verified one, when no other user has it.
|
|
343
|
+
async function adoptEmail(core: Core, record: UserRecord, profile: Profile): Promise<UserRecord> {
|
|
344
|
+
const email = profile.email == null || profile.email === '' ? undefined : normalizeEmail(profile.email)
|
|
345
|
+
|
|
346
|
+
if (record.email !== null || email === undefined || await core.store.users.findByEmail(email))
|
|
347
|
+
return record
|
|
348
|
+
|
|
349
|
+
return await core.store.users.update(record.id, { email, emailVerifiedAt: new Date() }) ?? record
|
|
350
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { Buffer } from 'node:buffer'
|
|
2
|
+
import { nanoid } from '@kaynooo/utils'
|
|
3
|
+
|
|
4
|
+
export interface PkcePair {
|
|
5
|
+
verifier: string
|
|
6
|
+
challenge: string
|
|
7
|
+
method: 'S256'
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Generates a PKCE verifier/challenge pair (RFC 7636, S256): keep `verifier` server-side, send `challenge` on authorize, replay `verifier` to `exchangeCode`. */
|
|
11
|
+
export async function createPkcePair(): Promise<PkcePair> {
|
|
12
|
+
const verifier = nanoid(64)
|
|
13
|
+
|
|
14
|
+
return { verifier, challenge: await challengeOf(verifier), method: 'S256' }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** The S256 challenge of a verifier, to send the same one again for a flow in progress. */
|
|
18
|
+
export async function challengeOf(verifier: string): Promise<string> {
|
|
19
|
+
return Buffer.from(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))).toString('base64url')
|
|
20
|
+
}
|