@kayjs/auth 0.0.0-stage → 1.104.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +78 -2
- package/llms/admin-and-organizations.md +70 -0
- package/llms/admin-pages.md +30 -0
- package/llms/grouped-methods.md +106 -0
- package/llms/hardening-and-testing.md +108 -0
- package/llms/oauth-passkeys-two-factor.md +111 -0
- package/llms/oauth-providers.md +28 -0
- package/llms/oauth-server-and-tokens.md +76 -0
- package/llms/organization-pages.md +20 -0
- package/llms/passwords-and-mails.md +129 -0
- package/llms/sessions-and-guards.md +51 -0
- package/llms/setup.md +122 -0
- package/llms/signed-in-components.md +59 -0
- package/llms.txt +28 -0
- package/package.json +85 -4
- package/src/access.ts +31 -0
- package/src/account.ts +198 -0
- package/src/add.ts +70 -0
- package/src/address.ts +51 -0
- package/src/admin.ts +361 -0
- package/src/auditWording.ts +153 -0
- package/src/auth.ts +219 -0
- package/src/authorize/clients.ts +160 -0
- package/src/authorize/grants.ts +44 -0
- package/src/authorize/metadata.ts +72 -0
- package/src/authorize/register.ts +38 -0
- package/src/authorize/reply.ts +9 -0
- package/src/authorize/request.ts +253 -0
- package/src/authorize/resource.ts +34 -0
- package/src/authorize/revoke.ts +36 -0
- package/src/authorize/routes.ts +87 -0
- package/src/authorize/token.ts +213 -0
- package/src/authorize/uris.ts +76 -0
- package/src/bearer.ts +208 -0
- package/src/bearerHeader.ts +11 -0
- package/src/breached.ts +47 -0
- package/src/browser.ts +59 -0
- package/src/captcha.ts +196 -0
- package/src/cbor.ts +129 -0
- package/src/components/deletion-banner.kay +20 -0
- package/src/components/impersonation-banner.kay +21 -0
- package/src/components/signed-in.kay +8 -0
- package/src/components/signed-out.kay +6 -0
- package/src/components/user-menu.kay +21 -0
- package/src/context.ts +5 -0
- package/src/core.ts +308 -0
- package/src/createUserCommand.ts +217 -0
- package/src/decide.ts +45 -0
- package/src/deletion.ts +80 -0
- package/src/devTool.ts +104 -0
- package/src/device.ts +37 -0
- package/src/email.ts +594 -0
- package/src/erase.ts +237 -0
- package/src/events.ts +297 -0
- package/src/export.ts +101 -0
- package/src/failure.ts +63 -0
- package/src/forwardAuth.ts +55 -0
- package/src/forwardRoutes.ts +68 -0
- package/src/gate.ts +104 -0
- package/src/guard.ts +22 -0
- package/src/guards.ts +72 -0
- package/src/guesses.ts +99 -0
- package/src/index.ts +46 -0
- package/src/keys.ts +51 -0
- package/src/limits.ts +182 -0
- package/src/load.ts +18 -0
- package/src/locale.ts +15 -0
- package/src/log.ts +4 -0
- package/src/mail.ts +225 -0
- package/src/memoryStore.ts +599 -0
- package/src/messages/fr.ts +357 -0
- package/src/methods/account.ts +80 -0
- package/src/methods/admin.ts +63 -0
- package/src/methods/audit.ts +15 -0
- package/src/methods/email.ts +39 -0
- package/src/methods/magicLink.ts +32 -0
- package/src/methods/oauth.ts +35 -0
- package/src/methods/oauthServer.ts +31 -0
- package/src/methods/organizations.ts +96 -0
- package/src/methods/passkeys.ts +61 -0
- package/src/methods/password.ts +53 -0
- package/src/methods/sessions.ts +18 -0
- package/src/methods/tokens.ts +24 -0
- package/src/methods/twoFactor.ts +62 -0
- package/src/oauth/client.ts +324 -0
- package/src/oauth/flow.ts +350 -0
- package/src/oauth/index.ts +5 -0
- package/src/oauth/pkce.ts +20 -0
- package/src/oauth/providers.ts +490 -0
- package/src/oauth/refresher.ts +177 -0
- package/src/oauth/timeout.ts +2 -0
- package/src/oauth/types.ts +78 -0
- package/src/oauthTest.ts +112 -0
- package/src/organizations.ts +675 -0
- package/src/organizationsCore.ts +60 -0
- package/src/own.ts +313 -0
- package/src/pages/components/captcha.kay +16 -0
- package/src/pages/components/frame.kay +11 -0
- package/src/pages/components/message.kay +8 -0
- package/src/pages/components/panel.kay +12 -0
- package/src/pages/components/passkey-add.kay +48 -0
- package/src/pages/components/passkey-sign-in.kay +34 -0
- package/src/pages/components/passkey-two-factor.kay +33 -0
- package/src/pages/components/proof.kay +15 -0
- package/src/pages/components/provider-buttons.kay +25 -0
- package/src/pages/components/recovery-codes.kay +13 -0
- package/src/pages/components/separator.kay +4 -0
- package/src/pages/english.ts +82 -0
- package/src/pages/forms.ts +185 -0
- package/src/pages/index.ts +361 -0
- package/src/pages/organizationPage.ts +12 -0
- package/src/pages/routes/account/_guard.ts +15 -0
- package/src/pages/routes/account/_layout.kay +37 -0
- package/src/pages/routes/account/clients.kay +33 -0
- package/src/pages/routes/account/connections.kay +57 -0
- package/src/pages/routes/account/data.kay +106 -0
- package/src/pages/routes/account/index.kay +109 -0
- package/src/pages/routes/account/organizations/[org].kay +188 -0
- package/src/pages/routes/account/organizations/_guard.ts +8 -0
- package/src/pages/routes/account/organizations/index.kay +86 -0
- package/src/pages/routes/account/security.kay +164 -0
- package/src/pages/routes/account/sessions.kay +51 -0
- package/src/pages/routes/account/tokens.kay +84 -0
- package/src/pages/routes/admin/_layout.kay +43 -0
- package/src/pages/routes/admin/audit.kay +43 -0
- package/src/pages/routes/admin/index.kay +60 -0
- package/src/pages/routes/admin/users/[id].kay +181 -0
- package/src/pages/routes/confirm-email.kay +39 -0
- package/src/pages/routes/invitation.kay +104 -0
- package/src/pages/routes/magic-link.kay +42 -0
- package/src/pages/routes/oauth/authorize.kay +80 -0
- package/src/pages/routes/register.kay +83 -0
- package/src/pages/routes/reset-password.kay +73 -0
- package/src/pages/routes/sign-in.kay +128 -0
- package/src/pages/routes/two-factor.kay +61 -0
- package/src/pages/routes/verify-email.kay +83 -0
- package/src/passkeys.ts +373 -0
- package/src/password.ts +316 -0
- package/src/payloads.ts +22 -0
- package/src/pg.ts +705 -0
- package/src/profile.ts +43 -0
- package/src/proof.ts +110 -0
- package/src/prune.ts +123 -0
- package/src/rates.ts +82 -0
- package/src/request.ts +712 -0
- package/src/requiredTwoFactor.ts +71 -0
- package/src/requirement.ts +23 -0
- package/src/roles.ts +18 -0
- package/src/routes.ts +202 -0
- package/src/rules-check.ts +37 -0
- package/src/rules.ts +108 -0
- package/src/securityNotice.ts +45 -0
- package/src/sessions.ts +184 -0
- package/src/setup.ts +417 -0
- package/src/signInOptions.ts +9 -0
- package/src/state.ts +34 -0
- package/src/store.ts +410 -0
- package/src/storeHelpers.ts +23 -0
- package/src/test.ts +46 -0
- package/src/testCookies.ts +9 -0
- package/src/testHelpers.ts +58 -0
- package/src/testing.ts +113 -0
- package/src/text.ts +6 -0
- package/src/totp.ts +120 -0
- package/src/twoFactor.ts +200 -0
- package/src/types.ts +23 -0
- package/src/userData.ts +47 -0
- package/src/viewer-layout/_layout.kay +11 -0
- package/src/viewer.ts +116 -0
- package/src/wayIn.ts +40 -0
- package/src/webauthn.ts +375 -0
- package/src/wsAuth.ts +53 -0
- package/types/access.d.ts +12 -0
- package/types/access.d.ts.map +1 -0
- package/types/account.d.ts +32 -0
- package/types/account.d.ts.map +1 -0
- package/types/add.d.ts +29 -0
- package/types/add.d.ts.map +1 -0
- package/types/address.d.ts +2 -0
- package/types/address.d.ts.map +1 -0
- package/types/admin.d.ts +84 -0
- package/types/admin.d.ts.map +1 -0
- package/types/auditWording.d.ts +9 -0
- package/types/auditWording.d.ts.map +1 -0
- package/types/auth.d.ts +3475 -0
- package/types/auth.d.ts.map +1 -0
- package/types/authorize/clients.d.ts +15 -0
- package/types/authorize/clients.d.ts.map +1 -0
- package/types/authorize/grants.d.ts +15 -0
- package/types/authorize/grants.d.ts.map +1 -0
- package/types/authorize/metadata.d.ts +20 -0
- package/types/authorize/metadata.d.ts.map +1 -0
- package/types/authorize/register.d.ts +4 -0
- package/types/authorize/register.d.ts.map +1 -0
- package/types/authorize/reply.d.ts +6 -0
- package/types/authorize/reply.d.ts.map +1 -0
- package/types/authorize/request.d.ts +48 -0
- package/types/authorize/request.d.ts.map +1 -0
- package/types/authorize/resource.d.ts +4 -0
- package/types/authorize/resource.d.ts.map +1 -0
- package/types/authorize/revoke.d.ts +4 -0
- package/types/authorize/revoke.d.ts.map +1 -0
- package/types/authorize/routes.d.ts +5 -0
- package/types/authorize/routes.d.ts.map +1 -0
- package/types/authorize/token.d.ts +7 -0
- package/types/authorize/token.d.ts.map +1 -0
- package/types/authorize/uris.d.ts +5 -0
- package/types/authorize/uris.d.ts.map +1 -0
- package/types/bearer.d.ts +45 -0
- package/types/bearer.d.ts.map +1 -0
- package/types/bearerHeader.d.ts +3 -0
- package/types/bearerHeader.d.ts.map +1 -0
- package/types/breached.d.ts +5 -0
- package/types/breached.d.ts.map +1 -0
- package/types/browser.d.ts +11 -0
- package/types/browser.d.ts.map +1 -0
- package/types/captcha.d.ts +42 -0
- package/types/captcha.d.ts.map +1 -0
- package/types/cbor.d.ts +4 -0
- package/types/cbor.d.ts.map +1 -0
- package/types/context.d.ts +3 -0
- package/types/context.d.ts.map +1 -0
- package/types/core.d.ts +180 -0
- package/types/core.d.ts.map +1 -0
- package/types/createUserCommand.d.ts +11 -0
- package/types/createUserCommand.d.ts.map +1 -0
- package/types/decide.d.ts +12 -0
- package/types/decide.d.ts.map +1 -0
- package/types/deletion.d.ts +17 -0
- package/types/deletion.d.ts.map +1 -0
- package/types/devTool.d.ts +3 -0
- package/types/devTool.d.ts.map +1 -0
- package/types/device.d.ts +7 -0
- package/types/device.d.ts.map +1 -0
- package/types/email.d.ts +73 -0
- package/types/email.d.ts.map +1 -0
- package/types/erase.d.ts +31 -0
- package/types/erase.d.ts.map +1 -0
- package/types/events.d.ts +139 -0
- package/types/events.d.ts.map +1 -0
- package/types/export.d.ts +54 -0
- package/types/export.d.ts.map +1 -0
- package/types/failure.d.ts +19 -0
- package/types/failure.d.ts.map +1 -0
- package/types/forwardAuth.d.ts +12 -0
- package/types/forwardAuth.d.ts.map +1 -0
- package/types/forwardRoutes.d.ts +11 -0
- package/types/forwardRoutes.d.ts.map +1 -0
- package/types/gate.d.ts +31 -0
- package/types/gate.d.ts.map +1 -0
- package/types/guard.d.ts +10 -0
- package/types/guard.d.ts.map +1 -0
- package/types/guards.d.ts +37 -0
- package/types/guards.d.ts.map +1 -0
- package/types/guesses.d.ts +18 -0
- package/types/guesses.d.ts.map +1 -0
- package/types/index.d.ts +47 -0
- package/types/index.d.ts.map +1 -0
- package/types/keys.d.ts +11 -0
- package/types/keys.d.ts.map +1 -0
- package/types/limits.d.ts +133 -0
- package/types/limits.d.ts.map +1 -0
- package/types/load.d.ts +18 -0
- package/types/load.d.ts.map +1 -0
- package/types/locale.d.ts +4 -0
- package/types/locale.d.ts.map +1 -0
- package/types/log.d.ts +2 -0
- package/types/log.d.ts.map +1 -0
- package/types/mail.d.ts +51 -0
- package/types/mail.d.ts.map +1 -0
- package/types/memoryStore.d.ts +3 -0
- package/types/memoryStore.d.ts.map +1 -0
- package/types/messages/fr.d.ts +409 -0
- package/types/messages/fr.d.ts.map +1 -0
- package/types/methods/account.d.ts +24 -0
- package/types/methods/account.d.ts.map +1 -0
- package/types/methods/admin.d.ts +30 -0
- package/types/methods/admin.d.ts.map +1 -0
- package/types/methods/audit.d.ts +11 -0
- package/types/methods/audit.d.ts.map +1 -0
- package/types/methods/email.d.ts +14 -0
- package/types/methods/email.d.ts.map +1 -0
- package/types/methods/magicLink.d.ts +12 -0
- package/types/methods/magicLink.d.ts.map +1 -0
- package/types/methods/oauth.d.ts +16 -0
- package/types/methods/oauth.d.ts.map +1 -0
- package/types/methods/oauthServer.d.ts +13 -0
- package/types/methods/oauthServer.d.ts.map +1 -0
- package/types/methods/organizations.d.ts +30 -0
- package/types/methods/organizations.d.ts.map +1 -0
- package/types/methods/passkeys.d.ts +19 -0
- package/types/methods/passkeys.d.ts.map +1 -0
- package/types/methods/password.d.ts +17 -0
- package/types/methods/password.d.ts.map +1 -0
- package/types/methods/sessions.d.ts +9 -0
- package/types/methods/sessions.d.ts.map +1 -0
- package/types/methods/tokens.d.ts +11 -0
- package/types/methods/tokens.d.ts.map +1 -0
- package/types/methods/twoFactor.d.ts +20 -0
- package/types/methods/twoFactor.d.ts.map +1 -0
- package/types/oauth/client.d.ts +39 -0
- package/types/oauth/client.d.ts.map +1 -0
- package/types/oauth/flow.d.ts +38 -0
- package/types/oauth/flow.d.ts.map +1 -0
- package/types/oauth/index.d.ts +6 -0
- package/types/oauth/index.d.ts.map +1 -0
- package/types/oauth/pkce.d.ts +10 -0
- package/types/oauth/pkce.d.ts.map +1 -0
- package/types/oauth/providers.d.ts +100 -0
- package/types/oauth/providers.d.ts.map +1 -0
- package/types/oauth/refresher.d.ts +55 -0
- package/types/oauth/refresher.d.ts.map +1 -0
- package/types/oauth/timeout.d.ts +2 -0
- package/types/oauth/timeout.d.ts.map +1 -0
- package/types/oauth/types.d.ts +75 -0
- package/types/oauth/types.d.ts.map +1 -0
- package/types/oauthTest.d.ts +23 -0
- package/types/oauthTest.d.ts.map +1 -0
- package/types/organizations.d.ts +111 -0
- package/types/organizations.d.ts.map +1 -0
- package/types/organizationsCore.d.ts +29 -0
- package/types/organizationsCore.d.ts.map +1 -0
- package/types/own.d.ts +55 -0
- package/types/own.d.ts.map +1 -0
- package/types/pages/english.d.ts +80 -0
- package/types/pages/english.d.ts.map +1 -0
- package/types/pages/forms.d.ts +204 -0
- package/types/pages/forms.d.ts.map +1 -0
- package/types/pages/index.d.ts +166 -0
- package/types/pages/index.d.ts.map +1 -0
- package/types/pages/organizationPage.d.ts +7 -0
- package/types/pages/organizationPage.d.ts.map +1 -0
- package/types/pages/routes/account/_guard.d.ts +3 -0
- package/types/pages/routes/account/_guard.d.ts.map +1 -0
- package/types/pages/routes/account/organizations/_guard.d.ts +3 -0
- package/types/pages/routes/account/organizations/_guard.d.ts.map +1 -0
- package/types/passkeys.d.ts +61 -0
- package/types/passkeys.d.ts.map +1 -0
- package/types/password.d.ts +49 -0
- package/types/password.d.ts.map +1 -0
- package/types/payloads.d.ts +4 -0
- package/types/payloads.d.ts.map +1 -0
- package/types/pg.d.ts +303 -0
- package/types/pg.d.ts.map +1 -0
- package/types/profile.d.ts +11 -0
- package/types/profile.d.ts.map +1 -0
- package/types/proof.d.ts +33 -0
- package/types/proof.d.ts.map +1 -0
- package/types/prune.d.ts +5 -0
- package/types/prune.d.ts.map +1 -0
- package/types/rates.d.ts +15 -0
- package/types/rates.d.ts.map +1 -0
- package/types/request.d.ts +119 -0
- package/types/request.d.ts.map +1 -0
- package/types/requiredTwoFactor.d.ts +16 -0
- package/types/requiredTwoFactor.d.ts.map +1 -0
- package/types/requirement.d.ts +4 -0
- package/types/requirement.d.ts.map +1 -0
- package/types/roles.d.ts +9 -0
- package/types/roles.d.ts.map +1 -0
- package/types/routes.d.ts +31 -0
- package/types/routes.d.ts.map +1 -0
- package/types/rules-check.d.ts +3 -0
- package/types/rules-check.d.ts.map +1 -0
- package/types/rules.d.ts +38 -0
- package/types/rules.d.ts.map +1 -0
- package/types/securityNotice.d.ts +7 -0
- package/types/securityNotice.d.ts.map +1 -0
- package/types/sessions.d.ts +32 -0
- package/types/sessions.d.ts.map +1 -0
- package/types/setup.d.ts +18 -0
- package/types/setup.d.ts.map +1 -0
- package/types/signInOptions.d.ts +6 -0
- package/types/signInOptions.d.ts.map +1 -0
- package/types/state.d.ts +25 -0
- package/types/state.d.ts.map +1 -0
- package/types/store.d.ts +295 -0
- package/types/store.d.ts.map +1 -0
- package/types/storeHelpers.d.ts +4 -0
- package/types/storeHelpers.d.ts.map +1 -0
- package/types/test.d.ts +21 -0
- package/types/test.d.ts.map +1 -0
- package/types/testCookies.d.ts +3 -0
- package/types/testCookies.d.ts.map +1 -0
- package/types/testHelpers.d.ts +34 -0
- package/types/testHelpers.d.ts.map +1 -0
- package/types/testing.d.ts +12 -0
- package/types/testing.d.ts.map +1 -0
- package/types/text.d.ts +2 -0
- package/types/text.d.ts.map +1 -0
- package/types/totp.d.ts +12 -0
- package/types/totp.d.ts.map +1 -0
- package/types/twoFactor.d.ts +41 -0
- package/types/twoFactor.d.ts.map +1 -0
- package/types/types.d.ts +17 -0
- package/types/types.d.ts.map +1 -0
- package/types/userData.d.ts +9 -0
- package/types/userData.d.ts.map +1 -0
- package/types/viewer.d.ts +23 -0
- package/types/viewer.d.ts.map +1 -0
- package/types/wayIn.d.ts +12 -0
- package/types/wayIn.d.ts.map +1 -0
- package/types/webauthn.d.ts +111 -0
- package/types/webauthn.d.ts.map +1 -0
- package/types/wsAuth.d.ts +14 -0
- package/types/wsAuth.d.ts.map +1 -0
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]'])
|
|
2
|
+
const REDIRECT_URI_MAX_LENGTH = 2048
|
|
3
|
+
|
|
4
|
+
function loopback(url: URL): boolean {
|
|
5
|
+
return url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname)
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
// A redirect URI an app may be registered with: https, or http on the machine itself for a native app's listener; never a fragment or a login in it.
|
|
9
|
+
export function validRedirectUri(value: unknown): value is string {
|
|
10
|
+
if (typeof value !== 'string' || value.length === 0 || value.length > REDIRECT_URI_MAX_LENGTH)
|
|
11
|
+
return false
|
|
12
|
+
|
|
13
|
+
let url: URL
|
|
14
|
+
|
|
15
|
+
try {
|
|
16
|
+
url = new URL(value)
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return false
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
if (url.hash !== '' || value.includes('#') || url.username !== '' || url.password !== '')
|
|
23
|
+
return false
|
|
24
|
+
|
|
25
|
+
return url.protocol === 'https:' ? url.hostname !== '' : loopback(url)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const REDIRECT_URIS_MAX = 10
|
|
29
|
+
// All the URIs of one client together, which every request naming it is checked against.
|
|
30
|
+
const REDIRECT_URIS_TOTAL = 2048
|
|
31
|
+
|
|
32
|
+
// A list of 1 to 10 redirect URIs a client may be registered with, 2048 characters in all.
|
|
33
|
+
export function validRedirectUris(value: unknown): value is string[] {
|
|
34
|
+
return Array.isArray(value) && value.length > 0 && value.length <= REDIRECT_URIS_MAX && value.every(validRedirectUri) && value.reduce((total: number, uri: string) => total + uri.length, 0) <= REDIRECT_URIS_TOTAL
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Whether `given` is one of the registered URIs: the same text, or for a listener on the machine itself the same URI whatever its port, as a native app picks a free one.
|
|
38
|
+
export function redirectUriRegistered(registered: readonly string[], given: string): boolean {
|
|
39
|
+
if (registered.includes(given))
|
|
40
|
+
return true
|
|
41
|
+
|
|
42
|
+
let wanted: URL
|
|
43
|
+
|
|
44
|
+
try {
|
|
45
|
+
wanted = new URL(given)
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return false
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if (!loopback(wanted))
|
|
52
|
+
return false
|
|
53
|
+
|
|
54
|
+
return registered.some((each) => {
|
|
55
|
+
try {
|
|
56
|
+
const url = new URL(each)
|
|
57
|
+
|
|
58
|
+
return loopback(url) && url.hostname === wanted.hostname && url.pathname === wanted.pathname && url.search === wanted.search
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return false
|
|
62
|
+
}
|
|
63
|
+
})
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// `base` with the query given, an existing one kept: how an authorization response reaches the client.
|
|
67
|
+
export function withParams(base: string, params: Record<string, string | undefined>): string {
|
|
68
|
+
const url = new URL(base)
|
|
69
|
+
|
|
70
|
+
for (const [name, value] of Object.entries(params)) {
|
|
71
|
+
if (value !== undefined)
|
|
72
|
+
url.searchParams.set(name, value)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
return url.href
|
|
76
|
+
}
|
package/src/bearer.ts
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import type { Duration } from 'kay'
|
|
2
|
+
import type { Core } from './core'
|
|
3
|
+
import type { AuthFailed } from './failure'
|
|
4
|
+
import type { Proof, ProofFailure } from './proof'
|
|
5
|
+
import type { RequestState } from './state'
|
|
6
|
+
import type { BearerTokenRecord, UserRecord } from './store'
|
|
7
|
+
import { durationSeconds } from 'kay/library'
|
|
8
|
+
import { siteBase, underResource } from './authorize/resource'
|
|
9
|
+
import { banned, TOUCH_EVERY_MS } from './core'
|
|
10
|
+
import { failed } from './failure'
|
|
11
|
+
import { digest, randomToken } from './keys'
|
|
12
|
+
import { reprove } from './proof'
|
|
13
|
+
import { securityNotice } from './securityNotice'
|
|
14
|
+
import { plainName } from './text'
|
|
15
|
+
|
|
16
|
+
const LABEL_MAX_LENGTH = 64
|
|
17
|
+
const TOKEN = /^\S{32,4096}$/
|
|
18
|
+
const MIN_DISTINCT_CHARACTERS = 10
|
|
19
|
+
const TOKEN_PREFIX = 'kat_'
|
|
20
|
+
const DEFAULT_EXPIRY_SECONDS = 90 * 24 * 60 * 60
|
|
21
|
+
|
|
22
|
+
// A prefix lets a secret scanner recognise a leaked token; the digest the store keeps covers it.
|
|
23
|
+
function newToken(): string {
|
|
24
|
+
return TOKEN_PREFIX + randomToken()
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// A bearer token as the app lists it; the token itself is shown once, when minted.
|
|
28
|
+
export interface BearerToken {
|
|
29
|
+
id: string
|
|
30
|
+
label: string
|
|
31
|
+
// Null for every scope.
|
|
32
|
+
scopes: string[] | null
|
|
33
|
+
createdAt: Date
|
|
34
|
+
lastUsedAt: Date | null
|
|
35
|
+
expiresAt: Date | null
|
|
36
|
+
expired: boolean
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface TokenOptions<Scope extends string = string> {
|
|
40
|
+
// What the token may reach, from the scopes the app declares; every one when left out.
|
|
41
|
+
scopes?: Scope[] | undefined
|
|
42
|
+
// How long until it stops working, a string such as '30d'; 90 days when left out, never with null.
|
|
43
|
+
maxAge?: Duration | null | undefined
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// The seconds a token lives, undefined for a value that is no positive duration.
|
|
47
|
+
function expirySeconds(maxAge: Duration): number | undefined {
|
|
48
|
+
try {
|
|
49
|
+
return durationSeconds(maxAge, 'maxAge')
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return undefined
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
type TokenProblem = 'label' | 'scope' | 'expiry'
|
|
57
|
+
|
|
58
|
+
export type CreateTokenResult = { ok: true, token: string, id: string } | AuthFailed<ProofFailure | TokenProblem>
|
|
59
|
+
|
|
60
|
+
export type IssueTokenResult = { ok: true, token: string, id: string } | AuthFailed<TokenProblem | 'token' | 'not-found' | 'banned'>
|
|
61
|
+
|
|
62
|
+
function tokenProblem(core: Core, name: string, options: TokenOptions): TokenProblem | undefined {
|
|
63
|
+
if (name.length === 0 || name.length > LABEL_MAX_LENGTH)
|
|
64
|
+
return 'label'
|
|
65
|
+
|
|
66
|
+
if (options.scopes && (options.scopes.length === 0 || options.scopes.some(scope => !core.scopes.has(scope))))
|
|
67
|
+
return 'scope'
|
|
68
|
+
|
|
69
|
+
const maxAge = options.maxAge
|
|
70
|
+
|
|
71
|
+
return maxAge != null && expirySeconds(maxAge) === undefined ? 'expiry' : undefined
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// The seconds a token lives: the default when left out, null for never.
|
|
75
|
+
function lifetime(maxAge: Duration | null | undefined): number | null {
|
|
76
|
+
if (maxAge === undefined)
|
|
77
|
+
return DEFAULT_EXPIRY_SECONDS
|
|
78
|
+
|
|
79
|
+
return maxAge === null ? null : expirySeconds(maxAge)!
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function storeToken(core: Core, userId: string, name: string, options: TokenOptions, token: string): Promise<string> {
|
|
83
|
+
const id = crypto.randomUUID()
|
|
84
|
+
const seconds = lifetime(options.maxAge)
|
|
85
|
+
|
|
86
|
+
await core.store.bearerTokens.create({
|
|
87
|
+
id,
|
|
88
|
+
userId,
|
|
89
|
+
label: name,
|
|
90
|
+
digest: digest(token),
|
|
91
|
+
scopes: options.scopes ? [...new Set(options.scopes)] : null,
|
|
92
|
+
createdAt: new Date(),
|
|
93
|
+
lastUsedAt: null,
|
|
94
|
+
expiresAt: seconds === null ? null : new Date(Date.now() + seconds * 1000),
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
return id
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// A token for a device or an API client of the signed-in user, minted from a session only, never from another token.
|
|
101
|
+
export async function createToken(state: RequestState, proof: Proof, label: string, options: TokenOptions = {}): Promise<CreateTokenResult> {
|
|
102
|
+
const name = plainName(label)
|
|
103
|
+
const problem = tokenProblem(state.core, name, options)
|
|
104
|
+
|
|
105
|
+
if (problem)
|
|
106
|
+
return failed(problem)
|
|
107
|
+
|
|
108
|
+
const proved = await reprove(state, proof)
|
|
109
|
+
|
|
110
|
+
if (!proved.ok)
|
|
111
|
+
return proved
|
|
112
|
+
|
|
113
|
+
if (state.via() !== 'session')
|
|
114
|
+
return failed('signed-out')
|
|
115
|
+
|
|
116
|
+
const token = newToken()
|
|
117
|
+
const id = await storeToken(state.core, proved.record.id, name, options, token)
|
|
118
|
+
|
|
119
|
+
await securityNotice(state, proved.record, 'token-created', name)
|
|
120
|
+
|
|
121
|
+
return { ok: true, token, id }
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// A token for `userId` with no proof, for the app to gate; `token` adopts one it handed out before, 32 to 4096 characters without whitespace, as a bearer header carries.
|
|
125
|
+
export async function issueToken(core: Core, userId: string, label: string, options: TokenOptions & { token?: string | undefined } = {}): Promise<IssueTokenResult> {
|
|
126
|
+
const name = plainName(label)
|
|
127
|
+
const problem = tokenProblem(core, name, options)
|
|
128
|
+
|
|
129
|
+
if (problem)
|
|
130
|
+
return failed(problem)
|
|
131
|
+
|
|
132
|
+
if (options.token !== undefined && (!TOKEN.test(options.token) || new Set(options.token).size < MIN_DISTINCT_CHARACTERS))
|
|
133
|
+
return failed('token')
|
|
134
|
+
|
|
135
|
+
const record = await core.store.users.get(userId)
|
|
136
|
+
|
|
137
|
+
if (!record)
|
|
138
|
+
return failed('not-found')
|
|
139
|
+
|
|
140
|
+
if (banned(record))
|
|
141
|
+
return failed('banned')
|
|
142
|
+
|
|
143
|
+
const token = options.token ?? newToken()
|
|
144
|
+
|
|
145
|
+
return { ok: true, token, id: await storeToken(core, record.id, name, options, token) }
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export async function listTokens(state: RequestState): Promise<BearerToken[]> {
|
|
149
|
+
const record = await state.current()
|
|
150
|
+
|
|
151
|
+
return record && state.via() === 'session' ? (await state.core.store.bearerTokens.listByUser(record.id)).filter(token => !token.oauth).map(publicToken) : []
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export type RevokeTokenResult = { ok: true } | AuthFailed<'signed-out' | 'not-found'>
|
|
155
|
+
|
|
156
|
+
export async function revokeToken(state: RequestState, id: string): Promise<RevokeTokenResult> {
|
|
157
|
+
const record = await state.current()
|
|
158
|
+
|
|
159
|
+
if (!record || state.via() !== 'session')
|
|
160
|
+
return failed('signed-out')
|
|
161
|
+
|
|
162
|
+
return (await state.core.store.bearerTokens.delete(record.id, id)) ? { ok: true } : failed('not-found')
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// The user a bearer token belongs to, as a websocket handshake checks one; an expired token is refused, and so is one bound to a resource unless `url`, the address the request was made to, is under it; without one (null) a bound token is refused.
|
|
166
|
+
export async function tokenUser(core: Core, token: string, url: string | null): Promise<{ record: UserRecord, scopes: string[] | null } | undefined> {
|
|
167
|
+
const { bearerTokens, users } = core.store
|
|
168
|
+
const hash = digest(token)
|
|
169
|
+
// One query for the token and its user when the store has it, else two.
|
|
170
|
+
const joined = bearerTokens.findByDigestWithUser ? await bearerTokens.findByDigestWithUser(hash) : undefined
|
|
171
|
+
const found = bearerTokens.findByDigestWithUser ? joined?.token : await bearerTokens.findByDigest(hash)
|
|
172
|
+
const now = new Date()
|
|
173
|
+
|
|
174
|
+
if (!found || (found.expiresAt !== null && found.expiresAt <= now))
|
|
175
|
+
return undefined
|
|
176
|
+
|
|
177
|
+
const resource = found.oauth?.resource
|
|
178
|
+
|
|
179
|
+
if (resource != null && resource !== '' && (url === null || !underResource(resource, url, siteBase(core))))
|
|
180
|
+
return undefined
|
|
181
|
+
|
|
182
|
+
const record = joined ? joined.user : await users.get(found.userId)
|
|
183
|
+
|
|
184
|
+
if (!record)
|
|
185
|
+
return undefined
|
|
186
|
+
|
|
187
|
+
if (found.lastUsedAt === null || now.getTime() - found.lastUsedAt.getTime() > TOUCH_EVERY_MS) {
|
|
188
|
+
await core.store.bearerTokens.touch(found.id, now)
|
|
189
|
+
|
|
190
|
+
// The account page's "last used" of an approved app is its last call, not its last refresh.
|
|
191
|
+
if (found.oauth)
|
|
192
|
+
await core.store.oauth?.grants.touch(found.userId, found.oauth.clientId, now)
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
return { record, scopes: found.scopes }
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function publicToken(token: BearerTokenRecord): BearerToken {
|
|
199
|
+
return {
|
|
200
|
+
id: token.id,
|
|
201
|
+
label: token.label,
|
|
202
|
+
scopes: token.scopes,
|
|
203
|
+
createdAt: token.createdAt,
|
|
204
|
+
lastUsedAt: token.lastUsedAt,
|
|
205
|
+
expiresAt: token.expiresAt,
|
|
206
|
+
expired: token.expiresAt !== null && token.expiresAt <= new Date(),
|
|
207
|
+
}
|
|
208
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
const BEARER = /^Bearer\s+(\S+)$/i
|
|
2
|
+
|
|
3
|
+
// Whether a request carries an `Authorization: Bearer` token, which no page can add to a cross-site request (a browser sends Basic credentials on its own), read without loading the token code.
|
|
4
|
+
export function bearerRequest(request: Request): boolean {
|
|
5
|
+
return BEARER.test(request.headers.get('authorization') ?? '')
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
// The token itself, if there is one.
|
|
9
|
+
export function bearerToken(request: Request): string | undefined {
|
|
10
|
+
return BEARER.exec(request.headers.get('authorization') ?? '')?.[1]
|
|
11
|
+
}
|
package/src/breached.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { Core } from './core'
|
|
2
|
+
import type { PasswordProblem } from './rules'
|
|
3
|
+
import { createHash } from 'node:crypto'
|
|
4
|
+
import { log } from './log'
|
|
5
|
+
import { passwordProblem } from './rules'
|
|
6
|
+
|
|
7
|
+
const RANGE_URL = 'https://api.pwnedpasswords.com/range/'
|
|
8
|
+
const TIMEOUT_MS = 3000
|
|
9
|
+
|
|
10
|
+
// Whether Have I Been Pwned lists the password, sending only the first five characters of its SHA-1 so the service never learns which one was asked about.
|
|
11
|
+
export async function pwnedPassword(password: string): Promise<boolean> {
|
|
12
|
+
const hash = createHash('sha1').update(password).digest('hex').toUpperCase()
|
|
13
|
+
// Padded with decoy suffixes, so even the answer's size tells nothing of the range.
|
|
14
|
+
const response = await fetch(`${RANGE_URL}${hash.slice(0, 5)}`, { headers: { 'Add-Padding': 'true' }, signal: AbortSignal.timeout(TIMEOUT_MS) })
|
|
15
|
+
|
|
16
|
+
if (!response.ok)
|
|
17
|
+
throw new Error(`${RANGE_URL} answered ${response.status}`)
|
|
18
|
+
|
|
19
|
+
const suffix = hash.slice(5)
|
|
20
|
+
|
|
21
|
+
for (const line of (await response.text()).split('\n')) {
|
|
22
|
+
const [candidate, count] = line.trim().split(':')
|
|
23
|
+
|
|
24
|
+
// A decoy is listed with a count of 0.
|
|
25
|
+
if (candidate === suffix)
|
|
26
|
+
return Number(count) > 0
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
return false
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// The rules' problem with a new password, or `breached` when the app checks for those and the check finds it. A check that fails lets the password through, logged, so an outage never stops anyone registering.
|
|
33
|
+
export async function newPasswordProblem(core: Core, password: string): Promise<PasswordProblem | 'breached' | undefined> {
|
|
34
|
+
const problem = passwordProblem(password, core.rules)
|
|
35
|
+
|
|
36
|
+
if (problem !== undefined || !core.breached)
|
|
37
|
+
return problem
|
|
38
|
+
|
|
39
|
+
try {
|
|
40
|
+
return await core.breached(password) ? 'breached' : undefined
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
log.error('the breached-password check failed, so the password passes', error)
|
|
44
|
+
|
|
45
|
+
return undefined
|
|
46
|
+
}
|
|
47
|
+
}
|
package/src/browser.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { AuthenticationResponseJSON, PublicKeyCredentialCreationOptionsJSON as CreationOptions, RegistrationResponseJSON, PublicKeyCredentialRequestOptionsJSON as RequestOptions } from './webauthn'
|
|
2
|
+
import { ActionError } from 'kay'
|
|
3
|
+
|
|
4
|
+
// The browser half of a passkey, for the islands asking one: the WebAuthn JSON methods are the browser's own, so no library ships to the page, and the options and answers are typed as the server's actions give and take them.
|
|
5
|
+
// What `toJSON()` gives is untyped, so each answer is told by the part only it has and read as the server's type.
|
|
6
|
+
function answerHas(answer: unknown, part: string): boolean {
|
|
7
|
+
return typeof answer === 'object' && answer !== null && 'response' in answer && typeof answer.response === 'object' && answer.response !== null && part in answer.response
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function isAssertion(answer: unknown): answer is AuthenticationResponseJSON {
|
|
11
|
+
return answerHas(answer, 'signature')
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function isAttestation(answer: unknown): answer is RegistrationResponseJSON {
|
|
15
|
+
return answerHas(answer, 'attestationObject')
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// Whether the page's first "keep me signed in" box is checked, undefined when it shows none: read by the sign-in ways that are no form of their own, the passkey and the provider buttons.
|
|
19
|
+
export function rememberChoice(): boolean | undefined {
|
|
20
|
+
return document.querySelector<HTMLInputElement>('input[name="remember"]')?.checked
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// Whether this browser can answer a passkey request.
|
|
24
|
+
export function canAskPasskey(): boolean {
|
|
25
|
+
return typeof PublicKeyCredential !== 'undefined' && 'parseRequestOptionsFromJSON' in PublicKeyCredential
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Whether this browser can make a passkey.
|
|
29
|
+
export function canMakePasskey(): boolean {
|
|
30
|
+
return typeof PublicKeyCredential !== 'undefined' && 'parseCreationOptionsFromJSON' in PublicKeyCredential
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// The answer to what `passkeys.signInOptions()`, `twoFactor.passkeyOptions()` or `passkeys.proofOptions()` gave, for the action calling `passkeys.signIn`, `twoFactor.verifyPasskey` or a proof; null when the person picked none.
|
|
34
|
+
// With `autofill`, the passkeys are offered in the autofill of a field with `autocomplete="username webauthn"` and the call waits until one is picked, or `signal` aborts it.
|
|
35
|
+
export async function askPasskey(options: RequestOptions, { autofill = false, signal }: { autofill?: boolean, signal?: AbortSignal } = {}): Promise<AuthenticationResponseJSON | null> {
|
|
36
|
+
const credential = await navigator.credentials.get({ publicKey: PublicKeyCredential.parseRequestOptionsFromJSON(options), ...autofill && { mediation: 'conditional' }, ...signal && { signal } })
|
|
37
|
+
const answer = credential instanceof PublicKeyCredential ? credential.toJSON() : undefined
|
|
38
|
+
|
|
39
|
+
return answer !== undefined && isAssertion(answer) ? answer : null
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// The answer to what `passkeys.registrationOptions()` gave, for the action calling `passkeys.register`; null when the person made none.
|
|
43
|
+
export async function makePasskey(options: CreationOptions): Promise<RegistrationResponseJSON | null> {
|
|
44
|
+
const credential = await navigator.credentials.create({ publicKey: PublicKeyCredential.parseCreationOptionsFromJSON(options) })
|
|
45
|
+
const answer = credential instanceof PublicKeyCredential ? credential.toJSON() : undefined
|
|
46
|
+
|
|
47
|
+
return answer !== undefined && isAttestation(answer) ? answer : null
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// What to tell the person when a passkey request threw: the message for the code an action refused it with, nothing when they dismissed the browser's prompt, else `failed`.
|
|
51
|
+
export function passkeyFailure(caught: unknown, errors: Record<string, string>, failed: string): string {
|
|
52
|
+
if (caught instanceof ActionError) {
|
|
53
|
+
const code = (caught.data as { error?: string } | undefined)?.error
|
|
54
|
+
|
|
55
|
+
return code !== undefined && Object.hasOwn(errors, code) ? errors[code] ?? failed : failed
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
return caught instanceof DOMException && caught.name === 'NotAllowedError' ? '' : failed
|
|
59
|
+
}
|
package/src/captcha.ts
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import type { Duration, RateStore } from 'kay'
|
|
2
|
+
import type { DEFAULT_LIMITS } from './limits'
|
|
3
|
+
import type { RequestState } from './state'
|
|
4
|
+
import { configError } from 'kay/library'
|
|
5
|
+
import { verifyWork, workChallenge } from 'kay/server'
|
|
6
|
+
import { counted, spend } from './limits'
|
|
7
|
+
import { log } from './log'
|
|
8
|
+
|
|
9
|
+
const TURNSTILE_URL = 'https://challenges.cloudflare.com/turnstile/v0/siteverify'
|
|
10
|
+
const HCAPTCHA_URL = 'https://api.hcaptcha.com/siteverify'
|
|
11
|
+
const TIMEOUT_MS = 5000
|
|
12
|
+
// The documented test secrets of Turnstile (`1x0...AA`, `2x...`, `3x...`) and hCaptcha (all zeros): their answers name a fixed hostname and action of their own, so those are not compared.
|
|
13
|
+
const TEST_SECRET = /^(?:[123]x0+AA|0x0+)$/
|
|
14
|
+
// Doubling the difficulty with each attempt past the threshold stops at 16 times.
|
|
15
|
+
const MOST_DOUBLINGS = 4
|
|
16
|
+
|
|
17
|
+
// The requests a CAPTCHA can guard: each one a bot would repeat.
|
|
18
|
+
export type CaptchaAction = 'register' | 'guest' | 'sign-in' | 'reset' | 'magic-link'
|
|
19
|
+
|
|
20
|
+
// When each request asks for one: `'always'`, a number to ask only once this client made that many of it in its attempt window, or false.
|
|
21
|
+
export type CaptchaRules = Partial<Record<CaptchaAction, 'always' | number | false>>
|
|
22
|
+
|
|
23
|
+
// A third party's check, or kay's proof of work: `proofOfWork()`, the default.
|
|
24
|
+
export type CaptchaOptions = CaptchaCheck | ProofOfWorkCaptcha
|
|
25
|
+
|
|
26
|
+
export interface CaptchaContext {
|
|
27
|
+
hostname?: string | undefined
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface CaptchaCheck {
|
|
31
|
+
// Checks the token the page's widget posted: `turnstile(secret)` and `hcaptcha(secret)` are presets, any function works.
|
|
32
|
+
// `context.hostname` is the site's own, from `url`, for a check to compare with the hostname the provider says the widget ran on.
|
|
33
|
+
verify: (token: string, action: CaptchaAction, context?: CaptchaContext) => boolean | Promise<boolean>
|
|
34
|
+
// Every request asks always by default, a guest sign-in as registering does.
|
|
35
|
+
on?: CaptchaRules | undefined
|
|
36
|
+
// The widget the prebuilt pages show where one is needed: `turnstileWidget(siteKey)` or `hcaptchaWidget(siteKey)`.
|
|
37
|
+
widget?: CaptchaWidget | undefined
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface AuthProofOfWorkOptions {
|
|
41
|
+
// The highest number the browser may hash up to past the threshold, 100,000 by default, doubled with each attempt after up to 16 times.
|
|
42
|
+
difficulty?: number | undefined
|
|
43
|
+
// How long a challenge stays good, an hour by default.
|
|
44
|
+
maxAge?: Duration | undefined
|
|
45
|
+
// Where the solutions already used are kept, this process's memory by default: `sqliteRates(path)` from `kay/server` shares them between processes.
|
|
46
|
+
store?: RateStore | undefined
|
|
47
|
+
// Registering, resets and magic links ask always by default, a password sign-in from the third attempt, a guest sign-in never, as an app often makes one with no form.
|
|
48
|
+
on?: CaptchaRules | undefined
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface ProofOfWorkCaptcha {
|
|
52
|
+
proofOfWork: { difficulty: number, maxAge: Duration, store: RateStore | undefined }
|
|
53
|
+
on: CaptchaRules
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// A provider's widget: its script, the element it fills, carrying the site key, and the field its token posts as.
|
|
57
|
+
export interface CaptchaWidget {
|
|
58
|
+
script: string
|
|
59
|
+
class: string
|
|
60
|
+
siteKey: string
|
|
61
|
+
field: 'cf-turnstile-response' | 'h-captcha-response'
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Each request's client limit, whose attempt count a threshold reads.
|
|
65
|
+
const COUNTED: Record<CaptchaAction, { key: string, limit: keyof typeof DEFAULT_LIMITS }> = {
|
|
66
|
+
'register': { key: 'register', limit: 'register' },
|
|
67
|
+
'guest': { key: 'register', limit: 'register' },
|
|
68
|
+
'sign-in': { key: 'sign-in-client', limit: 'signIn' },
|
|
69
|
+
'reset': { key: 'forgot', limit: 'forgot' },
|
|
70
|
+
'magic-link': { key: 'magicLink', limit: 'magicLink' },
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// A challenge kay's script solves in the browser, with no third party, no widget and no cookie: it costs a bot CPU per request rather than proving a human.
|
|
74
|
+
export function proofOfWork(options: AuthProofOfWorkOptions = {}): ProofOfWorkCaptcha {
|
|
75
|
+
const difficulty = options.difficulty ?? 100_000
|
|
76
|
+
|
|
77
|
+
// kay takes up to 1,000,000,000, which the difficulty reaches doubled to its most.
|
|
78
|
+
if (!Number.isInteger(difficulty) || difficulty < 1 || difficulty * 2 ** MOST_DOUBLINGS > 1e9)
|
|
79
|
+
throw configError('auth', 'proofOfWork', `proofOfWork's difficulty is ${difficulty}; it takes a whole number from 1 to ${1e9 / 2 ** MOST_DOUBLINGS}`)
|
|
80
|
+
|
|
81
|
+
return {
|
|
82
|
+
proofOfWork: { difficulty, maxAge: options.maxAge ?? '1h', store: options.store },
|
|
83
|
+
on: { 'register': 'always', 'guest': false, 'reset': 'always', 'magic-link': 'always', 'sign-in': 3, ...options.on },
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Cloudflare Turnstile's server check; the widget posts its token as `cf-turnstile-response`.
|
|
88
|
+
export function turnstile(secret: string): CaptchaCheck['verify'] {
|
|
89
|
+
return async (token, action, context) => siteverify(TURNSTILE_URL, secret, token, action, context)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function turnstileWidget(siteKey: string): CaptchaWidget {
|
|
93
|
+
return { script: 'https://challenges.cloudflare.com/turnstile/v0/api.js', class: 'cf-turnstile', siteKey, field: 'cf-turnstile-response' }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// hCaptcha's server check; the widget posts its token as `h-captcha-response`.
|
|
97
|
+
export function hcaptcha(secret: string): CaptchaCheck['verify'] {
|
|
98
|
+
return async (token, _action, context) => siteverify(HCAPTCHA_URL, secret, token, undefined, context)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function hcaptchaWidget(siteKey: string): CaptchaWidget {
|
|
102
|
+
return { script: 'https://js.hcaptcha.com/1/api.js', class: 'h-captcha', siteKey, field: 'h-captcha-response' }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// How many attempts past its threshold this client's next `action` comes, undefined when it needs no CAPTCHA.
|
|
106
|
+
async function pastThreshold(state: RequestState, action: CaptchaAction): Promise<number | undefined> {
|
|
107
|
+
const on = state.core.captcha?.on
|
|
108
|
+
const rule = state.core.captcha && (on?.[action] ?? (action === 'guest' ? on?.register : undefined) ?? 'always')
|
|
109
|
+
|
|
110
|
+
if (rule === undefined || rule === false)
|
|
111
|
+
return undefined
|
|
112
|
+
|
|
113
|
+
const count = await counted(state.core.rates, `${COUNTED[action].key}:${state.client}`, state.core.limits[COUNTED[action].limit])
|
|
114
|
+
const threshold = rule === 'always' ? 0 : rule
|
|
115
|
+
|
|
116
|
+
return count >= threshold ? count - threshold : undefined
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Whether the next `action` from this client needs a CAPTCHA token, for the page to show the widget.
|
|
120
|
+
export async function captchaRequired(state: RequestState, action: CaptchaAction): Promise<boolean> {
|
|
121
|
+
return await pastThreshold(state, action) !== undefined
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function workScope(action: CaptchaAction): string {
|
|
125
|
+
return `kayjs-auth:${action}`
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function workDifficulty(captcha: ProofOfWorkCaptcha, past: number): number {
|
|
129
|
+
return captcha.proofOfWork.difficulty * 2 ** Math.min(past, MOST_DOUBLINGS)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// The proof-of-work challenge for this client's next `action`, its field posting the solution as the token; null when none is needed or the CAPTCHA is a third party's.
|
|
133
|
+
export async function captchaChallenge(state: RequestState, action: CaptchaAction): Promise<string | null> {
|
|
134
|
+
const { captcha } = state.core
|
|
135
|
+
|
|
136
|
+
if (!captcha || !('proofOfWork' in captcha))
|
|
137
|
+
return null
|
|
138
|
+
|
|
139
|
+
const past = await pastThreshold(state, action)
|
|
140
|
+
|
|
141
|
+
return past === undefined ? null : workChallenge(workScope(action), { difficulty: workDifficulty(captcha, past), maxAge: captcha.proofOfWork.maxAge })
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// Spends one attempt of `action` against this client and answers what refuses it: `limited` past the limit, `captcha` without a token that checks out where one is needed.
|
|
145
|
+
export async function admit(state: RequestState, action: CaptchaAction, token: string | undefined): Promise<'limited' | 'captcha' | undefined> {
|
|
146
|
+
const { core } = state
|
|
147
|
+
// Read before the attempt counts, so a threshold of 3 lets three through without one.
|
|
148
|
+
const past = await pastThreshold(state, action)
|
|
149
|
+
const { key, limit } = COUNTED[action]
|
|
150
|
+
|
|
151
|
+
if (await spend(core.rates, `${key}:${state.client}`, core.limits[limit]))
|
|
152
|
+
return 'limited'
|
|
153
|
+
|
|
154
|
+
if (past === undefined)
|
|
155
|
+
return undefined
|
|
156
|
+
|
|
157
|
+
const captcha = core.captcha!
|
|
158
|
+
|
|
159
|
+
// A solution to a challenge easier than this attempt asks for is refused, the page then signing a harder one.
|
|
160
|
+
if ('proofOfWork' in captcha)
|
|
161
|
+
return await verifyWork(token, workScope(action), { difficulty: workDifficulty(captcha, past), store: captcha.proofOfWork.store }) === undefined ? undefined : 'captcha'
|
|
162
|
+
|
|
163
|
+
// A widget that never loaded posts nothing, which is no reason to call the provider.
|
|
164
|
+
if (token == null || token === '')
|
|
165
|
+
return 'captcha'
|
|
166
|
+
|
|
167
|
+
try {
|
|
168
|
+
return await captcha.verify(token, action, { hostname: core.url === undefined ? undefined : new URL(core.url).hostname }) ? undefined : 'captcha'
|
|
169
|
+
}
|
|
170
|
+
catch (error) {
|
|
171
|
+
log.error(`checking a CAPTCHA for ${action} failed`, error)
|
|
172
|
+
|
|
173
|
+
return 'captcha'
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// A token minted for another site's widget, or another form, is no proof for this one: the answer's hostname and, where the widget set one, its action must match. An answer without an action is taken, as a widget need not set one.
|
|
178
|
+
async function siteverify(url: string, secret: string, token: string, action: CaptchaAction | undefined, context: CaptchaContext | undefined): Promise<boolean> {
|
|
179
|
+
const response = await fetch(url, { method: 'POST', body: new URLSearchParams({ secret, response: token }), signal: AbortSignal.timeout(TIMEOUT_MS) })
|
|
180
|
+
|
|
181
|
+
if (!response.ok)
|
|
182
|
+
throw new Error(`${url} answered ${response.status}`)
|
|
183
|
+
|
|
184
|
+
const answer = await response.json() as { success?: unknown, hostname?: unknown, action?: unknown }
|
|
185
|
+
|
|
186
|
+
if (answer.success !== true)
|
|
187
|
+
return false
|
|
188
|
+
|
|
189
|
+
if (TEST_SECRET.test(secret))
|
|
190
|
+
return true
|
|
191
|
+
|
|
192
|
+
if (context?.hostname !== undefined && (typeof answer.hostname !== 'string' || answer.hostname.toLowerCase() !== context.hostname.toLowerCase()))
|
|
193
|
+
return false
|
|
194
|
+
|
|
195
|
+
return action === undefined || typeof answer.action !== 'string' || answer.action === '' || answer.action === action
|
|
196
|
+
}
|