@kayjs/auth 0.0.0-stage → 1.104.1
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/store.ts
ADDED
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
import type { Duration } from 'kay'
|
|
2
|
+
import type { MaybePromise } from 'kay/library'
|
|
3
|
+
import type { AuthRates } from './rates'
|
|
4
|
+
// An account as kayjs-auth stores it. The app sees a `User`, which leaves the secrets out.
|
|
5
|
+
export interface UserRecord {
|
|
6
|
+
id: string
|
|
7
|
+
// Lowercase; unique when set.
|
|
8
|
+
email: string | null
|
|
9
|
+
emailVerifiedAt: Date | null
|
|
10
|
+
// Unique when set, compared without case.
|
|
11
|
+
username: string | null
|
|
12
|
+
passwordHash: string | null
|
|
13
|
+
// Encrypted with the auth secret, bound to the user's id.
|
|
14
|
+
totpSecret: string | null
|
|
15
|
+
totpEnabledAt: Date | null
|
|
16
|
+
// The last 30-second step a code was accepted for, so no code is accepted twice.
|
|
17
|
+
totpLastStep: number
|
|
18
|
+
roles: string[]
|
|
19
|
+
// Raised to sign the user out everywhere: a session holding an older one is signed out.
|
|
20
|
+
sessionVersion: number
|
|
21
|
+
// A keyed digest of where the last sign-in came from.
|
|
22
|
+
lastSignIn: string | null
|
|
23
|
+
// The language the user reads, a BCP 47 tag such as `fr` or `pt-BR`, for their mails.
|
|
24
|
+
locale: string | null
|
|
25
|
+
// Made by `signInAsGuest`, with no way back in once its session ends, until registering or an OAuth sign-in makes it a real account.
|
|
26
|
+
guest: boolean
|
|
27
|
+
// Set while an admin bars the user from signing in, until `bannedUntil` or for good when null.
|
|
28
|
+
bannedAt: Date | null
|
|
29
|
+
bannedUntil: Date | null
|
|
30
|
+
banReason: string | null
|
|
31
|
+
// Set while the account waits out `account.deleteAfter`: the instant the prune deletes it, unless the user cancels first. Left out or null for an account not pending deletion, and a store that holds nothing here reads as null.
|
|
32
|
+
deleteAt?: Date | null | undefined
|
|
33
|
+
// What the app keeps on the user, as JSON checked against the `user` schema; `{}` when it has none, and a store that holds nothing here reads as `{}` too.
|
|
34
|
+
data?: Record<string, unknown> | undefined
|
|
35
|
+
createdAt: Date
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// An account at an OAuth provider, linked to a user.
|
|
39
|
+
export interface IdentityRecord {
|
|
40
|
+
provider: string
|
|
41
|
+
providerId: string
|
|
42
|
+
userId: string
|
|
43
|
+
// The provider's tokens, encrypted with the auth secret and bound to the identity.
|
|
44
|
+
accessToken: string | null
|
|
45
|
+
refreshToken: string | null
|
|
46
|
+
tokenExpiresAt: Date | null
|
|
47
|
+
createdAt: Date
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// A token a device or an API client sends as `Authorization: Bearer`, stored as its digest.
|
|
51
|
+
export interface BearerTokenRecord {
|
|
52
|
+
id: string
|
|
53
|
+
userId: string
|
|
54
|
+
label: string
|
|
55
|
+
digest: string
|
|
56
|
+
// What the token may reach, from the scopes the app declares; null for everything its user may.
|
|
57
|
+
scopes: string[] | null
|
|
58
|
+
createdAt: Date
|
|
59
|
+
lastUsedAt: Date | null
|
|
60
|
+
// Null for a token that never expires.
|
|
61
|
+
expiresAt: Date | null
|
|
62
|
+
// Set on a token an OAuth client was given, which revoking the client takes back; left out otherwise.
|
|
63
|
+
oauth?: { clientId: string, family: string, resource?: string | null | undefined } | null | undefined
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// A client registered by itself with the app's OAuth server (dynamic client registration), always public: it holds no secret. A client named by a metadata document URL is read from that URL and not stored.
|
|
67
|
+
export interface OAuthClientRecord {
|
|
68
|
+
id: string
|
|
69
|
+
name: string
|
|
70
|
+
redirectUris: string[]
|
|
71
|
+
createdAt: Date
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// What a user approved for a client, so signing in again skips the consent page until they revoke it or the client asks for more.
|
|
75
|
+
export interface OAuthGrantRecord {
|
|
76
|
+
userId: string
|
|
77
|
+
clientId: string
|
|
78
|
+
// The client's name when it was approved, for the account page.
|
|
79
|
+
clientName: string
|
|
80
|
+
// Null for every scope.
|
|
81
|
+
scopes: string[] | null
|
|
82
|
+
createdAt: Date
|
|
83
|
+
lastUsedAt: Date | null
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// An authorization code, stored as its digest and spent once; the row stays until it expires, so a second spend is told from a code never issued.
|
|
87
|
+
export interface OAuthCodeRecord {
|
|
88
|
+
digest: string
|
|
89
|
+
userId: string
|
|
90
|
+
clientId: string
|
|
91
|
+
redirectUri: string
|
|
92
|
+
// The PKCE challenge, S256.
|
|
93
|
+
challenge: string
|
|
94
|
+
scopes: string[] | null
|
|
95
|
+
// The tokens issued for it share this one, so spending the code twice takes them all back.
|
|
96
|
+
family: string
|
|
97
|
+
// The resource (RFC 8707) asked at authorize, which its tokens are bound to; null or left out for a code that asked for none, and for a row stored before this field.
|
|
98
|
+
resource?: string | null | undefined
|
|
99
|
+
createdAt: Date
|
|
100
|
+
expiresAt: Date
|
|
101
|
+
usedAt: Date | null
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// A refresh token, stored as its digest and replaced by a new one each time it is spent.
|
|
105
|
+
export interface OAuthRefreshRecord {
|
|
106
|
+
digest: string
|
|
107
|
+
userId: string
|
|
108
|
+
clientId: string
|
|
109
|
+
scopes: string[] | null
|
|
110
|
+
family: string
|
|
111
|
+
// The resource the family is bound to, kept through each rotation; null or left out for none, and for a row stored before this field.
|
|
112
|
+
resource?: string | null | undefined
|
|
113
|
+
// A token unused for 30 days from here is refused.
|
|
114
|
+
createdAt: Date
|
|
115
|
+
// Where the whole family ends, 90 days after its first token and the same for each rotation, so a spent token stays this long to catch a reuse.
|
|
116
|
+
expiresAt: Date
|
|
117
|
+
// Set once spent: spending it again means it leaked, and takes the whole family back.
|
|
118
|
+
usedAt: Date | null
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// A browser signed in as a user, so they can see where they are signed in and end one.
|
|
122
|
+
export interface SessionRecord {
|
|
123
|
+
id: string
|
|
124
|
+
userId: string
|
|
125
|
+
// The user's session version it was signed in under: one raised since ends it.
|
|
126
|
+
version: number
|
|
127
|
+
// As the browser sent it, cut to 512 characters.
|
|
128
|
+
userAgent: string
|
|
129
|
+
// The client's address when it was last seen.
|
|
130
|
+
ip: string
|
|
131
|
+
createdAt: Date
|
|
132
|
+
lastSeenAt: Date
|
|
133
|
+
// Seconds it lives unseen, as chosen at sign-in; null for `sessionMaxAge`. Kept as the number of seconds a store saves.
|
|
134
|
+
maxAge: number | null
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// Where a page of the audit log ends: an instant, or the last entry of the page, which tells the entries of its millisecond apart.
|
|
138
|
+
export type AuditCursor = Date | Pick<AuditRecord, 'at' | 'id'>
|
|
139
|
+
|
|
140
|
+
// A line of the audit log, kept past its user's deletion so the log still tells what happened, under a name that no longer leads to them.
|
|
141
|
+
export interface AuditRecord {
|
|
142
|
+
id: string
|
|
143
|
+
userId: string
|
|
144
|
+
event: string
|
|
145
|
+
detail: string | null
|
|
146
|
+
ip: string
|
|
147
|
+
userAgent: string
|
|
148
|
+
actorId: string | null
|
|
149
|
+
at: Date
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// A passkey: a WebAuthn credential the user signs in with, by its credential id.
|
|
153
|
+
export interface PasskeyRecord {
|
|
154
|
+
// The credential id, base64url.
|
|
155
|
+
id: string
|
|
156
|
+
userId: string
|
|
157
|
+
name: string
|
|
158
|
+
// The COSE public key, base64url.
|
|
159
|
+
publicKey: string
|
|
160
|
+
// The authenticator's signature counter, 0 for one that does not count.
|
|
161
|
+
counter: number
|
|
162
|
+
// How the browser reaches the authenticator, such as 'internal' or 'usb'.
|
|
163
|
+
transports: string[]
|
|
164
|
+
// Whether it syncs between devices, as one in a password manager does.
|
|
165
|
+
multiDevice: boolean
|
|
166
|
+
backedUp: boolean
|
|
167
|
+
// Whether it has proved user verification, which signing in requires: a passkey made without it is no way in.
|
|
168
|
+
userVerified: boolean
|
|
169
|
+
createdAt: Date
|
|
170
|
+
lastUsedAt: Date | null
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// A team or a workspace users belong to, each with roles of its own there.
|
|
174
|
+
export interface OrganizationRecord {
|
|
175
|
+
id: string
|
|
176
|
+
name: string
|
|
177
|
+
// Unique when set, lowercase, for URLs such as `/orgs/acme`.
|
|
178
|
+
slug: string | null
|
|
179
|
+
createdAt: Date
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// A user's place in an organization.
|
|
183
|
+
export interface MemberRecord {
|
|
184
|
+
organizationId: string
|
|
185
|
+
userId: string
|
|
186
|
+
// From the hierarchy of the `organizations` option.
|
|
187
|
+
roles: string[]
|
|
188
|
+
createdAt: Date
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// An address asked to join an organization; its id is the link mailed, which only an account verified at that address can accept.
|
|
192
|
+
export interface InvitationRecord {
|
|
193
|
+
id: string
|
|
194
|
+
organizationId: string
|
|
195
|
+
// Lowercase.
|
|
196
|
+
email: string
|
|
197
|
+
// What the member gets on accepting.
|
|
198
|
+
roles: string[]
|
|
199
|
+
// Null once that user is deleted.
|
|
200
|
+
invitedBy: string | null
|
|
201
|
+
createdAt: Date
|
|
202
|
+
expiresAt: Date
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// What an emailed link proves once used.
|
|
206
|
+
export type LinkType = 'verify-email' | 'reset-password' | 'magic-link' | 'change-email'
|
|
207
|
+
|
|
208
|
+
// What an emailed code proves once typed: the sign-in or the address of the mail it came in.
|
|
209
|
+
export type CodeType = 'sign-in-code' | 'verify-code'
|
|
210
|
+
|
|
211
|
+
export type TokenType = LinkType | CodeType
|
|
212
|
+
|
|
213
|
+
// A link or a code kayjs-auth emailed, stored as the digest of the token it carries, or the keyed digest of the code bound to the session that asked for it.
|
|
214
|
+
export interface TokenRecord {
|
|
215
|
+
digest: string
|
|
216
|
+
type: TokenType
|
|
217
|
+
userId: string
|
|
218
|
+
// What the link acts on: the address it verifies, or the one an email change moves to.
|
|
219
|
+
email: string
|
|
220
|
+
// Where a magic link signs in to.
|
|
221
|
+
redirect: string | null
|
|
222
|
+
expiresAt: Date
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// Where kayjs-auth keeps its data. Every method may answer synchronously or with a promise.
|
|
226
|
+
// One verb per operation: `create` adds a row, `delete` removes one, `upsert` creates or replaces, `consume` deletes a row and answers it once only; `use` marks an OAuth code or refresh token spent and keeps the row, so it can tell a reuse.
|
|
227
|
+
export interface AuthStore {
|
|
228
|
+
users: {
|
|
229
|
+
get: (id: string) => MaybePromise<UserRecord | undefined>
|
|
230
|
+
// The users with those ids in one query, the missing ones left out; without it kayjs-auth calls `get` for each.
|
|
231
|
+
getMany?: (ids: string[]) => MaybePromise<UserRecord[]>
|
|
232
|
+
// Given an address already normalised, as every caller does: a store may match it exactly.
|
|
233
|
+
findByEmail: (email: string) => MaybePromise<UserRecord | undefined>
|
|
234
|
+
findByUsername: (username: string) => MaybePromise<UserRecord | undefined>
|
|
235
|
+
// Throws when the email or the username is taken. Answers the user as stored when the store picks its own id, such as a serial column's: `user` whole with only its `id` changed. Answering nothing keeps `user.id`.
|
|
236
|
+
create: (user: UserRecord) => MaybePromise<UserRecord | void>
|
|
237
|
+
// The user once changed, or undefined when there is none; throws when the change takes an email or a username another user has.
|
|
238
|
+
update: (id: string, patch: Partial<Omit<UserRecord, 'id' | 'createdAt'>>) => MaybePromise<UserRecord | undefined>
|
|
239
|
+
// Deletes the user with everything kayjs-auth keeps for them: identities, links, sessions, passkeys, bearer tokens, OAuth grants, codes and refresh tokens, recovery codes and memberships; invitations they sent lose their `invitedBy`. False when there is none.
|
|
240
|
+
delete: (id: string) => MaybePromise<boolean>
|
|
241
|
+
// Up to `limit` guests created before `createdBefore` and holding no session, oldest first; without it guests are never pruned.
|
|
242
|
+
staleGuests?: (createdBefore: Date, limit: number) => MaybePromise<UserRecord[]>
|
|
243
|
+
// Up to `limit` users who are not guests, created before `createdBefore` with an email never verified, holding no session and no identity, oldest first; without it unverified accounts are never pruned.
|
|
244
|
+
staleUnverified?: (createdBefore: Date, limit: number) => MaybePromise<UserRecord[]>
|
|
245
|
+
// Up to `limit` users whose `deleteAt` is at or before `now`, earliest first; needed by the `account.deleteAfter` option, which a store without it refuses at boot.
|
|
246
|
+
dueForDeletion?: (now: Date, limit: number) => MaybePromise<UserRecord[]>
|
|
247
|
+
// Sets `deleteAt` only on a user whose is null, false when it is set already or the user is gone, even when two requests try it together; needed by `account.deleteAfter` too.
|
|
248
|
+
markForDeletion?: (id: string, deleteAt: Date) => MaybePromise<boolean>
|
|
249
|
+
// Newest first; `search` matches part of the email or the username, whatever its case, or the whole id.
|
|
250
|
+
// With `total: false` the caller does not read `total`, so a store may skip counting.
|
|
251
|
+
list: (query: { search?: string, offset: number, limit: number, total?: boolean }) => MaybePromise<{ users: UserRecord[], total: number }>
|
|
252
|
+
// Records `step` as the last one a code was accepted for, only when it is later than the one recorded: false when it is not, even when two requests try it together.
|
|
253
|
+
advanceTotpStep: (id: string, step: number) => MaybePromise<boolean>
|
|
254
|
+
}
|
|
255
|
+
identities: {
|
|
256
|
+
find: (provider: string, providerId: string) => MaybePromise<IdentityRecord | undefined>
|
|
257
|
+
listByUser: (userId: string) => MaybePromise<IdentityRecord[]>
|
|
258
|
+
// Throws when that provider account is linked already.
|
|
259
|
+
create: (identity: IdentityRecord) => MaybePromise<void>
|
|
260
|
+
update: (provider: string, providerId: string, patch: Partial<Pick<IdentityRecord, 'accessToken' | 'refreshToken' | 'tokenExpiresAt'>>) => MaybePromise<void>
|
|
261
|
+
// False when there is none.
|
|
262
|
+
delete: (provider: string, providerId: string) => MaybePromise<boolean>
|
|
263
|
+
// Deletes every identity of the user in one query and answers how many went; without it kayjs-auth deletes them one by one.
|
|
264
|
+
erase?: (userId: string) => MaybePromise<number>
|
|
265
|
+
}
|
|
266
|
+
tokens: {
|
|
267
|
+
create: (token: TokenRecord) => MaybePromise<void>
|
|
268
|
+
// Deletes and answers the token when it exists, has that type and has not expired: once only, even when two requests spend it together.
|
|
269
|
+
consume: (digest: string, type: TokenType) => MaybePromise<TokenRecord | undefined>
|
|
270
|
+
// Deletes the user's tokens of that type, or of every type, and answers how many went.
|
|
271
|
+
erase: (userId: string, type?: TokenType) => MaybePromise<number>
|
|
272
|
+
}
|
|
273
|
+
sessions: {
|
|
274
|
+
create: (session: SessionRecord) => MaybePromise<void>
|
|
275
|
+
get: (id: string) => MaybePromise<SessionRecord | undefined>
|
|
276
|
+
// Oldest first.
|
|
277
|
+
listByUser: (userId: string) => MaybePromise<SessionRecord[]>
|
|
278
|
+
update: (id: string, patch: Partial<Pick<SessionRecord, 'version' | 'ip' | 'lastSeenAt'>>) => MaybePromise<void>
|
|
279
|
+
// Deletes the user's session with that id; false when they have none.
|
|
280
|
+
delete: (userId: string, id: string) => MaybePromise<boolean>
|
|
281
|
+
}
|
|
282
|
+
passkeys: {
|
|
283
|
+
// Credential ids are unique, whoever holds them.
|
|
284
|
+
create: (passkey: PasskeyRecord) => MaybePromise<void>
|
|
285
|
+
get: (id: string) => MaybePromise<PasskeyRecord | undefined>
|
|
286
|
+
// Oldest first.
|
|
287
|
+
listByUser: (userId: string) => MaybePromise<PasskeyRecord[]>
|
|
288
|
+
update: (id: string, patch: Partial<Pick<PasskeyRecord, 'name' | 'counter' | 'backedUp' | 'userVerified' | 'lastUsedAt'>>) => MaybePromise<void>
|
|
289
|
+
// Deletes the user's passkey with that id; false when they have none.
|
|
290
|
+
delete: (userId: string, id: string) => MaybePromise<boolean>
|
|
291
|
+
}
|
|
292
|
+
// Needed only with the `audit` option.
|
|
293
|
+
audit?: {
|
|
294
|
+
add: (entry: AuditRecord) => MaybePromise<void>
|
|
295
|
+
// Newest first, entries of one millisecond by id descending (the library writes time-ordered ids, so that is newest written first); `before` excludes that instant, or when it names an entry's `at` and `id`, that entry and every one after it in this order.
|
|
296
|
+
list: (query: { userId?: string, before?: AuditCursor, limit: number }) => MaybePromise<AuditRecord[]>
|
|
297
|
+
// Deletes the entries older than `before` and answers how many went.
|
|
298
|
+
prune: (before: Date) => MaybePromise<number>
|
|
299
|
+
// Strips a deleted user from the log and answers how many entries it changed: `userId` becomes `pseudonym` in their entries, which lose their address, browser and detail, and in the entries they acted in, which lose their address and browser.
|
|
300
|
+
erase: (userId: string, pseudonym: string) => MaybePromise<number>
|
|
301
|
+
}
|
|
302
|
+
// Needed only with the `organizations` option, as are `members` and `invitations`.
|
|
303
|
+
organizations?: {
|
|
304
|
+
// Throws when the slug is taken.
|
|
305
|
+
create: (organization: OrganizationRecord) => MaybePromise<void>
|
|
306
|
+
get: (id: string) => MaybePromise<OrganizationRecord | undefined>
|
|
307
|
+
// The organizations with those ids in one query, the missing ones left out; without it kayjs-auth calls `get` for each.
|
|
308
|
+
getMany?: (ids: string[]) => MaybePromise<OrganizationRecord[]>
|
|
309
|
+
findBySlug: (slug: string) => MaybePromise<OrganizationRecord | undefined>
|
|
310
|
+
// The organization once changed, or undefined when there is none; throws when the change takes a slug another has.
|
|
311
|
+
update: (id: string, patch: Partial<Pick<OrganizationRecord, 'name' | 'slug'>>) => MaybePromise<OrganizationRecord | undefined>
|
|
312
|
+
// Deletes it with its members and invitations; false when there is none.
|
|
313
|
+
delete: (id: string) => MaybePromise<boolean>
|
|
314
|
+
}
|
|
315
|
+
members?: {
|
|
316
|
+
// Throws when the user is a member already.
|
|
317
|
+
add: (member: MemberRecord) => MaybePromise<void>
|
|
318
|
+
get: (organizationId: string, userId: string) => MaybePromise<MemberRecord | undefined>
|
|
319
|
+
// Oldest first.
|
|
320
|
+
listByOrganization: (organizationId: string) => MaybePromise<MemberRecord[]>
|
|
321
|
+
// Oldest first.
|
|
322
|
+
listByUser: (userId: string) => MaybePromise<MemberRecord[]>
|
|
323
|
+
update: (organizationId: string, userId: string, patch: Pick<MemberRecord, 'roles'>) => MaybePromise<MemberRecord | undefined>
|
|
324
|
+
// False when the user is no member.
|
|
325
|
+
delete: (organizationId: string, userId: string) => MaybePromise<boolean>
|
|
326
|
+
}
|
|
327
|
+
invitations?: {
|
|
328
|
+
create: (invitation: InvitationRecord) => MaybePromise<void>
|
|
329
|
+
get: (id: string) => MaybePromise<InvitationRecord | undefined>
|
|
330
|
+
// Oldest first, expired ones included.
|
|
331
|
+
listByOrganization: (organizationId: string) => MaybePromise<InvitationRecord[]>
|
|
332
|
+
// Oldest first, expired ones included; given an address already normalised.
|
|
333
|
+
listByEmail: (email: string) => MaybePromise<InvitationRecord[]>
|
|
334
|
+
// False when there is none.
|
|
335
|
+
delete: (id: string) => MaybePromise<boolean>
|
|
336
|
+
}
|
|
337
|
+
bearerTokens: {
|
|
338
|
+
create: (token: BearerTokenRecord) => MaybePromise<void>
|
|
339
|
+
findByDigest: (digest: string) => MaybePromise<BearerTokenRecord | undefined>
|
|
340
|
+
// The token with that digest and its user in one query, undefined when either is missing; without it kayjs-auth calls `findByDigest` then `users.get`.
|
|
341
|
+
findByDigestWithUser?: (digest: string) => MaybePromise<{ token: BearerTokenRecord, user: UserRecord } | undefined>
|
|
342
|
+
listByUser: (userId: string) => MaybePromise<BearerTokenRecord[]>
|
|
343
|
+
// Records a use, without changing anything else.
|
|
344
|
+
touch: (id: string, at: Date) => MaybePromise<void>
|
|
345
|
+
// Deletes the user's token with that id; false when they have none.
|
|
346
|
+
delete: (userId: string, id: string) => MaybePromise<boolean>
|
|
347
|
+
// Deletes every token of the user in one query and answers how many went; without it kayjs-auth deletes them one by one.
|
|
348
|
+
erase?: (userId: string) => MaybePromise<number>
|
|
349
|
+
}
|
|
350
|
+
// Needed only for the OAuth server (MCP clients signing in): without it the server is off.
|
|
351
|
+
oauth?: {
|
|
352
|
+
clients: {
|
|
353
|
+
create: (client: OAuthClientRecord) => MaybePromise<void>
|
|
354
|
+
get: (id: string) => MaybePromise<OAuthClientRecord | undefined>
|
|
355
|
+
}
|
|
356
|
+
grants: {
|
|
357
|
+
get: (userId: string, clientId: string) => MaybePromise<OAuthGrantRecord | undefined>
|
|
358
|
+
// Creates the grant or replaces the one of that user and client, keeping its `createdAt`.
|
|
359
|
+
upsert: (grant: OAuthGrantRecord) => MaybePromise<void>
|
|
360
|
+
// Records a use, without changing anything else.
|
|
361
|
+
touch: (userId: string, clientId: string, at: Date) => MaybePromise<void>
|
|
362
|
+
// Oldest first.
|
|
363
|
+
listByUser: (userId: string) => MaybePromise<OAuthGrantRecord[]>
|
|
364
|
+
// Deletes the grant with the user's refresh tokens and bearer tokens issued under it for that client; false when they have none.
|
|
365
|
+
revoke: (userId: string, clientId: string) => MaybePromise<boolean>
|
|
366
|
+
}
|
|
367
|
+
codes: {
|
|
368
|
+
create: (code: OAuthCodeRecord) => MaybePromise<void>
|
|
369
|
+
// Reads the code without spending it, so a request can be refused for what it asks before the code is used up. A store without it refuses after spending, as before.
|
|
370
|
+
get?: (digest: string) => MaybePromise<OAuthCodeRecord | undefined>
|
|
371
|
+
// Marks the code spent and answers it, `reused` when it was spent already: once only, even when two requests spend it together. Undefined for one never issued.
|
|
372
|
+
use: (digest: string, at: Date) => MaybePromise<{ code: OAuthCodeRecord, reused: boolean } | undefined>
|
|
373
|
+
}
|
|
374
|
+
refresh: {
|
|
375
|
+
create: (token: OAuthRefreshRecord) => MaybePromise<void>
|
|
376
|
+
// Reads the token without spending it, so a request can be refused for what it asks before the token is used up. A store without it refuses after spending, as before.
|
|
377
|
+
get?: (digest: string) => MaybePromise<OAuthRefreshRecord | undefined>
|
|
378
|
+
// As `codes.use`.
|
|
379
|
+
use: (digest: string, at: Date) => MaybePromise<{ token: OAuthRefreshRecord, reused: boolean } | undefined>
|
|
380
|
+
// Deletes the refresh tokens of the family and the bearer tokens issued under it.
|
|
381
|
+
revokeFamily: (userId: string, family: string) => MaybePromise<void>
|
|
382
|
+
// Deletes every refresh token of the user, as signing out everywhere does, and answers how many went.
|
|
383
|
+
erase: (userId: string) => MaybePromise<number>
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
// Digests of the codes that sign in in place of a second factor.
|
|
387
|
+
recoveryCodes: {
|
|
388
|
+
// Replaces the user's whole set.
|
|
389
|
+
replace: (userId: string, digests: string[]) => MaybePromise<void>
|
|
390
|
+
// Deletes and answers whether the user had that code: once only, even when two requests spend it together.
|
|
391
|
+
consume: (userId: string, digest: string) => MaybePromise<boolean>
|
|
392
|
+
count: (userId: string) => MaybePromise<number>
|
|
393
|
+
}
|
|
394
|
+
// Where the store counts attempts, shared by every process it is, as `memoryAuth` and `pgAuth` do: kay's `RateStore`, whose `peek` and `reset` kay derives when it lacks them. Without it they count in the app's `store.rates`, else this process's memory.
|
|
395
|
+
rates?: AuthRates | undefined
|
|
396
|
+
// Deletes what outlived its use: expired links and codes and invitations, bearer tokens expired long ago, sessions past their lifetime unseen or the session plugin's `absoluteMaxAge` old, and attempt windows that ended. kayjs-auth calls it at most once an hour; a store without it keeps those rows until the app deletes them.
|
|
397
|
+
prune?: (limits: PruneLimits) => MaybePromise<void>
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
export interface PruneLimits {
|
|
401
|
+
now: Date
|
|
402
|
+
// Bearer tokens expired before this go: the list shows an expired one for a while, so its owner sees why a device stopped working.
|
|
403
|
+
bearerExpiredBefore: Date
|
|
404
|
+
// How long a session may go unseen: the longest lifetime any session was given.
|
|
405
|
+
sessionMaxAge: Duration
|
|
406
|
+
// How long since a session's sign-in, whatever its use.
|
|
407
|
+
sessionAbsoluteMaxAge: Duration
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
export type { MaybePromise }
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { AuthStore, OrganizationRecord, UserRecord } from './store'
|
|
2
|
+
|
|
3
|
+
async function fetchMany<Found>(ids: string[], source: { getMany?: ((ids: string[]) => Found[] | Promise<Found[]>) | undefined, get: (id: string) => Found | undefined | Promise<Found | undefined> }): Promise<Found[]> {
|
|
4
|
+
if (source.getMany)
|
|
5
|
+
return source.getMany(ids)
|
|
6
|
+
|
|
7
|
+
return (await Promise.all(ids.map(async id => source.get(id)))).filter(found => found !== undefined)
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
// The records with those ids, in one query when the store has `getMany`; the ids not found are left out of the map.
|
|
11
|
+
export async function usersById(store: AuthStore, ids: string[]): Promise<Map<string, UserRecord>> {
|
|
12
|
+
const unique = [...new Set(ids)]
|
|
13
|
+
const found = unique.length === 0 ? [] : await fetchMany(unique, store.users)
|
|
14
|
+
|
|
15
|
+
return new Map(found.map(user => [user.id, user]))
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export async function organizationsById(store: NonNullable<AuthStore['organizations']>, ids: string[]): Promise<Map<string, OrganizationRecord>> {
|
|
19
|
+
const unique = [...new Set(ids)]
|
|
20
|
+
const found = unique.length === 0 ? [] : await fetchMany(unique, store)
|
|
21
|
+
|
|
22
|
+
return new Map(found.map(organization => [organization.id, organization]))
|
|
23
|
+
}
|
package/src/test.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { BareUser } from './core'
|
|
2
|
+
import type { OAuthSite, OAuthTest } from './oauthTest'
|
|
3
|
+
import type { CreateUserInput } from './password'
|
|
4
|
+
import type { TotpEnrolment } from './twoFactor'
|
|
5
|
+
import { builtOwn } from './own'
|
|
6
|
+
|
|
7
|
+
// What `auth.test(site)` gives.
|
|
8
|
+
export interface AuthTest {
|
|
9
|
+
// Signs the site in as a member, made when none has that email or username; `data` holds the fields of the app's `user` schema.
|
|
10
|
+
signInAs: (who: Omit<CreateUserInput, 'roles'> & { roles?: string[] | undefined, data?: object | undefined }) => Promise<BareUser>
|
|
11
|
+
// Signs the site out, its other cookies kept.
|
|
12
|
+
signOut: () => void
|
|
13
|
+
// The `Cookie` header of a new session signed in as that user.
|
|
14
|
+
sessionCookie: (userId: string, options?: { secure?: boolean }) => Promise<string>
|
|
15
|
+
// Turns two-factor on for that member as the app would, so a password sign-in asks for a code: the authenticator's `secret`, `code(offset?)` for the current step and the `recoveryCodes`, all usable at the next sign-in. Throws for a missing member or one who has it already.
|
|
16
|
+
enrollTotp: (userId: string) => Promise<TotpEnrolment>
|
|
17
|
+
// Signs in through an OAuth provider with no request to it: `await oauth.stub('discord', { id, email })` makes it answer with that account (or `{ error }` for a refused consent, a rejected code or a provider down), and `await oauth.signIn('discord')` leaves for it and comes back through the site, answering the callback's response.
|
|
18
|
+
oauth: OAuthTest
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface OwnTest {
|
|
22
|
+
test: (site: OAuthSite) => AuthTest
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// The `auth.test(site)` of an app whose kay.config.ts holds `auth()` and no `src/auth.ts` module: the auth that site's `testSite()` built, found as a call needs it, so call it after `testSite()`.
|
|
26
|
+
export function authTest(site: OAuthSite): AuthTest {
|
|
27
|
+
const made = () => {
|
|
28
|
+
const own = builtOwn(site)
|
|
29
|
+
|
|
30
|
+
if (!own)
|
|
31
|
+
throw new Error('kayjs-auth: authTest found no `auth()` built for this test site: await `testSite()` first, and give `authTest` the site it returned, of a project whose kay.config.ts registers `auth()` with no `module`')
|
|
32
|
+
|
|
33
|
+
return own.test(site)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
return {
|
|
37
|
+
signInAs: async who => made().signInAs(who),
|
|
38
|
+
signOut: () => made().signOut(),
|
|
39
|
+
sessionCookie: async (userId, options) => made().sessionCookie(userId, options),
|
|
40
|
+
enrollTotp: async userId => made().enrollTotp(userId),
|
|
41
|
+
oauth: {
|
|
42
|
+
stub: async (provider, outcome) => made().oauth.stub(provider, outcome),
|
|
43
|
+
signIn: async (provider, options) => made().oauth.signIn(provider, options),
|
|
44
|
+
},
|
|
45
|
+
}
|
|
46
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// The session cookie names `signInAs` set in a test site's jar, dropped with the default ones when the site signs out or in again.
|
|
2
|
+
export const signedInCookies = new WeakMap<Bun.CookieMap, string[]>()
|
|
3
|
+
|
|
4
|
+
export function dropSession(cookies: Bun.CookieMap): void {
|
|
5
|
+
for (const name of new Set(['kay_session', '__Host-kay_session', ...signedInCookies.get(cookies) ?? []]))
|
|
6
|
+
cookies.delete(name)
|
|
7
|
+
|
|
8
|
+
signedInCookies.delete(cookies)
|
|
9
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { Elysia } from 'elysia'
|
|
2
|
+
import type { BareUser, Core } from './core'
|
|
3
|
+
import type { OAuthSite, OAuthTest } from './oauthTest'
|
|
4
|
+
import type { CreateUserInput } from './password'
|
|
5
|
+
import type { TotpEnrolment } from './twoFactor'
|
|
6
|
+
import { load } from './load'
|
|
7
|
+
import { dropSession } from './testCookies'
|
|
8
|
+
|
|
9
|
+
// Who `signInAs` signs in: `createUser`'s fields and the app's own user `data` fields.
|
|
10
|
+
export type TestMember<Role extends string, UserData extends object> = Omit<CreateUserInput, 'roles'> & { roles?: Role[] | undefined, data?: { [Field in keyof UserData]?: UserData[Field] | undefined } | undefined }
|
|
11
|
+
|
|
12
|
+
// The calls a test makes on the auth of its site, with no form round trip.
|
|
13
|
+
export function testHelpers<Role extends string, UserData extends object>(core: Core, plugin: Elysia) {
|
|
14
|
+
const helpers = {
|
|
15
|
+
// The `Cookie` header of a new session signed in as `userId`, as `signIn` makes it, for a test or a script to send by hand; throws for a missing or banned user.
|
|
16
|
+
// The cookie is the one kay's server names for the scheme it sees: by default the plugin signs in over `http://localhost/`, so the server's own rule applies (an https `site` in kay.config.ts makes it `__Host-kay_session` in production); `secure: true` mints the one an https request reads, `secure: false` the plain one.
|
|
17
|
+
async sessionCookie(userId: string, cookieOptions: { secure?: boolean } = {}): Promise<string> {
|
|
18
|
+
return (await import('./testing')).mintSessionCookie(plugin, userId, cookieOptions.secure)
|
|
19
|
+
},
|
|
20
|
+
|
|
21
|
+
// Signs a test site in as a member, making them first when no user has their email or username, with no form round trip: `createUser`'s fields (`email`, `username`, `password`, `roles`, `emailVerified`, `locale`) for a new member, and the app's own user `data` fields. An existing member is signed in as they are, and throws when the email, username, roles or data given differ from theirs. It sets the session cookie in the site's cookie jar, so a second call switches member; returns the user.
|
|
22
|
+
async signInAs(site: { cookies: Bun.CookieMap }, who: TestMember<Role, UserData>): Promise<BareUser> {
|
|
23
|
+
return (await import('./testing')).signInAs(core, plugin, site, who)
|
|
24
|
+
},
|
|
25
|
+
|
|
26
|
+
// Turns two-factor on for a member as confirming a code would, for a test: it answers the authenticator's `secret`, `code(offset?)` for the current step and the `recoveryCodes`, all usable at the next sign-in. Throws for a missing member or one who has it already.
|
|
27
|
+
async enrollTotp(userId: string): Promise<TotpEnrolment> {
|
|
28
|
+
return (await load.twoFactor()).enrollTotp(core, userId)
|
|
29
|
+
},
|
|
30
|
+
|
|
31
|
+
// The provider calls of a test site: `await oauth.stub(provider, { id, email })` makes the provider answer with that account with no request leaving the test (or `{ error: 'access_denied' | 'invalid_grant' | 'server_error' }` a refused consent, a rejected code or a provider down), and `await oauth.signIn(provider)` leaves for it and comes back through the site, answering the callback's response.
|
|
32
|
+
oauth(site: OAuthSite): OAuthTest {
|
|
33
|
+
const made = async () => (await import('./oauthTest')).oauthTest(core, plugin, site)
|
|
34
|
+
|
|
35
|
+
return {
|
|
36
|
+
stub: async (provider, outcome) => (await made()).stub(provider, outcome),
|
|
37
|
+
signIn: async (provider, options) => (await made()).signIn(provider, options),
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
|
|
41
|
+
// Signs a test site out, however it was signed in, by dropping its session cookie: the site is anonymous again, its other cookies kept.
|
|
42
|
+
signOut(site: { cookies: Bun.CookieMap }): void {
|
|
43
|
+
dropSession(site.cookies)
|
|
44
|
+
},
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
return {
|
|
48
|
+
...helpers,
|
|
49
|
+
// The test calls on one test site, so a test names the site once: `const as = auth.test(site)`, then `await as.signInAs({ email })` and `as.signOut()`.
|
|
50
|
+
test: (site: OAuthSite) => ({
|
|
51
|
+
signInAs: async (who: TestMember<Role, UserData>) => helpers.signInAs(site, who),
|
|
52
|
+
signOut: () => helpers.signOut(site),
|
|
53
|
+
sessionCookie: async (userId: string, cookieOptions?: { secure?: boolean }) => helpers.sessionCookie(userId, cookieOptions),
|
|
54
|
+
enrollTotp: async (userId: string) => helpers.enrollTotp(userId),
|
|
55
|
+
oauth: helpers.oauth(site),
|
|
56
|
+
}),
|
|
57
|
+
}
|
|
58
|
+
}
|
package/src/testing.ts
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import type { Elysia } from 'elysia'
|
|
2
|
+
import type { BareUser, Core } from './core'
|
|
3
|
+
import type { CreateUserInput } from './password'
|
|
4
|
+
import { Elysia as ElysiaApp } from 'elysia'
|
|
5
|
+
import { publicUser } from './core'
|
|
6
|
+
import { normalizeEmail, normalizeUsername } from './rules'
|
|
7
|
+
import { dropSession, signedInCookies } from './testCookies'
|
|
8
|
+
import { mergedData } from './userData'
|
|
9
|
+
|
|
10
|
+
// `held` with `data` laid over it as the `user` schema accepts it; throws for data it refuses, or when the app declared no schema.
|
|
11
|
+
function signInAsData(core: Core, held: Record<string, unknown> | undefined, data: object): Record<string, unknown> {
|
|
12
|
+
if (!core.userData)
|
|
13
|
+
throw new Error('kayjs-auth: signInAs was given `data`, and authCore has no `user` schema')
|
|
14
|
+
|
|
15
|
+
const merged = mergedData(core.userData, held, data)
|
|
16
|
+
|
|
17
|
+
if (merged === undefined)
|
|
18
|
+
throw new Error('kayjs-auth: signInAs was given `data` that does not fit the `user` schema')
|
|
19
|
+
|
|
20
|
+
return merged
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// Throws when the member `signInAs` found holds other values than the fields it was given.
|
|
24
|
+
function signInAsMismatch(core: Core, user: BareUser, given: { email: string | undefined, username: string | undefined, roles: string[] | undefined, data: object | undefined }): void {
|
|
25
|
+
const differs: string[] = []
|
|
26
|
+
|
|
27
|
+
if (given.email !== undefined && given.email !== user.email)
|
|
28
|
+
differs.push('email')
|
|
29
|
+
|
|
30
|
+
if (given.username !== undefined && (user.username === null || given.username.toLowerCase() !== user.username.toLowerCase()))
|
|
31
|
+
differs.push('username')
|
|
32
|
+
|
|
33
|
+
if (given.roles !== undefined && !given.roles.every(role => user.roles.includes(role)))
|
|
34
|
+
differs.push('roles')
|
|
35
|
+
|
|
36
|
+
if (given.data !== undefined && !Bun.deepEquals(signInAsData(core, user.data, given.data), user.data))
|
|
37
|
+
differs.push('data')
|
|
38
|
+
|
|
39
|
+
if (differs.length > 0)
|
|
40
|
+
throw new Error(`kayjs-auth: signInAs found a member whose ${differs.join(', ')} differ from the fields given`)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// The Set-Cookie lines of a new session signed in as `userId`, minted by the plugin signing them in over a request of its own.
|
|
44
|
+
export async function mintSetCookies(plugin: Elysia, userId: string, secure: boolean | undefined): Promise<string[]> {
|
|
45
|
+
let failure: unknown
|
|
46
|
+
const signer = new ElysiaApp().use(plugin).post('/', async (context) => {
|
|
47
|
+
const { auth } = context as unknown as { auth: { signIn: (user: { id: string }) => Promise<void> } }
|
|
48
|
+
|
|
49
|
+
try {
|
|
50
|
+
await auth.signIn({ id: userId })
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
failure = error
|
|
54
|
+
}
|
|
55
|
+
})
|
|
56
|
+
const response = await signer.handle(new Request(secure === true ? 'https://localhost/' : 'http://localhost/', { method: 'POST', headers: secure === false ? { 'x-forwarded-proto': 'http' } : {} }))
|
|
57
|
+
|
|
58
|
+
if (failure !== undefined)
|
|
59
|
+
throw failure
|
|
60
|
+
|
|
61
|
+
return response.headers.getSetCookie()
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// `name=value` off each Set-Cookie line, its attributes dropped.
|
|
65
|
+
export async function mintSessionCookie(plugin: Elysia, userId: string, secure: boolean | undefined): Promise<string> {
|
|
66
|
+
return (await mintSetCookies(plugin, userId, secure)).map((line) => {
|
|
67
|
+
const cookie = Bun.Cookie.parse(line)
|
|
68
|
+
|
|
69
|
+
return `${cookie.name}=${cookie.value}`
|
|
70
|
+
}).join('; ')
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export async function signInAs(core: Core, plugin: Elysia, site: { cookies: Bun.CookieMap }, who: Omit<CreateUserInput, 'roles'> & { roles?: string[] | undefined, data?: object | undefined }): Promise<BareUser> {
|
|
74
|
+
const { data, ...fields } = who
|
|
75
|
+
const email = fields.email === undefined ? undefined : normalizeEmail(fields.email)
|
|
76
|
+
const username = fields.username === undefined ? undefined : normalizeUsername(fields.username)
|
|
77
|
+
const found = (email === undefined ? undefined : await core.store.users.findByEmail(email)) ?? (username === undefined ? undefined : await core.store.users.findByUsername(username))
|
|
78
|
+
let user: BareUser
|
|
79
|
+
|
|
80
|
+
if (found) {
|
|
81
|
+
user = publicUser(found)
|
|
82
|
+
signInAsMismatch(core, user, { email, username, roles: fields.roles, data })
|
|
83
|
+
}
|
|
84
|
+
else {
|
|
85
|
+
// Checked before the member is made, so a refused `data` leaves no half-made member behind.
|
|
86
|
+
const merged = data === undefined ? undefined : signInAsData(core, undefined, data)
|
|
87
|
+
const created = await (await import('./password')).createUser(core, fields)
|
|
88
|
+
|
|
89
|
+
if (!created.ok)
|
|
90
|
+
throw new Error(`kayjs-auth: signInAs could not make the member: ${JSON.stringify(created.errors)}`)
|
|
91
|
+
|
|
92
|
+
user = created.user
|
|
93
|
+
|
|
94
|
+
if (merged !== undefined)
|
|
95
|
+
user = publicUser((await core.store.users.update(user.id, { data: merged }))!)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const lines = await mintSetCookies(plugin, user.id, undefined)
|
|
99
|
+
const names: string[] = []
|
|
100
|
+
|
|
101
|
+
dropSession(site.cookies)
|
|
102
|
+
|
|
103
|
+
for (const line of lines) {
|
|
104
|
+
const cookie = Bun.Cookie.parse(line)
|
|
105
|
+
|
|
106
|
+
site.cookies.set(cookie.name, cookie.value)
|
|
107
|
+
names.push(cookie.name)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
signedInCookies.set(site.cookies, names)
|
|
111
|
+
|
|
112
|
+
return user
|
|
113
|
+
}
|