@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/sessions.ts
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import type { SessionSettings } from 'kay/server'
|
|
2
|
+
import type { BareUser, Core } from './core'
|
|
3
|
+
import type { Device } from './device'
|
|
4
|
+
import type { AuthFailed } from './failure'
|
|
5
|
+
import type { RequestState } from './state'
|
|
6
|
+
import type { SessionRecord, UserRecord } from './store'
|
|
7
|
+
import { durationSeconds } from 'kay/library'
|
|
8
|
+
import { TOUCH_EVERY_MS } from './core'
|
|
9
|
+
import { readDevice } from './device'
|
|
10
|
+
import { failed } from './failure'
|
|
11
|
+
import { log } from './log'
|
|
12
|
+
|
|
13
|
+
const USER_AGENT_MAX_LENGTH = 512
|
|
14
|
+
|
|
15
|
+
export type RevokeSessionResult = { ok: true } | AuthFailed<'signed-out' | 'not-found'>
|
|
16
|
+
|
|
17
|
+
export type GuestSignInResult = { ok: true, user: BareUser } | AuthFailed<'limited' | 'captcha' | 'signed-in' | 'off'>
|
|
18
|
+
|
|
19
|
+
// Where the user is signed in, as the app lists it.
|
|
20
|
+
export interface UserSession {
|
|
21
|
+
id: string
|
|
22
|
+
// Whether it is the browser asking.
|
|
23
|
+
current: boolean
|
|
24
|
+
device: Device
|
|
25
|
+
userAgent: string
|
|
26
|
+
ip: string
|
|
27
|
+
// Where the address is, when the app's `locate` says.
|
|
28
|
+
place: string | null
|
|
29
|
+
createdAt: Date
|
|
30
|
+
lastSeenAt: Date
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Records a new sign-in of `record` from this browser, living `maxAge` seconds unseen or the session plugin's `maxAge`, and answers its id.
|
|
34
|
+
export async function openSession(core: Core, record: UserRecord, ip: string, userAgent: string, maxAge: number | null = null): Promise<string> {
|
|
35
|
+
const now = new Date()
|
|
36
|
+
const id = crypto.randomUUID()
|
|
37
|
+
|
|
38
|
+
await core.store.sessions.create({ id, userId: record.id, version: record.sessionVersion, userAgent: userAgent.slice(0, USER_AGENT_MAX_LENGTH), ip, createdAt: now, lastSeenAt: now, maxAge })
|
|
39
|
+
|
|
40
|
+
return id
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Whether `signedIn` still names a live session of `record`: not ended, not signed out everywhere since, seen within the session's lifetime and signed in within the session plugin's `absoluteMaxAge`. A visit is recorded on the way.
|
|
44
|
+
export async function liveSession(state: RequestState, found: SessionRecord | undefined, record: UserRecord, ip: string): Promise<boolean> {
|
|
45
|
+
const { core } = state
|
|
46
|
+
const now = Date.now()
|
|
47
|
+
|
|
48
|
+
if (!found || found.userId !== record.id || !live(state.session.settings, found, record, now))
|
|
49
|
+
return false
|
|
50
|
+
|
|
51
|
+
if (now - found.lastSeenAt.getTime() > TOUCH_EVERY_MS || found.ip !== ip)
|
|
52
|
+
await core.store.sessions.update(found.id, { lastSeenAt: new Date(now), ip })
|
|
53
|
+
|
|
54
|
+
return true
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Ends one of the signed-in user's sessions, effective on its next request; ending this one signs out through `signOut`.
|
|
58
|
+
export async function revokeSession(state: RequestState, id: string, signOut: () => Promise<void>): Promise<RevokeSessionResult> {
|
|
59
|
+
const record = await state.current()
|
|
60
|
+
const signedIn = await state.session.get('auth')
|
|
61
|
+
|
|
62
|
+
if (!record || state.via() !== 'session')
|
|
63
|
+
return failed('signed-out')
|
|
64
|
+
|
|
65
|
+
if (signedIn?.session === id) {
|
|
66
|
+
await signOut()
|
|
67
|
+
|
|
68
|
+
return { ok: true }
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return (await state.core.store.sessions.delete(record.id, id)) ? { ok: true } : failed('not-found')
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// The signed-in user's sessions, oldest first; a session that ended without signing out, past its lifetime or signed out everywhere, is forgotten on the way.
|
|
75
|
+
export async function listSessions(state: RequestState): Promise<UserSession[]> {
|
|
76
|
+
const record = await state.current()
|
|
77
|
+
const signedIn = await state.session.get('auth')
|
|
78
|
+
|
|
79
|
+
if (!record || state.via() !== 'session')
|
|
80
|
+
return []
|
|
81
|
+
|
|
82
|
+
const now = Date.now()
|
|
83
|
+
const kept: SessionRecord[] = []
|
|
84
|
+
|
|
85
|
+
for (const found of await state.core.store.sessions.listByUser(record.id)) {
|
|
86
|
+
if (live(state.session.settings, found, record, now))
|
|
87
|
+
kept.push(found)
|
|
88
|
+
else
|
|
89
|
+
await state.core.store.sessions.delete(record.id, found.id)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Every lookup at once: the list waits on the slowest, not on their sum.
|
|
93
|
+
const places = await Promise.all(kept.map(async found => locate(state.core, found.ip)))
|
|
94
|
+
|
|
95
|
+
return kept.map((found, index) => ({
|
|
96
|
+
id: found.id,
|
|
97
|
+
current: found.id === signedIn?.session,
|
|
98
|
+
device: readDevice(found.userAgent),
|
|
99
|
+
userAgent: found.userAgent,
|
|
100
|
+
ip: found.ip,
|
|
101
|
+
place: places[index]!,
|
|
102
|
+
createdAt: found.createdAt,
|
|
103
|
+
lastSeenAt: found.lastSeenAt,
|
|
104
|
+
}))
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function live(settings: SessionSettings, session: SessionRecord, record: UserRecord, now: number): boolean {
|
|
108
|
+
return session.version === record.sessionVersion && now - session.lastSeenAt.getTime() < (session.maxAge ?? durationSeconds(settings.maxAge, 'the session maxAge')) * 1000 && now - session.createdAt.getTime() < durationSeconds(settings.absoluteMaxAge, 'the session absoluteMaxAge') * 1000
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// A failure is logged, not thrown: a lookup service down must not hide the list.
|
|
112
|
+
async function locate(core: Core, ip: string): Promise<string | null> {
|
|
113
|
+
try {
|
|
114
|
+
return await core.locate?.(ip) ?? null
|
|
115
|
+
}
|
|
116
|
+
catch (error) {
|
|
117
|
+
log.error('locate failed', error)
|
|
118
|
+
|
|
119
|
+
return null
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Keeps what the sign-in starting now chose about being remembered, for the session it opens; none leaves the session plugin's own lifetime.
|
|
124
|
+
export async function chooseRemember(state: RequestState, remember: boolean | undefined): Promise<void> {
|
|
125
|
+
if (remember !== undefined)
|
|
126
|
+
await state.session.set('authRemember', remember)
|
|
127
|
+
else if (await state.session.get('authRemember') !== undefined)
|
|
128
|
+
await state.session.unset('authRemember')
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// Gives the session signing in the lifetime `remember` chose, back to the session plugin's `maxAge` without a choice since one may linger from a sign-in before, and answers it in seconds, null for that `maxAge`.
|
|
132
|
+
export async function applyLifetime(state: RequestState, remember: boolean | undefined): Promise<number | null> {
|
|
133
|
+
const { core, session } = state
|
|
134
|
+
|
|
135
|
+
if (remember === undefined) {
|
|
136
|
+
await session.maxAge(session.settings.maxAge)
|
|
137
|
+
|
|
138
|
+
return null
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
await session.maxAge(remember ? `${core.rememberMaxAge}s` : 'browser')
|
|
142
|
+
|
|
143
|
+
return remember ? core.rememberMaxAge : durationSeconds(session.settings.browserMaxAge, 'the session browserMaxAge')
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// After a change to how the account is signed in to: every session the user holds ends but this browser's, and every bearer token with them, since one minted from a stolen session would outlive it.
|
|
147
|
+
export async function endOtherSessions(state: RequestState, record: UserRecord, patch: Partial<UserRecord> = {}): Promise<UserRecord | undefined> {
|
|
148
|
+
const updated = await state.core.store.users.update(record.id, { ...patch, sessionVersion: record.sessionVersion + 1 })
|
|
149
|
+
|
|
150
|
+
await revokeBearerTokens(state.core, record.id)
|
|
151
|
+
|
|
152
|
+
if (updated)
|
|
153
|
+
await state.renew(updated)
|
|
154
|
+
|
|
155
|
+
return updated
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export async function revokeBearerTokens(core: Core, userId: string): Promise<void> {
|
|
159
|
+
const { bearerTokens } = core.store
|
|
160
|
+
|
|
161
|
+
await core.store.oauth?.refresh.erase(userId)
|
|
162
|
+
|
|
163
|
+
if (bearerTokens.erase) {
|
|
164
|
+
await bearerTokens.erase(userId)
|
|
165
|
+
|
|
166
|
+
return
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
for (const token of await bearerTokens.listByUser(userId))
|
|
170
|
+
await bearerTokens.delete(userId, token.id)
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export async function removeIdentities(core: Core, userId: string): Promise<void> {
|
|
174
|
+
const { identities } = core.store
|
|
175
|
+
|
|
176
|
+
if (identities.erase) {
|
|
177
|
+
await identities.erase(userId)
|
|
178
|
+
|
|
179
|
+
return
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
for (const identity of await identities.listByUser(userId))
|
|
183
|
+
await identities.delete(identity.provider, identity.providerId)
|
|
184
|
+
}
|
package/src/setup.ts
ADDED
|
@@ -0,0 +1,417 @@
|
|
|
1
|
+
import type { Duration } from 'kay'
|
|
2
|
+
import type { Access } from './access'
|
|
3
|
+
import type { AuthOptions } from './auth'
|
|
4
|
+
import type { AuthSessionData, Core } from './core'
|
|
5
|
+
import type { AccountOptions } from './deletion'
|
|
6
|
+
import type { EmailOptions } from './email'
|
|
7
|
+
import type { AuthPagesConfig, PagesHandle } from './pages'
|
|
8
|
+
import type { AuthStore, LinkType, TokenType } from './store'
|
|
9
|
+
import { asConfigError, configError, configuredSite, decide, dispatch, durationSeconds, kv } from 'kay/library'
|
|
10
|
+
import { accessOf } from './access'
|
|
11
|
+
import { pwnedPassword } from './breached'
|
|
12
|
+
import { proofOfWork } from './captcha'
|
|
13
|
+
import { authContext } from './events'
|
|
14
|
+
import { forwardOf } from './forwardAuth'
|
|
15
|
+
import { guardOf } from './guards'
|
|
16
|
+
import { deriveKeys } from './keys'
|
|
17
|
+
import { resolveLimits } from './limits'
|
|
18
|
+
import { log } from './log'
|
|
19
|
+
import { mailLanguages } from './mail'
|
|
20
|
+
import { createOAuthClient } from './oauth/client'
|
|
21
|
+
import { createOAuthTokenRefresher } from './oauth/refresher'
|
|
22
|
+
import { organizationsCore } from './organizationsCore'
|
|
23
|
+
import { DEFAULT_PREFIX as DEFAULT_PAGES_PREFIX, pagePaths, pagesOf } from './pages'
|
|
24
|
+
import { authLimiters } from './rates'
|
|
25
|
+
import { resolveRules } from './rules-check'
|
|
26
|
+
import { userDataRules } from './userData'
|
|
27
|
+
|
|
28
|
+
const TRAILING_SLASH = /\/$/
|
|
29
|
+
|
|
30
|
+
const DEFAULT_REMEMBER_MAX_AGE = 90 * 24 * 60 * 60
|
|
31
|
+
const DEFAULT_AUDIT_MAX_AGE = 365 * 24 * 60 * 60
|
|
32
|
+
const DEFAULT_GUEST_MAX_AGE = 30 * 24 * 60 * 60
|
|
33
|
+
const DEFAULT_UNVERIFIED_MAX_AGE = 30 * 24 * 60 * 60
|
|
34
|
+
const LINK_TYPES: LinkType[] = ['verify-email', 'reset-password', 'magic-link', 'change-email']
|
|
35
|
+
|
|
36
|
+
const MINUTE = 60
|
|
37
|
+
const HOUR = 60 * MINUTE
|
|
38
|
+
|
|
39
|
+
// How long each link and code works, in seconds, unless the `email.maxAge` option says otherwise.
|
|
40
|
+
const TOKEN_LIFETIMES: Record<TokenType, number> = {
|
|
41
|
+
'verify-email': 24 * HOUR,
|
|
42
|
+
'reset-password': HOUR,
|
|
43
|
+
'magic-link': 15 * MINUTE,
|
|
44
|
+
'change-email': HOUR,
|
|
45
|
+
'sign-in-code': 10 * MINUTE,
|
|
46
|
+
'verify-code': 10 * MINUTE,
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// The lifetimes the `maxAge` option sets over the defaults, in seconds, a bad one failing at boot naming it.
|
|
50
|
+
export function tokenLifetimes(maxAge: EmailOptions['maxAge']): Record<TokenType, number> {
|
|
51
|
+
const lifetimes = { ...TOKEN_LIFETIMES }
|
|
52
|
+
const named = (key: string): string => `email.maxAge.${key}`
|
|
53
|
+
const unknown = Object.keys(maxAge ?? {}).find(key => !Object.hasOwn(TOKEN_LIFETIMES, key))
|
|
54
|
+
|
|
55
|
+
if (unknown !== undefined)
|
|
56
|
+
throw configError('auth', 'links', `${named(unknown)} is no link or code of kayjs-auth`)
|
|
57
|
+
|
|
58
|
+
for (const type of Object.keys(lifetimes) as TokenType[]) {
|
|
59
|
+
const wanted = maxAge?.[type]
|
|
60
|
+
|
|
61
|
+
if (wanted !== undefined)
|
|
62
|
+
lifetimes[type] = durationSeconds(wanted, named(type))
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
return lifetimes
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// A hook of the options as the positional function the core calls, given its event object.
|
|
69
|
+
function hooked<Args extends unknown[], Result>(hook: ((...args: never[]) => Result) | undefined, event: (...args: Args) => object): ((...args: Args) => Result) | undefined {
|
|
70
|
+
return hook && ((...args: Args) => hook(event(...args) as never))
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// `onSignUp` as the flows call it: told through `dispatch`, so a throw is reported and never fails the sign-up that happened.
|
|
74
|
+
function signUpHook(hook: AuthOptions<AuthSessionData, string>['onSignUp']): Core['onSignUp'] {
|
|
75
|
+
return hook && (async (user, profile) => dispatch('auth.onSignUp', [hook as never], { user, profile }, { context: await authContext() }))
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// `beforeDelete` as the erase asks it: a refusal answers the failure of kind `refused`, carrying the status and message the hook gave.
|
|
79
|
+
function deleteHook(hook: AuthOptions<AuthSessionData, string>['beforeDelete']): Core['beforeDelete'] {
|
|
80
|
+
return hook && (async (user, actor) => {
|
|
81
|
+
const answer = await decide('auth.beforeDelete', [hook as never], { user }, await authContext(actor))
|
|
82
|
+
|
|
83
|
+
if ('refused' in answer) {
|
|
84
|
+
const { status, message, errors, data } = answer.refused
|
|
85
|
+
|
|
86
|
+
return { code: 'refused', status, message, errors, data }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return undefined
|
|
90
|
+
})
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// The seconds of a lifetime option, rounded up to whole ones as a cookie's Max-Age and the stored lifetimes take them.
|
|
94
|
+
function wholeSeconds(value: Duration, what: string): number {
|
|
95
|
+
return Math.ceil(durationSeconds(value, what))
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Seconds an account never verified is kept: only where unverified accounts cannot sign in, as one that can is an account in use.
|
|
99
|
+
function unverifiedMaxAge(email: EmailOptions | undefined): number | undefined {
|
|
100
|
+
if (!email)
|
|
101
|
+
return undefined
|
|
102
|
+
|
|
103
|
+
if (email.unverifiedMaxAge !== undefined)
|
|
104
|
+
return wholeSeconds(email.unverifiedMaxAge, 'email.unverifiedMaxAge')
|
|
105
|
+
|
|
106
|
+
return email.requireVerified ?? true ? DEFAULT_UNVERIFIED_MAX_AGE : undefined
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// The grace period `account.deleteAfter` sets: a store that cannot list the accounts due is refused, as is a mail link with no page to open.
|
|
110
|
+
function deletionOf(options: { account?: AccountOptions | undefined, store: AuthStore }, pages: Core['pages']): Core['deletion'] {
|
|
111
|
+
const account = options.account
|
|
112
|
+
|
|
113
|
+
if (account?.deleteAfter === undefined)
|
|
114
|
+
return undefined
|
|
115
|
+
|
|
116
|
+
if (!options.store.users.dueForDeletion || !options.store.users.markForDeletion)
|
|
117
|
+
throw configError('auth', 'account', '`account.deleteAfter` needs a store with `users.dueForDeletion` and `users.markForDeletion`, as `memoryAuth` and `pgAuth` have')
|
|
118
|
+
|
|
119
|
+
if (!pages && account.cancelPage === undefined)
|
|
120
|
+
throw configError('auth', 'account', '`account.deleteAfter` mails a link to cancel the deletion: set `pages` for the prebuilt account page, or `account.cancelPage` to your own')
|
|
121
|
+
|
|
122
|
+
return { after: wholeSeconds(account.deleteAfter, 'account.deleteAfter'), cancelPage: account.cancelPage }
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function auditMaxAge(audit: true | { maxAge?: Duration, ip?: 'full' | 'truncated' }): number {
|
|
126
|
+
return audit === true || audit.maxAge === undefined ? DEFAULT_AUDIT_MAX_AGE : wholeSeconds(audit.maxAge, 'audit.maxAge')
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// Lets `auth()` hand a `authCore({ pages: true })` its prefix and home, the paths derived from the prefix following, whichever of the two ran first.
|
|
130
|
+
export function pagesHandle(core: Core, options: { pages?: boolean | AuthPagesConfig | undefined, signInPage?: string | undefined, twoFactorPage?: string | undefined, sessionsPage?: string | undefined, securityPage?: string | undefined, email?: { links?: Partial<Record<LinkType, string>> | undefined } | undefined }): PagesHandle {
|
|
131
|
+
const own = typeof options.pages === 'object' ? options.pages : {}
|
|
132
|
+
|
|
133
|
+
return {
|
|
134
|
+
adopt(given) {
|
|
135
|
+
const pages = core.pages
|
|
136
|
+
|
|
137
|
+
if (!pages)
|
|
138
|
+
return
|
|
139
|
+
|
|
140
|
+
if (own.prefix !== undefined && own.prefix !== (given.prefix ?? DEFAULT_PAGES_PREFIX))
|
|
141
|
+
throw configError('auth', 'pages', `auth() serves the pages under '${given.prefix ?? DEFAULT_PAGES_PREFIX}' and authCore({ pages: { prefix: '${own.prefix}' } }) sends users to '${own.prefix}'. Give auth({ prefix: '${own.prefix}' }), or drop the prefix of one of them`)
|
|
142
|
+
|
|
143
|
+
if (own.home === undefined && given.home !== undefined)
|
|
144
|
+
pages.home = given.home
|
|
145
|
+
else if (own.home !== undefined && given.home !== undefined && own.home !== given.home)
|
|
146
|
+
log.warn(`auth({ home: '${given.home}' }) and authCore({ pages: { home: '${own.home}' } }) differ, and authCore's wins: users go to '${own.home}'. Give home once, or the same in both`)
|
|
147
|
+
|
|
148
|
+
if (own.prefix !== undefined || given.prefix === undefined || given.prefix === pages.prefix)
|
|
149
|
+
return
|
|
150
|
+
|
|
151
|
+
const paths = pagePaths(given.prefix)
|
|
152
|
+
|
|
153
|
+
pages.prefix = given.prefix
|
|
154
|
+
core.signInPage = options.signInPage ?? paths.signIn
|
|
155
|
+
core.twoFactorPage = options.twoFactorPage ?? paths.twoFactor
|
|
156
|
+
core.sessionsPage = options.sessionsPage ?? paths.sessions
|
|
157
|
+
core.securityPage = options.securityPage ?? paths.security
|
|
158
|
+
|
|
159
|
+
if (core.email)
|
|
160
|
+
core.email.links = emailLinks(options.email?.links, paths.links)
|
|
161
|
+
},
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const HAS_SCHEME = /^[a-z][\d+.a-z-]*:\/\//i
|
|
166
|
+
const HOST_LIKE = /^(?:[\w-]+(?:\.[\w-]+)+(?::\d+)?|[\w.-]+:\d+)$/
|
|
167
|
+
|
|
168
|
+
// The keys are derived as `auth()` is made when it has a secret of its own, or a session that cannot derive one, so a bad one fails there; the session's is derived on first use.
|
|
169
|
+
function checkKeys(core: Core, options: { secret?: string | string[] | undefined, sessions: { deriveSecret?: unknown } }): void {
|
|
170
|
+
if (options.secret !== undefined || options.sessions.deriveSecret === undefined)
|
|
171
|
+
void core.keys
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// The origin and the display name the options give: `site` is the origin, which has a scheme.
|
|
175
|
+
function siteOptions(options: { site?: string | undefined, name?: string | undefined }): { origin: string | undefined, name: string | undefined } {
|
|
176
|
+
const site = options.site
|
|
177
|
+
|
|
178
|
+
if (site !== undefined && !HAS_SCHEME.test(site))
|
|
179
|
+
throw configError('auth', 'site', HOST_LIKE.test(site) ? `\`site\` is the site's origin, such as \`https://${site}\`, and \`${site}\` has no scheme: add it, or give the display name as \`name\`` : `\`site\` is the site's origin, such as \`https://example.com\`, and \`${site}\` is not one: give the display name as \`name\``)
|
|
180
|
+
|
|
181
|
+
return { origin: site, name: options.name }
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function noSecret(): never {
|
|
185
|
+
throw configError('auth', 'secret', '`secret` is missing and the session plugin cannot derive one; pass a secret of at least 32 characters, or a plugin from kay\'s `session()`')
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// What createCore builds on the site's origin, once it has one.
|
|
189
|
+
interface SiteBound {
|
|
190
|
+
url: string | undefined
|
|
191
|
+
oauth: Core['oauth']
|
|
192
|
+
refreshers: Core['refreshers']
|
|
193
|
+
name: string
|
|
194
|
+
passkeys: Core['passkeys']
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function warnWithoutPrivacy(pages: ReturnType<typeof pagesOf>, options: { signUp?: boolean | undefined, password?: unknown }) {
|
|
198
|
+
if (process.env.NODE_ENV === 'production' && pages && pages.privacy === undefined && (options.signUp ?? true) && options.password !== false)
|
|
199
|
+
log.warn('the stock register page collects an email address and states no purpose and links no privacy policy: set `pages: { privacy: \'/privacy\' }`, with `purpose` for the line above the link')
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export function createCore<Data extends AuthSessionData, Role extends string, Prefix extends string, Scope extends string, OrgRole extends string, UserData extends object>(options: AuthOptions<Data, Role, Prefix, Scope, OrgRole, UserData>): Core {
|
|
203
|
+
const prefix = options.prefix ?? '/auth'
|
|
204
|
+
|
|
205
|
+
const oauthApps = Object.entries(options.oauth ?? {})
|
|
206
|
+
const { origin, name } = siteOptions(options)
|
|
207
|
+
const given = origin?.replace(TRAILING_SLASH, '')
|
|
208
|
+
const languages = options.email && mailLanguages(options.email)
|
|
209
|
+
const pages = pagesOf(options.pages)
|
|
210
|
+
const passkeyOptions = options.passkeys === false ? undefined : options.passkeys
|
|
211
|
+
const paths = pages && pagePaths(pages.prefix)
|
|
212
|
+
const access = accessOf<Role>(options)
|
|
213
|
+
const admin = options.admin
|
|
214
|
+
|
|
215
|
+
if (process.env.NODE_ENV === 'production' && admin !== undefined && options.twoFactor !== false && !(typeof options.twoFactor === 'object' && options.twoFactor.require !== undefined))
|
|
216
|
+
log.warn('`admin` is on and no `twoFactor.require` names it, so an admin can sign in without two-factor: set `twoFactor: { require: [\'admin\'] }`')
|
|
217
|
+
|
|
218
|
+
warnWithoutPrivacy(pages, options)
|
|
219
|
+
|
|
220
|
+
const needsUrl = oauthApps.length > 0 || options.email !== undefined
|
|
221
|
+
let bound: SiteBound | undefined
|
|
222
|
+
// What a core with no origin yet builds: with nothing to build on it is the same each time, so it is kept until an origin turns up.
|
|
223
|
+
let waiting: SiteBound | undefined
|
|
224
|
+
|
|
225
|
+
// What depends on the site's origin: `url` if given, else the `site` of kay.config.ts or SITE_URL, which a server knows once it set up. An auth made while the app's modules load asks again when first used, and keeps what it built once it has an origin.
|
|
226
|
+
const bind = (): SiteBound => {
|
|
227
|
+
if (bound)
|
|
228
|
+
return bound
|
|
229
|
+
|
|
230
|
+
const url = given ?? configuredSite()?.origin.replace(TRAILING_SLASH, '')
|
|
231
|
+
|
|
232
|
+
if (needsUrl && url === undefined)
|
|
233
|
+
throw configError('auth', 'site', 'OAuth sign-in and mailed links need the site\'s public origin to build their URLs: set `site` in kay.config.ts or SITE_URL, or in authCore')
|
|
234
|
+
|
|
235
|
+
if (url === undefined && waiting)
|
|
236
|
+
return waiting
|
|
237
|
+
|
|
238
|
+
const clients: Core['oauth'] = new Map()
|
|
239
|
+
|
|
240
|
+
for (const [name, app] of oauthApps)
|
|
241
|
+
clients.set(name, { app, client: createOAuthClient(app.provider, { clientId: app.clientId, clientSecret: app.clientSecret, redirectUri: `${url}${prefix}/${name}/callback` }) })
|
|
242
|
+
|
|
243
|
+
const made: SiteBound = {
|
|
244
|
+
url,
|
|
245
|
+
oauth: clients,
|
|
246
|
+
refreshers: new Map(),
|
|
247
|
+
name: name ?? (url === undefined ? 'kayjs-auth' : new URL(url).host),
|
|
248
|
+
passkeys: url === undefined || options.passkeys === false
|
|
249
|
+
? undefined
|
|
250
|
+
: { id: passkeyOptions?.rpId ?? new URL(url).hostname, name: passkeyOptions?.rpName ?? name ?? new URL(url).host, origins: passkeyOptions?.origins ?? [new URL(url).origin], userVerification: passkeyOptions?.userVerification ?? 'preferred' },
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
if (url === undefined)
|
|
254
|
+
waiting = made
|
|
255
|
+
else
|
|
256
|
+
bound = made
|
|
257
|
+
|
|
258
|
+
refreshersFor(made)
|
|
259
|
+
|
|
260
|
+
return made
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// Without a mailer registering signs the new user in, so it cannot answer alike for a held address and a free one.
|
|
264
|
+
if (process.env.NODE_ENV === 'production' && (options.signUp ?? true) && options.password !== false && !(options.email?.requireVerified ?? options.email !== undefined))
|
|
265
|
+
log.warn('password sign-up is open with no `email` option or with `requireVerified` off, so `password.register` answers `taken` for an address that has an account and tells a guest which addresses exist: set `email` with a mailer (and `requireVerified` on), or `signUp: false`')
|
|
266
|
+
|
|
267
|
+
let keys: Core['keys'] | undefined
|
|
268
|
+
const core: Core = {
|
|
269
|
+
store: options.store,
|
|
270
|
+
rates: authLimiters(options.store),
|
|
271
|
+
// On first use, as the session's secret may be the config's, which is not read while a module loads.
|
|
272
|
+
get keys() {
|
|
273
|
+
return keys ??= deriveKeys(options.secret ?? options.sessions.deriveSecret?.('kayjs-auth') ?? noSecret())
|
|
274
|
+
},
|
|
275
|
+
get url() {
|
|
276
|
+
return bind().url
|
|
277
|
+
},
|
|
278
|
+
settle() {
|
|
279
|
+
if (needsUrl)
|
|
280
|
+
bind()
|
|
281
|
+
},
|
|
282
|
+
prefix,
|
|
283
|
+
signInPage: options.signInPage ?? paths?.signIn ?? '/',
|
|
284
|
+
ownSignInPage: options.signInPage,
|
|
285
|
+
twoFactorPage: options.twoFactorPage ?? paths?.twoFactor ?? '/two-factor',
|
|
286
|
+
pages,
|
|
287
|
+
get name() {
|
|
288
|
+
return bind().name
|
|
289
|
+
},
|
|
290
|
+
limits: resolveLimits(options.rateLimit),
|
|
291
|
+
rules: asConfigError(() => resolveRules(options.rules)),
|
|
292
|
+
sessionsPage: options.sessionsPage ?? paths?.sessions,
|
|
293
|
+
securityPage: options.securityPage ?? paths?.security,
|
|
294
|
+
locate: options.locate,
|
|
295
|
+
scopes: new Set(options.scopes),
|
|
296
|
+
get passkeys() {
|
|
297
|
+
return bind().passkeys
|
|
298
|
+
},
|
|
299
|
+
switches: { password: options.password !== false, passkeys: options.passkeys !== false, magicLink: options.magicLink !== false, twoFactor: options.twoFactor !== false },
|
|
300
|
+
...typeof options.twoFactor === 'object' && options.twoFactor.require !== undefined && { twoFactorRequire: options.twoFactor.require },
|
|
301
|
+
captcha: options.captcha === false ? undefined : options.captcha ?? proofOfWork(),
|
|
302
|
+
breached: breachedCheck(options.breachedPasswords),
|
|
303
|
+
email: options.email && {
|
|
304
|
+
...options.email,
|
|
305
|
+
maxAge: tokenLifetimes(options.email.maxAge),
|
|
306
|
+
links: emailLinks(options.email.links, paths?.links),
|
|
307
|
+
requireVerified: options.email.requireVerified ?? true,
|
|
308
|
+
get locales() {
|
|
309
|
+
return languages!.locales()
|
|
310
|
+
},
|
|
311
|
+
get templates() {
|
|
312
|
+
return languages!.templates()
|
|
313
|
+
},
|
|
314
|
+
codes: typeof options.email.codes === 'string' ? { 'magic-link': options.email.codes, 'verify-email': options.email.codes } : { 'magic-link': 'link', 'verify-email': 'link', ...options.email.codes },
|
|
315
|
+
},
|
|
316
|
+
oauthServer: oauthServerOf(options, pages),
|
|
317
|
+
forward: forwardOf(options.forwardAuth, options.twoFactor !== false),
|
|
318
|
+
get oauth() {
|
|
319
|
+
return bind().oauth
|
|
320
|
+
},
|
|
321
|
+
get refreshers() {
|
|
322
|
+
return bind().refreshers
|
|
323
|
+
},
|
|
324
|
+
allow: options.allow,
|
|
325
|
+
signUp: options.signUp ?? true,
|
|
326
|
+
defaultRoles: [...(options.defaultRoles ?? [])],
|
|
327
|
+
roles: options.roles && new Set(Object.keys(options.roles)),
|
|
328
|
+
hierarchy: options.roles,
|
|
329
|
+
access: access as unknown as Access<string>,
|
|
330
|
+
...admin !== undefined && { admin: async user => access.authorize(user, admin, 'write', {}) },
|
|
331
|
+
guard: guardOptions => guardOf(core, guardOptions),
|
|
332
|
+
onSignUp: signUpHook(options.onSignUp),
|
|
333
|
+
onProviderProfile: hooked(options.profileFields, (user, profile) => ({ user, profile })),
|
|
334
|
+
userData: options.user && userDataRules(options.user),
|
|
335
|
+
beforeDelete: deleteHook(options.beforeDelete),
|
|
336
|
+
|
|
337
|
+
guestMaxAge: options.guests === undefined ? DEFAULT_GUEST_MAX_AGE : wholeSeconds(options.guests.maxAge, 'guests.maxAge'),
|
|
338
|
+
unverifiedMaxAge: unverifiedMaxAge(options.email),
|
|
339
|
+
deletion: deletionOf(options, pages),
|
|
340
|
+
onExport: hooked(options.exportData, user => ({ user })),
|
|
341
|
+
onEvent: options.onEvent,
|
|
342
|
+
|
|
343
|
+
organizations: options.organizations && organizationsCore(options.organizations, access),
|
|
344
|
+
pruned: { at: 0 },
|
|
345
|
+
audit: options.audit == null || options.audit === false ? undefined : { maxAge: auditMaxAge(options.audit), prunedAt: 0, ip: options.audit === true ? 'truncated' : options.audit.ip ?? 'truncated' },
|
|
346
|
+
rememberMaxAge: wholeSeconds(options.remember?.maxAge ?? `${DEFAULT_REMEMBER_MAX_AGE}s`, 'remember.maxAge'),
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
checkKeys(core, options)
|
|
350
|
+
|
|
351
|
+
function refreshersFor(made: SiteBound): void {
|
|
352
|
+
for (const [name, { client }] of made.oauth) {
|
|
353
|
+
made.refreshers.set(name, createOAuthTokenRefresher({
|
|
354
|
+
oauth: client,
|
|
355
|
+
key: subject => `${name}:${subject.identity.providerId}`,
|
|
356
|
+
load: subject => subject.credential,
|
|
357
|
+
save: async (subject, tokens) => {
|
|
358
|
+
// A refusal can be a race another process won, its rotated token saved since this one was read: that one stays.
|
|
359
|
+
if (tokens === null && (await core.store.identities.find(name, subject.identity.providerId))?.refreshToken !== subject.identity.refreshToken)
|
|
360
|
+
return
|
|
361
|
+
|
|
362
|
+
const sealed = (await import('./oauth/flow')).sealTokens(core, name, subject.identity.providerId, tokens)
|
|
363
|
+
|
|
364
|
+
// A refresh that rotates no refresh token leaves the one held usable.
|
|
365
|
+
await core.store.identities.update(name, subject.identity.providerId, tokens && tokens.refreshToken === undefined ? { ...sealed, refreshToken: subject.identity.refreshToken } : sealed)
|
|
366
|
+
},
|
|
367
|
+
onError: error => log.error(`refreshing a ${name} token failed`, error),
|
|
368
|
+
}))
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
if (given !== undefined || configuredSite() !== undefined)
|
|
373
|
+
bind()
|
|
374
|
+
|
|
375
|
+
return core
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function oauthServerOf(options: { oauthServer?: boolean | { fetch?: ((url: string) => Promise<Response>) | undefined, defaultScopes?: readonly string[] | undefined } | undefined, scopes?: readonly string[] | undefined, store: AuthStore }, pages: Core['pages']): Core['oauthServer'] {
|
|
379
|
+
const wanted = options.oauthServer
|
|
380
|
+
|
|
381
|
+
if (wanted === false || (wanted === undefined && !(pages && options.store.oauth)))
|
|
382
|
+
return undefined
|
|
383
|
+
|
|
384
|
+
if (!pages || !options.store.oauth)
|
|
385
|
+
throw configError('auth', 'oauthServer', '`oauthServer` needs the prebuilt `pages`, for its consent page, and a store with `oauth`, as `memoryAuth` and `pgAuth` have')
|
|
386
|
+
|
|
387
|
+
const custom = typeof wanted === 'object' ? wanted.fetch : undefined
|
|
388
|
+
const defaultScopes = typeof wanted === 'object' ? [...new Set(wanted.defaultScopes)] : []
|
|
389
|
+
|
|
390
|
+
if (defaultScopes.some(scope => !options.scopes?.includes(scope)))
|
|
391
|
+
throw configError('auth', 'scopes', '`oauthServer.defaultScopes` names a scope that `scopes` does not declare')
|
|
392
|
+
|
|
393
|
+
// Switched on by the app, not by the pages and the store alone, which every app with the prebuilt pages has.
|
|
394
|
+
if (wanted !== undefined && (options.scopes?.length ?? 0) === 0)
|
|
395
|
+
log.warn('oauthServer is on but authCore declares no `scopes`, so every OAuth token gets every scope: declare `scopes` and give routes a `scope:`')
|
|
396
|
+
|
|
397
|
+
return { fetchDocument: async url => (await import('./authorize/clients')).documentFetcher(custom)(url), documents: kv('auth:oauth-documents'), defaultScopes }
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// On by default in production, where `false` turns it off.
|
|
401
|
+
function breachedCheck(option: boolean | ((password: string) => boolean | Promise<boolean>) | undefined): ((password: string) => boolean | Promise<boolean>) | undefined {
|
|
402
|
+
if (option === true || (option === undefined && process.env.NODE_ENV === 'production'))
|
|
403
|
+
return pwnedPassword
|
|
404
|
+
|
|
405
|
+
return typeof option === 'function' ? option : undefined
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
// The page each mailed link opens: the app's, else the prebuilt one.
|
|
409
|
+
function emailLinks(links: Partial<Record<LinkType, string>> | undefined, pages: Record<LinkType, string> | undefined): Record<LinkType, string> {
|
|
410
|
+
const merged = Object.fromEntries(LINK_TYPES.map(type => [type, links?.[type] ?? pages?.[type]]))
|
|
411
|
+
const missing = LINK_TYPES.filter(type => merged[type] === undefined)
|
|
412
|
+
|
|
413
|
+
if (missing.length > 0)
|
|
414
|
+
throw configError('auth', 'email', `email.links needs a page for ${missing.join(', ')}, or \`pages\` for the prebuilt ones`)
|
|
415
|
+
|
|
416
|
+
return merged as Record<LinkType, string>
|
|
417
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// What a way of signing in takes after its credentials, as a trailing options object: where to go next, whether the session is remembered, and the CAPTCHA widget's token. A method takes the ones it uses.
|
|
2
|
+
export interface SignInOptions {
|
|
3
|
+
// Where to go once signed in, a path on the site; the pages' home, `/` by default.
|
|
4
|
+
redirect?: string | undefined
|
|
5
|
+
// Whether the session lasts `remember.maxAge` (true) or until the browser closes (false), when the sign-in form asks; the session plugin's own lifetime without it.
|
|
6
|
+
remember?: boolean | undefined
|
|
7
|
+
// The CAPTCHA widget's token, when the app asks for one.
|
|
8
|
+
captcha?: string | undefined
|
|
9
|
+
}
|
package/src/state.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { Session } from 'kay/server'
|
|
2
|
+
import type { AuthSessionData, Core } from './core'
|
|
3
|
+
import type { AuthFailed } from './failure'
|
|
4
|
+
import type { UserRecord } from './store'
|
|
5
|
+
|
|
6
|
+
// What a flow works with for one request.
|
|
7
|
+
export interface RequestState {
|
|
8
|
+
core: Core
|
|
9
|
+
session: Session<AuthSessionData>
|
|
10
|
+
// Who is asking as rate limits count them: a keyed digest of the address, so the attempts table holds no address.
|
|
11
|
+
client: string
|
|
12
|
+
// The client's address as it is, for the list of where the user is signed in.
|
|
13
|
+
address: string
|
|
14
|
+
userAgent: string
|
|
15
|
+
// The languages the browser asks for, most wanted first.
|
|
16
|
+
languages: string[]
|
|
17
|
+
// Whether the request is a browser's cross-site POST or upgrade, which the session refuses to be read or written by.
|
|
18
|
+
crossSite: () => boolean
|
|
19
|
+
current: () => Promise<UserRecord | null>
|
|
20
|
+
// How the current user was read, once `current` has been.
|
|
21
|
+
via: () => 'session' | 'bearer' | null
|
|
22
|
+
// Signs `record` in, `method` saying how for the `signed-in` event, and answers where the browser goes next; refused while an admin bans them.
|
|
23
|
+
complete: (record: UserRecord, redirect: string, method: string) => Promise<{ ok: true, redirect: string } | AuthFailed<'banned'>>
|
|
24
|
+
// Signs `record` in under a new session id, with no ban check: for a flow that checked already, as a second factor does.
|
|
25
|
+
establish: (record: UserRecord, method: string) => Promise<void>
|
|
26
|
+
// Signs this session out, telling `onEvent`.
|
|
27
|
+
signOut: () => Promise<void>
|
|
28
|
+
// Takes `record` as the user this request is, as when an admin starts acting as them, and tags the browser's `local()` mirrors with them.
|
|
29
|
+
adopt: (record: UserRecord) => void
|
|
30
|
+
// Reads who the session is again, tagging the mirrors with them, and signs it out when nobody is.
|
|
31
|
+
reload: () => Promise<void>
|
|
32
|
+
// Keeps this session signed in as `record` after its session version was raised, when it is that user's.
|
|
33
|
+
renew: (record: UserRecord) => Promise<void>
|
|
34
|
+
}
|