@kayjs/auth 0.0.0-stage → 1.104.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +78 -2
- package/llms/admin-and-organizations.md +70 -0
- package/llms/admin-pages.md +30 -0
- package/llms/grouped-methods.md +106 -0
- package/llms/hardening-and-testing.md +108 -0
- package/llms/oauth-passkeys-two-factor.md +111 -0
- package/llms/oauth-providers.md +28 -0
- package/llms/oauth-server-and-tokens.md +76 -0
- package/llms/organization-pages.md +20 -0
- package/llms/passwords-and-mails.md +129 -0
- package/llms/sessions-and-guards.md +51 -0
- package/llms/setup.md +122 -0
- package/llms/signed-in-components.md +59 -0
- package/llms.txt +28 -0
- package/package.json +85 -4
- package/src/access.ts +31 -0
- package/src/account.ts +198 -0
- package/src/add.ts +70 -0
- package/src/address.ts +51 -0
- package/src/admin.ts +361 -0
- package/src/auditWording.ts +153 -0
- package/src/auth.ts +219 -0
- package/src/authorize/clients.ts +160 -0
- package/src/authorize/grants.ts +44 -0
- package/src/authorize/metadata.ts +72 -0
- package/src/authorize/register.ts +38 -0
- package/src/authorize/reply.ts +9 -0
- package/src/authorize/request.ts +253 -0
- package/src/authorize/resource.ts +34 -0
- package/src/authorize/revoke.ts +36 -0
- package/src/authorize/routes.ts +87 -0
- package/src/authorize/token.ts +213 -0
- package/src/authorize/uris.ts +76 -0
- package/src/bearer.ts +208 -0
- package/src/bearerHeader.ts +11 -0
- package/src/breached.ts +47 -0
- package/src/browser.ts +59 -0
- package/src/captcha.ts +196 -0
- package/src/cbor.ts +129 -0
- package/src/components/deletion-banner.kay +20 -0
- package/src/components/impersonation-banner.kay +21 -0
- package/src/components/signed-in.kay +8 -0
- package/src/components/signed-out.kay +6 -0
- package/src/components/user-menu.kay +21 -0
- package/src/context.ts +5 -0
- package/src/core.ts +308 -0
- package/src/createUserCommand.ts +217 -0
- package/src/decide.ts +45 -0
- package/src/deletion.ts +80 -0
- package/src/devTool.ts +104 -0
- package/src/device.ts +37 -0
- package/src/email.ts +594 -0
- package/src/erase.ts +237 -0
- package/src/events.ts +297 -0
- package/src/export.ts +101 -0
- package/src/failure.ts +63 -0
- package/src/forwardAuth.ts +55 -0
- package/src/forwardRoutes.ts +68 -0
- package/src/gate.ts +104 -0
- package/src/guard.ts +22 -0
- package/src/guards.ts +72 -0
- package/src/guesses.ts +99 -0
- package/src/index.ts +46 -0
- package/src/keys.ts +51 -0
- package/src/limits.ts +182 -0
- package/src/load.ts +18 -0
- package/src/locale.ts +15 -0
- package/src/log.ts +4 -0
- package/src/mail.ts +225 -0
- package/src/memoryStore.ts +599 -0
- package/src/messages/fr.ts +357 -0
- package/src/methods/account.ts +80 -0
- package/src/methods/admin.ts +63 -0
- package/src/methods/audit.ts +15 -0
- package/src/methods/email.ts +39 -0
- package/src/methods/magicLink.ts +32 -0
- package/src/methods/oauth.ts +35 -0
- package/src/methods/oauthServer.ts +31 -0
- package/src/methods/organizations.ts +96 -0
- package/src/methods/passkeys.ts +61 -0
- package/src/methods/password.ts +53 -0
- package/src/methods/sessions.ts +18 -0
- package/src/methods/tokens.ts +24 -0
- package/src/methods/twoFactor.ts +62 -0
- package/src/oauth/client.ts +324 -0
- package/src/oauth/flow.ts +350 -0
- package/src/oauth/index.ts +5 -0
- package/src/oauth/pkce.ts +20 -0
- package/src/oauth/providers.ts +490 -0
- package/src/oauth/refresher.ts +177 -0
- package/src/oauth/timeout.ts +2 -0
- package/src/oauth/types.ts +78 -0
- package/src/oauthTest.ts +112 -0
- package/src/organizations.ts +675 -0
- package/src/organizationsCore.ts +60 -0
- package/src/own.ts +313 -0
- package/src/pages/components/captcha.kay +16 -0
- package/src/pages/components/frame.kay +11 -0
- package/src/pages/components/message.kay +8 -0
- package/src/pages/components/panel.kay +12 -0
- package/src/pages/components/passkey-add.kay +48 -0
- package/src/pages/components/passkey-sign-in.kay +34 -0
- package/src/pages/components/passkey-two-factor.kay +33 -0
- package/src/pages/components/proof.kay +15 -0
- package/src/pages/components/provider-buttons.kay +25 -0
- package/src/pages/components/recovery-codes.kay +13 -0
- package/src/pages/components/separator.kay +4 -0
- package/src/pages/english.ts +82 -0
- package/src/pages/forms.ts +185 -0
- package/src/pages/index.ts +361 -0
- package/src/pages/organizationPage.ts +12 -0
- package/src/pages/routes/account/_guard.ts +15 -0
- package/src/pages/routes/account/_layout.kay +37 -0
- package/src/pages/routes/account/clients.kay +33 -0
- package/src/pages/routes/account/connections.kay +57 -0
- package/src/pages/routes/account/data.kay +106 -0
- package/src/pages/routes/account/index.kay +109 -0
- package/src/pages/routes/account/organizations/[org].kay +188 -0
- package/src/pages/routes/account/organizations/_guard.ts +8 -0
- package/src/pages/routes/account/organizations/index.kay +86 -0
- package/src/pages/routes/account/security.kay +164 -0
- package/src/pages/routes/account/sessions.kay +51 -0
- package/src/pages/routes/account/tokens.kay +84 -0
- package/src/pages/routes/admin/_layout.kay +43 -0
- package/src/pages/routes/admin/audit.kay +43 -0
- package/src/pages/routes/admin/index.kay +60 -0
- package/src/pages/routes/admin/users/[id].kay +181 -0
- package/src/pages/routes/confirm-email.kay +39 -0
- package/src/pages/routes/invitation.kay +104 -0
- package/src/pages/routes/magic-link.kay +42 -0
- package/src/pages/routes/oauth/authorize.kay +80 -0
- package/src/pages/routes/register.kay +83 -0
- package/src/pages/routes/reset-password.kay +73 -0
- package/src/pages/routes/sign-in.kay +128 -0
- package/src/pages/routes/two-factor.kay +61 -0
- package/src/pages/routes/verify-email.kay +83 -0
- package/src/passkeys.ts +373 -0
- package/src/password.ts +316 -0
- package/src/payloads.ts +22 -0
- package/src/pg.ts +705 -0
- package/src/profile.ts +43 -0
- package/src/proof.ts +110 -0
- package/src/prune.ts +123 -0
- package/src/rates.ts +82 -0
- package/src/request.ts +712 -0
- package/src/requiredTwoFactor.ts +71 -0
- package/src/requirement.ts +23 -0
- package/src/roles.ts +18 -0
- package/src/routes.ts +202 -0
- package/src/rules-check.ts +37 -0
- package/src/rules.ts +108 -0
- package/src/securityNotice.ts +45 -0
- package/src/sessions.ts +184 -0
- package/src/setup.ts +417 -0
- package/src/signInOptions.ts +9 -0
- package/src/state.ts +34 -0
- package/src/store.ts +410 -0
- package/src/storeHelpers.ts +23 -0
- package/src/test.ts +46 -0
- package/src/testCookies.ts +9 -0
- package/src/testHelpers.ts +58 -0
- package/src/testing.ts +113 -0
- package/src/text.ts +6 -0
- package/src/totp.ts +120 -0
- package/src/twoFactor.ts +200 -0
- package/src/types.ts +23 -0
- package/src/userData.ts +47 -0
- package/src/viewer-layout/_layout.kay +11 -0
- package/src/viewer.ts +116 -0
- package/src/wayIn.ts +40 -0
- package/src/webauthn.ts +375 -0
- package/src/wsAuth.ts +53 -0
- package/types/access.d.ts +12 -0
- package/types/access.d.ts.map +1 -0
- package/types/account.d.ts +32 -0
- package/types/account.d.ts.map +1 -0
- package/types/add.d.ts +29 -0
- package/types/add.d.ts.map +1 -0
- package/types/address.d.ts +2 -0
- package/types/address.d.ts.map +1 -0
- package/types/admin.d.ts +84 -0
- package/types/admin.d.ts.map +1 -0
- package/types/auditWording.d.ts +9 -0
- package/types/auditWording.d.ts.map +1 -0
- package/types/auth.d.ts +3475 -0
- package/types/auth.d.ts.map +1 -0
- package/types/authorize/clients.d.ts +15 -0
- package/types/authorize/clients.d.ts.map +1 -0
- package/types/authorize/grants.d.ts +15 -0
- package/types/authorize/grants.d.ts.map +1 -0
- package/types/authorize/metadata.d.ts +20 -0
- package/types/authorize/metadata.d.ts.map +1 -0
- package/types/authorize/register.d.ts +4 -0
- package/types/authorize/register.d.ts.map +1 -0
- package/types/authorize/reply.d.ts +6 -0
- package/types/authorize/reply.d.ts.map +1 -0
- package/types/authorize/request.d.ts +48 -0
- package/types/authorize/request.d.ts.map +1 -0
- package/types/authorize/resource.d.ts +4 -0
- package/types/authorize/resource.d.ts.map +1 -0
- package/types/authorize/revoke.d.ts +4 -0
- package/types/authorize/revoke.d.ts.map +1 -0
- package/types/authorize/routes.d.ts +5 -0
- package/types/authorize/routes.d.ts.map +1 -0
- package/types/authorize/token.d.ts +7 -0
- package/types/authorize/token.d.ts.map +1 -0
- package/types/authorize/uris.d.ts +5 -0
- package/types/authorize/uris.d.ts.map +1 -0
- package/types/bearer.d.ts +45 -0
- package/types/bearer.d.ts.map +1 -0
- package/types/bearerHeader.d.ts +3 -0
- package/types/bearerHeader.d.ts.map +1 -0
- package/types/breached.d.ts +5 -0
- package/types/breached.d.ts.map +1 -0
- package/types/browser.d.ts +11 -0
- package/types/browser.d.ts.map +1 -0
- package/types/captcha.d.ts +42 -0
- package/types/captcha.d.ts.map +1 -0
- package/types/cbor.d.ts +4 -0
- package/types/cbor.d.ts.map +1 -0
- package/types/context.d.ts +3 -0
- package/types/context.d.ts.map +1 -0
- package/types/core.d.ts +180 -0
- package/types/core.d.ts.map +1 -0
- package/types/createUserCommand.d.ts +11 -0
- package/types/createUserCommand.d.ts.map +1 -0
- package/types/decide.d.ts +12 -0
- package/types/decide.d.ts.map +1 -0
- package/types/deletion.d.ts +17 -0
- package/types/deletion.d.ts.map +1 -0
- package/types/devTool.d.ts +3 -0
- package/types/devTool.d.ts.map +1 -0
- package/types/device.d.ts +7 -0
- package/types/device.d.ts.map +1 -0
- package/types/email.d.ts +73 -0
- package/types/email.d.ts.map +1 -0
- package/types/erase.d.ts +31 -0
- package/types/erase.d.ts.map +1 -0
- package/types/events.d.ts +139 -0
- package/types/events.d.ts.map +1 -0
- package/types/export.d.ts +54 -0
- package/types/export.d.ts.map +1 -0
- package/types/failure.d.ts +19 -0
- package/types/failure.d.ts.map +1 -0
- package/types/forwardAuth.d.ts +12 -0
- package/types/forwardAuth.d.ts.map +1 -0
- package/types/forwardRoutes.d.ts +11 -0
- package/types/forwardRoutes.d.ts.map +1 -0
- package/types/gate.d.ts +31 -0
- package/types/gate.d.ts.map +1 -0
- package/types/guard.d.ts +10 -0
- package/types/guard.d.ts.map +1 -0
- package/types/guards.d.ts +37 -0
- package/types/guards.d.ts.map +1 -0
- package/types/guesses.d.ts +18 -0
- package/types/guesses.d.ts.map +1 -0
- package/types/index.d.ts +47 -0
- package/types/index.d.ts.map +1 -0
- package/types/keys.d.ts +11 -0
- package/types/keys.d.ts.map +1 -0
- package/types/limits.d.ts +133 -0
- package/types/limits.d.ts.map +1 -0
- package/types/load.d.ts +18 -0
- package/types/load.d.ts.map +1 -0
- package/types/locale.d.ts +4 -0
- package/types/locale.d.ts.map +1 -0
- package/types/log.d.ts +2 -0
- package/types/log.d.ts.map +1 -0
- package/types/mail.d.ts +51 -0
- package/types/mail.d.ts.map +1 -0
- package/types/memoryStore.d.ts +3 -0
- package/types/memoryStore.d.ts.map +1 -0
- package/types/messages/fr.d.ts +409 -0
- package/types/messages/fr.d.ts.map +1 -0
- package/types/methods/account.d.ts +24 -0
- package/types/methods/account.d.ts.map +1 -0
- package/types/methods/admin.d.ts +30 -0
- package/types/methods/admin.d.ts.map +1 -0
- package/types/methods/audit.d.ts +11 -0
- package/types/methods/audit.d.ts.map +1 -0
- package/types/methods/email.d.ts +14 -0
- package/types/methods/email.d.ts.map +1 -0
- package/types/methods/magicLink.d.ts +12 -0
- package/types/methods/magicLink.d.ts.map +1 -0
- package/types/methods/oauth.d.ts +16 -0
- package/types/methods/oauth.d.ts.map +1 -0
- package/types/methods/oauthServer.d.ts +13 -0
- package/types/methods/oauthServer.d.ts.map +1 -0
- package/types/methods/organizations.d.ts +30 -0
- package/types/methods/organizations.d.ts.map +1 -0
- package/types/methods/passkeys.d.ts +19 -0
- package/types/methods/passkeys.d.ts.map +1 -0
- package/types/methods/password.d.ts +17 -0
- package/types/methods/password.d.ts.map +1 -0
- package/types/methods/sessions.d.ts +9 -0
- package/types/methods/sessions.d.ts.map +1 -0
- package/types/methods/tokens.d.ts +11 -0
- package/types/methods/tokens.d.ts.map +1 -0
- package/types/methods/twoFactor.d.ts +20 -0
- package/types/methods/twoFactor.d.ts.map +1 -0
- package/types/oauth/client.d.ts +39 -0
- package/types/oauth/client.d.ts.map +1 -0
- package/types/oauth/flow.d.ts +38 -0
- package/types/oauth/flow.d.ts.map +1 -0
- package/types/oauth/index.d.ts +6 -0
- package/types/oauth/index.d.ts.map +1 -0
- package/types/oauth/pkce.d.ts +10 -0
- package/types/oauth/pkce.d.ts.map +1 -0
- package/types/oauth/providers.d.ts +100 -0
- package/types/oauth/providers.d.ts.map +1 -0
- package/types/oauth/refresher.d.ts +55 -0
- package/types/oauth/refresher.d.ts.map +1 -0
- package/types/oauth/timeout.d.ts +2 -0
- package/types/oauth/timeout.d.ts.map +1 -0
- package/types/oauth/types.d.ts +75 -0
- package/types/oauth/types.d.ts.map +1 -0
- package/types/oauthTest.d.ts +23 -0
- package/types/oauthTest.d.ts.map +1 -0
- package/types/organizations.d.ts +111 -0
- package/types/organizations.d.ts.map +1 -0
- package/types/organizationsCore.d.ts +29 -0
- package/types/organizationsCore.d.ts.map +1 -0
- package/types/own.d.ts +55 -0
- package/types/own.d.ts.map +1 -0
- package/types/pages/english.d.ts +80 -0
- package/types/pages/english.d.ts.map +1 -0
- package/types/pages/forms.d.ts +204 -0
- package/types/pages/forms.d.ts.map +1 -0
- package/types/pages/index.d.ts +166 -0
- package/types/pages/index.d.ts.map +1 -0
- package/types/pages/organizationPage.d.ts +7 -0
- package/types/pages/organizationPage.d.ts.map +1 -0
- package/types/pages/routes/account/_guard.d.ts +3 -0
- package/types/pages/routes/account/_guard.d.ts.map +1 -0
- package/types/pages/routes/account/organizations/_guard.d.ts +3 -0
- package/types/pages/routes/account/organizations/_guard.d.ts.map +1 -0
- package/types/passkeys.d.ts +61 -0
- package/types/passkeys.d.ts.map +1 -0
- package/types/password.d.ts +49 -0
- package/types/password.d.ts.map +1 -0
- package/types/payloads.d.ts +4 -0
- package/types/payloads.d.ts.map +1 -0
- package/types/pg.d.ts +303 -0
- package/types/pg.d.ts.map +1 -0
- package/types/profile.d.ts +11 -0
- package/types/profile.d.ts.map +1 -0
- package/types/proof.d.ts +33 -0
- package/types/proof.d.ts.map +1 -0
- package/types/prune.d.ts +5 -0
- package/types/prune.d.ts.map +1 -0
- package/types/rates.d.ts +15 -0
- package/types/rates.d.ts.map +1 -0
- package/types/request.d.ts +119 -0
- package/types/request.d.ts.map +1 -0
- package/types/requiredTwoFactor.d.ts +16 -0
- package/types/requiredTwoFactor.d.ts.map +1 -0
- package/types/requirement.d.ts +4 -0
- package/types/requirement.d.ts.map +1 -0
- package/types/roles.d.ts +9 -0
- package/types/roles.d.ts.map +1 -0
- package/types/routes.d.ts +31 -0
- package/types/routes.d.ts.map +1 -0
- package/types/rules-check.d.ts +3 -0
- package/types/rules-check.d.ts.map +1 -0
- package/types/rules.d.ts +38 -0
- package/types/rules.d.ts.map +1 -0
- package/types/securityNotice.d.ts +7 -0
- package/types/securityNotice.d.ts.map +1 -0
- package/types/sessions.d.ts +32 -0
- package/types/sessions.d.ts.map +1 -0
- package/types/setup.d.ts +18 -0
- package/types/setup.d.ts.map +1 -0
- package/types/signInOptions.d.ts +6 -0
- package/types/signInOptions.d.ts.map +1 -0
- package/types/state.d.ts +25 -0
- package/types/state.d.ts.map +1 -0
- package/types/store.d.ts +295 -0
- package/types/store.d.ts.map +1 -0
- package/types/storeHelpers.d.ts +4 -0
- package/types/storeHelpers.d.ts.map +1 -0
- package/types/test.d.ts +21 -0
- package/types/test.d.ts.map +1 -0
- package/types/testCookies.d.ts +3 -0
- package/types/testCookies.d.ts.map +1 -0
- package/types/testHelpers.d.ts +34 -0
- package/types/testHelpers.d.ts.map +1 -0
- package/types/testing.d.ts +12 -0
- package/types/testing.d.ts.map +1 -0
- package/types/text.d.ts +2 -0
- package/types/text.d.ts.map +1 -0
- package/types/totp.d.ts +12 -0
- package/types/totp.d.ts.map +1 -0
- package/types/twoFactor.d.ts +41 -0
- package/types/twoFactor.d.ts.map +1 -0
- package/types/types.d.ts +17 -0
- package/types/types.d.ts.map +1 -0
- package/types/userData.d.ts +9 -0
- package/types/userData.d.ts.map +1 -0
- package/types/viewer.d.ts +23 -0
- package/types/viewer.d.ts.map +1 -0
- package/types/wayIn.d.ts +12 -0
- package/types/wayIn.d.ts.map +1 -0
- package/types/webauthn.d.ts +111 -0
- package/types/webauthn.d.ts.map +1 -0
- package/types/wsAuth.d.ts +14 -0
- package/types/wsAuth.d.ts.map +1 -0
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import type { AcceptResult, CreateOrganizationResult, DeleteOrganizationResult, Invitation, InviteResult, ListInvitationsResult, ListMembersResult, MemberResult, Membership, RejectInvitationResult, RevokeInvitationResult, UpdateOrganizationResult } from '../organizations'
|
|
2
|
+
import type { RequestState } from '../state'
|
|
3
|
+
import { failed } from '../failure'
|
|
4
|
+
import { load } from '../load'
|
|
5
|
+
|
|
6
|
+
// `auth.organizations`: the teams or workspaces of the `organizations` option, each named by `ref`, its id or slug.
|
|
7
|
+
export class OrganizationMethods<OrgRole extends string = string> {
|
|
8
|
+
constructor(private readonly state: RequestState) {}
|
|
9
|
+
|
|
10
|
+
// A new organization, the signed-in user its owner. `slug`, lowercase letters, digits and dashes, names it in URLs.
|
|
11
|
+
async create(input: { name: string, slug?: string | null | undefined }): Promise<CreateOrganizationResult<OrgRole>> {
|
|
12
|
+
return (await load.organizations()).createOrganization(this.state, input) as Promise<CreateOrganizationResult<OrgRole>>
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// The organizations the signed-in user belongs to, with their roles in each.
|
|
16
|
+
async list(): Promise<Membership<OrgRole>[]> {
|
|
17
|
+
return (await load.organizations()).listMemberships(this.state) as Promise<Membership<OrgRole>[]>
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// The organization `ref` names, with the user's roles there; null unless they are a member.
|
|
21
|
+
async get(ref: string): Promise<Membership<OrgRole> | null> {
|
|
22
|
+
return (await load.organizations()).getMembership(this.state, ref) as Promise<Membership<OrgRole> | null>
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Whether the user is a member of the organization `ref` names, holding `role` there when given.
|
|
26
|
+
async isMember(ref: string, role?: OrgRole): Promise<boolean> {
|
|
27
|
+
const record = await this.state.current()
|
|
28
|
+
|
|
29
|
+
return record !== null && (await load.organizations()).holdsInOrganization(this.state.core, record.id, ref, role)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Renames it, or changes or clears its slug: for members holding `manage`.
|
|
33
|
+
async update(ref: string, patch: { name?: string | undefined, slug?: string | null | undefined }): Promise<UpdateOrganizationResult> {
|
|
34
|
+
return (await load.organizations()).updateOrganization(this.state, ref, patch)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// For members holding `owner`.
|
|
38
|
+
async delete(ref: string): Promise<DeleteOrganizationResult> {
|
|
39
|
+
return (await load.organizations()).deleteOrganization(this.state, ref)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Every member, oldest first, for any member to see.
|
|
43
|
+
async members(ref: string): Promise<ListMembersResult<OrgRole>> {
|
|
44
|
+
return (await load.organizations()).listMembers(this.state, ref) as Promise<ListMembersResult<OrgRole>>
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Replaces a member's roles: for members holding `manage`, giving only roles they hold, to a member holding none above theirs.
|
|
48
|
+
async setMemberRoles(ref: string, userId: string, roles: OrgRole[]): Promise<MemberResult> {
|
|
49
|
+
return (await load.organizations()).setMemberRoles(this.state, ref, userId, roles)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// For members holding `manage`, of a member holding no role above theirs.
|
|
53
|
+
async removeMember(ref: string, userId: string): Promise<MemberResult> {
|
|
54
|
+
return (await load.organizations()).removeMember(this.state, ref, userId)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async leave(ref: string): Promise<MemberResult> {
|
|
58
|
+
const record = await this.state.current()
|
|
59
|
+
|
|
60
|
+
return record ? (await load.organizations()).removeMember(this.state, ref, record.id) : failed('signed-out')
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Mails `email` a link to the `invitationPage`, else the prebuilt pages' invitation page, giving `roles` (`defaultRoles` when none) once accepted: for members holding `manage` and every role it gives.
|
|
64
|
+
async invite(ref: string, email: string, roles?: OrgRole[]): Promise<InviteResult<OrgRole>> {
|
|
65
|
+
return (await load.organizations()).invite(this.state, ref, email, roles) as Promise<InviteResult<OrgRole>>
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// The organization's open invitations, for members holding `manage`.
|
|
69
|
+
async invitations(ref: string): Promise<ListInvitationsResult<OrgRole>> {
|
|
70
|
+
return (await load.organizations()).listInvitations(this.state, ref) as Promise<ListInvitationsResult<OrgRole>>
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async revokeInvitation(ref: string, invitationId: string): Promise<RevokeInvitationResult> {
|
|
74
|
+
return (await load.organizations()).revokeInvitation(this.state, ref, invitationId)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// The invitations open to the signed-in user's verified address.
|
|
78
|
+
async myInvitations(): Promise<Invitation<OrgRole>[]> {
|
|
79
|
+
return (await load.organizations()).myInvitations(this.state) as Promise<Invitation<OrgRole>[]>
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// What the invitation link's page shows; null once revoked, accepted or expired.
|
|
83
|
+
async invitation(invitationId: string): Promise<Invitation<OrgRole> | null> {
|
|
84
|
+
return (await load.organizations()).getInvitation(this.state, invitationId) as Promise<Invitation<OrgRole> | null>
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// For an account verified at the invited address only.
|
|
88
|
+
async acceptInvitation(invitationId: string): Promise<AcceptResult<OrgRole>> {
|
|
89
|
+
return (await load.organizations()).acceptInvitation(this.state, invitationId) as Promise<AcceptResult<OrgRole>>
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Turns down an invitation open to the user; `not-found` for any other.
|
|
93
|
+
async rejectInvitation(invitationId: string): Promise<RejectInvitationResult> {
|
|
94
|
+
return (await load.organizations()).declineInvitation(this.state, invitationId)
|
|
95
|
+
}
|
|
96
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { Off } from '../core'
|
|
2
|
+
import type { Passkey, PasskeyOptionsResult, PasskeySignInResult, RegisterPasskeyResult, RenamePasskeyResult, RevokePasskeyResult } from '../passkeys'
|
|
3
|
+
import type { Proof, ProofFailure } from '../proof'
|
|
4
|
+
import type { SignInOptions } from '../signInOptions'
|
|
5
|
+
import type { RequestState } from '../state'
|
|
6
|
+
import type { AuthenticationResponseJSON, PublicKeyCredentialCreationOptionsJSON, PublicKeyCredentialRequestOptionsJSON, RegistrationResponseJSON } from '../webauthn'
|
|
7
|
+
import { configError } from 'kay/library'
|
|
8
|
+
import { OFF } from '../core'
|
|
9
|
+
import { load } from '../load'
|
|
10
|
+
import { chooseRemember } from '../sessions'
|
|
11
|
+
|
|
12
|
+
// `auth.passkeys`: making passkeys, signing in and re-proving with one; making one and signing in answer `off` with `passkeys: false`.
|
|
13
|
+
export class PasskeyMethods {
|
|
14
|
+
constructor(private readonly state: RequestState) {}
|
|
15
|
+
|
|
16
|
+
// The options for `makePasskey` of `@kayjs/auth/browser`, to make a passkey for the signed-in user once `proof` re-proves them, the second factor when it is on.
|
|
17
|
+
async registrationOptions(proof: Proof): Promise<PasskeyOptionsResult<PublicKeyCredentialCreationOptionsJSON, ProofFailure | 'off'>> {
|
|
18
|
+
return !this.state.core.switches.passkeys ? OFF : (await load.passkeys()).passkeyRegistrationOptions(this.state, proof)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// Keeps the passkey `makePasskey` made, under `name` or the browser and system it was made on.
|
|
22
|
+
async register(response: RegistrationResponseJSON, name?: string): Promise<RegisterPasskeyResult | Off> {
|
|
23
|
+
return !this.state.core.switches.passkeys ? OFF : (await load.passkeys()).registerPasskey(this.state, response, name)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async list(): Promise<Passkey[]> {
|
|
27
|
+
return (await load.passkeys()).listPasskeys(this.state)
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Renames one of the signed-in user's passkeys; refused with `not-found` for one that is not theirs and `invalid-name` for a blank name.
|
|
31
|
+
async rename(id: string, name: string): Promise<RenamePasskeyResult> {
|
|
32
|
+
return (await load.passkeys()).renamePasskey(this.state, id, name)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async revoke(id: string, proof: Proof): Promise<RevokePasskeyResult> {
|
|
36
|
+
return (await load.passkeys()).removePasskey(this.state, id, proof)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// The options for `askPasskey` of `@kayjs/auth/browser`, naming no account; with its `autofill` the browser offers the passkeys in the sign-in field's autofill.
|
|
40
|
+
async signInOptions(): Promise<PublicKeyCredentialRequestOptionsJSON> {
|
|
41
|
+
if (!this.state.core.switches.passkeys)
|
|
42
|
+
throw configError('auth', 'passkeys', 'passkeys are switched off: `passkeys: false` in the options of authCore or auth()')
|
|
43
|
+
|
|
44
|
+
return (await load.passkeys()).passkeySignInOptions(this.state)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Signs in with the passkey that answered `signInOptions`, with no second factor after it.
|
|
48
|
+
async signIn(response: AuthenticationResponseJSON, options: Pick<SignInOptions, 'redirect' | 'remember'> = {}): Promise<PasskeySignInResult | Off> {
|
|
49
|
+
if (!this.state.core.switches.passkeys)
|
|
50
|
+
return OFF
|
|
51
|
+
|
|
52
|
+
await chooseRemember(this.state, options.remember)
|
|
53
|
+
|
|
54
|
+
return (await load.passkeys()).signInWithPasskey(this.state, response, options.redirect, this.state.establish)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// The options for re-proving with a passkey, its answer then passed as `{ passkey }` wherever a proof is asked.
|
|
58
|
+
async proofOptions(): Promise<PasskeyOptionsResult<PublicKeyCredentialRequestOptionsJSON>> {
|
|
59
|
+
return !this.state.core.switches.passkeys ? OFF : (await load.passkeys()).passkeyProofOptions(this.state)
|
|
60
|
+
}
|
|
61
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { ChangePasswordResult } from '../account'
|
|
2
|
+
import type { Off } from '../core'
|
|
3
|
+
import type { MailRequestResult, ResetPasswordResult } from '../email'
|
|
4
|
+
import type { PasswordSignInInput, PasswordSignInResult, RegisterInput, RegisterResult } from '../password'
|
|
5
|
+
import type { Proof } from '../proof'
|
|
6
|
+
import type { SignInOptions } from '../signInOptions'
|
|
7
|
+
import type { RequestState } from '../state'
|
|
8
|
+
import { OFF } from '../core'
|
|
9
|
+
import { load } from '../load'
|
|
10
|
+
import { chooseRemember } from '../sessions'
|
|
11
|
+
|
|
12
|
+
// `auth.password`: registering, signing in, resets and changes; each answers `off` with `password: false`.
|
|
13
|
+
export class PasswordMethods {
|
|
14
|
+
constructor(private readonly state: RequestState) {}
|
|
15
|
+
|
|
16
|
+
// A new user with an email and a password, signed in on this session; field errors come back as codes. With `redirect`, the mail verifying the address leads on to that page.
|
|
17
|
+
async register(input: RegisterInput, options?: Pick<SignInOptions, 'remember' | 'captcha' | 'redirect'>): Promise<RegisterResult | Off> {
|
|
18
|
+
if (!this.state.core.switches.password)
|
|
19
|
+
return OFF
|
|
20
|
+
|
|
21
|
+
await chooseRemember(this.state, options?.remember)
|
|
22
|
+
|
|
23
|
+
return (await load.password()).register(this.state, input, options)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Signs in with an email or a username and a password; a wrong password and an unknown account answer alike.
|
|
27
|
+
async signIn(input: PasswordSignInInput, options?: SignInOptions): Promise<PasswordSignInResult | Off> {
|
|
28
|
+
if (!this.state.core.switches.password)
|
|
29
|
+
return OFF
|
|
30
|
+
|
|
31
|
+
await chooseRemember(this.state, options?.remember)
|
|
32
|
+
|
|
33
|
+
return (await load.password()).signInWithPassword(this.state, input, options ?? {})
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Mails a reset link to that address when an account has it; answers alike when none does. The reset signs in to `redirect` when given.
|
|
37
|
+
async requestReset(email: string, options: Pick<SignInOptions, 'captcha' | 'redirect'> = {}): Promise<MailRequestResult | Off> {
|
|
38
|
+
if (!this.state.core.switches.password)
|
|
39
|
+
return OFF
|
|
40
|
+
|
|
41
|
+
return (await load.email()).requestPasswordReset(this.state, email, options.captcha, options.redirect)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Spends a reset link's token on a new password, signing the user out everywhere else and in here.
|
|
45
|
+
async reset(token: string, password: string): Promise<ResetPasswordResult | Off> {
|
|
46
|
+
return !this.state.core.switches.password ? OFF : (await load.email()).resetPassword(this.state, token, password)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Sets the signed-in user's password, or a first one, and ends their other sessions.
|
|
50
|
+
async change(proof: Proof, password: string): Promise<ChangePasswordResult | Off> {
|
|
51
|
+
return !this.state.core.switches.password ? OFF : (await load.account()).changePassword(this.state, proof, password)
|
|
52
|
+
}
|
|
53
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { RevokeSessionResult, UserSession } from '../sessions'
|
|
2
|
+
import type { RequestState } from '../state'
|
|
3
|
+
import { listSessions, revokeSession } from '../sessions'
|
|
4
|
+
|
|
5
|
+
// `auth.sessions`: where the signed-in user is signed in.
|
|
6
|
+
export class SessionMethods {
|
|
7
|
+
constructor(private readonly state: RequestState) {}
|
|
8
|
+
|
|
9
|
+
// Where the signed-in user is signed in, this browser marked `current`; empty for a bearer token.
|
|
10
|
+
async list(): Promise<UserSession[]> {
|
|
11
|
+
return listSessions(this.state)
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// Ends one of the signed-in user's sessions, effective on its next request; ending this one signs out. Refused with `not-found` when they have none with that id, and `signed-out` through a bearer token.
|
|
15
|
+
async revoke(id: string): Promise<RevokeSessionResult> {
|
|
16
|
+
return revokeSession(this.state, id, this.state.signOut)
|
|
17
|
+
}
|
|
18
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { BearerToken, CreateTokenResult, RevokeTokenResult, TokenOptions } from '../bearer'
|
|
2
|
+
import type { Proof } from '../proof'
|
|
3
|
+
import type { RequestState } from '../state'
|
|
4
|
+
import { load } from '../load'
|
|
5
|
+
|
|
6
|
+
// `auth.tokens`: the signed-in user's bearer tokens, for their devices and API clients.
|
|
7
|
+
export class TokenMethods<Scope extends string = string> {
|
|
8
|
+
constructor(private readonly state: RequestState) {}
|
|
9
|
+
|
|
10
|
+
// A bearer token for a device or an API client of the signed-in user, shown this once; minted from a session only, never from another token.
|
|
11
|
+
async create(proof: Proof, label: string, options: TokenOptions<Scope> = {}): Promise<CreateTokenResult> {
|
|
12
|
+
return (await load.bearer()).createToken(this.state, proof, label, options)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// The signed-in user's bearer tokens, without the tokens themselves.
|
|
16
|
+
async list(): Promise<BearerToken[]> {
|
|
17
|
+
return (await load.bearer()).listTokens(this.state)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Revokes one of the signed-in user's bearer tokens, from a browser session only: `signed-out` through a token, `not-found` for one that is not theirs.
|
|
21
|
+
async revoke(id: string): Promise<RevokeTokenResult> {
|
|
22
|
+
return (await load.bearer()).revokeToken(this.state, id)
|
|
23
|
+
}
|
|
24
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { Off } from '../core'
|
|
2
|
+
import type { PasskeyOptionsResult } from '../passkeys'
|
|
3
|
+
import type { Proof } from '../proof'
|
|
4
|
+
import type { RequestState } from '../state'
|
|
5
|
+
import type { DisableTwoFactorResult, EnableTwoFactorResult, RecoveryCodesResult, SetUpTwoFactorResult, TwoFactorResult } from '../twoFactor'
|
|
6
|
+
import type { AuthenticationResponseJSON, PublicKeyCredentialRequestOptionsJSON } from '../webauthn'
|
|
7
|
+
import { OFF } from '../core'
|
|
8
|
+
import { load } from '../load'
|
|
9
|
+
import { challenged } from '../proof'
|
|
10
|
+
|
|
11
|
+
// `auth.twoFactor`: the second factor of a sign-in, and setting up an authenticator app; setting up answers `off` with `twoFactor: false`, a passkey answer with `passkeys: false`.
|
|
12
|
+
export class TwoFactorMethods {
|
|
13
|
+
constructor(private readonly state: RequestState) {}
|
|
14
|
+
|
|
15
|
+
// Whether this session holds a sign-in waiting for its second factor, for the page that asks for it.
|
|
16
|
+
async pending(): Promise<boolean> {
|
|
17
|
+
return challenged(this.state)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Finishes a sign-in waiting for its second factor with an authenticator code or a recovery code.
|
|
21
|
+
async verify(code: string): Promise<TwoFactorResult> {
|
|
22
|
+
return (await load.twoFactor()).verifyTwoFactor(this.state, code, this.state.establish)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// A secret for the signed-in user's authenticator, as text and as a QR code; the second factor turns on once `enable` gets a code from it.
|
|
26
|
+
async setUp(proof: Proof): Promise<SetUpTwoFactorResult | Off> {
|
|
27
|
+
return !this.state.core.switches.twoFactor ? OFF : (await load.twoFactor()).setUpTwoFactor(this.state, proof)
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Turns the second factor on with a code from the authenticator just set up; answers the recovery codes, to show this once.
|
|
31
|
+
async enable(code: string): Promise<EnableTwoFactorResult | Off> {
|
|
32
|
+
return !this.state.core.switches.twoFactor ? OFF : (await load.twoFactor()).enableTwoFactor(this.state, code)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async disable(proof: Proof): Promise<DisableTwoFactorResult> {
|
|
36
|
+
return (await load.twoFactor()).disableTwoFactor(this.state, proof)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// A new set of recovery codes, the old ones void.
|
|
40
|
+
async regenerateRecoveryCodes(proof: Proof): Promise<RecoveryCodesResult> {
|
|
41
|
+
return (await load.twoFactor()).regenerateRecoveryCodes(this.state, proof)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// How many unused recovery codes the signed-in user has, to warn when few are left.
|
|
45
|
+
async recoveryCodesLeft(): Promise<number> {
|
|
46
|
+
const record = await this.state.current()
|
|
47
|
+
|
|
48
|
+
return record ? this.state.core.store.recoveryCodes.count(record.id) : 0
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// The options for answering a pending sign-in's second factor with a passkey; `none` when the user has none.
|
|
52
|
+
async passkeyOptions(): Promise<PasskeyOptionsResult<PublicKeyCredentialRequestOptionsJSON>> {
|
|
53
|
+
return !this.state.core.switches.passkeys ? OFF : (await load.passkeys()).twoFactorPasskeyOptions(this.state)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async verifyPasskey(response: AuthenticationResponseJSON): Promise<TwoFactorResult | Off> {
|
|
57
|
+
if (!this.state.core.switches.passkeys)
|
|
58
|
+
return OFF
|
|
59
|
+
|
|
60
|
+
return (await load.passkeys()).verifyTwoFactorPasskey(this.state, response, this.state.establish)
|
|
61
|
+
}
|
|
62
|
+
}
|
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
import type { JWTVerifyGetKey } from 'jose'
|
|
2
|
+
import type { OAuthClientConfig, OAuthEndpoints, OAuthProvider, OAuthTokens, OpenIdCheck } from './types'
|
|
3
|
+
import { configError, KayError } from 'kay/library'
|
|
4
|
+
import { PROVIDER_TIMEOUT_MS } from './timeout'
|
|
5
|
+
|
|
6
|
+
// How far apart the provider's clock and this one may be when an ID token's times are read.
|
|
7
|
+
const CLOCK_TOLERANCE_S = 60
|
|
8
|
+
|
|
9
|
+
// What an ID token may be signed with when the provider names no list: asymmetric algorithms only, so neither `none` nor a shared-secret one passes.
|
|
10
|
+
const ID_TOKEN_ALGORITHMS = ['RS256', 'RS384', 'RS512', 'PS256', 'PS384', 'PS512', 'ES256', 'ES384', 'ES512', 'EdDSA']
|
|
11
|
+
|
|
12
|
+
interface AuthorizeUrlOptions {
|
|
13
|
+
state?: string
|
|
14
|
+
/** PKCE code challenge (S256); pair with `codeVerifier` on `exchangeCode`. */
|
|
15
|
+
codeChallenge?: string
|
|
16
|
+
/** Sent to an OpenID Connect provider only, to find in the ID token on `readUser`. */
|
|
17
|
+
nonce?: string
|
|
18
|
+
extraParams?: Record<string, string>
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// A form body with the headers its credentials ride in.
|
|
22
|
+
interface Credentialed {
|
|
23
|
+
body: URLSearchParams
|
|
24
|
+
headers: Record<string, string>
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Caps a provider response body embedded in an error so tokens/PII don't leak into logs. */
|
|
28
|
+
function redactBody(text: string): string {
|
|
29
|
+
return text.length > 200 ? `${text.slice(0, 200)}...` : text
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Thrown when the provider rejects the token exchange or user fetch, a bad or expired authorization code or the provider being down. `status` is the upstream HTTP status, so a caller can answer a client's bad code with a 4xx and a provider outage with a 502. */
|
|
33
|
+
export class OAuthExchangeError extends KayError {
|
|
34
|
+
override readonly name = 'OAuthExchangeError'
|
|
35
|
+
declare readonly code: 'oauth-exchange'
|
|
36
|
+
declare readonly status: number
|
|
37
|
+
|
|
38
|
+
constructor(status: number, message: string, options?: ErrorOptions) {
|
|
39
|
+
super('oauth-exchange', `kayjs-auth: ${message}`, { ...options, status })
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// A site served over https sends codes and tokens to https endpoints only, whatever NODE_ENV says.
|
|
44
|
+
function requireSecureEndpoints(endpoints: OAuthEndpoints, provider: string): void {
|
|
45
|
+
const urls = { authorizeUrl: endpoints.authorizeUrl, tokenUrl: endpoints.tokenUrl, userUrl: endpoints.userUrl, jwksUrl: endpoints.openId?.jwksUrl, discoveryBase: endpoints.discoveryBase }
|
|
46
|
+
|
|
47
|
+
for (const [name, url] of Object.entries(urls)) {
|
|
48
|
+
if (url !== undefined && new URL(url).protocol !== 'https:')
|
|
49
|
+
throw configError('auth', 'oauth', `the ${provider} provider's ${name} ${url} is not https, which a site at https refuses`)
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** A configured OAuth client bound to one provider and one app's credentials. */
|
|
54
|
+
export function createOAuthClient<Raw = unknown, User = unknown>(provider: OAuthProvider<Raw, User>, config: OAuthClientConfig) {
|
|
55
|
+
let discovered: Promise<OAuthEndpoints> | undefined
|
|
56
|
+
const secure = new URL(config.redirectUri).protocol === 'https:'
|
|
57
|
+
const keySets = new Map<string, JWTVerifyGetKey>()
|
|
58
|
+
|
|
59
|
+
if (secure)
|
|
60
|
+
requireSecureEndpoints(provider, provider.name)
|
|
61
|
+
|
|
62
|
+
// Discovered once; a failure is tried again on the next use rather than kept.
|
|
63
|
+
const endpoints = async (): Promise<OAuthEndpoints> => {
|
|
64
|
+
if (!provider.discover)
|
|
65
|
+
return provider
|
|
66
|
+
|
|
67
|
+
discovered ??= provider.discover()
|
|
68
|
+
|
|
69
|
+
try {
|
|
70
|
+
const found = { ...provider, ...await discovered }
|
|
71
|
+
|
|
72
|
+
if (secure)
|
|
73
|
+
requireSecureEndpoints(found, provider.name)
|
|
74
|
+
|
|
75
|
+
return found
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
discovered = undefined
|
|
79
|
+
|
|
80
|
+
throw new OAuthExchangeError(502, `OAuth discovery failed (${provider.name}): ${error instanceof Error ? error.message : String(error)}`, { cause: error })
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const endpoint = async (name: 'authorizeUrl' | 'tokenUrl'): Promise<string> => {
|
|
85
|
+
const url = (await endpoints())[name]
|
|
86
|
+
|
|
87
|
+
if (url === undefined)
|
|
88
|
+
throw configError('auth', 'oauth', `the ${provider.name} provider has no ${name}`)
|
|
89
|
+
|
|
90
|
+
return url
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// The app's credentials as the provider wants them: in the body, or as a Basic header (RFC 6749 form-encodes each part first) with no `client_id` in the body.
|
|
94
|
+
const withCredentials = async (body: URLSearchParams): Promise<Credentialed> => {
|
|
95
|
+
const secret = provider.clientSecret ? await provider.clientSecret(config.clientId) : config.clientSecret
|
|
96
|
+
|
|
97
|
+
if (provider.clientAuth === 'basic' && secret !== undefined)
|
|
98
|
+
return { body, headers: { Authorization: `Basic ${btoa(`${encodeURIComponent(config.clientId)}:${encodeURIComponent(secret)}`)}` } }
|
|
99
|
+
|
|
100
|
+
body.set('client_id', config.clientId)
|
|
101
|
+
|
|
102
|
+
if (secret !== undefined)
|
|
103
|
+
body.set('client_secret', secret)
|
|
104
|
+
|
|
105
|
+
return { body, headers: {} }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const userInfo = async (accessToken: string, userUrl: string | undefined): Promise<Record<string, unknown>> => {
|
|
109
|
+
if (userUrl === undefined)
|
|
110
|
+
throw configError('auth', 'oauth', `the ${provider.name} provider has neither a userUrl nor an ID token to read the user from`)
|
|
111
|
+
|
|
112
|
+
const { res, text } = await askProvider(provider.name, 'user fetch', userUrl, {
|
|
113
|
+
headers: {
|
|
114
|
+
Authorization: `Bearer ${accessToken}`,
|
|
115
|
+
...provider.authHeaders?.(accessToken),
|
|
116
|
+
},
|
|
117
|
+
})
|
|
118
|
+
|
|
119
|
+
if (!res.ok)
|
|
120
|
+
throw new OAuthExchangeError(res.status, `OAuth user fetch failed (${provider.name}): ${res.status} ${redactBody(text)}`)
|
|
121
|
+
|
|
122
|
+
return parseJson(provider.name, 'user fetch', text) as Record<string, unknown>
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const completed = async (raw: Raw, accessToken: string, scope: string | undefined): Promise<Raw> => provider.completeUser ? provider.completeUser(raw, { accessToken, scope }) : raw
|
|
126
|
+
|
|
127
|
+
const checkIdToken = async (idToken: string | undefined, check: OpenIdCheck, nonce: string | undefined): Promise<Record<string, unknown>> => {
|
|
128
|
+
if (idToken === undefined)
|
|
129
|
+
throw new OAuthExchangeError(400, `OAuth token response missing id_token (${provider.name})`)
|
|
130
|
+
|
|
131
|
+
// jose loads with the first ID token, so an app with no OpenID provider never reads it.
|
|
132
|
+
const { createRemoteJWKSet, errors, jwtVerify } = await import('jose')
|
|
133
|
+
let keys = keySets.get(check.jwksUrl)
|
|
134
|
+
|
|
135
|
+
if (!keys) {
|
|
136
|
+
keys = createRemoteJWKSet(new URL(check.jwksUrl))
|
|
137
|
+
keySets.set(check.jwksUrl, keys)
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
let claims: Record<string, unknown>
|
|
141
|
+
|
|
142
|
+
try {
|
|
143
|
+
({ payload: claims } = await jwtVerify(idToken, keys, { ...typeof check.issuer === 'function' ? {} : { issuer: check.issuer }, audience: config.clientId, algorithms: check.algorithms ?? ID_TOKEN_ALGORITHMS, clockTolerance: CLOCK_TOLERANCE_S, requiredClaims: ['sub', 'iat', 'exp'] }))
|
|
144
|
+
}
|
|
145
|
+
catch (error) {
|
|
146
|
+
// A key set out of reach is the provider down; any other failure, a token not to trust.
|
|
147
|
+
const refused = error instanceof errors.JOSEError && error.code !== 'ERR_JOSE_GENERIC' && !(error instanceof errors.JWKSTimeout)
|
|
148
|
+
|
|
149
|
+
throw new OAuthExchangeError(refused ? 400 : 502, `OAuth ID token refused (${provider.name}): ${error instanceof Error ? error.message : String(error)}`, { cause: error })
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const audiences = Array.isArray(claims.aud) ? claims.aud : [claims.aud]
|
|
153
|
+
|
|
154
|
+
if (typeof check.issuer === 'function' && !check.issuer(claims))
|
|
155
|
+
throw new OAuthExchangeError(400, `OAuth ID token refused (${provider.name}): unexpected issuer`)
|
|
156
|
+
|
|
157
|
+
// A token for several clients names the one it was given to.
|
|
158
|
+
if (audiences.length > 1 && claims.azp !== config.clientId)
|
|
159
|
+
throw new OAuthExchangeError(400, `OAuth ID token refused (${provider.name}): issued to another client`)
|
|
160
|
+
|
|
161
|
+
if (nonce !== undefined && claims.nonce !== nonce)
|
|
162
|
+
throw new OAuthExchangeError(400, `OAuth ID token refused (${provider.name}): nonce mismatch`)
|
|
163
|
+
|
|
164
|
+
return claims
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
return {
|
|
168
|
+
/** The provider authorize URL to redirect the user to. */
|
|
169
|
+
async authorizeUrl({ state, codeChallenge, nonce, extraParams }: AuthorizeUrlOptions = {}): Promise<string> {
|
|
170
|
+
const { openId } = await endpoints()
|
|
171
|
+
const params = new URLSearchParams({
|
|
172
|
+
client_id: config.clientId,
|
|
173
|
+
redirect_uri: config.redirectUri,
|
|
174
|
+
response_type: 'code',
|
|
175
|
+
scope: provider.scopes.join(provider.scopeSeparator ?? ' '),
|
|
176
|
+
...provider.authorizeParams,
|
|
177
|
+
...extraParams,
|
|
178
|
+
})
|
|
179
|
+
|
|
180
|
+
if (state !== undefined)
|
|
181
|
+
params.set('state', state)
|
|
182
|
+
|
|
183
|
+
if (codeChallenge !== undefined) {
|
|
184
|
+
params.set('code_challenge', codeChallenge)
|
|
185
|
+
params.set('code_challenge_method', 'S256')
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
if (nonce !== undefined && openId)
|
|
189
|
+
params.set('nonce', nonce)
|
|
190
|
+
|
|
191
|
+
return `${await endpoint('authorizeUrl')}?${params}`
|
|
192
|
+
},
|
|
193
|
+
|
|
194
|
+
/** Exchanges an authorization code for tokens (replay the PKCE `codeVerifier` if used). */
|
|
195
|
+
async exchangeCode(code: string, opts: { codeVerifier?: string } = {}): Promise<OAuthTokens> {
|
|
196
|
+
const body = new URLSearchParams({
|
|
197
|
+
grant_type: 'authorization_code',
|
|
198
|
+
code,
|
|
199
|
+
redirect_uri: config.redirectUri,
|
|
200
|
+
})
|
|
201
|
+
|
|
202
|
+
if (opts.codeVerifier !== undefined)
|
|
203
|
+
body.set('code_verifier', opts.codeVerifier)
|
|
204
|
+
|
|
205
|
+
return tokensFrom(provider, await postToken(provider.name, provider.tokenAccept, await endpoint('tokenUrl'), await withCredentials(body)))
|
|
206
|
+
},
|
|
207
|
+
|
|
208
|
+
/** Refreshes tokens with a refresh token. */
|
|
209
|
+
async refreshTokens(refreshToken: string): Promise<OAuthTokens> {
|
|
210
|
+
return tokensFrom(provider, await postToken(provider.name, provider.tokenAccept, await endpoint('tokenUrl'), await withCredentials(new URLSearchParams({
|
|
211
|
+
grant_type: 'refresh_token',
|
|
212
|
+
refresh_token: refreshToken,
|
|
213
|
+
}))))
|
|
214
|
+
},
|
|
215
|
+
|
|
216
|
+
/** Revokes a token at the provider (RFC 7009); false when the provider has no revocation endpoint. A refused or unreachable provider throws. */
|
|
217
|
+
async revokeToken(token: string): Promise<boolean> {
|
|
218
|
+
const url = (await endpoints()).revokeUrl
|
|
219
|
+
|
|
220
|
+
if (url === undefined)
|
|
221
|
+
return false
|
|
222
|
+
|
|
223
|
+
const { body, headers } = await withCredentials(new URLSearchParams({ token }))
|
|
224
|
+
const { res, text } = await askProvider(provider.name, 'token revocation', url, {
|
|
225
|
+
method: 'POST',
|
|
226
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json', ...headers },
|
|
227
|
+
body,
|
|
228
|
+
})
|
|
229
|
+
|
|
230
|
+
if (!res.ok)
|
|
231
|
+
throw new OAuthExchangeError(res.status, `OAuth token revocation failed (${provider.name}): ${res.status} ${redactBody(text)}`)
|
|
232
|
+
|
|
233
|
+
return true
|
|
234
|
+
},
|
|
235
|
+
|
|
236
|
+
/** Fetches and normalizes the provider user. */
|
|
237
|
+
async fetchUser(accessToken: string): Promise<User> {
|
|
238
|
+
return provider.normalizeUser(await completed(await userInfo(accessToken, (await endpoints()).userUrl) as Raw, accessToken, undefined), {})
|
|
239
|
+
},
|
|
240
|
+
|
|
241
|
+
/** The user a sign-in came back with: for OpenID Connect, off the ID token once checked, the user endpoint's answer over it when there is one; `callback` holds the parameters the provider came back with. */
|
|
242
|
+
async readUser(tokens: OAuthTokens, opts: { nonce?: string | undefined, callback?: Record<string, string> } = {}): Promise<User> {
|
|
243
|
+
const { userUrl, openId } = await endpoints()
|
|
244
|
+
const callback = opts.callback ?? {}
|
|
245
|
+
|
|
246
|
+
if (!openId)
|
|
247
|
+
return provider.normalizeUser(await completed(await userInfo(tokens.accessToken, userUrl) as Raw, tokens.accessToken, tokens.scope), callback)
|
|
248
|
+
|
|
249
|
+
const claims = await checkIdToken(tokens.idToken, openId, opts.nonce)
|
|
250
|
+
|
|
251
|
+
if (userUrl === undefined)
|
|
252
|
+
return provider.normalizeUser(claims as Raw, callback)
|
|
253
|
+
|
|
254
|
+
const info = await userInfo(tokens.accessToken, userUrl)
|
|
255
|
+
|
|
256
|
+
// An answer about another account than the token's would put one user's details on another.
|
|
257
|
+
if (info.sub !== claims.sub)
|
|
258
|
+
throw new OAuthExchangeError(502, `OAuth user fetch failed (${provider.name}): the user endpoint answered for another subject`)
|
|
259
|
+
|
|
260
|
+
return provider.normalizeUser({ ...claims, ...info } as Raw, callback)
|
|
261
|
+
},
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// The provider's answer read whole: one that hangs past the timeout, or a dropped connection, is the provider down.
|
|
266
|
+
async function askProvider(name: string, what: string, url: string, init: RequestInit): Promise<{ res: Response, text: string }> {
|
|
267
|
+
try {
|
|
268
|
+
const res = await fetch(url, { ...init, signal: AbortSignal.timeout(PROVIDER_TIMEOUT_MS) })
|
|
269
|
+
|
|
270
|
+
return { res, text: await res.text() }
|
|
271
|
+
}
|
|
272
|
+
catch (error) {
|
|
273
|
+
throw new OAuthExchangeError(502, `OAuth ${what} failed (${name}): ${error instanceof Error ? error.message : String(error)}`, { cause: error })
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// The body stays out of the error: a successful answer may hold tokens.
|
|
278
|
+
function parseJson(name: string, what: string, text: string): unknown {
|
|
279
|
+
try {
|
|
280
|
+
return JSON.parse(text)
|
|
281
|
+
}
|
|
282
|
+
catch {
|
|
283
|
+
throw new OAuthExchangeError(502, `OAuth ${what} failed (${name}): the answer is not JSON`)
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// A token answer the provider's parser cannot read, an app's own provider included, is the provider misbehaving rather than a server error.
|
|
288
|
+
function tokensFrom<Raw, User>(provider: OAuthProvider<Raw, User>, raw: unknown): OAuthTokens {
|
|
289
|
+
try {
|
|
290
|
+
return provider.parseTokens(raw)
|
|
291
|
+
}
|
|
292
|
+
catch (error) {
|
|
293
|
+
if (error instanceof OAuthExchangeError)
|
|
294
|
+
throw error
|
|
295
|
+
|
|
296
|
+
throw new OAuthExchangeError(502, `OAuth token request failed (${provider.name}): ${error instanceof Error ? error.message : String(error)}`, { cause: error })
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
async function postToken(name: string, accept: OAuthProvider['tokenAccept'], tokenUrl: string, { body, headers }: Credentialed): Promise<unknown> {
|
|
301
|
+
const { res, text } = await askProvider(name, 'token request', tokenUrl, {
|
|
302
|
+
method: 'POST',
|
|
303
|
+
headers: {
|
|
304
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
305
|
+
'Accept': 'application/json',
|
|
306
|
+
...headers,
|
|
307
|
+
},
|
|
308
|
+
body,
|
|
309
|
+
})
|
|
310
|
+
|
|
311
|
+
if (!res.ok)
|
|
312
|
+
throw new OAuthExchangeError(res.status, `OAuth token request failed (${name}): ${res.status} ${redactBody(text)}`)
|
|
313
|
+
|
|
314
|
+
const isJson = accept === 'json'
|
|
315
|
+
|| (accept !== 'form' && (res.headers.get('content-type') ?? '').includes('json'))
|
|
316
|
+
|
|
317
|
+
const parsed = (isJson ? parseJson(name, 'token request', text) : Object.fromEntries(new URLSearchParams(text))) as { error?: unknown } | null
|
|
318
|
+
|
|
319
|
+
// GitHub answers a refused grant with a 200 carrying `error`, where the spec answers a 400.
|
|
320
|
+
if (typeof parsed?.error === 'string')
|
|
321
|
+
throw new OAuthExchangeError(400, `OAuth token request refused (${name}): ${parsed.error}`)
|
|
322
|
+
|
|
323
|
+
return parsed
|
|
324
|
+
}
|