@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/erase.ts
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import type { AuthFailed } from './failure'
|
|
2
|
+
import type { RequestState } from './state'
|
|
3
|
+
import type { UserRecord } from './store'
|
|
4
|
+
import { notifications, personalData } from 'kay/server'
|
|
5
|
+
import { linkedUser } from './core'
|
|
6
|
+
import { reportFrom } from './events'
|
|
7
|
+
import { failed } from './failure'
|
|
8
|
+
import { log } from './log'
|
|
9
|
+
import { mailNotice, securityNotice } from './securityNotice'
|
|
10
|
+
|
|
11
|
+
type Core = RequestState['core']
|
|
12
|
+
|
|
13
|
+
// An organization whose only owner is the user: `alone` when they are its only member too, so it goes with them, else it needs another owner first.
|
|
14
|
+
interface SoleOwned {
|
|
15
|
+
id: string
|
|
16
|
+
name: string
|
|
17
|
+
alone: boolean
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// The organizations the user holds the owner role in.
|
|
21
|
+
async function owning(core: Core, record: UserRecord): Promise<string[]> {
|
|
22
|
+
const { organizations: config } = core
|
|
23
|
+
const { organizations, members } = core.store
|
|
24
|
+
|
|
25
|
+
if (!config || !organizations || !members)
|
|
26
|
+
return []
|
|
27
|
+
|
|
28
|
+
return (await members.listByUser(record.id)).filter(membership => membership.roles.includes(config.owner)).map(membership => membership.organizationId)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function soleOwned(core: Core, record: UserRecord): Promise<SoleOwned[]> {
|
|
32
|
+
const { organizations: config } = core
|
|
33
|
+
const { organizations, members } = core.store
|
|
34
|
+
const owned: SoleOwned[] = []
|
|
35
|
+
|
|
36
|
+
if (!config || !organizations || !members)
|
|
37
|
+
return owned
|
|
38
|
+
|
|
39
|
+
for (const id of await owning(core, record)) {
|
|
40
|
+
const everyone = await members.listByOrganization(id)
|
|
41
|
+
|
|
42
|
+
if (everyone.some(member => member.userId !== record.id && member.roles.includes(config.owner)))
|
|
43
|
+
continue
|
|
44
|
+
|
|
45
|
+
const organization = await organizations.get(id)
|
|
46
|
+
|
|
47
|
+
if (organization)
|
|
48
|
+
owned.push({ id, name: organization.name, alone: everyone.every(member => member.userId === record.id) })
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
return owned
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// The organizations deleting the signed-in user's account touches, by name: `deleted` the ones they are the only member of, `blocked` the ones they solely own with other members.
|
|
55
|
+
export interface DeletionImpact {
|
|
56
|
+
deleted: string[]
|
|
57
|
+
blocked: string[]
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function deletionImpact(state: RequestState): Promise<DeletionImpact> {
|
|
61
|
+
const record = await state.current()
|
|
62
|
+
const owned = record ? await soleOwned(state.core, record) : []
|
|
63
|
+
|
|
64
|
+
return { deleted: owned.filter(organization => organization.alone).map(organization => organization.name), blocked: owned.filter(organization => !organization.alone).map(organization => organization.name) }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Deletes the user with everything kayjs-auth keeps for them, and their notifications and mailing list rows. The app's `beforeDelete` is asked first and can refuse, and its records go before the erase, so a `beforeDelete` that throws leaves the account in place, to delete again. The audit log keeps what happened under a new random name, without the addresses, browsers and details that lead back to the user, and the provider tokens held are revoked upstream.
|
|
68
|
+
// For an account nobody leaves, as an unverified one a registration replaces or a guest past `guests.maxAge`: the address's invitations stay for whoever proves it, and no mail goes out to them, only to the new owner of an organization handed over.
|
|
69
|
+
// An organization it solely owned with other members passes to its longest-standing member, as it cannot be refused.
|
|
70
|
+
export async function eraseUser(core: Core, record: UserRecord): Promise<void> {
|
|
71
|
+
const erased = await eraseThen(core, record, true)
|
|
72
|
+
|
|
73
|
+
// Kept as a `beforeDelete` that refuses keeps it: the caller leaves the account to be tried again.
|
|
74
|
+
if (!erased.ok)
|
|
75
|
+
throw new Error(`beforeDelete refused to delete ${record.id}: ${erased.error.message}`)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// `eraseUser` for a user who goes, by their own hand or an admin's (`actor`): the invitations to their address go too, and the account-deleted notice is mailed. Refused with `refused` when `beforeDelete` says so, and with `last-owner` while they are the only owner of an organization with other members, unless `handOver` is set, as for an admin who cannot name an owner: the organization then passes to its longest-standing member. An organization they are alone in goes with them.
|
|
79
|
+
export async function eraseLeavingUser(state: RequestState, record: UserRecord, options: { actor?: UserRecord, handOver: true }): Promise<{ ok: true } | AuthFailed<'refused'>>
|
|
80
|
+
export async function eraseLeavingUser(state: RequestState, record: UserRecord, options?: { actor?: UserRecord, handOver?: false }): Promise<{ ok: true } | AuthFailed<'last-owner' | 'refused'>>
|
|
81
|
+
export async function eraseLeavingUser(state: RequestState, record: UserRecord, options: { actor?: UserRecord, handOver?: boolean } = {}): Promise<{ ok: true } | AuthFailed<'last-owner' | 'refused'>> {
|
|
82
|
+
const { actor, handOver = false } = options
|
|
83
|
+
|
|
84
|
+
return eraseThen(state.core, record, handOver, actor, async () => {
|
|
85
|
+
await dropInvitations(state.core, record)
|
|
86
|
+
await securityNotice(state, record, 'account-deleted', undefined, undefined, actor)
|
|
87
|
+
})
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function dropInvitations(core: Core, record: UserRecord): Promise<void> {
|
|
91
|
+
const { invitations } = core.store
|
|
92
|
+
|
|
93
|
+
if (record.email !== null && record.email !== '' && invitations) {
|
|
94
|
+
for (const invitation of await invitations.listByEmail(record.email))
|
|
95
|
+
await invitations.delete(invitation.id)
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// `eraseLeavingUser` for an account whose grace period (`account.deleteAfter`) ended, run by the prune with no request: the audit log and `onEvent` hear of the deletion and the notice is mailed to the user's language. An organization it solely owned passes to its longest-standing member, as nobody is there to refuse. Throws, leaving the account to be tried again, when `beforeDelete` refuses.
|
|
100
|
+
export async function eraseDue(core: Core, record: UserRecord): Promise<void> {
|
|
101
|
+
// Read again once beforeDelete is done, which can take a while: a cancel that came meanwhile wins.
|
|
102
|
+
const stillDue = async () => {
|
|
103
|
+
const current = await core.store.users.get(record.id)
|
|
104
|
+
|
|
105
|
+
return current?.deleteAt != null && current.deleteAt.getTime() <= Date.now()
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const erased = await eraseThen(core, record, true, undefined, async () => {
|
|
109
|
+
await dropInvitations(core, record)
|
|
110
|
+
await reportFrom(core, { address: '', userAgent: '' }, record, 'account-deleted')
|
|
111
|
+
mailNotice(core, [], record, 'account-deleted')
|
|
112
|
+
}, stillDue)
|
|
113
|
+
|
|
114
|
+
if (!erased.ok)
|
|
115
|
+
throw new Error(`the deletion of ${record.id} did not go through (${erased.error.code}): ${erased.error.message}`)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// `afterDelete` runs once the user is gone, and what it records is forgotten after it. The audit log forgets the user before and after, and a failure of either fails the erase, so none of their data stays behind unreported; only the first leaves the account to delete again.
|
|
119
|
+
// A throwing `afterDelete` fails the erase too, but only once the hand-over and the second strip have run.
|
|
120
|
+
async function eraseThen(core: Core, record: UserRecord, handOver: boolean, actor?: UserRecord, afterDelete?: () => Promise<void>, stillDue?: () => Promise<boolean>): Promise<{ ok: true } | AuthFailed<'last-owner' | 'refused'>> {
|
|
121
|
+
const { store } = core
|
|
122
|
+
|
|
123
|
+
if (!handOver && (await soleOwned(core, record)).some(organization => !organization.alone))
|
|
124
|
+
return failed('last-owner')
|
|
125
|
+
|
|
126
|
+
const refusal = await core.beforeDelete?.(await linkedUser(core, record), actor ? await linkedUser(core, actor) : null)
|
|
127
|
+
|
|
128
|
+
if (refusal)
|
|
129
|
+
return { ok: false, error: refusal }
|
|
130
|
+
|
|
131
|
+
if (stillDue && !await stillDue())
|
|
132
|
+
return failed('refused')
|
|
133
|
+
|
|
134
|
+
const owners = await owning(core, record)
|
|
135
|
+
const pseudonym = crypto.randomUUID()
|
|
136
|
+
|
|
137
|
+
const identities = await store.identities.listByUser(record.id)
|
|
138
|
+
|
|
139
|
+
if (identities.length > 0) {
|
|
140
|
+
const { revokeUpstream } = await import('./oauth/flow')
|
|
141
|
+
|
|
142
|
+
await Promise.all(identities.map(async identity => revokeUpstream(core, identity)))
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Before the account goes, so a store that cannot strip the audit log or reach the lists fails the erase with the account still there to delete again.
|
|
146
|
+
await eraseAside(core, record)
|
|
147
|
+
await forget(core, record, pseudonym)
|
|
148
|
+
await store.users.delete(record.id)
|
|
149
|
+
|
|
150
|
+
let failure: { error: unknown } | undefined
|
|
151
|
+
|
|
152
|
+
try {
|
|
153
|
+
await afterDelete?.()
|
|
154
|
+
}
|
|
155
|
+
catch (error) {
|
|
156
|
+
failure = { error }
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// Logged, not thrown: the account is gone by then, and a retry would find nothing to delete.
|
|
160
|
+
try {
|
|
161
|
+
await settle(core, owners)
|
|
162
|
+
}
|
|
163
|
+
catch (error) {
|
|
164
|
+
log.error('handing over a deleted user\'s organizations failed', error)
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// What `afterDelete` recorded still names them. The account is gone by then, so this failure is thrown for the app to see and cannot be retried.
|
|
168
|
+
if (afterDelete) {
|
|
169
|
+
try {
|
|
170
|
+
await forget(core, record, pseudonym)
|
|
171
|
+
}
|
|
172
|
+
catch (error) {
|
|
173
|
+
if (!failure)
|
|
174
|
+
throw error
|
|
175
|
+
|
|
176
|
+
log.error('stripping a deleted user\'s audit log failed', error)
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
if (failure)
|
|
181
|
+
throw failure.error
|
|
182
|
+
|
|
183
|
+
return { ok: true }
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// What other parts of the app keep about the user: their notifications, what libraries such as kayjs-ai registered with kay, and their address on the mailer's lists and in its queue. An address nobody proved is left there, as it may be someone else's.
|
|
187
|
+
async function eraseAside(core: Core, record: UserRecord): Promise<void> {
|
|
188
|
+
await notifications.erase(record.id)
|
|
189
|
+
await personalData.erase(record.id)
|
|
190
|
+
|
|
191
|
+
if (record.email !== null && record.email !== '' && record.emailVerifiedAt !== null)
|
|
192
|
+
await core.email?.mailer.erase?.(record.email)
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async function forget(core: Core, record: UserRecord, pseudonym: string): Promise<void> {
|
|
196
|
+
if (core.audit)
|
|
197
|
+
await core.store.audit?.erase(record.id, pseudonym)
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// Runs once the user is gone, so it also catches two owners deleted at the same moment, each having seen the other still there: an organization left empty is deleted, one left with members but no owner passes to the one who joined first.
|
|
201
|
+
async function settle(core: Core, ids: string[]): Promise<void> {
|
|
202
|
+
const { organizations: config } = core
|
|
203
|
+
const { organizations, members } = core.store
|
|
204
|
+
|
|
205
|
+
if (!config || !organizations || !members)
|
|
206
|
+
return
|
|
207
|
+
|
|
208
|
+
for (const id of ids) {
|
|
209
|
+
const left = await members.listByOrganization(id)
|
|
210
|
+
const [first] = left
|
|
211
|
+
|
|
212
|
+
if (!first) {
|
|
213
|
+
await organizations.delete(id)
|
|
214
|
+
}
|
|
215
|
+
else if (!left.some(member => member.roles.includes(config.owner))) {
|
|
216
|
+
await members.update(id, first.userId, { roles: [...new Set([...first.roles, config.owner])] })
|
|
217
|
+
await tellNewOwner(core, id, first.userId)
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// Reports the hand-over to the new owner's `onEvent` and audit log and mails them, after the organization is theirs; a failure here is logged, as the hand-over is done.
|
|
223
|
+
async function tellNewOwner(core: Core, organizationId: string, userId: string): Promise<void> {
|
|
224
|
+
try {
|
|
225
|
+
const owner = await core.store.users.get(userId)
|
|
226
|
+
const organization = await core.store.organizations?.get(organizationId)
|
|
227
|
+
|
|
228
|
+
if (!owner || !organization)
|
|
229
|
+
return
|
|
230
|
+
|
|
231
|
+
await reportFrom(core, { address: '', userAgent: '' }, owner, 'organization-handed-over', organizationId)
|
|
232
|
+
mailNotice(core, [], owner, 'organization-handed-over', organization.name)
|
|
233
|
+
}
|
|
234
|
+
catch (error) {
|
|
235
|
+
log.error('telling the new owner of a handed-over organization failed', error)
|
|
236
|
+
}
|
|
237
|
+
}
|
package/src/events.ts
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
import type { HookContext } from 'kay/library'
|
|
2
|
+
import type { Core, User } from './core'
|
|
3
|
+
import type { SecurityEvent } from './mail'
|
|
4
|
+
import type { RequestState } from './state'
|
|
5
|
+
import type { AuditCursor, UserRecord } from './store'
|
|
6
|
+
import { clamp } from '@kaynooo/utils'
|
|
7
|
+
import { configError, dispatch, hookContext, maintenance } from 'kay/library'
|
|
8
|
+
import { truncatedAddress } from './address'
|
|
9
|
+
import { linkedUser } from './core'
|
|
10
|
+
import { log } from './log'
|
|
11
|
+
import { PRUNE_EVERY_MS } from './prune'
|
|
12
|
+
|
|
13
|
+
const OAUTH_PREFIX = 'oauth:'
|
|
14
|
+
|
|
15
|
+
// The audit log is pruned of what outlived its age at most this often.
|
|
16
|
+
const AUDIT_PAGE_MAX = 200
|
|
17
|
+
|
|
18
|
+
// What happens to an account without changing what protects it, handed to `onEvent` but never mailed. An admin's doing, a role or a ban, or a manager's in an organization, names them in the context's `actor`.
|
|
19
|
+
// An organization event's detail is its id, then the roles given for `member-joined` and `member-roles-changed`.
|
|
20
|
+
export type ActivityEvent = 'signed-in' | 'signed-out' | 'sign-in-failed' | 'role-granted' | 'role-revoked' | 'banned' | 'unbanned' | 'impersonation-ended' | 'organization-created' | 'organization-deleted' | 'member-joined' | 'member-left' | 'member-removed' | 'member-roles-changed' | 'oauth-client-approved' | 'oauth-client-revoked' | 'account-deletion-scheduled'
|
|
21
|
+
|
|
22
|
+
export type AuthEvent = SecurityEvent | ActivityEvent
|
|
23
|
+
|
|
24
|
+
// What each event says besides who it happened to and where from, as `onEvent` hears it.
|
|
25
|
+
export interface EventFields {
|
|
26
|
+
// `method` is how: `password`, `register`, `reset-password`, `magic-link`, `email-code`, `passkey`, `guest`, `app` (the app called `auth.signIn`), `oauth` with the `provider`, or `unknown`.
|
|
27
|
+
'signed-in': { method: string, provider?: string }
|
|
28
|
+
'signed-out': Record<never, never>
|
|
29
|
+
// `method` is the attempt that failed: `password`, `passkey`, `two-factor` or `oauth`.
|
|
30
|
+
'sign-in-failed': { method: string }
|
|
31
|
+
'role-granted': { role: string }
|
|
32
|
+
'role-revoked': { role: string }
|
|
33
|
+
'banned': { reason?: string }
|
|
34
|
+
'unbanned': Record<never, never>
|
|
35
|
+
'impersonation-started': Record<never, never>
|
|
36
|
+
// `expired` is set when the 30 minutes ran out rather than the admin ending it.
|
|
37
|
+
'impersonation-ended': { expired?: boolean }
|
|
38
|
+
'organization-created': { organizationId: string }
|
|
39
|
+
'organization-deleted': { organizationId: string }
|
|
40
|
+
'member-joined': { organizationId: string, roles: string[] }
|
|
41
|
+
'member-left': { organizationId: string }
|
|
42
|
+
'member-removed': { organizationId: string }
|
|
43
|
+
'member-roles-changed': { organizationId: string, roles: string[] }
|
|
44
|
+
// `client` is the app's name.
|
|
45
|
+
'oauth-client-approved': { client: string }
|
|
46
|
+
'oauth-client-revoked': { client: string }
|
|
47
|
+
'new-sign-in': Record<never, never>
|
|
48
|
+
'sign-in-locked': Record<never, never>
|
|
49
|
+
'password-changed': Record<never, never>
|
|
50
|
+
// `email` is the address asked for, which the account has not moved to yet.
|
|
51
|
+
'email-change-requested': { email: string }
|
|
52
|
+
// `email` is the new address.
|
|
53
|
+
'email-changed': { email: string }
|
|
54
|
+
'two-factor-enabled': Record<never, never>
|
|
55
|
+
'two-factor-disabled': Record<never, never>
|
|
56
|
+
'recovery-code-used': Record<never, never>
|
|
57
|
+
'recovery-codes-regenerated': Record<never, never>
|
|
58
|
+
'provider-linked': { provider: string }
|
|
59
|
+
'provider-unlinked': { provider: string }
|
|
60
|
+
'passkey-added': { name?: string }
|
|
61
|
+
'passkey-removed': { name?: string }
|
|
62
|
+
'token-created': { name?: string }
|
|
63
|
+
// `keptThisOne` is whether the session that asked stayed signed in.
|
|
64
|
+
'signed-out-everywhere': { keptThisOne: boolean }
|
|
65
|
+
'account-deleted': Record<never, never>
|
|
66
|
+
// `deleteAt` is when the prune deletes the account, unless the user cancels first.
|
|
67
|
+
'account-deletion-scheduled': { deleteAt: Date }
|
|
68
|
+
'account-deletion-cancelled': Record<never, never>
|
|
69
|
+
'organization-handed-over': { organizationId: string }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// An event as `onEvent` hears it: the event, who it happened to, where from and its own fields, such as the `role` of a `role-granted`.
|
|
73
|
+
export type AuthEventInfo = { [Event in AuthEvent]: { event: Event, user: User, context: EventContext } & EventFields[Event] }[AuthEvent]
|
|
74
|
+
|
|
75
|
+
// What every hook of kayjs-auth is told about where it runs: kay's `HookContext`, and who acted when it was not the user, such as an admin.
|
|
76
|
+
export interface AuthHookContext extends HookContext {
|
|
77
|
+
actor: User | null
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Where an event came from: the context of the hook, with the address and browser the event was kept with, empty when it happened outside a request.
|
|
81
|
+
export interface EventContext extends AuthHookContext {
|
|
82
|
+
ip: string
|
|
83
|
+
userAgent: string
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// The context of a hook of kayjs-auth, read from the request being answered.
|
|
87
|
+
export async function authContext(actor: User | null = null): Promise<AuthHookContext> {
|
|
88
|
+
return { ...await hookContext(), actor }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// One line of the audit log.
|
|
92
|
+
export interface AuditEntry {
|
|
93
|
+
id: string
|
|
94
|
+
userId: string
|
|
95
|
+
event: AuthEvent
|
|
96
|
+
detail: string | null
|
|
97
|
+
ip: string
|
|
98
|
+
userAgent: string
|
|
99
|
+
// The user who acted, when not the one it happened to.
|
|
100
|
+
actorId: string | null
|
|
101
|
+
at: Date
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function impersonationEnd(detail: string | undefined): EventFields['impersonation-ended'] {
|
|
105
|
+
return detail === 'expired' ? { expired: true } : {}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// The fields of an event, read off the detail it is kept with in the audit log.
|
|
109
|
+
export function eventFields(event: AuthEvent, detail: string | undefined): EventFields[AuthEvent] {
|
|
110
|
+
const text = detail === undefined || detail === '' ? undefined : detail
|
|
111
|
+
|
|
112
|
+
// eslint-disable-next-line ts/switch-exhaustiveness-check -- the default hands the rest to `noticeFields`, which takes only them, so a new event still has to be placed
|
|
113
|
+
switch (event) {
|
|
114
|
+
case 'signed-in':
|
|
115
|
+
return text?.startsWith(OAUTH_PREFIX) ? { method: 'oauth', provider: text.slice(OAUTH_PREFIX.length) } : { method: text ?? 'unknown' }
|
|
116
|
+
case 'sign-in-failed':
|
|
117
|
+
return { method: text ?? 'unknown' }
|
|
118
|
+
case 'role-granted':
|
|
119
|
+
case 'role-revoked':
|
|
120
|
+
return { role: text ?? '' }
|
|
121
|
+
case 'banned':
|
|
122
|
+
return text === undefined ? {} : { reason: text }
|
|
123
|
+
case 'organization-created':
|
|
124
|
+
case 'organization-deleted':
|
|
125
|
+
case 'organization-handed-over':
|
|
126
|
+
case 'member-left':
|
|
127
|
+
case 'member-removed':
|
|
128
|
+
return { organizationId: text ?? '' }
|
|
129
|
+
case 'member-joined':
|
|
130
|
+
case 'member-roles-changed': {
|
|
131
|
+
const [organizationId = '', ...roles] = (text ?? '').split(' ')
|
|
132
|
+
|
|
133
|
+
return { organizationId, roles: roles.filter(role => role !== '') }
|
|
134
|
+
}
|
|
135
|
+
case 'oauth-client-approved':
|
|
136
|
+
case 'oauth-client-revoked':
|
|
137
|
+
return { client: text ?? '' }
|
|
138
|
+
case 'impersonation-ended':
|
|
139
|
+
return impersonationEnd(text)
|
|
140
|
+
case 'account-deletion-scheduled':
|
|
141
|
+
return { deleteAt: new Date(text ?? Number.NaN) }
|
|
142
|
+
case 'signed-out':
|
|
143
|
+
case 'unbanned':
|
|
144
|
+
case 'impersonation-started':
|
|
145
|
+
return {}
|
|
146
|
+
default:
|
|
147
|
+
return noticeFields(event, text)
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// The events that tell the user of a change to what protects the account.
|
|
152
|
+
type NoticeEvent = 'email-change-requested' | 'email-changed' | 'provider-linked' | 'provider-unlinked' | 'passkey-added' | 'passkey-removed' | 'token-created' | 'signed-out-everywhere' | 'new-sign-in' | 'sign-in-locked' | 'password-changed' | 'two-factor-enabled' | 'two-factor-disabled' | 'recovery-code-used' | 'recovery-codes-regenerated' | 'account-deleted' | 'account-deletion-cancelled'
|
|
153
|
+
|
|
154
|
+
function noticeFields(event: NoticeEvent, text: string | undefined): EventFields[NoticeEvent] {
|
|
155
|
+
switch (event) {
|
|
156
|
+
case 'email-change-requested':
|
|
157
|
+
case 'email-changed':
|
|
158
|
+
return { email: text ?? '' }
|
|
159
|
+
case 'provider-linked':
|
|
160
|
+
case 'provider-unlinked':
|
|
161
|
+
return { provider: text ?? '' }
|
|
162
|
+
case 'passkey-added':
|
|
163
|
+
case 'passkey-removed':
|
|
164
|
+
case 'token-created':
|
|
165
|
+
return text === undefined ? {} : { name: text }
|
|
166
|
+
case 'signed-out-everywhere':
|
|
167
|
+
return { keptThisOne: text === 'this-one-kept' }
|
|
168
|
+
case 'new-sign-in':
|
|
169
|
+
case 'sign-in-locked':
|
|
170
|
+
case 'password-changed':
|
|
171
|
+
case 'two-factor-enabled':
|
|
172
|
+
case 'two-factor-disabled':
|
|
173
|
+
case 'recovery-code-used':
|
|
174
|
+
case 'recovery-codes-regenerated':
|
|
175
|
+
case 'account-deleted':
|
|
176
|
+
case 'account-deletion-cancelled':
|
|
177
|
+
return {}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// The admin acting as the user this browser is signed in as, when one is.
|
|
182
|
+
export async function impersonatorOf(state: RequestState): Promise<string | undefined> {
|
|
183
|
+
return state.via() === 'bearer' ? undefined : (await state.session.get('auth'))?.impersonator?.user
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// Hands `event` to the app's `onEvent` and to the audit log when it is kept. A failure is logged, not thrown: what happened is done by then.
|
|
187
|
+
// While an admin acts as a user, whatever happens is the admin's doing, named as the actor.
|
|
188
|
+
export async function report(state: RequestState, record: UserRecord, event: AuthEvent, detail?: string, by?: UserRecord): Promise<void> {
|
|
189
|
+
const impersonator = await impersonatorOf(state)
|
|
190
|
+
const actor = impersonator === undefined ? by : await state.core.store.users.get(impersonator) ?? by
|
|
191
|
+
|
|
192
|
+
await reportFrom(state.core, state, record, event, detail, actor)
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// `report` for what happens outside a request, as a hand-over when a prune deletes an account: `where` is empty, so the entry names no address or browser.
|
|
196
|
+
export async function reportFrom(core: Core, where: { address: string, userAgent: string }, record: UserRecord, event: AuthEvent, detail?: string, actor?: UserRecord): Promise<void> {
|
|
197
|
+
if (core.onEvent) {
|
|
198
|
+
try {
|
|
199
|
+
const user = await linkedUser(core, record)
|
|
200
|
+
const context: EventContext = { ...await authContext(actor ? await linkedUser(core, actor) : null), ip: where.address, userAgent: where.userAgent }
|
|
201
|
+
|
|
202
|
+
await dispatch('auth.onEvent', [core.onEvent] as never, { event, user, ...eventFields(event, detail) }, { context })
|
|
203
|
+
}
|
|
204
|
+
catch (error) {
|
|
205
|
+
log.error(`onEvent failed for ${event}`, error)
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
if (!core.audit)
|
|
210
|
+
return
|
|
211
|
+
|
|
212
|
+
try {
|
|
213
|
+
await audit(core).add({ id: Bun.randomUUIDv7(), userId: record.id, event, detail: detail ?? null, ip: core.audit.ip === 'full' ? where.address : truncatedAddress(where.address), userAgent: where.userAgent, actorId: actor?.id ?? null, at: new Date() })
|
|
214
|
+
await prune(core)
|
|
215
|
+
}
|
|
216
|
+
catch (error) {
|
|
217
|
+
log.error(`writing ${event} to the audit log failed`, error)
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const AFTER_MAX = 200
|
|
222
|
+
let after = 0
|
|
223
|
+
|
|
224
|
+
// Runs `task` without making the request wait on it, a failure only logged: what the request did differs for a held address and a free one, and the time it takes must not tell which.
|
|
225
|
+
// With 200 tasks pending already, as when a hook hangs, the request waits on this one: a stalled hook slows requests rather than piling up without bound.
|
|
226
|
+
export async function afterResponse(what: string, task: () => Promise<void>): Promise<void> {
|
|
227
|
+
const run = (async () => {
|
|
228
|
+
after++
|
|
229
|
+
|
|
230
|
+
try {
|
|
231
|
+
await task()
|
|
232
|
+
}
|
|
233
|
+
catch (error) {
|
|
234
|
+
log.error(`${what} failed`, error)
|
|
235
|
+
}
|
|
236
|
+
finally {
|
|
237
|
+
after--
|
|
238
|
+
}
|
|
239
|
+
})()
|
|
240
|
+
|
|
241
|
+
if (after >= AFTER_MAX)
|
|
242
|
+
await run
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// A cursor as an app may hand it on after a JSON hop, which leaves a `Date` as its ISO text.
|
|
246
|
+
export type AuditCursorInput = AuditCursor | string | { at: Date | string, id: string }
|
|
247
|
+
|
|
248
|
+
// The audit log, newest first, for one user or everyone, a page of `limit` before `before`. A cursor that is no date answers an empty page, in every store.
|
|
249
|
+
export async function auditEntries(core: Core, query: { userId?: string | undefined, before?: AuditCursorInput | undefined, limit?: number | undefined }): Promise<AuditEntry[]> {
|
|
250
|
+
if (!core.audit)
|
|
251
|
+
return []
|
|
252
|
+
|
|
253
|
+
const limit = clamp(Math.trunc(query.limit ?? 50), 1, AUDIT_PAGE_MAX)
|
|
254
|
+
const before = query.before === undefined ? undefined : normalizeCursor(query.before)
|
|
255
|
+
|
|
256
|
+
if (before === null)
|
|
257
|
+
return []
|
|
258
|
+
|
|
259
|
+
return (await audit(core).list({ ...query.userId === undefined ? {} : { userId: query.userId }, ...before === undefined ? {} : { before }, limit })).map(entry => ({ ...entry, event: entry.event as AuthEvent }))
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// Typed loosely as it may come straight off a JSON body, where an Invalid Date is null.
|
|
263
|
+
function normalizeCursor(before: unknown): AuditCursor | null {
|
|
264
|
+
if (typeof before !== 'object' || before === null || before instanceof Date)
|
|
265
|
+
return validDate(before)
|
|
266
|
+
|
|
267
|
+
if (!('at' in before) || !('id' in before) || typeof before.id !== 'string')
|
|
268
|
+
return null
|
|
269
|
+
|
|
270
|
+
const at = validDate(before.at)
|
|
271
|
+
|
|
272
|
+
return at && { id: before.id, at }
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function validDate(value: unknown): Date | null {
|
|
276
|
+
const date = value instanceof Date || typeof value === 'string' ? new Date(value) : null
|
|
277
|
+
|
|
278
|
+
return date && !Number.isNaN(date.getTime()) ? date : null
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function audit(core: Core): NonNullable<Core['store']['audit']> {
|
|
282
|
+
if (!core.store.audit)
|
|
283
|
+
throw configError('auth', 'audit', 'the `audit` option needs a store keeping an audit log, as memoryAuth and pgAuth do')
|
|
284
|
+
|
|
285
|
+
return core.store.audit
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
async function prune(core: Core): Promise<void> {
|
|
289
|
+
const now = Date.now()
|
|
290
|
+
|
|
291
|
+
if (!core.audit || now - core.audit.prunedAt < PRUNE_EVERY_MS)
|
|
292
|
+
return
|
|
293
|
+
|
|
294
|
+
core.audit.prunedAt = now
|
|
295
|
+
core.audit.sweep ??= maintenance('auth-audit-prune', PRUNE_EVERY_MS, async () => audit(core).prune(new Date(Date.now() - core.audit!.maxAge * 1000)))
|
|
296
|
+
await core.audit.sweep.run()
|
|
297
|
+
}
|
package/src/export.ts
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import type { Notification } from 'kay/server'
|
|
2
|
+
import type { ApprovedClient } from './authorize/grants'
|
|
3
|
+
import type { BearerToken } from './bearer'
|
|
4
|
+
import type { User } from './core'
|
|
5
|
+
import type { AuditEntry } from './events'
|
|
6
|
+
import type { AuthFailed } from './failure'
|
|
7
|
+
import type { MailingSubscription } from './mail'
|
|
8
|
+
import type { Invitation, Membership } from './organizations'
|
|
9
|
+
import type { Passkey } from './passkeys'
|
|
10
|
+
import type { UserSession } from './sessions'
|
|
11
|
+
import type { RequestState } from './state'
|
|
12
|
+
import { notifications, personalData, pushSubscriptions } from 'kay/server'
|
|
13
|
+
import { listTokens } from './bearer'
|
|
14
|
+
import { linkedUser } from './core'
|
|
15
|
+
import { impersonatorOf } from './events'
|
|
16
|
+
import { failed } from './failure'
|
|
17
|
+
import { spend } from './limits'
|
|
18
|
+
import { provedLately } from './proof'
|
|
19
|
+
import { listSessions } from './sessions'
|
|
20
|
+
|
|
21
|
+
// More than a person's year of sign-ins, so only a bot's account is cut short.
|
|
22
|
+
const AUDIT_EXPORT_MAX = 100_000
|
|
23
|
+
// The most a person keeps, as kay's notifications hold the newest 200 each.
|
|
24
|
+
const NOTIFICATIONS_EXPORT_MAX = 200
|
|
25
|
+
|
|
26
|
+
// Everything kayjs-auth keeps about a user, secrets left out, and what the app's `exportData` adds.
|
|
27
|
+
export interface DataExport {
|
|
28
|
+
exportedAt: Date
|
|
29
|
+
user: User & { createdAt: Date, emailVerifiedAt: Date | null, twoFactorEnabledAt: Date | null }
|
|
30
|
+
identities: { provider: string, providerId: string, createdAt: Date }[]
|
|
31
|
+
sessions: UserSession[]
|
|
32
|
+
passkeys: Passkey[]
|
|
33
|
+
tokens: BearerToken[]
|
|
34
|
+
recoveryCodesLeft: number
|
|
35
|
+
// The apps the user approved to act as them; empty without an OAuth server.
|
|
36
|
+
grants: ApprovedClient[]
|
|
37
|
+
// The last ban an admin set, with the reason given, once its time has passed: a user under a ban in force cannot sign in to export. Null when never barred.
|
|
38
|
+
ban: { bannedAt: Date, until: Date | null, reason: string | null } | null
|
|
39
|
+
// Empty without the `organizations` option.
|
|
40
|
+
organizations: Membership[]
|
|
41
|
+
// The invitations to the user's address, expired ones included, and those they sent; empty without the `organizations` option.
|
|
42
|
+
invitations: { received: Invitation[], sent: Invitation[] }
|
|
43
|
+
// The user's notifications, the newest 200 of them.
|
|
44
|
+
notifications: Notification[]
|
|
45
|
+
// The devices the user opted in to web push on: each endpoint and when it was stored or last reached, the keys left out.
|
|
46
|
+
pushSubscriptions: { endpoint: string, createdAt: Date }[]
|
|
47
|
+
// What libraries registered with kay keep about the user, by library name: `ai` holds their kayjs-ai conversations. A library keeping nothing about them is left out.
|
|
48
|
+
libraries: Record<string, unknown>
|
|
49
|
+
// The mailing lists of kayjs-mail their address is on, pending ones included; empty without kayjs-mail.
|
|
50
|
+
mailingLists: MailingSubscription[]
|
|
51
|
+
// Empty without the `audit` option.
|
|
52
|
+
audit: AuditEntry[]
|
|
53
|
+
app: unknown
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export type ExportResult = { ok: true, data: DataExport } | AuthFailed<'signed-out' | 'limited' | 'impersonating' | 'stale'>
|
|
57
|
+
|
|
58
|
+
// Not for an admin acting as the user: they see what the user sees, not a copy of everything kept about them.
|
|
59
|
+
// Only within ten minutes of signing in or re-proving, so a session left open or stolen does not download everything the account holds.
|
|
60
|
+
export async function exportData(state: RequestState): Promise<ExportResult> {
|
|
61
|
+
const { core } = state
|
|
62
|
+
const record = await state.current()
|
|
63
|
+
|
|
64
|
+
if (!record || state.via() !== 'session')
|
|
65
|
+
return failed('signed-out')
|
|
66
|
+
|
|
67
|
+
if (await impersonatorOf(state) !== undefined)
|
|
68
|
+
return failed('impersonating')
|
|
69
|
+
|
|
70
|
+
if (!await provedLately(state))
|
|
71
|
+
return failed('stale')
|
|
72
|
+
|
|
73
|
+
if (await spend(core.rates, `export:${record.id}`, core.limits.export))
|
|
74
|
+
return failed('limited')
|
|
75
|
+
|
|
76
|
+
const user = await linkedUser(core, record)
|
|
77
|
+
const organizations = core.organizations ? await import('./organizations') : undefined
|
|
78
|
+
|
|
79
|
+
return {
|
|
80
|
+
ok: true,
|
|
81
|
+
data: {
|
|
82
|
+
exportedAt: new Date(),
|
|
83
|
+
user: { ...user, createdAt: record.createdAt, emailVerifiedAt: record.emailVerifiedAt, twoFactorEnabledAt: record.totpEnabledAt },
|
|
84
|
+
identities: (await core.store.identities.listByUser(record.id)).map(identity => ({ provider: identity.provider, providerId: identity.providerId, createdAt: identity.createdAt })),
|
|
85
|
+
sessions: await listSessions(state),
|
|
86
|
+
passkeys: await (await import('./passkeys')).listPasskeys(state),
|
|
87
|
+
tokens: await listTokens(state),
|
|
88
|
+
recoveryCodesLeft: await core.store.recoveryCodes.count(record.id),
|
|
89
|
+
grants: core.store.oauth ? await (await import('./authorize/grants')).approvedClients(state) : [],
|
|
90
|
+
ban: record.bannedAt === null ? null : { bannedAt: record.bannedAt, until: record.bannedUntil, reason: record.banReason },
|
|
91
|
+
organizations: organizations ? await organizations.listMemberships(state) : [],
|
|
92
|
+
invitations: organizations ? await organizations.exportedInvitations(state) : { received: [], sent: [] },
|
|
93
|
+
notifications: await notifications.list(record.id, { limit: NOTIFICATIONS_EXPORT_MAX }),
|
|
94
|
+
pushSubscriptions: await pushSubscriptions.list(record.id),
|
|
95
|
+
libraries: await personalData.export(record.id),
|
|
96
|
+
mailingLists: record.email !== null && record.email !== '' && core.email?.mailer.subscriptions ? await core.email.mailer.subscriptions(record.email) : [],
|
|
97
|
+
audit: core.audit ? (await core.store.audit!.list({ userId: record.id, limit: AUDIT_EXPORT_MAX })).map(entry => ({ ...entry, event: entry.event as AuditEntry['event'] })) : [],
|
|
98
|
+
app: await core.onExport?.(user) ?? null,
|
|
99
|
+
},
|
|
100
|
+
}
|
|
101
|
+
}
|