@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/text.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
const CONTROL = /[\p{Cc}\p{Zl}\p{Zp}\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/gu
|
|
2
|
+
|
|
3
|
+
// A name a visitor typed, without the control and direction characters that would reach a mail, a log or a page as markup, trimmed.
|
|
4
|
+
export function plainName(text: string): string {
|
|
5
|
+
return text.replace(CONTROL, '').trim()
|
|
6
|
+
}
|
package/src/totp.ts
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// RFC 6238 time-based one-time passwords. SHA-1, 6 digits and 30-second steps are what every authenticator reads from an `otpauth://` URI; several ignore any other algorithm and would show codes that never verify.
|
|
2
|
+
|
|
3
|
+
import { sameText } from './core'
|
|
4
|
+
|
|
5
|
+
const BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
|
|
6
|
+
const TOTP_DIGITS = 6
|
|
7
|
+
const TOTP_PERIOD_SECONDS = 30
|
|
8
|
+
// 160 bits, as RFC 4226 recommends.
|
|
9
|
+
const SECRET_BYTES = 20
|
|
10
|
+
// Steps either side of now that still verify: forgives a clock a few seconds out, at the cost of three live codes, which the attempt limits cap.
|
|
11
|
+
const TOTP_WINDOW = 1
|
|
12
|
+
const SPACES_AND_PADDING = /[\s=]/g
|
|
13
|
+
const NOT_DIGITS = /\D/g
|
|
14
|
+
|
|
15
|
+
export function base32Encode(bytes: Uint8Array): string {
|
|
16
|
+
let bits = 0
|
|
17
|
+
let value = 0
|
|
18
|
+
let out = ''
|
|
19
|
+
|
|
20
|
+
for (const byte of bytes) {
|
|
21
|
+
value = (value << 8) | byte
|
|
22
|
+
bits += 8
|
|
23
|
+
|
|
24
|
+
while (bits >= 5) {
|
|
25
|
+
out += BASE32_ALPHABET[(value >>> (bits - 5)) & 31]
|
|
26
|
+
bits -= 5
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Unpadded: authenticators accept it, and an `=` is one more character to escape in a URI.
|
|
31
|
+
return bits > 0 ? out + BASE32_ALPHABET[(value << (5 - bits)) & 31] : out
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Case and spacing are ignored; anything outside the alphabet decodes to nothing.
|
|
35
|
+
export function base32Decode(secret: string): Uint8Array<ArrayBuffer> {
|
|
36
|
+
let bits = 0
|
|
37
|
+
let value = 0
|
|
38
|
+
const out: number[] = []
|
|
39
|
+
|
|
40
|
+
for (const char of secret.toUpperCase().replace(SPACES_AND_PADDING, '')) {
|
|
41
|
+
const index = BASE32_ALPHABET.indexOf(char)
|
|
42
|
+
|
|
43
|
+
if (index < 0)
|
|
44
|
+
return new Uint8Array()
|
|
45
|
+
|
|
46
|
+
value = (value << 5) | index
|
|
47
|
+
bits += 5
|
|
48
|
+
|
|
49
|
+
if (bits >= 8) {
|
|
50
|
+
out.push((value >>> (bits - 8)) & 0xFF)
|
|
51
|
+
bits -= 8
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
return new Uint8Array(out)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Base32, so it can be typed in as well as scanned.
|
|
59
|
+
export function generateTotpSecret(): string {
|
|
60
|
+
return base32Encode(crypto.getRandomValues(new Uint8Array(SECRET_BYTES)))
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function totpStep(now = Date.now()): number {
|
|
64
|
+
return Math.floor(now / 1000 / TOTP_PERIOD_SECONDS)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export async function totpCode(secret: string, step: number): Promise<string> {
|
|
68
|
+
const cryptoKey = await importKey(secret)
|
|
69
|
+
|
|
70
|
+
return cryptoKey ? codeAt(cryptoKey, step) : ''
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function importKey(secret: string): Promise<CryptoKey | undefined> {
|
|
74
|
+
const key = base32Decode(secret)
|
|
75
|
+
|
|
76
|
+
return key.length === 0 ? undefined : crypto.subtle.importKey('raw', key, { name: 'HMAC', hash: 'SHA-1' }, false, ['sign'])
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function codeAt(cryptoKey: CryptoKey, step: number): Promise<string> {
|
|
80
|
+
const counter = new Uint8Array(8)
|
|
81
|
+
|
|
82
|
+
new DataView(counter.buffer).setBigUint64(0, BigInt(step))
|
|
83
|
+
|
|
84
|
+
const signature = new Uint8Array(await crypto.subtle.sign('HMAC', cryptoKey, counter))
|
|
85
|
+
// RFC 4226 dynamic truncation: the last byte's low nibble picks which four bytes become the code.
|
|
86
|
+
const offset = signature[signature.length - 1]! & 0x0F
|
|
87
|
+
const binary = ((signature[offset]! & 0x7F) << 24) | (signature[offset + 1]! << 16) | (signature[offset + 2]! << 8) | signature[offset + 3]!
|
|
88
|
+
|
|
89
|
+
return String(binary % 10 ** TOTP_DIGITS).padStart(TOTP_DIGITS, '0')
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// The step `code` is valid for, or undefined: the caller records the step so the code on screen cannot be used a second time.
|
|
93
|
+
export async function verifyTotp(secret: string, code: string, now = Date.now()): Promise<number | undefined> {
|
|
94
|
+
const digits = code.replace(NOT_DIGITS, '')
|
|
95
|
+
|
|
96
|
+
if (digits.length !== TOTP_DIGITS)
|
|
97
|
+
return undefined
|
|
98
|
+
|
|
99
|
+
const cryptoKey = await importKey(secret)
|
|
100
|
+
|
|
101
|
+
if (!cryptoKey)
|
|
102
|
+
return undefined
|
|
103
|
+
|
|
104
|
+
const current = totpStep(now)
|
|
105
|
+
|
|
106
|
+
for (let offset = -TOTP_WINDOW; offset <= TOTP_WINDOW; offset++) {
|
|
107
|
+
if (sameText(await codeAt(cryptoKey, current + offset), digits))
|
|
108
|
+
return current + offset
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
return undefined
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// What an authenticator scans. The label carries the issuer too, for apps that predate the `issuer` parameter.
|
|
115
|
+
export function otpauthUri({ secret, account, issuer }: { secret: string, account: string, issuer: string }): string {
|
|
116
|
+
const label = encodeURIComponent(`${issuer}:${account}`)
|
|
117
|
+
const params = new URLSearchParams({ secret, issuer, algorithm: 'SHA1', digits: String(TOTP_DIGITS), period: String(TOTP_PERIOD_SECONDS) })
|
|
118
|
+
|
|
119
|
+
return `otpauth://totp/${label}?${params}`
|
|
120
|
+
}
|
package/src/twoFactor.ts
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import type { Core } from './core'
|
|
2
|
+
import type { AuthFailed } from './failure'
|
|
3
|
+
import type { Proof, ProofFailure } from './proof'
|
|
4
|
+
import type { RequestState } from './state'
|
|
5
|
+
import type { UserRecord } from './store'
|
|
6
|
+
import { nanoid } from '@kaynooo/utils'
|
|
7
|
+
import { report } from './events'
|
|
8
|
+
import { failed } from './failure'
|
|
9
|
+
import { secondFactorLimited } from './guesses'
|
|
10
|
+
import { digest, totpContext } from './keys'
|
|
11
|
+
import { forget, spend } from './limits'
|
|
12
|
+
import { reprove } from './proof'
|
|
13
|
+
import { securityNotice } from './securityNotice'
|
|
14
|
+
import { endOtherSessions } from './sessions'
|
|
15
|
+
import { generateTotpSecret, otpauthUri, totpCode, totpStep, verifyTotp } from './totp'
|
|
16
|
+
|
|
17
|
+
const RECOVERY_CODE_COUNT = 10
|
|
18
|
+
// No 0, o, 1 or l, since these get copied by hand.
|
|
19
|
+
const RECOVERY_CODE_ALPHABET = '23456789abcdefghjkmnpqrstuvwxyz'
|
|
20
|
+
// About 74 bits: the stored digest is unsalted, so the safety comes from the code being out of reach.
|
|
21
|
+
const RECOVERY_CODE_LENGTH = 15
|
|
22
|
+
const NOT_CODE_CHARACTERS = /[^a-z0-9]/g
|
|
23
|
+
const EVERY_FIVE = /.{5}(?=.)/g
|
|
24
|
+
|
|
25
|
+
export interface TwoFactorSetup {
|
|
26
|
+
// Base32, for typing into an authenticator by hand.
|
|
27
|
+
secret: string
|
|
28
|
+
// Draw it as a QR code with kayjs-ui's `QrCode`.
|
|
29
|
+
uri: string
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export type TwoFactorResult = { ok: true, redirect: string } | AuthFailed<'invalid' | 'expired' | 'limited'>
|
|
33
|
+
|
|
34
|
+
export async function verifyTwoFactor(state: RequestState, code: string, signIn: (record: UserRecord, method: string) => Promise<void>): Promise<TwoFactorResult> {
|
|
35
|
+
const { store } = state.core
|
|
36
|
+
const challenge = await state.session.get('authChallenge')
|
|
37
|
+
const record = challenge && challenge.expires > Date.now() ? await store.users.get(challenge.user) : undefined
|
|
38
|
+
|
|
39
|
+
if (!challenge || !record || record.sessionVersion !== challenge.version || record.totpEnabledAt === null)
|
|
40
|
+
return failed('expired')
|
|
41
|
+
|
|
42
|
+
// Six digits with three live at a time make about one guess in 333,000: the attempt budget is what makes the factor strong.
|
|
43
|
+
if (await secondFactorLimited(state, record))
|
|
44
|
+
return failed('limited')
|
|
45
|
+
|
|
46
|
+
if (!(await spendSecondFactor(state, record, code))) {
|
|
47
|
+
await report(state, record, 'sign-in-failed', 'two-factor')
|
|
48
|
+
|
|
49
|
+
return failed('invalid')
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
await forget(state.core.rates, `two-factor:${record.id}`, state.core.limits.twoFactorAccount)
|
|
53
|
+
await state.session.unset('authChallenge')
|
|
54
|
+
await signIn(record, challenge.method ?? 'unknown')
|
|
55
|
+
|
|
56
|
+
return { ok: true, redirect: challenge.redirect }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export type SetUpTwoFactorResult = { ok: true, setup: TwoFactorSetup } | AuthFailed<ProofFailure | 'enabled'>
|
|
60
|
+
|
|
61
|
+
// A new secret for the signed-in user's authenticator, active once `twoFactor.enable` gets a code from it.
|
|
62
|
+
export async function setUpTwoFactor(state: RequestState, proof: Proof): Promise<SetUpTwoFactorResult> {
|
|
63
|
+
const proved = await reprove(state, proof)
|
|
64
|
+
|
|
65
|
+
if (!proved.ok)
|
|
66
|
+
return proved
|
|
67
|
+
|
|
68
|
+
if (proved.record.totpEnabledAt !== null)
|
|
69
|
+
return failed('enabled')
|
|
70
|
+
|
|
71
|
+
const secret = generateTotpSecret()
|
|
72
|
+
const uri = otpauthUri({ secret, account: proved.record.email ?? proved.record.username ?? proved.record.id, issuer: state.core.name })
|
|
73
|
+
|
|
74
|
+
await state.core.store.users.update(proved.record.id, { totpSecret: state.core.keys.encrypt(secret, totpContext(proved.record.id)) })
|
|
75
|
+
|
|
76
|
+
return { ok: true, setup: { secret, uri } }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export type EnableTwoFactorResult = { ok: true, recoveryCodes: string[] } | AuthFailed<'signed-out' | 'not-set-up' | 'enabled' | 'invalid' | 'limited'>
|
|
80
|
+
|
|
81
|
+
// Turns the second factor on once the authenticator proves it holds the secret; answers the recovery codes, shown this once.
|
|
82
|
+
export async function enableTwoFactor(state: RequestState, code: string): Promise<EnableTwoFactorResult> {
|
|
83
|
+
const record = await state.current()
|
|
84
|
+
|
|
85
|
+
if (!record || state.via() !== 'session')
|
|
86
|
+
return failed('signed-out')
|
|
87
|
+
|
|
88
|
+
if (record.totpEnabledAt !== null)
|
|
89
|
+
return failed('enabled')
|
|
90
|
+
|
|
91
|
+
const secret = record.totpSecret === null ? undefined : state.core.keys.decrypt(record.totpSecret, totpContext(record.id))
|
|
92
|
+
|
|
93
|
+
if (secret === undefined)
|
|
94
|
+
return failed('not-set-up')
|
|
95
|
+
|
|
96
|
+
// Counted like a sign-in code: a session alone may not guess the pending secret's codes at will.
|
|
97
|
+
if (await spend(state.core.rates, `two-factor:${state.client}`, state.core.limits.twoFactor) || await spend(state.core.rates, `enable-two-factor:${record.id}`, state.core.limits.twoFactorAccount))
|
|
98
|
+
return failed('limited')
|
|
99
|
+
|
|
100
|
+
const step = await verifyTotp(secret, code)
|
|
101
|
+
|
|
102
|
+
if (step === undefined)
|
|
103
|
+
return failed('invalid')
|
|
104
|
+
|
|
105
|
+
await forget(state.core.rates, `enable-two-factor:${record.id}`, state.core.limits.twoFactorAccount)
|
|
106
|
+
|
|
107
|
+
const updated = await endOtherSessions(state, record, { totpEnabledAt: new Date(), totpLastStep: step })
|
|
108
|
+
|
|
109
|
+
if (updated)
|
|
110
|
+
await securityNotice(state, updated, 'two-factor-enabled')
|
|
111
|
+
|
|
112
|
+
return { ok: true, recoveryCodes: await issueRecoveryCodes(state.core, record.id) }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// What `enrollTotp` hands a test: the authenticator's secret, a code for the current step (or one `offset` steps on), and the recovery codes.
|
|
116
|
+
export interface TotpEnrolment {
|
|
117
|
+
secret: string
|
|
118
|
+
code: (offset?: number) => Promise<string>
|
|
119
|
+
recoveryCodes: string[]
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Turns two-factor on for a member as the app would once they confirm a code, with no session, proof or mail, for a test; the code of the current step stays unspent, so it signs in.
|
|
123
|
+
export async function enrollTotp(core: Core, userId: string): Promise<TotpEnrolment> {
|
|
124
|
+
const record = await core.store.users.get(userId)
|
|
125
|
+
|
|
126
|
+
if (!record)
|
|
127
|
+
throw new Error(`kayjs-auth: enrollTotp found no member with id ${userId}`)
|
|
128
|
+
|
|
129
|
+
if (record.totpEnabledAt !== null)
|
|
130
|
+
throw new Error('kayjs-auth: enrollTotp found a member who already has two-factor')
|
|
131
|
+
|
|
132
|
+
const secret = generateTotpSecret()
|
|
133
|
+
|
|
134
|
+
await core.store.users.update(userId, { totpSecret: core.keys.encrypt(secret, totpContext(userId)), totpEnabledAt: new Date(), totpLastStep: 0 })
|
|
135
|
+
|
|
136
|
+
return { secret, code: async (offset = 0) => totpCode(secret, totpStep() + offset), recoveryCodes: await issueRecoveryCodes(core, userId) }
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export type DisableTwoFactorResult = { ok: true } | AuthFailed<ProofFailure>
|
|
140
|
+
|
|
141
|
+
export async function disableTwoFactor(state: RequestState, proof: Proof): Promise<DisableTwoFactorResult> {
|
|
142
|
+
const proved = await reprove(state, proof, { secondFactor: true })
|
|
143
|
+
|
|
144
|
+
if (!proved.ok)
|
|
145
|
+
return proved
|
|
146
|
+
|
|
147
|
+
await state.core.store.recoveryCodes.replace(proved.record.id, [])
|
|
148
|
+
await endOtherSessions(state, proved.record, { totpSecret: null, totpEnabledAt: null })
|
|
149
|
+
await securityNotice(state, proved.record, 'two-factor-disabled')
|
|
150
|
+
|
|
151
|
+
return { ok: true }
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export type RecoveryCodesResult = { ok: true, recoveryCodes: string[] } | AuthFailed<ProofFailure | 'not-enabled'>
|
|
155
|
+
|
|
156
|
+
// A new set of recovery codes, the old ones void.
|
|
157
|
+
export async function regenerateRecoveryCodes(state: RequestState, proof: Proof): Promise<RecoveryCodesResult> {
|
|
158
|
+
const proved = await reprove(state, proof, { secondFactor: true })
|
|
159
|
+
|
|
160
|
+
if (!proved.ok)
|
|
161
|
+
return proved
|
|
162
|
+
|
|
163
|
+
if (proved.record.totpEnabledAt === null)
|
|
164
|
+
return failed('not-enabled')
|
|
165
|
+
|
|
166
|
+
const recoveryCodes = await issueRecoveryCodes(state.core, proved.record.id)
|
|
167
|
+
|
|
168
|
+
await endOtherSessions(state, proved.record)
|
|
169
|
+
await securityNotice(state, proved.record, 'recovery-codes-regenerated')
|
|
170
|
+
|
|
171
|
+
return { ok: true, recoveryCodes }
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// An authenticator code, its step recorded so it works once; or a recovery code, spent.
|
|
175
|
+
export async function spendSecondFactor(state: RequestState, record: UserRecord, code: string): Promise<'totp' | 'recovery' | undefined> {
|
|
176
|
+
const { core } = state
|
|
177
|
+
const secret = record.totpSecret === null ? undefined : core.keys.decrypt(record.totpSecret, totpContext(record.id))
|
|
178
|
+
const step = secret === undefined ? undefined : await verifyTotp(secret, code)
|
|
179
|
+
|
|
180
|
+
if (step !== undefined)
|
|
181
|
+
return await core.store.users.advanceTotpStep(record.id, step) ? 'totp' : undefined
|
|
182
|
+
|
|
183
|
+
const normalized = code.toLowerCase().replace(NOT_CODE_CHARACTERS, '')
|
|
184
|
+
|
|
185
|
+
if (normalized.length !== RECOVERY_CODE_LENGTH || !(await core.store.recoveryCodes.consume(record.id, digest(normalized))))
|
|
186
|
+
return undefined
|
|
187
|
+
|
|
188
|
+
await securityNotice(state, record, 'recovery-code-used')
|
|
189
|
+
|
|
190
|
+
return 'recovery'
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// Grouped by five, `abcde-fghij-klmno`, since a wall of characters is where people misread.
|
|
194
|
+
async function issueRecoveryCodes(core: Core, userId: string): Promise<string[]> {
|
|
195
|
+
const codes = Array.from({ length: RECOVERY_CODE_COUNT }, () => nanoid(RECOVERY_CODE_LENGTH, RECOVERY_CODE_ALPHABET))
|
|
196
|
+
|
|
197
|
+
await core.store.recoveryCodes.replace(userId, codes.map(code => digest(code)))
|
|
198
|
+
|
|
199
|
+
return codes.map(code => code.replace(EVERY_FIVE, '$&-'))
|
|
200
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export type Level = 'read' | 'write'
|
|
2
|
+
|
|
3
|
+
/** The resolved actor, generic over the consumer's user type. `null` is anonymous. */
|
|
4
|
+
export type Principal<P> = P | null
|
|
5
|
+
|
|
6
|
+
/* eslint-disable ts/no-explicit-any -- a predicate reads the params and body of whichever routes it guards, each typed its own way */
|
|
7
|
+
/** Request-derived facts a predicate may read - a subset of the Elysia context. */
|
|
8
|
+
export interface PolicyContext {
|
|
9
|
+
params?: Record<string, any> | undefined
|
|
10
|
+
body?: any
|
|
11
|
+
query?: Record<string, string> | undefined
|
|
12
|
+
}
|
|
13
|
+
/* eslint-enable ts/no-explicit-any */
|
|
14
|
+
|
|
15
|
+
/** Custom authorization check: receives the resolved principal and request context. */
|
|
16
|
+
export type Predicate<P> = (principal: Principal<P>, ctx: PolicyContext) => boolean | Promise<boolean>
|
|
17
|
+
|
|
18
|
+
/** What a route requires: a grant type `G`, a resource-scoped `{ type, resourceId }`, a `Predicate`, or an array where ANY entry passes. */
|
|
19
|
+
export type Requirement<P, G extends string>
|
|
20
|
+
= | G
|
|
21
|
+
| { type: G, resourceId?: number | null }
|
|
22
|
+
| Predicate<P>
|
|
23
|
+
| Requirement<P, G>[]
|
package/src/userData.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { TypeCheck } from 'elysia/type-system'
|
|
2
|
+
import type { Schema } from 'kay'
|
|
3
|
+
import { Buffer } from 'node:buffer'
|
|
4
|
+
import { TypeCompiler } from 'elysia/type-system'
|
|
5
|
+
import { configError } from 'kay/library'
|
|
6
|
+
|
|
7
|
+
// What a user's app data is held to: the top-level fields the app's schema declares, and the schema's check.
|
|
8
|
+
export interface UserDataRules {
|
|
9
|
+
keys: string[]
|
|
10
|
+
check: TypeCheck<Schema>
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
// The most bytes of JSON a user's app data may take, so a profile cannot fill a row.
|
|
14
|
+
const MOST_DATA_LENGTH = 16_384
|
|
15
|
+
|
|
16
|
+
export function userDataRules(schema: Schema): UserDataRules {
|
|
17
|
+
const properties = (schema as { properties?: Record<string, unknown> }).properties
|
|
18
|
+
|
|
19
|
+
if (properties === undefined)
|
|
20
|
+
throw configError('auth', 'user', '`user` is an object schema, such as `s.Object({ avatar: s.Optional(s.String()) })`')
|
|
21
|
+
|
|
22
|
+
return { keys: Object.keys(properties), check: TypeCompiler.Compile(schema) }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// `held` with the declared fields of `given` laid over it, as the JSON the store keeps, or undefined when what results is no JSON the schema accepts or is too large. A field the schema does not declare is dropped, whatever its name, and one `given` leaves out or sets to undefined keeps its value.
|
|
26
|
+
export function mergedData(rules: UserDataRules, held: Record<string, unknown> | undefined, given: unknown): Record<string, unknown> | undefined {
|
|
27
|
+
if (typeof given !== 'object' || given === null || Array.isArray(given))
|
|
28
|
+
return undefined
|
|
29
|
+
|
|
30
|
+
const next: Record<string, unknown> = { ...held }
|
|
31
|
+
|
|
32
|
+
for (const key of rules.keys) {
|
|
33
|
+
const value = Object.hasOwn(given, key) ? (given as Record<string, unknown>)[key] : undefined
|
|
34
|
+
|
|
35
|
+
if (value !== undefined)
|
|
36
|
+
next[key] = value
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const text = JSON.stringify(next)
|
|
40
|
+
|
|
41
|
+
if (Buffer.byteLength(text) > MOST_DATA_LENGTH)
|
|
42
|
+
return undefined
|
|
43
|
+
|
|
44
|
+
const json = JSON.parse(text) as Record<string, unknown>
|
|
45
|
+
|
|
46
|
+
return rules.check.Check(json) ? json : undefined
|
|
47
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
--- server
|
|
2
|
+
import DeletionBanner from '../components/deletion-banner.kay'
|
|
3
|
+
import ImpersonationBanner from '../components/impersonation-banner.kay'
|
|
4
|
+
import { loadViewer } from '../viewer'
|
|
5
|
+
|
|
6
|
+
// Reads the signed-in user before the page renders, so SignedIn, SignedOut and UserMenu show with the first bytes rather than streaming in after them.
|
|
7
|
+
await loadViewer(ctx.request)
|
|
8
|
+
---
|
|
9
|
+
ImpersonationBanner
|
|
10
|
+
DeletionBanner
|
|
11
|
+
slot
|
package/src/viewer.ts
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import type { Auth } from './auth'
|
|
2
|
+
import type { BareUser } from './core'
|
|
3
|
+
import { log } from './log'
|
|
4
|
+
|
|
5
|
+
export interface Viewer {
|
|
6
|
+
auth: Auth
|
|
7
|
+
isGranted: (role: string, user: BareUser) => boolean
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const asViewer = (user: BareUser | null) => user && !user.guest ? user : null
|
|
11
|
+
const viewers = new WeakMap<Request, Viewer>()
|
|
12
|
+
// The user a layout read ahead of the render, `null` for none: what lets a template show them with no streamed block.
|
|
13
|
+
const loaded = new WeakMap<Request, BareUser | null>()
|
|
14
|
+
// The admin behind an impersonation read ahead of the render, `null` for none.
|
|
15
|
+
const impersonators = new WeakMap<Request, BareUser | null>()
|
|
16
|
+
// When the user's account is deleted if they do nothing, `null` for an account not pending deletion.
|
|
17
|
+
const deletions = new WeakMap<Request, Date | null>()
|
|
18
|
+
// The banners already drawn for a request, so a layout and a page both holding one show a single.
|
|
19
|
+
const banners = new WeakMap<Request, Set<string>>()
|
|
20
|
+
let requestReader: (() => Request | undefined) | undefined
|
|
21
|
+
|
|
22
|
+
// Given by the server code of `authCore`, so this module imports nothing server-only and a component using it never drags kay's server into a browser build.
|
|
23
|
+
export function readRequestWith(read: () => Request | undefined): void {
|
|
24
|
+
requestReader = read
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Called where `authCore` first sees the request, so a component can read the signed-in user without a server fence.
|
|
28
|
+
export function registerViewer(request: Request, viewer: Viewer): void {
|
|
29
|
+
viewers.set(request, viewer)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Reads the request's user ahead of the render: a failed read is reported and leaves the page signed out, while a component calling `currentUser` reads again and reports it too.
|
|
33
|
+
export async function loadViewer(request: Request): Promise<void> {
|
|
34
|
+
try {
|
|
35
|
+
const auth = viewers.get(request)?.auth
|
|
36
|
+
|
|
37
|
+
if (auth === undefined)
|
|
38
|
+
return
|
|
39
|
+
|
|
40
|
+
loaded.set(request, await auth.bareUser())
|
|
41
|
+
impersonators.set(request, await auth.impersonator())
|
|
42
|
+
deletions.set(request, (await auth.account.deletion())?.deleteAt ?? null)
|
|
43
|
+
}
|
|
44
|
+
catch (error) {
|
|
45
|
+
log.error('could not read the signed-in user ahead of the render', error)
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// What templates read off `ctx`: `ctx.user`, the signed-in user (none for a visitor or a guest), `ctx.can(role)`, whether they hold the role under the app's `roles` hierarchy, `ctx.impersonator`, the admin acting as that user (null for none), and `ctx.deletion`, when the user's account is deleted if they do nothing (null unless `account.deleteAfter` marked it pending).
|
|
50
|
+
export interface ViewerValues {
|
|
51
|
+
user: BareUser | null
|
|
52
|
+
impersonator: BareUser | null
|
|
53
|
+
deletion: Date | null
|
|
54
|
+
can: (role: string) => boolean
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export async function viewerValues(request: Request): Promise<ViewerValues> {
|
|
58
|
+
await loadViewer(request)
|
|
59
|
+
|
|
60
|
+
const viewer = viewers.get(request)
|
|
61
|
+
const user = loaded.has(request) ? asViewer(loaded.get(request)!) : null
|
|
62
|
+
|
|
63
|
+
return { user, impersonator: user && (impersonators.get(request) ?? null), deletion: user && (deletions.get(request) ?? null), can: role => user !== null && viewer !== undefined && viewer.isGranted(role, user) }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// The auth and role check of the page being rendered, for `SignedIn`, `SignedOut` and `UserMenu`.
|
|
67
|
+
export function currentViewer(): Viewer & { request: Request } {
|
|
68
|
+
const request = requestReader?.()
|
|
69
|
+
const viewer = request && viewers.get(request)
|
|
70
|
+
|
|
71
|
+
if (!viewer)
|
|
72
|
+
throw new Error('kayjs-auth: SignedIn, SignedOut and UserMenu read the signed-in user of the request being answered, so they cannot render in a prerendered page or outside a request; render the page per request (`prerender: false`)')
|
|
73
|
+
|
|
74
|
+
return { ...viewer, request }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// The signed-in user of the page being rendered, none for a visitor or a guest, or one lacking `role` (the app's role hierarchy applies). The user itself once the layout loaded it, else a promise a block waits for.
|
|
78
|
+
export function currentUser(role?: string): BareUser | null | Promise<BareUser | null> {
|
|
79
|
+
const { auth, isGranted, request } = currentViewer()
|
|
80
|
+
const within = (user: BareUser | null) => {
|
|
81
|
+
const signedIn = asViewer(user)
|
|
82
|
+
|
|
83
|
+
return signedIn && (role === undefined || isGranted(role, signedIn)) ? signedIn : null
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
return loaded.has(request) ? within(loaded.get(request)!) : read(auth, within)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async function read(auth: Auth, within: (user: BareUser | null) => BareUser | null): Promise<BareUser | null> {
|
|
90
|
+
return within(await auth.bareUser())
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// True the first time the banner is asked for by the request being rendered, false after.
|
|
94
|
+
export function claimBanner(banner = 'impersonation'): boolean {
|
|
95
|
+
const { request } = currentViewer()
|
|
96
|
+
const drawn = banners.get(request) ?? new Set<string>()
|
|
97
|
+
|
|
98
|
+
banners.set(request, drawn)
|
|
99
|
+
|
|
100
|
+
const free = !drawn.has(banner)
|
|
101
|
+
|
|
102
|
+
drawn.add(banner)
|
|
103
|
+
|
|
104
|
+
return free
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Whether the page being rendered is for a visitor with no account or a guest, `SignedOut` showing its children.
|
|
108
|
+
export function isSignedOut(): boolean | Promise<boolean> {
|
|
109
|
+
const user = currentUser()
|
|
110
|
+
|
|
111
|
+
return user instanceof Promise ? settled(user) : user === null
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async function settled(user: Promise<BareUser | null>): Promise<boolean> {
|
|
115
|
+
return await user === null
|
|
116
|
+
}
|
package/src/wayIn.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { RequestState } from './state'
|
|
2
|
+
import type { IdentityRecord, PasskeyRecord } from './store'
|
|
3
|
+
|
|
4
|
+
type Core = RequestState['core']
|
|
5
|
+
|
|
6
|
+
// What a removal takes away from the ways in.
|
|
7
|
+
export type Removed = { identity: IdentityRecord } | { passkey: PasskeyRecord }
|
|
8
|
+
|
|
9
|
+
// Whether the user can sign in some other way than by a session once `without` is gone: a password, a magic link to a verified address, a linked provider or a passkey that proved user verification, those the app switched off not counted. Read from the store, so it sees what a request racing this one wrote.
|
|
10
|
+
export async function hasWayIn(core: Core, userId: string, without?: Removed): Promise<boolean> {
|
|
11
|
+
const record = await core.store.users.get(userId)
|
|
12
|
+
|
|
13
|
+
if (!record)
|
|
14
|
+
return true
|
|
15
|
+
|
|
16
|
+
if ((core.switches.password && record.passwordHash !== null) || (core.switches.magicLink && core.email !== undefined && record.emailVerifiedAt !== null))
|
|
17
|
+
return true
|
|
18
|
+
|
|
19
|
+
const identities = await core.store.identities.listByUser(userId)
|
|
20
|
+
|
|
21
|
+
if (identities.some(identity => !(without && 'identity' in without && same(identity, without.identity))))
|
|
22
|
+
return true
|
|
23
|
+
|
|
24
|
+
return core.switches.passkeys && (await core.store.passkeys.listByUser(userId)).some(passkey => passkey.userVerified && !(without && 'passkey' in without && passkey.id === without.passkey.id))
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function same(a: IdentityRecord, b: IdentityRecord): boolean {
|
|
28
|
+
return a.provider === b.provider && a.providerId === b.providerId
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Puts a removed identity or passkey back; a request racing this one may have done so already, which leaves nothing to undo. Any other failure is rethrown once the user is found with no way in, rather than answered as a refusal that leaves them locked out.
|
|
32
|
+
export async function putBack(core: Core, userId: string, restore: () => unknown): Promise<void> {
|
|
33
|
+
try {
|
|
34
|
+
await restore()
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
if (!await hasWayIn(core, userId))
|
|
38
|
+
throw error
|
|
39
|
+
}
|
|
40
|
+
}
|