@softistx/janus 0.0.0-stage → 0.73.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 +2928 -2
- package/dist/auth/api-keys/authenticate-key.d.ts +21 -0
- package/dist/auth/api-keys/authenticate-key.d.ts.map +1 -0
- package/dist/auth/api-keys/bound.d.ts +11 -0
- package/dist/auth/api-keys/bound.d.ts.map +1 -0
- package/dist/auth/api-keys/count.d.ts +8 -0
- package/dist/auth/api-keys/count.d.ts.map +1 -0
- package/dist/auth/api-keys/create/checks.d.ts +42 -0
- package/dist/auth/api-keys/create/checks.d.ts.map +1 -0
- package/dist/auth/api-keys/create/index.d.ts +10 -0
- package/dist/auth/api-keys/create/index.d.ts.map +1 -0
- package/dist/auth/api-keys/events.d.ts +22 -0
- package/dist/auth/api-keys/events.d.ts.map +1 -0
- package/dist/auth/api-keys/expiry.d.ts +11 -0
- package/dist/auth/api-keys/expiry.d.ts.map +1 -0
- package/dist/auth/api-keys/flows.d.ts +13 -0
- package/dist/auth/api-keys/flows.d.ts.map +1 -0
- package/dist/auth/api-keys/index.d.ts +11 -0
- package/dist/auth/api-keys/index.d.ts.map +1 -0
- package/dist/auth/api-keys/read.d.ts +10 -0
- package/dist/auth/api-keys/read.d.ts.map +1 -0
- package/dist/auth/api-keys/shape.d.ts +24 -0
- package/dist/auth/api-keys/shape.d.ts.map +1 -0
- package/dist/auth/api-keys/to-api-key.d.ts +8 -0
- package/dist/auth/api-keys/to-api-key.d.ts.map +1 -0
- package/dist/auth/api-keys/token.d.ts +23 -0
- package/dist/auth/api-keys/token.d.ts.map +1 -0
- package/dist/auth/api-keys/user-bound.d.ts +10 -0
- package/dist/auth/api-keys/user-bound.d.ts.map +1 -0
- package/dist/auth/at.d.ts +9 -0
- package/dist/auth/at.d.ts.map +1 -0
- package/dist/auth/avatar/any-type.d.ts +13 -0
- package/dist/auth/avatar/any-type.d.ts.map +1 -0
- package/dist/auth/avatar/flows.d.ts +7 -0
- package/dist/auth/avatar/flows.d.ts.map +1 -0
- package/dist/auth/avatar/id.d.ts +10 -0
- package/dist/auth/avatar/id.d.ts.map +1 -0
- package/dist/auth/avatar/index.d.ts +7 -0
- package/dist/auth/avatar/index.d.ts.map +1 -0
- package/dist/auth/avatar/remove.d.ts +10 -0
- package/dist/auth/avatar/remove.d.ts.map +1 -0
- package/dist/auth/avatar/set.d.ts +12 -0
- package/dist/auth/avatar/set.d.ts.map +1 -0
- package/dist/auth/concurrency-limit.d.ts +13 -0
- package/dist/auth/concurrency-limit.d.ts.map +1 -0
- package/dist/auth/config/api-keys-config.d.ts +33 -0
- package/dist/auth/config/api-keys-config.d.ts.map +1 -0
- package/dist/auth/config/hasher.d.ts +22 -0
- package/dist/auth/config/hasher.d.ts.map +1 -0
- package/dist/auth/config/index.d.ts +24 -0
- package/dist/auth/config/index.d.ts.map +1 -0
- package/dist/auth/config/invitations-config.d.ts +74 -0
- package/dist/auth/config/invitations-config.d.ts.map +1 -0
- package/dist/auth/config/janus-config.d.ts +233 -0
- package/dist/auth/config/janus-config.d.ts.map +1 -0
- package/dist/auth/config/magic-link-config.d.ts +6 -0
- package/dist/auth/config/magic-link-config.d.ts.map +1 -0
- package/dist/auth/config/names.d.ts +9 -0
- package/dist/auth/config/names.d.ts.map +1 -0
- package/dist/auth/config/normalize.d.ts +26 -0
- package/dist/auth/config/normalize.d.ts.map +1 -0
- package/dist/auth/config/passkeys-config.d.ts +49 -0
- package/dist/auth/config/passkeys-config.d.ts.map +1 -0
- package/dist/auth/config/password-config.d.ts +22 -0
- package/dist/auth/config/password-config.d.ts.map +1 -0
- package/dist/auth/config/reserved.d.ts +14 -0
- package/dist/auth/config/reserved.d.ts.map +1 -0
- package/dist/auth/config/resolve-api-keys.d.ts +5 -0
- package/dist/auth/config/resolve-api-keys.d.ts.map +1 -0
- package/dist/auth/config/resolve-config.d.ts +9 -0
- package/dist/auth/config/resolve-config.d.ts.map +1 -0
- package/dist/auth/config/resolve-cookie.d.ts +5 -0
- package/dist/auth/config/resolve-cookie.d.ts.map +1 -0
- package/dist/auth/config/resolve-devices.d.ts +5 -0
- package/dist/auth/config/resolve-devices.d.ts.map +1 -0
- package/dist/auth/config/resolve-invitation-types.d.ts +5 -0
- package/dist/auth/config/resolve-invitation-types.d.ts.map +1 -0
- package/dist/auth/config/resolve-invitations.d.ts +5 -0
- package/dist/auth/config/resolve-invitations.d.ts.map +1 -0
- package/dist/auth/config/resolve-magic-link.d.ts +4 -0
- package/dist/auth/config/resolve-magic-link.d.ts.map +1 -0
- package/dist/auth/config/resolve-passkeys.d.ts +5 -0
- package/dist/auth/config/resolve-passkeys.d.ts.map +1 -0
- package/dist/auth/config/resolve-second-factor.d.ts +5 -0
- package/dist/auth/config/resolve-second-factor.d.ts.map +1 -0
- package/dist/auth/config/resolve-social.d.ts +17 -0
- package/dist/auth/config/resolve-social.d.ts.map +1 -0
- package/dist/auth/config/resolve-throttle.d.ts +37 -0
- package/dist/auth/config/resolve-throttle.d.ts.map +1 -0
- package/dist/auth/config/resolve-type.d.ts +6 -0
- package/dist/auth/config/resolve-type.d.ts.map +1 -0
- package/dist/auth/config/resolved-config.d.ts +126 -0
- package/dist/auth/config/resolved-config.d.ts.map +1 -0
- package/dist/auth/config/social-config.d.ts +154 -0
- package/dist/auth/config/social-config.d.ts.map +1 -0
- package/dist/auth/config/user-type.d.ts +79 -0
- package/dist/auth/config/user-type.d.ts.map +1 -0
- package/dist/auth/config/warn-throttle-window.d.ts +14 -0
- package/dist/auth/config/warn-throttle-window.d.ts.map +1 -0
- package/dist/auth/context/create-context.d.ts +31 -0
- package/dist/auth/context/create-context.d.ts.map +1 -0
- package/dist/auth/context/index.d.ts +17 -0
- package/dist/auth/context/index.d.ts.map +1 -0
- package/dist/auth/context/logins.d.ts +28 -0
- package/dist/auth/context/logins.d.ts.map +1 -0
- package/dist/auth/context/password.d.ts +34 -0
- package/dist/auth/context/password.d.ts.map +1 -0
- package/dist/auth/context/records.d.ts +27 -0
- package/dist/auth/context/records.d.ts.map +1 -0
- package/dist/auth/context/user.d.ts +21 -0
- package/dist/auth/context/user.d.ts.map +1 -0
- package/dist/auth/context/validate-fields.d.ts +12 -0
- package/dist/auth/context/validate-fields.d.ts.map +1 -0
- package/dist/auth/counter-key.d.ts +20 -0
- package/dist/auth/counter-key.d.ts.map +1 -0
- package/dist/auth/derived-keys.d.ts +9 -0
- package/dist/auth/derived-keys.d.ts.map +1 -0
- package/dist/auth/devices/cookie.d.ts +56 -0
- package/dist/auth/devices/cookie.d.ts.map +1 -0
- package/dist/auth/devices/hint.d.ts +42 -0
- package/dist/auth/devices/hint.d.ts.map +1 -0
- package/dist/auth/devices/index.d.ts +11 -0
- package/dist/auth/devices/index.d.ts.map +1 -0
- package/dist/auth/devices/report.d.ts +11 -0
- package/dist/auth/devices/report.d.ts.map +1 -0
- package/dist/auth/devices/token.d.ts +13 -0
- package/dist/auth/devices/token.d.ts.map +1 -0
- package/dist/auth/email-flows/any-type-change-email.d.ts +18 -0
- package/dist/auth/email-flows/any-type-change-email.d.ts.map +1 -0
- package/dist/auth/email-flows/any-type-reset-password.d.ts +19 -0
- package/dist/auth/email-flows/any-type-reset-password.d.ts.map +1 -0
- package/dist/auth/email-flows/any-type-verify-email.d.ts +18 -0
- package/dist/auth/email-flows/any-type-verify-email.d.ts.map +1 -0
- package/dist/auth/email-flows/change-email-token.d.ts +47 -0
- package/dist/auth/email-flows/change-email-token.d.ts.map +1 -0
- package/dist/auth/email-flows/change-email.d.ts +17 -0
- package/dist/auth/email-flows/change-email.d.ts.map +1 -0
- package/dist/auth/email-flows/confirm-reset.d.ts +16 -0
- package/dist/auth/email-flows/confirm-reset.d.ts.map +1 -0
- package/dist/auth/email-flows/email-token.d.ts +30 -0
- package/dist/auth/email-flows/email-token.d.ts.map +1 -0
- package/dist/auth/email-flows/flows.d.ts +13 -0
- package/dist/auth/email-flows/flows.d.ts.map +1 -0
- package/dist/auth/email-flows/index.d.ts +10 -0
- package/dist/auth/email-flows/index.d.ts.map +1 -0
- package/dist/auth/email-flows/owner-of.d.ts +17 -0
- package/dist/auth/email-flows/owner-of.d.ts.map +1 -0
- package/dist/auth/email-flows/prove-first.d.ts +45 -0
- package/dist/auth/email-flows/prove-first.d.ts.map +1 -0
- package/dist/auth/email-flows/reset-password.d.ts +17 -0
- package/dist/auth/email-flows/reset-password.d.ts.map +1 -0
- package/dist/auth/email-flows/set-email-verified.d.ts +19 -0
- package/dist/auth/email-flows/set-email-verified.d.ts.map +1 -0
- package/dist/auth/email-flows/verify-email.d.ts +25 -0
- package/dist/auth/email-flows/verify-email.d.ts.map +1 -0
- package/dist/auth/email-sign-in.d.ts +51 -0
- package/dist/auth/email-sign-in.d.ts.map +1 -0
- package/dist/auth/events.d.ts +166 -0
- package/dist/auth/events.d.ts.map +1 -0
- package/dist/auth/first-proof.d.ts +43 -0
- package/dist/auth/first-proof.d.ts.map +1 -0
- package/dist/auth/hashers.d.ts +52 -0
- package/dist/auth/hashers.d.ts.map +1 -0
- package/dist/auth/index.d.ts +22 -0
- package/dist/auth/index.d.ts.map +1 -0
- package/dist/auth/invitations/accept.d.ts +10 -0
- package/dist/auth/invitations/accept.d.ts.map +1 -0
- package/dist/auth/invitations/change-pending.d.ts +17 -0
- package/dist/auth/invitations/change-pending.d.ts.map +1 -0
- package/dist/auth/invitations/claim.d.ts +31 -0
- package/dist/auth/invitations/claim.d.ts.map +1 -0
- package/dist/auth/invitations/events.d.ts +46 -0
- package/dist/auth/invitations/events.d.ts.map +1 -0
- package/dist/auth/invitations/find-invitee.d.ts +20 -0
- package/dist/auth/invitations/find-invitee.d.ts.map +1 -0
- package/dist/auth/invitations/find-pending.d.ts +5 -0
- package/dist/auth/invitations/find-pending.d.ts.map +1 -0
- package/dist/auth/invitations/flows.d.ts +7 -0
- package/dist/auth/invitations/flows.d.ts.map +1 -0
- package/dist/auth/invitations/history-input.d.ts +29 -0
- package/dist/auth/invitations/history-input.d.ts.map +1 -0
- package/dist/auth/invitations/history.d.ts +10 -0
- package/dist/auth/invitations/history.d.ts.map +1 -0
- package/dist/auth/invitations/index.d.ts +11 -0
- package/dist/auth/invitations/index.d.ts.map +1 -0
- package/dist/auth/invitations/input.d.ts +30 -0
- package/dist/auth/invitations/input.d.ts.map +1 -0
- package/dist/auth/invitations/invited-type.d.ts +22 -0
- package/dist/auth/invitations/invited-type.d.ts.map +1 -0
- package/dist/auth/invitations/invitee.d.ts +11 -0
- package/dist/auth/invitations/invitee.d.ts.map +1 -0
- package/dist/auth/invitations/issue.d.ts +9 -0
- package/dist/auth/invitations/issue.d.ts.map +1 -0
- package/dist/auth/invitations/limit.d.ts +7 -0
- package/dist/auth/invitations/limit.d.ts.map +1 -0
- package/dist/auth/invitations/password-invitee.d.ts +18 -0
- package/dist/auth/invitations/password-invitee.d.ts.map +1 -0
- package/dist/auth/invitations/passwordless-invitee.d.ts +13 -0
- package/dist/auth/invitations/passwordless-invitee.d.ts.map +1 -0
- package/dist/auth/invitations/preview.d.ts +8 -0
- package/dist/auth/invitations/preview.d.ts.map +1 -0
- package/dist/auth/invitations/read.d.ts +10 -0
- package/dist/auth/invitations/read.d.ts.map +1 -0
- package/dist/auth/invitations/resend.d.ts +12 -0
- package/dist/auth/invitations/resend.d.ts.map +1 -0
- package/dist/auth/invitations/to-invitation.d.ts +11 -0
- package/dist/auth/invitations/to-invitation.d.ts.map +1 -0
- package/dist/auth/invitations/write.d.ts +17 -0
- package/dist/auth/invitations/write.d.ts.map +1 -0
- package/dist/auth/issuers/cache.d.ts +21 -0
- package/dist/auth/issuers/cache.d.ts.map +1 -0
- package/dist/auth/issuers/create.d.ts +18 -0
- package/dist/auth/issuers/create.d.ts.map +1 -0
- package/dist/auth/issuers/index.d.ts +3 -0
- package/dist/auth/issuers/index.d.ts.map +1 -0
- package/dist/auth/issuers/types.d.ts +45 -0
- package/dist/auth/issuers/types.d.ts.map +1 -0
- package/dist/auth/janus.d.ts +39 -0
- package/dist/auth/janus.d.ts.map +1 -0
- package/dist/auth/magic-link.d.ts +25 -0
- package/dist/auth/magic-link.d.ts.map +1 -0
- package/dist/auth/mail-requests.d.ts +55 -0
- package/dist/auth/mail-requests.d.ts.map +1 -0
- package/dist/auth/one-time/codes.d.ts +46 -0
- package/dist/auth/one-time/codes.d.ts.map +1 -0
- package/dist/auth/one-time/index.d.ts +15 -0
- package/dist/auth/one-time/index.d.ts.map +1 -0
- package/dist/auth/one-time/issue.d.ts +45 -0
- package/dist/auth/one-time/issue.d.ts.map +1 -0
- package/dist/auth/one-time/refusals.d.ts +26 -0
- package/dist/auth/one-time/refusals.d.ts.map +1 -0
- package/dist/auth/one-time/spend.d.ts +24 -0
- package/dist/auth/one-time/spend.d.ts.map +1 -0
- package/dist/auth/one-time/window.d.ts +50 -0
- package/dist/auth/one-time/window.d.ts.map +1 -0
- package/dist/auth/outage.d.ts +66 -0
- package/dist/auth/outage.d.ts.map +1 -0
- package/dist/auth/parse-sealing-keys.d.ts +26 -0
- package/dist/auth/parse-sealing-keys.d.ts.map +1 -0
- package/dist/auth/passkeys/assert.d.ts +51 -0
- package/dist/auth/passkeys/assert.d.ts.map +1 -0
- package/dist/auth/passkeys/assertion-options.d.ts +9 -0
- package/dist/auth/passkeys/assertion-options.d.ts.map +1 -0
- package/dist/auth/passkeys/challenge.d.ts +19 -0
- package/dist/auth/passkeys/challenge.d.ts.map +1 -0
- package/dist/auth/passkeys/commit.d.ts +33 -0
- package/dist/auth/passkeys/commit.d.ts.map +1 -0
- package/dist/auth/passkeys/flows.d.ts +13 -0
- package/dist/auth/passkeys/flows.d.ts.map +1 -0
- package/dist/auth/passkeys/index.d.ts +12 -0
- package/dist/auth/passkeys/index.d.ts.map +1 -0
- package/dist/auth/passkeys/manage.d.ts +11 -0
- package/dist/auth/passkeys/manage.d.ts.map +1 -0
- package/dist/auth/passkeys/name.d.ts +4 -0
- package/dist/auth/passkeys/name.d.ts.map +1 -0
- package/dist/auth/passkeys/register.d.ts +20 -0
- package/dist/auth/passkeys/register.d.ts.map +1 -0
- package/dist/auth/passkeys/registration-options.d.ts +22 -0
- package/dist/auth/passkeys/registration-options.d.ts.map +1 -0
- package/dist/auth/passkeys/remove-all.d.ts +26 -0
- package/dist/auth/passkeys/remove-all.d.ts.map +1 -0
- package/dist/auth/passkeys/sign-in-options.d.ts +12 -0
- package/dist/auth/passkeys/sign-in-options.d.ts.map +1 -0
- package/dist/auth/passkeys/sign-in.d.ts +21 -0
- package/dist/auth/passkeys/sign-in.d.ts.map +1 -0
- package/dist/auth/passkeys/verifier.d.ts +113 -0
- package/dist/auth/passkeys/verifier.d.ts.map +1 -0
- package/dist/auth/passkeys/view.d.ts +5 -0
- package/dist/auth/passkeys/view.d.ts.map +1 -0
- package/dist/auth/passkeys/wiring.d.ts +24 -0
- package/dist/auth/passkeys/wiring.d.ts.map +1 -0
- package/dist/auth/password-written.d.ts +55 -0
- package/dist/auth/password-written.d.ts.map +1 -0
- package/dist/auth/port/assert-api-keys.d.ts +21 -0
- package/dist/auth/port/assert-api-keys.d.ts.map +1 -0
- package/dist/auth/port/assert-invitations.d.ts +15 -0
- package/dist/auth/port/assert-invitations.d.ts.map +1 -0
- package/dist/auth/port/assert-stores.d.ts +16 -0
- package/dist/auth/port/assert-stores.d.ts.map +1 -0
- package/dist/auth/port/memory/api-keys/capabilities.d.ts +8 -0
- package/dist/auth/port/memory/api-keys/capabilities.d.ts.map +1 -0
- package/dist/auth/port/memory/api-keys/index.d.ts +13 -0
- package/dist/auth/port/memory/api-keys/index.d.ts.map +1 -0
- package/dist/auth/port/memory/api-keys/pages.d.ts +7 -0
- package/dist/auth/port/memory/api-keys/pages.d.ts.map +1 -0
- package/dist/auth/port/memory/copy.d.ts +6 -0
- package/dist/auth/port/memory/copy.d.ts.map +1 -0
- package/dist/auth/port/memory/index.d.ts +10 -0
- package/dist/auth/port/memory/index.d.ts.map +1 -0
- package/dist/auth/port/memory/invitations-pending.d.ts +6 -0
- package/dist/auth/port/memory/invitations-pending.d.ts.map +1 -0
- package/dist/auth/port/memory/invitations.d.ts +12 -0
- package/dist/auth/port/memory/invitations.d.ts.map +1 -0
- package/dist/auth/port/memory/passkeys.d.ts +9 -0
- package/dist/auth/port/memory/passkeys.d.ts.map +1 -0
- package/dist/auth/port/memory/sessions.d.ts +4 -0
- package/dist/auth/port/memory/sessions.d.ts.map +1 -0
- package/dist/auth/port/memory/social-links.d.ts +10 -0
- package/dist/auth/port/memory/social-links.d.ts.map +1 -0
- package/dist/auth/port/memory/stores.d.ts +26 -0
- package/dist/auth/port/memory/stores.d.ts.map +1 -0
- package/dist/auth/port/memory/tokens.d.ts +4 -0
- package/dist/auth/port/memory/tokens.d.ts.map +1 -0
- package/dist/auth/port/memory/user-index.d.ts +20 -0
- package/dist/auth/port/memory/user-index.d.ts.map +1 -0
- package/dist/auth/port/memory/user-update.d.ts +10 -0
- package/dist/auth/port/memory/user-update.d.ts.map +1 -0
- package/dist/auth/port/memory/users.d.ts +4 -0
- package/dist/auth/port/memory/users.d.ts.map +1 -0
- package/dist/auth/port/types/api-keys.d.ts +199 -0
- package/dist/auth/port/types/api-keys.d.ts.map +1 -0
- package/dist/auth/port/types/credentials.d.ts +46 -0
- package/dist/auth/port/types/credentials.d.ts.map +1 -0
- package/dist/auth/port/types/index.d.ts +75 -0
- package/dist/auth/port/types/index.d.ts.map +1 -0
- package/dist/auth/port/types/invitations/index.d.ts +15 -0
- package/dist/auth/port/types/invitations/index.d.ts.map +1 -0
- package/dist/auth/port/types/invitations/page.d.ts +52 -0
- package/dist/auth/port/types/invitations/page.d.ts.map +1 -0
- package/dist/auth/port/types/invitations/records.d.ts +101 -0
- package/dist/auth/port/types/invitations/records.d.ts.map +1 -0
- package/dist/auth/port/types/invitations/store.d.ts +82 -0
- package/dist/auth/port/types/invitations/store.d.ts.map +1 -0
- package/dist/auth/port/types/json.d.ts +27 -0
- package/dist/auth/port/types/json.d.ts.map +1 -0
- package/dist/auth/port/types/passkeys.d.ts +94 -0
- package/dist/auth/port/types/passkeys.d.ts.map +1 -0
- package/dist/auth/port/types/sessions.d.ts +142 -0
- package/dist/auth/port/types/sessions.d.ts.map +1 -0
- package/dist/auth/port/types/social-links.d.ts +64 -0
- package/dist/auth/port/types/social-links.d.ts.map +1 -0
- package/dist/auth/port/types/stores.d.ts +48 -0
- package/dist/auth/port/types/stores.d.ts.map +1 -0
- package/dist/auth/port/types/tokens.d.ts +168 -0
- package/dist/auth/port/types/tokens.d.ts.map +1 -0
- package/dist/auth/port/types/users.d.ts +260 -0
- package/dist/auth/port/types/users.d.ts.map +1 -0
- package/dist/auth/prepared.d.ts +21 -0
- package/dist/auth/prepared.d.ts.map +1 -0
- package/dist/auth/proven-sign-in.d.ts +22 -0
- package/dist/auth/proven-sign-in.d.ts.map +1 -0
- package/dist/auth/sealer-for.d.ts +44 -0
- package/dist/auth/sealer-for.d.ts.map +1 -0
- package/dist/auth/sealing.d.ts +36 -0
- package/dist/auth/sealing.d.ts.map +1 -0
- package/dist/auth/second-factor/activate.d.ts +9 -0
- package/dist/auth/second-factor/activate.d.ts.map +1 -0
- package/dist/auth/second-factor/app-code-attempts.d.ts +47 -0
- package/dist/auth/second-factor/app-code-attempts.d.ts.map +1 -0
- package/dist/auth/second-factor/challenge.d.ts +15 -0
- package/dist/auth/second-factor/challenge.d.ts.map +1 -0
- package/dist/auth/second-factor/codes-left.d.ts +14 -0
- package/dist/auth/second-factor/codes-left.d.ts.map +1 -0
- package/dist/auth/second-factor/disable.d.ts +10 -0
- package/dist/auth/second-factor/disable.d.ts.map +1 -0
- package/dist/auth/second-factor/enroll.d.ts +6 -0
- package/dist/auth/second-factor/enroll.d.ts.map +1 -0
- package/dist/auth/second-factor/factor.d.ts +33 -0
- package/dist/auth/second-factor/factor.d.ts.map +1 -0
- package/dist/auth/second-factor/flows.d.ts +36 -0
- package/dist/auth/second-factor/flows.d.ts.map +1 -0
- package/dist/auth/second-factor/lifecycle.d.ts +14 -0
- package/dist/auth/second-factor/lifecycle.d.ts.map +1 -0
- package/dist/auth/second-factor/passkey-confirm.d.ts +21 -0
- package/dist/auth/second-factor/passkey-confirm.d.ts.map +1 -0
- package/dist/auth/second-factor/recovery-codes.d.ts +36 -0
- package/dist/auth/second-factor/recovery-codes.d.ts.map +1 -0
- package/dist/auth/second-factor/recovery.d.ts +20 -0
- package/dist/auth/second-factor/recovery.d.ts.map +1 -0
- package/dist/auth/second-factor/redeem.d.ts +42 -0
- package/dist/auth/second-factor/redeem.d.ts.map +1 -0
- package/dist/auth/second-factor/refusal.d.ts +6 -0
- package/dist/auth/second-factor/refusal.d.ts.map +1 -0
- package/dist/auth/second-factor/regenerate.d.ts +12 -0
- package/dist/auth/second-factor/regenerate.d.ts.map +1 -0
- package/dist/auth/second-factor/reseal.d.ts +17 -0
- package/dist/auth/second-factor/reseal.d.ts.map +1 -0
- package/dist/auth/second-factor/spend-recovery-code.d.ts +15 -0
- package/dist/auth/second-factor/spend-recovery-code.d.ts.map +1 -0
- package/dist/auth/secrets.d.ts +17 -0
- package/dist/auth/secrets.d.ts.map +1 -0
- package/dist/auth/sessions/amr.d.ts +36 -0
- package/dist/auth/sessions/amr.d.ts.map +1 -0
- package/dist/auth/sessions/authenticate.d.ts +12 -0
- package/dist/auth/sessions/authenticate.d.ts.map +1 -0
- package/dist/auth/sessions/collect-expired.d.ts +15 -0
- package/dist/auth/sessions/collect-expired.d.ts.map +1 -0
- package/dist/auth/sessions/cookie.d.ts +9 -0
- package/dist/auth/sessions/cookie.d.ts.map +1 -0
- package/dist/auth/sessions/fresh.d.ts +35 -0
- package/dist/auth/sessions/fresh.d.ts.map +1 -0
- package/dist/auth/sessions/index.d.ts +12 -0
- package/dist/auth/sessions/index.d.ts.map +1 -0
- package/dist/auth/sessions/open-session.d.ts +22 -0
- package/dist/auth/sessions/open-session.d.ts.map +1 -0
- package/dist/auth/sessions/presented-token.d.ts +25 -0
- package/dist/auth/sessions/presented-token.d.ts.map +1 -0
- package/dist/auth/sessions/shared-api.d.ts +17 -0
- package/dist/auth/sessions/shared-api.d.ts.map +1 -0
- package/dist/auth/sessions/standing.d.ts +32 -0
- package/dist/auth/sessions/standing.d.ts.map +1 -0
- package/dist/auth/shared-api.d.ts +139 -0
- package/dist/auth/shared-api.d.ts.map +1 -0
- package/dist/auth/sign-in-attempts.d.ts +45 -0
- package/dist/auth/sign-in-attempts.d.ts.map +1 -0
- package/dist/auth/sign-in-code.d.ts +26 -0
- package/dist/auth/sign-in-code.d.ts.map +1 -0
- package/dist/auth/social/attach.d.ts +31 -0
- package/dist/auth/social/attach.d.ts.map +1 -0
- package/dist/auth/social/begin.d.ts +30 -0
- package/dist/auth/social/begin.d.ts.map +1 -0
- package/dist/auth/social/complete-link.d.ts +17 -0
- package/dist/auth/social/complete-link.d.ts.map +1 -0
- package/dist/auth/social/complete.d.ts +54 -0
- package/dist/auth/social/complete.d.ts.map +1 -0
- package/dist/auth/social/cookie.d.ts +16 -0
- package/dist/auth/social/cookie.d.ts.map +1 -0
- package/dist/auth/social/find-provider.d.ts +23 -0
- package/dist/auth/social/find-provider.d.ts.map +1 -0
- package/dist/auth/social/finish.d.ts +60 -0
- package/dist/auth/social/finish.d.ts.map +1 -0
- package/dist/auth/social/flow-cookie-value.d.ts +26 -0
- package/dist/auth/social/flow-cookie-value.d.ts.map +1 -0
- package/dist/auth/social/flow-secret.d.ts +40 -0
- package/dist/auth/social/flow-secret.d.ts.map +1 -0
- package/dist/auth/social/index.d.ts +19 -0
- package/dist/auth/social/index.d.ts.map +1 -0
- package/dist/auth/social/link-holder.d.ts +33 -0
- package/dist/auth/social/link-holder.d.ts.map +1 -0
- package/dist/auth/social/provider-call.d.ts +31 -0
- package/dist/auth/social/provider-call.d.ts.map +1 -0
- package/dist/auth/social/redeem.d.ts +45 -0
- package/dist/auth/social/redeem.d.ts.map +1 -0
- package/dist/auth/social/return-to.d.ts +18 -0
- package/dist/auth/social/return-to.d.ts.map +1 -0
- package/dist/auth/social/sign-in.d.ts +41 -0
- package/dist/auth/social/sign-in.d.ts.map +1 -0
- package/dist/auth/social/sign-up.d.ts +37 -0
- package/dist/auth/social/sign-up.d.ts.map +1 -0
- package/dist/auth/social/start.d.ts +21 -0
- package/dist/auth/social/start.d.ts.map +1 -0
- package/dist/auth/social/step-up-proof.d.ts +26 -0
- package/dist/auth/social/step-up-proof.d.ts.map +1 -0
- package/dist/auth/social/step-up-request.d.ts +28 -0
- package/dist/auth/social/step-up-request.d.ts.map +1 -0
- package/dist/auth/social/step-up.d.ts +19 -0
- package/dist/auth/social/step-up.d.ts.map +1 -0
- package/dist/auth/social/types-of.d.ts +12 -0
- package/dist/auth/social/types-of.d.ts.map +1 -0
- package/dist/auth/social/unlink.d.ts +16 -0
- package/dist/auth/social/unlink.d.ts.map +1 -0
- package/dist/auth/social/wiring.d.ts +10 -0
- package/dist/auth/social/wiring.d.ts.map +1 -0
- package/dist/auth/standard-schema.d.ts +41 -0
- package/dist/auth/standard-schema.d.ts.map +1 -0
- package/dist/auth/step-up/codes.d.ts +35 -0
- package/dist/auth/step-up/codes.d.ts.map +1 -0
- package/dist/auth/step-up/flows.d.ts +18 -0
- package/dist/auth/step-up/flows.d.ts.map +1 -0
- package/dist/auth/step-up/open.d.ts +23 -0
- package/dist/auth/step-up/open.d.ts.map +1 -0
- package/dist/auth/step-up/passkey.d.ts +31 -0
- package/dist/auth/step-up/passkey.d.ts.map +1 -0
- package/dist/auth/step-up/request.d.ts +15 -0
- package/dist/auth/step-up/request.d.ts.map +1 -0
- package/dist/auth/step-up/spend.d.ts +4 -0
- package/dist/auth/step-up/spend.d.ts.map +1 -0
- package/dist/auth/totp.d.ts +36 -0
- package/dist/auth/totp.d.ts.map +1 -0
- package/dist/auth/types/api-keys-of.d.ts +19 -0
- package/dist/auth/types/api-keys-of.d.ts.map +1 -0
- package/dist/auth/types/api-keys.d.ts +164 -0
- package/dist/auth/types/api-keys.d.ts.map +1 -0
- package/dist/auth/types/avatar.d.ts +72 -0
- package/dist/auth/types/avatar.d.ts.map +1 -0
- package/dist/auth/types/change-email.d.ts +82 -0
- package/dist/auth/types/change-email.d.ts.map +1 -0
- package/dist/auth/types/checks.d.ts +147 -0
- package/dist/auth/types/checks.d.ts.map +1 -0
- package/dist/auth/types/email-flows.d.ts +117 -0
- package/dist/auth/types/email-flows.d.ts.map +1 -0
- package/dist/auth/types/find-by-email.d.ts +31 -0
- package/dist/auth/types/find-by-email.d.ts.map +1 -0
- package/dist/auth/types/find-or-create.d.ts +59 -0
- package/dist/auth/types/find-or-create.d.ts.map +1 -0
- package/dist/auth/types/index.d.ts +38 -0
- package/dist/auth/types/index.d.ts.map +1 -0
- package/dist/auth/types/inference.d.ts +62 -0
- package/dist/auth/types/inference.d.ts.map +1 -0
- package/dist/auth/types/invitations/api.d.ts +203 -0
- package/dist/auth/types/invitations/api.d.ts.map +1 -0
- package/dist/auth/types/invitations/history.d.ts +87 -0
- package/dist/auth/types/invitations/history.d.ts.map +1 -0
- package/dist/auth/types/invitations/index.d.ts +10 -0
- package/dist/auth/types/invitations/index.d.ts.map +1 -0
- package/dist/auth/types/invitations/invitation.d.ts +76 -0
- package/dist/auth/types/invitations/invitation.d.ts.map +1 -0
- package/dist/auth/types/invitations/issue-type.d.ts +15 -0
- package/dist/auth/types/invitations/issue-type.d.ts.map +1 -0
- package/dist/auth/types/invitations-of.d.ts +26 -0
- package/dist/auth/types/invitations-of.d.ts.map +1 -0
- package/dist/auth/types/janus.d.ts +51 -0
- package/dist/auth/types/janus.d.ts.map +1 -0
- package/dist/auth/types/magic-link.d.ts +69 -0
- package/dist/auth/types/magic-link.d.ts.map +1 -0
- package/dist/auth/types/passkeys.d.ts +183 -0
- package/dist/auth/types/passkeys.d.ts.map +1 -0
- package/dist/auth/types/password.d.ts +113 -0
- package/dist/auth/types/password.d.ts.map +1 -0
- package/dist/auth/types/prepared.d.ts +68 -0
- package/dist/auth/types/prepared.d.ts.map +1 -0
- package/dist/auth/types/proven-sign-in.d.ts +43 -0
- package/dist/auth/types/proven-sign-in.d.ts.map +1 -0
- package/dist/auth/types/reset-password.d.ts +46 -0
- package/dist/auth/types/reset-password.d.ts.map +1 -0
- package/dist/auth/types/second-factor.d.ts +164 -0
- package/dist/auth/types/second-factor.d.ts.map +1 -0
- package/dist/auth/types/session.d.ts +68 -0
- package/dist/auth/types/session.d.ts.map +1 -0
- package/dist/auth/types/shared-api.d.ts +96 -0
- package/dist/auth/types/shared-api.d.ts.map +1 -0
- package/dist/auth/types/sign-in.d.ts +102 -0
- package/dist/auth/types/sign-in.d.ts.map +1 -0
- package/dist/auth/types/social-flow.d.ts +28 -0
- package/dist/auth/types/social-flow.d.ts.map +1 -0
- package/dist/auth/types/social-step-up.d.ts +38 -0
- package/dist/auth/types/social-step-up.d.ts.map +1 -0
- package/dist/auth/types/social.d.ts +193 -0
- package/dist/auth/types/social.d.ts.map +1 -0
- package/dist/auth/types/step-up.d.ts +133 -0
- package/dist/auth/types/step-up.d.ts.map +1 -0
- package/dist/auth/types/type-api.d.ts +29 -0
- package/dist/auth/types/type-api.d.ts.map +1 -0
- package/dist/auth/types/user-type.d.ts +106 -0
- package/dist/auth/types/user-type.d.ts.map +1 -0
- package/dist/auth/types/user.d.ts +62 -0
- package/dist/auth/types/user.d.ts.map +1 -0
- package/dist/auth/types/verify-email.d.ts +190 -0
- package/dist/auth/types/verify-email.d.ts.map +1 -0
- package/dist/auth/users/any-type-api.d.ts +6 -0
- package/dist/auth/users/any-type-api.d.ts.map +1 -0
- package/dist/auth/users/by-login.d.ts +10 -0
- package/dist/auth/users/by-login.d.ts.map +1 -0
- package/dist/auth/users/change-password.d.ts +26 -0
- package/dist/auth/users/change-password.d.ts.map +1 -0
- package/dist/auth/users/delete.d.ts +10 -0
- package/dist/auth/users/delete.d.ts.map +1 -0
- package/dist/auth/users/email-move-guard.d.ts +20 -0
- package/dist/auth/users/email-move-guard.d.ts.map +1 -0
- package/dist/auth/users/email-prefix.d.ts +23 -0
- package/dist/auth/users/email-prefix.d.ts.map +1 -0
- package/dist/auth/users/fields-patch.d.ts +21 -0
- package/dist/auth/users/fields-patch.d.ts.map +1 -0
- package/dist/auth/users/find-by-email.d.ts +11 -0
- package/dist/auth/users/find-by-email.d.ts.map +1 -0
- package/dist/auth/users/find-many.d.ts +29 -0
- package/dist/auth/users/find-many.d.ts.map +1 -0
- package/dist/auth/users/find-or-create.d.ts +12 -0
- package/dist/auth/users/find-or-create.d.ts.map +1 -0
- package/dist/auth/users/flow-types.d.ts +15 -0
- package/dist/auth/users/flow-types.d.ts.map +1 -0
- package/dist/auth/users/index.d.ts +9 -0
- package/dist/auth/users/index.d.ts.map +1 -0
- package/dist/auth/users/insert.d.ts +15 -0
- package/dist/auth/users/insert.d.ts.map +1 -0
- package/dist/auth/users/name-prefix.d.ts +19 -0
- package/dist/auth/users/name-prefix.d.ts.map +1 -0
- package/dist/auth/users/password-flows.d.ts +11 -0
- package/dist/auth/users/password-flows.d.ts.map +1 -0
- package/dist/auth/users/record-flows.d.ts +11 -0
- package/dist/auth/users/record-flows.d.ts.map +1 -0
- package/dist/auth/users/sign-in.d.ts +24 -0
- package/dist/auth/users/sign-in.d.ts.map +1 -0
- package/dist/auth/users/sign-up.d.ts +13 -0
- package/dist/auth/users/sign-up.d.ts.map +1 -0
- package/dist/auth/users/type-api.d.ts +10 -0
- package/dist/auth/users/type-api.d.ts.map +1 -0
- package/dist/auth/users/update.d.ts +16 -0
- package/dist/auth/users/update.d.ts.map +1 -0
- package/dist/background/background.d.ts +22 -0
- package/dist/background/background.d.ts.map +1 -0
- package/dist/chunks/index-2ttdcz7n.js +354 -0
- package/dist/chunks/index-2ttdcz7n.js.map +16 -0
- package/dist/chunks/index-5dxynm32.js +85 -0
- package/dist/chunks/index-5dxynm32.js.map +10 -0
- package/dist/chunks/index-ftz0ne6j.js +127 -0
- package/dist/chunks/index-ftz0ne6j.js.map +11 -0
- package/dist/chunks/index-k6y18nx9.js +724 -0
- package/dist/chunks/index-k6y18nx9.js.map +24 -0
- package/dist/chunks/index-n8jxmxeg.js +64 -0
- package/dist/chunks/index-n8jxmxeg.js.map +11 -0
- package/dist/conformance/api-keys/cases/bound.d.ts +3 -0
- package/dist/conformance/api-keys/cases/bound.d.ts.map +1 -0
- package/dist/conformance/api-keys/cases/expiry.d.ts +3 -0
- package/dist/conformance/api-keys/cases/expiry.d.ts.map +1 -0
- package/dist/conformance/api-keys/cases/index.d.ts +4 -0
- package/dist/conformance/api-keys/cases/index.d.ts.map +1 -0
- package/dist/conformance/api-keys/cases/insert.d.ts +3 -0
- package/dist/conformance/api-keys/cases/insert.d.ts.map +1 -0
- package/dist/conformance/api-keys/cases/outage.d.ts +3 -0
- package/dist/conformance/api-keys/cases/outage.d.ts.map +1 -0
- package/dist/conformance/api-keys/cases/revoke.d.ts +3 -0
- package/dist/conformance/api-keys/cases/revoke.d.ts.map +1 -0
- package/dist/conformance/api-keys/cases/touch.d.ts +3 -0
- package/dist/conformance/api-keys/cases/touch.d.ts.map +1 -0
- package/dist/conformance/api-keys/cases/user-bound.d.ts +3 -0
- package/dist/conformance/api-keys/cases/user-bound.d.ts.map +1 -0
- package/dist/conformance/api-keys/describe.d.ts +20 -0
- package/dist/conformance/api-keys/describe.d.ts.map +1 -0
- package/dist/conformance/api-keys/fixtures.d.ts +4 -0
- package/dist/conformance/api-keys/fixtures.d.ts.map +1 -0
- package/dist/conformance/api-keys/index.d.ts +18 -0
- package/dist/conformance/api-keys/index.d.ts.map +1 -0
- package/dist/conformance/api-keys/reference.d.ts +4 -0
- package/dist/conformance/api-keys/reference.d.ts.map +1 -0
- package/dist/conformance/api-keys/types.d.ts +42 -0
- package/dist/conformance/api-keys/types.d.ts.map +1 -0
- package/dist/conformance/assert.d.ts +40 -0
- package/dist/conformance/assert.d.ts.map +1 -0
- package/dist/conformance/cases/outage.d.ts +3 -0
- package/dist/conformance/cases/outage.d.ts.map +1 -0
- package/dist/conformance/cases/outage.passkeys.d.ts +12 -0
- package/dist/conformance/cases/outage.passkeys.d.ts.map +1 -0
- package/dist/conformance/cases/passkeys/deletion.d.ts +4 -0
- package/dist/conformance/cases/passkeys/deletion.d.ts.map +1 -0
- package/dist/conformance/cases/passkeys/index.d.ts +8 -0
- package/dist/conformance/cases/passkeys/index.d.ts.map +1 -0
- package/dist/conformance/cases/passkeys/inserts.d.ts +4 -0
- package/dist/conformance/cases/passkeys/inserts.d.ts.map +1 -0
- package/dist/conformance/cases/passkeys/reads.d.ts +4 -0
- package/dist/conformance/cases/passkeys/reads.d.ts.map +1 -0
- package/dist/conformance/cases/passkeys/uses.d.ts +4 -0
- package/dist/conformance/cases/passkeys/uses.d.ts.map +1 -0
- package/dist/conformance/cases/sessions/deletion.d.ts +4 -0
- package/dist/conformance/cases/sessions/deletion.d.ts.map +1 -0
- package/dist/conformance/cases/sessions/extension.d.ts +4 -0
- package/dist/conformance/cases/sessions/extension.d.ts.map +1 -0
- package/dist/conformance/cases/sessions/index.d.ts +4 -0
- package/dist/conformance/cases/sessions/index.d.ts.map +1 -0
- package/dist/conformance/cases/sessions/inserts.d.ts +4 -0
- package/dist/conformance/cases/sessions/inserts.d.ts.map +1 -0
- package/dist/conformance/cases/sessions/list.d.ts +4 -0
- package/dist/conformance/cases/sessions/list.d.ts.map +1 -0
- package/dist/conformance/cases/sessions/reads.d.ts +4 -0
- package/dist/conformance/cases/sessions/reads.d.ts.map +1 -0
- package/dist/conformance/cases/sessions/reauthentication.d.ts +4 -0
- package/dist/conformance/cases/sessions/reauthentication.d.ts.map +1 -0
- package/dist/conformance/cases/sessions/revocation.d.ts +4 -0
- package/dist/conformance/cases/sessions/revocation.d.ts.map +1 -0
- package/dist/conformance/cases/social-links/deletion.d.ts +4 -0
- package/dist/conformance/cases/social-links/deletion.d.ts.map +1 -0
- package/dist/conformance/cases/social-links/index.d.ts +8 -0
- package/dist/conformance/cases/social-links/index.d.ts.map +1 -0
- package/dist/conformance/cases/social-links/inserts.d.ts +4 -0
- package/dist/conformance/cases/social-links/inserts.d.ts.map +1 -0
- package/dist/conformance/cases/social-links/reads.d.ts +4 -0
- package/dist/conformance/cases/social-links/reads.d.ts.map +1 -0
- package/dist/conformance/cases/tokens/attempts.d.ts +7 -0
- package/dist/conformance/cases/tokens/attempts.d.ts.map +1 -0
- package/dist/conformance/cases/tokens/change-email.d.ts +8 -0
- package/dist/conformance/cases/tokens/change-email.d.ts.map +1 -0
- package/dist/conformance/cases/tokens/deletion.d.ts +4 -0
- package/dist/conformance/cases/tokens/deletion.d.ts.map +1 -0
- package/dist/conformance/cases/tokens/index.d.ts +4 -0
- package/dist/conformance/cases/tokens/index.d.ts.map +1 -0
- package/dist/conformance/cases/tokens/inserts.d.ts +7 -0
- package/dist/conformance/cases/tokens/inserts.d.ts.map +1 -0
- package/dist/conformance/cases/tokens/kinds.d.ts +7 -0
- package/dist/conformance/cases/tokens/kinds.d.ts.map +1 -0
- package/dist/conformance/cases/tokens/redemption.d.ts +7 -0
- package/dist/conformance/cases/tokens/redemption.d.ts.map +1 -0
- package/dist/conformance/cases/tokens/social-flow.d.ts +8 -0
- package/dist/conformance/cases/tokens/social-flow.d.ts.map +1 -0
- package/dist/conformance/cases/tokens/spending.d.ts +7 -0
- package/dist/conformance/cases/tokens/spending.d.ts.map +1 -0
- package/dist/conformance/cases/users/avatar.d.ts +8 -0
- package/dist/conformance/cases/users/avatar.d.ts.map +1 -0
- package/dist/conformance/cases/users/batch.d.ts +8 -0
- package/dist/conformance/cases/users/batch.d.ts.map +1 -0
- package/dist/conformance/cases/users/deletion.d.ts +4 -0
- package/dist/conformance/cases/users/deletion.d.ts.map +1 -0
- package/dist/conformance/cases/users/index.d.ts +4 -0
- package/dist/conformance/cases/users/index.d.ts.map +1 -0
- package/dist/conformance/cases/users/inserts.d.ts +4 -0
- package/dist/conformance/cases/users/inserts.d.ts.map +1 -0
- package/dist/conformance/cases/users/listing.d.ts +4 -0
- package/dist/conformance/cases/users/listing.d.ts.map +1 -0
- package/dist/conformance/cases/users/patches.d.ts +7 -0
- package/dist/conformance/cases/users/patches.d.ts.map +1 -0
- package/dist/conformance/cases/users/reads.d.ts +7 -0
- package/dist/conformance/cases/users/reads.d.ts.map +1 -0
- package/dist/conformance/cases/users/second-factor.d.ts +16 -0
- package/dist/conformance/cases/users/second-factor.d.ts.map +1 -0
- package/dist/conformance/cases/users/versions.d.ts +7 -0
- package/dist/conformance/cases/users/versions.d.ts.map +1 -0
- package/dist/conformance/describe.d.ts +82 -0
- package/dist/conformance/describe.d.ts.map +1 -0
- package/dist/conformance/fixtures.d.ts +31 -0
- package/dist/conformance/fixtures.d.ts.map +1 -0
- package/dist/conformance/index.d.ts +46 -0
- package/dist/conformance/index.d.ts.map +1 -0
- package/dist/conformance/index.js +4411 -0
- package/dist/conformance/index.js.map +86 -0
- package/dist/conformance/invitations/cases/actors.d.ts +3 -0
- package/dist/conformance/invitations/cases/actors.d.ts.map +1 -0
- package/dist/conformance/invitations/cases/find-pending.d.ts +3 -0
- package/dist/conformance/invitations/cases/find-pending.d.ts.map +1 -0
- package/dist/conformance/invitations/cases/imported.d.ts +3 -0
- package/dist/conformance/invitations/cases/imported.d.ts.map +1 -0
- package/dist/conformance/invitations/cases/index.d.ts +4 -0
- package/dist/conformance/invitations/cases/index.d.ts.map +1 -0
- package/dist/conformance/invitations/cases/insert.d.ts +3 -0
- package/dist/conformance/invitations/cases/insert.d.ts.map +1 -0
- package/dist/conformance/invitations/cases/list-lapsed.d.ts +3 -0
- package/dist/conformance/invitations/cases/list-lapsed.d.ts.map +1 -0
- package/dist/conformance/invitations/cases/list-status.d.ts +3 -0
- package/dist/conformance/invitations/cases/list-status.d.ts.map +1 -0
- package/dist/conformance/invitations/cases/list.d.ts +3 -0
- package/dist/conformance/invitations/cases/list.d.ts.map +1 -0
- package/dist/conformance/invitations/cases/outage.d.ts +3 -0
- package/dist/conformance/invitations/cases/outage.d.ts.map +1 -0
- package/dist/conformance/invitations/cases/scope.d.ts +3 -0
- package/dist/conformance/invitations/cases/scope.d.ts.map +1 -0
- package/dist/conformance/invitations/cases/update.d.ts +3 -0
- package/dist/conformance/invitations/cases/update.d.ts.map +1 -0
- package/dist/conformance/invitations/describe.d.ts +20 -0
- package/dist/conformance/invitations/describe.d.ts.map +1 -0
- package/dist/conformance/invitations/fixtures.d.ts +4 -0
- package/dist/conformance/invitations/fixtures.d.ts.map +1 -0
- package/dist/conformance/invitations/index.d.ts +18 -0
- package/dist/conformance/invitations/index.d.ts.map +1 -0
- package/dist/conformance/invitations/reference.d.ts +4 -0
- package/dist/conformance/invitations/reference.d.ts.map +1 -0
- package/dist/conformance/invitations/types.d.ts +34 -0
- package/dist/conformance/invitations/types.d.ts.map +1 -0
- package/dist/conformance/reference.d.ts +13 -0
- package/dist/conformance/reference.d.ts.map +1 -0
- package/dist/conformance/relations/cases/deletion.d.ts +4 -0
- package/dist/conformance/relations/cases/deletion.d.ts.map +1 -0
- package/dist/conformance/relations/cases/holders.d.ts +9 -0
- package/dist/conformance/relations/cases/holders.d.ts.map +1 -0
- package/dist/conformance/relations/cases/index.d.ts +4 -0
- package/dist/conformance/relations/cases/index.d.ts.map +1 -0
- package/dist/conformance/relations/cases/outage.d.ts +3 -0
- package/dist/conformance/relations/cases/outage.d.ts.map +1 -0
- package/dist/conformance/relations/cases/reads.d.ts +8 -0
- package/dist/conformance/relations/cases/reads.d.ts.map +1 -0
- package/dist/conformance/relations/cases/traversal.d.ts +7 -0
- package/dist/conformance/relations/cases/traversal.d.ts.map +1 -0
- package/dist/conformance/relations/cases/writes.d.ts +4 -0
- package/dist/conformance/relations/cases/writes.d.ts.map +1 -0
- package/dist/conformance/relations/describe.d.ts +20 -0
- package/dist/conformance/relations/describe.d.ts.map +1 -0
- package/dist/conformance/relations/fixtures.d.ts +8 -0
- package/dist/conformance/relations/fixtures.d.ts.map +1 -0
- package/dist/conformance/relations/index.d.ts +18 -0
- package/dist/conformance/relations/index.d.ts.map +1 -0
- package/dist/conformance/relations/reference.d.ts +4 -0
- package/dist/conformance/relations/reference.d.ts.map +1 -0
- package/dist/conformance/relations/types.d.ts +34 -0
- package/dist/conformance/relations/types.d.ts.map +1 -0
- package/dist/conformance/types.d.ts +79 -0
- package/dist/conformance/types.d.ts.map +1 -0
- package/dist/errors/janus-error/base.d.ts +47 -0
- package/dist/errors/janus-error/base.d.ts.map +1 -0
- package/dist/errors/janus-error/codes.credentials.d.ts +36 -0
- package/dist/errors/janus-error/codes.credentials.d.ts.map +1 -0
- package/dist/errors/janus-error/codes.d.ts +23 -0
- package/dist/errors/janus-error/codes.d.ts.map +1 -0
- package/dist/errors/janus-error/codes.invitations.d.ts +52 -0
- package/dist/errors/janus-error/codes.invitations.d.ts.map +1 -0
- package/dist/errors/janus-error/codes.one-time.d.ts +63 -0
- package/dist/errors/janus-error/codes.one-time.d.ts.map +1 -0
- package/dist/errors/janus-error/codes.records.d.ts +86 -0
- package/dist/errors/janus-error/codes.records.d.ts.map +1 -0
- package/dist/errors/janus-error/codes.social.d.ts +88 -0
- package/dist/errors/janus-error/codes.social.d.ts.map +1 -0
- package/dist/errors/janus-error/index.d.ts +17 -0
- package/dist/errors/janus-error/index.d.ts.map +1 -0
- package/dist/errors/janus-error/options.d.ts +105 -0
- package/dist/errors/janus-error/options.d.ts.map +1 -0
- package/dist/errors/janus-error/refusals.d.ts +151 -0
- package/dist/errors/janus-error/refusals.d.ts.map +1 -0
- package/dist/errors/janus-error/status.d.ts +21 -0
- package/dist/errors/janus-error/status.d.ts.map +1 -0
- package/dist/errors/janus-error/store.d.ts +36 -0
- package/dist/errors/janus-error/store.d.ts.map +1 -0
- package/dist/ids/derived.d.ts +25 -0
- package/dist/ids/derived.d.ts.map +1 -0
- package/dist/ids/id.d.ts +55 -0
- package/dist/ids/id.d.ts.map +1 -0
- package/dist/index.d.ts +32 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +6933 -0
- package/dist/index.js.map +208 -0
- package/dist/pagination/cursor-page.d.ts +53 -0
- package/dist/pagination/cursor-page.d.ts.map +1 -0
- package/dist/permissions/bound-model.d.ts +10 -0
- package/dist/permissions/bound-model.d.ts.map +1 -0
- package/dist/permissions/can.d.ts +13 -0
- package/dist/permissions/can.d.ts.map +1 -0
- package/dist/permissions/engine.d.ts +49 -0
- package/dist/permissions/engine.d.ts.map +1 -0
- package/dist/permissions/holders.d.ts +12 -0
- package/dist/permissions/holders.d.ts.map +1 -0
- package/dist/permissions/index.d.ts +36 -0
- package/dist/permissions/index.d.ts.map +1 -0
- package/dist/permissions/index.js +924 -0
- package/dist/permissions/index.js.map +28 -0
- package/dist/permissions/input.d.ts +43 -0
- package/dist/permissions/input.d.ts.map +1 -0
- package/dist/permissions/list.d.ts +16 -0
- package/dist/permissions/list.d.ts.map +1 -0
- package/dist/permissions/model/can.d.ts +41 -0
- package/dist/permissions/model/can.d.ts.map +1 -0
- package/dist/permissions/model/config.d.ts +36 -0
- package/dist/permissions/model/config.d.ts.map +1 -0
- package/dist/permissions/model/constraint.d.ts +37 -0
- package/dist/permissions/model/constraint.d.ts.map +1 -0
- package/dist/permissions/model/ctx.d.ts +23 -0
- package/dist/permissions/model/ctx.d.ts.map +1 -0
- package/dist/permissions/model/define.d.ts +78 -0
- package/dist/permissions/model/define.d.ts.map +1 -0
- package/dist/permissions/model/from-field.d.ts +31 -0
- package/dist/permissions/model/from-field.d.ts.map +1 -0
- package/dist/permissions/model/grant.d.ts +81 -0
- package/dist/permissions/model/grant.d.ts.map +1 -0
- package/dist/permissions/model/list.d.ts +48 -0
- package/dist/permissions/model/list.d.ts.map +1 -0
- package/dist/permissions/model/names.d.ts +51 -0
- package/dist/permissions/model/names.d.ts.map +1 -0
- package/dist/permissions/model/permissions.d.ts +48 -0
- package/dist/permissions/model/permissions.d.ts.map +1 -0
- package/dist/permissions/model/refs.d.ts +36 -0
- package/dist/permissions/model/refs.d.ts.map +1 -0
- package/dist/permissions/model/refusal.d.ts +13 -0
- package/dist/permissions/model/refusal.d.ts.map +1 -0
- package/dist/permissions/model/unions.d.ts +3 -0
- package/dist/permissions/model/unions.d.ts.map +1 -0
- package/dist/permissions/model/when.d.ts +16 -0
- package/dist/permissions/model/when.d.ts.map +1 -0
- package/dist/permissions/port/holders.d.ts +38 -0
- package/dist/permissions/port/holders.d.ts.map +1 -0
- package/dist/permissions/port/memory.d.ts +17 -0
- package/dist/permissions/port/memory.d.ts.map +1 -0
- package/dist/permissions/port/types.d.ts +101 -0
- package/dist/permissions/port/types.d.ts.map +1 -0
- package/dist/permissions/replace.d.ts +25 -0
- package/dist/permissions/replace.d.ts.map +1 -0
- package/dist/permissions/resolve/declared-names.d.ts +24 -0
- package/dist/permissions/resolve/declared-names.d.ts.map +1 -0
- package/dist/permissions/resolve/refuse-data-beyond-root.d.ts +11 -0
- package/dist/permissions/resolve/refuse-data-beyond-root.d.ts.map +1 -0
- package/dist/permissions/resolve/refuse-loops.d.ts +10 -0
- package/dist/permissions/resolve/refuse-loops.d.ts.map +1 -0
- package/dist/permissions/resolve/resolve-model.d.ts +13 -0
- package/dist/permissions/resolve/resolve-model.d.ts.map +1 -0
- package/dist/permissions/resolve/resolve-relation.d.ts +9 -0
- package/dist/permissions/resolve/resolve-relation.d.ts.map +1 -0
- package/dist/permissions/resolve/resolve-rule.d.ts +12 -0
- package/dist/permissions/resolve/resolve-rule.d.ts.map +1 -0
- package/dist/permissions/resolve/resolved.d.ts +52 -0
- package/dist/permissions/resolve/resolved.d.ts.map +1 -0
- package/dist/permissions/resolve/step.d.ts +4 -0
- package/dist/permissions/resolve/step.d.ts.map +1 -0
- package/dist/permissions/reverse.d.ts +53 -0
- package/dist/permissions/reverse.d.ts.map +1 -0
- package/dist/permissions/walk.d.ts +29 -0
- package/dist/permissions/walk.d.ts.map +1 -0
- package/dist/stores/guard.d.ts +24 -0
- package/dist/stores/guard.d.ts.map +1 -0
- package/dist/stores/storable.d.ts +15 -0
- package/dist/stores/storable.d.ts.map +1 -0
- package/dist/subjects/notation.d.ts +39 -0
- package/dist/subjects/notation.d.ts.map +1 -0
- package/dist/subjects/subject.d.ts +128 -0
- package/dist/subjects/subject.d.ts.map +1 -0
- package/dist/testing/index.d.ts +12 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +26 -0
- package/dist/testing/index.js.map +10 -0
- package/dist/time/clock.d.ts +31 -0
- package/dist/time/clock.d.ts.map +1 -0
- package/dist/time/duration.d.ts +23 -0
- package/dist/time/duration.d.ts.map +1 -0
- package/docs/README.md +46 -0
- package/docs/guide/adapters.md +858 -0
- package/docs/guide/api-keys.md +316 -0
- package/docs/guide/avatars.md +334 -0
- package/docs/guide/devices.md +441 -0
- package/docs/guide/email-flows.md +880 -0
- package/docs/guide/errors.md +180 -0
- package/docs/guide/events.md +467 -0
- package/docs/guide/invitations.md +465 -0
- package/docs/guide/issuers.md +107 -0
- package/docs/guide/magic-link.md +580 -0
- package/docs/guide/migrating-invitations.md +142 -0
- package/docs/guide/passkeys.md +425 -0
- package/docs/guide/passwords.md +325 -0
- package/docs/guide/permissions.md +719 -0
- package/docs/guide/second-factor.md +1124 -0
- package/docs/guide/sessions.md +521 -0
- package/docs/guide/sign-in-code.md +631 -0
- package/docs/guide/social.md +639 -0
- package/docs/guide/step-up.md +262 -0
- package/docs/guide/users.md +557 -0
- package/docs/guide/vocabulary.md +316 -0
- package/docs/roadmap.md +101 -0
- package/docs/troubleshooting.md +3305 -0
- package/package.json +77 -5
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/auth/devices/cookie.ts", "../src/auth/hashers.ts", "../src/auth/concurrency-limit.ts", "../src/time/clock.ts", "../src/time/duration.ts", "../src/auth/issuers/cache.ts", "../src/auth/issuers/create.ts", "../src/auth/context/create-context.ts", "../src/auth/config/normalize.ts", "../src/auth/config/reserved.ts", "../src/auth/config/names.ts", "../src/auth/config/resolve-api-keys.ts", "../src/auth/config/resolve-cookie.ts", "../src/auth/sealing.ts", "../src/auth/config/resolve-devices.ts", "../src/auth/config/resolve-invitation-types.ts", "../src/auth/config/resolve-invitations.ts", "../src/auth/config/resolve-magic-link.ts", "../src/auth/config/resolve-passkeys.ts", "../src/auth/config/resolve-throttle.ts", "../src/auth/config/resolve-second-factor.ts", "../src/auth/config/resolve-social.ts", "../src/auth/config/resolve-type.ts", "../src/auth/config/resolve-config.ts", "../src/auth/context/logins.ts", "../src/auth/outage.ts", "../src/auth/context/password.ts", "../src/auth/context/user.ts", "../src/auth/context/records.ts", "../src/auth/context/validate-fields.ts", "../src/auth/avatar/id.ts", "../src/auth/events.ts", "../src/auth/avatar/remove.ts", "../src/auth/avatar/set.ts", "../src/auth/avatar/any-type.ts", "../src/auth/avatar/flows.ts", "../src/auth/config/warn-throttle-window.ts", "../src/auth/derived-keys.ts", "../src/auth/counter-key.ts", "../src/auth/one-time/codes.ts", "../src/auth/secrets.ts", "../src/auth/one-time/refusals.ts", "../src/auth/one-time/spend.ts", "../src/auth/one-time/issue.ts", "../src/auth/one-time/window.ts", "../src/auth/mail-requests.ts", "../src/auth/users/fields-patch.ts", "../src/auth/email-flows/owner-of.ts", "../src/auth/email-flows/change-email-token.ts", "../src/auth/email-flows/change-email.ts", "../src/auth/email-flows/any-type-change-email.ts", "../src/auth/api-keys/events.ts", "../src/auth/password-written.ts", "../src/auth/email-flows/email-token.ts", "../src/auth/email-flows/confirm-reset.ts", "../src/auth/email-flows/any-type-reset-password.ts", "../src/auth/devices/token.ts", "../src/auth/devices/hint.ts", "../src/auth/devices/report.ts", "../src/auth/second-factor/factor.ts", "../src/auth/passkeys/remove-all.ts", "../src/auth/first-proof.ts", "../src/auth/email-sign-in.ts", "../src/auth/prepared.ts", "../src/auth/email-flows/prove-first.ts", "../src/auth/email-flows/verify-email.ts", "../src/auth/email-flows/any-type-verify-email.ts", "../src/auth/sessions/fresh.ts", "../src/auth/passkeys/name.ts", "../src/auth/passkeys/wiring.ts", "../src/auth/passkeys/commit.ts", "../src/auth/passkeys/registration-options.ts", "../src/auth/passkeys/view.ts", "../src/auth/passkeys/register.ts", "../src/auth/passkeys/manage.ts", "../src/auth/sessions/open-session.ts", "../src/auth/sessions/presented-token.ts", "../src/auth/api-keys/authenticate-key.ts", "../src/auth/api-keys/token.ts", "../src/auth/api-keys/to-api-key.ts", "../src/auth/sessions/standing.ts", "../src/auth/sessions/authenticate.ts", "../src/auth/sessions/collect-expired.ts", "../src/auth/sessions/cookie.ts", "../src/auth/sessions/shared-api.ts", "../src/auth/sessions/amr.ts", "../src/auth/sign-in-attempts.ts", "../src/auth/users/by-login.ts", "../src/auth/users/sign-in.ts", "../src/auth/passkeys/challenge.ts", "../src/auth/passkeys/assert.ts", "../src/auth/passkeys/sign-in-options.ts", "../src/auth/passkeys/sign-in.ts", "../src/auth/passkeys/flows.ts", "../src/auth/port/assert-api-keys.ts", "../src/auth/port/assert-invitations.ts", "../src/auth/port/assert-stores.ts", "../src/auth/api-keys/shape.ts", "../src/auth/api-keys/bound.ts", "../src/auth/api-keys/count.ts", "../src/auth/api-keys/create/checks.ts", "../src/auth/api-keys/create/index.ts", "../src/auth/api-keys/expiry.ts", "../src/auth/api-keys/user-bound.ts", "../src/auth/api-keys/read.ts", "../src/auth/api-keys/flows.ts", "../src/auth/email-flows/reset-password.ts", "../src/auth/email-flows/set-email-verified.ts", "../src/auth/email-flows/flows.ts", "../src/auth/magic-link.ts", "../src/auth/proven-sign-in.ts", "../src/auth/passkeys/assertion-options.ts", "../src/auth/second-factor/app-code-attempts.ts", "../src/auth/second-factor/redeem.ts", "../src/auth/second-factor/challenge.ts", "../src/auth/second-factor/codes-left.ts", "../src/auth/second-factor/recovery-codes.ts", "../src/auth/second-factor/refusal.ts", "../src/auth/second-factor/activate.ts", "../src/auth/second-factor/disable.ts", "../src/auth/second-factor/enroll.ts", "../src/auth/second-factor/regenerate.ts", "../src/auth/second-factor/spend-recovery-code.ts", "../src/auth/second-factor/lifecycle.ts", "../src/auth/second-factor/passkey-confirm.ts", "../src/auth/second-factor/recovery.ts", "../src/auth/second-factor/reseal.ts", "../src/auth/second-factor/flows.ts", "../src/auth/sign-in-code.ts", "../src/auth/step-up/spend.ts", "../src/auth/step-up/passkey.ts", "../src/auth/step-up/codes.ts", "../src/auth/step-up/open.ts", "../src/auth/step-up/request.ts", "../src/auth/step-up/flows.ts", "../src/auth/users/find-by-email.ts", "../src/auth/users/insert.ts", "../src/auth/users/find-or-create.ts", "../src/auth/users/change-password.ts", "../src/auth/users/sign-up.ts", "../src/auth/users/password-flows.ts", "../src/auth/users/delete.ts", "../src/auth/users/email-prefix.ts", "../src/auth/users/find-many.ts", "../src/auth/users/name-prefix.ts", "../src/auth/users/email-move-guard.ts", "../src/auth/users/update.ts", "../src/auth/users/record-flows.ts", "../src/auth/users/type-api.ts", "../src/auth/invitations/write.ts", "../src/auth/invitations/claim.ts", "../src/auth/invitations/events.ts", "../src/auth/invitations/input.ts", "../src/auth/invitations/invited-type.ts", "../src/auth/invitations/find-invitee.ts", "../src/auth/invitations/password-invitee.ts", "../src/auth/invitations/passwordless-invitee.ts", "../src/auth/invitations/invitee.ts", "../src/auth/invitations/to-invitation.ts", "../src/auth/invitations/accept.ts", "../src/auth/invitations/change-pending.ts", "../src/auth/invitations/find-pending.ts", "../src/ids/derived.ts", "../src/auth/invitations/history-input.ts", "../src/auth/invitations/history.ts", "../src/auth/invitations/limit.ts", "../src/auth/invitations/issue.ts", "../src/auth/invitations/read.ts", "../src/auth/invitations/preview.ts", "../src/auth/invitations/resend.ts", "../src/auth/invitations/flows.ts", "../src/auth/social/finish.ts", "../src/auth/social/attach.ts", "../src/auth/social/complete-link.ts", "../src/auth/social/provider-call.ts", "../src/auth/social/cookie.ts", "../src/auth/social/find-provider.ts", "../src/auth/social/step-up-request.ts", "../src/auth/social/flow-cookie-value.ts", "../src/auth/social/flow-secret.ts", "../src/auth/social/begin.ts", "../src/auth/social/redeem.ts", "../src/auth/social/link-holder.ts", "../src/auth/social/sign-up.ts", "../src/auth/social/sign-in.ts", "../src/auth/social/step-up-proof.ts", "../src/auth/social/step-up.ts", "../src/auth/social/complete.ts", "../src/auth/social/return-to.ts", "../src/auth/social/types-of.ts", "../src/auth/social/start.ts", "../src/auth/social/unlink.ts", "../src/auth/social/wiring.ts", "../src/auth/social/index.ts", "../src/auth/shared-api.ts", "../src/auth/janus.ts", "../src/auth/parse-sealing-keys.ts", "../src/auth/sealer-for.ts", "../src/background/background.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"/**\n * The device cookie: the long-lived cookie that holds the device token\n * `deviceToken` answers, as the `Set-Cookie` value that sets it and the\n * reading of a `Cookie` header that finds it. The integrations\n * (`@softistx/janus-hono`, `@softistx/janus-graphql`) call these, so they\n * cannot disagree on the cookie they write.\n */\n\n/** The device cookie's name when none is given. */\nexport const DEVICE_COOKIE = 'janus-device';\n\n/** Four hundred days: the longest a browser keeps a cookie. */\nconst MAX_AGE = 400 * 24 * 60 * 60;\n\n/**\n * The long-lived cookie that holds the device token `@softistx/janus` answers\n * as `deviceToken`. Every default is the strict one, as for the session\n * cookie; give `deviceFromCookieHeader` and `deviceCookie` the same options.\n */\nexport interface DeviceCookieOptions {\n\t/** `'janus-device'` when absent. */\n\treadonly name?: string;\n\treadonly domain?: string;\n\t/** `'/'` when absent. */\n\treadonly path?: string;\n\t/** `'Lax'` when absent. */\n\treadonly sameSite?: 'Lax' | 'Strict' | 'None';\n\t/** `true` when absent. */\n\treadonly secure?: boolean;\n\t/**\n\t * In seconds, rounded down. Four hundred days when absent — the longest a\n\t * browser keeps one. `deviceCookie` throws a `RangeError` for a value that\n\t * is not finite, is negative, or is above 34560000.\n\t */\n\treadonly maxAge?: number;\n}\n\n/** The cookie names RFC 6265 allows, as Hono's `setCookie` checks them. */\nconst NAME = /^[\\w!#$%&'*.^`|~+-]+$/;\n\n/** The raw value of the cookie `name` in a `Cookie` header, or `null`. */\nfunction rawValue(header: string, name: string): string | null {\n\tfor (const pair of header.split(';')) {\n\t\tconst at = pair.indexOf('=');\n\t\tif (at !== -1 && pair.slice(0, at).trim() === name) {\n\t\t\treturn pair.slice(at + 1).trim();\n\t\t}\n\t}\n\treturn null;\n}\n\n/**\n * The device token a request's `Cookie` header holds, or `null` when it holds\n * none or an empty one: what a sign-in takes as `device`. One pair of\n * surrounding double quotes is dropped and percent escapes are decoded; a\n * malformed escape answers the value as it came.\n *\n * ```ts\n * const device = deviceFromCookieHeader(request.headers.get('cookie'));\n * ```\n */\nexport function deviceFromCookieHeader(\n\theader: string | null | undefined,\n\toptions: DeviceCookieOptions = {},\n): string | null {\n\tif (header === null || header === undefined) return null;\n\tconst raw = rawValue(header, options.name ?? DEVICE_COOKIE);\n\tif (raw === null) return null;\n\tconst value =\n\t\traw.length >= 2 && raw.startsWith('\"') && raw.endsWith('\"')\n\t\t\t? raw.slice(1, -1)\n\t\t\t: raw;\n\tif (value === '') return null;\n\ttry {\n\t\treturn decodeURIComponent(value);\n\t} catch {\n\t\treturn value;\n\t}\n}\n\n/**\n * The `Set-Cookie` value that sets the device cookie, or sets it again so it\n * lasts another `maxAge`. Append it to the response, beside any other cookie.\n * Throws what Hono's `setCookie` refuses: a `TypeError` for an invalid name, a\n * `__Secure-` or `__Host-` name without its terms, or a `;`, CR or LF in\n * `domain`, `path` or `sameSite`; a `RangeError` for a `maxAge` a browser\n * would not keep.\n *\n * ```ts\n * headers.append('Set-Cookie', deviceCookie(signedIn.deviceToken));\n * ```\n */\nexport function deviceCookie(\n\tdeviceToken: string,\n\toptions: DeviceCookieOptions = {},\n): string {\n\tconst name = options.name ?? DEVICE_COOKIE;\n\tconst secure = options.secure ?? true;\n\tconst path = options.path ?? '/';\n\tconst maxAge = options.maxAge ?? MAX_AGE;\n\tif (!NAME.test(name)) {\n\t\tthrow new TypeError(\n\t\t\t`deviceCookie(): name '${name}' is not a valid cookie name`,\n\t\t);\n\t}\n\tif (name.startsWith('__Secure-') && !secure) {\n\t\tthrow new TypeError(\n\t\t\t'deviceCookie(): a __Secure- cookie must have secure: true',\n\t\t);\n\t}\n\tif (name.startsWith('__Host-')) {\n\t\tif (!secure) {\n\t\t\tthrow new TypeError(\n\t\t\t\t'deviceCookie(): a __Host- cookie must have secure: true',\n\t\t\t);\n\t\t}\n\t\tif (path !== '/') {\n\t\t\tthrow new TypeError(\n\t\t\t\t\"deviceCookie(): a __Host- cookie must have path: '/'\",\n\t\t\t);\n\t\t}\n\t\tif (options.domain) {\n\t\t\tthrow new TypeError(\n\t\t\t\t'deviceCookie(): a __Host- cookie must have no domain',\n\t\t\t);\n\t\t}\n\t}\n\tfor (const [key, value] of [\n\t\t['domain', options.domain],\n\t\t['path', options.path],\n\t\t['sameSite', options.sameSite],\n\t] as const) {\n\t\tif (value && /[;\\r\\n]/.test(value)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`deviceCookie(): ${key} must not contain ';', '\\\\r' or '\\\\n'`,\n\t\t\t);\n\t\t}\n\t}\n\tif (!Number.isFinite(maxAge) || maxAge < 0 || maxAge > MAX_AGE) {\n\t\tthrow new RangeError(\n\t\t\t`deviceCookie(): maxAge must be a number of seconds from 0 to ${MAX_AGE} (400 days), got ${maxAge}`,\n\t\t);\n\t}\n\treturn [\n\t\t`${name}=${encodeURIComponent(deviceToken)}`,\n\t\t`Max-Age=${Math.floor(maxAge)}`,\n\t\t...(options.domain ? [`Domain=${options.domain}`] : []),\n\t\t...(path ? [`Path=${path}`] : []),\n\t\t'HttpOnly',\n\t\t...(secure ? ['Secure'] : []),\n\t\t`SameSite=${options.sameSite ?? 'Lax'}`,\n\t].join('; ');\n}\n",
|
|
6
|
+
"import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto';\nimport { concurrencyOf, limit } from './concurrency-limit';\nimport type { PasswordHasher } from './config';\n\n/**\n * scrypt through `node:crypto` — the hasher that runs **everywhere**: Node and\n * Bun both implement it, and it needs no dependency.\n *\n * Measured before choosing it: `bun build --target node` leaves `Bun.password`\n * in the output as it is — a target changes the bundle's format, not which\n * APIs exist — and `crypto.argon2` is absent from Node 22. scrypt is the one\n * memory-hard function both runtimes ship.\n *\n * The defaults are OWASP's: N = 2^17, r = 8, p = 1, about 128 MiB per hash.\n * The parameters are written into the hash —\n * `$scrypt$ln=17,r=8,p=1$<salt>$<key>` — and read back from it to verify, so\n * raising `cost` later leaves every existing hash readable.\n *\n * `cost` is log2(N). Lower it only in tests: 10 is fast and still exercises\n * every line.\n *\n * **Concurrency.** Each call holds about 128 MiB while it runs, so a burst of\n * verifies — a credential-stuffing run, including the dummy verify of an unknown\n * e-mail — would otherwise allocate without bound. `concurrency` caps how many\n * `hash` and `verify` calls run at once, per hasher (default 2, about 256 MiB);\n * calls past the cap wait their turn, in order. The application's sign-in\n * throttle still applies on top.\n *\n * A hash written with other parameters than these is rewritten with these the\n * next time its owner signs in (`needsRehash`), so raising `cost` reaches every\n * active user without a migration.\n */\nexport function scryptHasher(options?: {\n\treadonly cost?: number;\n\treadonly concurrency?: number;\n}): PasswordHasher {\n\tconst cost = options?.cost ?? 17;\n\tif (!Number.isInteger(cost) || cost < 10 || cost > 20) {\n\t\tthrow new TypeError(\n\t\t\t'scryptHasher: cost is log2(N), an integer from 10 to 20 — 17 is the recommended value',\n\t\t);\n\t}\n\n\tconst run = limit(concurrencyOf('scryptHasher', options?.concurrency, 2));\n\n\treturn {\n\t\tprefix: SCRYPT_PREFIX,\n\t\thash: (plain) =>\n\t\t\trun(async () => {\n\t\t\t\tconst salt = randomBytes(16);\n\t\t\t\tconst key = await derive(plain, salt, cost, 8, 1);\n\t\t\t\treturn `${SCRYPT_PREFIX}ln=${cost},r=8,p=1$${salt.toString('base64')}$${key.toString('base64')}`;\n\t\t\t}),\n\t\tverify: (plain, hash) =>\n\t\t\trun(async () => {\n\t\t\t\tconst parsed = SCRYPT_HASH.exec(hash);\n\t\t\t\t// A hash this hasher cannot parse is not a wrong password, and not\n\t\t\t\t// something to guess at: the core picked this verifier by prefix, so\n\t\t\t\t// the stored hash is corrupt.\n\t\t\t\tif (parsed === null) {\n\t\t\t\t\tthrow new TypeError(\n\t\t\t\t\t\t'scryptHasher: the stored hash has the $scrypt$ prefix and not its format',\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst [, ln, r, p, salt, key] = parsed as unknown as [\n\t\t\t\t\tstring,\n\t\t\t\t\tstring,\n\t\t\t\t\tstring,\n\t\t\t\t\tstring,\n\t\t\t\t\tstring,\n\t\t\t\t\tstring,\n\t\t\t\t];\n\t\t\t\tconst expected = Buffer.from(key, 'base64');\n\t\t\t\tconst actual = await derive(\n\t\t\t\t\tplain,\n\t\t\t\t\tBuffer.from(salt, 'base64'),\n\t\t\t\t\tNumber(ln),\n\t\t\t\t\tNumber(r),\n\t\t\t\t\tNumber(p),\n\t\t\t\t\texpected.length,\n\t\t\t\t);\n\t\t\t\treturn timingSafeEqual(actual, expected);\n\t\t\t}),\n\t\tneedsRehash(hash) {\n\t\t\tconst parsed = SCRYPT_HASH.exec(hash);\n\t\t\t// Unparseable is verify's refusal to make, not a reason to rewrite.\n\t\t\tif (parsed === null) return false;\n\t\t\tconst [, ln, r, p] = parsed;\n\t\t\treturn Number(ln) !== cost || r !== '8' || p !== '1';\n\t\t},\n\t};\n}\n\nconst SCRYPT_PREFIX = '$scrypt$';\nconst SCRYPT_HASH =\n\t/^\\$scrypt\\$ln=(\\d+),r=(\\d+),p=(\\d+)\\$([A-Za-z0-9+/=]+)\\$([A-Za-z0-9+/=]+)$/;\n\nfunction derive(\n\tplain: string,\n\tsalt: Buffer,\n\tln: number,\n\tr: number,\n\tp: number,\n\tlength = 32,\n): Promise<Buffer> {\n\t// Node's camelCase aliases for N, r and p: this repository has no other\n\t// casing, and Node accepts both spellings.\n\tconst n = 2 ** ln;\n\treturn new Promise((resolve, reject) => {\n\t\t// maxmem: Node's default (32 MiB) is below what N = 2^17, r = 8 needs.\n\t\t// `error` is null on Node and undefined on Bun when there is none —\n\t\t// measured: testing `=== null` rejected every hash under Bun.\n\t\tscrypt(\n\t\t\tplain,\n\t\t\tsalt,\n\t\t\tlength,\n\t\t\t{ cost: n, blockSize: r, parallelization: p, maxmem: 256 * n * r },\n\t\t\t(error, key) => (error ? reject(error) : resolve(key)),\n\t\t);\n\t});\n}\n\n/**\n * argon2id through `Bun.password`.\n *\n * **Loaded only when named**: nothing reads `Bun` until this function is called,\n * so the package imports cleanly under Node. On Node, `scryptHasher()` is the\n * hasher; a hash written here reads anywhere a verifier for `$argon2id$` is\n * wired, so a database can move between the two runtimes.\n *\n * **Concurrency.** Each call holds 64 MiB (`memoryCost`) while it runs, so a\n * burst of verifies — a credential-stuffing run, including the dummy verify of\n * an unknown e-mail — would otherwise allocate without bound. `concurrency`\n * caps how many `hash` and `verify` calls run at once, per hasher (default 4,\n * about 256 MiB); calls past the cap wait their turn, in order. The\n * application's sign-in throttle still applies on top.\n */\nexport function bunHasher(options?: {\n\treadonly concurrency?: number;\n}): PasswordHasher {\n\tconst run = limit(concurrencyOf('bunHasher', options?.concurrency, 4));\n\n\t// `typeof` on an undeclared global is 'undefined' rather than a throw, so\n\t// this line is safe under Node.\n\tconst password: BunPassword | undefined =\n\t\ttypeof Bun === 'undefined' ? undefined : Bun.password;\n\n\tif (password === undefined) {\n\t\tthrow new TypeError(\n\t\t\t'bunHasher: Bun.password is not available — this runtime is not Bun; wire scryptHasher() instead',\n\t\t);\n\t}\n\n\treturn {\n\t\tprefix: '$argon2id$',\n\t\thash: (plain) => run(() => password.hash(plain, ARGON2ID)),\n\t\tverify: (plain, hash) => run(() => password.verify(plain, hash)),\n\t\tneedsRehash: (hash) => !hash.startsWith(ARGON2ID_PARAMETERS),\n\t};\n}\n\n/**\n * Pinned rather than left to `Bun.password`'s defaults — which they equal\n * today, measured: `$argon2id$v=19$m=65536,t=2,p=1$` — so that a change of\n * default in a Bun release is a rehash this package decided, not one it\n * inherited.\n */\nconst ARGON2ID = {\n\talgorithm: 'argon2id',\n\tmemoryCost: 65_536,\n\ttimeCost: 2,\n} as const;\nconst ARGON2ID_PARAMETERS = '$argon2id$v=19$m=65536,t=2,p=1$';\n\ninterface BunPassword {\n\thash(plain: string, options: typeof ARGON2ID): Promise<string>;\n\tverify(plain: string, hash: string): Promise<boolean>;\n}\n",
|
|
7
|
+
"/**\n * A FIFO semaphore: `limit(n)` returns a function that runs a task at once\n * while fewer than `n` run, and queues it otherwise. The next queued task\n * starts as soon as a running one settles — resolved, rejected, or thrown\n * synchronously. No dependency.\n */\nexport function limit(\n\tconcurrency: number,\n): <T>(task: () => Promise<T>) => Promise<T> {\n\tlet running = 0;\n\tconst waiting: Array<() => void> = [];\n\n\tconst release = (): void => {\n\t\tconst next = waiting.shift();\n\t\tif (next === undefined) running -= 1;\n\t\t// The slot passes straight to the next task: `running` is unchanged.\n\t\telse next();\n\t};\n\n\tconst run = async <T>(task: () => Promise<T>): Promise<T> => {\n\t\ttry {\n\t\t\treturn await task();\n\t\t} finally {\n\t\t\trelease();\n\t\t}\n\t};\n\n\treturn async <T>(task: () => Promise<T>): Promise<T> => {\n\t\tif (running < concurrency) {\n\t\t\trunning += 1;\n\t\t\treturn run(task);\n\t\t}\n\t\tawait new Promise<void>((resolve) => waiting.push(resolve));\n\t\treturn run(task);\n\t};\n}\n\n/**\n * Reads a hasher's `concurrency` option: an integer from 1 to 64, or the\n * hasher's default when left out.\n */\nexport function concurrencyOf(\n\thasher: string,\n\tvalue: number | undefined,\n\tfallback: number,\n): number {\n\tconst concurrency = value ?? fallback;\n\tif (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 64) {\n\t\tthrow new TypeError(\n\t\t\t`${hasher}: concurrency is how many hashes may run at once, an integer from 1 to 64 — ${fallback} is the default`,\n\t\t);\n\t}\n\treturn concurrency;\n}\n",
|
|
8
|
+
"/**\n * Where `now` comes from.\n *\n * Injected rather than read from `Date` directly, for one practical reason:\n * every expiry in this package — sessions, one-time tokens, refresh windows —\n * is a comparison against the current time, and a spec that has to move the\n * real clock to test one is a spec that needs fake timers, leaks them, and\n * fails differently under load. A `Clock` makes those specs synchronous and\n * exact.\n *\n * It is also the seam an application needs if it ever has to reason about a\n * store's clock rather than its own: MongoDB stamps a TTL against the server's\n * time, not the process's.\n */\nexport interface Clock {\n\tnow(): Date;\n}\n\n/** The process's own clock. The default everywhere. */\nexport const systemClock: Clock = {\n\tnow: () => new Date(),\n};\n\n/**\n * A clock a spec drives by hand.\n *\n * Shipped rather than kept in `test/`: a consumer writing their own tests\n * against this package needs exactly this, and writing it again is how two\n * subtly different versions of \"advance time\" come to exist.\n */\nexport function fixedClock(start: Date | number = 0): Clock & {\n\tadvance(ms: number): void;\n\tset(at: Date | number): void;\n} {\n\tlet ms = start instanceof Date ? start.getTime() : start;\n\n\treturn {\n\t\tnow: () => new Date(ms),\n\t\tadvance: (by) => {\n\t\t\tms += by;\n\t\t},\n\t\tset: (at) => {\n\t\t\tms = at instanceof Date ? at.getTime() : at;\n\t\t},\n\t};\n}\n",
|
|
9
|
+
"/**\n * A span of time, written the way a configuration file writes one: `'15m'`,\n * `'720h'`, `'30d'`. A plain number is milliseconds.\n *\n * Strings rather than milliseconds everywhere, because `2592000000` in a config\n * object is a number nobody reads back correctly, and Ory's own configuration\n * uses exactly this notation — so a team moving across recognises it.\n */\nexport type Duration = number | `${number}${'ms' | 's' | 'm' | 'h' | 'd'}`;\n\nconst UNITS = {\n\tms: 1,\n\ts: 1_000,\n\tm: 60_000,\n\th: 3_600_000,\n\td: 86_400_000,\n} as const;\n\nconst PATTERN = /^(\\d+(?:\\.\\d+)?)(ms|s|m|h|d)$/;\n\n/**\n * The duration in milliseconds.\n *\n * `where` names the option the consumer wrote — `session.lifespan`, not\n * `parseDuration` — because this package has half a dozen durations and a\n * message that does not say which one leaves the reader to guess.\n *\n * A bare `TypeError`: durations are written when the application is wired, so\n * this cannot come from a request, and no handler should answer it. The refusal\n * reports the **shape** expected and not the value's own bytes beyond echoing\n * it, which is the rule this repository inherits.\n */\nexport function parseDuration(value: Duration, where: string): number {\n\tif (typeof value === 'number') {\n\t\tif (!Number.isFinite(value) || value <= 0) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${where}: a duration in milliseconds must be a finite number above zero`,\n\t\t\t);\n\t\t}\n\t\treturn value;\n\t}\n\n\tconst match = PATTERN.exec(value);\n\n\tif (!match) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: \"${value}\" is not a duration; write a number followed by ms, s, m, h or d — for example \"15m\" or \"720h\"`,\n\t\t);\n\t}\n\n\tconst amount = Number(match[1]);\n\tconst unit = match[2] as keyof typeof UNITS;\n\tconst ms = amount * UNITS[unit];\n\n\tif (ms <= 0) {\n\t\tthrow new TypeError(`${where}: a duration must be above zero`);\n\t}\n\n\treturn ms;\n}\n",
|
|
10
|
+
"import type { Clock } from '../../time/clock';\n\ninterface Entry<V> {\n\treadonly version: string;\n\treadonly value: V;\n\tusedAt: number;\n}\n\nexport interface IssuerCache<V> {\n\t/** The value kept for this issuer at this version (and marks it used), or `undefined`. */\n\tget(issuer: string, version: string): V | undefined;\n\t/** Keeps a value, replacing the issuer's entry, and drops the least recently used past `max`. */\n\tset(issuer: string, version: string, value: V): void;\n\t/** Drops the issuer's entry, only if it still holds `value` when one is given. */\n\tdelete(issuer: string, value?: V): void;\n}\n\nexport interface IssuerCacheOptions {\n\treadonly max: number;\n\treadonly idleMs: number;\n\treadonly clock: Clock;\n}\n\n/**\n * An LRU map with an idle limit, without a timer: the order of a `Map` is\n * the recency, and an entry unused for `idleMs` is dropped when it is next\n * looked up or when another is added.\n */\nexport function createIssuerCache<V>(\n\toptions: IssuerCacheOptions,\n): IssuerCache<V> {\n\tconst entries = new Map<string, Entry<V>>();\n\tconst now = (): number => options.clock.now().getTime();\n\tconst expire = (at: number): void => {\n\t\tfor (const [issuer, entry] of entries) {\n\t\t\tif (at - entry.usedAt >= options.idleMs) entries.delete(issuer);\n\t\t}\n\t};\n\treturn {\n\t\tget(issuer, version) {\n\t\t\tconst at = now();\n\t\t\texpire(at);\n\t\t\tconst entry = entries.get(issuer);\n\t\t\tif (entry === undefined || entry.version !== version) return undefined;\n\t\t\tentry.usedAt = at;\n\t\t\tentries.delete(issuer);\n\t\t\tentries.set(issuer, entry);\n\t\t\treturn entry.value;\n\t\t},\n\t\tset(issuer, version, value) {\n\t\t\tconst at = now();\n\t\t\texpire(at);\n\t\t\tentries.delete(issuer);\n\t\t\tentries.set(issuer, { version, value, usedAt: at });\n\t\t\tfor (const oldest of entries.keys()) {\n\t\t\t\tif (entries.size <= options.max) break;\n\t\t\t\tentries.delete(oldest);\n\t\t\t}\n\t\t},\n\t\tdelete(issuer, value) {\n\t\t\tconst entry = entries.get(issuer);\n\t\t\tif (\n\t\t\t\tentry !== undefined &&\n\t\t\t\t(value === undefined || entry.value === value)\n\t\t\t) {\n\t\t\t\tentries.delete(issuer);\n\t\t\t}\n\t\t},\n\t};\n}\n",
|
|
11
|
+
"import { systemClock } from '../../time/clock';\nimport { parseDuration } from '../../time/duration';\nimport { createIssuerCache } from './cache';\nimport type {\n\tJanusIssuerKey,\n\tJanusIssuers,\n\tJanusIssuersOptions,\n} from './types';\n\n/**\n * Several issuers (tenants) in one process, one `janus()` instance each, built\n * when a request first needs it and kept in a bounded in-process cache.\n *\n * ```ts\n * const issuers = createJanusIssuers({\n * resolve: (request) => tenants.byHost(new URL(request.url).host), // { issuer, version } or null\n * build: (tenant) => janus({ user, store: stores.for(tenant.issuer), hasher }),\n * });\n * const auth = await issuers.forRequest(request); // null: no such issuer\n * ```\n *\n * Wrong options are a `TypeError` at wiring time; a `resolve` or `build`\n * failure rejects the request and its build is not kept.\n */\nexport function createJanusIssuers<T extends JanusIssuerKey, A>(\n\toptions: JanusIssuersOptions<T, A>,\n): JanusIssuers<A> {\n\tif (typeof options.resolve !== 'function') {\n\t\tthrow new TypeError('createJanusIssuers: resolve must be a function');\n\t}\n\tif (typeof options.build !== 'function') {\n\t\tthrow new TypeError('createJanusIssuers: build must be a function');\n\t}\n\tconst max = options.cache?.max ?? 100;\n\tif (!Number.isInteger(max) || max < 1) {\n\t\tthrow new TypeError(\n\t\t\t'createJanusIssuers: cache.max must be a positive integer',\n\t\t);\n\t}\n\tconst cache = createIssuerCache<Promise<A>>({\n\t\tmax,\n\t\tidleMs: parseDuration(options.cache?.idle ?? '1h', 'cache.idle'),\n\t\tclock: options.clock ?? systemClock,\n\t});\n\n\treturn {\n\t\tasync forRequest(request) {\n\t\t\tconst resolved = await options.resolve(request);\n\t\t\tif (resolved === null) return null;\n\t\t\tif (\n\t\t\t\ttypeof resolved !== 'object' ||\n\t\t\t\ttypeof resolved.issuer !== 'string' ||\n\t\t\t\tresolved.issuer === '' ||\n\t\t\t\ttypeof resolved.version !== 'string'\n\t\t\t) {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t'createJanusIssuers: resolve must answer null or { issuer, version } with two strings',\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst kept = cache.get(resolved.issuer, resolved.version);\n\t\t\tif (kept !== undefined) return kept;\n\t\t\t// `Promise.resolve().then` so a `build` that throws synchronously rejects too.\n\t\t\tconst pending = Promise.resolve().then(() => options.build(resolved));\n\t\t\tcache.set(resolved.issuer, resolved.version, pending);\n\t\t\tpending.catch(() => cache.delete(resolved.issuer, pending));\n\t\t\treturn pending;\n\t\t},\n\t\tevict: (issuer) => cache.delete(issuer),\n\t};\n}\n",
|
|
12
|
+
"/**\n * What every operation of the core is handed: the resolved configuration, the\n * guarded stores, the clock, the hashers and the events listener.\n */\n\nimport { mintId } from '../../ids/id';\nimport type { RelationStore } from '../../permissions/port/types';\nimport type { Clock } from '../../time/clock';\nimport type { PasswordHasher, ResolvedConfig } from '../config';\nimport type { UserEventListener } from '../events';\nimport type {\n\tApiKeyStore,\n\tInvitationStore,\n\tJanusStores,\n\tStoreCapabilities,\n} from '../port/types';\n\nexport interface Context {\n\treadonly config: ResolvedConfig;\n\t/** Already guarded, by `src/stores/guard.ts`. */\n\treadonly store: JanusStores;\n\t/** Already guarded. `null` when no relation store is wired. */\n\treadonly relations: RelationStore | null;\n\treadonly capabilities: StoreCapabilities;\n\treadonly clock: Clock;\n\treadonly hasher: PasswordHasher | null;\n\t/** The hasher first, then every verifier: whoever claims a prefix verifies it. */\n\treadonly verifiers: readonly PasswordHasher[];\n\t/** Hashed once, lazily: what a missing user's password is compared against. */\n\tdummyHash(): Promise<string>;\n\t/** What `janus({ events })` was given, or `null`. */\n\treadonly events: UserEventListener | null;\n\t/** Already guarded. `null` without `janus({ apiKeys })`. */\n\treadonly apiKeys: ApiKeyStore | null;\n\t/** Already guarded. `null` without `janus({ invitations })`. */\n\treadonly invitations: InvitationStore | null;\n}\n\nexport function createContext(\n\tconfig: ResolvedConfig,\n\tstore: JanusStores,\n\trelations: RelationStore | null,\n\tcapabilities: StoreCapabilities,\n\tclock: Clock,\n\thasher: PasswordHasher | null,\n\tverifiers: readonly PasswordHasher[],\n\tevents: UserEventListener | null = null,\n\tapiKeys: ApiKeyStore | null = null,\n\tinvitations: InvitationStore | null = null,\n): Context {\n\tlet dummy: Promise<string> | null = null;\n\n\treturn {\n\t\tconfig,\n\t\tstore,\n\t\trelations,\n\t\tcapabilities,\n\t\tclock,\n\t\thasher,\n\t\tverifiers,\n\t\tevents,\n\t\tapiKeys,\n\t\tinvitations,\n\t\tdummyHash: () => {\n\t\t\tif (hasher === null) {\n\t\t\t\tthrow new TypeError('janus: no hasher to compare a dummy hash with');\n\t\t\t}\n\t\t\tdummy ??= hasher.hash(`janus-dummy-${mintId()}`);\n\t\t\treturn dummy;\n\t\t},\n\t};\n}\n",
|
|
13
|
+
"/**\n * How a login, and an e-mail, is normalised before any store sees it: the\n * rules `password.normalize` may name, and the one an e-mail always uses.\n */\n\n/**\n * How a login is normalised before any store sees it. `'lowercaseTrim'` when\n * absent — right for an e-mail and for most usernames.\n *\n * A function is accepted for anything else. It must be deterministic: the same\n * rule normalises at sign-up and at sign-in.\n */\nexport type Normalize =\n\t| 'none'\n\t| 'lowercase'\n\t| 'lowercaseTrim'\n\t| 'nfkcLowercaseTrim'\n\t| ((value: string) => string);\n\nconst NORMALIZERS = {\n\tnone: (value: string) => value,\n\tlowercase: (value: string) => value.toLowerCase(),\n\tlowercaseTrim: (value: string) => value.toLowerCase().trim(),\n\tnfkcLowercaseTrim: (value: string) =>\n\t\tvalue.normalize('NFKC').toLowerCase().trim(),\n} as const satisfies Record<string, (value: string) => string>;\n\n/** How an e-mail is compared: always the same rule, whatever the login's. */\nexport const normalizeEmail = NORMALIZERS.lowercaseTrim;\n\n/** The function a {@link Normalize} rule names, or a wiring refusal. */\nexport function normalizer(\n\trule: Normalize,\n\twhere: string,\n): (value: string) => string {\n\tif (typeof rule === 'function') return rule;\n\tif (typeof rule === 'string' && Object.hasOwn(NORMALIZERS, rule)) {\n\t\treturn NORMALIZERS[rule];\n\t}\n\n\tthrow new TypeError(\n\t\t`${where} must be \"none\", \"lowercase\", \"lowercaseTrim\", \"nfkcLowercaseTrim\" or a function`,\n\t);\n}\n\n/** How many characters of a display name its search key keeps. */\nexport const NAME_KEY_LENGTH = 128;\n\n/**\n * How a display name, and a `namePrefix`, are folded before any store sees\n * them: NFKC, lowercased, trimmed, runs of white space reduced to one space,\n * cut to {@link NAME_KEY_LENGTH} characters. The same rule on both sides, so\n * the store compares bytes.\n */\nexport function foldName(value: string): string {\n\tconst folded = value\n\t\t.normalize('NFKC')\n\t\t.toLowerCase()\n\t\t.replace(/\\s+/gu, ' ')\n\t\t.trim();\n\treturn Array.from(folded).slice(0, NAME_KEY_LENGTH).join('');\n}\n",
|
|
14
|
+
"/**\n * The names `janus` keeps for itself: the single-type form's type name, the\n * keys it sets on every user, and the methods on its answer.\n */\n\n/** The type name the single-type form gives its users. */\nexport const SINGLE_TYPE = 'user';\n\n/**\n * Keys `janus` sets on every user, so a schema may not declare them.\n * `password` too: it is taken beside the fields, and never stored among them.\n */\nexport const RESERVED_FIELDS = [\n\t'id',\n\t'type',\n\t'emailVerified',\n\t'active',\n\t'hasPassword',\n\t'hasSecondFactor',\n\t'avatar',\n\t'version',\n\t'createdAt',\n\t'updatedAt',\n\t'password',\n] as const;\n\n/** Names on `janus()`'s answer, so a user type may not take one. */\nexport const RESERVED_TYPES = [\n\t'authenticate',\n\t'signOut',\n\t'signOutEverywhere',\n\t'sessions',\n\t'findUser',\n\t'getUser',\n\t'cookie',\n\t'collectExpired',\n\t'types',\n\t'avatar',\n\t'changeEmail',\n\t'verifyEmail',\n\t'resetPassword',\n\t'apiKeys',\n\t'invitations',\n\t'social',\n] as const;\n",
|
|
15
|
+
"/**\n * The names a configuration gives: a user type's, and the fields it points\n * at — each camelCase, and none of them one `janus` sets itself.\n */\n\nimport { RESERVED_FIELDS } from './reserved';\n\n/** A type name, or a field name: camelCase, as every key in this package. */\nexport const NAME = /^[A-Za-z][A-Za-z0-9]*$/;\n\n/** The field a configuration key names, or a wiring refusal. */\nexport function fieldName(field: unknown, where: string): string {\n\tif (typeof field !== 'string' || !NAME.test(field)) {\n\t\tthrow new TypeError(\n\t\t\t`${where} must name a top-level field of the schema, such as \"email\"`,\n\t\t);\n\t}\n\tif ((RESERVED_FIELDS as readonly string[]).includes(field)) {\n\t\tthrow new TypeError(`${where}: \"${field}\" is a field janus sets itself`);\n\t}\n\treturn field;\n}\n",
|
|
16
|
+
"/** Resolves `apiKeys`: the token prefix, the lifetimes and the limits, each refused at wiring when it cannot work. */\n\nimport { type Duration, parseDuration } from '../../time/duration';\nimport type { ApiKeysConfig } from './api-keys-config';\nimport type { ResolvedConfig, ResolvedType } from './resolved-config';\n\nconst PREFIX = /^[a-z][a-z0-9]{0,15}_$/;\nconst DAY_MS = 86_400_000;\n\nexport function resolveApiKeys(\n\tconfig: ApiKeysConfig | undefined,\n\ttypes: ReadonlyMap<string, ResolvedType>,\n\twhere: string,\n): ResolvedConfig['apiKeys'] {\n\tif (config === undefined) return null;\n\tconst at = `${where}: apiKeys`;\n\tif (typeof config !== 'object' || config === null) {\n\t\tthrow new TypeError(`${at} must be an object`);\n\t}\n\n\tif (typeof config.prefix !== 'string' || !PREFIX.test(config.prefix)) {\n\t\tthrow new TypeError(\n\t\t\t`${at}.prefix must be lowercase letters and digits, starting with a letter, at most 16 characters, ending in \"_\" — for example \"sl_\"`,\n\t\t);\n\t}\n\n\tif (!Array.isArray(config.lifetimes) || config.lifetimes.length === 0) {\n\t\tthrow new TypeError(\n\t\t\t`${at}.lifetimes must list at least one lifetime: there is no default and no key without an expiry`,\n\t\t);\n\t}\n\tconst lifetimesMs = (config.lifetimes as readonly Duration[]).map((value) => {\n\t\tconst ms = parseDuration(value, `${at}.lifetimes`);\n\t\tif (ms < DAY_MS) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${at}.lifetimes: \"${String(value)}\" is under one day; a key lives at least \"1d\"`,\n\t\t\t);\n\t\t}\n\t\treturn ms;\n\t});\n\n\tconst maxActive = config.maxActive ?? 10;\n\tif (!Number.isInteger(maxActive) || maxActive < 1 || maxActive > 100) {\n\t\tthrow new TypeError(`${at}.maxActive must be an integer from 1 to 100`);\n\t}\n\n\tconst revokeOnPasswordReset = config.revokeOnPasswordReset ?? true;\n\tif (typeof revokeOnPasswordReset !== 'boolean') {\n\t\tthrow new TypeError(`${at}.revokeOnPasswordReset must be a boolean`);\n\t}\n\n\treturn {\n\t\tprefix: config.prefix,\n\t\tlifetimesMs,\n\t\tmaxActive,\n\t\tfreshWithinMs: parseDuration(\n\t\t\tconfig.freshWithin ?? '10m',\n\t\t\t`${at}.freshWithin`,\n\t\t),\n\t\tlastUsedEveryMs: parseDuration(\n\t\t\tconfig.lastUsedEvery ?? '1h',\n\t\t\t`${at}.lastUsedEvery`,\n\t\t),\n\t\ttypes: allowedTypes(config.types, types, at),\n\t\trevokeOnPasswordReset,\n\t};\n}\n\nfunction allowedTypes(\n\tlisted: readonly string[] | undefined,\n\ttypes: ReadonlyMap<string, ResolvedType>,\n\tat: string,\n): ReadonlySet<string> {\n\tif (listed === undefined) return new Set(types.keys());\n\tif (!Array.isArray(listed) || listed.length === 0) {\n\t\tthrow new TypeError(\n\t\t\t`${at}.types must list at least one user type, or be left out for every type`,\n\t\t);\n\t}\n\tfor (const name of listed) {\n\t\tif (!types.has(name)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${at}.types: \"${String(name)}\" is not a user type of this instance`,\n\t\t\t);\n\t\t}\n\t}\n\treturn new Set(listed);\n}\n",
|
|
17
|
+
"/** Resolves the session cookie: the strict defaults, and a name browsers take. */\n\nimport type { CookieConfig } from './janus-config';\nimport type { ResolvedConfig } from './resolved-config';\n\n/** RFC 6265's cookie-name token: no control character, space, or separator. */\nconst COOKIE_NAME = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\n\nexport function resolveCookie(\n\tcookie: CookieConfig,\n\twhere: string,\n): ResolvedConfig['cookie'] {\n\tconst name = cookie.name ?? 'janus-session';\n\tif (!COOKIE_NAME.test(name)) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: cookie.name must be a cookie-name token — letters, digits and !#$%&'*+-.^_\\`|~, with no space, \";\" or \"=\"`,\n\t\t);\n\t}\n\tconst sameSite = cookie.sameSite ?? 'lax';\n\tconst secure = cookie.secure ?? true;\n\tif (sameSite === 'none' && !secure) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: cookie.sameSite \"none\" requires cookie.secure — browsers refuse the cookie otherwise`,\n\t\t);\n\t}\n\n\treturn {\n\t\tname,\n\t\tdomain: cookie.domain ?? null,\n\t\tpath: cookie.path ?? '/',\n\t\tsameSite,\n\t\tsecure,\n\t};\n}\n",
|
|
18
|
+
"import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';\n\n/**\n * A second factor's secret, sealed before any store sees it: AES-256-GCM\n * under a key the application holds, so a dump of the users is not a dump of\n * everyone's authenticator.\n *\n * The sealed form is `v1.<key id>.<iv>.<ciphertext and tag>`, the last two in\n * base64url. It names its key, so keys rotate: the first key seals, every key\n * opens, and a secret sealed under an older one is sealed again under the\n * first the next time a code is accepted. The user's id is the additional\n * data, so a sealed secret copied onto another user does not open.\n */\n\n/** One key, as `janus({ secondFactor: { keys } })` takes it. */\nexport interface SealingKey {\n\t/** Names the key in every secret it seals: letters, digits, `_` and `-`. */\n\treadonly id: string;\n\t/** 32 random bytes, in base64 or base64url: `openssl rand -base64 32`. */\n\treadonly key: string;\n}\n\n/** The keys, decoded and checked: the first seals. */\nexport interface Sealer {\n\treadonly sealWith: string;\n\treadonly keys: ReadonlyMap<string, Buffer>;\n}\n\n/** GCM's tag, always the full 16 bytes: a shorter one is easier to forge. */\nconst TAG_BYTES = 16;\n\nconst KEY_ID = /^[A-Za-z0-9_-]{1,64}$/;\n/** An id this long may be a key written first: it is never echoed. */\nconst KEY_LENGTH = 43;\nconst KEY = /^[A-Za-z0-9+/_-]{43}=?$/;\n\n/** Decodes the keys and refuses what cannot seal. `where` names the option. */\nexport function resolveSealer(keys: unknown, where: string): Sealer {\n\tif (!Array.isArray(keys) || keys.length === 0) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: expected at least one key — [{ id, key }], the first seals`,\n\t\t);\n\t}\n\tconst decoded = new Map<string, Buffer>();\n\tfor (const [index, entry] of (keys as readonly SealingKey[]).entries()) {\n\t\tconst id = entry?.id;\n\t\tif (typeof id !== 'string' || !KEY_ID.test(id)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${where}: every key needs an id of letters, digits, _ and -, at most 64 of them`,\n\t\t\t);\n\t\t}\n\t\t// A swapped entry — key:id — puts key material in the id, so an id that\n\t\t// long is named by its position, never echoed. Ids up to 64 stay valid.\n\t\tconst named =\n\t\t\tid.length >= KEY_LENGTH ? `entry ${index + 1}` : `the key \"${id}\"`;\n\t\tif (decoded.has(id)) {\n\t\t\tthrow new TypeError(\n\t\t\t\tid.length >= KEY_LENGTH\n\t\t\t\t\t? `${where}: entry ${index + 1} has the id of an earlier entry`\n\t\t\t\t\t: `${where}: two keys have the id \"${id}\"`,\n\t\t\t);\n\t\t}\n\t\tconst key = entry.key;\n\t\tif (typeof key !== 'string' || !KEY.test(key)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${where}: ${named} is not 32 bytes in base64 — make one with openssl rand -base64 32`,\n\t\t\t);\n\t\t}\n\t\tdecoded.set(id, Buffer.from(key, 'base64'));\n\t}\n\treturn { sealWith: (keys[0] as SealingKey).id, keys: decoded };\n}\n\n/** Seals `plain` under the first key, bound to `boundTo` — the user's id. */\nexport function seal(sealer: Sealer, plain: string, boundTo: string): string {\n\tconst key = sealer.keys.get(sealer.sealWith) as Buffer;\n\tconst iv = randomBytes(12);\n\tconst cipher = createCipheriv('aes-256-gcm', key, iv);\n\tcipher.setAAD(Buffer.from(boundTo));\n\tconst sealed = Buffer.concat([\n\t\tcipher.update(plain, 'utf8'),\n\t\tcipher.final(),\n\t\tcipher.getAuthTag(),\n\t]);\n\treturn `v1.${sealer.sealWith}.${iv.toString('base64url')}.${sealed.toString('base64url')}`;\n}\n\n/**\n * Opens a sealed secret, and says which key sealed it.\n *\n * Every failure is a **wiring** mistake, a bare `TypeError`: a key taken out\n * of `keys` while secrets it sealed are still stored, or a key changed under\n * the same id. None of them comes from a request.\n */\nfunction open(\n\tsealer: Sealer,\n\tsealed: string,\n\tboundTo: string,\n\twhere: string,\n): Opened | TypeError {\n\tconst parts = sealed.split('.');\n\tconst [version, keyId, iv, body] = parts;\n\tconst bytes = Buffer.from(body ?? '', 'base64url');\n\t// Exactly four parts, and a body longer than its 16-byte tag.\n\tif (\n\t\tparts.length !== 4 ||\n\t\tversion !== 'v1' ||\n\t\tkeyId === undefined ||\n\t\tiv === undefined ||\n\t\tbytes.length <= TAG_BYTES\n\t) {\n\t\treturn new TypeError(`${where}: the stored secret is not a sealed one`);\n\t}\n\tconst key = sealer.keys.get(keyId);\n\tif (key === undefined) {\n\t\treturn new TypeError(\n\t\t\t`${where}: the secret is sealed with the key \"${keyId}\", which secondFactor.keys no longer holds — keep a key until no secret is sealed with it`,\n\t\t);\n\t}\n\ttry {\n\t\tconst decipher = createDecipheriv(\n\t\t\t'aes-256-gcm',\n\t\t\tkey,\n\t\t\tBuffer.from(iv, 'base64url'),\n\t\t\t{ authTagLength: TAG_BYTES },\n\t\t);\n\t\tdecipher.setAAD(Buffer.from(boundTo));\n\t\tdecipher.setAuthTag(bytes.subarray(bytes.length - TAG_BYTES));\n\t\tconst plain = Buffer.concat([\n\t\t\tdecipher.update(bytes.subarray(0, bytes.length - TAG_BYTES)),\n\t\t\tdecipher.final(),\n\t\t]).toString('utf8');\n\t\treturn { plain, keyId };\n\t} catch (cause) {\n\t\treturn new TypeError(\n\t\t\t`${where}: the secret does not open with the key \"${keyId}\" — was that key changed under the same id, or the secret copied from another user?`,\n\t\t\t{ cause },\n\t\t);\n\t}\n}\n\ntype Opened = { readonly plain: string; readonly keyId: string };\n\n/** As {@link unseal}, but a secret that does not open is answered as `null`, for a sweep that counts it and goes on. */\nexport function tryUnseal(\n\tsealer: Sealer,\n\tsealed: string,\n\tboundTo: string,\n\twhere: string,\n): Opened | null {\n\tconst opened = open(sealer, sealed, boundTo, where);\n\treturn opened instanceof TypeError ? null : opened;\n}\n\nexport function unseal(\n\tsealer: Sealer,\n\tsealed: string,\n\tboundTo: string,\n\twhere: string,\n): Opened {\n\tconst opened = open(sealer, sealed, boundTo, where);\n\tif (opened instanceof TypeError) throw opened;\n\treturn opened;\n}\n",
|
|
19
|
+
"/** Resolves the device tokens' keys: the sealer that signs and checks them. */\n\nimport { resolveSealer } from '../sealing';\nimport type { DevicesConfig } from './janus-config';\nimport type { ResolvedConfig } from './resolved-config';\n\nexport function resolveDevices(\n\tconfig: DevicesConfig | undefined,\n\twhere: string,\n): ResolvedConfig['devices'] {\n\tif (config === undefined) return null;\n\t// `?.`: a JavaScript caller's `devices: null` gets resolveSealer's message.\n\treturn { sealer: resolveSealer(config?.keys, `${where}: devices.keys`) };\n}\n",
|
|
20
|
+
"/** Resolves `invitations.type`: the user types an invitation can be for, each refused at wiring when it cannot accept one. */\n\nimport type { ResolvedConfig, ResolvedType } from './resolved-config';\n\n/** The user types listed, in order; the instance's only type when `type` is absent. */\nexport function resolveInvitationTypes(\n\tnamed: unknown,\n\ttypes: ReadonlyMap<string, ResolvedType>,\n\tat: string,\n): NonNullable<ResolvedConfig['invitations']>['types'] {\n\tconst [first, ...rest] = listOf(named, types, at);\n\tif (first === undefined) throw new TypeError(`${at}.type: no user type`);\n\tconst listed: readonly [string, ...string[]] = [first, ...rest];\n\tfor (const name of listed) {\n\t\tconst resolved = types.get(name);\n\t\t// A password is chosen by the invitee, for the address they were invited at; no password, none to choose.\n\t\tif (\n\t\t\tresolved?.password != null &&\n\t\t\tresolved.password.login !== resolved.email\n\t\t) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${at}.type: \"${name}\" must have no password, or sign in with a password whose login is its e-mail — an invitee chooses a password for the address they were invited at`,\n\t\t\t);\n\t\t}\n\t}\n\treturn listed;\n}\n\nfunction listOf(\n\tnamed: unknown,\n\ttypes: ReadonlyMap<string, ResolvedType>,\n\tat: string,\n): readonly string[] {\n\tif (named === undefined) {\n\t\tconst [only, ...others] = types.keys();\n\t\tif (only === undefined || others.length > 0) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${at}.type must name the user type an invitation makes: this instance has several`,\n\t\t\t);\n\t\t}\n\t\treturn [only];\n\t}\n\tconst names = Array.isArray(named) ? (named as unknown[]) : [named];\n\tif (\n\t\tnames.length === 0 ||\n\t\t(typeof named !== 'string' && !Array.isArray(named))\n\t) {\n\t\tthrow new TypeError(\n\t\t\t`${at}.type must be a user type, or a non-empty list of distinct user types`,\n\t\t);\n\t}\n\tconst seen = new Set<string>();\n\tfor (const name of names) {\n\t\tif (typeof name !== 'string' || !types.has(name)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${at}.type: \"${String(name)}\" is not a user type of this instance`,\n\t\t\t);\n\t\t}\n\t\tif (seen.has(name)) {\n\t\t\tthrow new TypeError(`${at}.type: \"${name}\" is listed twice`);\n\t\t}\n\t\tseen.add(name);\n\t}\n\treturn [...seen];\n}\n",
|
|
21
|
+
"/** Resolves `invitations`: the user types, the lifetime and the limit, each refused at wiring when it cannot work. */\n\nimport { parseDuration } from '../../time/duration';\nimport type { InvitationsConfig } from './invitations-config';\nimport { resolveInvitationTypes } from './resolve-invitation-types';\nimport type { ResolvedConfig, ResolvedType } from './resolved-config';\n\nexport function resolveInvitations(\n\tconfig: InvitationsConfig | undefined,\n\ttypes: ReadonlyMap<string, ResolvedType>,\n\twhere: string,\n): ResolvedConfig['invitations'] {\n\tif (config === undefined) return null;\n\tconst at = `${where}: invitations`;\n\tif (typeof config !== 'object' || config === null) {\n\t\tthrow new TypeError(`${at} must be an object`);\n\t}\n\n\tif (typeof config.create !== 'function') {\n\t\tthrow new TypeError(\n\t\t\t`${at}.create must be a function that returns the fields of the user an invitation makes`,\n\t\t);\n\t}\n\tif (typeof config.onAccepted !== 'function') {\n\t\tthrow new TypeError(\n\t\t\t`${at}.onAccepted must be a function: where the application adds the new user to the scope`,\n\t\t);\n\t}\n\tif (\n\t\tconfig.beforeAccept !== undefined &&\n\t\ttypeof config.beforeAccept !== 'function'\n\t) {\n\t\tthrow new TypeError(\n\t\t\t`${at}.beforeAccept must be a function that may refuse an acceptance`,\n\t\t);\n\t}\n\tif (config.events !== undefined && typeof config.events !== 'function') {\n\t\tthrow new TypeError(\n\t\t\t`${at}.events must be a function that takes an invitation event`,\n\t\t);\n\t}\n\n\tconst maxPending = config.maxPending;\n\tif (\n\t\tmaxPending !== undefined &&\n\t\t(!Number.isInteger(maxPending) || maxPending < 1 || maxPending > 10_000)\n\t) {\n\t\tthrow new TypeError(`${at}.maxPending must be an integer from 1 to 10000`);\n\t}\n\n\tconst names = resolveInvitationTypes(config.type, types, at);\n\n\treturn {\n\t\ttypes: names,\n\t\tlifetimeMs: parseDuration(config.lifetime ?? '7d', `${at}.lifetime`),\n\t\tmaxPending: maxPending ?? null,\n\t\tcreate: config.create,\n\t\tbeforeAccept: config.beforeAccept ?? null,\n\t\tonAccepted: config.onAccepted,\n\t\tevents: config.events ?? null,\n\t};\n}\n",
|
|
22
|
+
"/** Resolves `magicLink`: on unless `enabled` is `false`; a malformed value is refused rather than left on. */\n\nimport type { MagicLinkConfig } from './magic-link-config';\n\nexport function resolveMagicLink(\n\tconfig: MagicLinkConfig | undefined,\n\twhere: string,\n): boolean {\n\tif (config === undefined) return true;\n\tif (typeof config !== 'object' || config === null) {\n\t\tthrow new TypeError(`${where}: magicLink must be an object — { enabled }`);\n\t}\n\tconst enabled = config.enabled === undefined ? true : config.enabled;\n\tif (typeof enabled !== 'boolean') {\n\t\tthrow new TypeError(`${where}: magicLink.enabled must be a boolean`);\n\t}\n\treturn enabled;\n}\n",
|
|
23
|
+
"/** Resolves `passkeys`: the relying party, the verifier and the freshness window, each refused at wiring when it cannot work. */\n\nimport { parseDuration } from '../../time/duration';\nimport type { PasskeysConfig } from './passkeys-config';\nimport type { ResolvedConfig } from './resolved-config';\n\nconst USER_VERIFICATION = ['required', 'preferred', 'discouraged'] as const;\nconst VERIFIER_METHODS = [\n\t'registrationOptions',\n\t'verifyRegistration',\n\t'authenticationOptions',\n\t'verifyAuthentication',\n] as const;\n// A host: dot-separated labels, no scheme, port, path or wildcard.\nconst RP_ID =\n\t/^(?=.{1,253}$)[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/;\n\nexport function resolvePasskeys(\n\tconfig: PasskeysConfig | undefined,\n\tsecondFactorOn: boolean,\n\twhere: string,\n): ResolvedConfig['passkeys'] {\n\tif (config === undefined) return null;\n\tconst at = `${where}: passkeys`;\n\tif (typeof config !== 'object' || config === null) {\n\t\tthrow new TypeError(`${at} must be an object`);\n\t}\n\t// A first-factor passkey seals nothing: the sealing keys are the TOTP's.\n\tif (!secondFactorOn && config.firstFactor !== true) {\n\t\tthrow new TypeError(\n\t\t\t`${at} needs secondFactor: a passkey is only registered beside an active TOTP — pass secondFactor: { issuer, keys }, or firstFactor: true to use passkeys alone`,\n\t\t);\n\t}\n\tif (typeof config.rpId !== 'string' || !RP_ID.test(config.rpId)) {\n\t\tthrow new TypeError(\n\t\t\t`${at}.rpId must be the domain credentials are scoped to — a lowercase host such as \"example.com\", with no scheme, port or path`,\n\t\t);\n\t}\n\tif (typeof config.rpName !== 'string' || config.rpName.trim() === '') {\n\t\tthrow new TypeError(\n\t\t\t`${at}.rpName must name your application — the browser shows it when it asks for a passkey`,\n\t\t);\n\t}\n\tconst origins = resolveRelatedOrigins(\n\t\tconfig.relatedOrigins,\n\t\tresolveOrigins(config.origins, config.rpId, at),\n\t\tat,\n\t);\n\tfor (const method of VERIFIER_METHODS) {\n\t\tif (\n\t\t\ttypeof (config.verifier as unknown as Record<string, unknown> | null)?.[\n\t\t\t\tmethod\n\t\t\t] !== 'function'\n\t\t) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${at}.verifier must be a PasskeyVerifier — ${method} is missing (simpleWebAuthnVerifier() from @softistx/janus-passkeys is one)`,\n\t\t\t);\n\t\t}\n\t}\n\tconst userVerification = config.userVerification ?? 'preferred';\n\tif (!USER_VERIFICATION.includes(userVerification)) {\n\t\tthrow new TypeError(\n\t\t\t`${at}.userVerification must be \"required\", \"preferred\" or \"discouraged\"`,\n\t\t);\n\t}\n\tif (\n\t\tconfig.firstFactor !== undefined &&\n\t\ttypeof config.firstFactor !== 'boolean'\n\t) {\n\t\tthrow new TypeError(`${at}.firstFactor must be true or false`);\n\t}\n\tconst maxPerUser = config.maxPerUser ?? 10;\n\tif (!Number.isInteger(maxPerUser) || maxPerUser < 1) {\n\t\tthrow new TypeError(`${at}.maxPerUser must be a positive integer`);\n\t}\n\treturn {\n\t\trp: {\n\t\t\trpId: config.rpId,\n\t\t\trpName: config.rpName,\n\t\t\torigins,\n\t\t\tuserVerification,\n\t\t},\n\t\tverifier: config.verifier,\n\t\tmaxPerUser,\n\t\tfirstFactor: config.firstFactor ?? false,\n\t\tfreshWithinMs: parseDuration(\n\t\t\tconfig.freshWithin ?? '10m',\n\t\t\t`${at}.freshWithin`,\n\t\t),\n\t};\n}\n\nfunction resolveOrigins(\n\torigins: unknown,\n\trpId: string,\n\tat: string,\n): readonly string[] {\n\tif (!Array.isArray(origins) || origins.length === 0) {\n\t\tthrow new TypeError(\n\t\t\t`${at}.origins must list at least one origin — the page the browser asks from, such as \"https://app.example.com\"`,\n\t\t);\n\t}\n\treturn origins.map((origin: unknown) => {\n\t\tconst url = parseOrigin(origin, `${at}.origins`);\n\t\tif (url.hostname !== rpId && !url.hostname.endsWith(`.${rpId}`)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${at}.origins: \"${url.origin}\" is not on rpId \"${rpId}\" — a credential is only usable from rpId or one of its subdomains; an origin on another host goes in ${at}.relatedOrigins (WebAuthn related origin requests, which also need /.well-known/webauthn on the rpId host)`,\n\t\t\t);\n\t\t}\n\t\treturn url.origin;\n\t});\n}\n\n/** `relatedOrigins`: well-formed, secure origins on any host, merged after `origins`; duplicates collapse. */\nfunction resolveRelatedOrigins(\n\trelated: unknown,\n\torigins: readonly string[],\n\tat: string,\n): readonly string[] {\n\tif (related === undefined) return origins;\n\tif (!Array.isArray(related)) {\n\t\tthrow new TypeError(\n\t\t\t`${at}.relatedOrigins must be a list of origins such as [\"https://app.example.org\"]`,\n\t\t);\n\t}\n\tconst merged = new Set(origins);\n\tfor (const origin of related) {\n\t\tmerged.add(parseOrigin(origin, `${at}.relatedOrigins`).origin);\n\t}\n\treturn [...merged];\n}\n\nfunction parseOrigin(origin: unknown, at: string): URL {\n\tconst url = typeof origin === 'string' ? URL.parse(origin) : null;\n\tif (url === null || url.origin !== origin) {\n\t\tthrow new TypeError(\n\t\t\t`${at}: ${JSON.stringify(origin)} is not an origin — write scheme, host and port only, with no trailing slash or path`,\n\t\t);\n\t}\n\t// Browsers treat 127.0.0.1, localhost and every *.localhost host as\n\t// secure contexts, on any port.\n\tconst local =\n\t\turl.protocol === 'http:' &&\n\t\t(url.hostname === 'localhost' ||\n\t\t\turl.hostname.endsWith('.localhost') ||\n\t\t\turl.hostname === '127.0.0.1');\n\tif (url.protocol !== 'https:' && !local) {\n\t\tthrow new TypeError(\n\t\t\t`${at}: \"${url.origin}\" must be https — browsers only offer passkeys on a secure origin (http://localhost, http://*.localhost and http://127.0.0.1 are the exceptions)`,\n\t\t);\n\t}\n\treturn url;\n}\n",
|
|
24
|
+
"/**\n * Resolves the three `{ throttle }` options, which take the same shape and\n * differ in their defaults: `signIn.throttle`, ten passwords per login per\n * fifteen minutes, `secondFactor.throttle`, ten second-step codes per account\n * per fifteen minutes, and `mail.throttle`, five requests per flow, per address\n * or user, per ten minutes. Each is on unless `false`.\n */\n\nimport { type Duration, parseDuration } from '../../time/duration';\nimport type { ResolvedConfig } from './resolved-config';\n\n/** A throttle once resolved, or `null` when it is `false`. */\ntype ResolvedThrottle = ResolvedConfig['signInThrottle'];\n\n/** What either option takes: `{ throttle }`, a limit or `false`. */\ninterface ThrottleOption {\n\treadonly throttle?:\n\t\t| { readonly attempts?: number; readonly window?: Duration }\n\t\t| false;\n}\n\n/** The defaults of one option, and the name a refusal gives it. */\ninterface Defaults {\n\treadonly option: 'signIn' | 'mail' | 'secondFactor';\n\treadonly attempts: number;\n\treadonly window: Duration;\n}\n\n/** Resolves `signIn.throttle`: on unless `false`, ten passwords per login per fifteen minutes. */\nexport function resolveSignInThrottle(\n\tconfig: ThrottleOption | undefined,\n\twhere: string,\n): ResolvedThrottle {\n\treturn resolveThrottle(\n\t\tconfig,\n\t\t{ option: 'signIn', attempts: 10, window: '15m' },\n\t\twhere,\n\t);\n}\n\n/**\n * Resolves `mail.throttle`: on unless `false`, five requests per flow, per\n * address or user, per ten minutes — room for a visitor who asks again, a\n * loop held to thirty e-mails an hour, and a window **no longer than the\n * shortest default lifetime** (a sign-in code's and a step-up's, `'10m'`):\n * the last link or code sent, issued in the window, still works until the\n * refusal ends.\n */\nexport function resolveMailThrottle(\n\tconfig: ThrottleOption | undefined,\n\twhere: string,\n): ResolvedThrottle {\n\treturn resolveThrottle(\n\t\tconfig,\n\t\t{ option: 'mail', attempts: 5, window: '10m' },\n\t\twhere,\n\t);\n}\n\n/**\n * Resolves `secondFactor.throttle`: on unless `false`, ten codes per account\n * per fifteen minutes — two challenges' worth, where one account's own\n * sign-ins stay far below it.\n */\nexport function resolveSecondFactorThrottle(\n\tconfig: ThrottleOption,\n\twhere: string,\n): ResolvedThrottle {\n\treturn resolveThrottle(\n\t\tconfig,\n\t\t{ option: 'secondFactor', attempts: 10, window: '15m' },\n\t\twhere,\n\t);\n}\n\nfunction resolveThrottle(\n\tconfig: ThrottleOption | undefined,\n\tdefaults: Defaults,\n\twhere: string,\n): ResolvedThrottle {\n\tconst { option } = defaults;\n\tif (config !== undefined && (typeof config !== 'object' || config === null)) {\n\t\tthrow new TypeError(`${where}: ${option} must be an object — { throttle }`);\n\t}\n\tconst throttle = config?.throttle ?? {};\n\tif (throttle === false) return null;\n\tconst at = `${where}: ${option}.throttle`;\n\tif (typeof throttle !== 'object' || throttle === null) {\n\t\tthrow new TypeError(\n\t\t\t`${at} must be { attempts, window }, or false to count nothing`,\n\t\t);\n\t}\n\tconst attempts = throttle.attempts ?? defaults.attempts;\n\tif (!Number.isSafeInteger(attempts) || attempts < 1) {\n\t\tthrow new TypeError(`${at}.attempts must be a whole number above zero`);\n\t}\n\treturn {\n\t\tattempts,\n\t\twindowMs: parseDuration(throttle.window ?? defaults.window, `${at}.window`),\n\t};\n}\n",
|
|
25
|
+
"/** Resolves the TOTP second factor: its issuer, its sealer, its challenge's lifespan. */\n\nimport { parseDuration } from '../../time/duration';\nimport { resolveSealer } from '../sealing';\nimport type { SecondFactorConfig } from './janus-config';\nimport { resolveSecondFactorThrottle } from './resolve-throttle';\nimport type { ResolvedConfig } from './resolved-config';\n\nexport function resolveSecondFactor(\n\tconfig: SecondFactorConfig | undefined,\n\twhere: string,\n): ResolvedConfig['secondFactor'] {\n\tif (config === undefined) return null;\n\tconst at = `${where}: secondFactor`;\n\tif (typeof config?.issuer !== 'string' || config.issuer.trim() === '') {\n\t\tthrow new TypeError(\n\t\t\t`${at}.issuer must name your application — the authenticator app shows it beside the account`,\n\t\t);\n\t}\n\treturn {\n\t\tissuer: config.issuer,\n\t\tsealer: resolveSealer(config.keys, `${at}.keys`),\n\t\tchallengeTtlMs: parseDuration(config.challenge ?? '5m', `${at}.challenge`),\n\t\tthrottle: resolveSecondFactorThrottle(config, where),\n\t};\n}\n",
|
|
26
|
+
"/** Resolves a user type's `social` block: the providers, the resolver, `signUp` and the freshness link demands. */\n\nimport { parseDuration } from '../../time/duration';\nimport type { ResolvedSocial } from './resolved-config';\nimport type { SocialConfig, SocialProvider } from './social-config';\n\n/** A provider's name: what a URL, a link record and an event carry. */\nexport const PROVIDER_NAME = /^[a-z][a-z0-9-]{0,31}$/;\n\n/**\n * `null` without `social`. `at` names the type in a refusal; `login` and\n * `email` are the type's login and e-mail fields (`login` is `null` without a\n * password), since a sign-up needs the e-mail to be the login.\n */\nexport function resolveSocial(\n\tsocial: SocialConfig | undefined,\n\ttype: { readonly login: string | null; readonly email: string },\n\tat: string,\n): ResolvedSocial | null {\n\tif (social === undefined) return null;\n\tif (typeof social !== 'object' || social === null) {\n\t\tthrow new TypeError(`${at}: social must be an object`);\n\t}\n\tconst resolveProvider = social.resolveProvider ?? null;\n\tif (resolveProvider !== null && typeof resolveProvider !== 'function') {\n\t\tthrow new TypeError(\n\t\t\t`${at}: social.resolveProvider must be a function that takes the provider's name and answers the provider, or null`,\n\t\t);\n\t}\n\tconst entries = Object.entries(social.providers ?? {});\n\tif (entries.length === 0 && resolveProvider === null) {\n\t\tthrow new TypeError(\n\t\t\t`${at}: social.providers must name at least one provider, or social.resolveProvider must be given`,\n\t\t);\n\t}\n\tconst providers = new Map<string, SocialProvider>();\n\tfor (const [name, provider] of entries) {\n\t\tif (!PROVIDER_NAME.test(name)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${at}: social.providers: \"${name}\" must be lowercase letters, digits and \"-\", starting with a letter, at most 32 characters`,\n\t\t\t);\n\t\t}\n\t\tif (!isSocialProvider(provider)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${at}: social.providers.${name} must be a provider — an object with authorizationUrl and exchange, such as google() from @softistx/janus-social`,\n\t\t\t);\n\t\t}\n\t\tproviders.set(name, provider);\n\t}\n\n\tconst signUp = social.signUp ?? false;\n\tif (signUp !== false && typeof signUp !== 'function') {\n\t\tthrow new TypeError(\n\t\t\t`${at}: social.signUp must be a function that takes the profile and answers the new user's fields, or false`,\n\t\t);\n\t}\n\tif (signUp !== false && type.login !== null && type.login !== type.email) {\n\t\tthrow new TypeError(\n\t\t\t`${at}: social.signUp needs a type whose login is its e-mail — password.login is \"${type.login}\", not \"${type.email}\"`,\n\t\t);\n\t}\n\n\treturn {\n\t\tproviders,\n\t\tresolveProvider,\n\t\tsignUp,\n\t\tfreshWithinMs: parseDuration(\n\t\t\tsocial.freshWithin ?? '10m',\n\t\t\t`${at}: social.freshWithin`,\n\t\t),\n\t};\n}\n\n/** Whether `value` has the two calls of a provider: what a configured one and a resolved one must have. */\nexport function isSocialProvider(value: unknown): value is SocialProvider {\n\tconst provider = value as Partial<SocialProvider> | null | undefined;\n\treturn (\n\t\ttypeof provider?.authorizationUrl === 'function' &&\n\t\ttypeof provider.exchange === 'function'\n\t);\n}\n",
|
|
27
|
+
"/** Resolves one user type: its schema, its password policy, its sessions. */\n\nimport { parseDuration } from '../../time/duration';\nimport { fieldName } from './names';\nimport { normalizer } from './normalize';\nimport type { PasswordConfig } from './password-config';\nimport { resolveSocial } from './resolve-social';\nimport type { ResolvedType } from './resolved-config';\nimport type { UserTypeConfig } from './user-type';\n\n/** `at` names the type in a refusal; `schemaKey` is the key its schema came in. */\nexport function resolveType(\n\tname: string,\n\ttype: UserTypeConfig,\n\tat: string,\n\tschemaKey: string,\n): ResolvedType {\n\tif (\n\t\ttypeof type?.schema !== 'object' ||\n\t\ttype.schema === null ||\n\t\ttypeof type.schema['~standard']?.validate !== 'function'\n\t) {\n\t\tthrow new TypeError(\n\t\t\t`${at}: ${schemaKey} must be a Standard Schema — a Zod 4, Valibot or ArkType schema`,\n\t\t);\n\t}\n\n\tconst password =\n\t\ttype.password === undefined ? null : resolvePassword(type.password, at);\n\n\tconst renewAfter = type.session?.renewAfter ?? '1d';\n\tconst email = fieldName(type.email ?? 'email', `${at}: email`);\n\n\tconst displayName = fieldName(\n\t\ttype.displayName ?? 'name',\n\t\t`${at}: displayName`,\n\t);\n\n\treturn {\n\t\tname,\n\t\tschema: type.schema,\n\t\tschemaVersion: type.schemaVersion ?? '1',\n\t\tpassword,\n\t\temail,\n\t\tdisplayName,\n\t\tlifespanMs: parseDuration(\n\t\t\ttype.session?.lifespan ?? '7d',\n\t\t\t`${at}: session.lifespan`,\n\t\t),\n\t\trenewAfterMs:\n\t\t\trenewAfter === false\n\t\t\t\t? null\n\t\t\t\t: parseDuration(renewAfter, `${at}: session.renewAfter`),\n\t\tabsoluteMs:\n\t\t\ttype.session?.absolute === undefined\n\t\t\t\t? null\n\t\t\t\t: parseDuration(type.session.absolute, `${at}: session.absolute`),\n\t\tsocial: resolveSocial(\n\t\t\ttype.social,\n\t\t\t{ login: password?.login ?? null, email },\n\t\t\tat,\n\t\t),\n\t};\n}\n\nfunction resolvePassword(\n\tpassword: PasswordConfig,\n\tat: string,\n): NonNullable<ResolvedType['password']> {\n\tconst minLength = password.minLength ?? 8;\n\tif (!Number.isInteger(minLength) || minLength < 1) {\n\t\tthrow new TypeError(\n\t\t\t`${at}: password.minLength must be an integer of at least 1`,\n\t\t);\n\t}\n\tconst requireVerified = password.requireVerifiedEmail ?? false;\n\tif (typeof requireVerified !== 'boolean') {\n\t\tthrow new TypeError(\n\t\t\t`${at}: password.requireVerifiedEmail must be a boolean`,\n\t\t);\n\t}\n\treturn {\n\t\tlogin: fieldName(password.login, `${at}: password.login`),\n\t\tnormalize: normalizer(\n\t\t\tpassword.normalize ?? 'lowercaseTrim',\n\t\t\t`${at}: password.normalize`,\n\t\t),\n\t\tminLength,\n\t\trequireVerifiedEmail: requireVerified,\n\t};\n}\n",
|
|
28
|
+
"/**\n * Resolves what `janus()` was given: applies the defaults and refuses what\n * cannot be wired, with a bare `TypeError` naming where.\n */\n\nimport { parseDuration } from '../../time/duration';\nimport type {\n\tJanusConfig,\n\tMultiTypeConfig,\n\tSingleTypeConfig,\n} from './janus-config';\nimport { NAME } from './names';\nimport { RESERVED_TYPES, SINGLE_TYPE } from './reserved';\nimport { resolveApiKeys } from './resolve-api-keys';\nimport { resolveCookie } from './resolve-cookie';\nimport { resolveDevices } from './resolve-devices';\nimport { resolveInvitations } from './resolve-invitations';\nimport { resolveMagicLink } from './resolve-magic-link';\nimport { resolvePasskeys } from './resolve-passkeys';\nimport { resolveSecondFactor } from './resolve-second-factor';\nimport { resolveMailThrottle, resolveSignInThrottle } from './resolve-throttle';\nimport { resolveType } from './resolve-type';\nimport type { ResolvedConfig, ResolvedType } from './resolved-config';\nimport type { UserSchema, UserTypeConfig } from './user-type';\n\n/** Applies the defaults and refuses what cannot be wired. `where` names the call. */\nexport function resolveConfig(\n\tconfig: JanusConfig,\n\twhere: string,\n): ResolvedConfig {\n\tif (typeof config !== 'object' || config === null) {\n\t\tthrow new TypeError(`${where}: expected a configuration object`);\n\t}\n\n\tconst hasUser = config.user !== undefined;\n\tconst hasUsers = config.users !== undefined;\n\tif (hasUser === hasUsers) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: pass either user (one user type) or users (several user types), and exactly one of them`,\n\t\t);\n\t}\n\n\tconst types = resolveTypes(entriesOf(config, hasUsers), hasUsers, where);\n\trefuseHashingWithoutHasher(config, types, where);\n\n\treturn {\n\t\tsingle: !hasUsers,\n\t\ttypes,\n\t\tstaticProviderNames: new Set(\n\t\t\t[...types.values()].flatMap((type) => [\n\t\t\t\t...(type.social?.providers.keys() ?? []),\n\t\t\t]),\n\t\t),\n\t\ttokenTtlMs: resolveTokenTtls(config, where),\n\t\tcookie: resolveCookie(config.cookie ?? {}, where),\n\t\tsignInThrottle: resolveSignInThrottle(config.signIn, where),\n\t\tmailThrottle: resolveMailThrottle(config.mail, where),\n\t\tmagicLinkEnabled: resolveMagicLink(config.magicLink, where),\n\t\tsecondFactor: resolveSecondFactor(config.secondFactor, where),\n\t\tpasskeys: resolvePasskeys(\n\t\t\tconfig.passkeys,\n\t\t\tconfig.secondFactor !== undefined,\n\t\t\twhere,\n\t\t),\n\t\tdevices: resolveDevices(config.devices, where),\n\t\tapiKeys: resolveApiKeys(config.apiKeys, types, where),\n\t\tinvitations: resolveInvitations(config.invitations, types, where),\n\t};\n}\n\n/** Every user type declared, by name: the single-type form's under {@link SINGLE_TYPE}. */\nfunction entriesOf(\n\tconfig: JanusConfig,\n\thasUsers: boolean,\n): [string, UserTypeConfig][] {\n\treturn hasUsers\n\t\t? Object.entries(config.users as MultiTypeConfig['users'])\n\t\t: [\n\t\t\t\t[\n\t\t\t\t\tSINGLE_TYPE,\n\t\t\t\t\t{\n\t\t\t\t\t\t...(config as SingleTypeConfig),\n\t\t\t\t\t\tschema: config.user as UserSchema,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t];\n}\n\nfunction resolveTypes(\n\tentries: [string, UserTypeConfig][],\n\thasUsers: boolean,\n\twhere: string,\n): Map<string, ResolvedType> {\n\tif (entries.length === 0) {\n\t\tthrow new TypeError(`${where}: users declares no user type`);\n\t}\n\n\tconst types = new Map<string, ResolvedType>();\n\tfor (const [name, type] of entries) {\n\t\tconst at = hasUsers ? `${where}: users.${name}` : where;\n\n\t\tif (!NAME.test(name)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${where}: the user type \"${name}\" must be a camelCase name — letters and digits, starting with a letter`,\n\t\t\t);\n\t\t}\n\t\tif ((RESERVED_TYPES as readonly string[]).includes(name)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${where}: \"${name}\" cannot name a user type — janus() answers a method of that name`,\n\t\t\t);\n\t\t}\n\t\ttypes.set(name, resolveType(name, type, at, hasUsers ? 'schema' : 'user'));\n\t}\n\treturn types;\n}\n\nfunction refuseHashingWithoutHasher(\n\tconfig: JanusConfig,\n\ttypes: ReadonlyMap<string, ResolvedType>,\n\twhere: string,\n): void {\n\tconst hashing = [...types.values()].some((type) => type.password !== null);\n\tif (hashing && config.hasher === undefined) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: a user type signs in with a password and no hasher is wired — pass hasher: scryptHasher(), or bunHasher() on Bun. There is no silent fallback`,\n\t\t);\n\t}\n}\n\nfunction resolveTokenTtls(\n\tconfig: JanusConfig,\n\twhere: string,\n): ResolvedConfig['tokenTtlMs'] {\n\treturn {\n\t\tverifyEmail: parseDuration(\n\t\t\tconfig.tokens?.verifyEmail ?? '24h',\n\t\t\t`${where}: tokens.verifyEmail`,\n\t\t),\n\t\tresetPassword: parseDuration(\n\t\t\tconfig.tokens?.resetPassword ?? '1h',\n\t\t\t`${where}: tokens.resetPassword`,\n\t\t),\n\t\tsignInCode: parseDuration(\n\t\t\tconfig.tokens?.signInCode ?? '10m',\n\t\t\t`${where}: tokens.signInCode`,\n\t\t),\n\t\tmagicLink: parseDuration(\n\t\t\tconfig.tokens?.magicLink ?? '15m',\n\t\t\t`${where}: tokens.magicLink`,\n\t\t),\n\t\tstepUp: parseDuration(\n\t\t\tconfig.tokens?.stepUp ?? '10m',\n\t\t\t`${where}: tokens.stepUp`,\n\t\t),\n\t\tchangeEmail: parseDuration(\n\t\t\tconfig.tokens?.changeEmail ?? '1h',\n\t\t\t`${where}: tokens.changeEmail`,\n\t\t),\n\t\tsocialFlow: parseDuration(\n\t\t\tconfig.tokens?.socialFlow ?? '10m',\n\t\t\t`${where}: tokens.socialFlow`,\n\t\t),\n\t\tpasskeyRegistration: parseDuration(\n\t\t\tconfig.tokens?.passkeyRegistration ?? '5m',\n\t\t\t`${where}: tokens.passkeyRegistration`,\n\t\t),\n\t};\n}\n",
|
|
29
|
+
"/**\n * What a user signs in with, and is found by: the login field and the e-mail,\n * each normalised by its own rule.\n */\n\nimport { UserInvalidError } from '../../errors/janus-error';\nimport { isStorable, UNSTORABLE } from '../../stores/storable';\nimport { foldName, normalizeEmail, type ResolvedType } from '../config';\nimport type { JsonObject, UserRecord } from '../port/types';\nimport type { Context } from './create-context';\n\n/** The user's e-mail, as stored, or `null` when the schema let it be absent. */\nexport function emailOf(type: ResolvedType, fields: JsonObject): string | null {\n\tconst value = fields[type.email];\n\treturn typeof value === 'string' ? value : null;\n}\n\n/**\n * What a user signs in with, normalised: the login field, by its own rule,\n * and the e-mail, by the e-mail rule — so a user whose login is a username can\n * still be found by the e-mail a reset is requested for.\n */\nexport function loginsOf(\n\ttype: ResolvedType,\n\tfields: JsonObject,\n\twhere: string,\n): string[] {\n\tconst logins = new Set<string>();\n\n\tif (type.password !== null) {\n\t\tconst login = fields[type.password.login];\n\t\tif (typeof login !== 'string') {\n\t\t\tthrow new TypeError(\n\t\t\t\t`janus: password.login \"${type.password.login}\" did not name a string in validated ${type.name} fields — it must name a required string field`,\n\t\t\t);\n\t\t}\n\t\tconst normalized = type.password.normalize(login);\n\t\t// The fields were checked; a function normaliser can still cut a\n\t\t// surrogate pair in half. Refused here, or the user is written with a\n\t\t// login nobody can sign in with — or not written at all, on PostgreSQL.\n\t\tif (!isStorable(normalized)) {\n\t\t\tconst path = [type.password.login];\n\t\t\tthrow new UserInvalidError(\n\t\t\t\t`${where}: the fields do not match the ${type.name} schema (1 issue, at ${path.join('.')})`,\n\t\t\t\t{\n\t\t\t\t\tissues: [\n\t\t\t\t\t\t{ path, message: `normalises to a login that ${UNSTORABLE}` },\n\t\t\t\t\t],\n\t\t\t\t\tuserType: type.name,\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t\tlogins.add(normalized);\n\t}\n\n\tconst email = emailOf(type, fields);\n\tif (email !== null) logins.add(normalizeEmail(email));\n\n\treturn [...logins];\n}\n\n/**\n * The user of this type whose e-mail this is, or `null`. Looked up as a\n * login — every e-mail is one — and then compared, so a username that only\n * looks like an e-mail is nobody's.\n */\nexport async function holderOfEmail(\n\tcontext: Context,\n\ttype: ResolvedType,\n\temail: string,\n): Promise<UserRecord | null> {\n\tconst wanted = normalizeEmail(email);\n\tif (!isStorable(wanted)) return null;\n\tconst record = await context.store.users.findUserByLogin(type.name, wanted);\n\tconst held = record === null ? null : emailOf(type, record.fields);\n\treturn held !== null && normalizeEmail(held) === wanted ? record : null;\n}\n\n/**\n * The search key of the user's display name, or `null` when the fields hold no\n * name to search: the field is absent, not a string, blank, or folds to\n * something no store can keep.\n */\nexport function nameKeyOf(\n\ttype: ResolvedType,\n\tfields: JsonObject,\n): string | null {\n\tconst value = fields[type.displayName];\n\tif (typeof value !== 'string') return null;\n\tconst key = foldName(value);\n\treturn key === '' || !isStorable(key) ? null : key;\n}\n",
|
|
30
|
+
"/**\n * **The identity side's two conversions**, and the one place a `null` becomes\n * an error.\n *\n * > An absence is `null`. A failure throws.\n *\n * {@link guardStores} puts the three identity stores behind the shared guard\n * (`src/stores/guard.ts`), the one place a store's answer is caught.\n * {@link required} turns an absence the caller cannot accept into its refusal,\n * {@link unlessVersionConflict} absorbs one named conflict and rethrows\n * everything else, and {@link unlessLoginTaken} hands back the other one.\n *\n * `outage.scan.spec.ts` reads every other file of `src/auth/`, `src/permissions/`\n * and `src/stores/` and fails if a `catch` appears in one, because the failure\n * this design exists to prevent is a single careless `catch { return null }`.\n */\n\nimport { type JanusError, StoreConflict } from '../errors/janus-error';\nimport { guardStore } from '../stores/guard';\nimport type { JanusStores } from './port/types';\n\n/**\n * The stores, with every method guarded.\n *\n * - A `JanusError` the adapter threw — `StoreFailure`, `StoreConflict`,\n * `NotFoundError` — passes through untouched, so `instanceof` still holds.\n * - **Anything else it threw is a failure**: a driver error, a `TypeError` from\n * a bug in the adapter, a string. It becomes `StoreFailure` with the original\n * as `cause`, naming the slot and the method. It is never an absence.\n * - A method that answers `undefined` where the port says `null` is a store\n * that forgot to answer, and becomes `StoreFailure` rather than \"not found\".\n * Rule 2 of the port, enforced at run time for the JavaScript adapter the\n * compiler never saw.\n *\n * The optional `deleteExpiredSessions` and `deleteExpiredTokens`, and the\n * optional `socialLinks` and `passkeys` slots, are guarded when present and left absent when absent, so capability detection still reads the truth.\n */\nexport function guardStores(stores: JanusStores): JanusStores {\n\treturn {\n\t\tusers: guardStore('users', stores.users),\n\t\tsessions: guardStore('sessions', stores.sessions),\n\t\ttokens: guardStore('tokens', stores.tokens),\n\t\t...(stores.socialLinks === undefined\n\t\t\t? {}\n\t\t\t: { socialLinks: guardStore('socialLinks', stores.socialLinks) }),\n\t\t...(stores.passkeys === undefined\n\t\t\t? {}\n\t\t\t: { passkeys: guardStore('passkeys', stores.passkeys) }),\n\t};\n}\n\n/**\n * A value the caller requires, or the refusal an absence deserves.\n *\n * The only place in the core where a `null` from a store turns into an error —\n * `get` becoming `NOT_FOUND`. Written as a function so that the conversion is\n * visible at every call site and nowhere else.\n */\nexport function required<T>(value: T | null, absent: () => JanusError): T {\n\tif (value === null) throw absent();\n\treturn value;\n}\n\n/**\n * A write that may lose a race, and is allowed to: its answer, or `null` when\n * the record's version moved under it.\n *\n * **Only `StoreConflict('version')` is absorbed.** A failure still throws, a\n * taken login still throws, `NOT_FOUND` still throws: an outage never reads as\n * \"somebody else wrote first\". It exists for writes the caller did not ask for\n * — rewriting a password hash on sign-in — where losing to a concurrent update\n * means only that the next sign-in tries again — and for `verifyEmail.proveFirst`,\n * which reads again and retries once.\n */\nexport async function unlessVersionConflict<T>(\n\twrite: Promise<T>,\n): Promise<T | null> {\n\ttry {\n\t\treturn await write;\n\t} catch (error) {\n\t\tif (error instanceof StoreConflict && error.on === 'version') return null;\n\t\tthrow error;\n\t}\n}\n\n/**\n * A write that may lose a race on a login, and says so: its answer, or the\n * `StoreConflict('login')` the store refused it with, **as a value**, for the\n * caller to read the login again and then rethrow or answer the winner.\n *\n * **Only `StoreConflict('login')` is handed back.** A failure still throws, a\n * version conflict still throws: an outage never reads as \"somebody else\n * created the user first\".\n */\nexport async function unlessLoginTaken<T>(\n\twrite: Promise<T>,\n): Promise<T | StoreConflict> {\n\ttry {\n\t\treturn await write;\n\t} catch (error) {\n\t\tif (error instanceof StoreConflict && error.on === 'login') return error;\n\t\tthrow error;\n\t}\n}\n",
|
|
31
|
+
"/**\n * The password steps every flow takes the same way: the type's rule, the\n * policy, the hasher, the comparison, and the rewrite of a stale hash.\n */\n\nimport { CredentialError } from '../../errors/janus-error';\nimport type { PasswordHasher, ResolvedType } from '../config';\nimport { unlessVersionConflict } from '../outage';\nimport type { UserRecord } from '../port/types';\nimport type { Context } from './create-context';\n\n/** The type's password rule, or a wiring refusal for a JavaScript caller. */\nexport function passwordRule(type: ResolvedType, where: string) {\n\tif (type.password === null) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: the ${type.name} type does not sign in with a password — add password: { login } to it`,\n\t\t);\n\t}\n\treturn type.password;\n}\n\n/** Refuses a password shorter than the policy. Reports the policy, never the password. */\nexport function checkPassword(\n\ttype: ResolvedType,\n\tpassword: string,\n\twhere: string,\n): void {\n\tconst minLength = type.password?.minLength ?? 8;\n\tif (typeof password !== 'string' || password.length < minLength) {\n\t\tthrow new CredentialError(\n\t\t\t'PASSWORD_TOO_SHORT',\n\t\t\t`${where}: the password is shorter than the policy's ${minLength} characters`,\n\t\t\t{ minLength, userType: type.name },\n\t\t);\n\t}\n}\n\n/** The hasher. `janus()` refused a password type without one, so this is a wiring net. */\nexport function requireHasher(context: Context, where: string): PasswordHasher {\n\tif (context.hasher === null) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: no password hasher is wired — pass hasher: scryptHasher(), or bunHasher() on Bun`,\n\t\t);\n\t}\n\treturn context.hasher;\n}\n\n/**\n * Whether `password` matches the stored hash. A hash whose prefix no wired\n * verifier claims is `HASH_UNSUPPORTED`, reporting the prefix, never the hash.\n */\nexport async function passwordMatches(\n\tcontext: Context,\n\trecord: UserRecord,\n\tpassword: string,\n\twhere: string,\n): Promise<boolean> {\n\tconst stored = record.password;\n\tif (stored === null) return false;\n\n\tconst verifier = context.verifiers.find((candidate) =>\n\t\tstored.hash.startsWith(candidate.prefix),\n\t);\n\tif (verifier === undefined) {\n\t\tconst hashPrefix = /^\\$[^$]*\\$/.exec(stored.hash)?.[0] ?? '(none)';\n\t\tthrow new CredentialError(\n\t\t\t'HASH_UNSUPPORTED',\n\t\t\t`${where}: no wired verifier claims the prefix \"${hashPrefix}\"`,\n\t\t\t{ hashPrefix, userId: record.id, userType: record.type },\n\t\t);\n\t}\n\n\treturn verifier.verify(password, stored.hash);\n}\n\n/**\n * The record, with its password hash rewritten by the current hasher when the\n * stored one is stale: written by another hasher — a `verifiers` one — or by\n * this one with other parameters. Called only once `password` has matched.\n *\n * The rewrite is conditioned on the version just read. Losing that race to a\n * concurrent update is not the sign-in's failure: the record is answered as\n * read, and the next sign-in tries again. A store failure still throws.\n */\nexport async function rehashed(\n\tcontext: Context,\n\trecord: UserRecord,\n\tpassword: string,\n): Promise<UserRecord> {\n\tconst { hasher } = context;\n\tconst stored = record.password;\n\tif (hasher === null || stored === null) return record;\n\n\tconst stale =\n\t\t!stored.hash.startsWith(hasher.prefix) ||\n\t\thasher.needsRehash?.(stored.hash) === true;\n\tif (!stale) return record;\n\n\tconst written = await unlessVersionConflict(\n\t\tcontext.store.users.updateUser(\n\t\t\trecord.id,\n\t\t\t{\n\t\t\t\tupdatedAt: context.clock.now(),\n\t\t\t\t// The same password, so the same `updatedAt`: when it was *set*.\n\t\t\t\tpassword: {\n\t\t\t\t\thash: await hasher.hash(password),\n\t\t\t\t\tupdatedAt: stored.updatedAt,\n\t\t\t\t},\n\t\t\t},\n\t\t\trecord.version,\n\t\t),\n\t);\n\treturn written ?? record;\n}\n",
|
|
32
|
+
"/** A user as the core answers one, from the record a store holds. */\n\nimport type { UserRecord } from '../port/types';\nimport type { User, UserRef } from '../types';\n\n/** A user of any type, as the degenericised core handles them. */\nexport type AnyUser = User<string, Record<string, unknown>>;\n\n/**\n * A user as application code sees it: their fields at the top level, then\n * what `janus` sets — written last, so no stored key can shadow it. No password\n * hash, ever.\n */\nexport function toUser(record: UserRecord): AnyUser {\n\treturn {\n\t\t...record.fields,\n\t\tid: record.id,\n\t\ttype: record.type,\n\t\temailVerified: record.emailVerifiedAt !== null,\n\t\tactive: record.active,\n\t\thasPassword: record.password !== null,\n\t\thasSecondFactor: record.secondFactor?.confirmedAt != null,\n\t\tavatar:\n\t\t\trecord.avatar === null\n\t\t\t\t? null\n\t\t\t\t: { id: record.avatar.id, updatedAt: record.avatar.updatedAt },\n\t\tversion: record.version,\n\t\tcreatedAt: record.createdAt,\n\t\tupdatedAt: record.updatedAt,\n\t};\n}\n\n/** The id a {@link UserRef} names. */\nexport const idOf = (user: UserRef): string =>\n\ttypeof user === 'string' ? user : user.id;\n\n/**\n * The id a JavaScript caller's reference names, or `''` — malformed, and\n * so `NOT_FOUND` without reaching the store — for anything that names none:\n * what the privileged calls read, `signInProven` and\n * `verifyEmail.proveFirst`, which must never mistake a bad value for a user.\n */\nexport function refId(user: UserRef): string {\n\tif (typeof user === 'string') return user;\n\tconst id: unknown =\n\t\ttypeof user === 'object' && user !== null ? user.id : undefined;\n\treturn typeof id === 'string' ? id : '';\n}\n",
|
|
33
|
+
"/**\n * Reading a user's record by id — an absence is `null`, `getRecord` makes it\n * `NOT_FOUND` — and the one write that follows such a read, under a version.\n */\n\nimport { NotFoundError, StoreConflict } from '../../errors/janus-error';\nimport { isId } from '../../ids/id';\nimport type { ResolvedType } from '../config';\nimport { required } from '../outage';\nimport type { UserPatch, UserRecord } from '../port/types';\nimport type { UserRef, WriteOptions } from '../types';\nimport type { Context } from './create-context';\nimport { idOf } from './user';\n\nconst notFound = (where: string, id: string, type: string | null) =>\n\tnew NotFoundError(\n\t\t`${where}: no ${type ?? 'user'} has this id`,\n\t\ttype === null\n\t\t\t? { userId: id, operation: where }\n\t\t\t: { userId: id, userType: type, operation: where },\n\t);\n\n/**\n * The user — of this type, when one is given — or `null`. A malformed id is an\n * absence decided without reaching the store: it arrives off a URL, and it is\n * \"no such user\", not a query and not an outage. A user of another type is\n * absent too: `auth.staff.find(patientId)` finds nobody.\n */\nexport async function findRecord(\n\tcontext: Context,\n\tid: string,\n\ttype: string | null,\n): Promise<UserRecord | null> {\n\tif (!isId(id)) return null;\n\tconst record = await context.store.users.findUser(id);\n\treturn record !== null && (type === null || record.type === type)\n\t\t? record\n\t\t: null;\n}\n\n/** The user, or `NOT_FOUND`. */\nexport async function getRecord(\n\tcontext: Context,\n\tid: string,\n\ttype: string | null,\n\twhere: string,\n): Promise<UserRecord> {\n\treturn required(await findRecord(context, id, type), () =>\n\t\tnotFound(where, id, type),\n\t);\n}\n\n/**\n * One write that follows a read, under a version: the core reads the user,\n * checks `ifVersion` against what it read, computes the patch from the record,\n * and writes under the version it read. A user who changed in between is\n * `VERSION_CONFLICT`, and nothing is written. A patch of `null` writes\n * nothing either: the flow found there was nothing to change, and the record\n * as read is the answer.\n */\nexport async function writeUser(\n\tcontext: Context,\n\tuser: UserRef,\n\ttype: ResolvedType,\n\toptions: WriteOptions | undefined,\n\twhere: string,\n\tpatchOf: (\n\t\trecord: UserRecord,\n\t\tnow: Date,\n\t) =>\n\t\t| Omit<UserPatch, 'updatedAt'>\n\t\t| null\n\t\t| Promise<Omit<UserPatch, 'updatedAt'> | null>,\n): Promise<UserRecord> {\n\tconst id = idOf(user);\n\tconst record = await getRecord(context, id, type.name, where);\n\tconst ifVersion = options?.ifVersion;\n\n\tif (ifVersion !== undefined && ifVersion !== record.version) {\n\t\tthrow new StoreConflict(\n\t\t\t'version',\n\t\t\t`${where}: expected version ${ifVersion}, found ${record.version}`,\n\t\t\t{\n\t\t\t\tuserId: id,\n\t\t\t\texpectedVersion: ifVersion,\n\t\t\t\tactualVersion: record.version,\n\t\t\t\toperation: where,\n\t\t\t},\n\t\t);\n\t}\n\n\tconst now = context.clock.now();\n\tconst patch = await patchOf(record, now);\n\tif (patch === null) return record;\n\treturn context.store.users.updateUser(\n\t\trecord.id,\n\t\t{ ...patch, updatedAt: now },\n\t\trecord.version,\n\t);\n}\n",
|
|
34
|
+
"/**\n * A user's fields, validated against the type's schema and answered as the\n * port holds them — or refused, reporting where and never the values.\n */\n\nimport { type Issue, UserInvalidError } from '../../errors/janus-error';\nimport { isStorable, UNSTORABLE } from '../../stores/storable';\nimport { RESERVED_FIELDS, type ResolvedType } from '../config';\nimport type { Json, JsonObject } from '../port/types';\nimport type { StandardSchemaV1 } from '../standard-schema';\n\n/**\n * Validates fields against the type's schema, and answers them as the port\n * holds them: an `undefined` property dropped, at every depth.\n */\nexport async function validateFields(\n\ttype: ResolvedType,\n\tinput: unknown,\n\twhere: string,\n): Promise<JsonObject> {\n\tconst result = await type.schema['~standard'].validate(input);\n\n\tconst issues: Issue[] =\n\t\tresult.issues === undefined\n\t\t\t? []\n\t\t\t: result.issues.map((issue) => ({\n\t\t\t\t\tpath: storablePrefix((issue.path ?? []).map(segmentKey)),\n\t\t\t\t\tmessage: issue.message,\n\t\t\t\t}));\n\n\t// A schema that passes unknown keys through would let a request set `id` or\n\t// `active` among the fields. `toUser` would shadow them anyway; refusing\n\t// them says so to whoever sent them.\n\tif (result.issues === undefined) {\n\t\tconst value = result.value as Record<string, unknown>;\n\t\tfor (const key of RESERVED_FIELDS) {\n\t\t\tif (Object.hasOwn(value, key)) {\n\t\t\t\tissues.push({ path: [key], message: 'set by janus, not by a request' });\n\t\t\t}\n\t\t}\n\t\tunstorableIn(value, [], issues);\n\t}\n\n\tif (issues.length > 0) {\n\t\t// The message reports how many and where, never the values: a field may\n\t\t// be anything the application chose to store, including something\n\t\t// private.\n\t\tthrow new UserInvalidError(\n\t\t\t`${where}: the fields do not match the ${type.name} schema (${issues.length} issue${issues.length === 1 ? '' : 's'}, at ${issues.map((i) => i.path.join('.') || '(root)').join(', ')})`,\n\t\t\t{ issues, userType: type.name },\n\t\t);\n\t}\n\n\treturn withoutUndefined((result as { value: unknown }).value) as JsonObject;\n}\n\n/** Pushes an issue for every key and every string no store can keep. */\nfunction unstorableIn(\n\tvalue: unknown,\n\tpath: (string | number)[],\n\tissues: Issue[],\n): void {\n\tif (typeof value === 'string') {\n\t\tif (!isStorable(value)) issues.push({ path, message: UNSTORABLE });\n\t\treturn;\n\t}\n\tif (Array.isArray(value)) {\n\t\tfor (const [index, inner] of value.entries()) {\n\t\t\tunstorableIn(inner, [...path, index], issues);\n\t\t}\n\t\treturn;\n\t}\n\tif (typeof value === 'object' && value !== null) {\n\t\tfor (const [key, inner] of Object.entries(value)) {\n\t\t\t// The key itself stays out of the path: the path reaches the message,\n\t\t\t// and a NUL has no business in a log line.\n\t\t\tif (!isStorable(key)) {\n\t\t\t\tissues.push({ path, message: `a key ${UNSTORABLE}` });\n\t\t\t} else {\n\t\t\t\tunstorableIn(inner, [...path, key], issues);\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * A path up to its first key no store can keep: the path reaches the message,\n * and a NUL has no business in a log line.\n */\nfunction storablePrefix(path: (string | number)[]): (string | number)[] {\n\tconst cut = path.findIndex(\n\t\t(segment) => typeof segment === 'string' && !isStorable(segment),\n\t);\n\treturn cut === -1 ? path : path.slice(0, cut);\n}\n\nfunction segmentKey(\n\tsegment: PropertyKey | StandardSchemaV1.PathSegment,\n): string | number {\n\tconst key = typeof segment === 'object' ? segment.key : segment;\n\treturn typeof key === 'number' ? key : String(key);\n}\n\nfunction withoutUndefined(value: unknown): Json {\n\tif (Array.isArray(value)) return value.map(withoutUndefined);\n\n\tif (typeof value === 'object' && value !== null) {\n\t\tconst out: Record<string, Json> = {};\n\t\tfor (const [key, inner] of Object.entries(value)) {\n\t\t\tif (inner !== undefined) out[key] = withoutUndefined(inner);\n\t\t}\n\t\treturn out;\n\t}\n\n\treturn value as Json;\n}\n",
|
|
35
|
+
"import { AvatarIdInvalidError } from '../../errors/janus-error';\nimport { isStorable } from '../../stores/storable';\n\n/** The longest avatar id janus stores: room for a key or a URL, not for a document. */\nexport const AVATAR_ID_MAX = 512;\n\n/**\n * The id `avatar.set` was given, or `AVATAR_ID_INVALID`. Janus never parses\n * it: it only has to be something every store can keep. Decided before any\n * read, since it arrives from the application's own upload step — and the\n * message names the shape, never the value.\n */\nexport function avatarIdOf(avatar: unknown, where: string): string {\n\tconst id =\n\t\ttypeof avatar === 'object' && avatar !== null\n\t\t\t? (avatar as { readonly id?: unknown }).id\n\t\t\t: undefined;\n\tif (\n\t\ttypeof id !== 'string' ||\n\t\tid === '' ||\n\t\tid.length > AVATAR_ID_MAX ||\n\t\t!isStorable(id)\n\t) {\n\t\tthrow new AvatarIdInvalidError(\n\t\t\t`${where}: the avatar id must be a non-empty string of at most ${AVATAR_ID_MAX} characters that every store can keep`,\n\t\t\t{ operation: where },\n\t\t);\n\t}\n\treturn id;\n}\n",
|
|
36
|
+
"import { type Id, mintId } from '../ids/id';\nimport type { Context } from './context';\n\n/**\n * What happened to a user, once it is written:\n *\n * - `user.created` — by `create` or `signUp`;\n * - `user.emailVerified` — by `verifyEmail.confirm`, or by the link of\n * `resetPassword.confirm`, `magicLink.confirm` or `changeEmail.confirm`, or the code of\n * `signInCode.confirm`, which prove the e-mail too; never for an e-mail\n * already verified;\n * - `user.passwordReset` — by `resetPassword.confirm`;\n * - `user.passwordChanged` — by `changePassword` and `setPassword`, and by\n * `signInCode.confirm` and `magicLink.confirm` when their first proof of\n * the e-mail dropped a password, after `user.emailVerified`; never by a\n * reset, which is `user.passwordReset` alone. Carries `first`: `true` when\n * the user had no password before (a `setPassword` on an account created\n * without a credential), so a \"your password was changed\" notice can skip it;\n * - `user.emailChanged` — by `update` and `changeEmail.confirm`, when they\n * changed the e-mail — compared\n * normalised, the same test that makes the new one unverified. The one\n * event that carries more than the user: `formerEmail`;\n * - `user.secondFactorEnabled` — by `secondFactor.activate`, once the factor\n * is active: not by `enroll`, which leaves it waiting for its first code;\n * - `user.secondFactorDisabled` — by `secondFactor.disable`, when it removed\n * an active factor, and by `signInCode.confirm` and `magicLink.confirm`\n * when their first proof of the e-mail removed one, after\n * `user.emailVerified` and any `user.passwordChanged`; never for a user who\n * had none, or one still waiting;\n * - `user.recoveryCodesRegenerated` — by `secondFactor.regenerateRecoveryCodes`:\n * the codes the user held stopped working. Not by `activate`, whose codes\n * come with `user.secondFactorEnabled`;\n * - `user.recoveryCodeUsed` — by `secondFactor.recover`, once the code is\n * spent: a sign-in without the user's phone;\n * - `user.newDeviceSignedIn` — by a sign-in that opened a session from a\n * device the user had not signed in from: `signIn`, `secondFactor.confirm`,\n * `secondFactor.recover`, `signInCode.confirm`, `magicLink.confirm` and\n * `signInProven`, when given a `device` its token did not prove. Never by\n * `signUp`, nor without a `device`. Carries `sessionId`;\n * - `user.avatarChanged` — by `avatar.set`, when it wrote a different id than\n * the user had. The same id again is no write and no event. Carries\n * `formerAvatarId`: how the application deletes the image it replaced;\n * - `user.avatarRemoved` — by `avatar.remove`, when the user had an avatar.\n * Carries `formerAvatarId`, the id it had;\n * - `user.socialLinked` — by `social.complete` when it linked a social\n * account: a link flow, an existing user matched by a verified e-mail, or\n * the account a social sign-up created. Not for an account already linked\n * to that user. Carries `provider`, never the account's id;\n * - `user.socialUnlinked` — by `social.unlink`, when it deleted a link.\n * Carries `provider`;\n * - `user.passkeyAdded` — by `passkeys.register`, once the passkey is stored;\n * not by `registrationOptions`, which stores no credential;\n * - `user.passkeyRemoved` — by `passkeys.remove`, when it deleted a passkey,\n * and by `secondFactor.disable` (and a first proof that removed an active\n * TOTP) once per passkey it took with the factor.\n * Both carry `passkey`, the credential id and name;\n * - `user.passkeyCloneSuspected` — by `secondFactor.confirmPasskey` and\n * `stepUp.confirmPasskey`, when an assertion's counter went backwards\n * (both counters non-zero): the sign-in is refused, the passkey stays\n * active. Carries `passkey`, the credential id and name;\n * - `user.apiKeyCreated` — by `apiKeys.create`, once the key is stored. The\n * body names the user, never the key;\n * - `user.apiKeyRevoked` — by every path that revokes keys: `apiKeys.revoke`,\n * `revokeAll` and `revokeAllBound`, a password reset and the first proof\n * of an e-mail that revoke the user's keys. **One event per call**, carrying\n * `count`, the keys it ended; a call that ended none sends none (revoking\n * a revoked key included). Never by `delete`, which sends `user.deleted`;\n * - `user.deleted` — by `delete`, once; a replay that finds nobody is none.\n */\nexport type UserEventType =\n\t| 'user.created'\n\t| 'user.emailVerified'\n\t| 'user.passwordReset'\n\t| 'user.passwordChanged'\n\t| 'user.emailChanged'\n\t| 'user.secondFactorEnabled'\n\t| 'user.secondFactorDisabled'\n\t| 'user.recoveryCodesRegenerated'\n\t| 'user.recoveryCodeUsed'\n\t| 'user.newDeviceSignedIn'\n\t| 'user.avatarChanged'\n\t| 'user.avatarRemoved'\n\t| 'user.socialLinked'\n\t| 'user.socialUnlinked'\n\t| 'user.passkeyAdded'\n\t| 'user.passkeyRemoved'\n\t| 'user.passkeyCloneSuspected'\n\t| 'user.apiKeyCreated'\n\t| 'user.apiKeyRevoked'\n\t| 'user.deleted';\n\n/**\n * A user event: **the user named by id, and nothing else** — no login, no\n * field, no password, no token. Whoever receives it reads the rest from where\n * it is kept, if they may. Three exceptions: `formerEmail` on\n * `user.emailChanged` — once the write landed, the old address is kept\n * nowhere — `sessionId` on `user.newDeviceSignedIn`, the session the new\n * device holds, and `formerAvatarId` on the two avatar events, the id of the\n * image the write let go, and `provider` on the two social events, the\n * application's name for the provider — never the account's id.\n */\nexport interface UserEvent {\n\t/** A UUIDv7 minted for this event: the key to deliver it once. */\n\treadonly id: Id;\n\treadonly type: UserEventType;\n\t/**\n\t * When the write landed: the `createdAt` or `updatedAt` it wrote, or, for\n\t * a deletion, the time read just before it — not when the listener ran.\n\t */\n\treadonly occurredAt: Date;\n\treadonly userId: Id;\n\treadonly userType: string;\n\t/**\n\t * On `user.emailChanged` only: the address the user had before, as it was\n\t * stored — `null` when they had none. So a notice can reach the inbox the\n\t * account was just taken from; the new address is on the user. Absent\n\t * from every other type, and from an event a webhook delivered.\n\t */\n\treadonly formerEmail?: string | null;\n\t/**\n\t * On `user.newDeviceSignedIn` only: the session the new device opened —\n\t * to sign it out from a \"this wasn't me\" page. Absent from every other\n\t * type, and from an event a webhook delivered.\n\t */\n\treadonly sessionId?: string;\n\t/**\n\t * On `user.avatarChanged` and `user.avatarRemoved` only: the avatar id the\n\t * user had before — `null` on a first `avatar.set` — so the application can\n\t * delete that image from its storage. Always a string on\n\t * `user.avatarRemoved`. Absent from every other type, and from an event a\n\t * webhook delivered.\n\t */\n\treadonly formerAvatarId?: string | null;\n\t/**\n\t * On `user.passwordChanged` only: `true` when the user had no password\n\t * before the write — `setPassword` on an account created without a\n\t * credential — and `false` for a change, or a first proof that dropped a\n\t * password. Absent from every other type, and from an event a webhook\n\t * delivered.\n\t */\n\treadonly first?: boolean;\n\t/**\n\t * On `user.socialLinked` and `user.socialUnlinked` only: the application's\n\t * name for the provider (`'google'`). **Never the provider's account id**,\n\t * nor its e-mail. Absent from every other type.\n\t */\n\treadonly provider?: string;\n\t/**\n\t * On the three passkey events only: which passkey, and\n\t * the name the user gave it — for a \"passkey added\" or \"clone suspected\"\n\t * notice. Stays in the\n\t * process, like `formerEmail`: an event a webhook delivers does not carry it.\n\t */\n\treadonly passkey?: {\n\t\treadonly credentialId: string;\n\t\treadonly name: string;\n\t};\n\t/**\n\t * On `user.apiKeyRevoked` only: how many keys the call revoked, 1 or more.\n\t * Never a key id or a secret. Stays in the process: an event a webhook\n\t * delivers does not carry it.\n\t */\n\treadonly count?: number;\n}\n\n/** What an event carries beyond the user, on the types that do. */\nexport type EventExtras = Pick<\n\tUserEvent,\n\t| 'formerEmail'\n\t| 'sessionId'\n\t| 'formerAvatarId'\n\t| 'first'\n\t| 'provider'\n\t| 'passkey'\n\t| 'count'\n>;\n\n/**\n * What `janus({ events })` takes: called once per event, **after** the write\n * landed and before the flow answers — awaited, so a queue that stores the\n * event durably has done so by then. A listener that throws fails nothing:\n * the write happened, and the flow answers as it would have. The failure is a\n * `JANUS_EVENT_FAILED` warning naming the event, never silence.\n */\nexport type UserEventListener = (event: UserEvent) => void | Promise<void>;\n\n/** The listener given to `janus()`, or a wiring refusal for a JavaScript caller. */\nexport function resolveEvents(\n\tevents: unknown,\n\twhere: string,\n): UserEventListener | null {\n\tif (events === undefined) return null;\n\tif (typeof events !== 'function') {\n\t\tthrow new TypeError(\n\t\t\t`${where}: events must be a function that takes a user event — webhooks({ … }) from @softistx/janus-webhooks, or your own`,\n\t\t);\n\t}\n\treturn events as UserEventListener;\n}\n\n/**\n * Hands one event to the listener after the write it reports. A flow whose\n * steps after the write matter to the listener — a reset's revocation, a\n * deletion's cleanup — runs them in a `try` and emits from its `finally`, so\n * an outage there does not lose the event for good. Its failure is the application's, not the flow's: warned about, with what\n * it takes to send the event again — never thrown, since the write has landed.\n */\nexport async function emit(\n\tcontext: Context,\n\ttype: UserEventType,\n\tuser: { readonly id: Id; readonly type: string },\n\toccurredAt: Date,\n\textras: EventExtras = {},\n): Promise<void> {\n\tconst listener = context.events;\n\tif (listener === null) return;\n\n\tconst event: UserEvent = Object.freeze({\n\t\tid: mintId(occurredAt.getTime()),\n\t\ttype,\n\t\t// A copy: the record's own Date is also the user the flow answers.\n\t\toccurredAt: new Date(occurredAt.getTime()),\n\t\tuserId: user.id,\n\t\tuserType: user.type,\n\t\t...extras,\n\t});\n\ttry {\n\t\tawait listener(event);\n\t} catch (failure) {\n\t\tprocess.emitWarning(\n\t\t\t`janus: the events listener failed on ${type} ${event.id} for user ${user.id}: ${failure instanceof Error ? failure.name : typeof failure}`,\n\t\t\t{ code: 'JANUS_EVENT_FAILED' },\n\t\t);\n\t}\n}\n",
|
|
37
|
+
"import type { ResolvedType } from '../config';\nimport { type AnyUser, type Context, toUser, writeUser } from '../context';\nimport { emit } from '../events';\nimport type { UserRef, WriteOptions } from '../types';\n\n/**\n * Clears the user's avatar. A user who had none writes nothing and reports\n * nothing; one who had is reported with the id it had, so the application can\n * delete that image.\n */\nexport async function removeAvatar(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tuser: UserRef,\n\toptions: WriteOptions | undefined,\n\twhere: string,\n): Promise<AnyUser> {\n\tconst outcome: { former: string | null } = { former: null };\n\tconst written = await writeUser(\n\t\tcontext,\n\t\tuser,\n\t\ttype,\n\t\toptions,\n\t\twhere,\n\t\t(record) => {\n\t\t\toutcome.former = record.avatar?.id ?? null;\n\t\t\treturn outcome.former === null ? null : { avatar: null };\n\t\t},\n\t);\n\tif (outcome.former !== null) {\n\t\tawait emit(context, 'user.avatarRemoved', written, written.updatedAt, {\n\t\t\tformerAvatarId: outcome.former,\n\t\t});\n\t}\n\treturn toUser(written);\n}\n",
|
|
38
|
+
"import type { ResolvedType } from '../config';\nimport { type AnyUser, type Context, toUser, writeUser } from '../context';\nimport { emit } from '../events';\nimport type { UserRef, WriteOptions } from '../types';\nimport { avatarIdOf } from './id';\n\n/**\n * Points the user at the image the application stored under `avatar.id`.\n * Setting the id the user already has writes nothing and reports nothing:\n * the image is the same, and so is the record. A different one is reported\n * with the id it replaced, the only place the application learns which image\n * to delete.\n */\nexport async function setAvatar(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tuser: UserRef,\n\tavatar: unknown,\n\toptions: WriteOptions | undefined,\n\twhere: string,\n): Promise<AnyUser> {\n\tconst id = avatarIdOf(avatar, where);\n\tconst outcome: { former: string | null; changed: boolean } = {\n\t\tformer: null,\n\t\tchanged: false,\n\t};\n\tconst written = await writeUser(\n\t\tcontext,\n\t\tuser,\n\t\ttype,\n\t\toptions,\n\t\twhere,\n\t\t(record, now) => {\n\t\t\toutcome.former = record.avatar?.id ?? null;\n\t\t\tif (outcome.former === id) return null;\n\t\t\toutcome.changed = true;\n\t\t\treturn { avatar: { id, updatedAt: now } };\n\t\t},\n\t);\n\tif (outcome.changed) {\n\t\tawait emit(context, 'user.avatarChanged', written, written.updatedAt, {\n\t\t\tformerAvatarId: outcome.former,\n\t\t});\n\t}\n\treturn toUser(written);\n}\n",
|
|
39
|
+
"/**\n * The avatar at the root of an instance with several user types: for the\n * page that holds a user's id and does not know the user's type.\n */\n\nimport { NotFoundError } from '../../errors/janus-error';\nimport { type AnyUser, type Context, getRecord, idOf } from '../context';\nimport type { AvatarApi, UserRef } from '../types';\nimport { avatarIdOf } from './id';\nimport { removeAvatar } from './remove';\nimport { setAvatar } from './set';\n\n/**\n * `{ avatar: { set, remove } }`: reads the user's record to find their type,\n * then does what that type's `avatar` does — the same write, event and\n * refusals. A user nobody holds is `NOT_FOUND`, whatever the type.\n */\nexport function anyTypeAvatar(context: Context): AvatarApi<AnyUser> {\n\tconst typeOf = async (user: UserRef, where: string) => {\n\t\tconst id = idOf(user);\n\t\tconst record = await getRecord(context, id, null, where);\n\t\tconst type = context.config.types.get(record.type);\n\t\t// A record of a type this configuration does not declare is not one of\n\t\t// its users: as good as absent.\n\t\tif (type === undefined) {\n\t\t\tthrow new NotFoundError(`${where}: no user has this id`, {\n\t\t\t\tuserId: id,\n\t\t\t\toperation: where,\n\t\t\t});\n\t\t}\n\t\treturn type;\n\t};\n\n\treturn {\n\t\tavatar: {\n\t\t\tasync set(user, avatar, options) {\n\t\t\t\tconst where = 'avatar.set';\n\t\t\t\t// Before the read: a refused id reaches no store.\n\t\t\t\tavatarIdOf(avatar, where);\n\t\t\t\tconst type = await typeOf(user, where);\n\t\t\t\treturn setAvatar(context, type, user, avatar, options, where);\n\t\t\t},\n\t\t\tasync remove(user, options) {\n\t\t\t\tconst where = 'avatar.remove';\n\t\t\t\tconst type = await typeOf(user, where);\n\t\t\t\treturn removeAvatar(context, type, user, options, where);\n\t\t\t},\n\t\t},\n\t};\n}\n",
|
|
40
|
+
"import type { At } from '../at';\nimport type { ResolvedType } from '../config';\nimport type { AnyUser, Context } from '../context';\nimport type { AvatarApi } from '../types';\nimport { removeAvatar } from './remove';\nimport { setAvatar } from './set';\n\n/** `avatar` of one user type: `set` the image its user points at, or `remove` it. */\nexport function avatarFlows(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tat: At,\n): AvatarApi<AnyUser>['avatar'] {\n\treturn {\n\t\tset: (user, avatar, options) =>\n\t\t\tsetAvatar(context, type, user, avatar, options, at('avatar.set')),\n\t\tremove: (user, options) =>\n\t\t\tremoveAvatar(context, type, user, options, at('avatar.remove')),\n\t};\n}\n",
|
|
41
|
+
"/**\n * The one wiring mistake the mail throttle cannot refuse: a `tokens.*`\n * lifetime shorter than `mail.throttle.window`. A refused request spends\n * nothing, so the last link or code sent keeps working, but only while it has\n * not expired: with a shorter lifetime it can lapse before the refusal ends.\n * That is a choice an application may make on purpose, so it is a warning,\n * emitted once per `janus()` call, never an error.\n */\n\nimport type { ResolvedConfig } from './resolved-config';\n\n/** The flows the mail throttle counts, in the order a warning names them. */\nconst FLOWS = [\n\t'magicLink',\n\t'signInCode',\n\t'resetPassword',\n\t'verifyEmail',\n\t'stepUp',\n\t'changeEmail',\n] as const;\n\nconst UNITS: readonly (readonly [string, number])[] = [\n\t['d', 86_400_000],\n\t['h', 3_600_000],\n\t['m', 60_000],\n\t['s', 1_000],\n];\n\n/** `600000` as `10m`: the largest unit that divides it exactly. */\nfunction show(ms: number): string {\n\tconst unit = UNITS.find(([, size]) => ms % size === 0);\n\treturn unit === undefined ? `${ms}ms` : `${ms / unit[1]}${unit[0]}`;\n}\n\n/** The warning's text, or `null` when no lifetime is shorter than the window. */\nexport function throttleWindowMessage(\n\tresolved: Pick<ResolvedConfig, 'mailThrottle' | 'tokenTtlMs'>,\n\twhere: string,\n): string | null {\n\tconst throttle = resolved.mailThrottle;\n\tif (throttle === null) return null;\n\tconst window = show(throttle.windowMs);\n\tconst shorter = FLOWS.filter(\n\t\t(flow) => resolved.tokenTtlMs[flow] < throttle.windowMs,\n\t);\n\tif (shorter.length === 0) return null;\n\tconst shortest = Math.min(\n\t\t...shorter.map((flow) => resolved.tokenTtlMs[flow]),\n\t);\n\tconst parts = shorter.map(\n\t\t(flow) =>\n\t\t\t`tokens.${flow} is ${show(resolved.tokenTtlMs[flow])}, shorter than mail.throttle.window, ${window}`,\n\t);\n\treturn `${where}: ${parts.join('; ')} — past the limit the last ${shorter.length === 1 ? 'token' : 'tokens'} sent can expire before the refusal ends. Set mail.throttle.window to ${show(shortest)} or less, or raise ${shorter.map((flow) => `tokens.${flow}`).join(', ')} to ${window} or more.`;\n}\n\n/** Emits {@link throttleWindowMessage} through `process.emitWarning`, where the runtime has one. */\nexport function warnThrottleWindow(\n\tresolved: Pick<ResolvedConfig, 'mailThrottle' | 'tokenTtlMs'>,\n\twhere: string,\n): void {\n\tconst message = throttleWindowMessage(resolved, where);\n\tif (message === null) return;\n\tif (\n\t\ttypeof process === 'undefined' ||\n\t\ttypeof process.emitWarning !== 'function'\n\t) {\n\t\treturn;\n\t}\n\tprocess.emitWarning(message, { code: 'JANUS_THROTTLE_WINDOW' });\n}\n",
|
|
42
|
+
"import { createHmac, hkdfSync } from 'node:crypto';\nimport type { Sealer } from './sealing';\n\n/**\n * Keys derived from the sealing keys, one per purpose — never the key that\n * seals a secret itself — and the keyed hashes made with them: a recovery\n * code's, and the names of the counts of attempts. Each caller keeps its own\n * purpose: renamed, what it hashed no longer matches.\n */\n\nconst derived = new WeakMap<Sealer, Map<string, Buffer>>();\n\n/**\n * The key `keyId` lends `purpose` — the first key by default — derived once\n * per key, or `undefined` when the sealer no longer holds that key.\n */\nexport function derivedKey(\n\tsealer: Sealer,\n\tpurpose: string,\n\tkeyId: string = sealer.sealWith,\n): Buffer | undefined {\n\tlet keys = derived.get(sealer);\n\tif (keys === undefined) {\n\t\tkeys = new Map();\n\t\tderived.set(sealer, keys);\n\t}\n\tconst name = `${purpose}\\u0000${keyId}`;\n\tlet key = keys.get(name);\n\tif (key === undefined) {\n\t\tconst secret = sealer.keys.get(keyId);\n\t\tif (secret === undefined) return undefined;\n\t\tkey = Buffer.from(hkdfSync('sha256', secret, Buffer.alloc(0), purpose, 32));\n\t\tkeys.set(name, key);\n\t}\n\treturn key;\n}\n\n/** HMAC-SHA256 of `parts`, joined by a NUL — which no part may hold. */\nexport function keyedHash(key: Buffer, parts: readonly string[]): Buffer {\n\treturn createHmac('sha256', key).update(parts.join('\\u0000')).digest();\n}\n",
|
|
43
|
+
"/**\n * The key that names a count of attempts stored under no user — the\n * passwords tried at a login (`sign-in-attempts.ts`), the e-mails asked for\n * an address (`mail-requests.ts`) — and the keyed hashes made with it.\n *\n * Derived from the sealing keys when `secondFactor` is configured; without\n * them it is a fixed one, and the hash only keeps the login or the address\n * out of plain sight — safe because a `secondFactor` token is redeemed only\n * by the second factor's flows, which do not exist without the keys (a\n * first-factor passkey sign-in does not use this hash for a secret).\n */\n\nimport type { Context } from './context';\nimport { derivedKey, keyedHash } from './derived-keys';\n\n/**\n * The key `purpose` names its counts with. Renamed, a purpose's every count\n * in progress would start over.\n */\nexport function counterKey(context: Context, purpose: string): Buffer {\n\tconst sealer = context.config.secondFactor?.sealer;\n\t// The first key is always held: resolveSealer names it from the keys.\n\treturn sealer === undefined\n\t\t? Buffer.from(purpose)\n\t\t: (derivedKey(sealer, purpose) as Buffer);\n}\n\n/** A keyed hash of `parts`, base64url: a name, never a secret. */\nexport const keyed = (key: Buffer, parts: readonly string[]): string =>\n\tkeyedHash(key, parts).toString('base64url');\n",
|
|
44
|
+
"/**\n * The six-digit code a challenge carries — a second factor's or an e-mailed\n * one: its attempts, counted before anything is compared, its hash, keyed by\n * the challenge, and the refusal of one that does not match.\n */\n\nimport { timingSafeEqual } from 'node:crypto';\nimport { TokenError } from '../../errors/janus-error';\nimport type { Context } from '../context';\nimport type { TokenKind, TokenRecord } from '../port/types';\nimport { hashSecret } from '../secrets';\nimport { refuseUnusable, unknownOneTime } from './refusals';\nimport { burnOneTime } from './spend';\n\n/**\n * How many codes one challenge takes — a second factor's or an e-mail\n * code's. A six-digit code has a million values: five attempts is a\n * one-in-200,000 chance **per challenge**, and the attempts are counted by\n * the store in one write, never read then written.\n */\nexport const CODE_ATTEMPTS = 5;\n\n/**\n * Counts one attempt at a challenge's code, before anything is compared: a\n * guess that fails for any reason has still cost one. Refuses a challenge\n * that cannot be used, and one past its last attempt — a call that raced the\n * one that spent it — unread.\n */\nexport async function countCodeAttempt(\n\tcontext: Context,\n\tsecret: string,\n\tkind: TokenKind,\n\twhere: string,\n\tuserType: string,\n): Promise<{ readonly token: TokenRecord; readonly attemptsLeft: number }> {\n\tconst token = await context.store.tokens.countAttempt(\n\t\thashSecret(secret),\n\t\tkind,\n\t);\n\trefuseUnusable(token, context.clock.now(), where, 'challenge');\n\tif (token.attempts > CODE_ATTEMPTS) {\n\t\tthrow codeInvalid(where, token.userId, userType, 0);\n\t}\n\treturn { token, attemptsLeft: CODE_ATTEMPTS - token.attempts };\n}\n\n/**\n * A code that does not match — a second factor's or an e-mailed one — or a\n * TOTP code already used. `attemptsLeft` only when a challenge counted it.\n */\nexport function codeInvalid(\n\twhere: string,\n\tuserId: string,\n\tuserType: string,\n\tattemptsLeft?: number,\n): TokenError {\n\treturn new TokenError(\n\t\t'CODE_INVALID',\n\t\t`${where}: the code does not match, or was already used`,\n\t\t{\n\t\t\toperation: where,\n\t\t\tuserId,\n\t\t\tuserType,\n\t\t\t...(attemptsLeft === undefined ? {} : { attemptsLeft }),\n\t\t},\n\t);\n}\n\n/**\n * The refusal for a challenge whose user is gone, or of another type — the\n * API of the wrong type compares no code. Its attempt was counted all the\n * same, before the type was known, so the last one spends the challenge, as\n * a wrong code would: past it, every call answers `TOKEN_SPENT`.\n */\nexport async function unknownChallenge(\n\tcontext: Context,\n\ttoken: TokenRecord,\n\tsecret: string,\n\twhere: string,\n): Promise<TokenError> {\n\tif (token.attempts === CODE_ATTEMPTS) {\n\t\tawait burnOneTime(context, secret, token.kind);\n\t}\n\treturn unknownOneTime(where, 'challenge');\n}\n\n/**\n * A code's hash, **keyed by its challenge**: the tokens alone — a dump, a\n * log of the table — do not reveal the code, since a million guesses at it\n * each need the challenge, which only the visitor holds.\n */\nexport const hashCode = (challenge: string, code: string): string =>\n\thashSecret(`${challenge}${code}`);\n\n/** Whether `code` is the one whose hash the token holds, compared in constant time. */\nexport function codeMatches(\n\ttoken: TokenRecord,\n\tchallenge: string,\n\tcode: string,\n): boolean {\n\tif (token.codeHash === null || !/^\\d{6}$/.test(code)) return false;\n\tconst given = Buffer.from(hashCode(challenge, code));\n\tconst held = Buffer.from(token.codeHash);\n\treturn given.length === held.length && timingSafeEqual(given, held);\n}\n",
|
|
45
|
+
"import { createHash, randomBytes } from 'node:crypto';\n\n/**\n * A fresh secret: 32 random bytes, base64url — safe in a header, a cookie and a\n * URL without escaping.\n *\n * Given to the application **once**. No store ever holds it.\n */\nexport function mintSecret(): string {\n\treturn randomBytes(32).toString('base64url');\n}\n\n/**\n * What a store holds instead of the secret: `sha256`, hex.\n *\n * SHA-256 and not argon2, on purpose. The secret carries 256 bits of entropy, so\n * there is nothing to brute-force, and an argon2 per request would put ~50 ms on\n * every authenticated call. What the hash buys is that a dump of the store\n * cannot be replayed.\n */\nexport function hashSecret(secret: string): string {\n\treturn createHash('sha256').update(secret).digest('hex');\n}\n",
|
|
46
|
+
"/**\n * The refusals of a one-time token that could not be used: none, spent,\n * lapsed, or sent to an e-mail the user no longer has.\n */\n\nimport { TokenError } from '../../errors/janus-error';\nimport { normalizeEmail, type ResolvedType } from '../config';\nimport { emailOf } from '../context';\nimport type { TokenRecord, UserRecord } from '../port/types';\n\n/**\n * `noun` is what the messages call it: `token` for a link, `challenge` for\n * what `signIn` answers. No message names the secret or its hash.\n */\nexport type OneTimeNoun = 'token' | 'challenge';\n\n/**\n * Refuses a token sent to an e-mail the user no longer has: redeeming it\n * would prove an address nobody holds any more.\n */\nexport function refuseStale(\n\ttype: ResolvedType,\n\tuser: UserRecord,\n\ttoken: TokenRecord,\n\twhere: string,\n\tnoun: 'token' | 'code',\n): void {\n\tconst email = emailOf(type, user.fields);\n\tif (\n\t\temail === null ||\n\t\tnormalizeEmail(email) !== normalizeEmail(token.address)\n\t) {\n\t\tthrow new TokenError(\n\t\t\t'TOKEN_STALE',\n\t\t\t`${where}: the ${noun} was sent to an e-mail the user no longer has`,\n\t\t\t{ operation: where, userId: user.id, userType: type.name },\n\t\t);\n\t}\n}\n\n/**\n * Refuses a token that cannot be used: none, spent, or lapsed. What a store\n * answered — before a `consumeToken`, after a `countAttempt` — is read the\n * same way: `spentAt` set means somebody else used it.\n */\nexport function refuseUnusable(\n\ttoken: TokenRecord | null,\n\tnow: Date,\n\twhere: string,\n\tnoun: OneTimeNoun,\n): asserts token is TokenRecord {\n\tif (token === null) {\n\t\tthrow new TokenError('TOKEN_UNKNOWN', `${where}: no such ${noun}`, {\n\t\t\toperation: where,\n\t\t});\n\t}\n\tif (token.spentAt !== null) {\n\t\tthrow new TokenError(\n\t\t\t'TOKEN_SPENT',\n\t\t\t`${where}: the ${noun} was already used`,\n\t\t\t{ operation: where },\n\t\t);\n\t}\n\tif (token.expiresAt.getTime() <= now.getTime()) {\n\t\tthrow new TokenError('TOKEN_EXPIRED', `${where}: the ${noun} has expired`, {\n\t\t\toperation: where,\n\t\t});\n\t}\n}\n\n/** The refusal for a token whose user is gone, or of another type. */\nexport const unknownOneTime = (where: string, noun: OneTimeNoun) =>\n\tnew TokenError('TOKEN_UNKNOWN', `${where}: no such ${noun}`, {\n\t\toperation: where,\n\t});\n",
|
|
47
|
+
"/**\n * Spending a one-time token: once when it is redeemed, and once more when its\n * last attempt failed.\n */\n\nimport type { Id } from '../../ids/id';\nimport type { Context } from '../context';\nimport type { TokenKind, TokenRecord } from '../port/types';\nimport { hashSecret } from '../secrets';\nimport { type OneTimeNoun, refuseUnusable, unknownOneTime } from './refusals';\n\nconst warned = new WeakSet<object>();\n\n/** Warns once per store that its `consumeToken` answered a token of another user. */\nfunction warnIgnoredUserId(tokens: object): void {\n\tif (warned.has(tokens)) return;\n\twarned.add(tokens);\n\tprocess.emitWarning(\n\t\t'tokens.consumeToken answered a token of another user although a userId was given: the store ignores its fourth argument. The call was refused, but the token was spent. Put userId in the consumeToken condition and run describeJanusStores (tokens.consumeBound).',\n\t\t{ code: 'JANUS_TOKEN_STORE_IGNORES_USER_ID' },\n\t);\n}\n\n/**\n * Spends a token, and refuses it when this call did not: the store answers it\n * **as it was before**, so exactly one call ever reads `spentAt: null`. A\n * lapsed token is spent all the same, so it cannot be retried.\n *\n * With `userId`, the token must be that user's: another's is refused as\n * unknown and is not spent, the store checking it in the same write.\n */\nexport async function spendOneTime(\n\tcontext: Context,\n\tsecret: string,\n\tkind: TokenKind,\n\twhere: string,\n\tnoun: OneTimeNoun,\n\tuserId?: Id,\n): Promise<TokenRecord> {\n\tconst now = context.clock.now();\n\tconst token = await context.store.tokens.consumeToken(\n\t\thashSecret(secret),\n\t\tkind,\n\t\tnow,\n\t\tuserId,\n\t);\n\t// Fail closed: a store that ignored `userId` has answered another user's\n\t// token. It is refused as unknown, and the store is reported once.\n\tif (userId !== undefined && token !== null && token.userId !== userId) {\n\t\twarnIgnoredUserId(context.store.tokens);\n\t\tthrow unknownOneTime(where, noun);\n\t}\n\trefuseUnusable(token, now, where, noun);\n\treturn token;\n}\n\n/**\n * Spends a token whose last attempt failed. Its answer is not read: a racing\n * call that spent it first changes nothing for this one, which is refused\n * for its code either way.\n */\nexport async function burnOneTime(\n\tcontext: Context,\n\tsecret: string,\n\tkind: TokenKind,\n): Promise<void> {\n\tawait context.store.tokens.consumeToken(\n\t\thashSecret(secret),\n\t\tkind,\n\t\tcontext.clock.now(),\n\t);\n}\n",
|
|
48
|
+
"/**\n * Issuing a one-time token — a link's, or a challenge carrying a code for a\n * person to type. The secret is given back once; the store holds its hash.\n */\n\nimport { randomInt } from 'node:crypto';\nimport type { Context } from '../context';\nimport type { TokenKind } from '../port/types';\nimport { hashSecret, mintSecret } from '../secrets';\nimport { hashCode } from './codes';\n\ninterface OneTimeRequest {\n\treadonly kind: TokenKind;\n\treadonly userId: string;\n\treadonly address: string;\n\treadonly ttlMs: number;\n\t/** The methods a second-factor challenge's first factor proved; kept only when there are some. */\n\treadonly amr?: readonly string[];\n\t/**\n\t * The secret to issue under, minted beforehand — a sign-in code's\n\t * challenge, handed to the visitor by `prepare` before the lookup. A\n\t * fresh one by default.\n\t */\n\treadonly secret?: string;\n}\n\n/**\n * Issues a one-time token: 32 random bytes, given back once, and only their\n * hash stored.\n */\nexport async function issueOneTime(\n\tcontext: Context,\n\ttoken: OneTimeRequest & {\n\t\t/**\n\t\t * What the token is bound to, stored as its `codeHash`: `changeEmail`\n\t\t * binds the address it replaces. `null` by default.\n\t\t */\n\t\treadonly boundHash?: string;\n\t},\n): Promise<{ readonly secret: string; readonly expiresAt: Date }> {\n\treturn insertOneTime(context, token, null, token.boundHash ?? null);\n}\n\n/**\n * Issues a one-time token with a six-digit code for a person to type: the\n * token is the challenge, and only the code's hash is stored, keyed by it.\n */\nexport async function issueCode(\n\tcontext: Context,\n\ttoken: OneTimeRequest,\n): Promise<{\n\treadonly secret: string;\n\treadonly expiresAt: Date;\n\treadonly code: string;\n}> {\n\tconst code = String(randomInt(1_000_000)).padStart(6, '0');\n\treturn { ...(await insertOneTime(context, token, code, null)), code };\n}\n\nasync function insertOneTime(\n\tcontext: Context,\n\ttoken: OneTimeRequest,\n\tcode: string | null,\n\tboundHash: string | null,\n): Promise<{ readonly secret: string; readonly expiresAt: Date }> {\n\tconst now = context.clock.now();\n\tconst secret = token.secret ?? mintSecret();\n\tconst expiresAt = new Date(now.getTime() + token.ttlMs);\n\n\tawait context.store.tokens.insertToken({\n\t\ttokenHash: hashSecret(secret),\n\t\tkind: token.kind,\n\t\tuserId: token.userId,\n\t\taddress: token.address,\n\t\t...(token.amr === undefined || token.amr.length === 0\n\t\t\t? {}\n\t\t\t: { amr: [...token.amr] }),\n\t\tcodeHash: code === null ? boundHash : hashCode(secret, code),\n\t\tattempts: 0,\n\t\texpiresAt,\n\t\tspentAt: null,\n\t\tcreatedAt: now,\n\t});\n\treturn { secret, expiresAt };\n}\n",
|
|
49
|
+
"/**\n * Attempts counted by the store in fixed windows of the clock — what bounds\n * the codes tried at an app outside a sign-in (`second-factor/app-code-attempts.ts`)\n * and the passwords tried at one login (`../sign-in-attempts.ts`).\n *\n * **No port of its own.** The count is a one-time token of kind\n * `secondFactor`, counted by `countAttempt` like a challenge's: one\n * conditional write per attempt, never read then written, so twenty guesses\n * at once are twenty distinct counts. Its secret is never given out: each\n * caller names it by a keyed hash of what the count is for, so it cannot be\n * redeemed as a challenge.\n *\n * A token once spent counts nothing more. So the count is a **chain** of\n * links, and what a spent link means is the caller's to say: `carry`, and the\n * next link carries on from the attempts it holds — a password written, which\n * spends every `secondFactor` token of the user, buys no guess; `restart`,\n * and the next link starts from zero — a sign-in that succeeded spends the\n * link it counted on, and the login's count starts again.\n */\n\nimport type { Context } from '../context';\nimport type { TokenRecord } from '../port/types';\n\n/**\n * More links than this in one window, for `carry`: more passwords written\n * than guesses, and the count is past any limit.\n */\nexport const MAX_LINKS = 32;\n\n/**\n * Probes enough for 2^30 sign-ins in one window, for `restart`: past them, the\n * store answers links nobody stored, and the count fails closed.\n */\nconst MAX_PROBES = 64;\n\n/** What {@link countInWindow} counts, and how. */\nexport interface AttemptWindow {\n\t/** How long one window lasts, in milliseconds. */\n\treadonly windowMs: number;\n\t/** What a spent link means: its attempts carried on, or a count started again. */\n\treadonly spent: 'carry' | 'restart';\n\t/** The `userId` each link is stored under. */\n\treadonly userId: string;\n\t/** A link's token hash in one window: never given out, and never a secret. */\n\treadonly linkHash: (window: number, link: number) => string;\n\t/** What to throw when a link is gone right after it was stored, or the links never end. */\n\treadonly vanished: () => Error;\n}\n\n/** One attempt, counted. */\nexport interface CountedAttempt {\n\t/** The attempts of this window, this one included. */\n\treadonly attempts: number;\n\t/** The link it was counted on — what spending restarts — or `null` past the last one. */\n\treadonly link: string | null;\n\t/** When the window ends, in milliseconds since the epoch. */\n\treadonly endsAt: number;\n}\n\ninterface Links {\n\treadonly context: Context;\n\treadonly counting: AttemptWindow;\n\treadonly window: number;\n\treadonly now: number;\n\treadonly expiresAt: number;\n}\n\n/** Counts one attempt in the current window, before anything is compared. */\nexport async function countInWindow(\n\tcontext: Context,\n\tcounting: AttemptWindow,\n): Promise<CountedAttempt> {\n\tconst now = context.clock.now().getTime();\n\tconst window = Math.floor(now / counting.windowMs);\n\t// A window of slack: a store whose clock runs ahead of this one must not\n\t// drop a link before its window ends. The window is in the hash, so a\n\t// link never counts for the next one.\n\tconst expiresAt = (window + 2) * counting.windowMs;\n\tconst links = { context, counting, window, now, expiresAt };\n\tconst counted =\n\t\tcounting.spent === 'carry'\n\t\t\t? await countCarrying(links)\n\t\t\t: await countRestarting(links);\n\treturn { ...counted, endsAt: (window + 1) * counting.windowMs };\n}\n\n/** Every link from the first, each spent one's attempts carried on. */\nasync function countCarrying(\n\tlinks: Links,\n): Promise<Omit<CountedAttempt, 'endsAt'>> {\n\tlet carried = 0;\n\tfor (let link = 0; link < MAX_LINKS; link += 1) {\n\t\tconst hash = links.counting.linkHash(links.window, link);\n\t\tconst counted = await countLink(links, hash);\n\t\tconst attempts = carried + counted.attempts;\n\t\tif (counted.spentAt === null) return { attempts, link: hash };\n\t\tcarried = attempts;\n\t}\n\treturn { attempts: Number.POSITIVE_INFINITY, link: null };\n}\n\n/**\n * The one unspent link, found by probing rather than walked to: a link is\n * stored only once the one before it is spent, so every link below it is\n * spent and none above it is stored. Probing a spent link or one never\n * stored writes nothing; probing the unspent one counts the attempt. So a\n * login signed in to a thousand times in one window costs twenty probes,\n * not a thousand — and no number of sign-ins turns the count off.\n */\nasync function countRestarting(\n\tlinks: Links,\n): Promise<Omit<CountedAttempt, 'endsAt'>> {\n\tconst tokens = links.context.store.tokens;\n\tlet spent = -1;\n\tlet absent = Number.POSITIVE_INFINITY;\n\tfor (let probes = 0; probes < MAX_PROBES; probes += 1) {\n\t\tconst next = absent === spent + 1;\n\t\tconst link = next\n\t\t\t? absent\n\t\t\t: absent === Number.POSITIVE_INFINITY\n\t\t\t\t? 2 * spent + 2\n\t\t\t\t: Math.floor((spent + absent) / 2);\n\t\tconst hash = links.counting.linkHash(links.window, link);\n\t\tconst counted = next\n\t\t\t? await insertLink(links, hash)\n\t\t\t: await tokens.countAttempt(hash, 'secondFactor');\n\t\tif (counted === null) absent = link;\n\t\telse if (counted.spentAt === null) {\n\t\t\treturn { attempts: counted.attempts, link: hash };\n\t\t} else {\n\t\t\tspent = link;\n\t\t\t// Spent by a sign-in that raced this one: look further on.\n\t\t\tif (absent <= spent) absent = Number.POSITIVE_INFINITY;\n\t\t}\n\t}\n\t// A store whose links never end: it cannot be counting what it stores.\n\tthrow links.counting.vanished();\n}\n\n/** One attempt on one link: inserted on the first, and counted. */\nasync function countLink(\n\tlinks: Links,\n\ttokenHash: string,\n): Promise<TokenRecord> {\n\tconst tokens = links.context.store.tokens;\n\tconst counted = await tokens.countAttempt(tokenHash, 'secondFactor');\n\treturn counted ?? insertLink(links, tokenHash);\n}\n\n/** A link stored — idempotent: of two first attempts at once, one inserts — and counted. */\nasync function insertLink(\n\tlinks: Links,\n\ttokenHash: string,\n): Promise<TokenRecord> {\n\tconst tokens = links.context.store.tokens;\n\tawait tokens.insertToken({\n\t\ttokenHash,\n\t\tkind: 'secondFactor',\n\t\tuserId: links.counting.userId,\n\t\taddress: '',\n\t\tcodeHash: null,\n\t\tattempts: 0,\n\t\texpiresAt: new Date(links.expiresAt),\n\t\tspentAt: null,\n\t\tcreatedAt: new Date(links.now),\n\t});\n\tconst inserted = await tokens.countAttempt(tokenHash, 'secondFactor');\n\tif (inserted !== null) return inserted;\n\tthrow links.counting.vanished();\n}\n",
|
|
50
|
+
"/**\n * The requests that hand out something to e-mail, counted by the store per\n * window — `janus({ mail: { throttle } })`, five per ten minutes by\n * default. Past the last one, the request answers `MAIL_THROTTLED` with\n * `retryAfter`, and **issues nothing**: no token is minted, so there is\n * nothing to send — and **nothing is spent**: counted before anything is\n * issued, a refused request never reaches the step that spends the earlier\n * tokens, so the last link or code sent still works. Nothing locks past a\n * window. With the default lifetimes, the window (`'10m'`) is no longer than\n * any token's, so the last one sent — issued in the window — outlives the\n * refusal: somebody who asks for an address in a loop mails its owner real\n * links, and the last of them signs in.\n *\n * **Each flow counts on its own**, so a loop on one — a sign-in link asked\n * for again and again — never shuts another, and what one address can be\n * sent is bounded per flow:\n *\n * - **per address**, for the requests anybody can make with an e-mail —\n * `magicLink.request`, `signInCode.request`, `resetPassword.request`,\n * `signUp.prepare` and `verifyEmail.prepare`.\n * Counted **before anything is looked up**, the address normalised, and\n * whatever the user type: an address nobody holds is counted, and refused\n * past the limit, as a registered one is, so being throttled never tells\n * who has an account;\n * - **per user**, for the requests the application makes for a user it\n * knows — `verifyEmail.send`, `changeEmail.send` (and, for the address it\n * names, per address too), and `stepUp.request` when it e-mails a code.\n * Nobody without the user's session or the application's call can spend\n * that count, so a loop on their address leaves their own requests alone;\n * and whatever addresses one user moves through, they are sent at most as\n * many.\n *\n * Counted in an attempt window (`one-time/window.ts`), in `secondFactor`\n * tokens stored under no user: the `userId` of each is a keyed hash of the\n * flow and the address or the user (`counter-key.ts`). Nothing spends a\n * link, and one that is spent carries its count on: the count never starts\n * again before its window ends.\n *\n * A store that cannot count throws `STORE_FAILED`: never a refusal, and\n * never a request let through uncounted.\n */\n\nimport { MailThrottledError, StoreFailure } from '../errors/janus-error';\nimport { normalizeEmail, type ResolvedType } from './config';\nimport type { Context } from './context';\nimport { counterKey, keyed } from './counter-key';\nimport { countInWindow } from './one-time';\nimport { hashSecret } from './secrets';\n\n/** What the key is derived for. Renamed, every count in progress would start over. */\nconst PURPOSE = 'janus/mail/requests/v1';\n\n/** The flows that hand out something to e-mail, each counted on its own. */\nexport type MailFlow =\n\t| 'magicLink'\n\t| 'signInCode'\n\t| 'resetPassword'\n\t| 'verifyEmail'\n\t| 'signUp'\n\t| 'stepUp'\n\t| 'changeEmail';\n\n/**\n * Who a request is counted for: the address it names (and, when the request\n * is a user's, the user it is made for, carried by a refusal), or the user.\n */\ntype Counted =\n\t| { readonly address: string; readonly userId?: string }\n\t| { readonly userId: string };\n\n/**\n * Counts one request of `flow` for `email` — before it is looked up — and\n * refuses past the last one, whether anybody holds the address or not.\n * `userId`, for a request made for a user (`changeEmail.send`), is only\n * carried by the refusal; the count stays the address's.\n */\nexport async function countMailByAddress(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tflow: MailFlow,\n\temail: string,\n\twhere: string,\n\tuserId?: string,\n): Promise<void> {\n\tawait countMail(\n\t\tcontext,\n\t\ttype,\n\t\tflow,\n\t\t{\n\t\t\taddress: normalizeEmail(email),\n\t\t\t...(userId === undefined ? {} : { userId }),\n\t\t},\n\t\twhere,\n\t);\n}\n\n/** Counts one request of `flow` for the user `userId`, and refuses past the last one. */\nexport async function countMailByUser(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tflow: MailFlow,\n\tuserId: string,\n\twhere: string,\n): Promise<void> {\n\tawait countMail(context, type, flow, { userId }, where);\n}\n\nasync function countMail(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tflow: MailFlow,\n\tcounted: Counted,\n\twhere: string,\n): Promise<void> {\n\tconst throttle = context.config.mailThrottle;\n\tif (throttle === null) return;\n\tconst key = counterKey(context, PURPOSE);\n\tconst subject =\n\t\t'address' in counted\n\t\t\t? keyed(key, [flow, 'address', counted.address])\n\t\t\t: keyed(key, [flow, 'user', counted.userId]);\n\tconst { attempts, endsAt } = await countInWindow(context, {\n\t\twindowMs: throttle.windowMs,\n\t\tspent: 'carry',\n\t\tuserId: subject,\n\t\tlinkHash: (window, link) =>\n\t\t\thashSecret(keyed(key, [subject, String(window), String(link)])),\n\t\t// A store that lost what it just stored cannot count: an outage.\n\t\tvanished: () =>\n\t\t\tnew StoreFailure(\n\t\t\t\t`${where}: the store dropped the requests it had just counted`,\n\t\t\t\t{ slot: 'tokens', operation: 'countAttempt' },\n\t\t\t),\n\t});\n\tif (attempts <= throttle.attempts) return;\n\n\tconst now = context.clock.now().getTime();\n\tthrow new MailThrottledError(\n\t\t`${where}: too many e-mails asked for this ${'address' in counted ? 'address' : 'user'} — the last one sent still works; use it, or wait for the next window`,\n\t\t{\n\t\t\tuserType: type.name,\n\t\t\t...(counted.userId === undefined ? {} : { userId: counted.userId }),\n\t\t\tretryAfter: Math.max(1, Math.ceil((endsAt - now) / 1000)),\n\t\t},\n\t);\n}\n",
|
|
51
|
+
"import { normalizeEmail, type ResolvedType } from '../config';\nimport { emailOf, loginsOf, nameKeyOf, validateFields } from '../context';\nimport type { JsonObject, UserRecord } from '../port/types';\nimport type { Input } from './flow-types';\n\nconst normalized = (email: string | null) =>\n\temail === null ? null : normalizeEmail(email);\n\n/**\n * Whether the e-mail differs between two sets of fields, compared normalised:\n * `Ada@Example.com` for `ada@example.com` is no change. The one test behind\n * both the new e-mail's verification reset and `user.emailChanged`.\n */\nexport function emailChanged(\n\ttype: ResolvedType,\n\tbefore: JsonObject,\n\tafter: JsonObject,\n): boolean {\n\treturn normalized(emailOf(type, before)) !== normalized(emailOf(type, after));\n}\n\n/**\n * What `update` writes: the patch merged over the stored fields, the whole\n * result validated, and the logins derived again from it.\n */\nexport async function fieldsPatch(\n\ttype: ResolvedType,\n\trecord: UserRecord,\n\tpatch: Input,\n\twhere: string,\n) {\n\tconst fields = await validateFields(\n\t\ttype,\n\t\t{ ...record.fields, ...patch },\n\t\twhere,\n\t);\n\n\treturn {\n\t\tfields,\n\t\tlogins: loginsOf(type, fields, where),\n\t\tnameKey: nameKeyOf(type, fields),\n\t\tschemaVersion: type.schemaVersion,\n\t\t// A new e-mail is an unproven one.\n\t\t...(emailChanged(type, record.fields, fields)\n\t\t\t? { emailVerifiedAt: null }\n\t\t\t: {}),\n\t};\n}\n",
|
|
52
|
+
"/**\n * The user a one-time token was issued to, and the type that owns them — the\n * lookup the e-mail flows' redemptions share.\n */\n\nimport type { ResolvedType } from '../config';\nimport { type Context, findRecord } from '../context';\nimport { unknownOneTime } from '../one-time';\nimport type { TokenRecord, UserRecord } from '../port/types';\n\n/**\n * The user `token` was issued to and their type: `type` when it is given, the\n * user's own when it is null. A user gone since, or of another type than the\n * one given, is as good as no token: `TOKEN_UNKNOWN`.\n */\nexport async function ownerOf(\n\tcontext: Context,\n\ttype: ResolvedType | null,\n\ttoken: TokenRecord,\n\twhere: string,\n): Promise<{ user: UserRecord; type: ResolvedType }> {\n\tconst user = await findRecord(context, token.userId, type?.name ?? null);\n\tconst owner = type ?? context.config.types.get(user?.type ?? '');\n\tif (user === null || owner === undefined)\n\t\tthrow unknownOneTime(where, 'token');\n\treturn { user, type: owner };\n}\n",
|
|
53
|
+
"/**\n * The token a change of e-mail sends and redeems: issued for the NEW\n * address, bound to the address it replaces, and refused when the user's\n * e-mail is no longer that one.\n *\n * `address` holds the new address; `codeHash` holds the former one, keyed by\n * the token's secret (`TokenRecord.codeHash`), so the port needs no field and\n * a dump of the store reveals neither.\n */\n\nimport { TokenError, UserInvalidError } from '../../errors/janus-error';\nimport { normalizeEmail, type ResolvedType } from '../config';\nimport { type Context, emailOf, validateFields } from '../context';\nimport { issueOneTime, spendOneTime, unknownOneTime } from '../one-time';\nimport type { TokenRecord, UserRecord } from '../port/types';\nimport { hashSecret, mintSecret } from '../secrets';\nimport type { IssuedToken } from '../types';\nimport { ownerOf } from './owner-of';\n\n/** What binds a token to the address it replaces. */\nexport const formerHash = (secret: string, former: string | null): string =>\n\thashSecret(\n\t\t`janus/changeEmail/former\\0${secret}\\0${normalizeEmail(former ?? '')}`,\n\t);\n\n/**\n * Validates `email` as the user's new address — by the type's own schema, the\n * other fields as they are — and gives it back as the schema left it. An\n * address equal to the current one once normalised is `USER_INVALID`: moving\n * to where the user already is means nothing (`verifyEmail` proves it).\n */\nexport async function newAddressOf(\n\ttype: ResolvedType,\n\tuser: UserRecord,\n\temail: string,\n\twhere: string,\n): Promise<string> {\n\tconst fields = await validateFields(\n\t\ttype,\n\t\t{ ...user.fields, [type.email]: email },\n\t\twhere,\n\t);\n\tconst address = emailOf(type, fields);\n\tif (address === null) {\n\t\tthrow new TypeError(\n\t\t\t`janus: email \"${type.email}\" did not name a string in validated ${type.name} fields — the schema must keep the e-mail field a required string`,\n\t\t);\n\t}\n\tif (\n\t\tnormalizeEmail(address) === normalizeEmail(emailOf(type, user.fields) ?? '')\n\t) {\n\t\tthrow new UserInvalidError(\n\t\t\t`${where}: the new e-mail is the user's current one — a change moves to another address; verifyEmail proves the current one`,\n\t\t\t{\n\t\t\t\tissues: [\n\t\t\t\t\t{ path: [type.email], message: 'is the current e-mail of the user' },\n\t\t\t\t],\n\t\t\t\tuserType: type.name,\n\t\t\t},\n\t\t);\n\t}\n\treturn address;\n}\n\n/**\n * Issues the token for the validated new `address`, bound to the address the\n * user has now, and spends the user's earlier ones.\n */\nexport async function issueChangeEmailToken(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tuser: UserRecord,\n\taddress: string,\n): Promise<IssuedToken> {\n\tconst secret = mintSecret();\n\tconst { expiresAt } = await issueOneTime(context, {\n\t\tkind: 'changeEmail',\n\t\tuserId: user.id,\n\t\taddress,\n\t\tttlMs: context.config.tokenTtlMs.changeEmail,\n\t\tsecret,\n\t\tboundHash: formerHash(secret, emailOf(type, user.fields)),\n\t});\n\t// One live link per user: issued first, spent after, as for a reset, so\n\t// requests that race leave at most one live — never one each.\n\tawait context.store.tokens.spendUserTokens(\n\t\tuser.id,\n\t\t'changeEmail',\n\t\tcontext.clock.now(),\n\t\thashSecret(secret),\n\t);\n\treturn { token: secret, email: address, expiresAt };\n}\n\n/**\n * Refuses a token asked from an address the user has left: the link would\n * move somebody who is no longer where the request came from.\n */\nexport function refuseMoved(\n\ttype: ResolvedType,\n\tuser: UserRecord,\n\ttoken: TokenRecord,\n\tsecret: string,\n\twhere: string,\n): void {\n\tif (token.codeHash !== formerHash(secret, emailOf(type, user.fields))) {\n\t\tthrow new TokenError(\n\t\t\t'TOKEN_STALE',\n\t\t\t`${where}: the token was asked from an e-mail the user no longer has`,\n\t\t\t{ operation: where, userId: user.id, userType: type.name },\n\t\t);\n\t}\n}\n\n/**\n * Spends a change's token and says why it cannot be used, when it cannot. A\n * user gone since, or of another type, is as good as no token; a user who\n * moved since the link was asked is stale.\n *\n * With `type` null the user's own type answers — whichever it is, provided it\n * has an e-mail: a page that does not know the type confirms the link, and\n * `type` in the answer is the one the user has.\n */\nexport async function redeemChangeEmailToken(\n\tcontext: Context,\n\ttype: ResolvedType | null,\n\tsecret: string,\n\twhere: string,\n): Promise<{ token: TokenRecord; user: UserRecord; type: ResolvedType }> {\n\tconst token = await spendOneTime(\n\t\tcontext,\n\t\tsecret,\n\t\t'changeEmail',\n\t\twhere,\n\t\t'token',\n\t);\n\tconst { user, type: owner } = await ownerOf(context, type, token, where);\n\t// A type with no e-mail field has no changeEmail: its users are as good as\n\t// unknown here, as through their own type, which has no such flow.\n\tif (emailOf(owner, user.fields) === null)\n\t\tthrow unknownOneTime(where, 'token');\n\n\trefuseMoved(owner, user, token, secret, where);\n\treturn { token, user, type: owner };\n}\n",
|
|
54
|
+
"/**\n * Changing a user's e-mail: send a token to the NEW address, then redeem it\n * to move the user there — verified, since the link reached its inbox.\n */\n\nimport { UserInactiveError } from '../../errors/janus-error';\nimport type { At } from '../at';\nimport type { ResolvedType } from '../config';\nimport {\n\ttype AnyUser,\n\ttype Context,\n\temailOf,\n\tgetRecord,\n\tidOf,\n\ttoUser,\n\twriteUser,\n} from '../context';\nimport { emit } from '../events';\nimport { countMailByAddress, countMailByUser } from '../mail-requests';\nimport type { UserRecord } from '../port/types';\nimport type { ChangeEmailApi } from '../types';\nimport { emailChanged, fieldsPatch } from '../users/fields-patch';\nimport {\n\tissueChangeEmailToken,\n\tnewAddressOf,\n\tredeemChangeEmailToken,\n\trefuseMoved,\n} from './change-email-token';\n\nconst inactive = (type: ResolvedType, user: UserRecord, where: string) =>\n\tnew UserInactiveError(`${where}: the user is inactive`, {\n\t\tuserId: user.id,\n\t\tuserType: type.name,\n\t});\n\n/** `changeEmail` of one user type: `send` to the new address, then `confirm`. */\nexport function changeEmailFlows(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tat: At,\n): ChangeEmailApi<AnyUser>['changeEmail'] {\n\treturn {\n\t\tasync send(user, email) {\n\t\t\tconst where = at('changeEmail.send');\n\t\t\tconst record = await getRecord(context, idOf(user), type.name, where);\n\t\t\tif (!record.active) throw inactive(type, record, where);\n\t\t\t// Validated first — a USER_INVALID spends nothing — then the user is\n\t\t\t// counted, then the address, all before anything is issued. The user\n\t\t\t// first: an account past its own count spends no address's, so one\n\t\t\t// account can exhaust at most one address per window. An address\n\t\t\t// other people exhausted costs the asking user one of their own.\n\t\t\tconst address = await newAddressOf(type, record, email, where);\n\t\t\tawait countMailByUser(context, type, 'changeEmail', record.id, where);\n\t\t\tawait countMailByAddress(\n\t\t\t\tcontext,\n\t\t\t\ttype,\n\t\t\t\t'changeEmail',\n\t\t\t\taddress,\n\t\t\t\twhere,\n\t\t\t\trecord.id,\n\t\t\t);\n\t\t\treturn issueChangeEmailToken(context, type, record, address);\n\t\t},\n\n\t\tasync confirm(secret) {\n\t\t\treturn confirmChange(context, type, secret, at('changeEmail.confirm'));\n\t\t},\n\t};\n}\n\n/**\n * Redeems a change's token: the write, then the events it earned. `asked` is\n * the type whose `confirm` was called, or null for the root's, where the\n * user's own type answers.\n */\nexport async function confirmChange(\n\tcontext: Context,\n\tasked: ResolvedType | null,\n\tsecret: string,\n\twhere: string,\n): Promise<AnyUser> {\n\tconst { token, user, type } = await redeemChangeEmailToken(\n\t\tcontext,\n\t\tasked,\n\t\tsecret,\n\t\twhere,\n\t);\n\tif (!user.active) throw inactive(type, user, where);\n\n\t// The record the write replaced, read in its callback, as `update` does.\n\tconst seen: { replaced: UserRecord | null } = { replaced: null };\n\tconst written = await writeUser(\n\t\tcontext,\n\t\tuser.id,\n\t\ttype,\n\t\tundefined,\n\t\twhere,\n\t\tasync (record, now) => {\n\t\t\t// Checked again on the record written, as for verifyEmail.\n\t\t\tif (!record.active) throw inactive(type, record, where);\n\t\t\trefuseMoved(type, record, token, secret, where);\n\t\t\tseen.replaced = record;\n\t\t\tconst patch = await fieldsPatch(\n\t\t\t\ttype,\n\t\t\t\trecord,\n\t\t\t\t{ [type.email]: token.address },\n\t\t\t\twhere,\n\t\t\t);\n\t\t\t// Verified by the link that reached the new address. `send` refuses\n\t\t\t// the current address and an `update` spends the link, so the address\n\t\t\t// always moves here; the test is a guard, not a path.\n\t\t\tconst proved =\n\t\t\t\trecord.emailVerifiedAt === null ||\n\t\t\t\temailChanged(type, record.fields, patch.fields);\n\t\t\treturn proved ? { ...patch, emailVerifiedAt: now } : patch;\n\t\t},\n\t);\n\tconst { replaced } = seen;\n\tconst moved =\n\t\treplaced !== null && emailChanged(type, replaced.fields, written.fields);\n\tif (replaced !== null && moved) {\n\t\tawait emit(context, 'user.emailChanged', written, written.updatedAt, {\n\t\t\tformerEmail: emailOf(type, replaced.fields),\n\t\t});\n\t}\n\tif (moved || replaced?.emailVerifiedAt === null) {\n\t\tawait emit(context, 'user.emailVerified', written, written.updatedAt);\n\t}\n\treturn toUser(written);\n}\n",
|
|
55
|
+
"/**\n * The confirmation of a change of e-mail at the root of an instance with\n * several user types: for the page that follows the link and does not know\n * the user's type.\n */\n\nimport type { AnyUser, Context } from '../context';\nimport { confirmChange } from './change-email';\n\n/**\n * `{ changeEmail: { confirm } }`. Built whatever the types, as each type's\n * flows are; the types show it only when one has an e-mail, and a user of a\n * type without one is `TOKEN_UNKNOWN`. `send` stays on each type: it needs the\n * user's type to validate the address.\n */\nexport function anyTypeChangeEmail(context: Context): {\n\treadonly changeEmail: { confirm(token: string): Promise<AnyUser> };\n} {\n\treturn {\n\t\tchangeEmail: {\n\t\t\tconfirm: (secret) =>\n\t\t\t\tconfirmChange(context, null, secret, 'changeEmail.confirm'),\n\t\t},\n\t};\n}\n",
|
|
56
|
+
"/** `user.apiKeyCreated` and `user.apiKeyRevoked`: sent from every path that makes or revokes keys. */\n\nimport type { Id } from '../../ids/id';\nimport type { Context } from '../context';\nimport { emit } from '../events';\n\n/** Who an API key event names: the user's id and type, nothing of the key. */\nexport interface KeyOwner {\n\treadonly id: Id;\n\treadonly type: string;\n}\n\n/** `user.apiKeyCreated`, once the key is stored. */\nexport async function keyCreated(\n\tcontext: Context,\n\towner: KeyOwner,\n\tat: Date,\n): Promise<void> {\n\tawait emit(context, 'user.apiKeyCreated', owner, at);\n}\n\n/**\n * The user a revoke is about, read **before** the write — a failure then\n * leaves nothing written — and only when a listener waits for it. `null`\n * when none does, or when the user is gone (their keys went with them).\n */\nexport async function ownerForEvent(\n\tcontext: Context,\n\tuserId: Id,\n): Promise<KeyOwner | null> {\n\tif (context.events === null) return null;\n\tconst user = await context.store.users.findUser(userId);\n\treturn user === null ? null : { id: user.id, type: user.type };\n}\n\n/**\n * `user.apiKeyRevoked`, once, carrying how many keys a revoke ended. Nothing\n * when it ended none — a no-op is no event.\n */\nexport async function keysRevoked(\n\tcontext: Context,\n\towner: KeyOwner | null,\n\tat: Date,\n\tcount: number,\n): Promise<void> {\n\tif (owner === null || count <= 0) return;\n\tawait emit(context, 'user.apiKeyRevoked', owner, at, { count });\n}\n",
|
|
57
|
+
"import type { Id } from '../ids/id';\nimport type { ResolvedType } from './config';\nimport {\n\ttype AnyUser,\n\ttype Context,\n\tfindRecord,\n\tpasswordMatches,\n} from './context';\nimport { emit } from './events';\nimport { burnOneTime } from './one-time';\nimport type { UserRecord } from './port/types';\nimport type { SignInResult } from './types';\n\n/**\n * What writing a password ends besides. A reset, a change and a set each call\n * it **after** the write, and a failure here throws — it is never ignored:\n *\n * - The user's reset links still unspent. A link answers a request to\n * replace the password; once it is replaced, an older link would replace\n * it again, without knowing the new one.\n * - Every second-factor challenge still open, so a sign-in started with the\n * old password cannot be finished — the other half of\n * {@link heldByPassword}, which reads **after** it issued.\n *\n * Both spends are attempted even when one fails, so a store failing one kind\n * still spends the other; the first failure is then thrown.\n *\n * After the write, not before: a link issued while the password is written\n * is spent too, where one issued between an earlier spend and the write\n * would survive. So an outage here leaves the password written and the\n * older links live, and the caller is told, with `STORE_FAILED`; the next\n * `resetPassword.request` spends them. Sign-in codes and step-ups are left\n * alone: the password proves neither, and a step-up belongs to a session,\n * which a reset revokes.\n */\nexport async function endWhatThePasswordOpened(\n\tcontext: Context,\n\tuserId: Id,\n): Promise<void> {\n\tconst now = context.clock.now();\n\tconst spent = await Promise.allSettled(\n\t\t(['resetPassword', 'secondFactor'] as const).map((kind) =>\n\t\t\tcontext.store.tokens.spendUserTokens(userId, kind, now),\n\t\t),\n\t);\n\tconst failed = spent.find(\n\t\t(result): result is PromiseRejectedResult => result.status === 'rejected',\n\t);\n\tif (failed !== undefined) throw failed.reason;\n}\n\n/**\n * What a change and a set do once the password is written: end what the\n * old one opened, then send `user.passwordChanged` — from a `finally`, so an\n * outage ending them still reports the write, which a retry would not make\n * again. `first` is `true` when the user had no password before.\n * A reset sends `user.passwordReset` instead, from its own flow.\n */\nexport async function passwordChanged(\n\tcontext: Context,\n\twritten: UserRecord,\n\tfirst = false,\n): Promise<void> {\n\ttry {\n\t\tawait endWhatThePasswordOpened(context, written.id);\n\t} finally {\n\t\tawait emit(context, 'user.passwordChanged', written, written.updatedAt, {\n\t\t\tfirst,\n\t\t});\n\t}\n}\n\n/**\n * Whether the password a sign-in verified is still the user's, once the\n * sign-in answered. A password written meanwhile ends the sign-in: its\n * session is revoked, or its challenge spent, and `false` is answered.\n *\n * A password writer writes, then spends the challenges waiting; a sign-in\n * issues, then reads here. Whichever order they interleave in, one of the two\n * sees the other. A hash that changed with the same password — a concurrent\n * sign-in rehashing it — is not a change: the password is compared again.\n */\nexport async function heldByPassword(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tverified: UserRecord,\n\tpassword: string,\n\tresult: SignInResult<AnyUser>,\n\twhere: string,\n): Promise<boolean> {\n\tconst now = await findRecord(context, verified.id, type.name);\n\tconst kept =\n\t\tnow !== null &&\n\t\tnow.password !== null &&\n\t\t(now.password.hash === verified.password?.hash ||\n\t\t\t(await passwordMatches(context, now, password, where)));\n\tif (kept) return true;\n\n\tif (result.status === 'signedIn') {\n\t\tawait context.store.sessions.revokeSession(\n\t\t\tresult.session.id,\n\t\t\tcontext.clock.now(),\n\t\t);\n\t} else {\n\t\tawait burnOneTime(context, result.challenge, 'secondFactor');\n\t}\n\treturn false;\n}\n\n/**\n * Runs each ending in order, whatever the others do, and throws the first\n * failure once all were tried: an outage in one must not leave the others\n * undone, since the link or the proof that led here is spent and a retry is\n * refused.\n */\nexport async function endEach(\n\tsteps: ReadonlyArray<() => Promise<unknown>>,\n): Promise<void> {\n\tlet failure: { reason: unknown } | null = null;\n\tfor (const step of steps) {\n\t\tconst [settled] = await Promise.allSettled([step()]);\n\t\tif (settled.status === 'rejected') failure ??= { reason: settled.reason };\n\t}\n\tif (failure !== null) throw failure.reason;\n}\n",
|
|
58
|
+
"/**\n * The token an e-mail flow sends and redeems: issued for the user's current\n * e-mail, and refused on redemption when that e-mail is not the one it was\n * sent to any more.\n */\n\nimport { NotFoundError } from '../../errors/janus-error';\nimport type { Id } from '../../ids/id';\nimport type { ResolvedType } from '../config';\nimport { type Context, emailOf } from '../context';\nimport {\n\tissueOneTime,\n\trefuseStale,\n\tspendOneTime,\n\tunknownOneTime,\n} from '../one-time';\nimport type { TokenKind, TokenRecord, UserRecord } from '../port/types';\nimport type { IssuedToken } from '../types';\nimport { ownerOf } from './owner-of';\n\n/**\n * Spends a token and says why it cannot be used, when it cannot. A user\n * gone since, or of another type, is as good as no token; a token sent to\n * an e-mail the user no longer has is stale.\n *\n * With `type` null the user's own type answers — whichever it is, provided it\n * has an e-mail: a page that does not know the type confirms the link, and\n * `type` in the answer is the one the user has.\n *\n * With `userId`, a token issued to another user is `TOKEN_UNKNOWN` and is not\n * spent (the store checks it in the spend itself).\n */\nexport async function redeemEmailToken(\n\tcontext: Context,\n\ttype: ResolvedType | null,\n\tkind: TokenKind,\n\tsecret: string,\n\twhere: string,\n\tuserId?: Id,\n): Promise<{ token: TokenRecord; user: UserRecord; type: ResolvedType }> {\n\tconst token = await spendOneTime(\n\t\tcontext,\n\t\tsecret,\n\t\tkind,\n\t\twhere,\n\t\t'token',\n\t\tuserId,\n\t);\n\tconst { user, type: owner } = await ownerOf(context, type, token, where);\n\t// A type with no e-mail field has no such flow: its users are as good as\n\t// unknown here, as through their own type.\n\tif (type === null && emailOf(owner, user.fields) === null)\n\t\tthrow unknownOneTime(where, 'token');\n\n\trefuseStale(owner, user, token, where, 'token');\n\treturn { token, user, type: owner };\n}\n\n/** Issues a one-time token for the user's current e-mail. */\nexport async function issueEmailToken(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tkind: 'verifyEmail' | 'resetPassword',\n\tuser: UserRecord,\n\twhere: string,\n): Promise<IssuedToken> {\n\tconst email = emailOf(type, user.fields);\n\tif (email === null) {\n\t\tthrow new NotFoundError(`${where}: the user has no e-mail`, {\n\t\t\tuserId: user.id,\n\t\t\tuserType: type.name,\n\t\t\toperation: where,\n\t\t});\n\t}\n\n\tconst { secret, expiresAt } = await issueOneTime(context, {\n\t\tkind,\n\t\tuserId: user.id,\n\t\taddress: email,\n\t\tttlMs: context.config.tokenTtlMs[kind],\n\t});\n\treturn { token: secret, email, expiresAt };\n}\n",
|
|
59
|
+
"/**\n * Redeeming a reset token: sets the password, proves the e-mail, signs the user\n * out everywhere — for one type's `confirm`, and for the root's, where the\n * user's type is only known once the token is spent.\n */\n\nimport type { Id } from '../../ids/id';\nimport { keysRevoked } from '../api-keys/events';\nimport type { ResolvedType } from '../config';\nimport {\n\ttype AnyUser,\n\ttype Context,\n\tcheckPassword,\n\tpasswordRule,\n\trequireHasher,\n\ttoUser,\n\twriteUser,\n} from '../context';\nimport { emit } from '../events';\nimport { refuseStale, unknownOneTime } from '../one-time';\nimport { endEach, endWhatThePasswordOpened } from '../password-written';\nimport { redeemEmailToken } from './email-token';\n\n/**\n * The type whose password rule is the strictest among those with a password,\n * or null when none has one. A password type with no e-mail counts too: the\n * root cannot tell, and such a user can never be reset, but its rule still\n * applies at the root. The first declared wins a tie.\n */\nfunction strictestType(context: Context): ResolvedType | null {\n\tlet strictest: ResolvedType | null = null;\n\tlet longest = 0;\n\tfor (const type of context.config.types.values()) {\n\t\tif (type.password === null) continue;\n\t\tif (strictest === null || type.password.minLength > longest) {\n\t\t\tstrictest = type;\n\t\t\tlongest = type.password.minLength;\n\t\t}\n\t}\n\treturn strictest;\n}\n\n/**\n * Redeems a reset token: sets the password, proves the e-mail, signs out\n * everywhere. `asked` is the type whose `confirm` was called, or null for the\n * root's: the password must then meet the strictest `minLength` of the types\n * with a password, before the token is spent, and the user's own type answers\n * after.\n */\nexport async function confirmReset(\n\tcontext: Context,\n\tasked: ResolvedType | null,\n\tsecret: string,\n\tpassword: string,\n\twhere: string,\n): Promise<AnyUser> {\n\t// Checked before the token is spent: a password refused for its\n\t// length must not cost the visitor their link. At the root the type is\n\t// only known after the spend, so the strictest rule stands in for it.\n\tconst gate = asked ?? strictestType(context);\n\tif (asked !== null) passwordRule(asked, where);\n\tif (gate !== null) checkPassword(gate, password, where);\n\t// No type with a password at the root: nothing can be reset, the spend\n\t// below answers it, and no hasher is needed (or wired) for that.\n\tconst hash =\n\t\tgate === null ? '' : await requireHasher(context, where).hash(password);\n\n\tconst { token, user, type } = await redeemEmailToken(\n\t\tcontext,\n\t\tasked,\n\t\t'resetPassword',\n\t\tsecret,\n\t\twhere,\n\t);\n\t// A type with no password has no reset: its users are as good as unknown.\n\tif (asked === null) {\n\t\tif (type.password === null) throw unknownOneTime(where, 'token');\n\t\tcheckPassword(type, password, where);\n\t}\n\tlet newlyVerified = false;\n\tconst written = await writeUser(\n\t\tcontext,\n\t\tuser.id,\n\t\ttype,\n\t\tundefined,\n\t\twhere,\n\t\t(record, now) => {\n\t\t\t// Checked again on the record written, as for verifyEmail.\n\t\t\trefuseStale(type, record, token, where, 'token');\n\t\t\tnewlyVerified = record.emailVerifiedAt === null;\n\t\t\treturn {\n\t\t\t\tpassword: { hash, updatedAt: now },\n\t\t\t\t// The link reached the inbox: that proves the e-mail.\n\t\t\t\t...(record.emailVerifiedAt === null ? { emailVerifiedAt: now } : {}),\n\t\t\t};\n\t\t},\n\t);\n\ttry {\n\t\tawait endWhatTheResetEnds(context, written, newlyVerified);\n\t} finally {\n\t\t// Reported even when an outage interrupts the steps above:\n\t\t// the link is spent, so a retry is refused and could not.\n\t\tawait emit(context, 'user.passwordReset', written, written.updatedAt);\n\t\tif (newlyVerified) {\n\t\t\tawait emit(context, 'user.emailVerified', written, written.updatedAt);\n\t\t}\n\t}\n\treturn toUser(written);\n}\n\n/**\n * What a reset ends, each whatever the others do (the link is spent, so a\n * retry is refused and could not make up for one an outage skipped). Whoever\n * had the old password is signed out first, so no session of it can make a\n * key after the keys are revoked; the keys follow — always when the link\n * proved the e-mail (whoever signed up with the address may have made keys\n * with a password that was not the inbox holder's), else when\n * `revokeOnPasswordReset` says so. A sign-in left waiting on its second factor\n * cannot be finished, and no other link replaces the password again.\n */\nasync function endWhatTheResetEnds(\n\tcontext: Context,\n\twritten: { readonly id: Id; readonly type: string },\n\tnewlyVerified: boolean,\n): Promise<void> {\n\tawait endEach([\n\t\t() =>\n\t\t\tcontext.store.sessions.revokeUserSessions(\n\t\t\t\twritten.id,\n\t\t\t\tcontext.clock.now(),\n\t\t\t),\n\t\tasync () => {\n\t\t\tif (newlyVerified || context.config.apiKeys?.revokeOnPasswordReset) {\n\t\t\t\tconst at = context.clock.now();\n\t\t\t\tconst count = await context.apiKeys?.revokeUserApiKeys(written.id, at);\n\t\t\t\tawait keysRevoked(context, written, at, count ?? 0);\n\t\t\t}\n\t\t},\n\t\t() => endWhatThePasswordOpened(context, written.id),\n\t]);\n}\n",
|
|
60
|
+
"/**\n * The confirmation of a password reset at the root of an instance with several\n * user types: for the page that follows the link and does not know the user's\n * type.\n */\n\nimport type { AnyUser, Context } from '../context';\nimport { confirmReset } from './confirm-reset';\n\n/**\n * `{ resetPassword: { confirm } }`. Built whatever the types, as each type's\n * flows are; the types show it only when one has a password and an e-mail, and\n * a user of a type without a password is `TOKEN_UNKNOWN`. `request` and\n * `prepare` stay on each type: they need the type to find the holder of the\n * address.\n */\nexport function anyTypeResetPassword(context: Context): {\n\treadonly resetPassword: {\n\t\tconfirm(token: string, password: string): Promise<AnyUser>;\n\t};\n} {\n\treturn {\n\t\tresetPassword: {\n\t\t\tconfirm: (secret, password) =>\n\t\t\t\tconfirmReset(context, null, secret, password, 'resetPassword.confirm'),\n\t\t},\n\t};\n}\n",
|
|
61
|
+
"import { randomBytes, timingSafeEqual } from 'node:crypto';\nimport { derivedKey, keyedHash } from '../derived-keys';\nimport type { Sealer } from '../sealing';\n\n/**\n * A device token: `d1.<key id>.<device id>.<mac>`, the last two in\n * base64url. The device id is 16 random bytes; the mac is an HMAC-SHA256 of\n * the user's id and the device id, under a key derived for this purpose from\n * `devices.keys`. **Nothing is stored**: the token is its own proof that this\n * user signed in on this device before, and a token copied onto another user\n * proves nothing.\n *\n * Every character is a cookie-value character, so it goes in a cookie as is.\n */\n\n/** What the key is derived for. Renamed, every device would be new again. */\nconst PURPOSE = 'janus/devices/v1';\n\nconst TOKEN =\n\t/^d1\\.([A-Za-z0-9_-]{1,64})\\.([A-Za-z0-9_-]{22})\\.([A-Za-z0-9_-]{43})$/;\n\nfunction macOf(key: Buffer, userId: string, deviceId: string): Buffer {\n\treturn keyedHash(key, [userId, deviceId]);\n}\n\nfunction signed(sealer: Sealer, userId: string, deviceId: string): string {\n\t// The first key is always held: resolveSealer names it from the keys.\n\tconst key = derivedKey(sealer, PURPOSE) as Buffer;\n\tconst mac = macOf(key, userId, deviceId).toString('base64url');\n\treturn `d1.${sealer.sealWith}.${deviceId}.${mac}`;\n}\n\n/** A token for a device never seen: a fresh device id, signed with the first key. */\nexport function mintDeviceToken(sealer: Sealer, userId: string): string {\n\treturn signed(sealer, userId, randomBytes(16).toString('base64url'));\n}\n\n/**\n * The token to hand back when `presented` proves this user signed in on this\n * device before — itself, or the same device signed again with the first key\n * when an older key signed it — or `null` when it proves nothing: malformed,\n * another user's, forged, or signed with a key no longer held.\n *\n * `presented` comes from a request, so nothing here throws.\n */\nexport function knownDeviceToken(\n\tsealer: Sealer,\n\tuserId: string,\n\tpresented: string,\n): string | null {\n\tconst [, keyId, deviceId, mac] = TOKEN.exec(presented) ?? [];\n\tif (keyId === undefined || deviceId === undefined || mac === undefined) {\n\t\treturn null;\n\t}\n\tconst key = derivedKey(sealer, PURPOSE, keyId);\n\tif (key === undefined) return null;\n\n\tconst expected = macOf(key, userId, deviceId);\n\tconst given = Buffer.from(mac, 'base64url');\n\tif (given.length !== expected.length || !timingSafeEqual(given, expected)) {\n\t\treturn null;\n\t}\n\treturn keyId === sealer.sealWith\n\t\t? presented\n\t\t: signed(sealer, userId, deviceId);\n}\n",
|
|
62
|
+
"import type { Context } from '../context';\nimport type { SignInOptions } from '../types';\nimport { knownDeviceToken, mintDeviceToken } from './token';\n\n/**\n * What a sign-in was told of the device. `token`: `undefined` when nothing —\n * devices are not tracked for that call — `null` for a device holding no\n * token yet, or the token it presented. `label`: the `deviceLabel` the\n * session records for a list of sessions, when given.\n */\nexport interface DeviceHint {\n\treadonly token: string | null | undefined;\n\treadonly label?: string | undefined;\n}\n\n/** The longest `deviceLabel` kept; a longer one is cut. */\nexport const DEVICE_LABEL_MAX = 256;\n\n/**\n * The `deviceLabel` a sign-in's options name, cut to {@link DEVICE_LABEL_MAX},\n * or `undefined` for none or an empty one. A label of another type is a\n * wiring mistake — a bare `TypeError`.\n */\nexport function deviceLabel(\n\toptions: SignInOptions | undefined,\n\twhere: string,\n): string | undefined {\n\tconst label = options?.deviceLabel;\n\tif (label === undefined) return undefined;\n\tif (typeof label !== 'string') {\n\t\tthrow new TypeError(`${where}: options.deviceLabel must be a string`);\n\t}\n\treturn label === '' ? undefined : label.slice(0, DEVICE_LABEL_MAX);\n}\n\n/** What a session-opening answer says of the device. */\nexport interface DeviceOutcome {\n\treadonly newDevice: boolean;\n\treadonly deviceToken: string | null;\n}\n\n/** No device given: nothing tracked, nothing minted. */\nexport const UNTRACKED: DeviceOutcome = Object.freeze({\n\tnewDevice: false,\n\tdeviceToken: null,\n});\n\n/**\n * The device a sign-in's options name. A JavaScript caller's options that\n * are not an object (the token itself), a `device` of another type, and a\n * device given to a `janus()` wired without `devices`, are wiring\n * mistakes — bare `TypeError`s. The value itself, whatever it holds, is the\n * client's, and never refused.\n */\nexport function deviceHint(\n\tcontext: Context,\n\toptions: SignInOptions | undefined,\n\twhere: string,\n): DeviceHint {\n\tif (\n\t\toptions !== undefined &&\n\t\t(typeof options !== 'object' || options === null)\n\t) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: options must be { device }, or left out — the token goes under device`,\n\t\t);\n\t}\n\tconst label = deviceLabel(options, where);\n\tconst device = options?.device;\n\tif (device === undefined) return { token: undefined, label };\n\tif (device !== null && typeof device !== 'string') {\n\t\tthrow new TypeError(\n\t\t\t`${where}: options.device must be the device token the client holds, or null when it holds none`,\n\t\t);\n\t}\n\tif (context.config.devices === null) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: a device was given, but janus() has no devices — pass devices: { keys }`,\n\t\t);\n\t}\n\treturn { token: device, label };\n}\n\n/**\n * Whether a session opening for `userId` comes from a new device, and the\n * token the client keeps from now on. A sign-up mints a token and is never\n * new: the account has no device to be new against.\n */\nexport function deviceOutcome(\n\tcontext: Context,\n\tuserId: string,\n\thint: DeviceHint,\n\tsignUp: boolean,\n): DeviceOutcome {\n\tconst sealer = context.config.devices?.sealer;\n\tconst { token } = hint;\n\tif (token === undefined || sealer === undefined) return UNTRACKED;\n\n\tconst known =\n\t\ttoken === null || signUp ? null : knownDeviceToken(sealer, userId, token);\n\tif (known !== null) return { newDevice: false, deviceToken: known };\n\treturn {\n\t\tnewDevice: !signUp,\n\t\tdeviceToken: mintDeviceToken(sealer, userId),\n\t};\n}\n",
|
|
63
|
+
"import type { AnyUser, Context } from '../context';\nimport { emit } from '../events';\nimport type { SignInResult } from '../types';\n\n/**\n * Sends `user.newDeviceSignedIn` for a session a new device just opened —\n * once the sign-in is complete, so a sign-in refused after its session\n * opened (a password written meanwhile) reports nothing. A challenge, and a\n * session from a known device or with no device given, report nothing\n * either.\n */\nexport async function reportNewDevice(\n\tcontext: Context,\n\tresult: SignInResult<AnyUser>,\n): Promise<void> {\n\tif (result.status !== 'signedIn' || !result.newDevice) return;\n\tawait emit(\n\t\tcontext,\n\t\t'user.newDeviceSignedIn',\n\t\tresult.user,\n\t\tresult.session.createdAt,\n\t\t{ sessionId: result.session.id },\n\t);\n}\n",
|
|
64
|
+
"import { EmailUnverifiedError } from '../../errors/janus-error';\nimport type { ResolvedConfig, ResolvedType } from '../config';\nimport { type Context, emailOf } from '../context';\nimport type { SecondFactorRecord, UserRecord } from '../port/types';\nimport { seal, unseal } from '../sealing';\nimport { fromBase32, matchStep } from '../totp';\n\n/**\n * What the second factor's flows share: its configuration, its states, and\n * the one check of a code against a sealed secret.\n *\n * A factor is **enrolled** once `enroll` wrote it, **active** once a first\n * code confirmed it, and gone after `disable`. Only an active one is asked\n * for at sign-in.\n */\n\nexport type Settings = NonNullable<ResolvedConfig['secondFactor']>;\n\ntype ActiveFactor = SecondFactorRecord & { readonly confirmedAt: Date };\n\nexport const isActive = (\n\tfactor: SecondFactorRecord | null,\n): factor is ActiveFactor => factor !== null && factor.confirmedAt !== null;\n\n/**\n * Refuses a factor on an account whose e-mail is not proved: the first proof\n * (`proveFirstEmail`) drops whatever factor stands, so one enrolled before it\n * would vanish unannounced. A type without an e-mail has nothing to prove.\n */\nexport function assertEmailProved(\n\ttype: ResolvedType,\n\trecord: UserRecord,\n\twhere: string,\n\twhat: string,\n): void {\n\tif (\n\t\temailOf(type, record.fields) !== null &&\n\t\trecord.emailVerifiedAt === null\n\t) {\n\t\tthrow new EmailUnverifiedError(\n\t\t\t`${where}: the e-mail is not verified — ${what} after it is proved`,\n\t\t\t{ userId: record.id, userType: type.name },\n\t\t);\n\t}\n}\n\n/** The configuration, or a wiring refusal: no keys, no second factor. */\nexport function requireSettings(\n\tcontext: Context,\n\twhere: string,\n\twhy: string,\n): Settings {\n\tconst configured = context.config.secondFactor;\n\tif (configured === null) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: ${why}, and janus() was given no secondFactor — pass secondFactor: { issuer, keys }`,\n\t\t);\n\t}\n\treturn configured;\n}\n\n/**\n * Checks a code against the user's secret. Answers the factor as it is to be\n * written — the step accepted, and the secret sealed again under the first\n * key when an older one sealed it — or `null` for a code that does not match,\n * or was already used.\n */\nexport function acceptCode(\n\tconfigured: Settings,\n\trecord: UserRecord,\n\tfactor: SecondFactorRecord,\n\tcode: string,\n\tnow: Date,\n\twhere: string,\n): SecondFactorRecord | null {\n\tconst { plain, keyId } = unseal(\n\t\tconfigured.sealer,\n\t\tfactor.secret,\n\t\trecord.id,\n\t\twhere,\n\t);\n\tconst step = matchStep(fromBase32(plain), code, now, factor.lastStep);\n\tif (step === null) return null;\n\treturn {\n\t\t...factor,\n\t\tlastStep: step,\n\t\tsecret:\n\t\t\tkeyId === configured.sealer.sealWith\n\t\t\t\t? factor.secret\n\t\t\t\t: seal(configured.sealer, plain, record.id),\n\t};\n}\n",
|
|
65
|
+
"/** What disabling the TOTP does to the passkeys: a passkey only stands beside an active TOTP. */\n\nimport type { ResolvedType } from '../config';\nimport { type Context, getRecord, idOf } from '../context';\nimport { emit } from '../events';\nimport { isActive } from '../second-factor/factor';\nimport type { UserRef } from '../types';\n\n/**\n * Deletes every passkey of a user whose TOTP was just removed, and emits one\n * `user.passkeyRemoved` per passkey it deleted — the list is read first, so\n * each event names the credential and the name it had. A no-op without\n * `passkeys` in the configuration, or without any passkey.\n */\nexport async function removeAllPasskeys(\n\tcontext: Context,\n\tuser: { readonly id: string; readonly type: string },\n\tnow: Date,\n): Promise<void> {\n\tconst store = context.store.passkeys;\n\tif (context.config.passkeys === null || store === undefined) return;\n\tconst held = await store.listUserPasskeys(user.id);\n\t// One delete per listed passkey, so an event is sent for each one this\n\t// call really removed — and not for one a concurrent call got to first.\n\tfor (const passkey of held) {\n\t\tif (await store.deletePasskey(user.id, passkey.credentialId)) {\n\t\t\tawait emit(context, 'user.passkeyRemoved', user, now, {\n\t\t\t\tpasskey: { credentialId: passkey.credentialId, name: passkey.name },\n\t\t\t});\n\t\t}\n\t}\n\t// The sweep: whatever a registration inserted since the list was read.\n\t// It sends no event (nothing names those passkeys); a registration that\n\t// lands after the TOTP went deletes its own passkey as it re-checks.\n\tawait store.deleteUserPasskeys(user.id);\n}\n\n/**\n * Before a waiting factor is activated, deletes the passkeys a failed removal\n * (a first proof, a disable) left behind. Before the write, so an outage here\n * loses no recovery codes and sends no event, and only for a factor that is\n * waiting: no legitimate passkey can exist before a TOTP is active (a\n * registration needs an active factor), so whatever is there is not the\n * owner's. Not with `passkeys.firstFactor`, where a passkey needs no TOTP. An\n * active factor, or a user of another type, is refused by the write that\n * follows and loses nothing.\n */\nexport async function sweepWaitingFactorPasskeys(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tuser: UserRef,\n\twhere: string,\n): Promise<void> {\n\tconst settings = context.config.passkeys;\n\tif (settings === null || settings.firstFactor) return;\n\tconst current = await getRecord(context, idOf(user), type.name, where);\n\tconst waiting =\n\t\tcurrent.secondFactor !== null && !isActive(current.secondFactor);\n\tif (waiting) await context.store.passkeys?.deleteUserPasskeys(current.id);\n}\n",
|
|
66
|
+
"/**\n * The first proof of an e-mail by a sign-in code or a sign-in link: the\n * address reached an inbox no one had proved before, so whatever was set on\n * the account before that proof is not the inbox holder's to keep.\n *\n * Anybody can sign up with somebody else's e-mail and a password of their\n * own. Enrolling a factor or a passkey is refused until the e-mail is proved,\n * so a factor only stands here on data stored before that rule, or enrolled\n * through a store write; `update` refuses to move the e-mail of a user who\n * holds a factor or a passkey (`EMAIL_CHANGE_NEEDS_PROOF`), so a factor enrolled\n * while the e-mail was proved is not left beside a new, unproved address —\n * `changeEmail` proves it. Without this, the real\n * holder signing in by e-mail later would verify the address and leave that\n * password, that factor and their sessions working: locked out by a factor\n * they never set, or signed in beside someone who still holds the account.\n * So the write that proves the address also drops the password, the avatar\n * and the second factor with its recovery codes, and every session is\n * revoked before the new one opens: the same ending as `resetPassword.confirm`, which\n * proves the address too, plus the factor it keeps.\n */\n\nimport type { Id } from '../ids/id';\nimport { keysRevoked } from './api-keys/events';\nimport type { ResolvedType } from './config';\nimport { type Context, writeUser } from './context';\nimport { emit } from './events';\nimport { removeAllPasskeys } from './passkeys/remove-all';\nimport { endEach, endWhatThePasswordOpened } from './password-written';\nimport type { UserRecord } from './port/types';\nimport { isActive } from './second-factor/factor';\n\n/**\n * Proves `user`'s e-mail, never proved before, under the version read — an\n * address changed since is not the one proved: a `VERSION_CONFLICT` then.\n * Drops the password, the avatar and the second factor — active or waiting,\n * and its recovery codes with it — in the same write, and revokes every session and\n * spends what the password opened — reset links and second-factor\n * challenges — **both before the write and after it**.\n *\n * Before, so an outage there leaves the e-mail unproved and the owner's next\n * code or link runs this again; after, so a sign-in landing in between is\n * ended too. An outage after the write is the one that leaves a session live.\n *\n * `user.emailVerified` is sent, then `user.passwordChanged` when a password\n * was dropped, `user.secondFactorDisabled` when an active factor was and\n * `user.avatarRemoved` (with `formerAvatarId`) when an avatar was —\n * the rule of `secondFactor.disable` — from a `finally`, so an outage ending\n * the sessions still reports the write, which a retry would not make again.\n */\nexport async function proveFirstEmail(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tuser: UserRecord,\n\twhere: string,\n): Promise<UserRecord> {\n\tawait endWhatTheSquatterOpened(context, user);\n\tlet dropped = false;\n\tlet disabled = false;\n\tlet formerAvatarId: string | null = null;\n\tconst proved = await writeUser(\n\t\tcontext,\n\t\tuser.id,\n\t\ttype,\n\t\t{ ifVersion: user.version },\n\t\twhere,\n\t\t(record, now) => {\n\t\t\tdropped = record.password !== null;\n\t\t\tdisabled = isActive(record.secondFactor);\n\t\t\tformerAvatarId = record.avatar?.id ?? null;\n\t\t\treturn {\n\t\t\t\temailVerifiedAt: now,\n\t\t\t\t...(dropped ? { password: null } : {}),\n\t\t\t\t...(record.secondFactor === null ? {} : { secondFactor: null }),\n\t\t\t\t...(formerAvatarId === null ? {} : { avatar: null }),\n\t\t\t};\n\t\t},\n\t);\n\ttry {\n\t\t// Whoever signed up with this address and not its inbox is signed\n\t\t// out, and a sign-in they left waiting on its second factor cannot\n\t\t// be finished — before the new session opens.\n\t\tawait endWhatTheSquatterOpened(context, proved);\n\t} finally {\n\t\tawait emit(context, 'user.emailVerified', proved, proved.updatedAt);\n\t\tif (dropped) {\n\t\t\tawait emit(context, 'user.passwordChanged', proved, proved.updatedAt, {\n\t\t\t\tfirst: false,\n\t\t\t});\n\t\t}\n\t\tif (disabled) {\n\t\t\tawait emit(\n\t\t\t\tcontext,\n\t\t\t\t'user.secondFactorDisabled',\n\t\t\t\tproved,\n\t\t\t\tproved.updatedAt,\n\t\t\t);\n\t\t}\n\t\tif (formerAvatarId !== null) {\n\t\t\tawait emit(context, 'user.avatarRemoved', proved, proved.updatedAt, {\n\t\t\t\tformerAvatarId,\n\t\t\t});\n\t\t}\n\t\t// Whether or not a factor was active: a passkey is only legitimate\n\t\t// beside one, and a squatter's must not outlive this proof. An outage\n\t\t// here still leaves the sweep below, then the one at activation.\n\t\ttry {\n\t\t\tawait removeAllPasskeys(context, proved, proved.updatedAt);\n\t\t} finally {\n\t\t\tif (context.config.passkeys !== null) {\n\t\t\t\tawait context.store.passkeys?.deleteUserPasskeys(proved.id);\n\t\t\t}\n\t\t}\n\t}\n\treturn proved;\n}\n\n/**\n * Every session of the user revoked, then every API key — whoever signed up\n * with the address may have made keys with their password, whatever\n * `revokeOnPasswordReset` says — and what their password opened spent.\n */\nasync function endWhatTheSquatterOpened(\n\tcontext: Context,\n\tuser: { readonly id: Id; readonly type: string },\n): Promise<void> {\n\tconst userId = user.id;\n\tawait endEach([\n\t\t() =>\n\t\t\tcontext.store.sessions.revokeUserSessions(userId, context.clock.now()),\n\t\tasync () => {\n\t\t\tconst at = context.clock.now();\n\t\t\tconst count = await context.apiKeys?.revokeUserApiKeys(userId, at);\n\t\t\tawait keysRevoked(context, user, at, count ?? 0);\n\t\t},\n\t\t() => endWhatThePasswordOpened(context, userId),\n\t]);\n}\n",
|
|
67
|
+
"/**\n * What the two sign-ins by e-mail share — a code typed back\n * (`sign-in-code.ts`) and a link followed (`magic-link.ts`): who may be sent\n * one, keeping only the last one live, and how a redeemed one ends — the\n * e-mail proved, then the same session or second-factor challenge a\n * password opens.\n */\n\nimport { UserInactiveError } from '../errors/janus-error';\nimport type { ResolvedType } from './config';\nimport { type AnyUser, type Context, holderOfEmail } from './context';\nimport { type DeviceHint, reportNewDevice } from './devices';\nimport { proveFirstEmail } from './first-proof';\nimport { refuseStale } from './one-time';\nimport type { TokenKind, TokenRecord, UserRecord } from './port/types';\nimport { hashSecret } from './secrets';\nimport type { SignInResult } from './types';\n\n/** What a sign-in answers once the user proved who they are: `secondFactor.finish`. */\nexport type Finish = (\n\trecord: UserRecord,\n\twhere: string,\n\tdevice: DeviceHint,\n\t/** What the sign-in proved, as `SessionRecord.amr`; none when omitted. */\n\tamr?: readonly string[],\n) => Promise<SignInResult<AnyUser>>;\n\n/**\n * The user of this type holding `email`, when they may be sent a sign-in:\n * `null` for nobody, and for an inactive user — the same answer, so the\n * caller cannot tell them apart either.\n */\nexport async function signInHolder(\n\tcontext: Context,\n\ttype: ResolvedType,\n\temail: string,\n): Promise<UserRecord | null> {\n\tconst record = await holderOfEmail(context, type, email);\n\treturn record === null || !record.active ? null : record;\n}\n\n/**\n * Spends every other unspent token of this kind the user holds, sparing the\n * one just issued. Issued first, spent after, so requests that race leave\n * at most one live — maybe none, and the visitor asks again — never one each.\n */\nexport async function keepOnlyLatest(\n\tcontext: Context,\n\tuserId: string,\n\tkind: TokenKind,\n\tsecret: string,\n): Promise<void> {\n\tawait context.store.tokens.spendUserTokens(\n\t\tuserId,\n\t\tkind,\n\t\tcontext.clock.now(),\n\t\thashSecret(secret),\n\t);\n}\n\n/**\n * Ends a sign-in by e-mail whose token is spent: refuses an e-mail changed\n * since it was sent and an inactive user, proves the e-mail — it reached the\n * inbox — and finishes as a password would, reporting a new device.\n *\n * **An e-mail proved for the first time drops the password and the second\n * factor, and revokes every session** before the new one opens\n * (`./first-proof`): whoever signed up with the address without holding its\n * inbox keeps nothing, and the owner is asked for no factor they never set.\n * An e-mail already proved changes nothing. The proof is written under the\n * version read, so an address changed since is not the one proved: a\n * `VERSION_CONFLICT` then, with the token spent.\n */\nexport async function finishEmailSignIn(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tfinish: Finish,\n\tsignIn: {\n\t\treadonly user: UserRecord;\n\t\treadonly token: TokenRecord;\n\t\treadonly where: string;\n\t\treadonly noun: 'token' | 'code';\n\t\treadonly device: DeviceHint;\n\t\t/** The methods the sign-in proved (`./sessions/amr`). */\n\t\treadonly amr: readonly string[];\n\t},\n): Promise<SignInResult<AnyUser>> {\n\tconst { user, token, where, noun, device, amr } = signIn;\n\trefuseStale(type, user, token, where, noun);\n\tif (!user.active) {\n\t\tthrow new UserInactiveError(`${where}: the user is inactive`, {\n\t\t\tuserId: user.id,\n\t\t\tuserType: type.name,\n\t\t});\n\t}\n\n\tconst proved =\n\t\tuser.emailVerifiedAt !== null\n\t\t\t? user\n\t\t\t: await proveFirstEmail(context, type, user, where);\n\tconst result = await finish(proved, where, device, amr);\n\tawait reportNewDevice(context, result);\n\treturn result;\n}\n",
|
|
68
|
+
"/**\n * A request for an e-mail made in two steps — `prepare` counts it, `send`\n * issues — so the mail throttle answers in the visitor's own request, while\n * the lookup and the writes, whose time depends on whether the address has\n * an account, run off it.\n *\n * `prepare` looks nobody up: it validates, counts the address\n * (`mail-requests.ts`) and refuses past the limit, the same store calls for\n * any address. `send` is what `request` does after the count, **once**: the\n * count `prepare` made pays for one issue, so a second call is a `TypeError`\n * — a bug of the caller's, never a value from a request — and nothing a\n * caller can pass skips the count.\n */\n\n/**\n * `send` for a prepared request: `issue` on the first call, a `TypeError`\n * on every other — marked spent before `issue` starts, so two calls at once\n * cannot both issue, and spent even when `issue` fails: prepare again then,\n * which counts again.\n */\nexport function sendOnce<T>(\n\twhere: string,\n\tissue: () => Promise<T>,\n): () => Promise<T> {\n\tlet sent = false;\n\treturn async () => {\n\t\tif (sent) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${where}(…).send: already called — a prepared request sends once; call ${where} again for another`,\n\t\t\t);\n\t\t}\n\t\tsent = true;\n\t\treturn issue();\n\t};\n}\n",
|
|
69
|
+
"/**\n * Proving an e-mail on the application's own proof of the inbox — an\n * invitation token it issued to the address — with the ending a first\n * sign-in by link or code gives an e-mail never proved (`../first-proof`).\n */\n\nimport { StoreConflict, UserInactiveError } from '../../errors/janus-error';\nimport type { At } from '../at';\nimport { normalizeEmail, type ResolvedType } from '../config';\nimport {\n\ttype AnyUser,\n\ttype Context,\n\temailOf,\n\tgetRecord,\n\trefId,\n\ttoUser,\n} from '../context';\nimport { proveFirstEmail } from '../first-proof';\nimport { unlessVersionConflict } from '../outage';\nimport type { UserRecord } from '../port/types';\nimport type { UserRef, VerifyEmailApi } from '../types';\n\n/**\n * `verifyEmail.proveFirst` for one user type: the user read by id —\n * `NOT_FOUND` for nobody, as `signInProven` — refused when inactive, then,\n * when the e-mail was never proved, `proveFirstEmail` exactly as\n * `magicLink.confirm` and `signInCode.confirm` run it, decided the same way:\n * on the record read, `emailVerifiedAt === null`. An e-mail already proved\n * is answered as it is, with nothing written.\n *\n * **The address the caller holds is checked.** When the `UserRef` is an\n * object carrying the type's e-mail field — a `User` — that address,\n * normalised as e-mails are, must be the one read, on the first read and on\n * the retry read; otherwise it is a `VERSION_CONFLICT` and nothing is proved.\n * With a bare id, or an object without the e-mail field, the current address\n * is proved.\n *\n * **A write landing between the read and the proof is retried once.**\n * `VERSION_CONFLICT` from `proveFirstEmail` runs the whole flow again on a\n * fresh read: nobody, or an inactive user, is refused as before; an e-mail\n * that is no longer the one first read — compared as e-mails are — is a\n * `VERSION_CONFLICT` naming both versions, since the address changed since the\n * first read (or is not the one the passed `User` carries) and the proof the\n * caller holds is for the address it read; an e-mail proved meanwhile is\n * answered `proved: false`; otherwise the proof runs under the new version.\n * A second `VERSION_CONFLICT` propagates.\n *\n * Running `proveFirstEmail` twice is harmless: a failed attempt wrote\n * nothing and sent no event (events follow the write); all it left is the\n * sessions revoked and the tokens spent before the write, which the second\n * attempt does again to the same end.\n *\n * No throttle is counted and no count restarted, no e-mail sent and no\n * token issued; the only tokens spent are the ones `proveFirstEmail`\n * spends, what the password opened.\n */\nexport function proveFirstFlow(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tat: At,\n): VerifyEmailApi<AnyUser>['verifyEmail']['proveFirst'] {\n\treturn async (user) => {\n\t\tconst where = at('verifyEmail.proveFirst');\n\t\tconst id = refId(user);\n\t\tconst claimed = claimedEmail(type, user);\n\t\tconst first = await readActive(context, type, id, where);\n\t\tassertClaimed(type, claimed, first, user, where);\n\t\tconst answer = await unlessVersionConflict(\n\t\t\tproveOrAnswer(context, type, first, where),\n\t\t);\n\t\tif (answer !== null) return answer;\n\t\tconst again = await readActive(context, type, id, where);\n\t\tassertClaimed(type, claimed, again, user, where);\n\t\tif (!sameEmail(type, first, again)) {\n\t\t\tthrow new StoreConflict(\n\t\t\t\t'version',\n\t\t\t\t`${where}: the e-mail changed since it was read`,\n\t\t\t\t{\n\t\t\t\t\tuserId: first.id,\n\t\t\t\t\texpectedVersion: first.version,\n\t\t\t\t\tactualVersion: again.version,\n\t\t\t\t\toperation: where,\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t\treturn proveOrAnswer(context, type, again, where);\n\t};\n}\n\n/** The user read by id, refused when inactive. */\nasync function readActive(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tid: string,\n\twhere: string,\n): Promise<UserRecord> {\n\tconst record = await getRecord(context, id, type.name, where);\n\tif (!record.active) {\n\t\tthrow new UserInactiveError(`${where}: the user is inactive`, {\n\t\t\tuserId: record.id,\n\t\t\tuserType: type.name,\n\t\t});\n\t}\n\treturn record;\n}\n\n/** `proved: false` for an e-mail already proved, else the proof itself. */\nasync function proveOrAnswer(\n\tcontext: Context,\n\ttype: ResolvedType,\n\trecord: UserRecord,\n\twhere: string,\n): Promise<{ user: AnyUser; proved: boolean }> {\n\tif (record.emailVerifiedAt !== null) {\n\t\treturn { user: toUser(record), proved: false };\n\t}\n\tconst proved = await proveFirstEmail(context, type, record, where);\n\treturn { user: toUser(proved), proved: true };\n}\n\n/** Whether both records hold one address, compared as e-mails are. */\nfunction sameEmail(type: ResolvedType, a: UserRecord, b: UserRecord): boolean {\n\tconst held = (record: UserRecord) => {\n\t\tconst email = emailOf(type, record.fields);\n\t\treturn email === null ? null : normalizeEmail(email);\n\t};\n\treturn held(a) === held(b);\n}\n\n/** The address a `User` caller holds, normalised; `null` for an id or no field. */\nfunction claimedEmail(type: ResolvedType, user: UserRef): string | null {\n\tif (typeof user !== 'object' || user === null) return null;\n\tconst value: unknown = (user as Record<string, unknown>)[type.email];\n\treturn typeof value === 'string' ? normalizeEmail(value) : null;\n}\n\n/** `VERSION_CONFLICT` when the address read is not the one the caller holds. */\nfunction assertClaimed(\n\ttype: ResolvedType,\n\tclaimed: string | null,\n\trecord: UserRecord,\n\tuser: UserRef,\n\twhere: string,\n): void {\n\tif (claimed === null) return;\n\tconst email = emailOf(type, record.fields);\n\tif (email !== null && normalizeEmail(email) === claimed) return;\n\tconst held = (user as { readonly version?: unknown }).version;\n\tthrow new StoreConflict(\n\t\t'version',\n\t\t`${where}: the e-mail changed since the user was read`,\n\t\t{\n\t\t\tuserId: record.id,\n\t\t\t...(typeof held === 'number' ? { expectedVersion: held } : {}),\n\t\t\tactualVersion: record.version,\n\t\t\toperation: where,\n\t\t},\n\t);\n}\n",
|
|
70
|
+
"/**\n * Verifying an e-mail: send a token to it, then redeem the token to mark the\n * address verified — or prove it on the application's own proof\n * (`prove-first.ts`).\n */\n\nimport type { Id } from '../../ids/id';\nimport type { At } from '../at';\nimport type { ResolvedType } from '../config';\nimport {\n\ttype AnyUser,\n\ttype Context,\n\tgetRecord,\n\tidOf,\n\trefId,\n\ttoUser,\n\twriteUser,\n} from '../context';\nimport { signInHolder } from '../email-sign-in';\nimport { emit } from '../events';\nimport { proveFirstEmail } from '../first-proof';\nimport { countMailByAddress, countMailByUser } from '../mail-requests';\nimport { refuseStale } from '../one-time';\nimport { sendOnce } from '../prepared';\nimport type {\n\tIssuedToken,\n\tPreparedRequest,\n\tVerifyEmailApi,\n\tVerifyEmailOptions,\n} from '../types';\nimport { issueEmailToken, redeemEmailToken } from './email-token';\nimport { proveFirstFlow } from './prove-first';\n\n/**\n * `verifyEmail` of one user type: `send` a token to its e-mail, then\n * `confirm` it; or `proveFirst`, on the application's own proof.\n */\nexport function verifyEmailFlows(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tat: At,\n): VerifyEmailApi<AnyUser>['verifyEmail'] {\n\treturn {\n\t\tasync send(user) {\n\t\t\tconst where = at('verifyEmail.send');\n\t\t\tconst record = await getRecord(context, idOf(user), type.name, where);\n\t\t\t// Counted per user: the application asks for a user it knows.\n\t\t\tawait countMailByUser(context, type, 'verifyEmail', record.id, where);\n\t\t\treturn issueEmailToken(context, type, 'verifyEmail', record, where);\n\t\t},\n\n\t\tasync prepare(email) {\n\t\t\tconst where = at('verifyEmail.prepare');\n\t\t\treturn prepareVerify(context, type, String(email), where);\n\t\t},\n\n\t\tconfirm: (secret, options) =>\n\t\t\tconfirmVerify(context, type, secret, at('verifyEmail.confirm'), options),\n\n\t\tproveFirst: proveFirstFlow(context, type, at),\n\t};\n}\n\n/**\n * Redeems a verification token: marks the e-mail verified. `asked` is the type\n * whose `confirm` was called, or null for the root's, where the user's own type\n * answers. With `options.firstProof`, an address never proved is proved as\n * `magicLink.confirm` does (`../first-proof`): the password and the second\n * factor set before the proof are dropped and every session is revoked.\n * With `options.user`, only that user's token confirms: another's is\n * `TOKEN_UNKNOWN`, not spent, and nothing is written.\n */\nexport async function confirmVerify(\n\tcontext: Context,\n\tasked: ResolvedType | null,\n\tsecret: string,\n\twhere: string,\n\toptions?: VerifyEmailOptions,\n): Promise<AnyUser> {\n\tconst bound = boundId(options);\n\tconst { token, user, type } = await redeemEmailToken(\n\t\tcontext,\n\t\tasked,\n\t\t'verifyEmail',\n\t\tsecret,\n\t\twhere,\n\t\tbound,\n\t);\n\tif (options?.firstProof === true && user.emailVerifiedAt === null) {\n\t\t// The token was checked against this very record; the proof is\n\t\t// written under its version, so an address changed since conflicts.\n\t\treturn toUser(await proveFirstEmail(context, type, user, where));\n\t}\n\tlet newlyVerified = false;\n\tconst written = await writeUser(\n\t\tcontext,\n\t\tuser.id,\n\t\ttype,\n\t\tundefined,\n\t\twhere,\n\t\t(record, now) => {\n\t\t\t// Checked again on the record written: an e-mail changed\n\t\t\t// since the read above is not the one the link proved.\n\t\t\trefuseStale(type, record, token, where, 'token');\n\t\t\tnewlyVerified = record.emailVerifiedAt === null;\n\t\t\treturn { emailVerifiedAt: now };\n\t\t},\n\t);\n\tif (newlyVerified) {\n\t\tawait emit(context, 'user.emailVerified', written, written.updatedAt);\n\t}\n\treturn toUser(written);\n}\n\n/**\n * The id `options.user` binds the confirmation to, `undefined` when it is\n * absent. A reference naming no user binds to an id no token has, so the\n * store answers it unknown; the store is not asked to read it as \"any\".\n */\nfunction boundId(options: VerifyEmailOptions | undefined): Id | undefined {\n\t// A `user` key present but empty (`{ user: session?.user }` with no session)\n\t// binds to nobody: it never falls back to an unbound confirmation.\n\tif (options === undefined || !('user' in options)) return undefined;\n\tconst { user } = options;\n\treturn refId(user);\n}\n\ntype IssuedVerify = IssuedToken & { readonly user: AnyUser };\n\n/**\n * Counts a verification asked for `email` — before it is looked up: past\n * the limit, nobody and somebody are refused alike — and answers the `send`\n * that issues it, once, for an active user who has not verified the address.\n */\nasync function prepareVerify(\n\tcontext: Context,\n\ttype: ResolvedType,\n\temail: string,\n\twhere: string,\n): Promise<PreparedRequest<IssuedVerify>> {\n\tawait countMailByAddress(context, type, 'verifyEmail', email, where);\n\treturn Object.freeze({\n\t\tsend: sendOnce(where, async () => {\n\t\t\t// Nobody, an inactive user and a verified address: the same answer.\n\t\t\tconst record = await signInHolder(context, type, email);\n\t\t\tif (record === null || record.emailVerifiedAt !== null) return null;\n\t\t\tconst issued = await issueEmailToken(\n\t\t\t\tcontext,\n\t\t\t\ttype,\n\t\t\t\t'verifyEmail',\n\t\t\t\trecord,\n\t\t\t\twhere,\n\t\t\t);\n\t\t\treturn { ...issued, user: toUser(record) };\n\t\t}),\n\t});\n}\n",
|
|
71
|
+
"/**\n * The confirmation of an e-mail at the root of an instance with several user\n * types: for the page that follows the link and does not know the user's type.\n */\n\nimport type { AnyUser, Context } from '../context';\nimport type { VerifyEmailOptions } from '../types';\nimport { confirmVerify } from './verify-email';\n\n/**\n * `{ verifyEmail: { confirm } }`. Built whatever the types, as each type's\n * flows are; the types show it only when one has an e-mail, and a user of a\n * type without one is `TOKEN_UNKNOWN`. `send` and `proveFirst` stay on each\n * type: they need the user's type.\n */\nexport function anyTypeVerifyEmail(context: Context): {\n\treadonly verifyEmail: {\n\t\tconfirm(token: string, options?: VerifyEmailOptions): Promise<AnyUser>;\n\t};\n} {\n\treturn {\n\t\tverifyEmail: {\n\t\t\tconfirm: (secret, options) =>\n\t\t\t\tconfirmVerify(context, null, secret, 'verifyEmail.confirm', options),\n\t\t},\n\t};\n}\n",
|
|
72
|
+
"/**\n * `assertFresh`: whether a session proved who it is recently enough for a\n * sensitive action — signed in, or confirmed by a step-up, less than\n * `maxAge` ago.\n */\n\nimport { StepUpRequiredError } from '../../errors/janus-error';\nimport { type Clock, systemClock } from '../../time/clock';\nimport { type Duration, parseDuration } from '../../time/duration';\nimport type { Principal, Session } from '../types';\n\n/**\n * Refuses a session whose credentials were last presented `maxAge` ago or\n * more — at its sign-in, or since by `stepUp.confirm` — with\n * `STEP_UP_REQUIRED` (403): ask for a step-up, then run the action again. One\n * field of the session `authenticate` already answered, so no store is read.\n *\n * ```ts\n * const current = await auth.authenticate(request);\n * if (current === null) return new Response(null, { status: 401 });\n * assertFresh(current.session, '10m'); // STEP_UP_REQUIRED past ten minutes\n * ```\n *\n * Pass the `clock` given to `janus()` when it is not the system's. A\n * `maxAge` that is not a duration is a `TypeError`: it is written in the\n * code, never read from a request.\n */\nexport function assertFresh(\n\tsession: Pick<Session, 'authenticatedAt' | 'userId'>,\n\tmaxAge: Duration,\n\tclock?: Clock,\n): void;\n/**\n * The same check on whoever `authenticate(request, { apiKey: true })`\n * answered. **A key is never fresh**: it always refuses with\n * `STEP_UP_REQUIRED` and `reason: 'apiKey'` — a step-up cannot make a key\n * fresh, so the caller needs a signed-in session instead.\n */\nexport function assertFresh(\n\tprincipal: Principal<{ readonly id: string }>,\n\tmaxAge: Duration,\n\tclock?: Clock,\n): void;\nexport function assertFresh(\n\tsubject:\n\t\t| Pick<Session, 'authenticatedAt' | 'userId'>\n\t\t| Principal<{ readonly id: string }>,\n\tmaxAge: Duration,\n\tclock: Clock = systemClock,\n): void {\n\tif ('via' in subject) {\n\t\tif (subject.via === 'apiKey') {\n\t\t\tthrow new StepUpRequiredError(\n\t\t\t\t'assertFresh: an API key is never fresh — the caller needs a signed-in session',\n\t\t\t\t{ userId: subject.apiKey.userId, reason: 'apiKey' },\n\t\t\t);\n\t\t}\n\t}\n\tconst session = 'via' in subject ? subject.session : subject;\n\tconst maxAgeMs = parseDuration(maxAge, 'assertFresh: maxAge');\n\tconst age = clock.now().getTime() - session.authenticatedAt.getTime();\n\tif (age >= maxAgeMs) {\n\t\tthrow new StepUpRequiredError(\n\t\t\t'assertFresh: the session proved who it is longer ago than maxAge — confirm with a step-up',\n\t\t\t{ userId: session.userId },\n\t\t);\n\t}\n}\n",
|
|
73
|
+
"/** The name a user gives a passkey: what `register` and `rename` accept. */\n\nimport { PasskeyError } from '../../errors/janus-error';\nimport { isStorable } from '../../stores/storable';\n\nconst NAME_MAX = 100;\n\n/** The trimmed name, or `PASSKEY_INVALID` with `field: 'name'`. Nothing is read or spent first. */\nexport function checkName(name: unknown, where: string): string {\n\tconst trimmed = typeof name === 'string' ? name.trim() : '';\n\tif (trimmed.length < 1 || trimmed.length > NAME_MAX || !isStorable(trimmed)) {\n\t\tthrow new PasskeyError(\n\t\t\t'PASSKEY_INVALID',\n\t\t\t`${where}: name must be 1 to ${NAME_MAX} characters once trimmed`,\n\t\t\t{ field: 'name' },\n\t\t);\n\t}\n\treturn trimmed;\n}\n",
|
|
74
|
+
"/** Wiring refusals for `passkeys`: bare `TypeError`s, since only wiring produces one. */\n\nimport type { ResolvedConfig } from '../config';\nimport type { Context } from '../context';\nimport type { JanusStores, PasskeyStore } from '../port/types';\n\n/**\n * `passkeys` needs `store.passkeys`: the slot is optional so an application\n * without passkeys carries none, and this is where the one that has them is\n * told which store to change.\n */\nexport function refusePasskeysWithoutSlot(\n\tresolved: ResolvedConfig,\n\tstore: JanusStores,\n\twhere: string,\n): void {\n\tif (resolved.passkeys !== null && store.passkeys === undefined) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: janus() is given passkeys and store.passkeys is missing — createMemoryStores() has it; an adapter's stores need its passkeys table or collection`,\n\t\t);\n\t}\n}\n\n/** What the flows work with, or a wiring refusal when `passkeys` was not configured. */\nexport function requirePasskeys(\n\tcontext: Context,\n\twhere: string,\n): {\n\treadonly settings: NonNullable<ResolvedConfig['passkeys']>;\n\treadonly store: PasskeyStore;\n} {\n\tconst settings = context.config.passkeys;\n\tconst store = context.store.passkeys;\n\tif (settings === null || store === undefined) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: janus() was given no passkeys — pass passkeys: { rpId, rpName, origins, verifier }`,\n\t\t);\n\t}\n\treturn { settings, store };\n}\n\n/**\n * What the passwordless flows work with, or a wiring refusal when\n * `passkeys.firstFactor` was not turned on.\n */\nexport function requireFirstFactor(\n\tcontext: Context,\n\twhere: string,\n): {\n\treadonly settings: NonNullable<ResolvedConfig['passkeys']>;\n\treadonly store: PasskeyStore;\n} {\n\tconst wired = requirePasskeys(context, where);\n\tif (!wired.settings.firstFactor) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: passkeys.firstFactor is not on — a passkey is a second factor only; pass passkeys: { …, firstFactor: true } to sign in with one alone`,\n\t\t);\n\t}\n\treturn wired;\n}\n",
|
|
75
|
+
"/** The last steps of `passkeys.register`: the insert, and the two checks a race can break. */\n\nimport {\n\tEmailUnverifiedError,\n\tPasskeyError,\n\tPasskeyLimitError,\n\tSecondFactorError,\n} from '../../errors/janus-error';\nimport type { ResolvedType } from '../config';\nimport { type Context, emailOf, getRecord } from '../context';\nimport type { PasskeyRecord, UserRecord } from '../port/types';\nimport { isActive } from '../second-factor/factor';\nimport type { PasskeyRegistration } from './verifier';\nimport { requirePasskeys } from './wiring';\n\nexport function limitReached(\n\tmaxPerUser: number,\n\tuserId: string,\n\twhere: string,\n): PasskeyLimitError {\n\treturn new PasskeyLimitError(\n\t\t`${where}: the user already holds ${maxPerUser} passkeys — remove one first`,\n\t\t{ userId, maxActive: maxPerUser },\n\t);\n}\n\n/**\n * Stores the verified passkey and answers the record held. Refuses, with\n * nothing kept, when:\n *\n * - the credential id is already held (`PASSKEY_TAKEN`);\n * - the TOTP was disabled meanwhile — its disable may have listed the\n * passkeys before this one was inserted, and a passkey never stands without\n * an active TOTP (`SECOND_FACTOR_NOT_ENROLLED`);\n * - the e-mail stopped being proved meanwhile, or is no longer the one the\n * call checked (`EMAIL_UNVERIFIED`): the first proof would drop the passkey,\n * so none is kept beside an unproved address, and one registered before a\n * proof of another address (the e-mail moved and proved between the check\n * and the insert) is not kept either. Fail closed: a `changeEmail.confirm`\n * landing in that instant withdraws a legitimate passkey, and the user\n * registers again;\n * - a parallel registration took the user past `maxPerUser` — the count is\n * read again after the insert, and **both** racers may then withdraw\n * (`PASSKEY_LIMIT`): fail closed, the user registers again.\n */\nexport async function commitPasskey(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tinput: {\n\t\treadonly user: UserRecord;\n\t\treadonly verified: PasskeyRegistration;\n\t\treadonly name: string;\n\t\treadonly now: Date;\n\t},\n\twhere: string,\n) {\n\tconst { store } = requirePasskeys(context, where);\n\tconst { user, verified, name, now } = input;\n\tconst refusal = { userId: user.id, userType: type.name };\n\tconst record: PasskeyRecord = {\n\t\tcredentialId: verified.credentialId,\n\t\tuserId: user.id,\n\t\tpublicKey: verified.publicKey,\n\t\tcounter: verified.counter,\n\t\ttransports: verified.transports,\n\t\taaguid: verified.aaguid,\n\t\tbackupEligible: verified.backupEligible,\n\t\tbackedUp: verified.backedUp,\n\t\tname,\n\t\tcreatedAt: now,\n\t\tlastUsedAt: null,\n\t};\n\tconst held = await store.insertPasskey(record);\n\t// The store answers the holder of the credential id: this write, or\n\t// whoever got there first — the same user included, since one\n\t// authenticator registers once.\n\tif (\n\t\theld.userId !== user.id ||\n\t\theld.createdAt.getTime() !== now.getTime() ||\n\t\theld.publicKey !== record.publicKey\n\t) {\n\t\tthrow new PasskeyError(\n\t\t\t'PASSKEY_TAKEN',\n\t\t\t`${where}: this credential is already registered`,\n\t\t\trefusal,\n\t\t);\n\t}\n\n\tawait assertStillHeld(context, type, user, held.credentialId, where);\n\treturn held;\n}\n\n/**\n * The checks after the insert, in order; each failure deletes the passkey just\n * inserted and throws, so nothing is kept.\n */\nasync function assertStillHeld(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tuser: UserRecord,\n\tcredentialId: string,\n\twhere: string,\n): Promise<void> {\n\tconst { settings, store } = requirePasskeys(context, where);\n\tconst refusal = { userId: user.id, userType: type.name };\n\tconst after = await getRecord(context, user.id, type.name, where);\n\tif (!settings.firstFactor && !isActive(after.secondFactor)) {\n\t\tawait store.deletePasskey(user.id, credentialId);\n\t\tthrow new SecondFactorError(\n\t\t\t'SECOND_FACTOR_NOT_ENROLLED',\n\t\t\t`${where}: the TOTP was disabled while the passkey was registered — nothing was kept`,\n\t\t\trefusal,\n\t\t);\n\t}\n\n\tif (emailOf(type, after.fields) !== null && after.emailVerifiedAt === null) {\n\t\tawait store.deletePasskey(user.id, credentialId);\n\t\tthrow new EmailUnverifiedError(\n\t\t\t`${where}: the e-mail stopped being verified while the passkey was registered — nothing was kept`,\n\t\t\trefusal,\n\t\t);\n\t}\n\n\t// The e-mail `assertCanHold` saw proved is not the one proved now: it was\n\t// moved and proved again between the check and the insert, and that proof\n\t// wiped the factors before this passkey existed.\n\tif (\n\t\temailOf(type, after.fields) !== emailOf(type, user.fields) ||\n\t\tafter.emailVerifiedAt?.getTime() !== user.emailVerifiedAt?.getTime()\n\t) {\n\t\tawait store.deletePasskey(user.id, credentialId);\n\t\tthrow new EmailUnverifiedError(\n\t\t\t`${where}: the e-mail changed or was proved again while the passkey was registered — nothing was kept`,\n\t\t\trefusal,\n\t\t);\n\t}\n\n\tif ((await store.listUserPasskeys(user.id)).length > settings.maxPerUser) {\n\t\tawait store.deletePasskey(user.id, credentialId);\n\t\tthrow limitReached(settings.maxPerUser, user.id, where);\n\t}\n}\n",
|
|
76
|
+
"/** `passkeys.registrationOptions`: a challenge, and the options the browser needs. */\n\nimport {\n\tEmailUnverifiedError,\n\tSecondFactorError,\n\tUserInactiveError,\n} from '../../errors/janus-error';\nimport type { ResolvedType } from '../config';\nimport { type Context, emailOf, getRecord, idOf } from '../context';\nimport { issueOneTime } from '../one-time';\nimport { isActive } from '../second-factor/factor';\nimport { hashSecret } from '../secrets';\nimport type { PasskeyRegistrationOptions, UserRef } from '../types';\nimport { requirePasskeys } from './wiring';\n\n/**\n * Refuses a user who cannot hold a passkey: unknown, inactive, or — unless\n * `passkeys.firstFactor` is on — without an active TOTP: a passkey is then\n * only ever registered beside one. With it, a type that has an e-mail needs\n * that e-mail verified: a passkey that signs in alone must never belong to\n * someone who squatted an address (a password reset or an e-mail proof of the\n * real owner would not remove it otherwise).\n */\nexport function assertCanHold(\n\trecord: {\n\t\treadonly id: string;\n\t\treadonly active: boolean;\n\t\treadonly fields: Parameters<typeof emailOf>[1];\n\t\treadonly emailVerifiedAt: Date | null;\n\t\treadonly secondFactor: Parameters<typeof isActive>[0];\n\t},\n\ttype: ResolvedType,\n\twhere: string,\n\tfirstFactor: boolean,\n): void {\n\tif (!record.active) {\n\t\tthrow new UserInactiveError(`${where}: the user is inactive`, {\n\t\t\tuserId: record.id,\n\t\t});\n\t}\n\t// The first proof of the e-mail drops every passkey with the factor, and\n\t// a passkey that signs in alone must never belong to a squatter.\n\tif (\n\t\temailOf(type, record.fields) !== null &&\n\t\trecord.emailVerifiedAt === null\n\t) {\n\t\tthrow new EmailUnverifiedError(\n\t\t\t`${where}: the e-mail is not verified — a passkey is registered after it is proved`,\n\t\t\t{ userId: record.id, userType: type.name },\n\t\t);\n\t}\n\tif (!firstFactor && !isActive(record.secondFactor)) {\n\t\tthrow new SecondFactorError(\n\t\t\t'SECOND_FACTOR_NOT_ENROLLED',\n\t\t\t`${where}: the user has no active TOTP — a passkey is only registered beside one`,\n\t\t\t{ userId: record.id, userType: type.name },\n\t\t);\n\t}\n}\n\nexport async function registrationOptions(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tuser: UserRef,\n\twhere: string,\n): Promise<PasskeyRegistrationOptions> {\n\tconst { settings, store } = requirePasskeys(context, where);\n\tconst record = await getRecord(context, idOf(user), type.name, where);\n\tassertCanHold(record, type, where, settings.firstFactor);\n\n\tconst existing = await store.listUserPasskeys(record.id);\n\tconst name = emailOf(type, record.fields) ?? record.id;\n\tconst { secret, expiresAt } = await issueOneTime(context, {\n\t\tkind: 'passkeyRegistration',\n\t\tuserId: record.id,\n\t\taddress: '',\n\t\tttlMs: context.config.tokenTtlMs.passkeyRegistration,\n\t});\n\t// One live registration per user, as for a step-up: issued first, the\n\t// others spent after, so requests that race leave at most one.\n\tawait context.store.tokens.spendUserTokens(\n\t\trecord.id,\n\t\t'passkeyRegistration',\n\t\tcontext.clock.now(),\n\t\thashSecret(secret),\n\t);\n\tconst options = await settings.verifier.registrationOptions({\n\t\trp: settings.rp,\n\t\t// Opaque and stable: the same user always gets the same handle, so an\n\t\t// authenticator that already holds a credential for them is recognised.\n\t\tuser: {\n\t\t\thandle: Buffer.from(record.id, 'utf8').toString('base64url'),\n\t\t\tname,\n\t\t\tdisplayName: name,\n\t\t},\n\t\tchallenge: secret,\n\t\texclude: existing.map((passkey) => ({\n\t\t\tcredentialId: passkey.credentialId,\n\t\t\ttransports: passkey.transports,\n\t\t})),\n\t\t...(settings.firstFactor ? { discoverable: true } : {}),\n\t});\n\treturn { options, challenge: secret, expiresAt };\n}\n",
|
|
77
|
+
"/** A stored passkey as the application sees it: without the public key or the counter. */\n\nimport type { PasskeyRecord } from '../port/types';\nimport type { Passkey } from '../types';\n\nexport function toPasskey(record: PasskeyRecord): Passkey {\n\treturn {\n\t\tcredentialId: record.credentialId,\n\t\tuserId: record.userId,\n\t\tname: record.name,\n\t\ttransports: [...record.transports],\n\t\taaguid: record.aaguid,\n\t\tbackupEligible: record.backupEligible,\n\t\tbackedUp: record.backedUp,\n\t\tcreatedAt: new Date(record.createdAt.getTime()),\n\t\tlastUsedAt:\n\t\t\trecord.lastUsedAt === null ? null : new Date(record.lastUsedAt.getTime()),\n\t};\n}\n",
|
|
78
|
+
"/** `passkeys.register`: spends the challenge, verifies the response, stores the passkey. */\n\nimport { NotFoundError, PasskeyError } from '../../errors/janus-error';\nimport type { ResolvedType } from '../config';\nimport { type Context, getRecord } from '../context';\nimport { emit } from '../events';\nimport { spendOneTime, unknownOneTime } from '../one-time';\nimport { assertFresh } from '../sessions/fresh';\nimport type { Authenticated, Passkey } from '../types';\nimport { commitPasskey, limitReached } from './commit';\nimport { checkName } from './name';\nimport { assertCanHold } from './registration-options';\nimport { toPasskey } from './view';\nimport { requirePasskeys } from './wiring';\n\ninterface Input {\n\treadonly challenge: unknown;\n\treadonly response: unknown;\n\treadonly name: unknown;\n}\n\nexport async function registerPasskey(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tcurrent: Authenticated<{ readonly id: string; readonly type: string }>,\n\tinput: Input,\n\twhere: string,\n): Promise<Passkey> {\n\tconst { settings, store } = requirePasskeys(context, where);\n\tconst userId = sessionUserId(current, type, where);\n\tassertFresh(current, settings.freshWithinMs, context.clock);\n\t// Before anything is spent: a bad name costs the user nothing.\n\tconst name = checkName(input?.name, where);\n\tconst challenge = input?.challenge;\n\tif (typeof challenge !== 'string' || challenge === '') {\n\t\tthrow unknownOneTime(where, 'challenge');\n\t}\n\n\t// Before the challenge is spent: a user at the cap loses nothing.\n\tif ((await store.listUserPasskeys(userId)).length >= settings.maxPerUser) {\n\t\tthrow limitReached(settings.maxPerUser, userId, where);\n\t}\n\n\tconst token = await spendOneTime(\n\t\tcontext,\n\t\tchallenge,\n\t\t'passkeyRegistration',\n\t\twhere,\n\t\t'challenge',\n\t);\n\t// Another user's challenge is no challenge at all.\n\tif (token.userId !== userId) throw unknownOneTime(where, 'challenge');\n\n\tconst user = await getRecord(context, userId, type.name, where);\n\tassertCanHold(user, type, where, settings.firstFactor);\n\n\tconst verified = await settings.verifier.verifyRegistration({\n\t\trp: settings.rp,\n\t\tresponse: input.response,\n\t\texpectedChallenge: challenge,\n\t});\n\tif (!verified.ok) {\n\t\tthrow new PasskeyError(\n\t\t\t'PASSKEY_INVALID',\n\t\t\t`${where}: the browser's response did not verify (${verified.reason}) — ask for new options`,\n\t\t\t{ userId, userType: type.name, reason: verified.reason },\n\t\t);\n\t}\n\n\tconst now = context.clock.now();\n\tconst held = await commitPasskey(\n\t\tcontext,\n\t\ttype,\n\t\t{ user, verified, name, now },\n\t\twhere,\n\t);\n\n\tawait emit(context, 'user.passkeyAdded', user, now, {\n\t\tpasskey: { credentialId: held.credentialId, name: held.name },\n\t});\n\treturn toPasskey(held);\n}\n\n/** The session's user id, refused when it is not of this type. */\nexport function sessionUserId(\n\tcurrent: Authenticated<{ readonly id: string; readonly type: string }>,\n\ttype: ResolvedType,\n\twhere: string,\n): string {\n\tconst user: unknown = current?.user;\n\tconst id = (user as { id?: unknown } | null)?.id;\n\tconst kind = (user as { type?: unknown } | null)?.type;\n\tif (typeof id !== 'string' || kind !== type.name) {\n\t\tthrow new NotFoundError(`${where}: no ${type.name} has this id`, {\n\t\t\toperation: where,\n\t\t});\n\t}\n\treturn id;\n}\n",
|
|
79
|
+
"/** `passkeys.list`, `rename` and `remove`. */\n\nimport { isId } from '../../ids/id';\nimport type { ResolvedType } from '../config';\nimport { type Context, getRecord, idOf } from '../context';\nimport { emit } from '../events';\nimport { assertFresh } from '../sessions/fresh';\nimport type { Authenticated, Passkey, UserRef } from '../types';\nimport { checkName } from './name';\nimport { sessionUserId } from './register';\nimport { toPasskey } from './view';\nimport { requirePasskeys } from './wiring';\n\nexport async function listPasskeys(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tuser: UserRef,\n\twhere: string,\n): Promise<readonly Passkey[]> {\n\tconst { store } = requirePasskeys(context, where);\n\tconst record = await getRecord(context, idOf(user), type.name, where);\n\tconst found = await store.listUserPasskeys(record.id);\n\treturn [...found]\n\t\t.sort(\n\t\t\t(a, b) =>\n\t\t\t\ta.createdAt.getTime() - b.createdAt.getTime() ||\n\t\t\t\ta.credentialId.localeCompare(b.credentialId),\n\t\t)\n\t\t.map(toPasskey);\n}\n\nexport async function renamePasskey(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tuser: UserRef,\n\tcredentialId: unknown,\n\tname: unknown,\n\twhere: string,\n): Promise<boolean> {\n\tconst { store } = requirePasskeys(context, where);\n\tconst checked = checkName(name, where);\n\tconst record = await getRecord(context, idOf(user), type.name, where);\n\tif (typeof credentialId !== 'string' || credentialId === '') return false;\n\treturn store.renamePasskey(record.id, credentialId, checked);\n}\n\nexport async function removePasskey(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tcurrent: Authenticated<{ readonly id: string; readonly type: string }>,\n\tcredentialId: unknown,\n\twhere: string,\n): Promise<boolean> {\n\tconst { settings, store } = requirePasskeys(context, where);\n\tconst userId = sessionUserId(current, type, where);\n\tassertFresh(current, settings.freshWithinMs, context.clock);\n\tif (\n\t\ttypeof credentialId !== 'string' ||\n\t\tcredentialId === '' ||\n\t\t!isId(userId)\n\t) {\n\t\treturn false;\n\t}\n\tconst held = await store.findPasskey(credentialId);\n\tif (!(await store.deletePasskey(userId, credentialId))) return false;\n\tawait emit(\n\t\tcontext,\n\t\t'user.passkeyRemoved',\n\t\tcurrent.user,\n\t\tcontext.clock.now(),\n\t\t{\n\t\t\t// `held` is the user's own: the delete is conditional on the owner.\n\t\t\tpasskey: { credentialId, name: held?.name ?? '' },\n\t\t},\n\t);\n\treturn true;\n}\n",
|
|
80
|
+
"/**\n * Opening a session once a user proved who they are, and the session as\n * application code sees it.\n */\n\nimport { mintId } from '../../ids/id';\nimport type { ResolvedType } from '../config';\nimport { type AnyUser, type Context, toUser } from '../context';\nimport { type DeviceHint, deviceOutcome } from '../devices';\nimport type { SessionRecord, UserRecord } from '../port/types';\nimport { hashSecret, mintSecret } from '../secrets';\nimport type { Session, SignedIn } from '../types';\n\n/** A session as application code sees it: everything but the token's hash. */\nexport function toSession(record: SessionRecord): Session {\n\tconst { tokenHash: _, amr, ...session } = record;\n\treturn { ...session, amr: [...(amr ?? [])] };\n}\n\n/**\n * Opens a session for a user who just proved who they are. The token is in\n * the answer and nowhere else: the store holds its hash.\n *\n * `device` is what the sign-in was told of the device, and the answer says\n * whether it is new to the user; `signUp` mints a first token and is never\n * new. `amr` is what the user proved (`./amr`). Reporting a new device is the caller's, once its sign-in is complete\n * (`reportNewDevice`).\n */\nexport async function openSession(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tuser: UserRecord,\n\tdevice: DeviceHint,\n\tsignUp = false,\n\tamr: readonly string[] = [],\n): Promise<SignedIn<AnyUser>> {\n\tconst now = context.clock.now();\n\tconst token = mintSecret();\n\tconst record: SessionRecord = {\n\t\tid: mintId(now.getTime()),\n\t\ttokenHash: hashSecret(token),\n\t\tuserId: user.id,\n\t\tauthenticatedAt: now,\n\t\t// A cap shorter than the lifespan ends the session at the cap.\n\t\texpiresAt: new Date(\n\t\t\tnow.getTime() +\n\t\t\t\tMath.min(type.lifespanMs, type.absoluteMs ?? type.lifespanMs),\n\t\t),\n\t\trevokedAt: null,\n\t\tcreatedAt: now,\n\t\t...(device.label === undefined ? {} : { device: device.label }),\n\t\tlastUsedAt: now,\n\t\tamr: [...amr],\n\t};\n\n\tawait context.store.sessions.insertSession(record);\n\treturn {\n\t\tstatus: 'signedIn',\n\t\tuser: toUser(user),\n\t\tsession: toSession(record),\n\t\ttoken,\n\t\t...deviceOutcome(context, user.id, device, signUp),\n\t};\n}\n",
|
|
81
|
+
"/**\n * Reading the session token a request presents, whatever shape the request\n * arrives in.\n */\n\nimport type { HeaderRecord, RequestLike } from '../types';\n\n/**\n * The session token a request presents: `Authorization: Bearer`, then\n * `X-Session-Token`, then the cookie.\n *\n * **The first credential present wins, not the first valid one.** A browser\n * sending a lapsed bearer beside a live cookie is anonymous, and should fix its\n * header rather than be rescued in silence — the rule `resolve` in `nxgt-ory`'s\n * SDK learned. An `Authorization` header of another scheme (`Basic`) is not a\n * session credential, and does not count as one.\n */\nexport function presentedToken(\n\trequest: RequestLike,\n\tcookieName: string,\n): string | null {\n\treturn presentedCredential(request, cookieName)?.token ?? null;\n}\n\n/**\n * The same credential with where it came from: only `authorization` may carry\n * an API key.\n */\nexport function presentedCredential(\n\trequest: RequestLike,\n\tcookieName: string,\n): {\n\treadonly token: string;\n\treadonly from: 'authorization' | 'header' | 'cookie';\n} | null {\n\tconst headers = headersOf(request);\n\tconst read = (name: string): string | null => {\n\t\tif (headers instanceof Headers) return headers.get(name);\n\t\tfor (const [key, value] of Object.entries(headers)) {\n\t\t\tif (key.toLowerCase() !== name || value === undefined) continue;\n\t\t\treturn typeof value === 'string' ? value : value.join(', ');\n\t\t}\n\t\treturn null;\n\t};\n\n\tconst authorization = read('authorization');\n\tif (authorization !== null) {\n\t\tconst match = /^bearer(?:\\s+(.*))?$/i.exec(authorization.trim());\n\t\tif (match) return { token: match[1]?.trim() ?? '', from: 'authorization' };\n\t}\n\n\tconst header = read('x-session-token');\n\tif (header !== null) return { token: header.trim(), from: 'header' };\n\n\tconst cookie = read('cookie');\n\tif (cookie !== null) {\n\t\tfor (const pair of cookie.split(';')) {\n\t\t\tconst at = pair.indexOf('=');\n\t\t\tif (at !== -1 && pair.slice(0, at).trim() === cookieName) {\n\t\t\t\treturn { token: pair.slice(at + 1).trim(), from: 'cookie' };\n\t\t\t}\n\t\t}\n\t}\n\n\treturn null;\n}\n\n/**\n * The headers of whatever was passed: a `Request`, `Headers`, anything with a\n * `headers` property — Node's `IncomingMessage` — or a plain record.\n */\nfunction headersOf(request: RequestLike): Headers | HeaderRecord {\n\tif (request instanceof Headers) return request;\n\tconst inner = (request as { headers?: unknown }).headers;\n\tif (inner instanceof Headers) return inner;\n\tif (typeof inner === 'object' && inner !== null) return inner as HeaderRecord;\n\treturn request as HeaderRecord;\n}\n",
|
|
82
|
+
"/**\n * `authenticate` for an API key: the principal a key-shaped bearer presents,\n * or `null` for anonymous. Runs before any session lookup.\n */\n\nimport { timingSafeEqual } from 'node:crypto';\nimport { type AnyUser, type Context, toUser } from '../context';\nimport type { ApiKeyStore } from '../port/types';\nimport { hashSecret } from '../secrets';\nimport type { KeyAuthenticated } from '../types';\nimport { toApiKey } from './to-api-key';\nimport { parseApiKeyToken } from './token';\n\n/** Whether a token is shaped like one of this instance's keys. */\nexport function isKeyShaped(prefix: string, token: string): boolean {\n\treturn parseApiKeyToken(prefix, token) !== null;\n}\n\n/**\n * The principal a key-shaped `token` stands for, or `null` when the key is\n * unknown, wrong, revoked, lapsed, or its user is gone, inactive or of\n * another type than asked for.\n *\n * Nothing is renewed. The key's `lastUsedAt` is written at most once per\n * `lastUsedEvery`; a store outage rejects with `STORE_FAILED`, never `null`.\n */\nexport async function authenticateKey(\n\tcontext: Context,\n\tkeys: ApiKeyStore,\n\ttoken: string,\n\toptions: { readonly type?: string } | undefined,\n): Promise<KeyAuthenticated<AnyUser> | null> {\n\tconst settings = context.config.apiKeys;\n\tif (settings === null) return null;\n\tconst parsed = parseApiKeyToken(settings.prefix, token);\n\tif (parsed === null) return null;\n\n\tconst record = await keys.findApiKey(parsed.id);\n\tif (record === null) return null;\n\n\t// Compared as fixed-length digests, in constant time.\n\tconst presented = Buffer.from(hashSecret(parsed.secret), 'hex');\n\tconst stored = Buffer.from(record.secretHash, 'hex');\n\tif (\n\t\tpresented.length !== stored.length ||\n\t\t!timingSafeEqual(presented, stored)\n\t) {\n\t\treturn null;\n\t}\n\n\tconst now = context.clock.now();\n\tif (\n\t\trecord.revokedAt !== null ||\n\t\trecord.expiresAt.getTime() <= now.getTime()\n\t) {\n\t\treturn null;\n\t}\n\n\tconst user = await context.store.users.findUser(record.userId);\n\tif (\n\t\tuser === null ||\n\t\t!user.active ||\n\t\t!settings.types.has(user.type) ||\n\t\t(options?.type !== undefined && user.type !== options.type)\n\t) {\n\t\treturn null;\n\t}\n\n\t// Throttled: one write per `lastUsedEvery`, so a busy key costs no write\n\t// per request. The key stands either way.\n\t// A key used within the window is not even asked: the record in hand says so.\n\tconst staleBefore = new Date(now.getTime() - settings.lastUsedEveryMs);\n\tconst stale =\n\t\trecord.lastUsedAt === null ||\n\t\trecord.lastUsedAt.getTime() < staleBefore.getTime();\n\tconst touched =\n\t\tstale && (await keys.touchApiKey(record.id, now, staleBefore));\n\n\tconst apiKey = toApiKey(\n\t\tsettings.prefix,\n\t\ttouched ? { ...record, lastUsedAt: now } : record,\n\t);\n\treturn {\n\t\tvia: 'apiKey',\n\t\tuser: toUser(user),\n\t\tapiKey,\n\t\tscopes: apiKey.scopes,\n\t\tbound: apiKey.bound,\n\t\tsession: null,\n\t\ttoken,\n\t\trenewed: false,\n\t};\n}\n",
|
|
83
|
+
"/**\n * The shape of an API key's token: `${prefix}${id}_${secret}`, where `id` is\n * the key's UUIDv7 without its hyphens (32 hex characters) and `secret` is 32\n * random bytes, base64url (43 characters).\n *\n * The id is in the token so a request finds its key with one read, by id; the\n * secret is then compared with the hash the store holds.\n */\n\nimport { isId } from '../../ids/id';\nimport type { ApiKeyId } from '../port/types';\n\nconst HEX_ID = /^[0-9a-f]{32}$/;\nconst SECRET = /^[A-Za-z0-9_-]{43}$/;\n/** How many hex characters of the id a hint shows. */\nconst HINT_LENGTH = 6;\n\n/** The token for a key: shown to the user once. */\nexport function apiKeyToken(\n\tprefix: string,\n\tid: ApiKeyId,\n\tsecret: string,\n): string {\n\treturn `${prefix}${id.replaceAll('-', '')}_${secret}`;\n}\n\n/**\n * The id and the secret a token holds, or `null` when it is not shaped like\n * one of this instance's keys: another prefix, a wrong length, or characters\n * a token never has. A shape check only — it reads no store.\n */\nexport function parseApiKeyToken(\n\tprefix: string,\n\ttoken: string,\n): { readonly id: ApiKeyId; readonly secret: string } | null {\n\tif (typeof token !== 'string' || !token.startsWith(prefix)) return null;\n\tconst rest = token.slice(prefix.length);\n\tconst separator = rest.indexOf('_');\n\tif (separator !== 32) return null;\n\n\tconst hex = rest.slice(0, 32);\n\tconst secret = rest.slice(33);\n\tif (!HEX_ID.test(hex) || !SECRET.test(secret)) return null;\n\n\tconst id = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n\treturn isId(id) ? { id, secret } : null;\n}\n\n/** The start of the token, safe to display: `sl_0192ab…`. */\nexport function apiKeyHint(prefix: string, id: ApiKeyId): string {\n\treturn `${prefix}${id.replaceAll('-', '').slice(0, HINT_LENGTH)}…`;\n}\n",
|
|
84
|
+
"import type { ApiKeyRecord } from '../port/types';\nimport type { ApiKey } from '../types';\nimport { apiKeyHint } from './token';\n\n/**\n * A key as application code sees it: the record without its hash, with a\n * hint, and `null` for the fields a key made without them does not hold.\n */\nexport function toApiKey(prefix: string, record: ApiKeyRecord): ApiKey {\n\tconst { secretHash: _hash, scopes, bound, expiryNotifiedAt, ...key } = record;\n\treturn {\n\t\t...key,\n\t\thint: apiKeyHint(prefix, record.id),\n\t\tscopes: scopes ?? null,\n\t\tbound: bound ?? null,\n\t\texpiryNotifiedAt: expiryNotifiedAt ?? null,\n\t};\n}\n",
|
|
85
|
+
"/**\n * The standing session a request presents — one rule for `authenticate` and\n * `stepUp.confirm`, so the two never disagree on what \"signed in\" means.\n */\n\nimport type { ResolvedType } from '../config';\nimport type { Context } from '../context';\nimport type { SessionRecord, UserRecord } from '../port/types';\nimport { hashSecret } from '../secrets';\nimport type { RequestLike } from '../types';\nimport { presentedToken } from './presented-token';\n\n/**\n * A standing session, the session token that presented it, and its user —\n * `null` when the user is gone, which the caller decides what to make of.\n */\nexport interface Presented {\n\treadonly token: string;\n\treadonly session: SessionRecord;\n\treadonly user: UserRecord | null;\n}\n\n/**\n * When a session's absolute cap falls, in epoch milliseconds — `null` for a\n * type without one. Counted from the session's creation, whatever its use.\n */\nexport function absoluteEnd(\n\ttype: ResolvedType | undefined,\n\tsession: SessionRecord,\n): number | null {\n\treturn type?.absoluteMs == null\n\t\t? null\n\t\t: session.createdAt.getTime() + type.absoluteMs;\n}\n\n/** Whether `session` is past its type's absolute cap at `now`. */\nexport function pastAbsolute(\n\ttype: ResolvedType | undefined,\n\tsession: SessionRecord,\n\tnow: number,\n): boolean {\n\tconst end = absoluteEnd(type, session);\n\treturn end !== null && end <= now;\n}\n\n/**\n * Answers the session `request` presents, with its token — or `null` when\n * none stands: no token, or a session gone, revoked, lapsed or past its\n * type's absolute cap. Expiry is decided here, against the context's clock:\n * a store may still hold a session past its term.\n */\nexport async function standingSession(\n\tcontext: Context,\n\trequest: RequestLike,\n): Promise<Presented | null> {\n\tconst token = presentedToken(request, context.config.cookie.name);\n\tif (token === null) return null;\n\n\tconst session = await context.store.sessions.findSessionByTokenHash(\n\t\thashSecret(token),\n\t);\n\tconst now = context.clock.now().getTime();\n\tif (\n\t\tsession === null ||\n\t\tsession.revokedAt !== null ||\n\t\tsession.expiresAt.getTime() <= now\n\t) {\n\t\treturn null;\n\t}\n\n\tconst user = await context.store.users.findUser(session.userId);\n\tconst type = user === null ? undefined : context.config.types.get(user.type);\n\treturn pastAbsolute(type, session, now) ? null : { token, session, user };\n}\n",
|
|
86
|
+
"/**\n * `authenticate`: the user and the session a request presents, or `null` for\n * anonymous — and the renewal of a session used past its `renewAfter`.\n */\n\nimport { authenticateKey, isKeyShaped } from '../api-keys/authenticate-key';\nimport type { ResolvedType } from '../config';\nimport { type AnyUser, type Context, toUser } from '../context';\nimport type { SessionRecord } from '../port/types';\nimport type { Principal, RequestLike } from '../types';\nimport { toSession } from './open-session';\nimport { presentedCredential } from './presented-token';\nimport { absoluteEnd, standingSession } from './standing';\n\n/** Answers the user and the session `request` presents, or `null` for anonymous. */\nexport async function authenticate(\n\tcontext: Context,\n\trequest: RequestLike,\n\toptions?: { readonly type?: string; readonly apiKey?: boolean },\n): Promise<Principal<AnyUser> | null> {\n\tconst { store, clock, config } = context;\n\n\tconst settings = config.apiKeys;\n\tif (\n\t\toptions?.apiKey === true &&\n\t\t(settings === null || context.apiKeys === null)\n\t) {\n\t\tthrow new TypeError(\n\t\t\t'authenticate: apiKey: true needs janus({ apiKeys }) — no API keys are configured',\n\t\t);\n\t}\n\tif (settings !== null && context.apiKeys !== null) {\n\t\tconst presented = presentedCredential(request, config.cookie.name);\n\t\t// A key-shaped credential is a key, never a session: it is accepted\n\t\t// only where the caller asked, and only from `Authorization: Bearer` —\n\t\t// in the cookie or `X-Session-Token` it is anonymous, with the option too.\n\t\tif (presented !== null && isKeyShaped(settings.prefix, presented.token)) {\n\t\t\treturn options?.apiKey === true && presented.from === 'authorization'\n\t\t\t\t? authenticateKey(context, context.apiKeys, presented.token, options)\n\t\t\t\t: null;\n\t\t}\n\t}\n\n\t// Lapsed, revoked, or gone: anonymous.\n\tconst presented = await standingSession(context, request);\n\tif (presented === null) return null;\n\tconst { token, session, user } = presented;\n\tconst now = clock.now().getTime();\n\n\t// A user gone, inactive, or of another type than asked for is\n\t// anonymous: the session stands, and proves nothing here.\n\tif (\n\t\tuser === null ||\n\t\t!user.active ||\n\t\t(options?.type !== undefined && user.type !== options.type)\n\t) {\n\t\treturn null;\n\t}\n\n\tconst type = config.types.get(user.type);\n\tif (type === undefined || !renewalDue(type, session, now)) {\n\t\treturn {\n\t\t\tvia: 'session',\n\t\t\tuser: toUser(user),\n\t\t\tsession: toSession(session),\n\t\t\ttoken,\n\t\t\trenewed: false,\n\t\t};\n\t}\n\n\t// Renewal never goes past the absolute cap: a session already at it has\n\t// nothing to extend, and is not written again on every call.\n\tconst end = absoluteEnd(type, session);\n\tconst renewedTo = Math.min(\n\t\tnow + type.lifespanMs,\n\t\tend ?? Number.POSITIVE_INFINITY,\n\t);\n\tif (renewedTo <= session.expiresAt.getTime()) {\n\t\treturn {\n\t\t\tvia: 'session',\n\t\t\tuser: toUser(user),\n\t\t\tsession: toSession(session),\n\t\t\ttoken,\n\t\t\trenewed: false,\n\t\t};\n\t}\n\n\tconst extended = await store.sessions.extendSession(\n\t\tsession.id,\n\t\tnew Date(renewedTo),\n\t\tnew Date(now),\n\t);\n\t// Revoked between the read and the renewal: anonymous, and never\n\t// brought back.\n\tif (extended === null) return null;\n\treturn {\n\t\tvia: 'session',\n\t\tuser: toUser(user),\n\t\tsession: toSession(extended),\n\t\ttoken,\n\t\trenewed: true,\n\t};\n}\n\n/**\n * Whether a session is renewed now: once `renewAfter` has passed since it\n * was opened or last renewed — the lifespan minus what is left — so a busy\n * session is written at most once per period.\n */\nfunction renewalDue(\n\ttype: ResolvedType,\n\tsession: SessionRecord,\n\tnow: number,\n): boolean {\n\treturn (\n\t\ttype.renewAfterMs !== null &&\n\t\ttype.lifespanMs - (session.expiresAt.getTime() - now) >= type.renewAfterMs\n\t);\n}\n",
|
|
87
|
+
"/**\n * `collectExpired()`: the lapsed sessions, the lapsed one-time tokens and — with\n * `janus({ apiKeys })` — the lapsed API keys, from whichever of the stores\n * implements its collector.\n */\n\nimport { UnsupportedError } from '../../errors/janus-error';\nimport type { Context } from '../context';\n\n/**\n * Deletes what has lapsed at `clock.now()` and answers how many in all.\n *\n * Sessions first, then tokens, then API keys, one after the other: every\n * deletion is idempotent, so a failure after an earlier one went leaves a call\n * that can simply be repeated. `UNSUPPORTED` only when no store has a collector.\n */\nexport async function collectExpired(context: Context): Promise<number> {\n\tconst { store, clock, capabilities } = context;\n\tconst sessions = capabilities.collectExpired\n\t\t? store.sessions.deleteExpiredSessions\n\t\t: undefined;\n\tconst tokens = capabilities.collectExpiredTokens\n\t\t? store.tokens.deleteExpiredTokens\n\t\t: undefined;\n\n\tconst apiKeys = context.apiKeys?.deleteExpiredApiKeys?.bind(context.apiKeys);\n\n\tif (sessions === undefined && tokens === undefined && apiKeys === undefined) {\n\t\tthrow new UnsupportedError(\n\t\t\t'collectExpired: store.sessions does not implement deleteExpiredSessions, nor store.tokens deleteExpiredTokens — their stores expire records on their own, or implement the methods',\n\t\t\t{ slot: 'sessions', operation: 'deleteExpiredSessions' },\n\t\t);\n\t}\n\n\tconst before = clock.now();\n\tconst collected = sessions === undefined ? 0 : await sessions(before);\n\tconst collectedTokens = tokens === undefined ? 0 : await tokens(before);\n\tconst collectedKeys = apiKeys === undefined ? 0 : await apiKeys(before);\n\treturn collected + collectedTokens + collectedKeys;\n}\n",
|
|
88
|
+
"/**\n * The session cookie: its name, and the `Set-Cookie` values that set and\n * clear it, under the attributes the configuration resolved.\n */\n\nimport type { AnyUser, Context } from '../context';\nimport type { Session, SharedApi } from '../types';\n\n/** The session cookie's name, and how to set it for a session and clear it. */\nexport function cookieOf(context: Context): SharedApi<AnyUser>['cookie'] {\n\tconst { name, domain, path, sameSite, secure } = context.config.cookie;\n\tconst attributes = [\n\t\t`Path=${path}`,\n\t\t...(domain === null ? [] : [`Domain=${domain}`]),\n\t\t'HttpOnly',\n\t\t`SameSite=${sameSite[0]?.toUpperCase()}${sameSite.slice(1)}`,\n\t\t...(secure ? ['Secure'] : []),\n\t].join('; ');\n\n\treturn {\n\t\tname,\n\t\tserialize: (token: string, session: Session) =>\n\t\t\t`${name}=${token}; Expires=${session.expiresAt.toUTCString()}; ${attributes}`,\n\t\tclear: () =>\n\t\t\t`${name}=; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; ${attributes}`,\n\t};\n}\n",
|
|
89
|
+
"/**\n * What `janus()` answers whatever its user types: authenticating a request,\n * signing out, finding a user by id, the cookie, and collecting expired\n * sessions and one-time tokens.\n */\n\nimport { UnsupportedError } from '../../errors/janus-error';\nimport { isId } from '../../ids/id';\nimport {\n\ttype AnyUser,\n\ttype Context,\n\tfindRecord,\n\tgetRecord,\n\tidOf,\n\ttoUser,\n} from '../context';\nimport { hashSecret } from '../secrets';\nimport type { Principal, RequestLike, SharedApi } from '../types';\nimport { authenticate } from './authenticate';\nimport { collectExpired } from './collect-expired';\nimport { cookieOf } from './cookie';\nimport { toSession } from './open-session';\nimport { presentedToken } from './presented-token';\n\n/** `SharedApi`, degenericised: `janus()` casts it to the typed form once. */\nexport type InternalSharedApi = Omit<SharedApi<AnyUser>, 'authenticate'> & {\n\tauthenticate(\n\t\trequest: RequestLike,\n\t\toptions?: { readonly type?: string; readonly apiKey?: boolean },\n\t): Promise<Principal<AnyUser> | null>;\n};\n\n/** `auth.sessions`: one user's standing sessions, listed and revoked one by one. */\nfunction sessionsApi(context: Context): InternalSharedApi['sessions'] {\n\tconst { store, clock } = context;\n\n\tconst standing = async (user: Parameters<typeof idOf>[0], where: string) => {\n\t\tconst id = idOf(user);\n\t\tconst list = store.sessions.listUserSessions;\n\t\tif (list === undefined) {\n\t\t\tthrow new UnsupportedError(\n\t\t\t\t`${where}: store.sessions does not implement listUserSessions`,\n\t\t\t\t{ slot: 'sessions', operation: 'listUserSessions' },\n\t\t\t);\n\t\t}\n\t\tif (!isId(id)) return [];\n\t\treturn list.call(store.sessions, id, clock.now());\n\t};\n\n\treturn {\n\t\tasync list(user) {\n\t\t\tconst found = await standing(user, 'sessions.list');\n\t\t\treturn found\n\t\t\t\t.map(toSession)\n\t\t\t\t.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());\n\t\t},\n\n\t\tasync revoke(user, sessionId) {\n\t\t\tconst found = await standing(user, 'sessions.revoke');\n\t\t\tif (!found.some((session) => session.id === sessionId)) return false;\n\t\t\treturn store.sessions.revokeSession(sessionId, clock.now());\n\t\t},\n\t};\n}\n\n/** Everything `janus()` answers whatever its user types. */\nexport function sharedApi(context: Context): InternalSharedApi {\n\tconst { store, clock, config } = context;\n\n\treturn {\n\t\tasync authenticate(request, options) {\n\t\t\treturn authenticate(context, request, options);\n\t\t},\n\n\t\tasync signOut(request) {\n\t\t\tconst token = presentedToken(request, config.cookie.name);\n\t\t\tif (token === null) return false;\n\n\t\t\tconst session = await store.sessions.findSessionByTokenHash(\n\t\t\t\thashSecret(token),\n\t\t\t);\n\t\t\tif (session === null) return false;\n\t\t\treturn store.sessions.revokeSession(session.id, clock.now());\n\t\t},\n\n\t\tasync signOutEverywhere(user, options) {\n\t\t\tconst id = idOf(user);\n\t\t\tif (!isId(id)) return 0;\n\t\t\t// An `except` that is no id this package minted names no session:\n\t\t\t// every session goes, as it would for an unknown one.\n\t\t\tconst except =\n\t\t\t\toptions?.except !== undefined && isId(options.except)\n\t\t\t\t\t? options.except\n\t\t\t\t\t: undefined;\n\t\t\tconst issuedBefore = options?.issuedBefore;\n\t\t\t// A date that is none has no cut-off: the stores would disagree on what\n\t\t\t// it means, so refuse it rather than guess.\n\t\t\tif (\n\t\t\t\tissuedBefore !== undefined &&\n\t\t\t\t(!(issuedBefore instanceof Date) ||\n\t\t\t\t\tNumber.isNaN(issuedBefore.getTime()))\n\t\t\t) {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t'signOutEverywhere: issuedBefore is not a valid Date',\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn issuedBefore === undefined\n\t\t\t\t? except === undefined\n\t\t\t\t\t? store.sessions.revokeUserSessions(id, clock.now())\n\t\t\t\t\t: store.sessions.revokeUserSessions(id, clock.now(), except)\n\t\t\t\t: store.sessions.revokeUserSessions(\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tclock.now(),\n\t\t\t\t\t\texcept,\n\t\t\t\t\t\tissuedBefore,\n\t\t\t\t\t);\n\t\t},\n\n\t\tsessions: sessionsApi(context),\n\n\t\tasync findUser(id) {\n\t\t\tconst record = await findRecord(context, id, null);\n\t\t\treturn record === null ? null : toUser(record);\n\t\t},\n\n\t\tasync getUser(id) {\n\t\t\treturn toUser(await getRecord(context, id, null, 'getUser'));\n\t\t},\n\n\t\tcookie: cookieOf(context),\n\n\t\tasync collectExpired() {\n\t\t\treturn collectExpired(context);\n\t\t},\n\n\t\ttypes: [...config.types.keys()],\n\t};\n}\n",
|
|
90
|
+
"/**\n * The RFC 8176 authentication methods a session records (`SessionRecord.amr`),\n * and the one place that says which sign-in or step-up proves which.\n *\n * | Proof | `amr` |\n * | --- | --- |\n * | password | `pwd` |\n * | e-mailed code, magic link | `otp` |\n * | passkey (user verified) | `hwk`, `user` |\n * | app code (TOTP) as a second factor or step-up | `otp`, `mfa` |\n * | recovery code as a second factor | `otp`, `mfa` |\n * | passkey as a second factor or step-up | `hwk`, `user`, `mfa` |\n * | social provider | `fed` |\n * | `signInProven` (the application's own proof) | none |\n *\n * A second factor adds its methods to the first factor's, plus `mfa`.\n */\n\nimport type { Session } from '../types/session';\n\n/** The methods each proof records. */\nexport const AMR = {\n\tpassword: ['pwd'],\n\toneTimeCode: ['otp'],\n\tpasskey: ['hwk', 'user'],\n\tappCode: ['otp', 'mfa'],\n\trecoveryCode: ['otp', 'mfa'],\n\tpasskeySecondFactor: ['hwk', 'user', 'mfa'],\n\tsocial: ['fed'],\n} as const satisfies Record<string, readonly string[]>;\n\n/** `a` then `b`, each value once. */\nexport function mergeAmr(\n\ta: readonly string[] | undefined,\n\tb: readonly string[],\n): string[] {\n\treturn [...new Set([...(a ?? []), ...b])];\n}\n\n/**\n * Whether a session proved more than one factor: `mfa` was recorded, or a\n * user-verified passkey (`hwk` with `user`) was.\n */\nexport function isMultiFactor(session: Pick<Session, 'amr'>): boolean {\n\tconst { amr } = session;\n\treturn amr.includes('mfa') || (amr.includes('hwk') && amr.includes('user'));\n}\n",
|
|
91
|
+
"/**\n * The passwords tried at one login, counted by the store per window —\n * `janus({ signIn: { throttle } })`, ten per fifteen minutes by default.\n * Past the last one, `signIn` answers `CREDENTIALS_INVALID` with\n * `retryAfter`, the right password included, until the window ends. **Nothing\n * locks** past a window — but somebody who keeps trying a login keeps its\n * password sign-in shut, window after window: a per-client limit is the\n * application's, and a sign-in code still opens the account.\n *\n * `changePassword` counts in the same budget: each call is one more\n * password tried at the user's login, counted before `current` is compared\n * (a user with no password too) and refused past the limit alike, and a\n * change that is written restarts the count. Wrong guesses of both add up.\n *\n * Counted per login, **known or not**: an unknown login is counted as a\n * registered one is, so the throttle does not tell them apart. Counted\n * before anything is looked up or compared, so of twenty guesses at once,\n * exactly as many as the limit are compared.\n *\n * Counted in an attempt window (`one-time/window.ts`), in `secondFactor`\n * tokens stored under no user: the `userId` of each is a keyed hash of the\n * login, never the login (`counter-key.ts`). A sign-in that opens a session\n * spends the link it counts on, and the login's count **restarts** from\n * zero.\n *\n * A store that cannot count throws `STORE_FAILED`: never a refusal, and\n * never a sign-in let through uncounted.\n */\n\nimport { CredentialError, StoreFailure } from '../errors/janus-error';\nimport type { ResolvedType } from './config';\nimport type { Context } from './context';\nimport { counterKey, keyed } from './counter-key';\nimport { type CountedAttempt, countInWindow } from './one-time';\nimport type { UserRecord } from './port/types';\nimport { hashSecret } from './secrets';\n\n/** What the key is derived for. Renamed, every count in progress would start over. */\nconst PURPOSE = 'janus/sign-in/attempts/v1';\n\n/** One attempt counted at `login`, already normalised, or `null` with the throttle off. */\nasync function countLogin(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tlogin: string,\n\twhere: string,\n): Promise<CountedAttempt | null> {\n\tconst throttle = context.config.signInThrottle;\n\tif (throttle === null) return null;\n\tconst key = counterKey(context, PURPOSE);\n\tconst loginKey = keyed(key, [type.name, login]);\n\treturn countInWindow(context, {\n\t\twindowMs: throttle.windowMs,\n\t\tspent: 'restart',\n\t\tuserId: loginKey,\n\t\tlinkHash: (window, link) =>\n\t\t\thashSecret(keyed(key, [loginKey, String(window), String(link)])),\n\t\t// A store that lost what it just stored cannot count: an outage.\n\t\tvanished: () =>\n\t\t\tnew StoreFailure(\n\t\t\t\t`${where}: the store dropped the attempts it had just stored`,\n\t\t\t\t{ slot: 'tokens', operation: 'countAttempt' },\n\t\t\t),\n\t});\n}\n\n/**\n * Counts one password tried at `login` — already normalised — before it is\n * looked up, and refuses past the last one: the right password included.\n */\nexport async function countSignInAttempt(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tlogin: string,\n\twhere: string,\n): Promise<void> {\n\tconst counted = await countLogin(context, type, login, where);\n\tconst limit = context.config.signInThrottle?.attempts;\n\tif (counted === null || limit === undefined || counted.attempts <= limit) {\n\t\treturn;\n\t}\n\tconst now = context.clock.now().getTime();\n\tthrow new CredentialError(\n\t\t'CREDENTIALS_INVALID',\n\t\t`${where}: too many passwords tried at this login — wait for the next window`,\n\t\t{\n\t\t\treason: 'throttled',\n\t\t\tuserType: type.name,\n\t\t\tretryAfter: Math.max(1, Math.ceil((counted.endsAt - now) / 1000)),\n\t\t},\n\t);\n}\n\n/**\n * Starts the user's count again, once a sign-in opens a session: after the\n * password alone, or after the second factor's code — never after the\n * password of a user whose second factor is still to come, so knowing the\n * password buys no more challenges. It counts one attempt on the current\n * link, and spends it: the next one counts from zero.\n */\nexport async function restartSignInCount(\n\tcontext: Context,\n\ttype: ResolvedType,\n\trecord: UserRecord,\n\twhere: string,\n): Promise<void> {\n\tconst rule = type.password;\n\tconst login = rule === null ? undefined : record.fields[rule.login];\n\tif (rule === null || typeof login !== 'string') return;\n\tconst counted = await countLogin(context, type, rule.normalize(login), where);\n\tif (counted?.link == null) return;\n\tawait context.store.tokens.consumeToken(\n\t\tcounted.link,\n\t\t'secondFactor',\n\t\tcontext.clock.now(),\n\t);\n}\n",
|
|
92
|
+
"import { isStorable } from '../../stores/storable';\nimport type { ResolvedType } from '../config';\nimport type { Context } from '../context';\nimport type { UserRecord } from '../port/types';\n\n/**\n * The user holding this normalised login, or `null`. A login no store can\n * keep is nobody's: answered as an absence, without asking a store that\n * would fail on it.\n */\nexport const byLogin = async (\n\tcontext: Context,\n\ttype: ResolvedType,\n\tlogin: string,\n): Promise<UserRecord | null> =>\n\tisStorable(login)\n\t\t? context.store.users.findUserByLogin(type.name, login)\n\t\t: null;\n",
|
|
93
|
+
"import {\n\tCredentialError,\n\ttype CredentialRefusal,\n\tEmailUnverifiedError,\n\tUserInactiveError,\n} from '../../errors/janus-error';\nimport type { ResolvedType } from '../config';\nimport {\n\ttype AnyUser,\n\ttype Context,\n\temailOf,\n\tpasswordMatches,\n\tpasswordRule,\n\trehashed,\n\trequireHasher,\n} from '../context';\nimport { type DeviceHint, reportNewDevice } from '../devices';\nimport { heldByPassword } from '../password-written';\nimport type { UserRecord } from '../port/types';\nimport { isActive } from '../second-factor/factor';\nimport { AMR } from '../sessions/amr';\nimport { countSignInAttempt, restartSignInCount } from '../sign-in-attempts';\nimport type { SignInResult } from '../types';\nimport { byLogin } from './by-login';\nimport type { Finish, Input } from './flow-types';\n\n/**\n * Checks the password and answers what `finish` answers for the user. One\n * refusal for an unknown login, no password, a wrong one and a login past\n * its attempts; `USER_INACTIVE` only once the password matched.\n */\nexport async function signIn(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tfinish: Finish,\n\tinput: Input,\n\tcall: { readonly where: string; readonly device: DeviceHint },\n): Promise<SignInResult<AnyUser>> {\n\tconst { where, device } = call;\n\tconst rule = passwordRule(type, where);\n\tconst hasher = requireHasher(context, where);\n\tconst login = input?.[rule.login];\n\tconst password = input?.['password'];\n\n\tconst normalized = typeof login === 'string' ? rule.normalize(login) : null;\n\t// Counted before the login is looked up, so the count says nothing of\n\t// whether it is registered.\n\tif (normalized !== null) {\n\t\tawait countSignInAttempt(context, type, normalized, where);\n\t}\n\tconst record =\n\t\tnormalized === null ? null : await byLogin(context, type, normalized);\n\tconst refuse = (reason: CredentialRefusal) =>\n\t\tnew CredentialError(\n\t\t\t'CREDENTIALS_INVALID',\n\t\t\t`${where}: the login and the password do not match`,\n\t\t\t{ reason, userType: type.name },\n\t\t);\n\n\tif (record === null || record.password === null) {\n\t\t// Compared all the same, so the response time does not say which\n\t\t// logins are registered. The store's own latency stays observable;\n\t\t// that limit is documented, not denied.\n\t\tawait hasher.verify(String(password), await context.dummyHash());\n\t\tthrow refuse(record === null ? 'unknownLogin' : 'noPassword');\n\t}\n\n\tif (!(await passwordMatches(context, record, String(password), where))) {\n\t\tthrow refuse('wrongPassword');\n\t}\n\t// Checked after the password, so only somebody who knows it is told.\n\trefuseAfterPassword(type, record, where);\n\n\t// A session opens: the login's count starts again. With a second factor\n\t// to come, only its code starts it — the password alone buys no more\n\t// challenges.\n\tif (!isActive(record.secondFactor)) {\n\t\tawait restartSignInCount(context, type, record, where);\n\t}\n\tconst verified = await rehashed(context, record, String(password));\n\tconst result = await finish(verified, where, device, AMR.password);\n\t// A password written while this sign-in ran ends it: the password\n\t// verified above is no longer the user's.\n\tif (\n\t\t!(await heldByPassword(\n\t\t\tcontext,\n\t\t\ttype,\n\t\t\tverified,\n\t\t\tString(password),\n\t\t\tresult,\n\t\t\twhere,\n\t\t))\n\t) {\n\t\tthrow refuse('wrongPassword');\n\t}\n\t// Complete only now: a sign-in refused above reports no new device.\n\tawait reportNewDevice(context, result);\n\treturn result;\n}\n\n/**\n * What is refused only once the password matched, so only somebody who\n * knows it is told: an inactive account (`USER_INACTIVE`) and, with\n * `password.requireVerifiedEmail`, an address never verified\n * (`EMAIL_UNVERIFIED`). Either way no session opens. A passkey sign-in\n * (`passkeys.signIn`) refuses the same two once its assertion verified.\n */\nexport function refuseAfterPassword(\n\ttype: ResolvedType,\n\trecord: UserRecord,\n\twhere: string,\n): void {\n\tif (!record.active) {\n\t\tthrow new UserInactiveError(`${where}: the user is inactive`, {\n\t\t\tuserId: record.id,\n\t\t\tuserType: type.name,\n\t\t});\n\t}\n\tif (type.password?.requireVerifiedEmail !== true) return;\n\tif (emailOf(type, record.fields) === null) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: password.requireVerifiedEmail needs an e-mail on the ${type.name} type — its schema has no required string \"${type.email}\" field`,\n\t\t);\n\t}\n\tif (record.emailVerifiedAt === null) {\n\t\tthrow new EmailUnverifiedError(`${where}: the e-mail is not verified`, {\n\t\t\tuserId: record.id,\n\t\t\tuserType: type.name,\n\t\t});\n\t}\n}\n",
|
|
94
|
+
"/**\n * The WebAuthn challenge of a sign-in or a step-up: **an HMAC of the token's\n * secret, and stored nowhere**. The visitor holds the secret (`challenge`)\n * and the page holds the options made from the HMAC; `confirmPasskey` derives\n * it again from the secret it is given. A key derived per purpose\n * (`../derived-keys.ts`), so the challenge of a sign-in is never the one of\n * a step-up, and the browser — which sees only the HMAC — learns nothing of\n * the secret.\n *\n * The key is the sealing keys' first: a rotation between the options and the\n * assertion (the challenge lives five minutes) refuses that assertion, and\n * the user asks again.\n */\n\nimport { derivedKey, keyedHash } from '../derived-keys';\nimport type { Sealer } from '../sealing';\n\n/** What the challenge is for. Each purpose has a key of its own. */\nexport type AssertionPurpose = 'secondFactor' | 'stepUp';\n\n/**\n * Named after what each protects, and kept: renamed, every challenge in\n * progress would stop matching.\n */\nconst PURPOSES: Readonly<Record<AssertionPurpose, string>> = {\n\tsecondFactor: 'janus/passkeys/second-factor-challenge/v1',\n\tstepUp: 'janus/passkeys/step-up-challenge/v1',\n};\n\n/** The WebAuthn challenge (base64url) for the token whose secret is `secret`. */\nexport function assertionChallenge(\n\tsealer: Sealer,\n\tpurpose: AssertionPurpose,\n\tsecret: string,\n): string {\n\t// The first key is always held: resolveSealer names it from the keys.\n\tconst key = derivedKey(sealer, PURPOSES[purpose]) as Buffer;\n\treturn keyedHash(key, [secret]).toString('base64url');\n}\n",
|
|
95
|
+
"/**\n * The check a passkey sign-in and a passkey step-up share: the credential is\n * the user's, the verifier accepts the assertion for the challenge derived\n * from the token's secret, the counter did not go backwards — and the use is\n * recorded.\n */\n\nimport type { Context } from '../context';\nimport { emit } from '../events';\nimport type { PasskeyRecord, UserRecord } from '../port/types';\nimport { requireSettings } from '../second-factor/factor';\nimport { type AssertionPurpose, assertionChallenge } from './challenge';\nimport { requirePasskeys } from './wiring';\n\n/**\n * Whether the counter went backwards. A stored or a received `0` is an\n * authenticator without a counter, never a regression.\n */\nexport function regressed(stored: number, received: number): boolean {\n\treturn received !== 0 && stored !== 0 && received <= stored;\n}\n\n/** The credential id a browser's JSON names, or `null` when it names none. */\nexport function credentialIdOf(assertion: unknown): string | null {\n\tconst id = (assertion as { id?: unknown } | null | undefined)?.id;\n\treturn typeof id === 'string' && id !== '' ? id : null;\n}\n\n/**\n * Checks `assertion` for `user` against the challenge derived from `secret`.\n * `true` when it verified and its use is recorded (counter, `backedUp` and\n * `lastUsedAt`); `false` for everything a visitor can cause — a response of\n * the wrong shape, a credential that is not the user's, a response that does\n * not verify, a counter that went backwards (which also emits\n * `user.passkeyCloneSuspected`, the passkey staying active) and a use another\n * call recorded first. The caller answers `false` as a code that does not\n * match; only an unexpected failure throws.\n */\nexport async function acceptAssertion(\n\tcontext: Context,\n\tuser: UserRecord,\n\tgiven: {\n\t\treadonly assertion: unknown;\n\t\treadonly purpose: AssertionPurpose;\n\t\treadonly secret: string;\n\t},\n\twhere: string,\n): Promise<boolean> {\n\tconst { store } = requirePasskeys(context, where);\n\tconst sealer = requireSettings(\n\t\tcontext,\n\t\twhere,\n\t\t'a passkey is being confirmed',\n\t).sealer;\n\tconst id = credentialIdOf(given.assertion);\n\tif (id === null) return false;\n\tconst held = await store.findPasskey(id);\n\tif (held === null || held.userId !== user.id) return false;\n\n\treturn checkAssertion(\n\t\tcontext,\n\t\tuser,\n\t\theld,\n\t\t{\n\t\t\tassertion: given.assertion,\n\t\t\texpectedChallenge: assertionChallenge(\n\t\t\t\tsealer,\n\t\t\t\tgiven.purpose,\n\t\t\t\tgiven.secret,\n\t\t\t),\n\t\t\trequireUserVerified: false,\n\t\t},\n\t\twhere,\n\t);\n}\n\n/**\n * The checks every passkey use shares once the stored credential is known:\n * the verifier accepts `assertion` for `expectedChallenge`, user verification\n * holds where it is required, the counter did not go backwards, and the use\n * is recorded — conditionally on the counter read. `false` for everything a\n * visitor can cause; a clone suspicion also emits\n * `user.passkeyCloneSuspected`, the passkey staying active.\n *\n * `requireUserVerified` asks the authenticator's user verification whatever\n * `passkeys.userVerification` says: a passkey that is the only factor must\n * have verified the user.\n */\nexport async function checkAssertion(\n\tcontext: Context,\n\tuser: UserRecord,\n\theld: PasskeyRecord,\n\tgiven: {\n\t\treadonly assertion: unknown;\n\t\treadonly expectedChallenge: string;\n\t\treadonly requireUserVerified: boolean;\n\t\t/** Called after the assertion verified and before its use is recorded. */\n\t\treadonly beforeRecord?: () => Promise<void>;\n\t},\n\twhere: string,\n): Promise<boolean> {\n\tconst { settings, store } = requirePasskeys(context, where);\n\tconst suspected = () =>\n\t\temit(context, 'user.passkeyCloneSuspected', user, context.clock.now(), {\n\t\t\tpasskey: { credentialId: held.credentialId, name: held.name },\n\t\t});\n\tconst rp = given.requireUserVerified\n\t\t? { ...settings.rp, userVerification: 'required' as const }\n\t\t: settings.rp;\n\tconst verified = await settings.verifier.verifyAuthentication({\n\t\trp,\n\t\tresponse: given.assertion,\n\t\texpectedChallenge: given.expectedChallenge,\n\t\tcredential: held,\n\t});\n\tif (!verified.ok) {\n\t\tif (verified.reason === 'counterRegression') await suspected();\n\t\treturn false;\n\t}\n\tif (verified.credentialId !== held.credentialId) return false;\n\t// The verifier is the application's to replace: `required` is held here too.\n\tif (rp.userVerification === 'required' && !verified.userVerified) {\n\t\treturn false;\n\t}\n\t// The verifier is the application's to replace: the rule is held here too.\n\tif (regressed(held.counter, verified.counter)) {\n\t\tawait suspected();\n\t\treturn false;\n\t}\n\tawait given.beforeRecord?.();\n\n\tconst recorded = await store.recordPasskeyUse(\n\t\tuser.id,\n\t\theld.credentialId,\n\t\t{\n\t\t\t// A received 0 after a counted history never lowers the stored one.\n\t\t\tcounter: Math.max(held.counter, verified.counter),\n\t\t\tbackedUp: verified.backedUp,\n\t\t\tlastUsedAt: context.clock.now(),\n\t\t},\n\t\theld.counter,\n\t);\n\treturn recorded !== null;\n}\n",
|
|
96
|
+
"/** `passkeys.signInOptions`: the challenge and options of a passwordless sign-in. */\n\nimport { mintId } from '../../ids/id';\nimport type { Context } from '../context';\nimport { issueOneTime } from '../one-time';\nimport type { PasskeySignInChallenge } from '../types';\nimport { requireFirstFactor } from './wiring';\n\n/**\n * What marks a `passkeyRegistration` token as a sign-in's challenge. Its\n * owner is an id minted for the call, since nobody is known yet: a\n * registration, which compares the owner with the session's user, never\n * accepts it, and `passkeys.signIn` never accepts a registration's.\n */\nexport const SIGN_IN_ADDRESS = 'passkeySignIn';\n\nexport async function signInOptions(\n\tcontext: Context,\n\twhere: string,\n): Promise<PasskeySignInChallenge> {\n\tconst { settings } = requireFirstFactor(context, where);\n\tconst { secret, expiresAt } = await issueOneTime(context, {\n\t\tkind: 'passkeyRegistration',\n\t\tuserId: mintId(context.clock.now().getTime()),\n\t\taddress: SIGN_IN_ADDRESS,\n\t\tttlMs: context.config.tokenTtlMs.passkeyRegistration,\n\t});\n\tconst options = await settings.verifier.authenticationOptions({\n\t\t// The only factor must verify the user: the browser is told so.\n\t\trp: { ...settings.rp, userVerification: 'required' },\n\t\tchallenge: secret,\n\t\tallow: [],\n\t});\n\treturn { options, challenge: secret, expiresAt };\n}\n",
|
|
97
|
+
"/** `passkeys.signIn`: a session from a passkey alone. */\n\nimport { CredentialError } from '../../errors/janus-error';\nimport type { ResolvedType } from '../config';\nimport { type AnyUser, type Context, findRecord } from '../context';\nimport { deviceHint, reportNewDevice } from '../devices';\nimport { spendOneTime, unknownOneTime } from '../one-time';\nimport { openSession } from '../sessions';\nimport { AMR } from '../sessions/amr';\nimport type { SignedIn, SignInOptions } from '../types';\nimport { refuseAfterPassword } from '../users/sign-in';\nimport { checkAssertion, credentialIdOf } from './assert';\nimport { SIGN_IN_ADDRESS } from './sign-in-options';\nimport { requireFirstFactor } from './wiring';\n\n/**\n * The challenge is spent first, once: a failed attempt costs the visitor a new\n * `signInOptions`, and nothing a visitor sends is guessable. Then the passkey\n * names the user — the store is the scope, so a credential of another store\n * is unknown here — and the assertion is checked with user verification\n * required. The user's state is refused only once the assertion verified, so\n * only a holder is told, and before the use is recorded.\n *\n * No TOTP code is asked: a verified passkey is the whole proof, whether or\n * not the user holds a TOTP.\n */\nexport async function signInWithPasskey(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tgiven: {\n\t\treadonly challenge: unknown;\n\t\treadonly response: unknown;\n\t\treadonly options: SignInOptions | undefined;\n\t},\n\twhere: string,\n): Promise<SignedIn<AnyUser>> {\n\t// Before anything is spent: a wiring mistake costs the visitor nothing.\n\tconst { store } = requireFirstFactor(context, where);\n\tconst device = deviceHint(context, given.options, where);\n\tconst challenge = given.challenge;\n\tif (typeof challenge !== 'string' || challenge === '') {\n\t\tthrow unknownOneTime(where, 'challenge');\n\t}\n\tconst token = await spendOneTime(\n\t\tcontext,\n\t\tchallenge,\n\t\t'passkeyRegistration',\n\t\twhere,\n\t\t'challenge',\n\t);\n\t// A registration's challenge is no sign-in's.\n\tif (token.address !== SIGN_IN_ADDRESS)\n\t\tthrow unknownOneTime(where, 'challenge');\n\n\tconst refuse = () =>\n\t\tnew CredentialError(\n\t\t\t'CREDENTIALS_INVALID',\n\t\t\t`${where}: the passkey was not accepted`,\n\t\t\t{ reason: 'passkey', userType: type.name },\n\t\t);\n\tconst id = credentialIdOf(given.response);\n\tif (id === null) throw refuse();\n\tconst held = await store.findPasskey(id);\n\tif (held === null) throw refuse();\n\tconst record = await findRecord(context, held.userId, type.name);\n\tif (record === null) throw refuse();\n\t// A discoverable credential carries the user handle it was made for.\n\tconst handle = userHandleOf(given.response);\n\t// With nobody named before the ceremony, WebAuthn requires the handle.\n\tif (\n\t\thandle === null ||\n\t\thandle !== Buffer.from(record.id, 'utf8').toString('base64url')\n\t) {\n\t\tthrow refuse();\n\t}\n\n\tconst accepted = await checkAssertion(\n\t\tcontext,\n\t\trecord,\n\t\theld,\n\t\t{\n\t\t\tassertion: given.response,\n\t\t\texpectedChallenge: challenge,\n\t\t\trequireUserVerified: true,\n\t\t\tbeforeRecord: async () => refuseAfterPassword(type, record, where),\n\t\t},\n\t\twhere,\n\t);\n\tif (!accepted) throw refuse();\n\n\tconst signedIn = await openSession(\n\t\tcontext,\n\t\ttype,\n\t\trecord,\n\t\tdevice,\n\t\tfalse,\n\t\tAMR.passkey,\n\t);\n\tawait reportNewDevice(context, signedIn);\n\treturn signedIn;\n}\n\n/** The user handle a browser's assertion carries, or `null` when it has none. */\nfunction userHandleOf(response: unknown): string | null {\n\tconst handle = (\n\t\tresponse as { response?: { userHandle?: unknown } } | null | undefined\n\t)?.response?.userHandle;\n\treturn typeof handle === 'string' && handle !== '' ? handle : null;\n}\n",
|
|
98
|
+
"import type { At } from '../at';\nimport type { ResolvedType } from '../config';\nimport type { AnyUser, Context } from '../context';\nimport type { PasskeyFirstFactorApi, PasskeysApi } from '../types';\nimport { listPasskeys, removePasskey, renamePasskey } from './manage';\nimport { registerPasskey } from './register';\nimport { registrationOptions } from './registration-options';\nimport { signInWithPasskey } from './sign-in';\nimport { signInOptions } from './sign-in-options';\n\n/**\n * The passkeys of one user type: the flows its API answers. Each step is a\n * module of its own — `./registration-options`, `./register`, `./manage`, and for a first\n * factor `./sign-in-options` and `./sign-in`.\n * Built for every type; each call refuses with a `TypeError` when `janus()`\n * was given no `passkeys`.\n */\nexport function passkeyFlows(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tat: At,\n): (PasskeysApi<AnyUser> & PasskeyFirstFactorApi<AnyUser>)['passkeys'] {\n\treturn {\n\t\tregistrationOptions: (user) =>\n\t\t\tregistrationOptions(\n\t\t\t\tcontext,\n\t\t\t\ttype,\n\t\t\t\tuser,\n\t\t\t\tat('passkeys.registrationOptions'),\n\t\t\t),\n\t\tregister: (current, input) =>\n\t\t\tregisterPasskey(context, type, current, input, at('passkeys.register')),\n\t\tlist: (user) => listPasskeys(context, type, user, at('passkeys.list')),\n\t\trename: (user, credentialId, name) =>\n\t\t\trenamePasskey(\n\t\t\t\tcontext,\n\t\t\t\ttype,\n\t\t\t\tuser,\n\t\t\t\tcredentialId,\n\t\t\t\tname,\n\t\t\t\tat('passkeys.rename'),\n\t\t\t),\n\t\tremove: (current, credentialId) =>\n\t\t\tremovePasskey(\n\t\t\t\tcontext,\n\t\t\t\ttype,\n\t\t\t\tcurrent,\n\t\t\t\tcredentialId,\n\t\t\t\tat('passkeys.remove'),\n\t\t\t),\n\t\tsignInOptions: () => signInOptions(context, at('passkeys.signInOptions')),\n\t\tsignIn: (challenge, response, options) =>\n\t\t\tsignInWithPasskey(\n\t\t\t\tcontext,\n\t\t\t\ttype,\n\t\t\t\t{ challenge, response, options },\n\t\t\t\tat('passkeys.signIn'),\n\t\t\t),\n\t};\n}\n",
|
|
99
|
+
"import type { ApiKeyStore } from './types';\n\n/** The methods an API key store must answer, in the order the port declares them. */\nconst REQUIRED = [\n\t'insertApiKey',\n\t'findApiKey',\n\t'listUserApiKeys',\n\t'touchApiKey',\n\t'revokeApiKey',\n\t'revokeUserApiKeys',\n\t'deleteUserApiKeys',\n] as const;\n\n/** What `assertApiKeyStore` found beyond the required methods. */\nexport interface ApiKeyStoreCapabilities {\n\t/** Whether `deleteExpiredApiKeys` is implemented. */\n\treadonly collectExpired: boolean;\n\t/** Whether `listBoundApiKeys` and `revokeBoundApiKeys` are: the store keeps `scopes` and `bound`. */\n\treadonly bound: boolean;\n\t/** Whether `listUserBoundApiKeys` is; it needs `bound`. */\n\treadonly userBound: boolean;\n\t/** Whether `listExpiringApiKeys` and `markApiKeyExpiryNotified` are. */\n\treadonly expiryNotice: boolean;\n}\n\n/** The optional methods that come in pairs: one without the other is a store half written. */\nconst PAIRS = {\n\tbound: ['listBoundApiKeys', 'revokeBoundApiKeys'],\n\texpiryNotice: ['listExpiringApiKeys', 'markApiKeyExpiryNotified'],\n} as const;\n\n/**\n * Checks that a store answers every method of the {@link ApiKeyStore} port,\n * and reports its optional capability. The net for a JavaScript caller, as\n * `assertStores` is for the three identity stores; a bare `TypeError`, since a\n * missing method can only come from how the application was wired.\n *\n * `where` names the call the consumer wrote, so the sentence says what to fix.\n */\nexport function assertApiKeyStore(\n\tstore: unknown,\n\twhere: string,\n): ApiKeyStoreCapabilities {\n\tif (typeof store !== 'object' || store === null) {\n\t\tthrow new TypeError(`${where}: the API key store must be an object`);\n\t}\n\n\tconst methods = store as Record<string, unknown>;\n\tfor (const method of REQUIRED) {\n\t\tif (typeof methods[method] !== 'function') {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${where}: the API key store has no method ${method}, which the port requires`,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst has = (method: string): boolean => {\n\t\tconst found = methods[method];\n\t\tif (found !== undefined && typeof found !== 'function') {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${where}: the API key store's ${method} must be a function or absent`,\n\t\t\t);\n\t\t}\n\t\treturn found !== undefined;\n\t};\n\tconst pair = (capability: keyof typeof PAIRS): boolean => {\n\t\tconst [first, second] = PAIRS[capability];\n\t\tconst present = [has(first), has(second)];\n\t\tif (present[0] !== present[1]) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${where}: the API key store has ${present[0] ? first : second} without ${present[0] ? second : first}: the ${capability} capability needs both`,\n\t\t\t);\n\t\t}\n\t\treturn present[0] === true;\n\t};\n\n\tconst bound = pair('bound');\n\tconst userBound = has('listUserBoundApiKeys');\n\tif (userBound && !bound) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: the API key store has listUserBoundApiKeys without the bound capability (listBoundApiKeys and revokeBoundApiKeys): the userBound capability needs it`,\n\t\t);\n\t}\n\n\treturn {\n\t\tcollectExpired: has('deleteExpiredApiKeys'),\n\t\tbound,\n\t\tuserBound,\n\t\texpiryNotice: pair('expiryNotice'),\n\t};\n}\n",
|
|
100
|
+
"import type { InvitationStore } from './types';\n\n/** The methods an invitation store must answer, in the order the port declares them. */\nconst REQUIRED = [\n\t'insertInvitation',\n\t'findInvitation',\n\t'findInvitationByCodeHash',\n\t'listScopeInvitations',\n\t'countPendingInvitations',\n\t'updateInvitation',\n\t'deleteScopeInvitations',\n] as const;\n\n/** What `assertInvitationStore` found beyond the required methods. */\nexport interface InvitationStoreCapabilities {\n\t/** Whether `deleteExpiredInvitations` is implemented. */\n\treadonly collectExpired: boolean;\n}\n\n/**\n * Checks that a store answers every method of the {@link InvitationStore}\n * port, and reports its optional capability. The net for a JavaScript caller,\n * as `assertApiKeyStore` is for the API key store; a bare `TypeError`, since a\n * missing method can only come from how the application was wired.\n *\n * `where` names the call the consumer wrote, so the sentence says what to fix.\n */\nexport function assertInvitationStore(\n\tstore: unknown,\n\twhere: string,\n): InvitationStoreCapabilities {\n\tif (typeof store !== 'object' || store === null) {\n\t\tthrow new TypeError(`${where}: the invitation store must be an object`);\n\t}\n\n\tconst methods = store as Record<string, unknown>;\n\tfor (const method of REQUIRED) {\n\t\tif (typeof methods[method] !== 'function') {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${where}: the invitation store has no method ${method}, which the port requires`,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst pending = methods['findPendingInvitation'];\n\tif (pending !== undefined && typeof pending !== 'function') {\n\t\tthrow new TypeError(\n\t\t\t`${where}: the invitation store's findPendingInvitation must be a function or absent`,\n\t\t);\n\t}\n\n\tconst found = methods['deleteExpiredInvitations'];\n\tif (found !== undefined && typeof found !== 'function') {\n\t\tthrow new TypeError(\n\t\t\t`${where}: the invitation store's deleteExpiredInvitations must be a function or absent`,\n\t\t);\n\t}\n\treturn { collectExpired: found !== undefined };\n}\n",
|
|
101
|
+
"import type { JanusStores, StoreCapabilities } from './types';\n\n/**\n * The methods each slot must answer, in the order the port declares them.\n *\n * Kept beside the interfaces rather than derived from them: a type does not\n * exist at runtime, and this list is the net for the JavaScript caller the\n * compiler never saw.\n */\nconst REQUIRED = {\n\tusers: [\n\t\t'insertUser',\n\t\t'findUser',\n\t\t'findUserByLogin',\n\t\t'listUsers',\n\t\t'countUsers',\n\t\t'updateUser',\n\t\t'deleteUser',\n\t],\n\tsessions: [\n\t\t'insertSession',\n\t\t'findSessionByTokenHash',\n\t\t'extendSession',\n\t\t'reauthenticateSession',\n\t\t'revokeSession',\n\t\t'revokeUserSessions',\n\t\t'deleteUserSessions',\n\t],\n\ttokens: [\n\t\t'insertToken',\n\t\t'consumeToken',\n\t\t'countAttempt',\n\t\t'spendUserTokens',\n\t\t'deleteUserTokens',\n\t],\n} as const satisfies Record<\n\tExclude<keyof JanusStores, 'socialLinks' | 'passkeys'>,\n\treadonly string[]\n>;\n\n/** The methods the optional `socialLinks` slot must answer, when it is there. */\nconst SOCIAL_LINKS = [\n\t'insertSocialLink',\n\t'findSocialLink',\n\t'listUserSocialLinks',\n\t'deleteSocialLink',\n\t'deleteUserSocialLinks',\n] as const;\n\n/** The methods the optional `passkeys` slot must answer, when it is there. */\nconst PASSKEYS = [\n\t'insertPasskey',\n\t'findPasskey',\n\t'listUserPasskeys',\n\t'recordPasskeyUse',\n\t'renamePasskey',\n\t'deletePasskey',\n\t'deleteUserPasskeys',\n] as const;\n\n/**\n * Checks that every slot answers every method the port declares, and reports\n * the optional capabilities found.\n *\n * TypeScript already refuses a partial store and names the missing method;\n * this is the net for a JavaScript caller, and for a store assembled from\n * `any`. A bare `TypeError`, because a missing method can only come from how\n * the application was wired — no request produces one, and no handler should\n * answer one.\n *\n * `where` names the call the consumer wrote — `janus` — so the\n * sentence says which call to fix and which slot to change.\n */\nexport function assertStores(\n\tstores: unknown,\n\twhere: string,\n): StoreCapabilities {\n\tif (typeof stores !== 'object' || stores === null) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: store must be an object with users, sessions and tokens`,\n\t\t);\n\t}\n\n\tfor (const slot of Object.keys(REQUIRED) as (keyof typeof REQUIRED)[]) {\n\t\tconst store: unknown = (stores as Record<string, unknown>)[slot];\n\n\t\tif (typeof store !== 'object' || store === null) {\n\t\t\tthrow new TypeError(`${where}: store.${slot} is missing`);\n\t\t}\n\n\t\tfor (const method of REQUIRED[slot]) {\n\t\t\tif (typeof (store as Record<string, unknown>)[method] !== 'function') {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t`${where}: store.${slot} has no method ${method}, which the port requires`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tassertSocialLinks((stores as JanusStores).socialLinks, where);\n\tassertPasskeys((stores as JanusStores).passkeys, where);\n\n\tconst slots = stores as Record<\n\t\tkeyof typeof REQUIRED,\n\t\tRecord<string, unknown>\n\t>;\n\t// Present, it must be a function; absent is a store that cannot list.\n\toptional(slots, 'sessions', 'listUserSessions', where);\n\treturn {\n\t\tcollectExpired: optional(slots, 'sessions', 'deleteExpiredSessions', where),\n\t\tcollectExpiredTokens: optional(\n\t\t\tslots,\n\t\t\t'tokens',\n\t\t\t'deleteExpiredTokens',\n\t\t\twhere,\n\t\t),\n\t\tfindUsers: optional(slots, 'users', 'findUsers', where),\n\t};\n}\n\n/**\n * Whether an optional method is there. Present but not a function is a wiring\n * mistake, not an absent capability: reporting it as \"unsupported\" would send\n * the reader to the wrong fix.\n */\nfunction optional(\n\tstores: Record<keyof typeof REQUIRED, Record<string, unknown>>,\n\tslot: keyof typeof REQUIRED,\n\tmethod: string,\n\twhere: string,\n): boolean {\n\tconst found = stores[slot][method];\n\tif (found !== undefined && typeof found !== 'function') {\n\t\tthrow new TypeError(\n\t\t\t`${where}: store.${slot}.${method} must be a function or absent`,\n\t\t);\n\t}\n\treturn found !== undefined;\n}\n\n/**\n * The optional `socialLinks` slot: absent is fine (`janus()` refuses it later\n * for a type with `social`), but present it must answer the whole port.\n */\nfunction assertSocialLinks(store: unknown, where: string): void {\n\tif (store === undefined) return;\n\tif (typeof store !== 'object' || store === null) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: store.socialLinks must be a social link store or absent`,\n\t\t);\n\t}\n\n\tfor (const method of SOCIAL_LINKS) {\n\t\tif (typeof (store as Record<string, unknown>)[method] !== 'function') {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${where}: store.socialLinks has no method ${method}, which the port requires`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n/** The optional `passkeys` slot: absent is fine, but present it must answer the whole port. */\nfunction assertPasskeys(store: unknown, where: string): void {\n\tif (store === undefined) return;\n\tif (typeof store !== 'object' || store === null) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: store.passkeys must be a passkey store or absent`,\n\t\t);\n\t}\n\n\tfor (const method of PASSKEYS) {\n\t\tif (typeof (store as Record<string, unknown>)[method] !== 'function') {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${where}: store.passkeys has no method ${method}, which the port requires`,\n\t\t\t);\n\t\t}\n\t}\n}\n",
|
|
102
|
+
"/**\n * The shape of what `apiKeys.create` stores beside a key — its `scopes` and\n * its `bound` object — and of the object `listBound` and `revokeAllBound`\n * read. Read from a request, so refused with `API_KEY_INVALID`, never thrown\n * as a `TypeError`.\n */\n\nimport { ApiKeyInvalidError } from '../../errors/janus-error';\nimport { isStorable } from '../../stores/storable';\nimport type { ApiKeyBound, ApiKeyStore } from '../port/types';\n\nconst SCOPES_MAX = 32;\nconst SCOPE_MAX = 100;\nconst BOUND_TYPE_MAX = 64;\nconst BOUND_ID_MAX = 200;\n\n/** A scope token as OAuth writes one: printable ASCII but space, `\"` and `\\`. */\nconst SCOPE = /^[\\x21\\x23-\\x5b\\x5d-\\x7e]+$/;\n\n/** The scopes as stored: `undefined` for none, else 1 to 32 distinct tokens in the order given. */\nexport function checkScopes(\n\tscopes: unknown,\n\twhere: string,\n): readonly string[] | undefined {\n\tif (scopes === undefined) return undefined;\n\tconst valid =\n\t\tArray.isArray(scopes) &&\n\t\tscopes.length >= 1 &&\n\t\tscopes.every(\n\t\t\t(scope) =>\n\t\t\t\ttypeof scope === 'string' &&\n\t\t\t\tscope.length <= SCOPE_MAX &&\n\t\t\t\tSCOPE.test(scope),\n\t\t);\n\tconst distinct = valid ? [...new Set(scopes as string[])] : [];\n\tif (!valid || distinct.length > SCOPES_MAX) {\n\t\tthrow new ApiKeyInvalidError(\n\t\t\t`${where}: scopes must be 1 to ${SCOPES_MAX} distinct tokens of 1 to ${SCOPE_MAX} printable characters, with no space, quote or backslash`,\n\t\t\t{ field: 'scopes' },\n\t\t);\n\t}\n\treturn distinct;\n}\n\n/** Whether `value` is an object a key can be bound to: a `type` and an `id`, both within their lengths. */\nexport function isBound(value: unknown): value is ApiKeyBound {\n\tif (typeof value !== 'object' || value === null) return false;\n\tconst { type, id } = value as Record<string, unknown>;\n\treturn (\n\t\ttypeof type === 'string' &&\n\t\ttype.length >= 1 &&\n\t\ttype.length <= BOUND_TYPE_MAX &&\n\t\tisStorable(type) &&\n\t\ttypeof id === 'string' &&\n\t\tid.length >= 1 &&\n\t\tid.length <= BOUND_ID_MAX &&\n\t\tisStorable(id)\n\t);\n}\n\n/** The bound object as stored — only its `type` and `id` — or `undefined` for none. */\nexport function checkBound(\n\tbound: unknown,\n\twhere: string,\n): ApiKeyBound | undefined {\n\tif (bound === undefined) return undefined;\n\tif (!isBound(bound)) {\n\t\tthrow new ApiKeyInvalidError(\n\t\t\t`${where}: bound must be { type, id }, a type of 1 to ${BOUND_TYPE_MAX} characters and an id of 1 to ${BOUND_ID_MAX}`,\n\t\t\t{ field: 'bound' },\n\t\t);\n\t}\n\treturn { type: bound.type, id: bound.id };\n}\n\n/** The store's `bound` methods, or a `TypeError`: a store without them would drop what binds a key. */\nexport function boundMethods(keys: ApiKeyStore, where: string) {\n\tconst { listBoundApiKeys, revokeBoundApiKeys } = keys;\n\tif (listBoundApiKeys === undefined || revokeBoundApiKeys === undefined) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: the API key store does not implement listBoundApiKeys and revokeBoundApiKeys, so it cannot keep scopes or a bound object`,\n\t\t);\n\t}\n\treturn {\n\t\tlist: listBoundApiKeys.bind(keys),\n\t\trevoke: revokeBoundApiKeys.bind(keys),\n\t};\n}\n\n/** The store's `expiryNotice` methods, or a `TypeError`. */\nexport function expiryMethods(keys: ApiKeyStore, where: string) {\n\tconst { listExpiringApiKeys, markApiKeyExpiryNotified } = keys;\n\tif (\n\t\tlistExpiringApiKeys === undefined ||\n\t\tmarkApiKeyExpiryNotified === undefined\n\t) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: the API key store does not implement listExpiringApiKeys and markApiKeyExpiryNotified`,\n\t\t);\n\t}\n\treturn {\n\t\tlist: listExpiringApiKeys.bind(keys),\n\t\tmark: markApiKeyExpiryNotified.bind(keys),\n\t};\n}\n",
|
|
103
|
+
"/** `apiKeys.listBound` and `apiKeys.revokeAllBound`: the keys of one bound object. */\n\nimport { isId } from '../../ids/id';\nimport { invalidCursor, pageLimit } from '../../pagination/cursor-page';\nimport { type Context, refId } from '../context';\nimport type { ApiKeyStore } from '../port/types';\nimport type { ApiKeysApi } from '../types';\nimport { keysRevoked, ownerForEvent } from './events';\nimport { boundMethods, isBound } from './shape';\nimport { toApiKey } from './to-api-key';\n\ntype Api = ApiKeysApi<{\n\treadonly id: string;\n\treadonly type: string;\n}>['apiKeys'];\n\nexport function boundApi(\n\tcontext: Context,\n\tprefix: string,\n\tkeys: ApiKeyStore,\n): Pick<Api, 'listBound' | 'revokeAllBound'> {\n\treturn {\n\t\tasync listBound(object, page) {\n\t\t\tconst store = boundMethods(keys, 'apiKeys.listBound');\n\t\t\tconst after = page?.after ?? null;\n\t\t\tif (after !== null && !isId(after)) {\n\t\t\t\tthrow invalidCursor('apiKeys.listBound', after);\n\t\t\t}\n\t\t\tconst first = pageLimit(page?.limit, 'apiKeys.listBound');\n\t\t\t// Nothing can be bound to what is no bound shape.\n\t\t\tif (!isBound(object)) return { items: [], nextCursor: null };\n\n\t\t\tconst found = await store.list(\n\t\t\t\t{ type: object.type, id: object.id },\n\t\t\t\t{ first, after },\n\t\t\t);\n\t\t\treturn {\n\t\t\t\titems: found.items.map((record) => toApiKey(prefix, record)),\n\t\t\t\tnextCursor: found.nextCursor,\n\t\t\t};\n\t\t},\n\n\t\tasync revokeAllBound(user, object) {\n\t\t\tconst store = boundMethods(keys, 'apiKeys.revokeAllBound');\n\t\t\tconst owner = refId(user);\n\t\t\tif (!isId(owner) || !isBound(object)) return 0;\n\t\t\tconst who = await ownerForEvent(context, owner);\n\t\t\tconst at = context.clock.now();\n\t\t\tconst count = await store.revoke(\n\t\t\t\towner,\n\t\t\t\t{ type: object.type, id: object.id },\n\t\t\t\tat,\n\t\t\t);\n\t\t\tawait keysRevoked(context, who, at, count);\n\t\t\treturn count;\n\t\t},\n\t};\n}\n",
|
|
104
|
+
"import { MAX_PAGE_SIZE } from '../../pagination/cursor-page';\nimport type { ApiKeyStore } from '../port/types';\n\n/**\n * How many standing keys a user holds at `now` — not revoked, not lapsed —\n * counted up to `stopAt`: past it the answer is only \"too many\", so the\n * walk through the user's keys ends there.\n */\nexport async function countStanding(\n\tkeys: ApiKeyStore,\n\tuserId: string,\n\tnow: Date,\n\tstopAt: number,\n): Promise<number> {\n\tlet standing = 0;\n\tlet after: string | null = null;\n\tdo {\n\t\tconst page = await keys.listUserApiKeys(userId, {\n\t\t\tfirst: MAX_PAGE_SIZE,\n\t\t\tafter,\n\t\t});\n\t\tfor (const key of page.items) {\n\t\t\tif (key.revokedAt === null && key.expiresAt.getTime() > now.getTime()) {\n\t\t\t\tstanding += 1;\n\t\t\t}\n\t\t}\n\t\tafter = page.nextCursor;\n\t} while (after !== null && standing < stopAt);\n\treturn standing;\n}\n",
|
|
105
|
+
"/** What `apiKeys.create` checks, before the insert and once the key is stored. */\n\nimport {\n\tApiKeyInvalidError,\n\tApiKeyLimitError,\n\tEmailUnverifiedError,\n\tNotFoundError,\n\tStepUpRequiredError,\n\tUserInactiveError,\n} from '../../../errors/janus-error';\nimport { isStorable } from '../../../stores/storable';\nimport { parseDuration } from '../../../time/duration';\nimport type { ResolvedConfig } from '../../config';\nimport { type Context, emailOf } from '../../context';\nimport type { ApiKeyStore } from '../../port/types';\nimport { hashSecret } from '../../secrets';\nimport { assertFresh } from '../../sessions/fresh';\nimport { pastAbsolute } from '../../sessions/standing';\nimport type { CreateApiKeyInput, Principal } from '../../types';\nimport { countStanding } from '../count';\nimport { boundMethods, checkBound, checkScopes } from '../shape';\n\nconst NAME_MAX = 100;\nexport const WHERE = 'apiKeys.create';\n\nexport type Settings = NonNullable<ResolvedConfig['apiKeys']>;\n\n/** What `create` takes, degenericised. */\nexport type CreateInput = CreateApiKeyInput<string | number>;\n\n/**\n * Who asks and what for, before anything is written: a session fresh enough\n * whose password is still the user's, a valid name and lifetime, a user who\n * can hold keys, and room under `maxActive`. A user at the limit is refused\n * with no write.\n */\nexport async function checkBeforeInsert(\n\tcontext: Context,\n\tsettings: Settings,\n\tkeys: ApiKeyStore,\n\tcurrent: Principal<{ readonly id: string; readonly type: string }>,\n\tinput: CreateInput,\n) {\n\tconst { store, clock } = context;\n\tconst userId = refOf(current);\n\t// A key never proves who anyone is, so it is never fresh.\n\tif (current.via === 'apiKey') {\n\t\tthrow new StepUpRequiredError(\n\t\t\t`${WHERE}: an API key cannot create a key — it is never fresh; sign in or confirm a step-up`,\n\t\t\t{ userId, reason: 'apiKey' },\n\t\t);\n\t}\n\tassertFresh(\n\t\t{ authenticatedAt: current.session.authenticatedAt, userId },\n\t\tsettings.freshWithinMs,\n\t\tclock,\n\t);\n\n\tconst name = checkName(input?.name);\n\tconst lifetimeMs = checkLifetime(settings, input?.lifetime);\n\tconst scopes = checkScopes(input?.scopes, WHERE);\n\tconst bound = checkBound(input?.bound, WHERE);\n\t// A store that cannot keep a valid restriction is a wiring fault, found\n\t// before anything is written; a malformed one was refused above, as 400.\n\tif (scopes !== undefined || bound !== undefined) boundMethods(keys, WHERE);\n\n\t// Read again: the object in hand may be older than the user's state.\n\tconst user = await store.users.findUser(userId);\n\tif (user === null || !settings.types.has(user.type)) {\n\t\tthrow new NotFoundError(`${WHERE}: no such user can hold API keys`, {\n\t\t\tuserId,\n\t\t});\n\t}\n\tif (!user.active) {\n\t\tthrow new UserInactiveError(`${WHERE}: the user is inactive`, { userId });\n\t}\n\t// A key outlives the session that made it: whoever signed up with an\n\t// address and not its inbox must not be able to hold one. A user with no\n\t// address has nothing to squat, and could never verify one.\n\tconst type = context.config.types.get(user.type);\n\tif (\n\t\tuser.emailVerifiedAt === null &&\n\t\ttype !== undefined &&\n\t\temailOf(type, user.fields) !== null\n\t) {\n\t\tthrow new EmailUnverifiedError(`${WHERE}: the e-mail is not verified`, {\n\t\t\tuserId,\n\t\t\tuserType: user.type,\n\t\t});\n\t}\n\tcheckPasswordHeld(current, user);\n\n\tif (\n\t\t(await countStanding(keys, user.id, clock.now(), settings.maxActive)) >=\n\t\tsettings.maxActive\n\t) {\n\t\tthrow limitReached(settings, userId);\n\t}\n\treturn {\n\t\tuser,\n\t\tname,\n\t\tlifetimeMs,\n\t\t// Absent rather than `null`: an unscoped, unbound key is stored exactly\n\t\t// as before these fields existed.\n\t\textra: {\n\t\t\t...(scopes === undefined ? {} : { scopes }),\n\t\t\t...(bound === undefined ? {} : { bound }),\n\t\t},\n\t};\n}\n\nfunction limitReached(settings: Settings, userId: string): ApiKeyLimitError {\n\treturn new ApiKeyLimitError(\n\t\t`${WHERE}: the user already holds ${settings.maxActive} API keys — revoke one first`,\n\t\t{ userId, maxActive: settings.maxActive },\n\t);\n}\n\n/** A password written after the session proved who it is ends its right to a key. */\nfunction checkPasswordHeld(\n\tcurrent: Principal<{ readonly id: string }>,\n\tuser: {\n\t\treadonly id: string;\n\t\treadonly password: { readonly updatedAt: Date } | null;\n\t},\n): void {\n\tconst written = user.password?.updatedAt;\n\tif (\n\t\tcurrent.via !== 'apiKey' &&\n\t\twritten !== undefined &&\n\t\twritten.getTime() > current.session.authenticatedAt.getTime()\n\t) {\n\t\tthrow new StepUpRequiredError(\n\t\t\t`${WHERE}: the password changed since this session proved who it is — sign in or confirm a step-up`,\n\t\t\t{ userId: user.id },\n\t\t);\n\t}\n}\n\n/**\n * What can only be known once the key is stored: the limit still holds\n * against a racing creation, the user still can hold a key, and the session\n * still stands. A reset or a first proof that landed since the user was read\n * revoked the sessions first and the keys after, so a session that no longer\n * stands (read again, since a tie in time hides a reset from the password\n * check, and a first proof drops a password there is none to compare) means\n * the key being made is not the user's to keep. The password check stays\n * beside it.\n */\nexport async function checkAfterInsert(\n\tcontext: Context,\n\tsettings: Settings,\n\tkeys: ApiKeyStore,\n\tcurrent: Principal<{ readonly id: string; readonly type: string }>,\n\tuserId: string,\n): Promise<void> {\n\tconst { store, clock } = context;\n\tconst standing = await countStanding(\n\t\tkeys,\n\t\tuserId,\n\t\tclock.now(),\n\t\tsettings.maxActive + 1,\n\t);\n\tif (standing > settings.maxActive) throw limitReached(settings, userId);\n\n\tconst user = await store.users.findUser(userId);\n\tif (user === null) {\n\t\tthrow new NotFoundError(`${WHERE}: no such user can hold API keys`, {\n\t\t\tuserId,\n\t\t});\n\t}\n\tif (!user.active) {\n\t\tthrow new UserInactiveError(`${WHERE}: the user is inactive`, { userId });\n\t}\n\tcheckPasswordHeld(current, user);\n\tif (current.via === 'apiKey') return;\n\tconst session = await store.sessions.findSessionByTokenHash(\n\t\thashSecret(current.token),\n\t);\n\tif (\n\t\tsession === null ||\n\t\tsession.revokedAt !== null ||\n\t\tsession.expiresAt.getTime() <= clock.now().getTime() ||\n\t\tpastAbsolute(\n\t\t\tcontext.config.types.get(user.type),\n\t\t\tsession,\n\t\t\tclock.now().getTime(),\n\t\t)\n\t) {\n\t\tthrow new StepUpRequiredError(\n\t\t\t`${WHERE}: the session ended while the key was made — sign in again`,\n\t\t\t{ userId },\n\t\t);\n\t}\n}\n\nfunction refOf(current: Principal<{ readonly id: string }>): string {\n\tconst id: unknown = current?.user?.id;\n\treturn typeof id === 'string' ? id : '';\n}\n\nfunction checkName(name: unknown): string {\n\tconst trimmed = typeof name === 'string' ? name.trim() : '';\n\tif (trimmed.length < 1 || trimmed.length > NAME_MAX || !isStorable(trimmed)) {\n\t\tthrow new ApiKeyInvalidError(\n\t\t\t`${WHERE}: name must be 1 to ${NAME_MAX} characters once trimmed`,\n\t\t\t{ field: 'name' },\n\t\t);\n\t}\n\treturn trimmed;\n}\n\nfunction checkLifetime(settings: Settings, lifetime: unknown): number {\n\t// Read from a request: refused, never thrown as a TypeError, when it is no\n\t// duration at all.\n\tconst shaped =\n\t\ttypeof lifetime === 'number'\n\t\t\t? Number.isFinite(lifetime) && lifetime > 0\n\t\t\t: typeof lifetime === 'string' &&\n\t\t\t\t/^\\d+(?:\\.\\d+)?(?:ms|s|m|h|d)$/.test(lifetime) &&\n\t\t\t\tNumber.parseFloat(lifetime) > 0;\n\tconst ms = shaped ? parseDuration(lifetime as number, WHERE) : Number.NaN;\n\tif (!settings.lifetimesMs.includes(ms)) {\n\t\tthrow new ApiKeyInvalidError(\n\t\t\t`${WHERE}: lifetime is not one of the configured lifetimes`,\n\t\t\t{ field: 'lifetime' },\n\t\t);\n\t}\n\treturn ms;\n}\n",
|
|
106
|
+
"/** `apiKeys.create`: checks who asks and what for, inserts, then counts. */\n\nimport { mintId } from '../../../ids/id';\nimport type { Context } from '../../context';\nimport type { ApiKeyStore } from '../../port/types';\nimport { hashSecret, mintSecret } from '../../secrets';\nimport type { CreatedApiKey, Principal } from '../../types';\nimport { keyCreated } from '../events';\nimport { toApiKey } from '../to-api-key';\nimport { apiKeyToken } from '../token';\nimport {\n\ttype CreateInput,\n\tcheckAfterInsert,\n\tcheckBeforeInsert,\n\ttype Settings,\n} from './checks';\n\nexport async function createApiKey(\n\tcontext: Context,\n\tsettings: Settings,\n\tkeys: ApiKeyStore,\n\tcurrent: Principal<{ readonly id: string; readonly type: string }>,\n\tinput: CreateInput,\n): Promise<CreatedApiKey> {\n\tconst { clock } = context;\n\tconst { user, name, lifetimeMs, extra } = await checkBeforeInsert(\n\t\tcontext,\n\t\tsettings,\n\t\tkeys,\n\t\tcurrent,\n\t\tinput,\n\t);\n\n\tconst secret = mintSecret();\n\tconst id = mintId();\n\tconst createdAt = clock.now();\n\tconst record = {\n\t\tid,\n\t\tuserId: user.id,\n\t\tname,\n\t\tsecretHash: hashSecret(secret),\n\t\tcreatedAt,\n\t\texpiresAt: new Date(createdAt.getTime() + lifetimeMs),\n\t\tlastUsedAt: null,\n\t\trevokedAt: null,\n\t\t...extra,\n\t};\n\n\t// The count after the insert stays as the race guard — two creations\n\t// racing at the limit both insert, both count the other, and both are\n\t// refused — so the limit is never exceeded.\n\tawait keys.insertApiKey(record);\n\tconst [after] = await Promise.allSettled([\n\t\tcheckAfterInsert(context, settings, keys, current, user.id),\n\t]);\n\tif (after.status === 'rejected') {\n\t\t// No refusal and no outage leaves a standing key nobody holds — unless\n\t\t// the revoke fails too, which is warned of below; the token is only\n\t\t// answered when the checks pass.\n\t\tconst [revoked] = await Promise.allSettled([\n\t\t\tkeys.revokeApiKey(id, clock.now()),\n\t\t]);\n\t\tif (revoked.status === 'rejected') {\n\t\t\tprocess.emitWarning(\n\t\t\t\t`janus: an API key could not be revoked after its creation failed: ${\n\t\t\t\t\trevoked.reason instanceof Error\n\t\t\t\t\t\t? revoked.reason.name\n\t\t\t\t\t\t: typeof revoked.reason\n\t\t\t\t}`,\n\t\t\t\t{ code: 'JANUS_API_KEY_REVOKE_FAILED' },\n\t\t\t);\n\t\t}\n\t\tthrow after.reason;\n\t}\n\n\tawait keyCreated(context, user, createdAt);\n\treturn {\n\t\tapiKey: toApiKey(settings.prefix, record),\n\t\ttoken: apiKeyToken(settings.prefix, id, secret),\n\t};\n}\n",
|
|
107
|
+
"/** `apiKeys.expiring` and `apiKeys.markExpiryNotified`: what a daily sweep reads and records. */\n\nimport { NotFoundError } from '../../errors/janus-error';\nimport { isId } from '../../ids/id';\nimport { invalidCursor, pageLimit } from '../../pagination/cursor-page';\nimport { parseDuration } from '../../time/duration';\nimport type { Context } from '../context';\nimport type { ApiKeyStore } from '../port/types';\nimport type { ApiKeysApi } from '../types';\nimport { expiryMethods } from './shape';\nimport { toApiKey } from './to-api-key';\n\ntype Api = ApiKeysApi<{\n\treadonly id: string;\n\treadonly type: string;\n}>['apiKeys'];\n\nexport function expiryApi(\n\tcontext: Context,\n\tprefix: string,\n\tkeys: ApiKeyStore,\n): Pick<Api, 'expiring' | 'markExpiryNotified'> {\n\tconst { clock } = context;\n\n\treturn {\n\t\tasync expiring(options) {\n\t\t\tconst store = expiryMethods(keys, 'apiKeys.expiring');\n\t\t\tconst withinMs = parseDuration(\n\t\t\t\toptions?.within,\n\t\t\t\t'apiKeys.expiring: within',\n\t\t\t);\n\t\t\tconst after = options?.after ?? null;\n\t\t\tif (after !== null && !isId(after)) {\n\t\t\t\tthrow invalidCursor('apiKeys.expiring', after);\n\t\t\t}\n\t\t\tconst first = pageLimit(options?.limit, 'apiKeys.expiring');\n\t\t\tconst now = clock.now();\n\n\t\t\tconst found = await store.list({\n\t\t\t\tnow,\n\t\t\t\tbefore: new Date(now.getTime() + withinMs),\n\t\t\t\tfirst,\n\t\t\t\tafter,\n\t\t\t});\n\t\t\treturn {\n\t\t\t\titems: found.items.map((record) => toApiKey(prefix, record)),\n\t\t\t\tnextCursor: found.nextCursor,\n\t\t\t};\n\t\t},\n\n\t\tasync markExpiryNotified(id) {\n\t\t\tconst store = expiryMethods(keys, 'apiKeys.markExpiryNotified');\n\t\t\tconst missing = () =>\n\t\t\t\tnew NotFoundError('apiKeys.markExpiryNotified: no such API key');\n\t\t\tif (typeof id !== 'string' || !isId(id)) throw missing();\n\n\t\t\tif (await store.mark(id, clock.now())) return true;\n\t\t\t// Not written: already notified, or no key at all.\n\t\t\tif ((await keys.findApiKey(id)) === null) throw missing();\n\t\t\treturn false;\n\t\t},\n\t};\n}\n",
|
|
108
|
+
"/** One user's keys filtered on their bound object: the store's own method, or a scan of the user's keys. */\n\nimport type { Id } from '../../ids/id';\nimport type { CursorPage } from '../../pagination/cursor-page';\nimport type {\n\tApiKeyBound,\n\tApiKeyPageRequest,\n\tApiKeyRecord,\n\tApiKeyStore,\n} from '../port/types';\n\n/** How many of the user's keys the fallback reads at a time. */\nconst READ = 100;\n\n/** Whether a stored `bound` is the one asked for; `null` asks for none. */\nfunction matches(\n\tstored: ApiKeyBound | undefined,\n\tbound: ApiKeyBound | null,\n): boolean {\n\tif (bound === null) return stored === undefined;\n\treturn (\n\t\tstored !== undefined && stored.type === bound.type && stored.id === bound.id\n\t);\n}\n\n/**\n * Reads the user's keys `READ` at a time and keeps those that match, until the\n * page fills (one key more is read to know whether another page follows).\n */\nasync function scanUserBound(\n\tkeys: ApiKeyStore,\n\tuserId: Id,\n\tbound: ApiKeyBound | null,\n\t{ first, after }: ApiKeyPageRequest,\n): Promise<CursorPage<ApiKeyRecord>> {\n\tconst kept: ApiKeyRecord[] = [];\n\tlet cursor = after;\n\n\tdo {\n\t\tconst found = await keys.listUserApiKeys(userId, {\n\t\t\tfirst: READ,\n\t\t\tafter: cursor,\n\t\t});\n\t\tfor (const record of found.items) {\n\t\t\tif (matches(record.bound, bound)) kept.push(record);\n\t\t}\n\t\tcursor = found.nextCursor;\n\t} while (cursor !== null && kept.length <= first);\n\n\tconst items = kept.slice(0, first);\n\tconst last = items.at(-1);\n\treturn {\n\t\titems,\n\t\tnextCursor: kept.length > first && last !== undefined ? last.id : null,\n\t};\n}\n\n/**\n * One page of a user's keys bound to `bound` (`null`: unbound): the store's\n * `listUserBoundApiKeys` when it has it, else a scan of the user's keys.\n */\nexport async function listUserBound(\n\tkeys: ApiKeyStore,\n\tuserId: Id,\n\tbound: ApiKeyBound | null,\n\tpage: ApiKeyPageRequest,\n): Promise<CursorPage<ApiKeyRecord>> {\n\tif (keys.listUserBoundApiKeys !== undefined) {\n\t\treturn keys.listUserBoundApiKeys(userId, bound, page);\n\t}\n\treturn scanUserBound(keys, userId, bound, page);\n}\n",
|
|
109
|
+
"/** `apiKeys.get` and `apiKeys.list`: reading keys, one or a user's page. */\n\nimport { isId } from '../../ids/id';\nimport { invalidCursor, pageLimit } from '../../pagination/cursor-page';\nimport { refId } from '../context';\nimport type { ApiKeyStore } from '../port/types';\nimport type { ApiKeysApi } from '../types';\nimport { boundMethods, isBound } from './shape';\nimport { toApiKey } from './to-api-key';\nimport { listUserBound } from './user-bound';\n\ntype Api = ApiKeysApi<{\n\treadonly id: string;\n\treadonly type: string;\n}>['apiKeys'];\n\nexport function readApi(\n\tprefix: string,\n\tkeys: ApiKeyStore,\n): Pick<Api, 'get' | 'list'> {\n\treturn {\n\t\tasync get(id, options) {\n\t\t\tif (typeof id !== 'string' || !isId(id)) return null;\n\n\t\t\tconst record = await keys.findApiKey(id);\n\t\t\tif (record === null) return null;\n\t\t\t// Another user's key is no key at all: a request-supplied id must\n\t\t\t// not tell which keys exist.\n\t\t\tif (\n\t\t\t\ttypeof options === 'object' &&\n\t\t\t\toptions !== null &&\n\t\t\t\t'owner' in options &&\n\t\t\t\trecord.userId !== refId(options.owner)\n\t\t\t) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn toApiKey(prefix, record);\n\t\t},\n\n\t\tasync list(user, options) {\n\t\t\tconst owner = refId(user);\n\t\t\tconst after = options?.after ?? null;\n\t\t\tif (after !== null && !isId(after)) {\n\t\t\t\tthrow invalidCursor('apiKeys.list', after);\n\t\t\t}\n\t\t\tconst first = pageLimit(options?.limit, 'apiKeys.list');\n\t\t\tconst bound = options?.bound;\n\t\t\t// A store without `bound` would drop what binds a key: refuse before any read.\n\t\t\tif (bound !== undefined) boundMethods(keys, 'apiKeys.list');\n\t\t\t// Nothing can be bound to what is no bound shape.\n\t\t\tif (bound !== undefined && bound !== null && !isBound(bound)) {\n\t\t\t\treturn { items: [], nextCursor: null };\n\t\t\t}\n\t\t\tif (!isId(owner)) return { items: [], nextCursor: null };\n\n\t\t\tconst found =\n\t\t\t\tbound === undefined\n\t\t\t\t\t? await keys.listUserApiKeys(owner, { first, after })\n\t\t\t\t\t: await listUserBound(\n\t\t\t\t\t\t\tkeys,\n\t\t\t\t\t\t\towner,\n\t\t\t\t\t\t\tbound === null ? null : { type: bound.type, id: bound.id },\n\t\t\t\t\t\t\t{ first, after },\n\t\t\t\t\t\t);\n\t\t\treturn {\n\t\t\t\titems: found.items.map((record) => toApiKey(prefix, record)),\n\t\t\t\tnextCursor: found.nextCursor,\n\t\t\t};\n\t\t},\n\t};\n}\n",
|
|
110
|
+
"/** The `auth.apiKeys` surface: create, get, list, revoke, revokeAll, and the bound and expiry methods beside. */\n\nimport { NotFoundError } from '../../errors/janus-error';\nimport { isId } from '../../ids/id';\nimport { type Context, refId } from '../context';\nimport type { ApiKeyStore } from '../port/types';\nimport type { ApiKeysApi } from '../types';\nimport { boundApi } from './bound';\nimport { createApiKey } from './create';\nimport { keysRevoked, ownerForEvent } from './events';\nimport { expiryApi } from './expiry';\nimport { readApi } from './read';\n\n/** `ApiKeysApi`, degenericised: `janus()` casts it to the typed form once. */\ntype InternalApiKeysApi = ApiKeysApi<{\n\treadonly id: string;\n\treadonly type: string;\n}>['apiKeys'];\n\n/** The `apiKeys` of an instance whose `janus()` was given `apiKeys`. */\nexport function apiKeysApi(\n\tcontext: Context,\n\tkeys: ApiKeyStore,\n): InternalApiKeysApi {\n\tconst settings = context.config.apiKeys;\n\tif (settings === null) {\n\t\tthrow new TypeError('janus: apiKeysApi needs janus({ apiKeys })');\n\t}\n\tconst { clock } = context;\n\n\treturn {\n\t\tasync create(current, input) {\n\t\t\treturn createApiKey(context, settings, keys, current, input);\n\t\t},\n\n\t\tasync revoke(id, options) {\n\t\t\tconst missing = () =>\n\t\t\t\tnew NotFoundError('apiKeys.revoke: no such API key');\n\t\t\tif (typeof id !== 'string' || !isId(id)) throw missing();\n\n\t\t\tconst record = await keys.findApiKey(id);\n\t\t\tif (record === null) throw missing();\n\t\t\t// Another user's key is no key at all: a request-supplied id must\n\t\t\t// not tell which keys exist.\n\t\t\tif (\n\t\t\t\ttypeof options === 'object' &&\n\t\t\t\toptions !== null &&\n\t\t\t\t'owner' in options &&\n\t\t\t\trecord.userId !== refId(options.owner)\n\t\t\t) {\n\t\t\t\tthrow missing();\n\t\t\t}\n\t\t\tconst owner = await ownerForEvent(context, record.userId);\n\t\t\tconst at = clock.now();\n\t\t\tif (!(await keys.revokeApiKey(id, at))) throw missing();\n\t\t\t// Revoking a revoked key is no revoke, so no event.\n\t\t\tawait keysRevoked(context, owner, at, record.revokedAt === null ? 1 : 0);\n\t\t},\n\n\t\tasync revokeAll(user) {\n\t\t\tconst owner = refId(user);\n\t\t\tif (!isId(owner)) return 0;\n\t\t\tconst who = await ownerForEvent(context, owner);\n\t\t\tconst at = clock.now();\n\t\t\tconst count = await keys.revokeUserApiKeys(owner, at);\n\t\t\tawait keysRevoked(context, who, at, count);\n\t\t\treturn count;\n\t\t},\n\n\t\t...readApi(settings.prefix, keys),\n\t\t...boundApi(context, settings.prefix, keys),\n\t\t...expiryApi(context, settings.prefix, keys),\n\t};\n}\n",
|
|
111
|
+
"/**\n * Resetting a password: send a token to the holder of an e-mail, then redeem\n * it to set the password — which proves the e-mail, and signs the user out\n * everywhere.\n */\n\nimport type { At } from '../at';\nimport type { ResolvedType } from '../config';\nimport {\n\ttype AnyUser,\n\ttype Context,\n\tholderOfEmail,\n\tpasswordRule,\n\ttoUser,\n} from '../context';\nimport { countMailByAddress } from '../mail-requests';\nimport { sendOnce } from '../prepared';\nimport { hashSecret } from '../secrets';\nimport type { IssuedToken, PreparedRequest, ResetPasswordApi } from '../types';\nimport { confirmReset } from './confirm-reset';\nimport { issueEmailToken } from './email-token';\n\ntype ResetPassword = ResetPasswordApi<AnyUser>['resetPassword'];\ntype IssuedReset = IssuedToken & { readonly user: AnyUser };\n\n/**\n * `resetPassword` of one user type: `request` a token for the holder of an\n * e-mail, then `confirm` it with a new password.\n */\nexport function resetPasswordFlows(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tat: At,\n): ResetPassword {\n\treturn {\n\t\tasync request(email) {\n\t\t\tconst where = at('resetPassword.request');\n\t\t\treturn (await prepareReset(context, type, String(email), where)).send();\n\t\t},\n\n\t\tasync prepare(email) {\n\t\t\tconst where = at('resetPassword.prepare');\n\t\t\treturn prepareReset(context, type, String(email), where);\n\t\t},\n\n\t\tasync confirm(secret, password) {\n\t\t\treturn confirmReset(\n\t\t\t\tcontext,\n\t\t\t\ttype,\n\t\t\t\tsecret,\n\t\t\t\tpassword,\n\t\t\t\tat('resetPassword.confirm'),\n\t\t\t);\n\t\t},\n\t};\n}\n\n/**\n * Counts a reset asked for `email` — before it is looked up: past the\n * limit, nobody and somebody are refused alike — and answers the `send`\n * that issues it, once. `request` is this, then `send`.\n */\nasync function prepareReset(\n\tcontext: Context,\n\ttype: ResolvedType,\n\temail: string,\n\twhere: string,\n): Promise<PreparedRequest<IssuedReset>> {\n\tpasswordRule(type, where);\n\tawait countMailByAddress(context, type, 'resetPassword', email, where);\n\treturn Object.freeze({\n\t\tsend: sendOnce(where, () => issueReset(context, type, email, where)),\n\t});\n}\n\n/** Issues a reset token for the holder of `email`, and spends every other they had. */\nasync function issueReset(\n\tcontext: Context,\n\ttype: ResolvedType,\n\temail: string,\n\twhere: string,\n): Promise<IssuedReset | null> {\n\tconst record = await holderOfEmail(context, type, email);\n\tif (record === null) return null;\n\n\tconst issued = await issueEmailToken(\n\t\tcontext,\n\t\ttype,\n\t\t'resetPassword',\n\t\trecord,\n\t\twhere,\n\t);\n\t// One live link per user: the ones sent before stop working. Issued\n\t// first, spent after, as for a sign-in code, so requests that race\n\t// leave at most one live — never one each.\n\tawait context.store.tokens.spendUserTokens(\n\t\trecord.id,\n\t\t'resetPassword',\n\t\tcontext.clock.now(),\n\t\thashSecret(issued.token),\n\t);\n\treturn { ...issued, user: toUser(record) };\n}\n",
|
|
112
|
+
"/**\n * `setEmailVerified`: the flag alone, for an administrator who checked the\n * address out of band. Nothing of `proveFirst`'s takeover-proofing runs.\n */\n\nimport { NotFoundError } from '../../errors/janus-error';\nimport type { At } from '../at';\nimport type { ResolvedType } from '../config';\nimport {\n\ttype AnyUser,\n\ttype Context,\n\temailOf,\n\ttoUser,\n\twriteUser,\n} from '../context';\nimport { emit } from '../events';\nimport type { VerifyEmailApi } from '../types';\n\n/**\n * Sets `emailVerified` to `true` (stamping `emailVerifiedAt` with the clock)\n * or back to `false`, in one write under the version read, and touches\n * nothing else: the password, avatar and second factor stay, and no session,\n * API key or token is revoked or spent. Marking a user with no e-mail verified\n * is `NOT_FOUND`, as sending them a link is. A flag already as asked is no write\n * and no event. Sends `user.emailVerified` when it turned the flag on;\n * turning it off has no event, as no event type reports it.\n */\nexport function setEmailVerifiedFlow(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tat: At,\n): VerifyEmailApi<AnyUser>['setEmailVerified'] {\n\treturn async (user, verified, options) => {\n\t\tlet turnedOn = false;\n\t\tconst written = await writeUser(\n\t\t\tcontext,\n\t\t\tuser,\n\t\t\ttype,\n\t\t\toptions,\n\t\t\tat('setEmailVerified'),\n\t\t\t(record, now) => {\n\t\t\t\tconst wanted = verified === true;\n\t\t\t\tif (wanted && emailOf(type, record.fields) === null) {\n\t\t\t\t\tthrow new NotFoundError(\n\t\t\t\t\t\t`${at('setEmailVerified')}: the user has no e-mail`,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tuserId: record.id,\n\t\t\t\t\t\t\tuserType: type.name,\n\t\t\t\t\t\t\toperation: at('setEmailVerified'),\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif ((record.emailVerifiedAt !== null) === wanted) return null;\n\t\t\t\tturnedOn = wanted;\n\t\t\t\treturn { emailVerifiedAt: wanted ? now : null };\n\t\t\t},\n\t\t);\n\t\tif (turnedOn) {\n\t\t\tawait emit(context, 'user.emailVerified', written, written.updatedAt);\n\t\t}\n\t\treturn toUser(written);\n\t};\n}\n",
|
|
113
|
+
"/** The e-mail flows of one user type, assembled from the files beside this one. */\n\nimport type { At } from '../at';\nimport type { ResolvedType } from '../config';\nimport type { AnyUser, Context } from '../context';\nimport type {\n\tChangeEmailApi,\n\tResetPasswordApi,\n\tVerifyEmailApi,\n} from '../types';\nimport { changeEmailFlows } from './change-email';\nimport { resetPasswordFlows } from './reset-password';\nimport { setEmailVerifiedFlow } from './set-email-verified';\nimport { verifyEmailFlows } from './verify-email';\n\n/**\n * The e-mail flows: send a one-time token by e-mail, then confirm it —\n * verifying the address, resetting the password, or moving to a new address.\n * All three confirm the same way: spend the token, read the user, and check\n * the address again on the very record the write replaces.\n */\nexport function emailFlows(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tat: At,\n): VerifyEmailApi<AnyUser> &\n\tResetPasswordApi<AnyUser> &\n\tChangeEmailApi<AnyUser> {\n\treturn {\n\t\tverifyEmail: verifyEmailFlows(context, type, at),\n\t\tsetEmailVerified: setEmailVerifiedFlow(context, type, at),\n\t\tresetPassword: resetPasswordFlows(context, type, at),\n\t\tchangeEmail: changeEmailFlows(context, type, at),\n\t};\n}\n",
|
|
114
|
+
"import { MagicLinkDisabledError } from '../errors/janus-error';\nimport type { At } from './at';\nimport type { ResolvedType } from './config';\nimport { type AnyUser, type Context, toUser } from './context';\nimport { type DeviceHint, deviceHint } from './devices';\nimport { redeemEmailToken } from './email-flows/email-token';\nimport {\n\ttype Finish,\n\tfinishEmailSignIn,\n\tkeepOnlyLatest,\n\tsignInHolder,\n} from './email-sign-in';\nimport { countMailByAddress } from './mail-requests';\nimport { issueOneTime } from './one-time';\nimport { sendOnce } from './prepared';\nimport { AMR } from './sessions/amr';\nimport type {\n\tIssuedToken,\n\tMagicLinkApi,\n\tPreparedRequest,\n\tSignInResult,\n} from './types';\n\ntype IssuedLink = IssuedToken & { readonly user: AnyUser };\n\n/**\n * Signing in with a link sent to the user's e-mail: no password, and the\n * link proves the address — a sign-in code with nothing to type.\n *\n * The token is 32 random bytes, so there is nothing to guess and no attempt\n * to count: redeeming it is one conditional write, and of two redemptions\n * at once exactly one signs in. **At most one link is live per user**, as\n * for a sign-in code: `request` spends every other once it issued its own.\n * A token of its own kind, `magicLink`, so a sign-in code's challenge — which\n * the visitor holds — is never a link, nor a link a challenge.\n *\n * Whoever opens the link signs in, in the browser that opened it: the\n * application confirms it from a `POST`, never from the `GET` of the link,\n * which a mail scanner follows too.\n *\n * `request` is `prepare`, then `send`: counted, then looked up and issued\n * (`prepared.ts`).\n */\nexport function magicLinkFlows(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tat: At,\n\tfinish: Finish,\n): MagicLinkApi<AnyUser, SignInResult<AnyUser>>['magicLink'] {\n\tconst enabled = context.config.magicLinkEnabled;\n\treturn {\n\t\tenabled,\n\n\t\tasync request(email) {\n\t\t\tconst where = at('magicLink.request');\n\t\t\trefuseWhenDisabled(enabled, where);\n\t\t\treturn (await prepareLink(context, type, String(email), where)).send();\n\t\t},\n\n\t\tasync prepare(email) {\n\t\t\tconst where = at('magicLink.prepare');\n\t\t\trefuseWhenDisabled(enabled, where);\n\t\t\treturn prepareLink(context, type, String(email), where);\n\t\t},\n\n\t\tasync confirm(token, options) {\n\t\t\tconst where = at('magicLink.confirm');\n\t\t\trefuseWhenDisabled(enabled, where);\n\t\t\tconst device = deviceHint(context, options, where);\n\t\t\treturn confirmLink(context, type, finish, String(token), where, device);\n\t\t},\n\t};\n}\n\n/** Before any store access, mail or token: the switch is off. */\nfunction refuseWhenDisabled(enabled: boolean, where: string): void {\n\tif (!enabled) {\n\t\tthrow new MagicLinkDisabledError(\n\t\t\t`${where}: magic-link sign-in is disabled`,\n\t\t);\n\t}\n}\n\n/**\n * Counts a link asked for `email` — before it is looked up: past the limit,\n * nobody and somebody are refused alike — and answers the `send` that\n * issues it, once.\n */\nasync function prepareLink(\n\tcontext: Context,\n\ttype: ResolvedType,\n\temail: string,\n\twhere: string,\n): Promise<PreparedRequest<IssuedLink>> {\n\tawait countMailByAddress(context, type, 'magicLink', email, where);\n\treturn Object.freeze({\n\t\tsend: sendOnce(where, () => issueLink(context, type, email)),\n\t});\n}\n\n/** Issues a link's token for the holder of `email`, and spends every other they had. */\nasync function issueLink(\n\tcontext: Context,\n\ttype: ResolvedType,\n\temail: string,\n): Promise<IssuedLink | null> {\n\t// Nobody, and an inactive user, get the same answer: no link.\n\tconst record = await signInHolder(context, type, email);\n\tif (record === null) return null;\n\n\tconst address = String(record.fields[type.email]);\n\tconst { secret, expiresAt } = await issueOneTime(context, {\n\t\tkind: 'magicLink',\n\t\tuserId: record.id,\n\t\taddress,\n\t\tttlMs: context.config.tokenTtlMs.magicLink,\n\t});\n\t// One live link per user: the ones sent before stop working.\n\tawait keepOnlyLatest(context, record.id, 'magicLink', secret);\n\treturn { token: secret, email: address, expiresAt, user: toUser(record) };\n}\n\n/** Spends a link's token, proves the e-mail, and finishes the sign-in. */\nasync function confirmLink(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tfinish: Finish,\n\tsecret: string,\n\twhere: string,\n\tdevice: DeviceHint,\n): Promise<SignInResult<AnyUser>> {\n\t// Spent first, whatever follows: a link is redeemed once, and a refused\n\t// one — stale, inactive, another type's — cannot be tried again.\n\tconst { token, user } = await redeemEmailToken(\n\t\tcontext,\n\t\ttype,\n\t\t'magicLink',\n\t\tsecret,\n\t\twhere,\n\t);\n\n\treturn finishEmailSignIn(context, type, finish, {\n\t\tuser,\n\t\ttoken,\n\t\twhere,\n\t\tnoun: 'token',\n\t\tdevice,\n\t\tamr: AMR.oneTimeCode,\n\t});\n}\n",
|
|
115
|
+
"/**\n * Signing in a user the application proved by its own means — an\n * invitation token it issued, a channel of its own: no credential checked\n * here, so nothing to count, nothing to send and nothing to spend.\n */\n\nimport { UserInactiveError } from '../errors/janus-error';\nimport type { At } from './at';\nimport type { ResolvedType } from './config';\nimport { type AnyUser, type Context, getRecord, refId } from './context';\nimport { deviceHint, reportNewDevice } from './devices';\nimport type { Finish } from './email-sign-in';\nimport type { ProvenSignInApi, SignInResult } from './types';\n\n/**\n * `signInProven` for one user type: the user read by id — `NOT_FOUND` for\n * nobody, as `get` — refused when inactive, then finished as every sign-in\n * is, by `secondFactor.finish`: a session, or a challenge for an active\n * factor.\n *\n * No throttle is counted and no count restarted, no token issued or spent,\n * no e-mail proved: the proof is the application's, and links and codes\n * already sent keep working.\n */\nexport function provenSignInFlows(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tat: At,\n\tfinish: Finish,\n): ProvenSignInApi<AnyUser, SignInResult<AnyUser>> {\n\treturn {\n\t\tasync signInProven(user, options) {\n\t\t\tconst where = at('signInProven');\n\t\t\tconst device = deviceHint(context, options, where);\n\t\t\tconst record = await getRecord(context, refId(user), type.name, where);\n\t\t\tif (!record.active) {\n\t\t\t\tthrow new UserInactiveError(`${where}: the user is inactive`, {\n\t\t\t\t\tuserId: record.id,\n\t\t\t\t\tuserType: type.name,\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst result = await finish(record, where, device);\n\t\t\tawait reportNewDevice(context, result);\n\t\t\treturn result;\n\t\t},\n\t};\n}\n",
|
|
116
|
+
"/** The options a browser needs to answer with a passkey, for a challenge already issued. */\n\nimport type { Context } from '../context';\nimport { requireSettings } from '../second-factor/factor';\nimport { type AssertionPurpose, assertionChallenge } from './challenge';\n\n/**\n * The JSON for `navigator.credentials.get`, allowing the user's passkeys —\n * or `null` when `janus()` was given no `passkeys`, or the user holds none.\n */\nexport async function assertionOptions(\n\tcontext: Context,\n\tuserId: string,\n\tpurpose: AssertionPurpose,\n\tsecret: string,\n\twhere: string,\n): Promise<Readonly<Record<string, unknown>> | null> {\n\tconst settings = context.config.passkeys;\n\tconst store = context.store.passkeys;\n\tif (settings === null || store === undefined) return null;\n\tconst held = await store.listUserPasskeys(userId);\n\tif (held.length === 0) return null;\n\tconst sealer = requireSettings(\n\t\tcontext,\n\t\twhere,\n\t\t'a passkey challenge is being made',\n\t).sealer;\n\treturn settings.verifier.authenticationOptions({\n\t\trp: settings.rp,\n\t\tchallenge: assertionChallenge(sealer, purpose, secret),\n\t\tallow: held.map((passkey) => ({\n\t\t\tcredentialId: passkey.credentialId,\n\t\t\ttransports: passkey.transports,\n\t\t})),\n\t});\n}\n",
|
|
117
|
+
"import { StoreConflict, TokenError } from '../../errors/janus-error';\nimport type { Context } from '../context';\nimport { derivedKey, keyedHash } from '../derived-keys';\nimport { CODE_ATTEMPTS, countInWindow } from '../one-time';\nimport type { UserRecord } from '../port/types';\nimport type { Sealer } from '../sealing';\nimport { hashSecret } from '../secrets';\n\n/**\n * The attempts at an app's code outside a sign-in — `regenerateRecoveryCodes`\n * and a step-up confirmed with the app — counted by the store, in one count\n * both share: the same {@link CODE_ATTEMPTS} a challenge takes, per user and\n * per window, so a stolen session cannot guess the app's code at leisure,\n * nor buy more guesses by switching from one to the other.\n *\n * Counted in an attempt window (`../one-time/window.ts`): a `secondFactor`\n * token named by a keyed hash of what the count is for, so nobody without\n * the sealing keys can name it — nor redeem it as a challenge.\n *\n * What it is for decides when it starts again: the **window**, a fixed\n * {@link APP_CODE_WINDOW_MS} slice of the clock, and the factor's\n * `lastStep`, which **any code accepted** moves — a regenerate that\n * succeeded starts the count again, and so does a sign-in finished with the\n * app.\n *\n * {@link countSignInCodeAttempt} is the same count for `signIn`'s second step\n * (`confirm`, `recover`), in a window of its own.\n *\n * Writing a password spends every `secondFactor` token of the user, this one\n * included. So a spent link **carries** its attempts on to the next — a\n * password written between guesses buys none.\n */\n\n/** How long the attempts of one window last: fifteen minutes. */\nexport const APP_CODE_WINDOW_MS = 15 * 60_000;\n\n/**\n * What the key is derived for: never the key that seals a secret itself.\n * Named after the first flow that counted, and kept: renamed, every count\n * in progress would start over.\n */\nconst PURPOSE = 'janus/second-factor/regenerate-attempts/v1';\n\n/**\n * What the key is derived for the sign-in's account count. A key of its own:\n * a stolen session guessing at regenerate never spends the sign-in's budget,\n * nor the other way round.\n */\nconst SIGN_IN_PURPOSE = 'janus/second-factor/sign-in-attempts/v1';\n\n/** A link's token hash: its secret is never given out, nor stored. */\nfunction linkHash(\n\tsealer: Sealer,\n\trecord: UserRecord,\n\tpurpose: string,\n\twindow: number,\n\tlink: number,\n): string {\n\tconst parts = [\n\t\trecord.id,\n\t\tString(window),\n\t\tString(record.secondFactor?.lastStep ?? ''),\n\t\tString(link),\n\t];\n\t// The first key is always held: resolveSealer names it from the keys.\n\tconst key = derivedKey(sealer, purpose) as Buffer;\n\treturn hashSecret(keyedHash(key, parts).toString('base64url'));\n}\n\n/** What one count is for: its key, window and limit. */\ninterface Counting {\n\treadonly purpose: string;\n\treadonly windowMs: number;\n\treadonly limit: number;\n}\n\n/**\n * Counts one attempt at the app's code — to regenerate the user's recovery\n * codes, or to confirm a step-up — before the code is compared, and\n * answers how many are left. Past the last one, it refuses — the right\n * code included — until the window ends, with `reason: 'throttled'` and\n * `retryAfter`, the seconds until it does, as a sign-in's throttle does.\n */\nexport function countAppCodeAttempt(\n\tcontext: Context,\n\tsealer: Sealer,\n\trecord: UserRecord,\n\twhere: string,\n): Promise<number> {\n\treturn countAccountAttempt(context, sealer, record, where, {\n\t\tpurpose: PURPOSE,\n\t\twindowMs: APP_CODE_WINDOW_MS,\n\t\tlimit: CODE_ATTEMPTS,\n\t});\n}\n\n/**\n * Counts one code tried at `signIn`'s second step — `confirm` or `recover`,\n * on any challenge of the account — before it is compared, in the account's\n * own window (`secondFactor.throttle`), apart from the app-code one. Refuses\n * past the limit as {@link countAppCodeAttempt} does. Nothing is counted\n * with the throttle off. A code accepted moves the factor's `lastStep`, and\n * the count starts again, as it does for the app-code window.\n */\nexport async function countSignInCodeAttempt(\n\tcontext: Context,\n\tsealer: Sealer,\n\trecord: UserRecord,\n\twhere: string,\n): Promise<void> {\n\tconst throttle = context.config.secondFactor?.throttle;\n\tif (throttle === null || throttle === undefined) return;\n\tawait countAccountAttempt(context, sealer, record, where, {\n\t\tpurpose: SIGN_IN_PURPOSE,\n\t\twindowMs: throttle.windowMs,\n\t\tlimit: throttle.attempts,\n\t});\n}\n\n/** `15-minute`, or whole seconds when the window is not whole minutes. */\nfunction windowLabel(windowMs: number): string {\n\treturn windowMs % 60_000 === 0\n\t\t? `${windowMs / 60_000}-minute`\n\t\t: `${Math.ceil(windowMs / 1000)}-second`;\n}\n\nasync function countAccountAttempt(\n\tcontext: Context,\n\tsealer: Sealer,\n\trecord: UserRecord,\n\twhere: string,\n\t{ purpose, windowMs, limit }: Counting,\n): Promise<number> {\n\tconst { attempts, endsAt } = await countInWindow(context, {\n\t\twindowMs,\n\t\tspent: 'carry',\n\t\tuserId: record.id,\n\t\tlinkHash: (window, link) => linkHash(sealer, record, purpose, window, link),\n\t\t// Gone right after it was stored: the user was deleted meanwhile.\n\t\tvanished: () =>\n\t\t\tnew StoreConflict(\n\t\t\t\t'version',\n\t\t\t\t`${where}: the user changed while the code was checked — read it again and retry`,\n\t\t\t\t{\n\t\t\t\t\tuserId: record.id,\n\t\t\t\t\texpectedVersion: record.version,\n\t\t\t\t\toperation: where,\n\t\t\t\t},\n\t\t\t),\n\t});\n\tif (attempts > limit) {\n\t\tthrow new TokenError(\n\t\t\t'CODE_INVALID',\n\t\t\t`${where}: too many codes tried — wait for the next ${windowLabel(windowMs)} window`,\n\t\t\t{\n\t\t\t\toperation: where,\n\t\t\t\tuserId: record.id,\n\t\t\t\tuserType: record.type,\n\t\t\t\tattemptsLeft: 0,\n\t\t\t\treason: 'throttled',\n\t\t\t\tretryAfter: Math.max(\n\t\t\t\t\t1,\n\t\t\t\t\tMath.ceil((endsAt - context.clock.now().getTime()) / 1000),\n\t\t\t\t),\n\t\t\t},\n\t\t);\n\t}\n\treturn limit - attempts;\n}\n",
|
|
118
|
+
"import { SecondFactorError, UserInactiveError } from '../../errors/janus-error';\nimport type { ResolvedType } from '../config';\nimport { type Context, findRecord } from '../context';\nimport {\n\tburnOneTime,\n\tcodeInvalid,\n\tcountCodeAttempt,\n\tspendOneTime,\n\tunknownChallenge,\n} from '../one-time';\nimport type { SecondFactorRecord, UserRecord } from '../port/types';\nimport { mergeAmr } from '../sessions/amr';\nimport { countSignInCodeAttempt } from './app-code-attempts';\nimport { isActive, requireSettings, type Settings } from './factor';\n\n/**\n * What redeeming `signIn`'s challenge takes before any code is compared —\n * with an app's code (`confirm`) or a recovery code (`recover`): the attempt\n * counted, then the user read, and refused when gone, inactive or without an\n * active factor any more.\n */\n\n/** A challenge counted, and the user it waits for, whose factor is active. */\nexport interface OpenedChallenge {\n\treadonly configured: Settings;\n\treadonly secret: string;\n\treadonly attemptsLeft: number;\n\t/** What the first factor proved, as the challenge was issued with. */\n\treadonly firstFactor: readonly string[];\n\treadonly record: UserRecord & {\n\t\treadonly secondFactor: SecondFactorRecord & { readonly confirmedAt: Date };\n\t};\n}\n\n/** Spends a second-factor challenge, refusing it when this call did not. */\nexport const spendChallenge = (\n\tcontext: Context,\n\tchallenge: string,\n\twhere: string,\n) => spendOneTime(context, challenge, 'secondFactor', where, 'challenge');\n\n/**\n * Counts one attempt at the challenge, then reads its user: refused for a\n * user gone, of another type, inactive, or whose factor was disabled since.\n */\nexport async function openChallenge(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tchallenge: string,\n\twhere: string,\n): Promise<OpenedChallenge> {\n\tconst configured = requireSettings(\n\t\tcontext,\n\t\twhere,\n\t\t'a second factor is being confirmed',\n\t);\n\tconst secret = String(challenge);\n\n\tconst { token, attemptsLeft } = await countCodeAttempt(\n\t\tcontext,\n\t\tsecret,\n\t\t'secondFactor',\n\t\twhere,\n\t\ttype.name,\n\t);\n\n\t// A user gone since, or of another type, is as good as no challenge.\n\tconst record = await findRecord(context, token.userId, type.name);\n\tif (record === null) {\n\t\tthrow await unknownChallenge(context, token, secret, where);\n\t}\n\tif (!record.active) {\n\t\tawait spendChallenge(context, secret, where);\n\t\tthrow new UserInactiveError(`${where}: the user is inactive`, {\n\t\t\tuserId: record.id,\n\t\t\tuserType: type.name,\n\t\t});\n\t}\n\tconst factor = record.secondFactor;\n\tif (!isActive(factor)) {\n\t\tawait spendChallenge(context, secret, where);\n\t\tthrow new SecondFactorError(\n\t\t\t'SECOND_FACTOR_NOT_ENROLLED',\n\t\t\t`${where}: the user no longer has a second factor — sign in again`,\n\t\t\t{ operation: where, userId: record.id, userType: type.name },\n\t\t);\n\t}\n\treturn {\n\t\tconfigured,\n\t\tsecret,\n\t\tattemptsLeft,\n\t\tfirstFactor: [...(token.amr ?? [])],\n\t\trecord: { ...record, secondFactor: factor },\n\t};\n}\n\n/**\n * Counts one **code** tried in the account's own window, after the challenge's\n * count: a refusal here spends nothing — the challenge stays as it was, bar\n * the attempt it counted. Only the paths that compare a code call it: a\n * passkey assertion cannot be guessed, so it is never counted nor refused.\n */\nexport const countAccountCode = (\n\tcontext: Context,\n\topened: OpenedChallenge,\n\twhere: string,\n) =>\n\tcountSignInCodeAttempt(\n\t\tcontext,\n\t\topened.configured.sealer,\n\t\topened.record,\n\t\twhere,\n\t);\n\n/** A code that does not match: on the last attempt, the challenge is spent. */\nexport async function refuseCode(\n\tcontext: Context,\n\ttype: ResolvedType,\n\topened: OpenedChallenge,\n\twhere: string,\n): Promise<never> {\n\tif (opened.attemptsLeft === 0) {\n\t\tawait burnOneTime(context, opened.secret, 'secondFactor');\n\t}\n\tthrow codeInvalid(where, opened.record.id, type.name, opened.attemptsLeft);\n}\n\n/** A session's `amr` once the second factor is proved: the first factor's methods and the second's. */\nexport const secondFactorAmr = (\n\topened: Pick<OpenedChallenge, 'firstFactor'>,\n\tsecond: readonly string[],\n): string[] => mergeAmr(opened.firstFactor, second);\n",
|
|
119
|
+
"import type { At } from '../at';\nimport type { ResolvedType } from '../config';\nimport type { AnyUser, Context } from '../context';\nimport { deviceHint, reportNewDevice } from '../devices';\nimport { issueOneTime } from '../one-time';\nimport { assertionOptions } from '../passkeys/assertion-options';\nimport type { UserRecord } from '../port/types';\nimport { openSession } from '../sessions';\nimport { AMR } from '../sessions/amr';\nimport { restartSignInCount } from '../sign-in-attempts';\nimport type { SecondFactorRequired, SignedIn, SignInOptions } from '../types';\nimport { acceptCode, requireSettings } from './factor';\nimport {\n\tcountAccountCode,\n\topenChallenge,\n\trefuseCode,\n\tsecondFactorAmr,\n\tspendChallenge,\n} from './redeem';\n\n/**\n * The challenge `signIn` answers instead of a session, and the code that\n * redeems it. **Only the challenge's hash is stored**, like a session\n * token's.\n */\nexport function challengeFlows(context: Context, type: ResolvedType, at: At) {\n\treturn {\n\t\tasync issue(\n\t\t\trecord: UserRecord,\n\t\t\twhere: string,\n\t\t\tfirstFactor: readonly string[] = [],\n\t\t): Promise<SecondFactorRequired> {\n\t\t\tconst configured = requireSettings(\n\t\t\t\tcontext,\n\t\t\t\twhere,\n\t\t\t\t\"the user's second factor is active\",\n\t\t\t);\n\t\t\tconst { secret, expiresAt } = await issueOneTime(context, {\n\t\t\t\tkind: 'secondFactor',\n\t\t\t\tuserId: record.id,\n\t\t\t\t// Nothing is sent for a challenge: there is no address.\n\t\t\t\taddress: '',\n\t\t\t\t// What the first factor proved, for the session to open with.\n\t\t\t\tamr: firstFactor,\n\t\t\t\tttlMs: configured.challengeTtlMs,\n\t\t\t});\n\t\t\tconst passkeyOptions = await assertionOptions(\n\t\t\t\tcontext,\n\t\t\t\trecord.id,\n\t\t\t\t'secondFactor',\n\t\t\t\tsecret,\n\t\t\t\twhere,\n\t\t\t);\n\t\t\treturn {\n\t\t\t\tstatus: 'secondFactor',\n\t\t\t\tchallenge: secret,\n\t\t\t\texpiresAt,\n\t\t\t\tuserId: record.id,\n\t\t\t\tmethods: passkeyOptions === null ? ['totp'] : ['totp', 'passkey'],\n\t\t\t\t...(passkeyOptions === null ? {} : { passkeyOptions }),\n\t\t\t};\n\t\t},\n\n\t\tasync confirm(\n\t\t\tchallenge: string,\n\t\t\tcode: string,\n\t\t\toptions?: SignInOptions,\n\t\t): Promise<SignedIn<AnyUser>> {\n\t\t\treturn confirmChallenge(context, type, challenge, code, at, options);\n\t\t},\n\t};\n}\n\n/**\n * Redeems a challenge with its code: counted first, then refused for a user\n * gone, inactive or without a factor any more, then compared — and the factor\n * written under the version read before the session opens.\n */\nasync function confirmChallenge(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tchallenge: string,\n\tcode: string,\n\tat: At,\n\toptions: SignInOptions | undefined,\n): Promise<SignedIn<AnyUser>> {\n\tconst where = at('secondFactor.confirm');\n\tconst device = deviceHint(context, options, where);\n\tconst opened = await openChallenge(context, type, challenge, where);\n\tawait countAccountCode(context, opened, where);\n\tconst { record } = opened;\n\n\tconst now = context.clock.now();\n\tconst accepted = acceptCode(\n\t\topened.configured,\n\t\trecord,\n\t\trecord.secondFactor,\n\t\tString(code),\n\t\tnow,\n\t\twhere,\n\t);\n\tif (accepted === null) return refuseCode(context, type, opened, where);\n\n\t// Read, decided, then written under the version read: of two codes\n\t// accepted at once, the second write is VERSION_CONFLICT.\n\tconst written = await context.store.users.updateUser(\n\t\trecord.id,\n\t\t{ secondFactor: accepted, updatedAt: now },\n\t\trecord.version,\n\t);\n\tawait spendChallenge(context, opened.secret, where);\n\t// The sign-in is complete: the password's count starts again.\n\tawait restartSignInCount(context, type, written, where);\n\tconst signedIn = await openSession(\n\t\tcontext,\n\t\ttype,\n\t\twritten,\n\t\tdevice,\n\t\tfalse,\n\t\tsecondFactorAmr(opened, AMR.appCode),\n\t);\n\tawait reportNewDevice(context, signedIn);\n\treturn signedIn;\n}\n",
|
|
120
|
+
"import type { ResolvedType } from '../config';\nimport { type Context, getRecord, idOf } from '../context';\nimport type { UserRef } from '../types';\nimport { isActive } from './factor';\n\n/**\n * How many recovery codes the user still holds, read from their record: the\n * count `secondFactor.recover` answers, for whoever did not see that answer —\n * a `user.recoveryCodeUsed` listener, a security settings page.\n *\n * `null` when the user has no active factor: none, or one still waiting for\n * its first code, holds no codes to count. An unknown id, or a user of\n * another type, is `NOT_FOUND`; a store that fails throws. Writes nothing.\n */\nexport async function recoveryCodesLeftOf(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tuser: UserRef,\n\twhere: string,\n): Promise<number | null> {\n\tconst record = await getRecord(context, idOf(user), type.name, where);\n\tconst factor = record.secondFactor;\n\treturn isActive(factor) ? factor.recoveryCodes.length : null;\n}\n",
|
|
121
|
+
"import { randomInt, timingSafeEqual } from 'node:crypto';\nimport { derivedKey, keyedHash } from '../derived-keys';\nimport type { Sealer } from '../sealing';\n\n/**\n * A second factor's recovery codes: minted, hashed with a key derived from\n * the sealing keys, and found again.\n *\n * A code is **ten characters of Crockford's base32** — digits and lower-case\n * letters without `i`, `l`, `o` and `u` — shown as `xxxxx-xxxxx`: fifty bits,\n * typable off a sheet of paper. Only its hash is stored, **keyed** rather\n * than a bare `sha256`, like a sign-in code's: a dump of the users, without\n * the keys, cannot check a guess. The hash is `v1.<key id>.<mac>`, so it\n * names its key as a sealed secret does, and a rotation keeps it readable.\n * The user's id is part of what is hashed: a hash copied onto another user\n * matches nothing.\n */\n\n/** How many codes `activate` and `regenerateRecoveryCodes` answer. */\nexport const RECOVERY_CODES = 10;\n\nconst ALPHABET = '0123456789abcdefghjkmnpqrstvwxyz';\nconst LENGTH = 10;\nconst SHAPE = /^[0-9a-hjkmnp-tv-z]{10}$/;\n\n/** What the key is derived for: never the key that seals a secret itself. */\nconst PURPOSE = 'janus/second-factor/recovery-codes/v1';\n\n/** Fresh codes, as the user is shown them once: `7k2mq-x9d4c`. */\nexport function mintRecoveryCodes(): string[] {\n\treturn Array.from({ length: RECOVERY_CODES }, () => {\n\t\tlet code = '';\n\t\tfor (let at = 0; at < LENGTH; at += 1) {\n\t\t\tcode += ALPHABET[randomInt(ALPHABET.length)];\n\t\t}\n\t\treturn `${code.slice(0, 5)}-${code.slice(5)}`;\n\t});\n}\n\n/**\n * A code as typed, read as the one it could be — case, spaces and dashes\n * ignored, `o` read as `0`, `i` and `l` as `1` — or `null` for one that\n * cannot be a code at all.\n */\nexport function readRecoveryCode(typed: string): string | null {\n\tconst code = typed\n\t\t.toLowerCase()\n\t\t.replace(/[\\s-]/g, '')\n\t\t.replace(/o/g, '0')\n\t\t.replace(/[il]/g, '1');\n\treturn SHAPE.test(code) ? code : null;\n}\n\n/** The key a sealing key lends the codes, derived once per key. */\nconst macKey = (sealer: Sealer, keyId: string): Buffer | undefined =>\n\tderivedKey(sealer, PURPOSE, keyId);\n\nconst mac = (key: Buffer, userId: string, code: string): Buffer =>\n\tkeyedHash(key, [userId, code]);\n\n/** A code's keyed hash, under the first key, bound to the user's id. */\nexport function hashRecoveryCode(\n\tsealer: Sealer,\n\tuserId: string,\n\tcode: string,\n): string {\n\tconst read = readRecoveryCode(code) ?? code;\n\tconst key = macKey(sealer, sealer.sealWith) as Buffer;\n\treturn `v1.${sealer.sealWith}.${mac(key, userId, read).toString('base64url')}`;\n}\n\n/**\n * Where `typed` is among the user's hashes, or `-1`. Every hash is compared,\n * in constant time, whether or not one matched already.\n *\n * A hash naming a key the sealer no longer holds is a **wiring** mistake, a\n * bare `TypeError`, as for a sealed secret: never a `CODE_INVALID` that would\n * blame the user.\n */\nexport function findRecoveryCode(\n\tsealer: Sealer,\n\tuserId: string,\n\thashes: readonly string[],\n\ttyped: string,\n\twhere: string,\n): number {\n\tconst code = readRecoveryCode(typed);\n\tlet found = -1;\n\thashes.forEach((hash, index) => {\n\t\tconst [version, keyId, body, ...rest] = hash.split('.');\n\t\tif (\n\t\t\tversion !== 'v1' ||\n\t\t\tkeyId === undefined ||\n\t\t\tbody === undefined ||\n\t\t\trest.length > 0\n\t\t) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${where}: a stored recovery code is not a keyed hash`,\n\t\t\t);\n\t\t}\n\t\tconst key = macKey(sealer, keyId);\n\t\tif (key === undefined) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${where}: a recovery code is hashed with the key \"${keyId}\", which secondFactor.keys no longer holds — keep a key until no secret or recovery code uses it`,\n\t\t\t);\n\t\t}\n\t\tif (code === null) return;\n\t\tconst held = Buffer.from(body, 'base64url');\n\t\tconst given = mac(key, userId, code);\n\t\tif (held.length === given.length && timingSafeEqual(held, given)) {\n\t\t\tfound = found === -1 ? index : found;\n\t\t}\n\t});\n\treturn found;\n}\n",
|
|
122
|
+
"import { SecondFactorError } from '../../errors/janus-error';\nimport type { ResolvedType } from '../config';\nimport type { UserRecord } from '../port/types';\n\n/** The refusal of a lifecycle step, naming the user and its type. */\nexport const refusal = (\n\ttype: ResolvedType,\n\tcode: 'SECOND_FACTOR_NOT_ENROLLED' | 'SECOND_FACTOR_ACTIVE',\n\tmessage: string,\n\twhere: string,\n\trecord: UserRecord,\n) =>\n\tnew SecondFactorError(code, `${where}: ${message}`, {\n\t\toperation: where,\n\t\tuserId: record.id,\n\t\tuserType: type.name,\n\t});\n",
|
|
123
|
+
"import type { ResolvedType } from '../config';\nimport { type AnyUser, type Context, toUser, writeUser } from '../context';\nimport { emit } from '../events';\nimport { codeInvalid } from '../one-time';\nimport { sweepWaitingFactorPasskeys } from '../passkeys/remove-all';\nimport type { RecoveryCodesIssued, UserRef, WriteOptions } from '../types';\nimport {\n\tacceptCode,\n\tassertEmailProved,\n\tisActive,\n\trequireSettings,\n} from './factor';\nimport { hashRecoveryCode, mintRecoveryCodes } from './recovery-codes';\nimport { refusal } from './refusal';\n\n/**\n * Confirms a waiting factor with its first code: from then on, it is asked\n * for. Its recovery codes are written in the same write, and answered once.\n */\nexport async function activateFactor(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tuser: UserRef,\n\tcode: string,\n\toptions: WriteOptions | undefined,\n\twhere: string,\n): Promise<RecoveryCodesIssued<AnyUser>> {\n\tconst configured = requireSettings(\n\t\tcontext,\n\t\twhere,\n\t\t'a second factor is being activated',\n\t);\n\tconst recoveryCodes = mintRecoveryCodes();\n\n\tawait sweepWaitingFactorPasskeys(context, type, user, where);\n\n\tconst written = await writeUser(\n\t\tcontext,\n\t\tuser,\n\t\ttype,\n\t\toptions,\n\t\twhere,\n\t\t(record, now) => {\n\t\t\tassertEmailProved(type, record, where, 'a second factor is activated');\n\t\t\tconst factor = record.secondFactor;\n\t\t\tif (factor === null) {\n\t\t\t\tthrow refusal(\n\t\t\t\t\ttype,\n\t\t\t\t\t'SECOND_FACTOR_NOT_ENROLLED',\n\t\t\t\t\t'the user has no second factor waiting — call enroll first',\n\t\t\t\t\twhere,\n\t\t\t\t\trecord,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (isActive(factor)) {\n\t\t\t\tthrow refusal(\n\t\t\t\t\ttype,\n\t\t\t\t\t'SECOND_FACTOR_ACTIVE',\n\t\t\t\t\t\"the user's second factor is already active\",\n\t\t\t\t\twhere,\n\t\t\t\t\trecord,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst accepted = acceptCode(\n\t\t\t\tconfigured,\n\t\t\t\trecord,\n\t\t\t\tfactor,\n\t\t\t\tString(code),\n\t\t\t\tnow,\n\t\t\t\twhere,\n\t\t\t);\n\t\t\tif (accepted === null) throw codeInvalid(where, record.id, type.name);\n\t\t\treturn {\n\t\t\t\tsecondFactor: {\n\t\t\t\t\t...accepted,\n\t\t\t\t\tconfirmedAt: now,\n\t\t\t\t\trecoveryCodes: recoveryCodes.map((one) =>\n\t\t\t\t\t\thashRecoveryCode(configured.sealer, record.id, one),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t);\n\t// After the write, the flow's last step: the factor is asked for from now.\n\tawait emit(context, 'user.secondFactorEnabled', written, written.updatedAt);\n\treturn { user: toUser(written), recoveryCodes };\n}\n",
|
|
124
|
+
"import type { ResolvedType } from '../config';\nimport { type AnyUser, type Context, toUser, writeUser } from '../context';\nimport { emit } from '../events';\nimport { removeAllPasskeys } from '../passkeys/remove-all';\nimport type { UserRef, WriteOptions } from '../types';\nimport { isActive } from './factor';\n\n/**\n * Removes the factor, active or waiting. Reported only when an active one\n * went: a user who had none, or whose factor never received its first code,\n * was never asked for one, and still is not.\n */\nexport async function disableFactor(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tuser: UserRef,\n\toptions: WriteOptions | undefined,\n\twhere: string,\n): Promise<AnyUser> {\n\tlet wasActive = false;\n\tconst written = await writeUser(\n\t\tcontext,\n\t\tuser,\n\t\ttype,\n\t\toptions,\n\t\twhere,\n\t\t(record) => {\n\t\t\twasActive = isActive(record.secondFactor);\n\t\t\treturn { secondFactor: null };\n\t\t},\n\t);\n\tif (wasActive) {\n\t\tawait emit(\n\t\t\tcontext,\n\t\t\t'user.secondFactorDisabled',\n\t\t\twritten,\n\t\t\twritten.updatedAt,\n\t\t);\n\t}\n\t// Whether or not a factor was active: a retry after an outage here still\n\t// finds the passkeys a first call did not get to.\n\t// With `passkeys.firstFactor` a passkey signs in on its own: it stays.\n\tif (context.config.passkeys?.firstFactor !== true) {\n\t\tawait removeAllPasskeys(context, written, written.updatedAt);\n\t}\n\treturn toUser(written);\n}\n",
|
|
125
|
+
"import type { ResolvedType } from '../config';\nimport { type Context, emailOf, writeUser } from '../context';\nimport type { UserRecord } from '../port/types';\nimport { seal } from '../sealing';\nimport { mintTotpSecret, otpauthUri } from '../totp';\nimport type { SecondFactorEnrolment, UserRef, WriteOptions } from '../types';\nimport { assertEmailProved, isActive, requireSettings } from './factor';\nimport { refusal } from './refusal';\n\n/** Writes a factor waiting for its first code, and answers the secret to show. */\nexport async function enrollFactor(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tuser: UserRef,\n\toptions: WriteOptions | undefined,\n\twhere: string,\n): Promise<SecondFactorEnrolment> {\n\tconst configured = requireSettings(\n\t\tcontext,\n\t\twhere,\n\t\t'a second factor is being enrolled',\n\t);\n\tconst secret = mintTotpSecret();\n\n\tconst written = await writeUser(\n\t\tcontext,\n\t\tuser,\n\t\ttype,\n\t\toptions,\n\t\twhere,\n\t\t(record) => {\n\t\t\tif (isActive(record.secondFactor)) {\n\t\t\t\tthrow refusal(\n\t\t\t\t\ttype,\n\t\t\t\t\t'SECOND_FACTOR_ACTIVE',\n\t\t\t\t\t\"the user's second factor is active — disable it first\",\n\t\t\t\t\twhere,\n\t\t\t\t\trecord,\n\t\t\t\t);\n\t\t\t}\n\t\t\tassertEmailProved(type, record, where, 'a second factor is enrolled');\n\t\t\taccountOf(type, record, where);\n\t\t\treturn {\n\t\t\t\tsecondFactor: {\n\t\t\t\t\tmethod: 'totp',\n\t\t\t\t\tsecret: seal(configured.sealer, secret, record.id),\n\t\t\t\t\tconfirmedAt: null,\n\t\t\t\t\tlastStep: null,\n\t\t\t\t\trecoveryCodes: [],\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t);\n\n\treturn {\n\t\tsecret,\n\t\turi: otpauthUri(configured.issuer, accountOf(type, written, where), secret),\n\t};\n}\n\n/**\n * The account name the authenticator app shows: the login a password type\n * signs in with, else the e-mail of a passwordless type.\n */\nfunction accountOf(\n\ttype: ResolvedType,\n\trecord: UserRecord,\n\twhere: string,\n): string {\n\tif (type.password !== null) {\n\t\treturn String(record.fields[type.password.login]);\n\t}\n\tconst email = emailOf(type, record.fields);\n\tif (email === null) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: the ${type.name} type has no password and the user has no e-mail, so a second factor has no account name`,\n\t\t);\n\t}\n\treturn email;\n}\n",
|
|
126
|
+
"import type { ResolvedType } from '../config';\nimport { type AnyUser, type Context, toUser, writeUser } from '../context';\nimport { emit } from '../events';\nimport { codeInvalid } from '../one-time';\nimport type { RecoveryCodesIssued, UserRef, WriteOptions } from '../types';\nimport { countAppCodeAttempt } from './app-code-attempts';\nimport { acceptCode, isActive, requireSettings } from './factor';\nimport { hashRecoveryCode, mintRecoveryCodes } from './recovery-codes';\nimport { refusal } from './refusal';\n\n/**\n * Replaces a user's recovery codes with new ones, and answers them once: the\n * old ones, used or not, stop working. Takes a **fresh code from the app** —\n * whoever holds a session alone cannot mint codes that outlive it — and\n * spends it, as a code accepted anywhere else is spent. The attempts are\n * counted first, five per user per window, as a challenge's are.\n */\nexport async function regenerateRecoveryCodes(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tuser: UserRef,\n\tcode: string,\n\toptions: WriteOptions | undefined,\n\twhere: string,\n): Promise<RecoveryCodesIssued<AnyUser>> {\n\tconst configured = requireSettings(\n\t\tcontext,\n\t\twhere,\n\t\t'recovery codes are being regenerated',\n\t);\n\tconst recoveryCodes = mintRecoveryCodes();\n\n\tconst written = await writeUser(\n\t\tcontext,\n\t\tuser,\n\t\ttype,\n\t\toptions,\n\t\twhere,\n\t\tasync (record, now) => {\n\t\t\tconst factor = record.secondFactor;\n\t\t\tif (!isActive(factor)) {\n\t\t\t\tthrow refusal(\n\t\t\t\t\ttype,\n\t\t\t\t\t'SECOND_FACTOR_NOT_ENROLLED',\n\t\t\t\t\t'the user has no active second factor — recovery codes come with one',\n\t\t\t\t\twhere,\n\t\t\t\t\trecord,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst left = await countAppCodeAttempt(\n\t\t\t\tcontext,\n\t\t\t\tconfigured.sealer,\n\t\t\t\trecord,\n\t\t\t\twhere,\n\t\t\t);\n\t\t\tconst accepted = acceptCode(\n\t\t\t\tconfigured,\n\t\t\t\trecord,\n\t\t\t\tfactor,\n\t\t\t\tString(code),\n\t\t\t\tnow,\n\t\t\t\twhere,\n\t\t\t);\n\t\t\tif (accepted === null) {\n\t\t\t\tthrow codeInvalid(where, record.id, type.name, left);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tsecondFactor: {\n\t\t\t\t\t...accepted,\n\t\t\t\t\trecoveryCodes: recoveryCodes.map((one) =>\n\t\t\t\t\t\thashRecoveryCode(configured.sealer, record.id, one),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t);\n\tawait emit(\n\t\tcontext,\n\t\t'user.recoveryCodesRegenerated',\n\t\twritten,\n\t\twritten.updatedAt,\n\t);\n\treturn { user: toUser(written), recoveryCodes };\n}\n",
|
|
127
|
+
"import type { ResolvedType } from '../config';\nimport { type AnyUser, type Context, toUser, writeUser } from '../context';\nimport { codeInvalid } from '../one-time';\nimport type { SpentRecoveryCode, UserRef, WriteOptions } from '../types';\nimport { countAppCodeAttempt } from './app-code-attempts';\nimport { isActive, requireSettings } from './factor';\nimport { findRecoveryCode } from './recovery-codes';\nimport { refusal } from './refusal';\n\n/**\n * Spends one of a user's recovery codes outside a sign-in — to turn the\n * factor off from a session that already stands. No challenge, no session,\n * no event: it is not a sign-in.\n *\n * The attempts are counted first, in the count `regenerateRecoveryCodes`\n * and a step-up confirmed with the app share: five per user per window. A\n * code that matches is removed in one write under the version read, as\n * `recover` removes it.\n */\nexport async function spendRecoveryCode(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tuser: UserRef,\n\tcode: string,\n\toptions: WriteOptions | undefined,\n\twhere: string,\n): Promise<SpentRecoveryCode<AnyUser>> {\n\tconst configured = requireSettings(\n\t\tcontext,\n\t\twhere,\n\t\t'a recovery code is being spent',\n\t);\n\tlet left = 0;\n\tconst written = await writeUser(\n\t\tcontext,\n\t\tuser,\n\t\ttype,\n\t\toptions,\n\t\twhere,\n\t\tasync (record) => {\n\t\t\tconst factor = record.secondFactor;\n\t\t\tif (!isActive(factor)) {\n\t\t\t\tthrow refusal(\n\t\t\t\t\ttype,\n\t\t\t\t\t'SECOND_FACTOR_NOT_ENROLLED',\n\t\t\t\t\t'the user has no active second factor — recovery codes come with one',\n\t\t\t\t\twhere,\n\t\t\t\t\trecord,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst attemptsLeft = await countAppCodeAttempt(\n\t\t\t\tcontext,\n\t\t\t\tconfigured.sealer,\n\t\t\t\trecord,\n\t\t\t\twhere,\n\t\t\t);\n\t\t\tconst found = findRecoveryCode(\n\t\t\t\tconfigured.sealer,\n\t\t\t\trecord.id,\n\t\t\t\tfactor.recoveryCodes,\n\t\t\t\tString(code),\n\t\t\t\twhere,\n\t\t\t);\n\t\t\tif (found === -1) {\n\t\t\t\tthrow codeInvalid(where, record.id, type.name, attemptsLeft);\n\t\t\t}\n\t\t\tconst recoveryCodes = factor.recoveryCodes.filter(\n\t\t\t\t(_, index) => index !== found,\n\t\t\t);\n\t\t\tleft = recoveryCodes.length;\n\t\t\treturn { secondFactor: { ...factor, recoveryCodes } };\n\t\t},\n\t);\n\treturn { user: toUser(written), recoveryCodesLeft: left };\n}\n",
|
|
128
|
+
"import type { At } from '../at';\nimport type { ResolvedType } from '../config';\nimport type { AnyUser, Context } from '../context';\nimport type { SecondFactorApi } from '../types';\nimport { activateFactor } from './activate';\nimport { disableFactor } from './disable';\nimport { enrollFactor } from './enroll';\nimport { regenerateRecoveryCodes } from './regenerate';\nimport { spendRecoveryCode } from './spend-recovery-code';\n\ntype Lifecycle = Pick<\n\tSecondFactorApi<AnyUser>['secondFactor'],\n\t| 'enroll'\n\t| 'activate'\n\t| 'regenerateRecoveryCodes'\n\t| 'spendRecoveryCode'\n\t| 'disable'\n>;\n\n/**\n * Enrolling, activating, regenerating its recovery codes and disabling a\n * factor: each one write under a version. This module only names each call;\n * each step is a module of its own — `./enroll`, `./activate`,\n * `./regenerate`, `./disable`.\n */\nexport function lifecycleFlows(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tat: At,\n): Lifecycle {\n\treturn {\n\t\tasync enroll(user, options) {\n\t\t\treturn enrollFactor(\n\t\t\t\tcontext,\n\t\t\t\ttype,\n\t\t\t\tuser,\n\t\t\t\toptions,\n\t\t\t\tat('secondFactor.enroll'),\n\t\t\t);\n\t\t},\n\n\t\tasync activate(user, code, options) {\n\t\t\treturn activateFactor(\n\t\t\t\tcontext,\n\t\t\t\ttype,\n\t\t\t\tuser,\n\t\t\t\tcode,\n\t\t\t\toptions,\n\t\t\t\tat('secondFactor.activate'),\n\t\t\t);\n\t\t},\n\n\t\tasync regenerateRecoveryCodes(user, code, options) {\n\t\t\treturn regenerateRecoveryCodes(\n\t\t\t\tcontext,\n\t\t\t\ttype,\n\t\t\t\tuser,\n\t\t\t\tcode,\n\t\t\t\toptions,\n\t\t\t\tat('secondFactor.regenerateRecoveryCodes'),\n\t\t\t);\n\t\t},\n\n\t\tasync spendRecoveryCode(user, code, options) {\n\t\t\treturn spendRecoveryCode(\n\t\t\t\tcontext,\n\t\t\t\ttype,\n\t\t\t\tuser,\n\t\t\t\tcode,\n\t\t\t\toptions,\n\t\t\t\tat('secondFactor.spendRecoveryCode'),\n\t\t\t);\n\t\t},\n\n\t\tasync disable(user, options) {\n\t\t\treturn disableFactor(\n\t\t\t\tcontext,\n\t\t\t\ttype,\n\t\t\t\tuser,\n\t\t\t\toptions,\n\t\t\t\tat('secondFactor.disable'),\n\t\t\t);\n\t\t},\n\t};\n}\n",
|
|
129
|
+
"import type { At } from '../at';\nimport type { ResolvedType } from '../config';\nimport type { AnyUser, Context } from '../context';\nimport { deviceHint, reportNewDevice } from '../devices';\nimport { acceptAssertion } from '../passkeys/assert';\nimport { requirePasskeys } from '../passkeys/wiring';\nimport { openSession } from '../sessions';\nimport { AMR } from '../sessions/amr';\nimport { restartSignInCount } from '../sign-in-attempts';\nimport type { SignedIn, SignInOptions } from '../types';\nimport {\n\topenChallenge,\n\trefuseCode,\n\tsecondFactorAmr,\n\tspendChallenge,\n} from './redeem';\n\n/**\n * Redeems `signIn`'s challenge with a passkey instead of a code.\n *\n * The challenge is counted and its user checked exactly as for `confirm` —\n * the same five attempts, whatever the method — and an assertion that does\n * not verify is refused as a code that does not match. The passkey's use is\n * recorded before the challenge is spent, as `confirm` writes the factor\n * first: an assertion replayed on the same counter finds it moved. The user\n * record is not written, so there is no version to race on; the spent\n * challenge is what lets only one call open a session.\n */\nexport async function confirmWithPasskey(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tgiven: {\n\t\treadonly challenge: string;\n\t\treadonly assertion: unknown;\n\t\treadonly options: SignInOptions | undefined;\n\t},\n\tat: At,\n): Promise<SignedIn<AnyUser>> {\n\tconst where = at('secondFactor.confirmPasskey');\n\t// Before any attempt is counted: a wiring mistake costs the user nothing.\n\trequirePasskeys(context, where);\n\tconst device = deviceHint(context, given.options, where);\n\tconst opened = await openChallenge(context, type, given.challenge, where);\n\tconst { record } = opened;\n\n\tconst accepted = await acceptAssertion(\n\t\tcontext,\n\t\trecord,\n\t\t{\n\t\t\tassertion: given.assertion,\n\t\t\tpurpose: 'secondFactor',\n\t\t\tsecret: opened.secret,\n\t\t},\n\t\twhere,\n\t);\n\tif (!accepted) return refuseCode(context, type, opened, where);\n\n\tawait spendChallenge(context, opened.secret, where);\n\t// The sign-in is complete: the password's count starts again.\n\tawait restartSignInCount(context, type, record, where);\n\tconst signedIn = await openSession(\n\t\tcontext,\n\t\ttype,\n\t\trecord,\n\t\tdevice,\n\t\tfalse,\n\t\tsecondFactorAmr(opened, AMR.passkeySecondFactor),\n\t);\n\tawait reportNewDevice(context, signedIn);\n\treturn signedIn;\n}\n",
|
|
130
|
+
"import type { At } from '../at';\nimport type { ResolvedType } from '../config';\nimport type { AnyUser, Context } from '../context';\nimport { deviceHint, reportNewDevice } from '../devices';\nimport { emit } from '../events';\nimport { openSession } from '../sessions';\nimport { AMR } from '../sessions/amr';\nimport { restartSignInCount } from '../sign-in-attempts';\nimport type { RecoveredSignIn, SignedIn, SignInOptions } from '../types';\nimport { findRecoveryCode } from './recovery-codes';\nimport {\n\tcountAccountCode,\n\topenChallenge,\n\trefuseCode,\n\tsecondFactorAmr,\n\tspendChallenge,\n} from './redeem';\n\n/**\n * Redeems `signIn`'s challenge with a recovery code instead of an app's\n * code: for a user whose phone is gone.\n *\n * The challenge is counted and its user checked exactly as for `confirm`.\n * A code that matches is **removed** — its hash dropped from the factor — in\n * one write under the version read, as `confirm` writes its last step: of\n * two sign-ins spending the same code at once, the second write is\n * `VERSION_CONFLICT`, and that sign-in opens nothing.\n */\nexport async function recoverWithCode(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tgiven: {\n\t\treadonly challenge: string;\n\t\treadonly code: string;\n\t\treadonly options: SignInOptions | undefined;\n\t},\n\tat: At,\n): Promise<RecoveredSignIn<AnyUser>> {\n\tconst where = at('secondFactor.recover');\n\tconst device = deviceHint(context, given.options, where);\n\tconst { code } = given;\n\tconst opened = await openChallenge(context, type, given.challenge, where);\n\tawait countAccountCode(context, opened, where);\n\tconst { record } = opened;\n\tconst factor = record.secondFactor;\n\n\tconst found = findRecoveryCode(\n\t\topened.configured.sealer,\n\t\trecord.id,\n\t\tfactor.recoveryCodes,\n\t\tString(code),\n\t\twhere,\n\t);\n\tif (found === -1) return refuseCode(context, type, opened, where);\n\n\tconst recoveryCodes = factor.recoveryCodes.filter(\n\t\t(_, index) => index !== found,\n\t);\n\tconst written = await context.store.users.updateUser(\n\t\trecord.id,\n\t\t{\n\t\t\tsecondFactor: { ...factor, recoveryCodes },\n\t\t\tupdatedAt: context.clock.now(),\n\t\t},\n\t\trecord.version,\n\t);\n\t// The code is spent once written, whatever follows: the event reports it\n\t// even when spending the challenge or opening the session fails.\n\tlet signedIn: SignedIn<AnyUser>;\n\ttry {\n\t\tawait spendChallenge(context, opened.secret, where);\n\t\tawait restartSignInCount(context, type, written, where);\n\t\tsignedIn = await openSession(\n\t\t\tcontext,\n\t\t\ttype,\n\t\t\twritten,\n\t\t\tdevice,\n\t\t\tfalse,\n\t\t\tsecondFactorAmr(opened, AMR.recoveryCode),\n\t\t);\n\t} finally {\n\t\tawait emit(context, 'user.recoveryCodeUsed', written, written.updatedAt);\n\t}\n\tawait reportNewDevice(context, signedIn);\n\treturn { ...signedIn, recoveryCodesLeft: recoveryCodes.length };\n}\n",
|
|
131
|
+
"import { isId } from '../../ids/id';\nimport { invalidCursor, MAX_PAGE_SIZE } from '../../pagination/cursor-page';\nimport type { ResolvedType } from '../config';\nimport type { Context } from '../context';\nimport { unlessVersionConflict } from '../outage';\nimport { seal, tryUnseal } from '../sealing';\nimport type { SecondFactorResealed } from '../types';\nimport { requireSettings } from './factor';\n\n/** How many users a call visits when `batch` is absent. */\nconst DEFAULT_BATCH = 100;\n\n/**\n * Seals the secrets of one page of users again under the first key: the step\n * between putting a new key first and dropping the old one, for the users who\n * do not sign in. A page of the type's users is read after `after`; each one\n * with a factor — active or waiting for its first code — whose secret is not\n * under the first key is rewritten, under the version it was read at, so a\n * writer that got there first is never overwritten (`skipped`: run again).\n * Nothing else of the record changes, and no event is sent.\n */\nexport async function resealSecrets(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tinput:\n\t\t| { readonly batch?: number; readonly after?: string | null }\n\t\t| undefined,\n\twhere: string,\n): Promise<SecondFactorResealed> {\n\tconst configured = requireSettings(\n\t\tcontext,\n\t\twhere,\n\t\t'secrets are being sealed again',\n\t);\n\tconst batch = input?.batch ?? DEFAULT_BATCH;\n\tif (!Number.isInteger(batch) || batch < 1) {\n\t\tthrow new TypeError(`${where}: batch must be an integer of at least 1`);\n\t}\n\tconst after = input?.after ?? null;\n\tif (after !== null && (typeof after !== 'string' || !isId(after))) {\n\t\tthrow invalidCursor(where, String(after));\n\t}\n\tconst { sealer } = configured;\n\n\tconst page = await context.store.users.listUsers({\n\t\ttype: type.name,\n\t\tafter,\n\t\tlimit: Math.min(batch, MAX_PAGE_SIZE),\n\t});\n\tlet resealed = 0;\n\tlet current = 0;\n\tlet skipped = 0;\n\tlet unreadable = 0;\n\tfor (const record of page.items) {\n\t\tconst factor = record.secondFactor;\n\t\tif (factor === null) continue;\n\t\tconst opened = tryUnseal(sealer, factor.secret, record.id, where);\n\t\tif (opened === null) {\n\t\t\tunreadable++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (opened.keyId === sealer.sealWith) {\n\t\t\tcurrent++;\n\t\t\tcontinue;\n\t\t}\n\t\tconst written = await unlessVersionConflict(\n\t\t\tcontext.store.users.updateUser(\n\t\t\t\trecord.id,\n\t\t\t\t{\n\t\t\t\t\tupdatedAt: context.clock.now(),\n\t\t\t\t\tsecondFactor: {\n\t\t\t\t\t\t...factor,\n\t\t\t\t\t\tsecret: seal(sealer, opened.plain, record.id),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\trecord.version,\n\t\t\t),\n\t\t);\n\t\tif (written === null) skipped++;\n\t\telse resealed++;\n\t}\n\treturn {\n\t\tscanned: page.items.length,\n\t\tresealed,\n\t\tcurrent,\n\t\tskipped,\n\t\tunreadable,\n\t\tnextCursor: page.nextCursor,\n\t};\n}\n",
|
|
132
|
+
"import type { At } from '../at';\nimport type { ResolvedType } from '../config';\nimport type { AnyUser, Context } from '../context';\nimport type { DeviceHint } from '../devices';\nimport type { UserRecord } from '../port/types';\nimport { openSession } from '../sessions';\nimport type { PasskeySignInApi, SecondFactorApi, SignInResult } from '../types';\nimport { challengeFlows } from './challenge';\nimport { recoveryCodesLeftOf } from './codes-left';\nimport { isActive } from './factor';\nimport { lifecycleFlows } from './lifecycle';\nimport { confirmWithPasskey } from './passkey-confirm';\nimport { recoverWithCode } from './recovery';\nimport { resealSecrets } from './reseal';\n\n/**\n * The second factor of one user type: the flows its API answers, and what\n * `signIn` needs — whether to ask for a code, and the challenge to answer.\n */\nexport function secondFactorFlows(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tat: At,\n) {\n\tconst challenges = challengeFlows(context, type, at);\n\tconst api: (SecondFactorApi<AnyUser> &\n\t\tPasskeySignInApi<AnyUser>)['secondFactor'] = {\n\t\t...lifecycleFlows(context, type, at),\n\t\tconfirm: challenges.confirm,\n\t\tconfirmPasskey: (challenge, assertion, options) =>\n\t\t\tconfirmWithPasskey(context, type, { challenge, assertion, options }, at),\n\t\trecover: (challenge, code, options) =>\n\t\t\trecoverWithCode(context, type, { challenge, code, options }, at),\n\t\treseal: (input) =>\n\t\t\tresealSecrets(context, type, input, at('secondFactor.reseal')),\n\t\trecoveryCodesLeft: (user) =>\n\t\t\trecoveryCodesLeftOf(\n\t\t\t\tcontext,\n\t\t\t\ttype,\n\t\t\t\tuser,\n\t\t\t\tat('secondFactor.recoveryCodesLeft'),\n\t\t\t),\n\t};\n\n\treturn {\n\t\tapi,\n\t\t/**\n\t\t * What a sign-in answers once the user proved who they are — by\n\t\t * password or by an e-mail code: a session, or a challenge when their\n\t\t * second factor is active. The first factor alone opens nothing then,\n\t\t * and the device is not carried: its confirmation is given it again.\n\t\t */\n\t\tfinish: (\n\t\t\trecord: UserRecord,\n\t\t\twhere: string,\n\t\t\tdevice: DeviceHint,\n\t\t\tamr: readonly string[] = [],\n\t\t): Promise<SignInResult<AnyUser>> =>\n\t\t\tisActive(record.secondFactor)\n\t\t\t\t? challenges.issue(record, where, amr)\n\t\t\t\t: openSession(context, type, record, device, false, amr),\n\t};\n}\n",
|
|
133
|
+
"import type { At } from './at';\nimport type { ResolvedType } from './config';\nimport { type AnyUser, type Context, findRecord, toUser } from './context';\nimport { deviceHint } from './devices';\nimport {\n\ttype Finish,\n\tfinishEmailSignIn,\n\tkeepOnlyLatest,\n\tsignInHolder,\n} from './email-sign-in';\nimport { countMailByAddress } from './mail-requests';\nimport {\n\tburnOneTime,\n\tCODE_ATTEMPTS,\n\tcodeInvalid,\n\tcodeMatches,\n\tcountCodeAttempt,\n\tissueCode,\n\tspendOneTime,\n\tunknownChallenge,\n} from './one-time';\nimport { sendOnce } from './prepared';\nimport { mintSecret } from './secrets';\nimport { AMR } from './sessions/amr';\nimport type {\n\tIssuedCode,\n\tPreparedCode,\n\tSignInCodeApi,\n\tSignInOptions,\n\tSignInResult,\n} from './types';\n\n/**\n * Signing in with a code sent to the user's e-mail: no password, and the\n * code proves the address.\n *\n * The code is six digits, so it is guessable where a link is not. What\n * bounds that is the same as for a second factor: the store counts every\n * attempt in one write, before the code is compared, and the fifth wrong one\n * spends the challenge. **At most one code is live per user**: `request`\n * spends every other once it issued its own, so concurrent requests cannot\n * each keep one. Yet anybody who knows an e-mail can ask for another — and\n * each request cancels the code before — so `request` is counted per\n * address (`mail-requests.ts`), and the application rate-limits it per\n * client. The code's hash is keyed by the challenge, so the\n * tokens alone do not reveal it.\n *\n * `request` is `prepare`, then `send` (`prepared.ts`): counted, the\n * challenge minted — before anybody is looked up, so the visitor gets one\n * whoever holds the address — then looked up and issued under it.\n */\nexport function signInCodeFlows(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tat: At,\n\tfinish: Finish,\n): SignInCodeApi<AnyUser, SignInResult<AnyUser>>['signInCode'] {\n\treturn {\n\t\tasync request(email) {\n\t\t\tconst where = at('signInCode.request');\n\t\t\treturn (await prepareCode(context, type, String(email), where)).send();\n\t\t},\n\n\t\tasync prepare(email) {\n\t\t\tconst where = at('signInCode.prepare');\n\t\t\treturn prepareCode(context, type, String(email), where);\n\t\t},\n\n\t\tasync confirm(challenge, code, options) {\n\t\t\treturn confirmCode(\n\t\t\t\tcontext,\n\t\t\t\ttype,\n\t\t\t\tfinish,\n\t\t\t\t{ challenge, code, options },\n\t\t\t\tat,\n\t\t\t);\n\t\t},\n\t};\n}\n\n/**\n * Counts a code asked for `email` — before it is looked up: past the limit,\n * nobody and somebody are refused alike — mints its challenge, and answers\n * the `send` that issues it, once.\n */\nasync function prepareCode(\n\tcontext: Context,\n\ttype: ResolvedType,\n\temail: string,\n\twhere: string,\n): Promise<PreparedCode<AnyUser>> {\n\tawait countMailByAddress(context, type, 'signInCode', email, where);\n\tconst challenge = mintSecret();\n\treturn Object.freeze({\n\t\tchallenge,\n\t\tsend: sendOnce(where, () =>\n\t\t\tissueSignInCode(context, type, email, challenge),\n\t\t),\n\t});\n}\n\n/** Issues a code under `challenge` for the holder of `email`, and spends every other they had. */\nasync function issueSignInCode(\n\tcontext: Context,\n\ttype: ResolvedType,\n\temail: string,\n\tchallenge: string,\n): Promise<IssuedCode<AnyUser> | null> {\n\t// Nobody, and an inactive user, get the same answer: no code.\n\tconst record = await signInHolder(context, type, email);\n\tif (record === null) return null;\n\n\tconst address = String(record.fields[type.email]);\n\tconst { secret, code, expiresAt } = await issueCode(context, {\n\t\tkind: 'signInCode',\n\t\tuserId: record.id,\n\t\taddress,\n\t\tttlMs: context.config.tokenTtlMs.signInCode,\n\t\tsecret: challenge,\n\t});\n\t// One live code per user: the ones sent before stop working.\n\tawait keepOnlyLatest(context, record.id, 'signInCode', secret);\n\treturn {\n\t\tcode,\n\t\tchallenge: secret,\n\t\temail: address,\n\t\texpiresAt,\n\t\tuser: toUser(record),\n\t};\n}\n\n/** Redeems a challenge's code, proves the e-mail, and finishes the sign-in. */\nasync function confirmCode(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tfinish: Finish,\n\tgiven: {\n\t\treadonly challenge: string;\n\t\treadonly code: string;\n\t\treadonly options: SignInOptions | undefined;\n\t},\n\tat: At,\n): Promise<SignInResult<AnyUser>> {\n\tconst where = at('signInCode.confirm');\n\tconst device = deviceHint(context, given.options, where);\n\tconst secret = String(given.challenge);\n\tconst code = given.code;\n\tconst { token, attemptsLeft } = await countCodeAttempt(\n\t\tcontext,\n\t\tsecret,\n\t\t'signInCode',\n\t\twhere,\n\t\ttype.name,\n\t);\n\n\t// A user gone since, or of another type, is as good as no challenge:\n\t// another type's API compares nothing — though the attempt, counted\n\t// before the type is known, is gone, and the last one spends it.\n\tconst user = await findRecord(context, token.userId, type.name);\n\tif (user === null) {\n\t\tthrow await unknownChallenge(context, token, secret, where);\n\t}\n\n\tif (!codeMatches(token, secret, String(code))) {\n\t\t// The last attempt, and a wrong code: the challenge is spent.\n\t\tif (token.attempts === CODE_ATTEMPTS) {\n\t\t\tawait burnOneTime(context, secret, 'signInCode');\n\t\t}\n\t\tthrow codeInvalid(where, user.id, type.name, attemptsLeft);\n\t}\n\n\tawait spendOneTime(context, secret, 'signInCode', where, 'challenge');\n\treturn finishEmailSignIn(context, type, finish, {\n\t\tuser,\n\t\ttoken,\n\t\twhere,\n\t\tnoun: 'code',\n\t\tdevice,\n\t\tamr: AMR.oneTimeCode,\n\t});\n}\n",
|
|
134
|
+
"import type { Context } from '../context';\nimport { spendOneTime } from '../one-time';\n\n/** Spends a step-up's challenge, refusing it when this call did not. */\nexport const spendStepUp = (context: Context, secret: string, where: string) =>\n\tspendOneTime(context, secret, 'stepUp', where, 'challenge');\n",
|
|
135
|
+
"/**\n * A step-up confirmed by a passkey: issued with the options the browser\n * needs, confirmed with its assertion. The WebAuthn challenge is derived from\n * the token's secret, so the token is the app's kind — no code hash — and\n * stores nothing more.\n */\n\nimport { SecondFactorError } from '../../errors/janus-error';\nimport type { ResolvedType } from '../config';\nimport { type AnyUser, type Context, toUser } from '../context';\nimport {\n\tburnOneTime,\n\tcodeInvalid,\n\tissueOneTime,\n\tunknownChallenge,\n} from '../one-time';\nimport { acceptAssertion } from '../passkeys/assert';\nimport { assertionOptions } from '../passkeys/assertion-options';\nimport { requirePasskeys } from '../passkeys/wiring';\nimport type { UserRecord } from '../port/types';\nimport { isActive } from '../second-factor/factor';\nimport type { StepUpByPasskey } from '../types';\nimport type { CountedStepUp } from './codes';\nimport { spendStepUp } from './spend';\n\n/**\n * The mark a passkey step-up's token carries in `address` (nothing is sent,\n * so there is no address): it tells the token from the app's, which has\n * none, so neither kind confirms the other.\n *\n * `TokenRecord.address` carries this mark only for a passkey step-up's token:\n * no e-mail address can equal it (an address holds an `@`), so a token sent\n * to a real address is never taken for a passkey's.\n */\nexport const PASSKEY_MARK = 'passkey';\n\n/** A challenge the user's passkey answers. */\nexport async function byPasskey(\n\tcontext: Context,\n\ttype: ResolvedType,\n\trecord: UserRecord,\n\twhere: string,\n): Promise<StepUpByPasskey<AnyUser>> {\n\trequirePasskeys(context, where);\n\tif (!isActive(record.secondFactor)) {\n\t\tthrow new SecondFactorError(\n\t\t\t'SECOND_FACTOR_NOT_ENROLLED',\n\t\t\t`${where}: the user has no active second factor — a passkey is only registered beside one`,\n\t\t\t{ operation: where, userId: record.id, userType: type.name },\n\t\t);\n\t}\n\tconst { secret, expiresAt } = await issueOneTime(context, {\n\t\tkind: 'stepUp',\n\t\tuserId: record.id,\n\t\taddress: PASSKEY_MARK,\n\t\tttlMs: context.config.tokenTtlMs.stepUp,\n\t});\n\tconst options = await assertionOptions(\n\t\tcontext,\n\t\trecord.id,\n\t\t'stepUp',\n\t\tsecret,\n\t\twhere,\n\t);\n\tif (options === null) {\n\t\t// Nothing was shown: the token is spent so it cannot linger.\n\t\tawait burnOneTime(context, secret, 'stepUp');\n\t\tthrow new SecondFactorError(\n\t\t\t'SECOND_FACTOR_NOT_ENROLLED',\n\t\t\t`${where}: the user holds no passkey — register one, or request the step-up without via`,\n\t\t\t{ operation: where, userId: record.id, userType: type.name },\n\t\t);\n\t}\n\treturn {\n\t\tvia: 'passkey',\n\t\tchallenge: secret,\n\t\toptions,\n\t\texpiresAt,\n\t\tuser: toUser(record),\n\t};\n}\n\n/**\n * Checks the assertion. The challenge's attempts are the only ones counted\n * (an assertion is not guessable, so the per-user window of the app's codes\n * does not apply). Refused when the user's second factor was removed since —\n * their passkeys went with it.\n */\nexport async function checkPasskey(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tuser: UserRecord,\n\tcounted: CountedStepUp,\n\tassertion: unknown,\n\twhere: string,\n): Promise<void> {\n\tconst { token, secret, attemptsLeft } = counted;\n\t// A challenge issued for the app's code or an e-mail is not a passkey's.\n\tif (token.address !== PASSKEY_MARK) {\n\t\tthrow await unknownChallenge(context, token, secret, where);\n\t}\n\tif (!isActive(user.secondFactor)) {\n\t\tawait spendStepUp(context, secret, where);\n\t\tthrow new SecondFactorError(\n\t\t\t'SECOND_FACTOR_NOT_ENROLLED',\n\t\t\t`${where}: the user no longer has a second factor — request a step-up again`,\n\t\t\t{ operation: where, userId: user.id, userType: type.name },\n\t\t);\n\t}\n\tconst accepted = await acceptAssertion(\n\t\tcontext,\n\t\tuser,\n\t\t{ assertion, purpose: 'stepUp', secret },\n\t\twhere,\n\t);\n\tif (!accepted) {\n\t\tif (attemptsLeft === 0) await burnOneTime(context, secret, 'stepUp');\n\t\tthrow codeInvalid(where, user.id, type.name, attemptsLeft);\n\t}\n\tawait spendStepUp(context, secret, where);\n}\n",
|
|
136
|
+
"/**\n * The two codes that confirm a step-up: the one e-mailed with the challenge,\n * and, for a user whose second factor is active, the one their app shows.\n * Each spends the challenge once it matched.\n */\n\nimport { SecondFactorError } from '../../errors/janus-error';\nimport type { ResolvedType } from '../config';\nimport type { Context } from '../context';\nimport {\n\tburnOneTime,\n\tcodeInvalid,\n\tcodeMatches,\n\trefuseStale,\n\tspendOneTime,\n\tunknownChallenge,\n} from '../one-time';\nimport type { TokenRecord, UserRecord } from '../port/types';\nimport { countAppCodeAttempt } from '../second-factor/app-code-attempts';\nimport { acceptCode, isActive, requireSettings } from '../second-factor/factor';\nimport { PASSKEY_MARK } from './passkey';\n\n/** A challenge counted: the token as counted, its secret, and what is left of its attempts. */\nexport interface CountedStepUp {\n\treadonly token: TokenRecord;\n\treadonly secret: string;\n\treadonly attemptsLeft: number;\n}\n\nconst spend = (context: Context, secret: string, where: string) =>\n\tspendOneTime(context, secret, 'stepUp', where, 'challenge');\n\n/**\n * Checks the e-mailed code. Refused when the user's second factor became\n * active since it was sent — their app is what confirms now — and when the\n * e-mail it was sent to is not theirs any more.\n */\nexport async function checkEmailedCode(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tuser: UserRecord,\n\tcounted: CountedStepUp,\n\tcode: string,\n\twhere: string,\n): Promise<void> {\n\tconst { token, secret, attemptsLeft } = counted;\n\tif (isActive(user.secondFactor)) {\n\t\tawait spend(context, secret, where);\n\t\tthrow new SecondFactorError(\n\t\t\t'SECOND_FACTOR_ACTIVE',\n\t\t\t`${where}: the user's second factor became active since the code was sent — request a step-up again`,\n\t\t\t{ operation: where, userId: user.id, userType: type.name },\n\t\t);\n\t}\n\tif (!codeMatches(token, secret, code)) {\n\t\tif (attemptsLeft === 0) await burnOneTime(context, secret, 'stepUp');\n\t\tthrow codeInvalid(where, user.id, type.name, attemptsLeft);\n\t}\n\tawait spend(context, secret, where);\n\trefuseStale(type, user, token, where, 'code');\n}\n\n/**\n * Checks a code from the user's app. Its attempts are counted twice before it\n * is compared: against the challenge, and per user and window, as\n * `regenerateRecoveryCodes`' are — a stolen session asking for challenge\n * after challenge still gets five guesses per window, not five per\n * challenge. The code accepted is written, so it confirms nothing else.\n */\nexport async function checkAppCode(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tuser: UserRecord,\n\tcounted: CountedStepUp,\n\tcode: string,\n\twhere: string,\n): Promise<void> {\n\tconst { secret, attemptsLeft } = counted;\n\tconst factor = user.secondFactor;\n\tif (!isActive(factor)) {\n\t\tawait spend(context, secret, where);\n\t\tthrow new SecondFactorError(\n\t\t\t'SECOND_FACTOR_NOT_ENROLLED',\n\t\t\t`${where}: the user no longer has a second factor — request a step-up again`,\n\t\t\t{ operation: where, userId: user.id, userType: type.name },\n\t\t);\n\t}\n\tconst configured = requireSettings(\n\t\tcontext,\n\t\twhere,\n\t\t\"the user's second factor is active\",\n\t);\n\tconst windowLeft = await countAppCodeAttempt(\n\t\tcontext,\n\t\tconfigured.sealer,\n\t\tuser,\n\t\twhere,\n\t);\n\n\tconst now = context.clock.now();\n\tconst accepted = acceptCode(configured, user, factor, code, now, where);\n\tif (accepted === null) {\n\t\tif (attemptsLeft === 0) await burnOneTime(context, secret, 'stepUp');\n\t\tthrow codeInvalid(\n\t\t\twhere,\n\t\t\tuser.id,\n\t\t\ttype.name,\n\t\t\tMath.min(attemptsLeft, windowLeft),\n\t\t);\n\t}\n\t// Written under the version read: of two codes accepted at once, the\n\t// second write is VERSION_CONFLICT.\n\tawait context.store.users.updateUser(\n\t\tuser.id,\n\t\t{ secondFactor: accepted, updatedAt: now },\n\t\tuser.version,\n\t);\n\tawait spend(context, secret, where);\n}\n\n/**\n * Checks the code a `stepUp.confirm` was given, by the kind of challenge:\n * a passkey's is confirmed by an assertion alone (it is unknown here), one\n * without a code hash was issued for the user's app, the rest were e-mailed.\n */\nexport async function checkCode(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tuser: UserRecord,\n\tcounted: CountedStepUp,\n\tcode: string,\n\twhere: string,\n): Promise<void> {\n\tconst { token } = counted;\n\tif (token.address === PASSKEY_MARK) {\n\t\tthrow await unknownChallenge(context, token, counted.secret, where);\n\t}\n\tif (token.codeHash === null) {\n\t\tawait checkAppCode(context, type, user, counted, code, where);\n\t} else {\n\t\tawait checkEmailedCode(context, type, user, counted, code, where);\n\t}\n}\n",
|
|
137
|
+
"/**\n * What confirming a step-up takes before any code is compared: the session\n * the request presents, and the user the challenge is for — the two the\n * same, both standing.\n */\n\nimport { UserInactiveError } from '../../errors/janus-error';\nimport type { ResolvedType } from '../config';\nimport { type Context, findRecord } from '../context';\nimport { spendOneTime, unknownChallenge } from '../one-time';\nimport type { SessionRecord, TokenRecord, UserRecord } from '../port/types';\nimport { standingSession } from '../sessions/standing';\nimport type { RequestLike } from '../types';\n\n/** The session a step-up confirms, and its user. */\nexport interface OpenedStepUp {\n\treadonly session: SessionRecord;\n\treadonly user: UserRecord;\n}\n\n/**\n * Reads the session the request presents and the user the challenge is for.\n * A session absent, revoked, lapsed, or another user's is as good as no\n * challenge — a challenge is confirmed on its user's own session, never on\n * somebody else's — and so is a user gone since, or of another type. Each\n * attempt was counted before, so the last one spends the challenge.\n */\nexport async function openStepUp(\n\tcontext: Context,\n\ttype: ResolvedType,\n\trequest: RequestLike,\n\ttoken: TokenRecord,\n\tsecret: string,\n\twhere: string,\n): Promise<OpenedStepUp> {\n\tconst session = (await standingSession(context, request))?.session ?? null;\n\tif (session === null || session.userId !== token.userId) {\n\t\tthrow await unknownChallenge(context, token, secret, where);\n\t}\n\n\tconst user = await findRecord(context, token.userId, type.name);\n\tif (user === null) {\n\t\tthrow await unknownChallenge(context, token, secret, where);\n\t}\n\tif (!user.active) {\n\t\tawait spendOneTime(context, secret, 'stepUp', where, 'challenge');\n\t\tthrow new UserInactiveError(`${where}: the user is inactive`, {\n\t\t\tuserId: user.id,\n\t\t\tuserType: type.name,\n\t\t});\n\t}\n\treturn { session, user };\n}\n",
|
|
138
|
+
"/**\n * Issuing a step-up: a challenge for the user, with a code to e-mail, or to\n * confirm with their app when their second factor is active.\n */\n\nimport { NotFoundError, UserInactiveError } from '../../errors/janus-error';\nimport type { At } from '../at';\nimport type { ResolvedType } from '../config';\nimport {\n\ttype AnyUser,\n\ttype Context,\n\temailOf,\n\tgetRecord,\n\tidOf,\n\ttoUser,\n} from '../context';\nimport { countMailByUser } from '../mail-requests';\nimport { issueCode, issueOneTime } from '../one-time';\nimport type { UserRecord } from '../port/types';\nimport { isActive, requireSettings } from '../second-factor/factor';\nimport { hashSecret } from '../secrets';\nimport type {\n\tStepUpApi,\n\tStepUpByApp,\n\tStepUpByEmail,\n\tStepUpByPasskey,\n\tStepUpPasskeyApi,\n\tUserRef,\n} from '../types';\nimport { byPasskey } from './passkey';\n\n/** What `stepUp.request` answers, whatever the type's configuration. */\nexport type IssuedStepUp =\n\t| StepUpByEmail<AnyUser>\n\t| StepUpByApp<AnyUser>\n\t| StepUpByPasskey<AnyUser>;\n\n/** Issues a step-up for the user, and spends every other they had. */\nexport async function requestStepUp(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tuser: UserRef,\n\twhere: string,\n\tvia?: 'passkey',\n): Promise<IssuedStepUp> {\n\tconst record = await getRecord(context, idOf(user), type.name, where);\n\tif (!record.active) {\n\t\tthrow new UserInactiveError(`${where}: the user is inactive`, {\n\t\t\tuserId: record.id,\n\t\t\tuserType: type.name,\n\t\t});\n\t}\n\n\tconst issued =\n\t\tvia === 'passkey'\n\t\t\t? await byPasskey(context, type, record, where)\n\t\t\t: isActive(record.secondFactor)\n\t\t\t\t? await byApp(context, record, where)\n\t\t\t\t: await byEmail(context, type, record, where);\n\t// One live step-up per user, as for a sign-in code: issued first, the\n\t// others spent after, so requests that race leave at most one.\n\tawait context.store.tokens.spendUserTokens(\n\t\trecord.id,\n\t\t'stepUp',\n\t\tcontext.clock.now(),\n\t\thashSecret(issued.challenge),\n\t);\n\treturn issued;\n}\n\n/** A challenge the user's app confirms: nothing is sent, so there is no address. */\nasync function byApp(\n\tcontext: Context,\n\trecord: UserRecord,\n\twhere: string,\n): Promise<StepUpByApp<AnyUser>> {\n\trequireSettings(context, where, \"the user's second factor is active\");\n\tconst { secret, expiresAt } = await issueOneTime(context, {\n\t\tkind: 'stepUp',\n\t\tuserId: record.id,\n\t\taddress: '',\n\t\tttlMs: context.config.tokenTtlMs.stepUp,\n\t});\n\treturn {\n\t\tvia: 'secondFactor',\n\t\tchallenge: secret,\n\t\texpiresAt,\n\t\tuser: toUser(record),\n\t};\n}\n\n/** A challenge with a six-digit code, for the user's current e-mail. */\nasync function byEmail(\n\tcontext: Context,\n\ttype: ResolvedType,\n\trecord: UserRecord,\n\twhere: string,\n): Promise<StepUpByEmail<AnyUser>> {\n\tconst email = emailOf(type, record.fields);\n\tif (email === null) {\n\t\tthrow new NotFoundError(`${where}: the user has no e-mail`, {\n\t\t\tuserId: record.id,\n\t\t\tuserType: type.name,\n\t\t\toperation: where,\n\t\t});\n\t}\n\t// Counted per user, and only when a code is e-mailed: an app's challenge\n\t// sends nothing.\n\tawait countMailByUser(context, type, 'stepUp', record.id, where);\n\tconst { secret, code, expiresAt } = await issueCode(context, {\n\t\tkind: 'stepUp',\n\t\tuserId: record.id,\n\t\taddress: email,\n\t\tttlMs: context.config.tokenTtlMs.stepUp,\n\t});\n\treturn {\n\t\tvia: 'email',\n\t\tcode,\n\t\tchallenge: secret,\n\t\temail,\n\t\texpiresAt,\n\t\tuser: toUser(record),\n\t};\n}\n\n/** `stepUp.request` of one user type: the overloads, then {@link requestStepUp}. */\nexport function stepUpRequest(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tat: At,\n): (StepUpApi<AnyUser, StepUpByEmail<AnyUser> | StepUpByApp<AnyUser>> &\n\tStepUpPasskeyApi<AnyUser>)['stepUp']['request'] {\n\tfunction request(\n\t\tuser: UserRef,\n\t): Promise<StepUpByEmail<AnyUser> | StepUpByApp<AnyUser>>;\n\tfunction request(\n\t\tuser: UserRef,\n\t\toptions: { readonly via: 'passkey' },\n\t): Promise<StepUpByPasskey<AnyUser>>;\n\tfunction request(\n\t\tuser: UserRef,\n\t\toptions?: { readonly via: 'passkey' },\n\t): Promise<IssuedStepUp> {\n\t\treturn requestStepUp(\n\t\t\tcontext,\n\t\t\ttype,\n\t\t\tuser,\n\t\t\tat('stepUp.request'),\n\t\t\toptions?.via === 'passkey' ? 'passkey' : undefined,\n\t\t);\n\t}\n\treturn request;\n}\n",
|
|
139
|
+
"/**\n * A step-up: a signed-in user proving again who they are before a sensitive\n * action, with a code sent by e-mail — or from their app, when their second\n * factor is active — and **the session they are on stamped as freshly\n * confirmed**. It opens no session: its `authenticatedAt` moves, which is\n * what a route checks with `assertFresh`.\n *\n * The same six digits, challenge and five attempts as a sign-in code, on a\n * token kind of its own: a sign-in code never confirms an action, nor an\n * action's code signs anyone in.\n */\n\nimport { TokenError } from '../../errors/janus-error';\nimport type { At } from '../at';\nimport type { ResolvedType } from '../config';\nimport type { AnyUser, Context } from '../context';\nimport { countCodeAttempt } from '../one-time';\nimport { requirePasskeys } from '../passkeys/wiring';\nimport type { UserRecord } from '../port/types';\nimport { AMR, mergeAmr } from '../sessions/amr';\nimport { toSession } from '../sessions/open-session';\nimport type {\n\tRequestLike,\n\tSession,\n\tStepUpApi,\n\tStepUpByApp,\n\tStepUpByEmail,\n\tStepUpPasskeyApi,\n} from '../types';\nimport { type CountedStepUp, checkCode } from './codes';\nimport { openStepUp } from './open';\nimport { checkPasskey } from './passkey';\nimport { stepUpRequest } from './request';\n\n/** The step-up of one user type. */\nexport function stepUpFlows(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tat: At,\n): (StepUpApi<AnyUser, StepUpByEmail<AnyUser> | StepUpByApp<AnyUser>> &\n\tStepUpPasskeyApi<AnyUser>)['stepUp'] {\n\treturn {\n\t\trequest: stepUpRequest(context, type, at),\n\n\t\tasync confirm(request, challenge, code) {\n\t\t\tconst where = at('stepUp.confirm');\n\t\t\treturn confirmStepUp(\n\t\t\t\tcontext,\n\t\t\t\ttype,\n\t\t\t\trequest,\n\t\t\t\tString(challenge),\n\t\t\t\twhere,\n\t\t\t\t// A challenge without a code hash is the app's (TOTP); the rest were e-mailed.\n\t\t\t\t(counted) =>\n\t\t\t\t\tcounted.token.codeHash === null ? AMR.appCode : AMR.oneTimeCode,\n\t\t\t\t(user, counted) =>\n\t\t\t\t\tcheckCode(context, type, user, counted, String(code), where),\n\t\t\t);\n\t\t},\n\n\t\tasync confirmPasskey(request, challenge, assertion) {\n\t\t\tconst where = at('stepUp.confirmPasskey');\n\t\t\t// Before any attempt is counted: a wiring mistake costs the user nothing.\n\t\t\trequirePasskeys(context, where);\n\t\t\treturn confirmStepUp(\n\t\t\t\tcontext,\n\t\t\t\ttype,\n\t\t\t\trequest,\n\t\t\t\tString(challenge),\n\t\t\t\twhere,\n\t\t\t\t() => AMR.passkeySecondFactor,\n\t\t\t\t(user, counted) =>\n\t\t\t\t\tcheckPasskey(context, type, user, counted, assertion, where),\n\t\t\t);\n\t\t},\n\t};\n}\n\n/**\n * Counts the attempt first — a guess that fails for any reason has still\n * cost one — then reads the session and the user, runs `check` (a code, or a\n * passkey's assertion) and stamps the session.\n */\nasync function confirmStepUp(\n\tcontext: Context,\n\ttype: ResolvedType,\n\trequest: RequestLike,\n\tsecret: string,\n\twhere: string,\n\tmethods: (counted: CountedStepUp) => readonly string[],\n\tcheck: (user: UserRecord, counted: CountedStepUp) => Promise<void>,\n): Promise<Session> {\n\tconst { token, attemptsLeft } = await countCodeAttempt(\n\t\tcontext,\n\t\tsecret,\n\t\t'stepUp',\n\t\twhere,\n\t\ttype.name,\n\t);\n\tconst { session, user } = await openStepUp(\n\t\tcontext,\n\t\ttype,\n\t\trequest,\n\t\ttoken,\n\t\tsecret,\n\t\twhere,\n\t);\n\n\tconst counted = { token, secret, attemptsLeft };\n\tawait check(user, counted);\n\n\tconst confirmed = await context.store.sessions.reauthenticateSession(\n\t\tsession.id,\n\t\tcontext.clock.now(),\n\t\tmergeAmr(session.amr, methods(counted)),\n\t);\n\t// Revoked while the code was checked: signed out, and never brought back.\n\tif (confirmed === null) {\n\t\tthrow new TokenError(\n\t\t\t'TOKEN_UNKNOWN',\n\t\t\t`${where}: the session was signed out while the code was checked`,\n\t\t\t{ operation: where },\n\t\t);\n\t}\n\treturn toSession(confirmed);\n}\n",
|
|
140
|
+
"import type { ResolvedType } from '../config';\nimport { type AnyUser, type Context, holderOfEmail, toUser } from '../context';\nimport type { FindByEmailApi } from '../types';\n\n/**\n * `findByEmail` for one user type: the holder the e-mail flows would find —\n * the same normalisation, the same comparison with the stored address — with\n * nothing counted, issued or written. A value that is no address is\n * nobody's, as a malformed id is for `find`, and the store is not asked.\n */\nexport function findByEmailFlows(\n\tcontext: Context,\n\ttype: ResolvedType,\n): FindByEmailApi<AnyUser> {\n\treturn {\n\t\tasync findByEmail(email) {\n\t\t\t// From JavaScript, or a value a request carried: nobody's, never a throw.\n\t\t\tif (typeof email !== 'string' || email.trim() === '') return null;\n\t\t\tconst record = await holderOfEmail(context, type, email);\n\t\t\treturn record === null ? null : toUser(record);\n\t\t},\n\t};\n}\n",
|
|
141
|
+
"import { mintId } from '../../ids/id';\nimport type { ResolvedType } from '../config';\nimport {\n\ttype Context,\n\tcheckPassword,\n\tloginsOf,\n\tnameKeyOf,\n\trequireHasher,\n\tvalidateFields,\n} from '../context';\nimport { emit } from '../events';\nimport type { JsonObject, UserRecord } from '../port/types';\nimport type { Input } from './flow-types';\n\n/**\n * Validates, hashes, writes once. What `create`, `signUp` and `findOrCreate`\n * share. `accept` sees the validated fields and may throw to refuse before\n * anything is written; it is `findOrCreate`'s check that the input names the\n * key it was asked for. `emailVerified` writes the user with their e-mail\n * proved — the provider of a social sign-up vouched for it.\n */\nexport async function insert(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tinput: Input,\n\twhere: string,\n\taccept?: (fields: JsonObject) => void,\n\toptions: { readonly emailVerified?: boolean } = {},\n): Promise<UserRecord> {\n\tconst { store, clock } = context;\n\tconst { password, active, ...rest } = input ?? {};\n\tconst now = clock.now();\n\tconst fields = await validateFields(type, rest, where);\n\taccept?.(fields);\n\n\tlet hash: UserRecord['password'] = null;\n\tif (password !== undefined) {\n\t\tcheckPassword(type, password as string, where);\n\t\thash = {\n\t\t\thash: await requireHasher(context, where).hash(password as string),\n\t\t\tupdatedAt: now,\n\t\t};\n\t}\n\n\tconst nameKey = nameKeyOf(type, fields);\n\tconst inserted = await store.users.insertUser({\n\t\tid: mintId(now.getTime()),\n\t\ttype: type.name,\n\t\tschemaVersion: type.schemaVersion,\n\t\tactive: active === undefined ? true : active === true,\n\t\tfields,\n\t\tlogins: loginsOf(type, fields, where),\n\t\tpassword: hash,\n\t\tsecondFactor: null,\n\t\tavatar: null,\n\t\temailVerifiedAt: options.emailVerified === true ? now : null,\n\t\t...(nameKey === null ? {} : { nameKey }),\n\t\tversion: 0,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t});\n\t// Once the user exists: an outage opening signUp's session later still\n\t// leaves a user created, and reported.\n\tawait emit(context, 'user.created', inserted, inserted.createdAt);\n\treturn inserted;\n}\n",
|
|
142
|
+
"import { StoreConflict, UserInvalidError } from '../../errors/janus-error';\nimport type { At } from '../at';\nimport { normalizeEmail, type ResolvedType } from '../config';\nimport { type AnyUser, type Context, holderOfEmail, toUser } from '../context';\nimport { unlessLoginTaken } from '../outage';\nimport type { JsonObject, UserRecord } from '../port/types';\nimport type { FindOrCreateApi } from '../types';\nimport { byLogin } from './by-login';\nimport type { Input } from './flow-types';\nimport { insert } from './insert';\n\n/** The user holding the key as the type's own lookup reads it, or `null`. */\nasync function holder(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tkey: string,\n): Promise<UserRecord | null> {\n\tif (type.password !== null) {\n\t\treturn byLogin(context, type, type.password.normalize(key));\n\t}\n\treturn key.trim() === '' ? null : holderOfEmail(context, type, key);\n}\n\n/** The refusal, before any write, of an input that names another key. */\nfunction refusal(type: ResolvedType, where: string, field: string) {\n\treturn new UserInvalidError(\n\t\t`${where}: the fields do not match the ${type.name} schema (1 issue, at ${field})`,\n\t\t{\n\t\t\tissues: [\n\t\t\t\t{ path: [field], message: 'is not the key findOrCreate was given' },\n\t\t\t],\n\t\t\tuserType: type.name,\n\t\t},\n\t);\n}\n\n/** Throws unless the validated fields name `key`, normalised as the lookup does. */\nfunction mustNameKey(\n\ttype: ResolvedType,\n\tkey: string,\n\twhere: string,\n): (fields: JsonObject) => void {\n\treturn (fields) => {\n\t\tconst field = type.password === null ? type.email : type.password.login;\n\t\tconst value = fields[field];\n\t\tconst named =\n\t\t\ttypeof value !== 'string'\n\t\t\t\t? null\n\t\t\t\t: type.password === null\n\t\t\t\t\t? normalizeEmail(value)\n\t\t\t\t\t: type.password.normalize(value);\n\t\tconst wanted =\n\t\t\ttype.password === null\n\t\t\t\t? normalizeEmail(key)\n\t\t\t\t: type.password.normalize(key);\n\t\tif (named === null || named !== wanted) {\n\t\t\tthrow refusal(type, where, field);\n\t\t}\n\t};\n}\n\n/**\n * `findOrCreate` for one user type: the lookup by login (e-mail on a type\n * with no password), and when nobody holds the key, `input()` and the\n * creation `create` does — once more the lookup if the write lost a race.\n */\nexport function findOrCreateFlows(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tat: At,\n): FindOrCreateApi<AnyUser, Input> {\n\treturn {\n\t\tasync findOrCreate(key, input) {\n\t\t\tconst where = at('findOrCreate');\n\t\t\tif (typeof key !== 'string') {\n\t\t\t\tthrow new UserInvalidError(`${where}: the key must be a string`, {\n\t\t\t\t\tissues: [{ path: [], message: 'is not a string' }],\n\t\t\t\t\tuserType: type.name,\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst found = await holder(context, type, key);\n\t\t\tif (found !== null) return { user: toUser(found), created: false };\n\n\t\t\tconst record = await input();\n\t\t\tconst written = await unlessLoginTaken(\n\t\t\t\tinsert(context, type, record, where, mustNameKey(type, key, where)),\n\t\t\t);\n\t\t\tif (!(written instanceof StoreConflict)) {\n\t\t\t\treturn { user: toUser(written), created: true };\n\t\t\t}\n\t\t\t// Lost a race, or another of the new user's logins is taken: read the key again.\n\t\t\tconst winner = await holder(context, type, key);\n\t\t\tif (winner === null) throw written;\n\t\t\treturn { user: toUser(winner), created: false };\n\t\t},\n\t};\n}\n",
|
|
143
|
+
"import { CredentialError } from '../../errors/janus-error';\nimport type { ResolvedType } from '../config';\nimport {\n\ttype Context,\n\tcheckPassword,\n\tpasswordMatches,\n\tpasswordRule,\n\trequireHasher,\n\twriteUser,\n} from '../context';\nimport { passwordChanged } from '../password-written';\nimport type { UserRecord } from '../port/types';\nimport { countSignInAttempt, restartSignInCount } from '../sign-in-attempts';\nimport type { UserRef, WriteOptions } from '../types';\n\n/**\n * Replaces the password after checking the current one, in the write that\n * replaces it — so the check is made on the very record the write replaces.\n *\n * Each call counts one attempt in the sign-in throttle of the user's login,\n * the one `signIn` counts in, so a caller holding a session cannot try\n * current passwords without limit, and the wrong guesses of both add up. The\n * attempt is counted on the record the write reads, before the password is\n * compared (a user with no password included, so the answer does not tell\n * the two apart); past the limit the call is refused with `retryAfter`, the\n * right password included, and nothing is compared or written. The write\n * runs its callback once, so a call counts exactly once. A user with no login\n * string, or the throttle off, counts nothing. A change that is written\n * restarts the count, as a sign-in that opens a session does — after\n * {@link passwordChanged}, so an outage restarting it cannot skip what the\n * old password opened.\n */\nexport async function changePassword(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tuser: UserRef,\n\tchange: { readonly current: string; readonly next: string },\n\toptions: WriteOptions | undefined,\n\twhere: string,\n): Promise<UserRecord> {\n\tconst rule = passwordRule(type, where);\n\tcheckPassword(type, change?.next, where);\n\tconst hasher = requireHasher(context, where);\n\n\tconst written = await writeUser(\n\t\tcontext,\n\t\tuser,\n\t\ttype,\n\t\toptions,\n\t\twhere,\n\t\tasync (record, now) => {\n\t\t\tconst login =\n\t\t\t\trule.login in record.fields ? record.fields[rule.login] : undefined;\n\t\t\tif (typeof login === 'string') {\n\t\t\t\tawait countSignInAttempt(context, type, rule.normalize(login), where);\n\t\t\t}\n\t\t\tif (\n\t\t\t\trecord.password === null ||\n\t\t\t\t!(await passwordMatches(context, record, change.current, where))\n\t\t\t) {\n\t\t\t\tthrow new CredentialError(\n\t\t\t\t\t'CREDENTIALS_INVALID',\n\t\t\t\t\t`${where}: the current password does not match`,\n\t\t\t\t\t{\n\t\t\t\t\t\treason: record.password === null ? 'noPassword' : 'wrongPassword',\n\t\t\t\t\t\tuserId: record.id,\n\t\t\t\t\t\tuserType: type.name,\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tpassword: {\n\t\t\t\t\thash: await hasher.hash(change.next),\n\t\t\t\t\tupdatedAt: now,\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t);\n\tawait passwordChanged(context, written);\n\tawait restartSignInCount(context, type, written, where);\n\treturn written;\n}\n",
|
|
144
|
+
"import { StoreConflict, UserInvalidError } from '../../errors/janus-error';\nimport type { ResolvedType } from '../config';\nimport {\n\ttype AnyUser,\n\ttype Context,\n\tcheckPassword,\n\temailOf,\n\tholderOfEmail,\n\tpasswordRule,\n\ttoUser,\n\tvalidateFields,\n} from '../context';\nimport { issueEmailToken } from '../email-flows/email-token';\nimport { countMailByAddress } from '../mail-requests';\nimport { unlessLoginTaken } from '../outage';\nimport { sendOnce } from '../prepared';\nimport type { PreparedSignUp, SignUpOutcome } from '../types';\nimport { byLogin } from './by-login';\nimport type { Input } from './flow-types';\nimport { insert } from './insert';\n\n/**\n * `signUp.prepare`: validates the fields and the password against the policy,\n * and counts the attempt per e-mail address — all before anybody is looked\n * up, with the same store calls whatever the address. Its `send()` creates\n * the user and issues a verification token, or finds the login taken\n * (`prepared.ts`: once).\n */\nexport async function prepareSignUp(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tinput: Input,\n\twhere: string,\n): Promise<PreparedSignUp<AnyUser>> {\n\tconst rule = passwordRule(type, where);\n\tif (rule.login !== type.email) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: the ${type.name} type signs in with \"${rule.login}\", not its e-mail \"${type.email}\" — a taken login would reveal an account and the notice would go to the holder of another address; use signUp`,\n\t\t);\n\t}\n\tconst { password, active: _active, ...rest } = input ?? {};\n\tconst fields = await validateFields(type, rest, where);\n\tconst email = emailOf(type, fields);\n\tif (email === null) {\n\t\tthrow new UserInvalidError(\n\t\t\t`${where}: the ${type.name} type needs an e-mail to verify — its schema let it be absent`,\n\t\t\t{ userType: type.name },\n\t\t);\n\t}\n\tcheckPassword(type, password as string, where);\n\tawait countMailByAddress(context, type, 'signUp', email, where);\n\n\t// What send() writes is a copy taken now: a later change of the caller's\n\t// object, or an `active` it carried, changes nothing.\n\tconst written: Input = { ...rest, password };\n\tconst login = fields[rule.login];\n\treturn Object.freeze({\n\t\tsend: sendOnce(where, () =>\n\t\t\tcreateOrFindTaken(context, type, written, String(login), email, where),\n\t\t),\n\t});\n}\n\nasync function createOrFindTaken(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tinput: Input,\n\tlogin: string,\n\temail: string,\n\twhere: string,\n): Promise<SignUpOutcome<AnyUser>> {\n\tconst written = await unlessLoginTaken(insert(context, type, input, where));\n\tif (written instanceof StoreConflict) {\n\t\t// The login, or the e-mail when it is another login of the user, is held.\n\t\tconst rule = passwordRule(type, where);\n\t\tconst holder =\n\t\t\t(await byLogin(context, type, rule.normalize(login))) ??\n\t\t\t(await holderOfEmail(context, type, email));\n\t\t// Gone since the conflict: nothing to say about it.\n\t\tif (holder === null) throw written;\n\t\treturn { status: 'taken', user: toUser(holder) };\n\t}\n\tconst record = written;\n\tconst issued = await issueEmailToken(\n\t\tcontext,\n\t\ttype,\n\t\t'verifyEmail',\n\t\trecord,\n\t\twhere,\n\t);\n\treturn { status: 'created', user: toUser(record), issued };\n}\n",
|
|
145
|
+
"import type { At } from '../at';\nimport type { ResolvedType } from '../config';\nimport {\n\ttype AnyUser,\n\ttype Context,\n\tcheckPassword,\n\tpasswordRule,\n\trequireHasher,\n\ttoUser,\n\twriteUser,\n} from '../context';\nimport { deviceHint } from '../devices';\nimport { passwordChanged } from '../password-written';\nimport { openSession } from '../sessions';\nimport { AMR } from '../sessions/amr';\nimport type {\n\tPasswordApi,\n\tSignInOptions,\n\tSignInResult,\n\tSignUpPrepareApi,\n} from '../types';\nimport { byLogin } from './by-login';\nimport { changePassword } from './change-password';\nimport type { Finish, Input } from './flow-types';\nimport { insert } from './insert';\nimport { signIn } from './sign-in';\nimport { prepareSignUp } from './sign-up';\n\n/**\n * The password flows of one user type: signing up and in, finding a user by\n * the login they sign in with, and setting or changing their password.\n */\nexport function passwordFlows(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tat: At,\n\tfinish: Finish,\n): PasswordApi<AnyUser, Input, string, SignInResult<AnyUser>> &\n\tSignUpPrepareApi<AnyUser, Input> {\n\treturn {\n\t\tsignUp: Object.assign(\n\t\t\tasync (\n\t\t\t\tinput: Input & { readonly password: string },\n\t\t\t\toptions?: SignInOptions,\n\t\t\t) => {\n\t\t\t\tconst where = at('signUp');\n\t\t\t\tconst device = deviceHint(context, options, where);\n\t\t\t\tpasswordRule(type, where);\n\t\t\t\tif (input?.['password'] === undefined) {\n\t\t\t\t\tcheckPassword(type, undefined as unknown as string, where);\n\t\t\t\t}\n\t\t\t\tconst record = await insert(context, type, input, where);\n\t\t\t\treturn openSession(context, type, record, device, true, AMR.password);\n\t\t\t},\n\t\t\t{\n\t\t\t\tprepare: (input: Input & { readonly password: string }) =>\n\t\t\t\t\tprepareSignUp(context, type, input, at('signUp.prepare')),\n\t\t\t},\n\t\t),\n\n\t\tasync signIn(input, options) {\n\t\t\tconst where = at('signIn');\n\t\t\tconst device = deviceHint(context, options, where);\n\t\t\treturn signIn(context, type, finish, input as Input, { where, device });\n\t\t},\n\n\t\tasync findByLogin(login) {\n\t\t\tconst rule = passwordRule(type, at('findByLogin'));\n\t\t\tconst record = await byLogin(context, type, rule.normalize(login));\n\t\t\treturn record === null ? null : toUser(record);\n\t\t},\n\n\t\tasync setPassword(user, password, options) {\n\t\t\tconst where = at('setPassword');\n\t\t\tpasswordRule(type, where);\n\t\t\tcheckPassword(type, password, where);\n\t\t\tconst hash = await requireHasher(context, where).hash(password);\n\n\t\t\tlet first = false;\n\t\t\tconst written = await writeUser(\n\t\t\t\tcontext,\n\t\t\t\tuser,\n\t\t\t\ttype,\n\t\t\t\toptions,\n\t\t\t\twhere,\n\t\t\t\t(record, now) => {\n\t\t\t\t\tfirst = record.password === null;\n\t\t\t\t\treturn { password: { hash, updatedAt: now } };\n\t\t\t\t},\n\t\t\t);\n\t\t\tawait passwordChanged(context, written, first);\n\t\t\treturn toUser(written);\n\t\t},\n\n\t\tasync changePassword(user, change, options) {\n\t\t\tconst where = at('changePassword');\n\t\t\treturn toUser(\n\t\t\t\tawait changePassword(context, type, user, change, options, where),\n\t\t\t);\n\t\t},\n\t};\n}\n",
|
|
146
|
+
"import { isId } from '../../ids/id';\nimport type { ResolvedType } from '../config';\nimport { type Context, idOf } from '../context';\nimport { emit } from '../events';\nimport type { UserRef } from '../types';\n\n/**\n * Deletes the user, then every session, token, API key, social link, passkey and tuple naming them. `true`\n * when this call deleted them; a replay finds nobody, answers `false`, and\n * still deletes what was left.\n */\nexport async function deleteUser(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tuser: UserRef,\n): Promise<boolean> {\n\tconst { store, clock } = context;\n\tconst id = idOf(user);\n\tif (!isId(id)) return false;\n\n\t// Read first, so a staff API never deletes a patient: another type's\n\t// id is answered as nobody, and nothing of theirs is touched.\n\tconst record = await store.users.findUser(id);\n\tif (record !== null && record.type !== type.name) return false;\n\n\t// The user first: from then on nobody can sign in as them, and what\n\t// is left — sessions, tokens — is refused for a user who is gone. An\n\t// outage between the steps leaves only that inert remainder, and a\n\t// replay, finding no user, still deletes it.\n\tconst deletedAt = clock.now();\n\tconst deleted = record !== null && (await store.users.deleteUser(id));\n\ttry {\n\t\tawait store.sessions.deleteUserSessions(id);\n\t\tawait store.tokens.deleteUserTokens(id);\n\t\tawait context.apiKeys?.deleteUserApiKeys(id);\n\t\tawait store.socialLinks?.deleteUserSocialLinks(id);\n\t\tawait store.passkeys?.deleteUserPasskeys(id);\n\t\t// Last, and on a replay too: the tuples naming them.\n\t\tawait context.relations?.deleteEntity({ type: type.name, id });\n\t} finally {\n\t\t// Once, when this call deleted them — even when an outage\n\t\t// interrupts the steps above: a replay deletes nobody, so it\n\t\t// could not send it.\n\t\tif (deleted) {\n\t\t\tawait emit(context, 'user.deleted', { id, type: type.name }, deletedAt);\n\t\t}\n\t}\n\treturn deleted;\n}\n",
|
|
147
|
+
"import { isStorable } from '../../stores/storable';\nimport { normalizeEmail } from '../config';\n\n/** What a store is asked for, from the `emailPrefix` a caller wrote. */\nexport type PrefixFilter =\n\t| { readonly kind: 'all' }\n\t| { readonly kind: 'none' }\n\t| { readonly kind: 'prefix'; readonly loginPrefix: string };\n\n/**\n * The login prefix a store is given, from the `emailPrefix` of a `list` or\n * `count` call.\n *\n * The prefix is normalised with the rule every e-mail is stored under, so the\n * store compares bytes. `undefined`, and a prefix that is empty once\n * normalised, filter nothing. A prefix no store can hold (a NUL, half a\n * surrogate pair) matches no user, and is answered without reaching the store.\n *\n * A bare `TypeError` for a prefix that is not a string: it is written in the\n * application's own code.\n */\nexport function prefixFilter(\n\temailPrefix: unknown,\n\twhere: string,\n): PrefixFilter {\n\tif (emailPrefix === undefined) return { kind: 'all' };\n\tif (typeof emailPrefix !== 'string') {\n\t\tthrow new TypeError(`${where}: emailPrefix must be a string, or absent`);\n\t}\n\n\tconst loginPrefix = normalizeEmail(emailPrefix);\n\tif (loginPrefix === '') return { kind: 'all' };\n\tif (!isStorable(loginPrefix)) return { kind: 'none' };\n\treturn { kind: 'prefix', loginPrefix };\n}\n",
|
|
148
|
+
"/**\n * `findMany`: several users of one type by id, in one query when the users\n * store implements the optional `findUsers`, and with `findUser`, a few ids at\n * a time, when it does not.\n */\n\nimport { StoreFailure } from '../../errors/janus-error';\nimport { isId } from '../../ids/id';\nimport type { Context } from '../context';\nimport type { UserRecord } from '../port/types';\n\n/**\n * The most ids one `findUsers` call is given. A longer list is read in\n * several calls, one after another, so no query grows with the caller's list.\n */\nexport const FIND_MANY_BATCH = 100;\n\n/**\n * How many `findUser` calls run at once when the store has no `findUsers`:\n * enough to keep a 100-row list quick, few enough to leave the connection\n * pool to the rest of the application.\n */\nexport const FIND_MANY_CONCURRENCY = 10;\n\n/**\n * The users of this type holding these ids, **in the order the ids were\n * given**, each once — at its first occurrence. An id that is malformed, held\n * by nobody or held by a user of another type is left out: an absence is a\n * shorter list, never a rejection. A failure throws.\n *\n * An empty list — or one with no well-formed id — answers `[]` without\n * reaching the store.\n */\nexport async function findManyRecords(\n\tcontext: Context,\n\tids: readonly string[],\n\ttype: string,\n\twhere: string,\n): Promise<UserRecord[]> {\n\tif (!Array.isArray(ids)) {\n\t\tthrow new TypeError(`${where}: ids must be an array of user ids`);\n\t}\n\n\tconst wanted = [\n\t\t...new Set(ids.filter((id) => typeof id === 'string' && isId(id))),\n\t];\n\tconst found = new Map<string, UserRecord>();\n\n\tfor (let start = 0; start < wanted.length; start += FIND_MANY_BATCH) {\n\t\tconst batch = wanted.slice(start, start + FIND_MANY_BATCH);\n\t\tfor (const record of await readBatch(context, batch)) {\n\t\t\tif (record.type === type) found.set(record.id, record);\n\t\t}\n\t}\n\n\t// Read back through the ids asked for, so a record the store answered\n\t// for an id nobody asked about never reaches the caller.\n\treturn wanted.flatMap((id) => {\n\t\tconst record = found.get(id);\n\t\treturn record === undefined ? [] : [record];\n\t});\n}\n\n/** One batch: one `findUsers` call, or bounded `findUser` calls. */\nasync function readBatch(\n\tcontext: Context,\n\tids: readonly string[],\n): Promise<readonly UserRecord[]> {\n\tconst { users } = context.store;\n\n\tif (context.capabilities.findUsers && users.findUsers !== undefined) {\n\t\tconst answer: unknown = await users.findUsers(ids);\n\t\tif (!Array.isArray(answer)) {\n\t\t\tthrow new StoreFailure(\n\t\t\t\t'users.findUsers answered no list: an absence is a shorter list, so this store forgot to answer',\n\t\t\t\t{ slot: 'users', operation: 'findUsers' },\n\t\t\t);\n\t\t}\n\t\treturn answer as readonly UserRecord[];\n\t}\n\n\tconst records: UserRecord[] = [];\n\tfor (let start = 0; start < ids.length; start += FIND_MANY_CONCURRENCY) {\n\t\tconst answers = await Promise.all(\n\t\t\tids\n\t\t\t\t.slice(start, start + FIND_MANY_CONCURRENCY)\n\t\t\t\t.map((id) => users.findUser(id)),\n\t\t);\n\t\tfor (const record of answers) if (record !== null) records.push(record);\n\t}\n\treturn records;\n}\n",
|
|
149
|
+
"import { isStorable } from '../../stores/storable';\nimport { foldName } from '../config';\n\n/** What a store is asked for, from the `namePrefix` a caller wrote. */\nexport type NamePrefixFilter =\n\t| { readonly kind: 'all' }\n\t| { readonly kind: 'none' }\n\t| { readonly kind: 'prefix'; readonly namePrefix: string };\n\n/**\n * The name prefix a store is given, from the `namePrefix` of a `list` or\n * `count` call, folded as a display name is when it is stored. `undefined`,\n * and a prefix that is blank once folded, filter nothing. A prefix no store\n * can hold matches no user, and is answered without reaching the store.\n *\n * A bare `TypeError` for a prefix that is not a string.\n */\nexport function namePrefixFilter(\n\tnamePrefix: unknown,\n\twhere: string,\n): NamePrefixFilter {\n\tif (namePrefix === undefined) return { kind: 'all' };\n\tif (typeof namePrefix !== 'string') {\n\t\tthrow new TypeError(`${where}: namePrefix must be a string, or absent`);\n\t}\n\tconst folded = foldName(namePrefix);\n\tif (folded === '') return { kind: 'all' };\n\tif (!isStorable(folded)) return { kind: 'none' };\n\treturn { kind: 'prefix', namePrefix: folded };\n}\n",
|
|
150
|
+
"import { EmailChangeNeedsProofError } from '../../errors/janus-error';\nimport type { ResolvedType } from '../config';\nimport type { Context } from '../context';\nimport type { UserRecord } from '../port/types';\n\n/**\n * Refuses an `update` that moves the e-mail of a user who holds a second\n * factor (active or waiting) or at least one passkey, before anything is\n * written. The new address is unproved, and the first proof of an e-mail drops\n * what stands on the account: `changeEmail` proves the new address first and\n * keeps both.\n *\n * A user who had no e-mail has nothing to move with `changeEmail`: the\n * message then says to remove the factor and the passkeys first. Only called\n * for a new e-mail that is set: clearing it is allowed.\n *\n * Called from the write's own callback, after the record is read and right\n * before the version-checked write, so the factor is the one the write\n * replaces and the passkeys are listed at the latest moment the core can.\n */\nexport async function assertCanMoveEmail(\n\tcontext: Context,\n\ttype: ResolvedType,\n\trecord: UserRecord,\n\thadEmail: boolean,\n\twhere: string,\n): Promise<void> {\n\tconst holdsFactor = record.secondFactor !== null;\n\tconst holdsPasskey =\n\t\t!holdsFactor &&\n\t\t((await context.store.passkeys?.listUserPasskeys(record.id))?.length ?? 0) >\n\t\t\t0;\n\tif (!holdsFactor && !holdsPasskey) return;\n\tconst what = holdsFactor ? 'second factor' : 'passkey';\n\tthrow new EmailChangeNeedsProofError(\n\t\thadEmail\n\t\t\t? `${where}: the user holds a ${what} — moving the e-mail with update would leave the new address unproved and the first proof would drop it; use changeEmail, which proves the new address`\n\t\t\t: `${where}: the user holds a ${what} and has no e-mail — setting one with update would leave it unproved and the first proof would drop it; remove the second factor and the passkeys first`,\n\t\t{ userId: record.id, userType: type.name },\n\t);\n}\n",
|
|
151
|
+
"import type { ResolvedType } from '../config';\nimport { type Context, emailOf, writeUser } from '../context';\nimport { emit } from '../events';\nimport type { UserRecord } from '../port/types';\nimport type { UserRef, WriteOptions } from '../types';\nimport { assertCanMoveEmail } from './email-move-guard';\nimport { emailChanged, fieldsPatch } from './fields-patch';\nimport type { Input } from './flow-types';\n\n/**\n * `update`: the patch written over the stored fields — refused with\n * `EMAIL_CHANGE_NEEDS_PROOF` when it would move the e-mail of a user who holds\n * a second factor or a passkey, since `changeEmail` proves the new address —\n * then — when it changed\n * the e-mail — `user.emailChanged`, carrying the address the write replaced,\n * which nothing keeps once it landed, and the user's pending `changeEmail`\n * links spent.\n */\nexport async function update(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tuser: UserRef,\n\tpatch: Input,\n\toptions: WriteOptions | undefined,\n\twhere: string,\n): Promise<UserRecord> {\n\t// The record the write replaced, read in its callback — which writeUser\n\t// always calls, once, before it writes under that record's version — so\n\t// the e-mail compared is the one this write changed.\n\tconst seen: { replaced: UserRecord | null } = { replaced: null };\n\tconst written = await writeUser(\n\t\tcontext,\n\t\tuser,\n\t\ttype,\n\t\toptions,\n\t\twhere,\n\t\tasync (record) => {\n\t\t\tseen.replaced = record;\n\t\t\tconst patched = await fieldsPatch(type, record, patch, where);\n\t\t\t// Refused before any write: a new address is unproved, and its\n\t\t\t// first proof drops the factor and the passkeys.\n\t\t\t// Clearing the e-mail leaves nothing unproved to prove.\n\t\t\tconst next = emailOf(type, patched.fields);\n\t\t\tif (next !== null && emailChanged(type, record.fields, patched.fields)) {\n\t\t\t\tawait assertCanMoveEmail(\n\t\t\t\t\tcontext,\n\t\t\t\t\ttype,\n\t\t\t\t\trecord,\n\t\t\t\t\temailOf(type, record.fields) !== null,\n\t\t\t\t\twhere,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn patched;\n\t\t},\n\t);\n\tconst { replaced } = seen;\n\tif (\n\t\treplaced !== null &&\n\t\temailChanged(type, replaced.fields, written.fields)\n\t) {\n\t\t// A pending changeEmail link was asked from the address just left:\n\t\t// spent, so a move back to that address cannot revive it. The event is\n\t\t// sent from a `finally`, so an outage there still reports the write.\n\t\ttry {\n\t\t\tawait context.store.tokens.spendUserTokens(\n\t\t\t\twritten.id,\n\t\t\t\t'changeEmail',\n\t\t\t\tcontext.clock.now(),\n\t\t\t);\n\t\t} finally {\n\t\t\tawait emit(context, 'user.emailChanged', written, written.updatedAt, {\n\t\t\t\tformerEmail: emailOf(type, replaced.fields),\n\t\t\t});\n\t\t}\n\t}\n\treturn written;\n}\n",
|
|
152
|
+
"import { isId } from '../../ids/id';\nimport { invalidCursor, pageLimit } from '../../pagination/cursor-page';\nimport type { At } from '../at';\nimport type { ResolvedType } from '../config';\nimport {\n\ttype AnyUser,\n\ttype Context,\n\tfindRecord,\n\tgetRecord,\n\ttoUser,\n\twriteUser,\n} from '../context';\nimport type { UserTypeApi } from '../types';\nimport { deleteUser } from './delete';\nimport { prefixFilter } from './email-prefix';\nimport { findManyRecords } from './find-many';\nimport type { Input } from './flow-types';\nimport { insert } from './insert';\nimport { namePrefixFilter } from './name-prefix';\nimport { update } from './update';\n\n/**\n * The flows every user type has, whatever its configuration: creating,\n * reading, listing, updating, deactivating and deleting its users.\n */\nexport function recordFlows(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tat: At,\n): UserTypeApi<AnyUser, Input> {\n\tconst { store } = context;\n\n\treturn {\n\t\tasync create(input) {\n\t\t\treturn toUser(await insert(context, type, input as Input, at('create')));\n\t\t},\n\n\t\tasync find(id) {\n\t\t\tconst record = await findRecord(context, id, type.name);\n\t\t\treturn record === null ? null : toUser(record);\n\t\t},\n\n\t\tasync findMany(ids) {\n\t\t\tconst records = await findManyRecords(\n\t\t\t\tcontext,\n\t\t\t\tids,\n\t\t\t\ttype.name,\n\t\t\t\tat('findMany'),\n\t\t\t);\n\t\t\treturn records.map(toUser);\n\t\t},\n\n\t\tasync get(id) {\n\t\t\treturn toUser(await getRecord(context, id, type.name, at('get')));\n\t\t},\n\n\t\tasync list(page) {\n\t\t\tconst after = page?.after ?? null;\n\t\t\t// Never a silent first page: a caller paging a list would loop for\n\t\t\t// ever, and the loop would look like a slow query.\n\t\t\tif (after !== null && !isId(after)) {\n\t\t\t\tthrow invalidCursor(at('list'), after);\n\t\t\t}\n\n\t\t\tconst filter = prefixFilter(page?.emailPrefix, at('list'));\n\t\t\tconst name = namePrefixFilter(page?.namePrefix, at('list'));\n\t\t\tif (filter.kind === 'none' || name.kind === 'none') {\n\t\t\t\treturn { items: [], nextCursor: null };\n\t\t\t}\n\n\t\t\tconst answer = await store.users.listUsers({\n\t\t\t\ttype: type.name,\n\t\t\t\t...(filter.kind === 'prefix' && { loginPrefix: filter.loginPrefix }),\n\t\t\t\t...(name.kind === 'prefix' && { namePrefix: name.namePrefix }),\n\t\t\t\tafter,\n\t\t\t\tlimit: pageLimit(page?.limit, at('list')),\n\t\t\t});\n\t\t\treturn { items: answer.items.map(toUser), nextCursor: answer.nextCursor };\n\t\t},\n\n\t\tasync count(filter) {\n\t\t\tconst prefix = prefixFilter(filter?.emailPrefix, at('count'));\n\t\t\tconst name = namePrefixFilter(filter?.namePrefix, at('count'));\n\t\t\tif (prefix.kind === 'none' || name.kind === 'none') return 0;\n\n\t\t\treturn store.users.countUsers({\n\t\t\t\ttype: type.name,\n\t\t\t\t...(prefix.kind === 'prefix' && { loginPrefix: prefix.loginPrefix }),\n\t\t\t\t...(name.kind === 'prefix' && { namePrefix: name.namePrefix }),\n\t\t\t});\n\t\t},\n\n\t\tasync update(user, patch, options) {\n\t\t\treturn toUser(\n\t\t\t\tawait update(\n\t\t\t\t\tcontext,\n\t\t\t\t\ttype,\n\t\t\t\t\tuser,\n\t\t\t\t\tpatch as Input,\n\t\t\t\t\toptions,\n\t\t\t\t\tat('update'),\n\t\t\t\t),\n\t\t\t);\n\t\t},\n\n\t\tasync setActive(user, active, options) {\n\t\t\treturn toUser(\n\t\t\t\tawait writeUser(context, user, type, options, at('setActive'), () => ({\n\t\t\t\t\tactive: active === true,\n\t\t\t\t})),\n\t\t\t);\n\t\t},\n\n\t\tasync delete(user) {\n\t\t\treturn deleteUser(context, type, user);\n\t\t},\n\t};\n}\n",
|
|
153
|
+
"import type { At } from '../at';\nimport { avatarFlows } from '../avatar';\nimport type { ResolvedType } from '../config';\nimport type { Context } from '../context';\nimport { emailFlows } from '../email-flows';\nimport { magicLinkFlows } from '../magic-link';\nimport { passkeyFlows } from '../passkeys';\nimport { provenSignInFlows } from '../proven-sign-in';\nimport { secondFactorFlows } from '../second-factor/flows';\nimport { signInCodeFlows } from '../sign-in-code';\nimport { stepUpFlows } from '../step-up/flows';\nimport type { AnyTypeApi } from './any-type-api';\nimport { findByEmailFlows } from './find-by-email';\nimport { findOrCreateFlows } from './find-or-create';\nimport { passwordFlows } from './password-flows';\nimport { recordFlows } from './record-flows';\n\n/**\n * Everything one user type answers, gathered from its flows: its records,\n * its password, its sign-in on the application's proof, its second factor,\n * its sign-in code and link, its step-up, its e-mails, the lookup by e-mail and the lookup that creates.\n */\nexport function typeApi(context: Context, type: ResolvedType): AnyTypeApi {\n\tconst at: At = (operation) =>\n\t\tcontext.config.single ? operation : `${type.name}.${operation}`;\n\tconst secondFactor = secondFactorFlows(context, type, at);\n\tconst signInCode = signInCodeFlows(context, type, at, secondFactor.finish);\n\n\treturn {\n\t\t...recordFlows(context, type, at),\n\t\t...passwordFlows(context, type, at, secondFactor.finish),\n\t\t...provenSignInFlows(context, type, at, secondFactor.finish),\n\n\t\tavatar: avatarFlows(context, type, at),\n\t\tsecondFactor: secondFactor.api,\n\t\tpasskeys: passkeyFlows(context, type, at),\n\t\tsignInCode,\n\t\tmagicLink: magicLinkFlows(context, type, at, secondFactor.finish),\n\t\tstepUp: stepUpFlows(context, type, at),\n\n\t\t...findByEmailFlows(context, type),\n\t\t...findOrCreateFlows(context, type, at),\n\t\t...emailFlows(context, type, at),\n\t};\n}\n",
|
|
154
|
+
"/** One write under a version, told apart from the race that moved it. */\n\nimport { StoreConflict } from '../../errors/janus-error';\nimport type {\n\tInvitationPatch,\n\tInvitationRecord,\n\tInvitationStore,\n} from '../port/types';\n\n/** What {@link writeUnderVersion} answers: the record as written (`null` when it is gone), or that the version moved. */\nexport type Written =\n\t| { readonly moved: false; readonly record: InvitationRecord | null }\n\t| { readonly moved: true };\n\n/**\n * `updateInvitation`, with a version that moved answered as `moved` — the\n * caller reads the invitation again — and every other failure thrown as it\n * came. Written with `allSettled` rather than a `catch`: the core keeps no\n * `catch` around a store call (`outage.scan.spec.ts`).\n */\nexport async function writeUnderVersion(\n\tinvitations: InvitationStore,\n\tcurrent: InvitationRecord,\n\tpatch: InvitationPatch,\n): Promise<Written> {\n\tconst [settled] = await Promise.allSettled([\n\t\tinvitations.updateInvitation(current.id, current.version, patch),\n\t]);\n\tif (settled.status === 'fulfilled') {\n\t\treturn { moved: false, record: settled.value };\n\t}\n\tif (\n\t\tsettled.reason instanceof StoreConflict &&\n\t\tsettled.reason.on === 'version'\n\t) {\n\t\treturn { moved: true };\n\t}\n\tthrow settled.reason;\n}\n",
|
|
155
|
+
"/** The claim on an invitation `accept` makes, and its release. */\n\nimport {\n\tInvitationInvalidError,\n\ttype InvitationRefusal,\n} from '../../errors/janus-error';\nimport type { Clock } from '../../time/clock';\nimport type { InvitationRecord, InvitationStore } from '../port/types';\nimport { writeUnderVersion } from './write';\n\n/**\n * The refusal for every code that cannot be accepted: one code, `INVITATION_INVALID`,\n * with `reason` saying why when the invitation is known (`unknown` otherwise,\n * and for what nothing may tell from an unknown code: an inactive account,\n * a login taken, a claim lost to a concurrent write).\n */\nexport function invalidCode(\n\twhere: string,\n\treason: InvitationRefusal = 'unknown',\n): InvitationInvalidError {\n\treturn new InvitationInvalidError(\n\t\t`${where}: this code names no pending invitation`,\n\t\t{ field: 'code', reason },\n\t);\n}\n\n/** Why a record cannot be used: `accepted` or `revoked` by its status, `expired` when pending past its lifetime, `null` when it can. */\nexport function refusalOf(\n\tclock: Clock,\n\tfound: InvitationRecord,\n): InvitationRefusal | null {\n\tif (found.status === 'accepted') return 'accepted';\n\tif (found.status === 'revoked') return 'revoked';\n\tif (found.status !== 'pending') return 'unknown';\n\treturn found.expiresAt.getTime() <= clock.now().getTime() ? 'expired' : null;\n}\n\n/**\n * Moves a pending, unlapsed invitation to `accepted` under its version: of\n * concurrent claims on one version exactly one wins, and the others — or an\n * accept racing a `resend` or a `revoke` — are `INVITATION_INVALID`.\n */\nexport async function claim(\n\tinvitations: InvitationStore,\n\tclock: Clock,\n\tfound: InvitationRecord | null,\n\twhere: string,\n): Promise<InvitationRecord> {\n\tconst now = clock.now();\n\tconst pending = pendingRecord(clock, found, where);\n\tconst written = await writeUnderVersion(invitations, pending, {\n\t\tupdatedAt: now,\n\t\tstatus: 'accepted',\n\t\tacceptedAt: now,\n\t});\n\tif (written.moved || written.record === null) throw invalidCode(where);\n\treturn written.record;\n}\n\n/** The invitation when it is pending and unlapsed, else the one refusal; writes nothing. */\nexport function pendingRecord(\n\tclock: Clock,\n\tfound: InvitationRecord | null,\n\twhere: string,\n): InvitationRecord {\n\tif (found === null) throw invalidCode(where);\n\tconst refusal = refusalOf(clock, found);\n\tif (refusal !== null) throw invalidCode(where, refusal);\n\treturn found;\n}\n\n/** Records who accepted, still under the claim. */\nexport async function recordAcceptor(\n\tinvitations: InvitationStore,\n\tclock: Clock,\n\tclaimed: InvitationRecord,\n\tuserId: InvitationRecord['acceptedBy'],\n\twhere: string,\n): Promise<InvitationRecord> {\n\t// A version that moved after the claim comes from a write outside Janus\n\t// (`changePending` refuses a non-pending invitation): the same refusal as a null.\n\tconst written = await writeUnderVersion(invitations, claimed, {\n\t\tupdatedAt: clock.now(),\n\t\tacceptedBy: userId,\n\t});\n\tif (written.moved || written.record === null) throw invalidCode(where);\n\treturn written.record;\n}\n\n/**\n * Puts a claimed invitation back to `pending`, as it was. Never throws: the\n * failure that made the release necessary is the one the caller sees, so a\n * release that fails too (a store outage, or a newer pending invitation\n * for the same address that took the place meanwhile) is a warning.\n */\nexport async function release(\n\tinvitations: InvitationStore,\n\tclock: Clock,\n\tclaimed: InvitationRecord,\n): Promise<void> {\n\tconst [released] = await Promise.allSettled([\n\t\tinvitations.updateInvitation(claimed.id, claimed.version, {\n\t\t\tupdatedAt: clock.now(),\n\t\t\tstatus: 'pending',\n\t\t\tacceptedBy: null,\n\t\t\tacceptedAt: null,\n\t\t}),\n\t]);\n\tif (released.status === 'rejected') {\n\t\tprocess.emitWarning(\n\t\t\t`janus: invitation ${claimed.id} could not be released after a failed accept: ${\n\t\t\t\treleased.reason instanceof Error\n\t\t\t\t\t? released.reason.name\n\t\t\t\t\t: typeof released.reason\n\t\t\t}`,\n\t\t\t{ code: 'JANUS_INVITATION_RELEASE_FAILED' },\n\t\t);\n\t}\n}\n",
|
|
156
|
+
"/** The events `janus({ invitations: { events } })` is called with, and the step that sends one. */\n\nimport { type Id, mintId } from '../../ids/id';\n\n/**\n * What happened to an invitation, once it is written:\n *\n * - `invitation.issued` — by `issue`, once the invitation is stored;\n * - `invitation.resent` — by `resend`: the old code stopped working;\n * - `invitation.revoked` — by `revoke`, and by an `issue` that took the place\n * of a pending invitation for the same address;\n * - `invitation.accepted` — by `accept`, once the invitee is a user and the\n * application's `onAccepted` returned.\n */\nexport type InvitationEventType =\n\t| 'invitation.issued'\n\t| 'invitation.resent'\n\t| 'invitation.revoked'\n\t| 'invitation.accepted';\n\n/**\n * An invitation event: **the invitation named by id and scope, and nothing\n * else** — never the invited address, the name or the code. Whoever receives\n * it reads the rest from where it is kept, if they may.\n */\nexport interface InvitationEvent {\n\t/** A UUIDv7 minted for this event: the key to deliver it once. */\n\treadonly id: Id;\n\treadonly type: InvitationEventType;\n\t/** When the write landed: the `updatedAt` it wrote, not when the listener ran. */\n\treadonly occurredAt: Date;\n\treadonly invitationId: string;\n\treadonly scope: string;\n\t/** Who sent the invitation, or `null` when the system did. */\n\treadonly invitedBy: Id | null;\n\t/** Who acted (`revoke` and `resend`'s `by`); absent when the call named nobody. */\n\treadonly by?: string;\n}\n\n/**\n * What `janus({ invitations: { events } })` takes: called once per event,\n * **after** the write landed and before the call answers — awaited. A\n * listener that throws fails nothing: the write happened, and the call\n * answers as it would have. The failure is a `JANUS_EVENT_FAILED` warning\n * naming the event, never silence.\n */\nexport type InvitationEventListener = (\n\tevent: InvitationEvent,\n) => void | Promise<void>;\n\n/** Hands one event to the listener after the write it reports. */\nexport async function emitInvitation(\n\tlistener: InvitationEventListener | null,\n\ttype: InvitationEventType,\n\tinvitation: {\n\t\treadonly id: string;\n\t\treadonly scope: string;\n\t\treadonly invitedBy: Id | null;\n\t},\n\toccurredAt: Date,\n\tby?: string,\n): Promise<void> {\n\tif (listener === null) return;\n\n\tconst event: InvitationEvent = Object.freeze({\n\t\tid: mintId(occurredAt.getTime()),\n\t\ttype,\n\t\toccurredAt: new Date(occurredAt.getTime()),\n\t\tinvitationId: invitation.id,\n\t\tscope: invitation.scope,\n\t\tinvitedBy: invitation.invitedBy,\n\t\t...(by === undefined ? {} : { by }),\n\t});\n\ttry {\n\t\tawait listener(event);\n\t} catch (failure) {\n\t\tprocess.emitWarning(\n\t\t\t`janus: the invitation events listener failed on ${type} ${event.id} for invitation ${invitation.id}: ${failure instanceof Error ? failure.name : typeof failure}`,\n\t\t\t{ code: 'JANUS_EVENT_FAILED' },\n\t\t);\n\t}\n}\n",
|
|
157
|
+
"/** What `invitations.issue` and its siblings accept from the application, refused as `INVITATION_INVALID` or `NOT_FOUND` when they are not. */\n\nimport { InvitationInvalidError } from '../../errors/janus-error';\nimport { isId } from '../../ids/id';\nimport { isStorable } from '../../stores/storable';\nimport { normalizeEmail } from '../config';\nimport { refId } from '../context';\nimport type { UserRef } from '../types';\n\nexport const SCOPE_MAX = 512;\nexport const ROLE_MAX = 100;\nexport const NAME_MAX = 100;\nexport const EMAIL_MAX = 254;\nexport const LOCALE_MAX = 35;\nexport const REF_MAX = 100;\n/** 32 bytes, base64url. */\nconst CODE = /^[A-Za-z0-9_-]{43}$/;\n\n/** A string of 1 to `max` characters once trimmed that every store can keep, or `null` when it is not one. */\nexport function shapedText(\n\tvalue: unknown,\n\tmax: number,\n\ttrim: boolean,\n): string | null {\n\tconst shaped = typeof value === 'string' && (trim ? value.trim() : value);\n\tif (\n\t\ttypeof shaped !== 'string' ||\n\t\tshaped.length < 1 ||\n\t\tshaped.length > max ||\n\t\t!isStorable(shaped)\n\t) {\n\t\treturn null;\n\t}\n\treturn shaped;\n}\n\n/** The address in the shape of one, normalised the way every e-mail is, or `null`. */\nexport function shapedEmail(value: unknown): string | null {\n\tconst text = shapedText(value, EMAIL_MAX, true);\n\tif (text === null) return null;\n\tconst email = normalizeEmail(text);\n\tconst at = email.indexOf('@');\n\tif (at < 1 || at !== email.lastIndexOf('@') || at === email.length - 1) {\n\t\treturn null;\n\t}\n\treturn email;\n}\n\n/** {@link shapedText}, thrown as `INVITATION_INVALID` on `field` when it is not one. */\nfunction text(\n\twhere: string,\n\tfield: 'name' | 'role' | 'scope' | 'email' | 'locale' | 'ref',\n\tvalue: unknown,\n\tmax: number,\n\ttrim: boolean,\n): string {\n\tconst shaped = shapedText(value, max, trim);\n\tif (shaped === null) {\n\t\tthrow new InvitationInvalidError(\n\t\t\t`${where}: ${field} must be 1 to ${max} characters`,\n\t\t\t{ field },\n\t\t);\n\t}\n\treturn shaped;\n}\n\n/** A scope is the application's own string, kept as given. */\nexport function scopeOf(where: string, value: unknown): string {\n\treturn text(where, 'scope', value, SCOPE_MAX, false);\n}\n\nexport function nameOf(where: string, value: unknown): string {\n\treturn text(where, 'name', value, NAME_MAX, true);\n}\n\nexport function roleOf(where: string, value: unknown): string {\n\treturn text(where, 'role', value, ROLE_MAX, false);\n}\n\nexport function localeOf(where: string, value: unknown): string | null {\n\tif (value === undefined || value === null) return null;\n\treturn text(where, 'locale', value, LOCALE_MAX, false);\n}\n\n/** The application's opaque reference, kept as given, or `null`. */\nexport function refOf(where: string, value: unknown): string | null {\n\tif (value === undefined || value === null) return null;\n\treturn text(where, 'ref', value, REF_MAX, false);\n}\n\n/** The address, normalised the way every e-mail is, with the shape of one. */\nexport function emailOf(where: string, value: unknown): string {\n\ttext(where, 'email', value, EMAIL_MAX, true);\n\tconst email = shapedEmail(value);\n\tif (email === null) {\n\t\tthrow new InvitationInvalidError(\n\t\t\t`${where}: email must be an address with one \"@\"`,\n\t\t\t{ field: 'email' },\n\t\t);\n\t}\n\treturn email;\n}\n\n/**\n * The id of the inviter, from a user or an id, or `null` for the system\n * (`invitedBy: null`). `undefined` is not `null`: a forgotten inviter is\n * refused rather than read as a system issue.\n */\nexport function inviterOf(where: string, value: UserRef | null): string | null {\n\tif (value === null) return null;\n\tconst id = refId(value);\n\tif (!isId(id)) {\n\t\tthrow new InvitationInvalidError(\n\t\t\t`${where}: invitedBy must be a user or a user id`,\n\t\t\t{ field: 'invitedBy' },\n\t\t);\n\t}\n\treturn id;\n}\n\n/** Whether `code` has the shape `issue` mints. Anything else names no invitation. */\nexport function isCode(code: unknown): code is string {\n\treturn typeof code === 'string' && CODE.test(code);\n}\n",
|
|
158
|
+
"/** Which user type an invitation is for: asked at `issue`, read back from the record afterwards. */\n\nimport { InvitationInvalidError } from '../../errors/janus-error';\nimport type { ResolvedType } from '../config';\nimport type { Context } from '../context';\nimport type { InvitationRecord } from '../port/types';\nimport type { AnyTypeApi } from '../users/any-type-api';\n\n/** The flows and configuration of one of the invitation user types, by name. */\nexport type InvitedType = (name: string) => {\n\treadonly api: AnyTypeApi;\n\treadonly type: ResolvedType;\n};\n\ntype Settings = NonNullable<Context['config']['invitations']>;\n\n/**\n * The user type `issue` was asked for. Absent, it is the only one configured;\n * with several, absent or unlisted is `INVITATION_INVALID` on `type`.\n */\nexport function issuedType(\n\twhere: string,\n\tsettings: Settings,\n\tvalue: unknown,\n): string {\n\tif (value === undefined && settings.types.length === 1) {\n\t\treturn settings.types[0];\n\t}\n\tif (typeof value === 'string' && settings.types.includes(value)) return value;\n\tthrow new InvitationInvalidError(\n\t\t`${where}: type must be one of ${settings.types.map((name) => `\"${name}\"`).join(', ')}`,\n\t\t{ field: 'type' },\n\t);\n}\n\n/** The type a record is for: the one stored, or the first listed for a record stored without one. */\nexport function typeOfRecord(\n\tsettings: Settings,\n\trecord: Pick<InvitationRecord, 'type'>,\n): string {\n\treturn record.type ?? settings.types[0];\n}\n\n/** The record's type when it is still configured, else `null`: such an invitation is listed but cannot be previewed or accepted. */\nexport function configuredType(\n\tsettings: Settings,\n\trecord: Pick<InvitationRecord, 'type'>,\n): string | null {\n\tconst type = typeOfRecord(settings, record);\n\treturn settings.types.includes(type) ? type : null;\n}\n",
|
|
159
|
+
"/** The user who holds an invitation's address, found or made, shared by the invitees of both kinds of user type. */\n\nimport { StoreConflict } from '../../errors/janus-error';\nimport type { AnyUser } from '../context';\nimport type { Invitation } from '../types';\nimport type { AnyTypeApi } from '../users/any-type-api';\nimport { invalidCode } from './claim';\n\nexport type Create = (\n\tinvitation: Invitation,\n) => Record<string, unknown> | Promise<Record<string, unknown>>;\n\n/** The invitee, and whether accepting proved their e-mail now (`false`: they are left as they are and sign in themselves). */\nexport interface Invitee {\n\treadonly user: AnyUser;\n\treadonly proved: boolean;\n}\n\n/**\n * The user who holds the invitation's address, made by `make` when nobody\n * does. A second login already taken by the new user, or an inactive account,\n * is as unknown as a spent code.\n */\nexport async function findInvitee(\n\ttyped: AnyTypeApi,\n\tinvitation: Invitation,\n\tmake: () => Promise<Record<string, unknown>>,\n\twhere: string,\n): Promise<{ readonly user: AnyUser; readonly created: boolean }> {\n\t// `allSettled`, not a `catch`: the core keeps no `catch` around a store call (`outage.scan.spec.ts`).\n\tconst [found] = await Promise.allSettled([\n\t\ttyped.findOrCreate(invitation.email, make),\n\t]);\n\tif (found.status === 'rejected') {\n\t\t// Another of the new user's logins is taken: nothing tells that from a spent code.\n\t\tif (found.reason instanceof StoreConflict && found.reason.on === 'login') {\n\t\t\tthrow invalidCode(where);\n\t\t}\n\t\tthrow found.reason;\n\t}\n\tif (!found.value.user.active) {\n\t\t// Nothing tells an inactive account from a spent code.\n\t\tthrow invalidCode(where);\n\t}\n\treturn found.value;\n}\n",
|
|
160
|
+
"/** The invitee of a user type with a password: the invitee chooses one for the address they were invited at. */\n\nimport { PasswordRequiredError } from '../../errors/janus-error';\nimport type { ResolvedType } from '../config';\nimport { checkPassword } from '../context';\nimport type { Invitation } from '../types';\nimport type { AnyTypeApi } from '../users/any-type-api';\nimport { type Create, findInvitee, type Invitee } from './find-invitee';\n\n/** A password is something to choose: a non-empty string. */\nfunction isChosen(password: unknown): password is string {\n\treturn typeof password === 'string' && password !== '';\n}\n\nfunction required(password: unknown, where: string): string {\n\tif (!isChosen(password)) {\n\t\tthrow new PasswordRequiredError(\n\t\t\t`${where}: choose a password to accept this invitation`,\n\t\t);\n\t}\n\treturn password;\n}\n\n/**\n * `proved` is `false` for a user who already held a proved e-mail and has a\n * password: they are left as they are, and the password given is ignored. One\n * with a proved e-mail and no password — what a `setPassword` that failed after\n * `proveFirst` leaves — gets the password given, if any, and is signed in.\n *\n * `PASSWORD_REQUIRED` is thrown before anything is written when the address\n * has no user, or has one whose e-mail was never proved. A user created here\n * holds no password until the e-mail is proved, because proving it drops\n * one (`verifyEmail.proveFirst`), and the password is set after.\n */\nexport async function passwordInvitee(\n\ttyped: AnyTypeApi,\n\ttype: ResolvedType,\n\tinvitation: Invitation,\n\tcreate: Create,\n\tpassword: unknown,\n\twhere: string,\n): Promise<Invitee> {\n\tconst { user, created } = await findInvitee(\n\t\ttyped,\n\t\tinvitation,\n\t\tasync () => {\n\t\t\tcheckPassword(type, required(password, where), where);\n\t\t\treturn create(invitation);\n\t\t},\n\t\twhere,\n\t);\n\tif (!created && user.emailVerified) {\n\t\t// A proved user with no password is what a failed `setPassword` leaves: the\n\t\t// retry sets the one given, so they can sign in. One who has a password is\n\t\t// left as they are.\n\t\tif (user.hasPassword || !isChosen(password)) return { user, proved: false };\n\t\tcheckPassword(type, password, where);\n\t\treturn { user: await typed.setPassword(user, password), proved: true };\n\t}\n\n\tconst chosen = required(password, where);\n\tcheckPassword(type, chosen, where);\n\tconst first = await typed.verifyEmail.proveFirst(user);\n\tconst withPassword = await typed.setPassword(first.user, chosen);\n\treturn { user: withPassword, proved: true };\n}\n",
|
|
161
|
+
"/** The invitee of a user type with no password: nothing to choose, so the e-mail is proved and the person signed in. */\n\nimport type { Invitation } from '../types';\nimport type { AnyTypeApi } from '../users/any-type-api';\nimport { type Create, findInvitee, type Invitee } from './find-invitee';\n\n/**\n * Nobody holds the address: the user `create` describes is made, their e-mail\n * proved. A user whose e-mail was never proved gets it proved\n * (`verifyEmail.proveFirst`, which drops what an unproved account held). A\n * user with a proved e-mail is left as they are (`proved: false`), and signs\n * in with the link or code they already use. A password given is ignored.\n */\nexport async function passwordlessInvitee(\n\ttyped: AnyTypeApi,\n\tinvitation: Invitation,\n\tcreate: Create,\n\twhere: string,\n): Promise<Invitee> {\n\tconst { user, created } = await findInvitee(\n\t\ttyped,\n\t\tinvitation,\n\t\tasync () => create(invitation),\n\t\twhere,\n\t);\n\tif (!created && user.emailVerified) return { user, proved: false };\n\tconst first = await typed.verifyEmail.proveFirst(user);\n\t// A holder proved in a race is left as they are: no session, `signIn`.\n\treturn { user: first.user, proved: first.proved };\n}\n",
|
|
162
|
+
"/** Who an invitation makes of the person who follows it: a new user, a user whose e-mail is now proved, or a user who already was. */\n\nimport type { ResolvedType } from '../config';\nimport type { Invitation } from '../types';\nimport type { AnyTypeApi } from '../users/any-type-api';\nimport type { Create, Invitee } from './find-invitee';\nimport { passwordInvitee } from './password-invitee';\nimport { passwordlessInvitee } from './passwordless-invitee';\n\n/**\n * The user the invitation is for, ready to be added to the scope: a type with\n * a password has its invitee choose one, a type without has nothing to choose.\n */\nexport function inviteeOf(\n\ttyped: AnyTypeApi,\n\ttype: ResolvedType,\n\tinvitation: Invitation,\n\tcreate: Create,\n\tpassword: unknown,\n\twhere: string,\n): Promise<Invitee> {\n\treturn type.password === null\n\t\t? passwordlessInvitee(typed, invitation, create, where)\n\t\t: passwordInvitee(typed, type, invitation, create, password, where);\n}\n",
|
|
163
|
+
"import type { InvitationRecord } from '../port/types';\nimport type { Invitation, InvitationPreview } from '../types';\n\n/**\n * An invitation as application code sees it: the record without its code's\n * hash and its version. `firstType` is the type a record stored without one\n * reads as: the first listed in `invitations.type`.\n */\nexport function toInvitation(\n\trecord: InvitationRecord,\n\tfirstType: string,\n): Invitation {\n\tconst {\n\t\tcodeHash: _hash,\n\t\tversion: _version,\n\t\tref,\n\t\ttype,\n\t\trevokedBy,\n\t\tresentBy,\n\t\t...invitation\n\t} = record;\n\treturn {\n\t\t...invitation,\n\t\tref: ref ?? null,\n\t\ttype: type ?? firstType,\n\t\trevokedBy: revokedBy ?? null,\n\t\tresentBy: resentBy ?? null,\n\t};\n}\n\n/** What a code's holder sees before accepting: no inviter, no status internals. */\nexport function toPreview(\n\trecord: InvitationRecord,\n\ttype: string,\n\tneedsPassword: boolean,\n): InvitationPreview {\n\treturn {\n\t\tid: record.id,\n\t\tscope: record.scope,\n\t\temail: record.email,\n\t\tname: record.name,\n\t\trole: record.role,\n\t\tlocale: record.locale,\n\t\ttype,\n\t\texpiresAt: record.expiresAt,\n\t\tneedsPassword,\n\t};\n}\n",
|
|
164
|
+
"/** `invitations.accept`: claim, make the invitee a user, tell the application, sign them in. */\n\nimport { InvitationRefusedError } from '../../errors/janus-error';\nimport type { Clock } from '../../time/clock';\nimport type { ResolvedType } from '../config';\nimport type { AnyUser, Context } from '../context';\nimport { deviceHint } from '../devices';\nimport type { InvitationRecord, InvitationStore } from '../port/types';\nimport { hashSecret } from '../secrets';\nimport type { AcceptedInvitation, InvitationsApi } from '../types';\nimport type { AnyTypeApi } from '../users/any-type-api';\nimport {\n\tclaim,\n\tinvalidCode,\n\tpendingRecord,\n\trecordAcceptor,\n\trelease,\n} from './claim';\nimport { emitInvitation } from './events';\nimport { isCode } from './input';\nimport { configuredType, type InvitedType } from './invited-type';\nimport { inviteeOf } from './invitee';\nimport { toInvitation } from './to-invitation';\n\nconst WHERE = 'invitations.accept';\n\ntype Settings = NonNullable<Context['config']['invitations']>;\ntype AcceptInput = Parameters<InvitationsApi['invitations']['accept']>[0];\n\n/** What happens between the claim and `onAccepted`'s return, and what it leaves. */\ninterface Prepared {\n\treadonly record: InvitationRecord;\n\treadonly proved: boolean;\n\treadonly user: AnyUser;\n}\n\nexport async function acceptInvitation(\n\tcontext: Context,\n\tsettings: Settings,\n\tinvitations: InvitationStore,\n\tinvited: InvitedType,\n\tinput: AcceptInput,\n): Promise<AcceptedInvitation> {\n\tconst { clock } = context;\n\tconst code: unknown = input?.code;\n\tif (!isCode(code)) throw invalidCode(WHERE);\n\tconst options = input.device === undefined ? {} : { device: input.device };\n\t// A device the instance cannot take is the caller's mistake: found before anything is claimed.\n\tdeviceHint(context, options, WHERE);\n\n\tconst found = await invitations.findInvitationByCodeHash(hashSecret(code));\n\t// A type no longer configured is as unknown as a spent code.\n\tconst name = found === null ? null : configuredType(settings, found);\n\tif (name === null) throw invalidCode(WHERE);\n\tconst { api: typed, type } = invited(name);\n\t// Before the claim: the hook may refuse while nothing has been written.\n\tawait beforeAccept(clock, settings, typed, found);\n\tconst claimed = await claim(invitations, clock, found, WHERE);\n\n\tconst prepared = await releasedOnFailure(invitations, clock, claimed, () =>\n\t\tprepare(\n\t\t\tcontext,\n\t\t\tsettings,\n\t\t\tinvitations,\n\t\t\ttyped,\n\t\t\ttype,\n\t\t\tclaimed,\n\t\t\tinput.password,\n\t\t),\n\t);\n\tconst invitation = toInvitation(prepared.record, settings.types[0]);\n\tawait emitInvitation(\n\t\tsettings.events,\n\t\t'invitation.accepted',\n\t\tprepared.record,\n\t\tprepared.record.updatedAt,\n\t);\n\n\t// From here the application has added the user: nothing is released.\n\tif (!prepared.proved) {\n\t\treturn { status: 'signIn', user: prepared.user, invitation };\n\t}\n\tconst result = await typed.signInProven(prepared.user.id, options);\n\treturn { ...result, invitation };\n}\n\n/**\n * Runs the application's `beforeAccept`, if it has one, on a pending\n * invitation and the user who already holds its e-mail. Writes nothing: a\n * refusal, or a failure of the hook or of the lookup, leaves the invitation\n * pending.\n */\nasync function beforeAccept(\n\tclock: Clock,\n\tsettings: Settings,\n\ttyped: AnyTypeApi,\n\tfound: InvitationRecord | null,\n): Promise<void> {\n\tif (settings.beforeAccept === null) return;\n\tconst pending = pendingRecord(clock, found, WHERE);\n\tconst existing = await typed.findByEmail(pending.email);\n\t// Nothing tells a deactivated account from a spent code: the hook never sees one.\n\tif (existing !== null && !existing.active) throw invalidCode(WHERE);\n\tconst proceed = await settings.beforeAccept({\n\t\tinvitation: toInvitation(pending, settings.types[0]),\n\t\tuser: existing === null ? null : { id: existing.id, type: existing.type },\n\t});\n\tif (!proceed) {\n\t\tthrow new InvitationRefusedError(\n\t\t\t`${WHERE}: the application refused this acceptance; the invitation is still pending`,\n\t\t);\n\t}\n}\n\n/** The invitee as a user, the acceptor recorded, then the application's `onAccepted`. */\nasync function prepare(\n\tcontext: Context,\n\tsettings: Settings,\n\tinvitations: InvitationStore,\n\ttyped: AnyTypeApi,\n\ttype: ResolvedType,\n\tclaimed: InvitationRecord,\n\tpassword: unknown,\n): Promise<Prepared> {\n\tconst { user, proved } = await inviteeOf(\n\t\ttyped,\n\t\ttype,\n\t\ttoInvitation(claimed, settings.types[0]),\n\t\tsettings.create,\n\t\tpassword,\n\t\tWHERE,\n\t);\n\tconst record = await recordAcceptor(\n\t\tinvitations,\n\t\tcontext.clock,\n\t\tclaimed,\n\t\tuser.id,\n\t\tWHERE,\n\t);\n\tawait settings.onAccepted({\n\t\tinvitation: toInvitation(record, settings.types[0]),\n\t\tuser: { id: user.id, type: user.type },\n\t});\n\treturn { record, proved, user };\n}\n\n/**\n * Runs `work`; when it fails, puts the claim back and rethrows what it threw.\n * Written with `allSettled` rather than a `catch`: the core keeps no `catch`\n * around a store call (`outage.scan.spec.ts`).\n */\nasync function releasedOnFailure<T>(\n\tinvitations: InvitationStore,\n\tclock: Clock,\n\tclaimed: InvitationRecord,\n\twork: () => Promise<T>,\n): Promise<T> {\n\tconst [settled] = await Promise.allSettled([work()]);\n\tif (settled.status === 'fulfilled') return settled.value;\n\tconst held = await current(invitations, claimed);\n\t// Revoked (or anything else) meanwhile: not the claim any more, left alone.\n\tif (held.status === 'accepted') await release(invitations, clock, held);\n\tthrow settled.reason;\n}\n\n/** The claim as stored now: the acceptor may have been recorded since it was made. */\nasync function current(\n\tinvitations: InvitationStore,\n\tclaimed: InvitationRecord,\n): Promise<InvitationRecord> {\n\tconst [read] = await Promise.allSettled([\n\t\tinvitations.findInvitation(claimed.id),\n\t]);\n\treturn read.status === 'fulfilled' && read.value !== null\n\t\t? read.value\n\t\t: claimed;\n}\n",
|
|
165
|
+
"/** Applies a patch to a pending invitation of one scope, under its version. */\n\nimport {\n\tInvitationNotPendingError,\n\tNotFoundError,\n\tStoreConflict,\n} from '../../errors/janus-error';\nimport { isId } from '../../ids/id';\nimport type { Clock } from '../../time/clock';\nimport type {\n\tInvitationPatch,\n\tInvitationRecord,\n\tInvitationStore,\n} from '../port/types';\nimport { writeUnderVersion } from './write';\n\nconst ATTEMPTS = 3;\n\n/**\n * `NOT_FOUND` for an invitation that is not in this scope, whatever the\n * reason; `INVITATION_NOT_PENDING` for one that is final. `before` runs on the\n * pending record just before its write, and may refuse it. A version that\n * moved meanwhile is read again, a few times.\n */\nexport async function changePending(\n\tinvitations: InvitationStore,\n\tclock: Clock,\n\twhere: string,\n\tinput: { readonly id: string; readonly scope: string },\n\tpatch: (now: Date) => Omit<InvitationPatch, 'updatedAt'>,\n\tbefore?: (found: InvitationRecord, now: Date) => Promise<void>,\n): Promise<{ readonly record: InvitationRecord; readonly now: Date }> {\n\tconst missing = () => new NotFoundError(`${where}: no such invitation`);\n\tconst id: unknown = input?.id;\n\tconst scope: unknown = input?.scope;\n\tif (typeof id !== 'string' || !isId(id) || typeof scope !== 'string') {\n\t\tthrow missing();\n\t}\n\n\tfor (let attempt = 0; attempt < ATTEMPTS; attempt += 1) {\n\t\tconst found = await invitations.findInvitation(id);\n\t\t// An id of another scope is no invitation at all: a request-supplied\n\t\t// id must not tell which invitations exist elsewhere.\n\t\tif (found === null || found.scope !== scope) throw missing();\n\t\tif (found.status !== 'pending') {\n\t\t\tthrow new InvitationNotPendingError(\n\t\t\t\t`${where}: the invitation is ${found.status}`,\n\t\t\t);\n\t\t}\n\n\t\tconst now = clock.now();\n\t\tawait before?.(found, now);\n\t\tconst written = await writeUnderVersion(invitations, found, {\n\t\t\tupdatedAt: now,\n\t\t\t...patch(now),\n\t\t});\n\t\tif (written.moved) continue;\n\t\tif (written.record === null) throw missing();\n\t\treturn { record: written.record, now };\n\t}\n\tthrow new StoreConflict('version', `${where}: the invitation kept changing`, {\n\t\toperation: 'updateInvitation',\n\t});\n}\n",
|
|
166
|
+
"/** The pending invitation an address holds in a scope, lapsed or not. */\n\nimport { MAX_PAGE_SIZE } from '../../pagination/cursor-page';\nimport type { InvitationRecord, InvitationStore } from '../port/types';\n\n/** The pending invitation of an address in a scope — lapsed or not — or `null`. */\nexport async function findPending(\n\tinvitations: InvitationStore,\n\tscope: string,\n\temail: string,\n): Promise<InvitationRecord | null> {\n\tif (invitations.findPendingInvitation !== undefined) {\n\t\treturn invitations.findPendingInvitation(scope, email);\n\t}\n\tlet after: string | null = null;\n\tdo {\n\t\tconst page = await invitations.listScopeInvitations(scope, {\n\t\t\tstatus: 'pending',\n\t\t\tfirst: MAX_PAGE_SIZE,\n\t\t\tafter,\n\t\t});\n\t\tconst found = page.items.find((record) => record.email === email);\n\t\tif (found !== undefined) return found;\n\t\tafter = page.nextCursor;\n\t} while (after !== null);\n\treturn null;\n}\n",
|
|
167
|
+
"/**\n * An id that is decided by what it names, not drawn: a UUIDv7 whose timestamp\n * is given and whose other bits come from a seed. The same timestamp and seed\n * always give the same id, so writing a record twice writes it once.\n *\n * Not exported from the package: only the import of invitation history uses it.\n */\n\nimport { createHash } from 'node:crypto';\nimport type { Id } from './id';\n\n/**\n * `sha256` of the parts, hex. Each part is prefixed by its length, so\n * `('ab', 'c')` and `('a', 'bc')` give two seeds.\n */\nexport function seedOf(...parts: readonly string[]): string {\n\tconst hash = createHash('sha256');\n\tfor (const part of parts) {\n\t\thash.update(`${part.length}:`);\n\t\thash.update(part);\n\t}\n\treturn hash.digest('hex');\n}\n\n/**\n * A UUIDv7 leading with `at` (milliseconds) and carrying the first 74 bits\n * of `seed`, a hex string of at least 19 digits (as {@link seedOf} gives), in\n * the place of the sequence and the random tail.\n *\n * Throws a `TypeError` for a time outside 0 to 2**48 - 1 (a UUIDv7 holds 48 bits).\n *\n * Two records of one millisecond order by their seed: a total order, stable\n * from one run to the next, not the order they were created in.\n */\nexport function derivedId(at: number, seed: string): Id {\n\tif (!Number.isSafeInteger(at) || at < 0 || at >= 2 ** 48) {\n\t\tthrow new TypeError(\n\t\t\t'derivedId: at is a millisecond time of 0 to 2**48 - 1',\n\t\t);\n\t}\n\tconst time = at.toString(16).padStart(12, '0');\n\t// 12 bits for the sequence's place, then 62 for the tail, the variant on top.\n\tconst sequence = seed.slice(0, 3);\n\tconst variant = (0x8 | (Number.parseInt(seed.charAt(3), 16) & 0x3)).toString(\n\t\t16,\n\t);\n\tconst tail = seed.slice(4, 19);\n\treturn `${time.slice(0, 8)}-${time.slice(8)}-7${sequence}-${variant}${tail.slice(0, 3)}-${tail.slice(3)}`;\n}\n",
|
|
168
|
+
"/** One record of `invitations.importHistory`, checked into an `InvitationRecord` or a refusal that names a shape, never a value. */\n\nimport { derivedId, seedOf } from '../../ids/derived';\nimport { isId } from '../../ids/id';\nimport type { Context } from '../context';\nimport type { InvitationRecord } from '../port/types';\nimport type { HistoryRefusal } from '../types';\nimport {\n\tLOCALE_MAX,\n\tNAME_MAX,\n\tREF_MAX,\n\tROLE_MAX,\n\tSCOPE_MAX,\n\tshapedEmail,\n\tshapedText,\n} from './input';\n\ntype Settings = NonNullable<Context['config']['invitations']>;\n\n/** The longest `key` the application may give. */\nexport const KEY_MAX = 100;\n\n/** A record that cannot be imported: why, and on which field when it is `invalid`. */\nexport interface Refused {\n\treadonly ok: false;\n\treadonly key: string | null;\n\treadonly id: string | null;\n\treadonly reason: HistoryRefusal;\n\treadonly field?: string;\n}\n\n/** A record ready for the store. */\nexport interface Checked {\n\treadonly ok: true;\n\treadonly key: string;\n\treadonly record: InvitationRecord;\n}\n\nfunction invalid(key: string | null, field: string): Refused {\n\treturn { ok: false, key, id: null, reason: 'invalid', field };\n}\n\nfunction dateOf(value: unknown): Date | null {\n\treturn value instanceof Date && !Number.isNaN(value.getTime()) ? value : null;\n}\n\n/** A `createdAt` the id can carry: a Date of 0 to 2**48 - 1 milliseconds. */\nfunction createdAtOf(value: unknown): Date | null {\n\tconst date = dateOf(value);\n\tif (date === null) return null;\n\tconst time = date.getTime();\n\treturn Number.isSafeInteger(time) && time >= 0 && time < 2 ** 48\n\t\t? date\n\t\t: null;\n}\n\n/** A janus user id (given as a user or an id), `null` when absent, `undefined` when it is neither. */\nfunction userIdOf(value: unknown): string | null | undefined {\n\tif (value === undefined || value === null) return null;\n\tconst id: unknown =\n\t\ttypeof value === 'object' ? (value as { id?: unknown }).id : value;\n\treturn typeof id === 'string' && isId(id) ? id : undefined;\n}\n\n/** The optional text `field` holds: `null` when absent, `undefined` when it is not valid. */\nfunction optionalText(value: unknown, max: number): string | null | undefined {\n\tif (value === undefined || value === null) return null;\n\treturn shapedText(value, max, false) ?? undefined;\n}\n\n/** The user type: the only one configured when absent, else a listed name. */\nfunction typeOf(\n\tsettings: Settings,\n\tkey: string,\n\tvalue: unknown,\n): string | Refused {\n\tif ((value === undefined || value === null) && settings.types.length === 1) {\n\t\treturn settings.types[0];\n\t}\n\tif (typeof value !== 'string') return invalid(key, 'type');\n\tif (!settings.types.includes(value)) {\n\t\treturn { ok: false, key, id: null, reason: 'unknown-type' };\n\t}\n\treturn value;\n}\n\n/** What the status adds to a record: who and when it was answered. */\ninterface Answer {\n\treadonly acceptedAt: Date | null;\n\treadonly acceptedBy: string | null;\n\treadonly revokedAt: Date | null;\n\treadonly revokedBy: string | null;\n}\n\nfunction answerOf(\n\traw: Record<string, unknown>,\n\tkey: string,\n\tstatus: 'accepted' | 'revoked' | 'pending',\n): Answer | Refused {\n\tconst none = {\n\t\tacceptedAt: null,\n\t\tacceptedBy: null,\n\t\trevokedAt: null,\n\t\trevokedBy: null,\n\t};\n\tif (status === 'pending') return none;\n\tconst prefix = status === 'accepted' ? 'accepted' : 'revoked';\n\tconst at = dateOf(raw[`${prefix}At`]);\n\tif (at === null) return invalid(key, `${prefix}At`);\n\tconst by = userIdOf(raw[`${prefix}By`]);\n\tif (by === undefined) return invalid(key, `${prefix}By`);\n\treturn status === 'accepted'\n\t\t? { ...none, acceptedAt: at, acceptedBy: by }\n\t\t: { ...none, revokedAt: at, revokedBy: by };\n}\n\n/**\n * Checks `input` — anything an application passed — and builds the record the\n * store keeps: the derived id and unusable code hash, `version: 0`, the\n * dates the record gave and the defaults the rest take.\n */\nexport function checkHistoryRecord(\n\tcontext: Context,\n\tsettings: Settings,\n\tinput: unknown,\n): Checked | Refused {\n\tconst raw = (\n\t\ttypeof input === 'object' && input !== null ? input : {}\n\t) as Record<string, unknown>;\n\tconst key = shapedText(raw['key'], KEY_MAX, false);\n\tif (key === null) return invalid(null, 'key');\n\tconst scope = shapedText(raw['scope'], SCOPE_MAX, false);\n\tif (scope === null) return invalid(key, 'scope');\n\tconst email = shapedEmail(raw['email']);\n\tif (email === null) return invalid(key, 'email');\n\tconst name = shapedText(raw['name'], NAME_MAX, true);\n\tif (name === null) return invalid(key, 'name');\n\tconst role = shapedText(raw['role'], ROLE_MAX, false);\n\tif (role === null) return invalid(key, 'role');\n\tconst locale = optionalText(raw['locale'], LOCALE_MAX);\n\tif (locale === undefined) return invalid(key, 'locale');\n\tconst ref = optionalText(raw['ref'], REF_MAX);\n\tif (ref === undefined) return invalid(key, 'ref');\n\tconst invitedBy = userIdOf(raw['invitedBy']);\n\tif (invitedBy === undefined) return invalid(key, 'invitedBy');\n\tconst type = typeOf(settings, key, raw['type']);\n\tif (typeof type !== 'string') return type;\n\tconst status = raw['status'];\n\tif (status !== 'accepted' && status !== 'revoked' && status !== 'pending') {\n\t\treturn invalid(key, 'status');\n\t}\n\tconst createdAt = createdAtOf(raw['createdAt']);\n\tif (createdAt === null) return invalid(key, 'createdAt');\n\tconst expiresAt =\n\t\traw['expiresAt'] === undefined\n\t\t\t? new Date(createdAt.getTime() + settings.lifetimeMs)\n\t\t\t: dateOf(raw['expiresAt']);\n\tif (expiresAt === null) return invalid(key, 'expiresAt');\n\tconst answer = answerOf(raw, key, status);\n\tif ('ok' in answer) return answer;\n\n\tconst id = derivedId(createdAt.getTime(), seedOf('janus-import', scope, key));\n\tconst live = expiresAt.getTime() > context.clock.now().getTime();\n\tif (status === 'pending' && live) {\n\t\treturn { ok: false, key, id, reason: 'live-pending' };\n\t}\n\tconst updatedAt =\n\t\traw['updatedAt'] === undefined\n\t\t\t? (answer.acceptedAt ?? answer.revokedAt ?? createdAt)\n\t\t\t: dateOf(raw['updatedAt']);\n\tif (updatedAt === null) return invalid(key, 'updatedAt');\n\n\treturn {\n\t\tok: true,\n\t\tkey,\n\t\trecord: {\n\t\t\tid,\n\t\t\tscope,\n\t\t\temail,\n\t\t\tname,\n\t\t\trole,\n\t\t\tlocale,\n\t\t\tref,\n\t\t\ttype,\n\t\t\t// Nothing a code hashes to: the prefix is not hex, so no code matches it.\n\t\t\tcodeHash: `import:${seedOf(scope, key)}`,\n\t\t\tinvitedBy,\n\t\t\tstatus,\n\t\t\tversion: 0,\n\t\t\tcreatedAt,\n\t\t\tupdatedAt,\n\t\t\texpiresAt,\n\t\t\t...answer,\n\t\t\tresentBy: null,\n\t\t},\n\t};\n}\n",
|
|
169
|
+
"/** `invitations.importHistory`: copies the old system's invitations in as history, once each, with no event, mail or code. */\n\nimport type { Context } from '../context';\nimport type { InvitationStore } from '../port/types';\nimport type {\n\tHistoryRefusal,\n\tImportHistoryItem,\n\tImportHistoryReport,\n} from '../types';\nimport { findPending } from './find-pending';\nimport { checkHistoryRecord } from './history-input';\n\nconst WHERE = 'invitations.importHistory';\n/** At most this many records per call: a bigger import is cut into calls. */\nexport const IMPORT_MAX = 1000;\n\ntype Settings = NonNullable<Context['config']['invitations']>;\n\n/** `dryRun`, or a `TypeError` for options that are not `{ dryRun?: boolean }`. */\nfunction dryRunOf(options: unknown): boolean {\n\tif (options === undefined) return false;\n\tif (\n\t\ttypeof options !== 'object' ||\n\t\toptions === null ||\n\t\tArray.isArray(options)\n\t) {\n\t\tthrow new TypeError(`${WHERE}: options must be an object`);\n\t}\n\tconst { dryRun } = options as { dryRun?: unknown };\n\tif (dryRun !== undefined && typeof dryRun !== 'boolean') {\n\t\tthrow new TypeError(`${WHERE}: options.dryRun must be a boolean`);\n\t}\n\treturn dryRun === true;\n}\n\nfunction refused(\n\tkey: string | null,\n\tid: string | null,\n\treason: HistoryRefusal,\n\tfield?: string,\n): ImportHistoryItem {\n\treturn {\n\t\tkey,\n\t\tid,\n\t\toutcome: 'refused',\n\t\treason,\n\t\t...(field === undefined ? {} : { field }),\n\t};\n}\n\nexport async function importHistory(\n\tcontext: Context,\n\tsettings: Settings,\n\tinvitations: InvitationStore,\n\trecords: unknown,\n\toptions: unknown,\n): Promise<ImportHistoryReport> {\n\tif (!Array.isArray(records)) {\n\t\tthrow new TypeError(`${WHERE}: records must be an array`);\n\t}\n\tif (records.length > IMPORT_MAX) {\n\t\tthrow new TypeError(`${WHERE}: at most ${IMPORT_MAX} records per call`);\n\t}\n\tconst dryRun = dryRunOf(options);\n\n\tconst items: ImportHistoryItem[] = [];\n\t// What this call has taken so far, so a repeat is refused before the store sees it.\n\tconst keys = new Set<string>();\n\tconst held = new Set<string>();\n\tfor (const input of records as readonly unknown[]) {\n\t\tconst checked = checkHistoryRecord(context, settings, input);\n\t\tif (!checked.ok) {\n\t\t\titems.push(\n\t\t\t\trefused(checked.key, checked.id, checked.reason, checked.field),\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tconst { key, record } = checked;\n\t\tconst keyed = JSON.stringify([record.scope, key]);\n\t\tif (keys.has(keyed)) {\n\t\t\titems.push(refused(key, record.id, 'duplicate-key'));\n\t\t\tcontinue;\n\t\t}\n\t\tkeys.add(keyed);\n\n\t\t// The code hash derives from the scope and key alone, so it finds the record\n\t\t// whatever its `createdAt` was: the same id is `present`, another is a key\n\t\t// imported under a different `createdAt`.\n\t\tconst known = await invitations.findInvitationByCodeHash(record.codeHash);\n\t\tif (known !== null) {\n\t\t\titems.push(\n\t\t\t\tknown.id === record.id\n\t\t\t\t\t? { key, id: record.id, outcome: 'present' }\n\t\t\t\t\t: refused(key, known.id, 'key-taken'),\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tif (record.status === 'pending') {\n\t\t\tconst place = JSON.stringify([record.scope, record.email]);\n\t\t\tconst taken =\n\t\t\t\theld.has(place) ||\n\t\t\t\t(await findPending(invitations, record.scope, record.email)) !== null;\n\t\t\tif (taken) {\n\t\t\t\titems.push(refused(key, record.id, 'pending-held'));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\theld.add(place);\n\t\t}\n\t\t// The store answers false only when a pending invitation took the place meanwhile.\n\t\tif (!dryRun && !(await invitations.insertInvitation(record))) {\n\t\t\titems.push(refused(key, record.id, 'pending-held'));\n\t\t\tcontinue;\n\t\t}\n\t\titems.push({ key, id: record.id, outcome: 'inserted' });\n\t}\n\n\tconst count = (outcome: ImportHistoryItem['outcome']) =>\n\t\titems.filter((item) => item.outcome === outcome).length;\n\treturn {\n\t\tdryRun,\n\t\tinserted: count('inserted'),\n\t\tpresent: count('present'),\n\t\trefused: count('refused'),\n\t\titems,\n\t};\n}\n",
|
|
170
|
+
"/** The refusal for a scope at its `maxPending`, shared by `issue` and `resend`. */\n\nimport { InvitationLimitError } from '../../errors/janus-error';\nimport type { Context } from '../context';\n\ntype Settings = NonNullable<Context['config']['invitations']>;\n\nexport function limitReached(\n\twhere: string,\n\tsettings: Settings,\n): InvitationLimitError {\n\treturn new InvitationLimitError(\n\t\t`${where}: the scope already holds ${settings.maxPending} pending invitations — revoke one first`,\n\t\tsettings.maxPending === null ? {} : { maxActive: settings.maxPending },\n\t);\n}\n",
|
|
171
|
+
"/** `invitations.issue`: finds room, takes the place of a pending invitation for the same address, inserts, then checks the limit again. */\n\nimport { StoreConflict } from '../../errors/janus-error';\nimport { mintId } from '../../ids/id';\nimport type { Context } from '../context';\nimport type { InvitationRecord, InvitationStore } from '../port/types';\nimport { hashSecret, mintSecret } from '../secrets';\nimport type { InvitationsApi, IssuedInvitation } from '../types';\nimport { emitInvitation } from './events';\nimport { findPending } from './find-pending';\nimport {\n\temailOf,\n\tinviterOf,\n\tlocaleOf,\n\tnameOf,\n\trefOf,\n\troleOf,\n\tscopeOf,\n} from './input';\nimport { issuedType } from './invited-type';\nimport { limitReached } from './limit';\nimport { toInvitation } from './to-invitation';\nimport { writeUnderVersion } from './write';\n\nconst WHERE = 'invitations.issue';\nconst ATTEMPTS = 3;\n\ntype Settings = NonNullable<Context['config']['invitations']>;\ntype IssueInput = Parameters<InvitationsApi['invitations']['issue']>[0];\n\nexport async function issueInvitation(\n\tcontext: Context,\n\tsettings: Settings,\n\tinvitations: InvitationStore,\n\tinput: IssueInput,\n): Promise<IssuedInvitation> {\n\tconst { clock } = context;\n\tconst scope = scopeOf(WHERE, input?.scope);\n\tconst email = emailOf(WHERE, input?.email);\n\tconst name = nameOf(WHERE, input?.name);\n\tconst role = roleOf(WHERE, input?.role);\n\tconst locale = localeOf(WHERE, input?.locale);\n\tconst invitedBy = inviterOf(WHERE, input?.invitedBy);\n\tconst ref = refOf(WHERE, input?.ref);\n\tconst type = issuedType(WHERE, settings, input?.type);\n\n\tawait checkRoom(context, settings, invitations, scope, email);\n\t// The invitation this issue may replace: only the one pending before it began.\n\tconst preexisting = await findPending(invitations, scope, email);\n\n\tconst code = mintSecret();\n\tconst createdAt = clock.now();\n\tconst record: InvitationRecord = {\n\t\tid: mintId(createdAt.getTime()),\n\t\tscope,\n\t\temail,\n\t\tname,\n\t\trole,\n\t\tlocale,\n\t\tref,\n\t\ttype,\n\t\tcodeHash: hashSecret(code),\n\t\tinvitedBy,\n\t\tstatus: 'pending',\n\t\tversion: 0,\n\t\tcreatedAt,\n\t\tupdatedAt: createdAt,\n\t\texpiresAt: new Date(createdAt.getTime() + settings.lifetimeMs),\n\t\tacceptedBy: null,\n\t\tacceptedAt: null,\n\t\trevokedAt: null,\n\t};\n\n\tawait insertInPlaceOfPending(\n\t\tcontext,\n\t\tsettings,\n\t\tinvitations,\n\t\trecord,\n\t\tpreexisting?.id ?? null,\n\t);\n\tawait checkTypeKept(settings, invitations, record);\n\n\t// The count after the insert stays as the race guard: two issues racing at\n\t// the limit both insert, both count the other, and both are refused.\n\tif (settings.maxPending !== null) {\n\t\tconst pending = await invitations.countPendingInvitations(\n\t\t\tscope,\n\t\t\tclock.now(),\n\t\t);\n\t\tif (pending > settings.maxPending) {\n\t\t\tawait withdraw(context, settings, invitations, record);\n\t\t\tthrow limitReached(WHERE, settings);\n\t\t}\n\t}\n\n\tawait emitInvitation(settings.events, 'invitation.issued', record, createdAt);\n\treturn { invitation: toInvitation(record, type), code };\n}\n\n/**\n * With several types, a store that drops `type` would turn every invitation\n * into the first one listed: the record is read back once, and a store that\n * did not keep it is a `TypeError` naming the fix.\n */\nasync function checkTypeKept(\n\tsettings: Settings,\n\tinvitations: InvitationStore,\n\trecord: InvitationRecord,\n): Promise<void> {\n\tif (settings.types.length < 2) return;\n\tconst stored = await invitations.findInvitation(record.id);\n\tif (stored === null || stored.type !== record.type) {\n\t\tthrow new TypeError(\n\t\t\t`${WHERE}: the invitation store did not keep the invitation's type: with several invitation types, the store must keep \\`type\\` — update the adapter`,\n\t\t);\n\t}\n}\n\n/** Refuses a scope at its limit, unless this address's own pending invitation is about to make room. */\nasync function checkRoom(\n\tcontext: Context,\n\tsettings: Settings,\n\tinvitations: InvitationStore,\n\tscope: string,\n\temail: string,\n): Promise<void> {\n\tif (settings.maxPending === null) return;\n\tconst now = context.clock.now();\n\tconst pending = await invitations.countPendingInvitations(scope, now);\n\tif (pending < settings.maxPending) return;\n\n\tconst held = await findPending(invitations, scope, email);\n\tif (held === null || held.expiresAt.getTime() <= now.getTime()) {\n\t\tthrow limitReached(WHERE, settings);\n\t}\n}\n\n/**\n * Inserts the record. One pending invitation holds a scope and address, a\n * constraint of the store: when it refuses, the one that holds the place is\n * revoked — **lapsed or not**, it is still `pending` — and the insert is\n * tried again, a few times in case another issue wins the place meanwhile.\n *\n * **Only the invitation that was pending when this issue began is replaced**\n * (`replaceable`). One that appeared since is a concurrent issue's winner:\n * this issue loses to it with `INVITATION_PENDING` and leaves it pending, so\n * racing issues for one address end with exactly one pending invitation.\n */\nasync function insertInPlaceOfPending(\n\tcontext: Context,\n\tsettings: Settings,\n\tinvitations: InvitationStore,\n\trecord: InvitationRecord,\n\treplaceable: string | null,\n): Promise<void> {\n\tfor (let attempt = 0; attempt < ATTEMPTS; attempt += 1) {\n\t\tif (await invitations.insertInvitation(record)) return;\n\n\t\tconst held = await findPending(invitations, record.scope, record.email);\n\t\tif (held === null) continue;\n\t\tif (held.id !== replaceable) break;\n\t\tconst revokedAt = context.clock.now();\n\t\tconst written = await writeUnderVersion(invitations, held, {\n\t\t\tupdatedAt: revokedAt,\n\t\t\tstatus: 'revoked',\n\t\t\trevokedAt,\n\t\t});\n\t\t// Changed since it was read: read it again on the next attempt.\n\t\tif (written.moved) continue;\n\t\tawait emitInvitation(\n\t\t\tsettings.events,\n\t\t\t'invitation.revoked',\n\t\t\theld,\n\t\t\trevokedAt,\n\t\t);\n\t}\n\tthrow new StoreConflict(\n\t\t'pending',\n\t\t`${WHERE}: another pending invitation holds this scope and address`,\n\t\t{ operation: 'insertInvitation' },\n\t);\n}\n\n/** Revokes an invitation made over the limit by a race; a failure there is warned of, the refusal stands. */\nasync function withdraw(\n\tcontext: Context,\n\tsettings: Settings,\n\tinvitations: InvitationStore,\n\trecord: InvitationRecord,\n): Promise<void> {\n\tconst revokedAt = context.clock.now();\n\tconst [revoked] = await Promise.allSettled([\n\t\tinvitations.updateInvitation(record.id, record.version, {\n\t\t\tupdatedAt: revokedAt,\n\t\t\tstatus: 'revoked',\n\t\t\trevokedAt,\n\t\t}),\n\t]);\n\tif (revoked.status === 'rejected') {\n\t\tprocess.emitWarning(\n\t\t\t`janus: an invitation could not be revoked after its issue went over the limit: ${\n\t\t\t\trevoked.reason instanceof Error\n\t\t\t\t\t? revoked.reason.name\n\t\t\t\t\t: typeof revoked.reason\n\t\t\t}`,\n\t\t\t{ code: 'JANUS_INVITATION_REVOKE_FAILED' },\n\t\t);\n\t\treturn;\n\t}\n\tawait emitInvitation(\n\t\tsettings.events,\n\t\t'invitation.revoked',\n\t\trecord,\n\t\trevokedAt,\n\t);\n}\n",
|
|
172
|
+
"/** `invitations.get`, `list`, `count` and `preview`: reads that write nothing. */\n\nimport { createHash } from 'node:crypto';\nimport { CursorFilterMismatchError } from '../../errors/janus-error';\nimport { isId } from '../../ids/id';\nimport {\n\tinvalidCursor,\n\tMAX_PAGE_SIZE,\n\tpageLimit,\n} from '../../pagination/cursor-page';\nimport type { Clock } from '../../time/clock';\nimport type { Context } from '../context';\nimport type {\n\tInvitationFilter,\n\tInvitationStatus,\n\tInvitationStore,\n} from '../port/types';\nimport type { InvitationsApi } from '../types';\nimport type { InvitedType } from './invited-type';\nimport { previewInvitation } from './preview';\nimport { toInvitation } from './to-invitation';\n\ntype Api = InvitationsApi['invitations'];\n\nconst STATUSES: readonly InvitationStatus[] = [\n\t'pending',\n\t'accepted',\n\t'revoked',\n];\n\n/** The filters of `list` and `count`, validated: a wrong one is a `TypeError`, never an unfiltered answer. */\nfunction filterOf(\n\twhere: string,\n\tinput:\n\t\t| { status?: unknown; role?: unknown; ref?: unknown; lapsed?: unknown }\n\t\t| undefined,\n\tnow: Date,\n): InvitationFilter {\n\tconst status = input?.status ?? null;\n\tif (status !== null && !STATUSES.includes(status as InvitationStatus)) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: status must be \"pending\", \"accepted\" or \"revoked\", or absent`,\n\t\t);\n\t}\n\tconst role = input?.role ?? null;\n\tif (role !== null && (typeof role !== 'string' || role === '')) {\n\t\tthrow new TypeError(`${where}: role must be a non-empty string, or absent`);\n\t}\n\tconst ref = input?.ref ?? null;\n\tif (ref !== null && (typeof ref !== 'string' || ref === '')) {\n\t\tthrow new TypeError(`${where}: ref must be a non-empty string, or absent`);\n\t}\n\tconst mode = input?.lapsed ?? null;\n\tif (mode !== null && mode !== 'exclude' && mode !== 'only') {\n\t\tthrow new TypeError(\n\t\t\t`${where}: lapsed must be \"exclude\" or \"only\", or absent`,\n\t\t);\n\t}\n\treturn {\n\t\tstatus: status as InvitationStatus | null,\n\t\trole: role as string | null,\n\t\tref: ref as string | null,\n\t\tlapsed: mode === null ? null : { mode, now },\n\t};\n}\n\n/**\n * The cursor a list hands out: the store's own last id, behind a fingerprint\n * of the list it came from (scope, status, role, ref, lapsed, order). The store never\n * sees the fingerprint, so every store gets the binding.\n */\nfunction fingerprint(\n\tscope: string,\n\tfilter: InvitationFilter,\n\torder: 'asc' | 'desc',\n): string {\n\tconst key = JSON.stringify([\n\t\tscope,\n\t\tfilter.status,\n\t\tfilter.role,\n\t\tfilter.ref,\n\t\tfilter.lapsed?.mode ?? null,\n\t\torder,\n\t]);\n\treturn createHash('sha256').update(key).digest('hex').slice(0, 16);\n}\n\n/** The store's id out of a cursor issued for `print`; refused when it was issued for another list. */\nfunction openCursor(where: string, cursor: unknown, print: string): string {\n\tif (typeof cursor !== 'string') throw invalidCursor(where, String(cursor));\n\tconst [issuedFor, id, ...rest] = cursor.split('.');\n\tif (\n\t\trest.length > 0 ||\n\t\tissuedFor === undefined ||\n\t\tid === undefined ||\n\t\t!/^[0-9a-f]{16}$/.test(issuedFor) ||\n\t\t!isId(id)\n\t) {\n\t\tthrow invalidCursor(where, cursor);\n\t}\n\tif (issuedFor !== print) {\n\t\tthrow new CursorFilterMismatchError(\n\t\t\t`${where}: this cursor was issued for another scope, status, role, ref, lapsed or order than the one given`,\n\t\t);\n\t}\n\treturn id;\n}\n\n/** Counts by paging, for a store without `countScopeInvitations`. */\nasync function countByPaging(\n\tinvitations: InvitationStore,\n\tscope: string,\n\tfilter: InvitationFilter,\n): Promise<number> {\n\tlet total = 0;\n\tlet after: string | null = null;\n\tdo {\n\t\tconst found: Awaited<ReturnType<InvitationStore['listScopeInvitations']>> =\n\t\t\tawait invitations.listScopeInvitations(scope, {\n\t\t\t\t...filter,\n\t\t\t\tfirst: MAX_PAGE_SIZE,\n\t\t\t\tafter,\n\t\t\t});\n\t\ttotal += found.items.length;\n\t\tafter = found.nextCursor;\n\t} while (after !== null);\n\treturn total;\n}\n\nexport function readApi(\n\tinvitations: InvitationStore,\n\tclock: Clock,\n\tsettings: NonNullable<Context['config']['invitations']>,\n\tinvited: InvitedType,\n): Pick<Api, 'get' | 'list' | 'count' | 'preview'> {\n\treturn {\n\t\tasync count(scope, filter) {\n\t\t\tconst checked = filterOf('invitations.count', filter, clock.now());\n\t\t\tif (typeof scope !== 'string' || scope === '') return 0;\n\t\t\treturn invitations.countScopeInvitations === undefined\n\t\t\t\t? countByPaging(invitations, scope, checked)\n\t\t\t\t: invitations.countScopeInvitations(scope, checked);\n\t\t},\n\n\t\tasync get(input) {\n\t\t\tconst id: unknown = input?.id;\n\t\t\tconst scope: unknown = input?.scope;\n\t\t\tif (typeof id !== 'string' || !isId(id)) return null;\n\t\t\tif (typeof scope !== 'string' || scope === '') return null;\n\t\t\tconst found = await invitations.findInvitation(id);\n\t\t\t// An id of another scope is no invitation at all.\n\t\t\treturn found === null || found.scope !== scope\n\t\t\t\t? null\n\t\t\t\t: toInvitation(found, settings.types[0]);\n\t\t},\n\n\t\tasync list(scope, page) {\n\t\t\tconst where = 'invitations.list';\n\t\t\tconst order = page?.order ?? 'asc';\n\t\t\tif (order !== 'asc' && order !== 'desc') {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t`${where}: order must be \"asc\" or \"desc\", or absent`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst rawAfter = page?.after ?? null;\n\t\t\tconst filter = filterOf(where, page, clock.now());\n\t\t\tconst first = pageLimit(page?.limit, where);\n\t\t\t// A scope the application could not have used holds nothing.\n\t\t\tif (typeof scope !== 'string' || scope === '') {\n\t\t\t\treturn { items: [], nextCursor: null };\n\t\t\t}\n\t\t\tconst print = fingerprint(scope, filter, order);\n\t\t\tconst after =\n\t\t\t\trawAfter === null ? null : openCursor(where, rawAfter, print);\n\n\t\t\tconst found = await invitations.listScopeInvitations(scope, {\n\t\t\t\t...filter,\n\t\t\t\tfirst,\n\t\t\t\tafter,\n\t\t\t\torder,\n\t\t\t});\n\t\t\treturn {\n\t\t\t\titems: found.items.map((record) =>\n\t\t\t\t\ttoInvitation(record, settings.types[0]),\n\t\t\t\t),\n\t\t\t\tnextCursor:\n\t\t\t\t\tfound.nextCursor === null ? null : `${print}.${found.nextCursor}`,\n\t\t\t};\n\t\t},\n\n\t\tasync preview(code) {\n\t\t\treturn previewInvitation(invitations, clock, settings, invited, code);\n\t\t},\n\t};\n}\n",
|
|
173
|
+
"/** `invitations.preview`: what a code names, without spending it. */\n\nimport type { Clock } from '../../time/clock';\nimport type { Context } from '../context';\nimport type { InvitationStore } from '../port/types';\nimport { hashSecret } from '../secrets';\nimport type { InvitationPreview } from '../types';\nimport { invalidCode, refusalOf } from './claim';\nimport { isCode } from './input';\nimport { configuredType, type InvitedType } from './invited-type';\nimport { toPreview } from './to-invitation';\n\nconst WHERE = 'invitations.preview';\n\nexport async function previewInvitation(\n\tinvitations: InvitationStore,\n\tclock: Clock,\n\tsettings: NonNullable<Context['config']['invitations']>,\n\tinvited: InvitedType,\n\tcode: unknown,\n): Promise<InvitationPreview> {\n\tif (!isCode(code)) throw invalidCode(WHERE);\n\n\tconst record = await invitations.findInvitationByCodeHash(hashSecret(code));\n\t// A type no longer configured is as unknown as a spent code.\n\tconst name = record === null ? null : configuredType(settings, record);\n\tif (record === null || name === null) throw invalidCode(WHERE);\n\tconst refusal = refusalOf(clock, record);\n\tif (refusal !== null) throw invalidCode(WHERE, refusal);\n\tconst { api, type } = invited(name);\n\tif (type.password === null) return toPreview(record, name, false);\n\tconst user = await api.findByEmail(record.email);\n\tconst signsIn = user?.emailVerified === true && user.hasPassword;\n\treturn toPreview(record, name, !signsIn);\n}\n",
|
|
174
|
+
"/** `resend`: a pending invitation gets a new code and lifetime; a lapsed one needs a place. */\n\nimport type { Context } from '../context';\nimport type { InvitationRecord, InvitationStore } from '../port/types';\nimport { hashSecret, mintSecret } from '../secrets';\nimport type { IssuedInvitation } from '../types';\nimport { changePending } from './change-pending';\nimport { emitInvitation } from './events';\nimport { limitReached } from './limit';\nimport { toInvitation } from './to-invitation';\nimport { writeUnderVersion } from './write';\n\ntype Settings = NonNullable<Context['config']['invitations']>;\n\nconst WHERE = 'invitations.resend';\n\nexport async function resendInvitation(\n\tcontext: Context,\n\tsettings: Settings,\n\tinvitations: InvitationStore,\n\tinput: {\n\t\treadonly id: string;\n\t\treadonly scope: string;\n\t\treadonly by?: string;\n\t},\n): Promise<IssuedInvitation> {\n\tconst { clock } = context;\n\tconst code = mintSecret();\n\t// The record as it was when it had lapsed, of the attempt that wrote.\n\tlet lapsed = null as InvitationRecord | null;\n\tconst { record, now } = await changePending(\n\t\tinvitations,\n\t\tclock,\n\t\tWHERE,\n\t\tinput,\n\t\t(at) => ({\n\t\t\tcodeHash: hashSecret(code),\n\t\t\texpiresAt: new Date(at.getTime() + settings.lifetimeMs),\n\t\t\tresentBy: input.by ?? null,\n\t\t}),\n\t\t// A lapsed invitation no longer counts toward the limit: reviving one\n\t\t// takes a place, so it needs room like an issue does.\n\t\tasync (found, at) => {\n\t\t\t// Each attempt reads the invitation again: a retry may find it live.\n\t\t\tlapsed = null;\n\t\t\tif (settings.maxPending === null) return;\n\t\t\tif (found.expiresAt.getTime() > at.getTime()) return;\n\t\t\tlapsed = found;\n\t\t\tconst pending = await invitations.countPendingInvitations(\n\t\t\t\tfound.scope,\n\t\t\t\tat,\n\t\t\t);\n\t\t\tif (pending >= settings.maxPending) throw limitReached(WHERE, settings);\n\t\t},\n\t);\n\t// The count before the write stays as the race guard: two revivals (or a\n\t// revival and an issue) racing at the limit both write, both count the\n\t// other, and both are put back lapsed and refused.\n\tconst revived = lapsed;\n\tif (revived !== null && settings.maxPending !== null) {\n\t\tconst pending = await invitations.countPendingInvitations(\n\t\t\trecord.scope,\n\t\t\tnow,\n\t\t);\n\t\tif (pending > settings.maxPending) {\n\t\t\tawait writeUnderVersion(invitations, record, {\n\t\t\t\tupdatedAt: clock.now(),\n\t\t\t\tcodeHash: revived.codeHash,\n\t\t\t\texpiresAt: revived.expiresAt,\n\t\t\t\tresentBy: revived.resentBy ?? null,\n\t\t\t});\n\t\t\tthrow limitReached(WHERE, settings);\n\t\t}\n\t}\n\tawait emitInvitation(\n\t\tsettings.events,\n\t\t'invitation.resent',\n\t\trecord,\n\t\tnow,\n\t\tinput.by,\n\t);\n\treturn { invitation: toInvitation(record, settings.types[0]), code };\n}\n",
|
|
175
|
+
"/** The `auth.invitations` surface: issue, resend, revoke, list, preview, accept. */\n\nimport type { Context } from '../context';\nimport type { InvitationStore } from '../port/types';\nimport type { InvitationsApi } from '../types';\nimport type { AnyTypeApi } from '../users/any-type-api';\nimport { typeApi } from '../users/type-api';\nimport { acceptInvitation } from './accept';\nimport { changePending } from './change-pending';\nimport { emitInvitation } from './events';\nimport { importHistory } from './history';\nimport type { InvitedType } from './invited-type';\nimport { issueInvitation } from './issue';\nimport { readApi } from './read';\nimport { resendInvitation } from './resend';\nimport { toInvitation } from './to-invitation';\n\n/** The `invitations` of an instance whose `janus()` was given `invitations`. */\nexport function invitationsApi(\n\tcontext: Context,\n\tinvitations: InvitationStore,\n): InvitationsApi['invitations'] {\n\tconst settings = context.config.invitations;\n\tif (settings === null) {\n\t\tthrow new TypeError('janus: invitationsApi needs janus({ invitations })');\n\t}\n\tconst { clock } = context;\n\t// Each invited user type's flows, built when one of its invitations is first read or accepted.\n\tconst typed = new Map<string, AnyTypeApi>();\n\tconst invited: InvitedType = (name) => {\n\t\tconst type = context.config.types.get(name);\n\t\tif (type === undefined) throw new TypeError('janus: invitations.type');\n\t\tlet api = typed.get(name);\n\t\tif (api === undefined) {\n\t\t\tapi = typeApi(context, type);\n\t\t\ttyped.set(name, api);\n\t\t}\n\t\treturn { api, type };\n\t};\n\n\treturn {\n\t\tasync issue(input) {\n\t\t\treturn issueInvitation(context, settings, invitations, input);\n\t\t},\n\n\t\tasync resend(input) {\n\t\t\treturn resendInvitation(context, settings, invitations, input);\n\t\t},\n\n\t\tasync revoke(input) {\n\t\t\tconst { record, now } = await changePending(\n\t\t\t\tinvitations,\n\t\t\t\tclock,\n\t\t\t\t'invitations.revoke',\n\t\t\t\tinput,\n\t\t\t\t(at) => ({\n\t\t\t\t\tstatus: 'revoked',\n\t\t\t\t\trevokedAt: at,\n\t\t\t\t\trevokedBy: input.by ?? null,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tawait emitInvitation(\n\t\t\t\tsettings.events,\n\t\t\t\t'invitation.revoked',\n\t\t\t\trecord,\n\t\t\t\tnow,\n\t\t\t\tinput.by,\n\t\t\t);\n\t\t\treturn toInvitation(record, settings.types[0]);\n\t\t},\n\n\t\tasync importHistory(records, options) {\n\t\t\treturn importHistory(context, settings, invitations, records, options);\n\t\t},\n\n\t\tasync accept(input) {\n\t\t\treturn acceptInvitation(context, settings, invitations, invited, input);\n\t\t},\n\n\t\t...readApi(invitations, clock, settings, invited),\n\t};\n}\n",
|
|
176
|
+
"/** Ending a social sign-in as every sign-in ends, and the shape of what it answers. */\n\nimport { UserInactiveError } from '../../errors/janus-error';\nimport type { ResolvedType } from '../config';\nimport type { Context, toUser } from '../context';\nimport { type DeviceHint, reportNewDevice } from '../devices';\nimport type { Finish } from '../email-sign-in';\nimport type { UserRecord } from '../port/types';\nimport { AMR } from '../sessions/amr';\nimport type { SignInResult, SocialStepUpProof } from '../types';\n\n/** What the sign-in paths hand `finishSocial`: the type's finish, and the call's details. */\nexport interface Ending {\n\treadonly context: Context;\n\treadonly type: ResolvedType;\n\treadonly finish: Finish;\n\treadonly device: DeviceHint;\n\treadonly returnTo: string | null;\n\t/** What the flow's step-up request proved, or `null` for a plain flow. */\n\treadonly stepUp: SocialStepUpProof | null;\n\treadonly where: string;\n}\n\n/**\n * What a refusal after the flow was authenticated carries: the `returnTo` the\n * flow was started with, and that the flow is spent.\n */\nexport function afterFlow(ending: Pick<Ending, 'returnTo'>, provider?: string) {\n\treturn {\n\t\t...(provider === undefined ? {} : { provider }),\n\t\treturnTo: ending.returnTo,\n\t\tflowSpent: true,\n\t};\n}\n\n/**\n * Refuses an inactive user, then finishes: a session, or a second-factor\n * challenge when their factor is active — the provider's proof is a first\n * factor, as a password is. A new device is reported once the session opened.\n */\nexport async function finishSocial(\n\tending: Ending,\n\trecord: UserRecord,\n\toutcome: {\n\t\treadonly provider: string;\n\t\treadonly created: boolean;\n\t\treadonly linked: boolean;\n\t},\n) {\n\tconst { context, type, finish, device, returnTo, stepUp, where } = ending;\n\tif (!record.active) {\n\t\tthrow new UserInactiveError(`${where}: the user is inactive`, {\n\t\t\tuserId: record.id,\n\t\t\tuserType: type.name,\n\t\t\t...afterFlow(ending),\n\t\t});\n\t}\n\tconst result: SignInResult<ReturnType<typeof toUser>> = await finish(\n\t\trecord,\n\t\twhere,\n\t\tdevice,\n\t\tAMR.social,\n\t);\n\tawait reportNewDevice(context, result);\n\treturn result.status === 'signedIn'\n\t\t? { ...result, ...outcome, returnTo, stepUp }\n\t\t: { ...result, provider: outcome.provider, returnTo, stepUp };\n}\n",
|
|
177
|
+
"/** Writing a link: atomic, answering whether this call won the pair. */\n\nimport { SocialError } from '../../errors/janus-error';\nimport type { SocialIdentity } from '../config';\nimport type { Context } from '../context';\nimport { emit } from '../events';\nimport type { SocialLinkRecord, SocialLinkStore } from '../port/types';\nimport type { SocialLink } from '../types';\nimport { afterFlow, type Ending } from './finish';\n\n/** The wired link store: `janus()` refused to start without it. */\nexport function linkStore(context: Context): SocialLinkStore {\n\tconst store = context.store.socialLinks;\n\tif (store === undefined) {\n\t\tthrow new TypeError('janus: social needs store.socialLinks');\n\t}\n\treturn store;\n}\n\n/** A link as the application sees it. */\nexport function toSocialLink(record: SocialLinkRecord): SocialLink {\n\treturn {\n\t\tprovider: record.provider,\n\t\taccountId: record.accountId,\n\t\temail: record.email,\n\t\tlinkedAt: new Date(record.createdAt.getTime()),\n\t};\n}\n\n/** What attaching a link answered: the link, and whether this call wrote it. */\nexport type Attached =\n\t| {\n\t\t\treadonly taken: false;\n\t\t\treadonly link: SocialLinkRecord;\n\t\t\treadonly won: boolean;\n\t }\n\t| { readonly taken: true };\n\n/**\n * Links `identity` to `user` unless the pair belongs to somebody else\n * (`taken`). A pair already theirs is answered as it is, with no write and no\n * event. A new link sends `user.socialLinked`, once the write landed.\n */\nexport async function attachLink(\n\tcontext: Context,\n\tuser: { readonly id: string; readonly type: string },\n\tprovider: string,\n\tidentity: SocialIdentity,\n): Promise<Attached> {\n\tconst store = linkStore(context);\n\tconst held = await store.findSocialLink(provider, identity.accountId);\n\tif (held !== null) {\n\t\treturn held.userId === user.id\n\t\t\t? { taken: false, link: held, won: false }\n\t\t\t: { taken: true };\n\t}\n\n\tconst now = context.clock.now();\n\tconst stored = await store.insertSocialLink({\n\t\tprovider,\n\t\taccountId: identity.accountId,\n\t\tuserId: user.id,\n\t\temail: identity.email,\n\t\tcreatedAt: now,\n\t});\n\tif (stored.userId !== user.id) return { taken: true };\n\tawait emit(context, 'user.socialLinked', user, now, { provider });\n\treturn { taken: false, link: stored, won: true };\n}\n\n/** `SOCIAL_ACCOUNT_TAKEN`: the account is another user's. */\nexport function accountTaken(ending: Ending, provider: string): SocialError {\n\treturn new SocialError(\n\t\t'SOCIAL_ACCOUNT_TAKEN',\n\t\t`${ending.where}: this social account is already linked to another user`,\n\t\tafterFlow(ending, provider),\n\t);\n}\n",
|
|
178
|
+
"/** A link flow's callback: the signed-in user who started it links the account. */\n\nimport { UserInactiveError } from '../../errors/janus-error';\nimport type { SocialIdentity } from '../config';\nimport { getRecord, toUser } from '../context';\nimport { accountTaken, attachLink, toSocialLink } from './attach';\nimport { afterFlow, type Ending } from './finish';\n\n/**\n * Links the identity to the user the flow belongs to. **No e-mail match is\n * required**: the user is signed in, and chose to link. An account already\n * theirs answers `linked` with no write and no event; one that is another\n * user's is `SOCIAL_ACCOUNT_TAKEN`.\n */\nexport async function completeLink(\n\tending: Ending,\n\tuserId: string,\n\tprovider: string,\n\tidentity: SocialIdentity,\n) {\n\tconst { context, type, returnTo, stepUp, where } = ending;\n\tconst record = await getRecord(context, userId, type.name, where);\n\tif (!record.active) {\n\t\tthrow new UserInactiveError(`${where}: the user is inactive`, {\n\t\t\tuserId: record.id,\n\t\t\tuserType: type.name,\n\t\t\t...afterFlow(ending),\n\t\t});\n\t}\n\tconst attached = await attachLink(context, record, provider, identity);\n\tif (attached.taken) throw accountTaken(ending, provider);\n\treturn {\n\t\tstatus: 'linked' as const,\n\t\tuser: toUser(record),\n\t\tlink: toSocialLink(attached.link),\n\t\treturnTo,\n\t\tstepUp,\n\t};\n}\n",
|
|
179
|
+
"/**\n * The one place a provider's failure is caught: the `try` holds the provider's\n * call alone — never a store — and the `catch` throws. A `JanusError` passes\n * through (`@softistx/janus-social` throws `PROVIDER_ERROR` with its own\n * `reason`, or `SOCIAL_STEP_UP_UNMET` for a fixed step-up it holds the ID\n * token to); anything else the provider threw is `PROVIDER_ERROR` with the\n * original as `cause`. `outage.scan.spec.ts` allows this file one `catch`.\n */\n\nimport { JanusError, SocialError } from '../../errors/janus-error';\nimport { isStorable } from '../../stores/storable';\nimport type { SocialIdentity } from '../config';\n\n/** What a flow, once authenticated, adds to the failures of its provider. */\ninterface Flow {\n\treadonly returnTo: string | null;\n}\n\n/** Runs a provider's call, and turns what it throws into `PROVIDER_ERROR`. */\nexport async function callProvider<T>(\n\tcall: () => Promise<T>,\n\tprovider: string,\n\twhere: string,\n\tflow?: Flow,\n\twrapOthers = true,\n): Promise<T> {\n\ttry {\n\t\treturn await call();\n\t} catch (failure) {\n\t\tthrow providerFailure(failure, provider, where, flow, wrapOthers);\n\t}\n}\n\n/**\n * Runs the application's `resolveProvider` lookup at a callback, whose flow is\n * spent: a `PROVIDER_ERROR` it throws leaves with the flow's `returnTo` and\n * `flowSpent`, like a provider's own, and everything else (a `StoreFailure`, a\n * `TypeError`) propagates untouched.\n */\nexport function callResolver<T>(\n\tcall: () => Promise<T>,\n\tprovider: string,\n\tflow: Flow,\n): Promise<T> {\n\treturn callProvider(call, provider, 'social.complete', flow, false);\n}\n\n/**\n * A `PROVIDER_ERROR` or `SOCIAL_STEP_UP_UNMET` rebuilt to carry the\n * authenticated flow's `returnTo` and `flowSpent`; any other failure as it is.\n */\nexport function withFlow(\n\tfailure: unknown,\n\tprovider: string,\n\tflow: Flow,\n): unknown {\n\tif (\n\t\t!(failure instanceof JanusError) ||\n\t\t(failure.code !== 'PROVIDER_ERROR' &&\n\t\t\tfailure.code !== 'SOCIAL_STEP_UP_UNMET')\n\t) {\n\t\treturn failure;\n\t}\n\treturn new SocialError(failure.code, failure.message, {\n\t\tprovider,\n\t\t...(failure.reason === undefined ? {} : { reason: failure.reason }),\n\t\treturnTo: flow.returnTo,\n\t\tflowSpent: true,\n\t\tcause: failure,\n\t});\n}\n\n/**\n * The error to throw for what a provider threw: a `JanusError` as it is —\n * except a `PROVIDER_ERROR` or a `SOCIAL_STEP_UP_UNMET`, rebuilt to carry the\n * flow's `returnTo` when the flow is authenticated — and anything else as\n * `PROVIDER_ERROR`.\n */\nfunction providerFailure(\n\tfailure: unknown,\n\tprovider: string,\n\twhere: string,\n\tflow: Flow | undefined,\n\twrapOthers: boolean,\n): unknown {\n\tif (failure instanceof JanusError) {\n\t\treturn flow === undefined ? failure : withFlow(failure, provider, flow);\n\t}\n\tif (!wrapOthers) return failure;\n\tconst after =\n\t\tflow === undefined ? {} : { returnTo: flow.returnTo, flowSpent: true };\n\treturn new SocialError(\n\t\t'PROVIDER_ERROR',\n\t\t`${where}: the provider \"${provider}\" failed`,\n\t\t{ provider, reason: 'refused', ...after, cause: failure },\n\t);\n}\n\n/** The provider's answer, or `PROVIDER_ERROR` when it is not an identity this core can keep. */\nexport function checkIdentity(\n\tidentity: unknown,\n\tprovider: string,\n\twhere: string,\n\tflow?: Flow,\n): SocialIdentity {\n\tconst found = identity as Partial<SocialIdentity> | null;\n\tconst { accountId, email, emailVerified } = found ?? {};\n\tif (\n\t\ttypeof accountId !== 'string' ||\n\t\taccountId === '' ||\n\t\taccountId.length > 512 ||\n\t\t!isStorable(accountId) ||\n\t\t(email !== null && (typeof email !== 'string' || !isStorable(email))) ||\n\t\ttypeof emailVerified !== 'boolean' ||\n\t\t!evidenceFits(found as Partial<SocialIdentity>)\n\t) {\n\t\tthrow new SocialError(\n\t\t\t'PROVIDER_ERROR',\n\t\t\t`${where}: the provider \"${provider}\" answered no usable identity — accountId, email and emailVerified are required, acr a string and authTime a valid Date when given`,\n\t\t\t{\n\t\t\t\tprovider,\n\t\t\t\treason: 'refused',\n\t\t\t\t...(flow === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { returnTo: flow.returnTo, flowSpent: true }),\n\t\t\t},\n\t\t);\n\t}\n\treturn found as SocialIdentity;\n}\n\n/** Whether the step-up evidence a provider reported, when it reported any, is well formed. */\nfunction evidenceFits({ acr, authTime }: Partial<SocialIdentity>): boolean {\n\treturn (\n\t\t(acr === undefined ||\n\t\t\t(typeof acr === 'string' && acr.length <= 256 && isStorable(acr))) &&\n\t\t(authTime === undefined ||\n\t\t\t(authTime instanceof Date && !Number.isNaN(authTime.getTime())))\n\t);\n}\n",
|
|
180
|
+
"/**\n * The flow cookie: the secret and contents of a flow in progress, kept by the\n * visitor's browser between the redirect to the provider and its callback.\n * `HttpOnly` and `SameSite=Lax` always — the callback is a top-level\n * navigation from the provider, which `Strict` would not carry the cookie\n * on — with the session cookie's `Path`, `Domain` and `Secure`.\n */\n\nimport type { Context } from '../context';\nimport type { SocialApi } from '../types';\n\n/** The name of the flow cookie. */\nexport const FLOW_COOKIE = 'janus-social-flow';\n\n/**\n * The name the cookie is set under: `__Host-janus-social-flow` when the\n * session cookie has no `Domain`, is `Secure` and its `Path` is `/` — the\n * prefix browsers hold to exactly those terms — else `janus-social-flow`.\n * Read it from `social.cookie.name`.\n */\nfunction nameOf(cookie: Context['config']['cookie']): string {\n\treturn cookie.domain === null && cookie.secure && cookie.path === '/'\n\t\t? `__Host-${FLOW_COOKIE}`\n\t\t: FLOW_COOKIE;\n}\n\n/** `social.cookie`: how to set the flow cookie and clear it. */\nexport function socialCookie(\n\tcontext: Context,\n): SocialApi<{ readonly type: string }, string, string>['social']['cookie'] {\n\tconst { domain, path, secure } = context.config.cookie;\n\tconst name = nameOf(context.config.cookie);\n\tconst attributes = [\n\t\t`Path=${path}`,\n\t\t...(domain === null ? [] : [`Domain=${domain}`]),\n\t\t'HttpOnly',\n\t\t'SameSite=Lax',\n\t\t...(secure ? ['Secure'] : []),\n\t].join('; ');\n\treturn {\n\t\tname,\n\t\tserialize: (flow, expiresAt) =>\n\t\t\t`${name}=${flow}; Expires=${expiresAt.toUTCString()}; Max-Age=${Math.max(0, Math.ceil((expiresAt.getTime() - context.clock.now().getTime()) / 1000))}; ${attributes}`,\n\t\tclear: () =>\n\t\t\t`${name}=; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; ${attributes}`,\n\t};\n}\n",
|
|
181
|
+
"/**\n * Finding the provider a flow names: the static `providers` first, then the\n * application's `resolveProvider`. Nothing is caught here — a resolver that\n * throws (a `StoreFailure` when its database is down) reaches the caller as\n * it is.\n */\n\nimport type { ResolvedSocial, SocialProvider } from '../config';\nimport { isSocialProvider, PROVIDER_NAME } from '../config/resolve-social';\n\n/**\n * The provider called `name`, or `null` when the type configures none:\n *\n * - a name in `providers` wins, and the resolver is not asked;\n * - a name that any user type configures in `providers` is never the\n * resolver's: links are keyed by (provider, accountId) across the whole\n * instance, so a resolver answering it for another type would let a\n * tenant's provider squat on the static one's accounts. It is `null`,\n * without a call (`staticNames` holds them all);\n * - a name that does not fit the provider-name pattern never reaches the\n * resolver, so what it receives is always a name `social.start` could take;\n * - the resolver's `null` is `null`; anything else it answers must be a\n * provider, or this is a `TypeError` (the application's bug, not a refusal).\n */\nexport async function findProvider(\n\tsocial: ResolvedSocial | null,\n\tname: string,\n\tstaticNames: ReadonlySet<string>,\n): Promise<SocialProvider | null> {\n\tif (social === null) return null;\n\tconst configured = social.providers.get(name);\n\tif (configured !== undefined) return configured;\n\tif (\n\t\tsocial.resolveProvider === null ||\n\t\t!PROVIDER_NAME.test(name) ||\n\t\tstaticNames.has(name)\n\t) {\n\t\treturn null;\n\t}\n\n\tconst resolved = await social.resolveProvider(name);\n\tif (resolved === null) return null;\n\tif (!isSocialProvider(resolved)) {\n\t\tthrow new TypeError(\n\t\t\t`social.resolveProvider(\"${name}\") must answer a provider — an object with authorizationUrl and exchange — or null`,\n\t\t);\n\t}\n\treturn resolved;\n}\n",
|
|
182
|
+
"/**\n * A flow's step-up request: what `social.start` / `social.link` accept\n * (`stepUp: { acrValues?, maxAge? }`), its validation, and the canonical text\n * the flow cookie and the binding carry. Nothing here touches a store or a\n * provider.\n *\n * The same checks read the cookie back (`decodeStepUp`), so a request the\n * visitor edited into something `start` would have refused is a malformed\n * cookie, not a flow.\n */\n\nimport type { SocialStepUpRequest } from '../config';\n\nconst MAX_ACR_VALUES = 10;\nconst MAX_ACR_LENGTH = 128;\n/** Thirty days: a larger `max_age` asks for nothing a session could not give. */\nconst MAX_AGE_LIMIT = 2_592_000;\n/** Visible ASCII: no whitespace (the values are space-joined), no control character. */\nconst ACR_VALUE = /^[!-~]+$/;\nconst DIGITS = /^(?:0|[1-9][0-9]{0,6})$/;\n\n/** The reason a value is no `acr_values` list, or `null` when it is one. */\nfunction acrProblem(value: unknown): string | null {\n\tif (\n\t\t!Array.isArray(value) ||\n\t\tvalue.length < 1 ||\n\t\tvalue.length > MAX_ACR_VALUES\n\t) {\n\t\treturn `acrValues must be an array of 1 to ${MAX_ACR_VALUES} strings`;\n\t}\n\tfor (const entry of value as unknown[]) {\n\t\tif (\n\t\t\ttypeof entry !== 'string' ||\n\t\t\tentry.length > MAX_ACR_LENGTH ||\n\t\t\t!ACR_VALUE.test(entry)\n\t\t) {\n\t\t\treturn `each acrValues entry must be 1 to ${MAX_ACR_LENGTH} visible ASCII characters, no whitespace`;\n\t\t}\n\t}\n\treturn null;\n}\n\nconst maxAgeFits = (value: unknown): value is number =>\n\ttypeof value === 'number' &&\n\tNumber.isInteger(value) &&\n\tvalue >= 0 &&\n\tvalue <= MAX_AGE_LIMIT;\n\n/**\n * The request an option holds, or `null` when there is none. Anything that is\n * not `{ acrValues?: string[], maxAge?: number }` with at least one part is a\n * `TypeError`: a step-up that silently asked for nothing would look like one.\n */\nexport function parseStepUp(\n\tinput: unknown,\n\twhere: string,\n): SocialStepUpRequest | null {\n\tif (input === undefined) return null;\n\tconst fail = (why: string) => new TypeError(`${where}: stepUp: ${why}`);\n\tif (typeof input !== 'object' || input === null || Array.isArray(input)) {\n\t\tthrow fail('must be { acrValues?: string[], maxAge?: number }');\n\t}\n\tconst given = input as Record<string, unknown>;\n\tfor (const name of Object.keys(given)) {\n\t\tif (name !== 'acrValues' && name !== 'maxAge') {\n\t\t\tthrow fail(`unknown key \"${name}\" — acrValues and maxAge only`);\n\t\t}\n\t}\n\tconst { acrValues, maxAge } = given;\n\tif (acrValues === undefined && maxAge === undefined) {\n\t\tthrow fail('give acrValues, maxAge or both');\n\t}\n\tif (acrValues !== undefined) {\n\t\tconst problem = acrProblem(acrValues);\n\t\tif (problem !== null) throw fail(problem);\n\t}\n\tif (maxAge !== undefined && !maxAgeFits(maxAge)) {\n\t\tthrow fail(\n\t\t\t`maxAge must be an integer number of seconds from 0 to ${MAX_AGE_LIMIT}`,\n\t\t);\n\t}\n\treturn Object.freeze({\n\t\tacrValues:\n\t\t\tacrValues === undefined\n\t\t\t\t? null\n\t\t\t\t: Object.freeze([...(acrValues as string[])]),\n\t\tmaxAge: maxAge === undefined ? null : (maxAge as number),\n\t});\n}\n\n/** The request as the two texts the cookie and the binding carry: `''` for a part not asked. */\nexport function encodeStepUp(request: SocialStepUpRequest): {\n\treadonly acr: string;\n\treadonly maxAge: string;\n} {\n\treturn {\n\t\tacr: request.acrValues === null ? '' : request.acrValues.join(' '),\n\t\tmaxAge: request.maxAge === null ? '' : String(request.maxAge),\n\t};\n}\n\n/**\n * The request two cookie texts hold, or `null` for anything `encodeStepUp`\n * could not have written (both empty included): the cookie is then malformed.\n */\nexport function decodeStepUp(\n\tacr: string,\n\tmaxAge: string,\n): SocialStepUpRequest | null {\n\tif (acr === '' && maxAge === '') return null;\n\tconst listed = acr === '' ? null : acr.split(' ');\n\tif (listed !== null && acrProblem(listed) !== null) return null;\n\tconst acrValues = listed === null ? null : Object.freeze(listed);\n\tlet seconds: number | null = null;\n\tif (maxAge !== '') {\n\t\tseconds = DIGITS.test(maxAge) ? Number(maxAge) : Number.NaN;\n\t\tif (!maxAgeFits(seconds)) return null;\n\t}\n\treturn Object.freeze({ acrValues, maxAge: seconds });\n}\n",
|
|
183
|
+
"/**\n * The value of the flow cookie: the secret, a dot, and the flow's contents\n * (`FlowMeta`) in base64url. The contents are not secret and are bound to the\n * stored token by a keyed hash (`flow-secret.ts`), so a changed cookie is\n * `FLOW_MISMATCH`. A plain separator format, not JSON: reading a cookie\n * the visitor controls never throws.\n *\n * Four parts for a plain flow (type, provider, link, returnTo); six when the\n * flow asked for a step-up, the space-joined `acr_values` and the `max_age`\n * digits added, each empty when not asked.\n */\n\nimport type { FlowMeta } from './flow-secret';\nimport { decodeStepUp, encodeStepUp } from './step-up-request';\n\nconst SECRET = /^[A-Za-z0-9_-]{43}$/;\nconst BODY = /^[A-Za-z0-9_-]*$/;\n/**\n * The longest flow cookie value `unpackFlow` reads (more than a type, a\n * provider and a path of 2048 characters can come to); `beginFlow` refuses to\n * issue a longer one.\n */\nexport const MAX_FLOW = 4096;\n\n/** The cookie's value for this secret and these contents. */\nexport function packFlow(secret: string, meta: FlowMeta): string {\n\tconst body = [\n\t\tmeta.type,\n\t\tmeta.provider,\n\t\tmeta.link ? '1' : '0',\n\t\tmeta.returnTo ?? '',\n\t\t...(meta.stepUp === null\n\t\t\t? []\n\t\t\t: [encodeStepUp(meta.stepUp).acr, encodeStepUp(meta.stepUp).maxAge]),\n\t].join('\\u0000');\n\treturn `${secret}.${Buffer.from(body).toString('base64url')}`;\n}\n\n/** The secret and contents a cookie's value holds, or `null` for anything else. */\nexport function unpackFlow(\n\tflow: unknown,\n): { readonly secret: string; readonly meta: FlowMeta } | null {\n\tif (typeof flow !== 'string' || flow.length > MAX_FLOW) return null;\n\tconst [secret, body, ...rest] = flow.split('.');\n\tif (\n\t\trest.length > 0 ||\n\t\tsecret === undefined ||\n\t\tbody === undefined ||\n\t\t!SECRET.test(secret) ||\n\t\t!BODY.test(body)\n\t) {\n\t\treturn null;\n\t}\n\tconst parts = Buffer.from(body, 'base64url').toString('utf8').split('\\u0000');\n\tconst [type, provider, link, returnTo, acr, maxAge] = parts;\n\tconst stepUp =\n\t\tparts.length === 6 ? decodeStepUp(acr ?? '', maxAge ?? '') : null;\n\tif (\n\t\t(parts.length !== 4 && !(parts.length === 6 && stepUp !== null)) ||\n\t\ttype === undefined ||\n\t\tprovider === undefined ||\n\t\treturnTo === undefined ||\n\t\t(link !== '0' && link !== '1')\n\t) {\n\t\treturn null;\n\t}\n\treturn {\n\t\tsecret,\n\t\tmeta: {\n\t\t\ttype,\n\t\t\tprovider,\n\t\t\tlink: link === '1',\n\t\t\treturnTo: returnTo === '' ? null : returnTo,\n\t\t\tstepUp,\n\t\t},\n\t};\n}\n",
|
|
184
|
+
"/**\n * What one social flow's secret yields: the `state`, `nonce` and PKCE\n * `codeVerifier` the provider is given, and the keyed hash that binds the\n * flow cookie's contents to the token the store holds. **Nothing here is\n * stored**: the cookie holds the secret, the store only its hash and the\n * binding, so the three values are recomputed at the callback.\n *\n * Each value is an HMAC-SHA256 of its own label under the secret, so none\n * reveals another and none reveals the secret.\n */\n\nimport { createHmac, timingSafeEqual } from 'node:crypto';\nimport type { SocialStepUpRequest } from '../config';\nimport { encodeStepUp } from './step-up-request';\n\n/** What the provider is handed, all derived from the secret. */\nexport interface FlowValues {\n\treadonly state: string;\n\treadonly nonce: string;\n\t/** 43 characters of base64url: inside RFC 7636's 43 to 128. */\n\treadonly codeVerifier: string;\n}\n\n/** What the cookie carries beside the secret, and the binding covers. */\nexport interface FlowMeta {\n\treadonly type: string;\n\treadonly provider: string;\n\t/** A path of this site, or `null`. */\n\treadonly returnTo: string | null;\n\t/** `true` for `social.link`: the token then belongs to a user. */\n\treadonly link: boolean;\n\t/** The step-up the flow asked for, or `null` for a plain flow. */\n\treadonly stepUp: SocialStepUpRequest | null;\n}\n\nconst hmac = (secret: string, label: string): Buffer =>\n\tcreateHmac('sha256', secret).update(label).digest();\n\n/** The `state`, `nonce` and `codeVerifier` of the flow this secret opened. */\nexport function deriveFlow(secret: string): FlowValues {\n\treturn {\n\t\tstate: hmac(secret, 'janus.social.state').toString('base64url'),\n\t\tnonce: hmac(secret, 'janus.social.nonce').toString('base64url'),\n\t\tcodeVerifier: hmac(secret, 'janus.social.verifier').toString('base64url'),\n\t};\n}\n\n/**\n * The binding of a flow's contents: a keyed hash, hex, stored as the token's\n * `codeHash`. `userId` is the token's, so a link flow cannot be completed as\n * a sign-in nor the reverse.\n */\nexport function bindingOf(\n\tsecret: string,\n\tmeta: FlowMeta,\n\tuserId: string,\n): string {\n\t// A step-up is appended only when there is one, so a plain flow's binding\n\t// stays what it always was (`flow-cookie-value.step-up.spec.ts` pins it).\n\tconst stepUp =\n\t\tmeta.stepUp === null\n\t\t\t? []\n\t\t\t: [\n\t\t\t\t\t`acr:${encodeStepUp(meta.stepUp).acr}`,\n\t\t\t\t\t`max-age:${encodeStepUp(meta.stepUp).maxAge}`,\n\t\t\t\t];\n\treturn createHmac('sha256', secret)\n\t\t.update(\n\t\t\t[\n\t\t\t\t'janus.social.binding',\n\t\t\t\tuserId,\n\t\t\t\tmeta.type,\n\t\t\t\tmeta.provider,\n\t\t\t\tmeta.link ? 'link' : 'sign-in',\n\t\t\t\tmeta.returnTo ?? '',\n\t\t\t\t...stepUp,\n\t\t\t].join('\\u0000'),\n\t\t)\n\t\t.digest('hex');\n}\n\n/** Whether two strings are equal, in time that does not depend on where they differ. */\nexport function sameText(a: string, b: string): boolean {\n\tconst left = Buffer.from(a);\n\tconst right = Buffer.from(b);\n\treturn left.length === right.length && timingSafeEqual(left, right);\n}\n",
|
|
185
|
+
"/**\n * Starting a flow, for a sign-in and for a link: the provider's URL, the flow\n * token in the store, and the cookie's value. What `social.start` and\n * `social.link` share.\n */\n\nimport { SocialError } from '../../errors/janus-error';\nimport { type Id, mintId } from '../../ids/id';\nimport type { ResolvedType, SocialStepUpRequest } from '../config';\nimport { PROVIDER_NAME } from '../config/resolve-social';\nimport type { Context } from '../context';\nimport { issueOneTime } from '../one-time';\nimport { mintSecret } from '../secrets';\nimport type { SocialFlowStart } from '../types';\nimport { socialCookie } from './cookie';\nimport { findProvider } from './find-provider';\nimport { MAX_FLOW, packFlow } from './flow-cookie-value';\nimport { bindingOf, deriveFlow, type FlowMeta } from './flow-secret';\nimport { callProvider } from './provider-call';\n\n/**\n * Issues a flow of `type` for `provider`. `userId` is the user a link flow\n * belongs to, `null` for a sign-in, whose token then names nobody.\n *\n * The provider is asked first, so a provider that cannot be reached leaves no\n * token behind.\n */\nexport async function beginFlow(\n\tcontext: Context,\n\ttype: ResolvedType,\n\tflow: {\n\t\treadonly provider: string;\n\t\treadonly returnTo: string | null;\n\t\treadonly userId: Id | null;\n\t\treadonly stepUp: SocialStepUpRequest | null;\n\t\treadonly where: string;\n\t},\n): Promise<SocialFlowStart> {\n\tconst { provider, returnTo, userId, stepUp, where } = flow;\n\tconst configured = await findProvider(\n\t\ttype.social,\n\t\tprovider,\n\t\tcontext.config.staticProviderNames,\n\t);\n\tif (configured === null) throw unknownProvider(provider, where);\n\n\tif (stepUp !== null && configured.supportsStepUp !== true) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: the provider \"${provider}\" does not support stepUp — it does not set supportsStepUp, so it may ignore acr_values and max_age; start the flow without stepUp, or use a provider that supports it`,\n\t\t);\n\t}\n\n\tconst secret = mintSecret();\n\tconst meta: FlowMeta = {\n\t\ttype: type.name,\n\t\tprovider,\n\t\treturnTo,\n\t\tlink: userId !== null,\n\t\tstepUp,\n\t};\n\tconst value = packFlow(secret, meta);\n\tif (value.length > MAX_FLOW) {\n\t\t// A longer cookie would be refused at `complete`: a flow dead on arrival.\n\t\tthrow new TypeError(\n\t\t\t`${where}: returnTo and stepUp together are too long for the flow cookie`,\n\t\t);\n\t}\n\tconst owner = userId ?? mintId(context.clock.now().getTime());\n\tconst url = await callProvider(\n\t\t() => configured.authorizationUrl({ ...deriveFlow(secret), stepUp }),\n\t\tprovider,\n\t\twhere,\n\t);\n\n\tconst { expiresAt } = await issueOneTime(context, {\n\t\tkind: 'socialFlow',\n\t\tuserId: owner,\n\t\taddress: '',\n\t\tttlMs: context.config.tokenTtlMs.socialFlow,\n\t\tsecret,\n\t\tboundHash: bindingOf(secret, meta, owner),\n\t});\n\treturn {\n\t\turl: String(url),\n\t\tflow: value,\n\t\texpiresAt,\n\t\tsetCookie: socialCookie(context).serialize(value, expiresAt),\n\t};\n}\n\n/** `SOCIAL_PROVIDER_UNKNOWN`: the provider is none the type configures. */\nexport function unknownProvider(\n\tprovider: unknown,\n\twhere: string,\n\tafter?: { readonly returnTo: string | null; readonly flowSpent: true },\n): SocialError {\n\treturn new SocialError(\n\t\t'SOCIAL_PROVIDER_UNKNOWN',\n\t\t`${where}: the user type configures no such social provider`,\n\t\t{\n\t\t\t...(typeof provider === 'string' && PROVIDER_NAME.test(provider)\n\t\t\t\t? { provider }\n\t\t\t\t: {}),\n\t\t\t...after,\n\t\t},\n\t);\n}\n",
|
|
186
|
+
"/**\n * Redeeming a flow at its callback: the cookie read, the `state` checked\n * before anything is spent, the token spent once, and the cookie's contents\n * checked against the binding the store holds. The provider is looked up last\n * (`find-provider.ts`), so a connection removed since `start` is\n * `SOCIAL_PROVIDER_UNKNOWN`, the flow spent.\n */\n\nimport { SocialError } from '../../errors/janus-error';\nimport type { ResolvedType, SocialProvider } from '../config';\nimport type { Context } from '../context';\nimport { hashSecret } from '../secrets';\nimport { unknownProvider } from './begin';\nimport { findProvider } from './find-provider';\nimport { unpackFlow } from './flow-cookie-value';\nimport {\n\tbindingOf,\n\tderiveFlow,\n\ttype FlowMeta,\n\ttype FlowValues,\n\tsameText,\n} from './flow-secret';\nimport { callResolver } from './provider-call';\n\n/** A flow redeemed: whose it is, what it asked for, and what the provider is given. */\nexport interface Redeemed {\n\treadonly type: ResolvedType;\n\treadonly meta: FlowMeta;\n\t/** The provider the flow names, looked up once here. */\n\treadonly provider: SocialProvider;\n\treadonly values: FlowValues;\n\t/** For a link flow, the user it belongs to; `null` for a sign-in. */\n\treadonly userId: string | null;\n}\n\n/** `spent`: whether the flow was spent when this was refused. */\nconst mismatch = (where: string, why: string, spent: boolean) =>\n\tnew SocialError('FLOW_MISMATCH', `${where}: ${why}`, { flowSpent: spent });\n\n/**\n * Parses the cookie and checks the callback's `state` — both before the token\n * is spent, so a stranger's callback cannot burn the visitor's flow — then\n * spends the token.\n *\n * - no cookie, a malformed one, or a `state` that is not this flow's:\n * `FLOW_MISMATCH`;\n * - an unknown, spent or lapsed token: `FLOW_EXPIRED`, a lapsed one spent\n * all the same;\n * - contents that do not match the binding, or a link flow completed by\n * somebody other than its user: `FLOW_MISMATCH`, the token spent;\n * - a flow of the other kind than the `purpose` expected:\n * `FLOW_PURPOSE_MISMATCH`, the token spent.\n */\nexport async function redeemFlow(\n\tcontext: Context,\n\tinput: {\n\t\treadonly callback: URLSearchParams;\n\t\treadonly flow: unknown;\n\t\treadonly purpose?: 'signIn' | 'link' | undefined;\n\t\treadonly current: { readonly user: { readonly id: string } } | null;\n\t},\n\twhere: string,\n): Promise<Redeemed> {\n\tconst parsed = unpackFlow(input.flow);\n\tif (parsed === null) {\n\t\tthrow mismatch(where, 'the flow cookie is missing or malformed', false);\n\t}\n\tconst { secret, meta } = parsed;\n\tconst values = deriveFlow(secret);\n\tconst state = input.callback.get('state');\n\tif (state === null || !sameText(state, values.state)) {\n\t\tthrow mismatch(where, \"the callback's state is not this flow's\", false);\n\t}\n\n\tconst now = context.clock.now();\n\tconst token = await context.store.tokens.consumeToken(\n\t\thashSecret(secret),\n\t\t'socialFlow',\n\t\tnow,\n\t);\n\tif (\n\t\ttoken === null ||\n\t\ttoken.spentAt !== null ||\n\t\ttoken.expiresAt.getTime() <= now.getTime()\n\t) {\n\t\tthrow new SocialError(\n\t\t\t'FLOW_EXPIRED',\n\t\t\t`${where}: the flow is unknown, used or lapsed — start it again`,\n\t\t\t{ flowSpent: true },\n\t\t);\n\t}\n\tif (\n\t\ttoken.codeHash === null ||\n\t\t!sameText(token.codeHash, bindingOf(secret, meta, token.userId))\n\t) {\n\t\tthrow mismatch(where, \"the flow cookie's contents were changed\", true);\n\t}\n\tif (input.purpose !== undefined && (input.purpose === 'link') !== meta.link) {\n\t\tthrow new SocialError(\n\t\t\t'FLOW_PURPOSE_MISMATCH',\n\t\t\t`${where}: this is ${meta.link ? 'a link' : 'a sign-in'} flow, and ${input.purpose === 'link' ? 'a link' : 'a sign-in'} flow was expected`,\n\t\t\t{ flowSpent: true },\n\t\t);\n\t}\n\tif (meta.link && input.current?.user.id !== token.userId) {\n\t\tthrow mismatch(where, 'this link was started by another user', true);\n\t}\n\n\tconst type = context.config.types.get(meta.type);\n\tconst provider =\n\t\ttype === undefined\n\t\t\t? null\n\t\t\t: await callResolver(\n\t\t\t\t\t() =>\n\t\t\t\t\t\tfindProvider(\n\t\t\t\t\t\t\ttype.social,\n\t\t\t\t\t\t\tmeta.provider,\n\t\t\t\t\t\t\tcontext.config.staticProviderNames,\n\t\t\t\t\t\t),\n\t\t\t\t\tmeta.provider,\n\t\t\t\t\t{ returnTo: meta.returnTo },\n\t\t\t\t);\n\tif (type === undefined || provider === null) {\n\t\tthrow unknownProvider(meta.provider, where, {\n\t\t\treturnTo: meta.returnTo,\n\t\t\tflowSpent: true,\n\t\t});\n\t}\n\treturn {\n\t\ttype,\n\t\tmeta,\n\t\tprovider,\n\t\tvalues,\n\t\tuserId: meta.link ? token.userId : null,\n\t};\n}\n",
|
|
187
|
+
"/** A user matched by the identity's e-mail: linked, and signed in, when both sides vouch for it. */\n\nimport { SocialError, UserInactiveError } from '../../errors/janus-error';\nimport type { SocialIdentity } from '../config';\nimport { getRecord } from '../context';\nimport type { UserRecord } from '../port/types';\nimport { accountTaken, attachLink } from './attach';\nimport { afterFlow, type Ending, finishSocial } from './finish';\n\n/**\n * Links a user matched by e-mail, and signs them in — **only when the\n * provider and the local account both vouch for the address**; either\n * unverified is `EMAIL_NOT_VERIFIED_FOR_LINK` and nothing is linked.\n */\nexport async function linkHolder(\n\tending: Ending,\n\tholder: UserRecord,\n\tprovider: string,\n\tidentity: SocialIdentity,\n) {\n\tconst { context, where } = ending;\n\tif (!identity.emailVerified || holder.emailVerifiedAt === null) {\n\t\tthrow new SocialError(\n\t\t\t'EMAIL_NOT_VERIFIED_FOR_LINK',\n\t\t\t`${where}: a user holds this e-mail, and the provider or the account does not vouch for it — sign in another way, then link the account`,\n\t\t\tafterFlow(ending, provider),\n\t\t);\n\t}\n\t// Read again by id: the record handed in may be a login lookup's.\n\tconst record = await getRecord(context, holder.id, holder.type, where);\n\tif (!record.active) {\n\t\tthrow new UserInactiveError(`${where}: the user is inactive`, {\n\t\t\tuserId: record.id,\n\t\t\tuserType: record.type,\n\t\t\t...afterFlow(ending),\n\t\t});\n\t}\n\tconst attached = await attachLink(context, record, provider, identity);\n\tif (attached.taken) throw accountTaken(ending, provider);\n\treturn finishSocial(ending, record, {\n\t\tprovider,\n\t\tcreated: false,\n\t\tlinked: attached.won,\n\t});\n}\n",
|
|
188
|
+
"/** A social sign-up: nobody holds the account or its e-mail, and the type lets a stranger in. */\n\nimport {\n\tEmailUnverifiedError,\n\tSocialError,\n\tStoreConflict,\n\tUserInvalidError,\n} from '../../errors/janus-error';\nimport { normalizeEmail, type SocialIdentity } from '../config';\nimport { holderOfEmail } from '../context';\nimport { unlessLoginTaken } from '../outage';\nimport type { JsonObject } from '../port/types';\nimport { deleteUser } from '../users/delete';\nimport { insert } from '../users/insert';\nimport { accountTaken, attachLink } from './attach';\nimport { afterFlow, type Ending, finishSocial } from './finish';\nimport { linkHolder } from './link-holder';\n\n/**\n * Creates the user `social.signUp` describes, verified and with no password,\n * links the account and signs them in.\n *\n * - no `signUp`: `SIGN_UP_DISABLED`; nothing is created;\n * - an e-mail the provider does not vouch for (or none): `EMAIL_UNVERIFIED`;\n * - fields whose e-mail is not the provider's: `USER_INVALID`, before any write;\n * - a race for the e-mail lost to another sign-up: the winner is read again\n * and linked, as a user matched by e-mail is.\n */\nexport async function signUpNew(\n\tending: Ending,\n\tprovider: string,\n\tidentity: SocialIdentity,\n) {\n\tconst { context, type, where } = ending;\n\tconst signUp = type.social?.signUp ?? false;\n\tif (signUp === false) {\n\t\tthrow new SocialError(\n\t\t\t'SIGN_UP_DISABLED',\n\t\t\t`${where}: nobody holds this account's e-mail, and the user type does not sign strangers up`,\n\t\t\tafterFlow(ending, provider),\n\t\t);\n\t}\n\tif (identity.email === null || !identity.emailVerified) {\n\t\tthrow new EmailUnverifiedError(\n\t\t\t`${where}: the provider does not vouch for an e-mail, so no account is created`,\n\t\t\t{ ...afterFlow(ending, provider), userType: type.name },\n\t\t);\n\t}\n\n\tconst profile = Object.freeze({ ...identity, provider });\n\tconst described = (await signUp(profile)) as Record<string, unknown> | null;\n\tconst { password: _password, active: _active, ...fields } = described ?? {};\n\tconst email = identity.email;\n\tconst written = await unlessLoginTaken(\n\t\tinsert(\n\t\t\tcontext,\n\t\t\ttype,\n\t\t\tfields,\n\t\t\twhere,\n\t\t\t(valid) => mustBeTheirs(valid, ending, email),\n\t\t\t{\n\t\t\t\temailVerified: true,\n\t\t\t},\n\t\t),\n\t);\n\tif (written instanceof StoreConflict) {\n\t\t// Lost the race for the address: whoever won is who the e-mail matches.\n\t\tconst winner = await holderOfEmail(context, type, email);\n\t\tif (winner === null) throw written;\n\t\treturn linkHolder(ending, winner, provider, identity);\n\t}\n\n\t// The user exists but has no link yet: whatever stops the link — the\n\t// account taken meanwhile, an outage — takes the user back, and rethrows.\n\t// The rollback is settled, not awaited bare: if it fails too, the link's\n\t// failure is the one thrown, not the rollback's. The leftover user has a\n\t// verified e-mail and no link, so the next social sign-in links it.\n\tlet linked = false;\n\ttry {\n\t\tconst attached = await attachLink(context, written, provider, identity);\n\t\tif (attached.taken) throw accountTaken(ending, provider);\n\t\tlinked = true;\n\t} finally {\n\t\tif (!linked) {\n\t\t\tawait Promise.allSettled([deleteUser(context, type, written.id)]);\n\t\t}\n\t}\n\treturn finishSocial(ending, written, {\n\t\tprovider,\n\t\tcreated: true,\n\t\tlinked: true,\n\t});\n}\n\n/** Throws unless the validated fields hold the provider's e-mail, normalised as a login is. */\nfunction mustBeTheirs(fields: JsonObject, ending: Ending, email: string): void {\n\tconst held = fields[ending.type.email];\n\tif (\n\t\ttypeof held !== 'string' ||\n\t\tnormalizeEmail(held) !== normalizeEmail(email)\n\t) {\n\t\tthrow new UserInvalidError(\n\t\t\t`${ending.where}: the fields do not match the ${ending.type.name} schema (1 issue, at ${ending.type.email})`,\n\t\t\t{\n\t\t\t\tissues: [\n\t\t\t\t\t{\n\t\t\t\t\t\tpath: [ending.type.email],\n\t\t\t\t\t\tmessage: \"is not the provider's e-mail\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tuserType: ending.type.name,\n\t\t\t},\n\t\t);\n\t}\n}\n",
|
|
189
|
+
"/**\n * A sign-in flow's callback, once the provider vouched for an identity: the\n * account already linked, a user matched by a verified e-mail, or nobody.\n */\n\nimport type { SocialIdentity } from '../config';\nimport { holderOfEmail } from '../context';\nimport { accountTaken, linkStore } from './attach';\nimport { type Ending, finishSocial } from './finish';\nimport { linkHolder } from './link-holder';\nimport { signUpNew } from './sign-up';\n\n/**\n * Signs in whoever holds the identity's account.\n *\n * 1. A linked account signs in its user: of this flow's type, else\n * `SOCIAL_ACCOUNT_TAKEN`; inactive is `USER_INACTIVE`. A link whose user is\n * gone is deleted and the account treated as new.\n * 2. Otherwise a user of the type holding the identity's e-mail is linked and\n * signed in — **only when the provider and the local account both vouch for\n * the address**; either unverified is `EMAIL_NOT_VERIFIED_FOR_LINK`.\n * 3. Otherwise nobody is known: `sign-up.ts`.\n */\nexport async function signInAccount(\n\tending: Ending,\n\tprovider: string,\n\tidentity: SocialIdentity,\n) {\n\tconst { context, type } = ending;\n\tconst store = linkStore(context);\n\tconst link = await store.findSocialLink(provider, identity.accountId);\n\tif (link !== null) {\n\t\tconst record = await context.store.users.findUser(link.userId);\n\t\tif (record !== null) {\n\t\t\tif (record.type !== type.name) throw accountTaken(ending, provider);\n\t\t\treturn finishSocial(ending, record, {\n\t\t\t\tprovider,\n\t\t\t\tcreated: false,\n\t\t\t\tlinked: false,\n\t\t\t});\n\t\t}\n\t\t// The link outlived its user (a sign-up that was taken back mid-race):\n\t\t// it belongs to nobody, so it goes, and the account is a stranger's.\n\t\tawait store.deleteSocialLink(link.userId, provider, identity.accountId);\n\t}\n\n\tconst holder =\n\t\tidentity.email === null\n\t\t\t? null\n\t\t\t: await holderOfEmail(context, type, identity.email);\n\tif (holder !== null) return linkHolder(ending, holder, provider, identity);\n\treturn signUpNew(ending, provider, identity);\n}\n",
|
|
190
|
+
"/**\n * Whether an identity proves the step-up its flow asked for. **The core\n * decides, on its own clock**: a provider that ignored `acr_values` or\n * `max_age` is caught here, and evidence that is missing is a refusal\n * (fail closed), since `acr_values` is only a request to the provider.\n *\n * Deliberately duplicated by `@softistx/janus-social`'s `holdsStepUp` (a\n * package that must not import this one's internals): AGENTS.md, \"Deliberate\n * duplications\".\n */\n\nimport type { SocialIdentity, SocialStepUpRequest } from '../config';\nimport type { SocialStepUpProof } from '../types';\n\n/** Clock skew allowed between this server and the provider, in both directions. */\nexport const AUTH_TIME_TOLERANCE_MS = 60_000;\n\n/** Why a request is not proven: the part that failed, for logs only. */\nexport type StepUpFailure = 'acr' | 'authTime';\n\n/**\n * The proof the identity gives of `request`, or the part that failed.\n *\n * - `acrValues`: the identity's `acr` must be one of them;\n * - `maxAge`: the identity's `authTime` must lie within\n * `[now - maxAge - 60 s, now + 60 s]`, so `maxAge: 0` asks for roughly the\n * last minute.\n */\nexport function proveStepUp(\n\trequest: SocialStepUpRequest,\n\tidentity: Pick<SocialIdentity, 'acr' | 'authTime'>,\n\tnow: Date,\n): SocialStepUpProof | StepUpFailure {\n\tconst { acr, authTime } = identity;\n\tif (\n\t\trequest.acrValues !== null &&\n\t\t(acr === undefined || !request.acrValues.includes(acr))\n\t) {\n\t\treturn 'acr';\n\t}\n\tif (request.maxAge !== null) {\n\t\tif (authTime === undefined) return 'authTime';\n\t\tconst at = authTime.getTime();\n\t\tconst earliest =\n\t\t\tnow.getTime() - request.maxAge * 1000 - AUTH_TIME_TOLERANCE_MS;\n\t\tif (at < earliest || at > now.getTime() + AUTH_TIME_TOLERANCE_MS) {\n\t\t\treturn 'authTime';\n\t\t}\n\t}\n\treturn {\n\t\tacrValues: request.acrValues,\n\t\tmaxAge: request.maxAge,\n\t\tacr: acr ?? null,\n\t\tauthTime: authTime ?? null,\n\t};\n}\n",
|
|
191
|
+
"/** The step-up check of `social.complete`: what a refusal carries, and the proof an answer echoes. */\n\nimport { SocialError } from '../../errors/janus-error';\nimport type { SocialIdentity } from '../config';\nimport type { SocialStepUpProof } from '../types';\nimport type { FlowMeta } from './flow-secret';\nimport { proveStepUp } from './step-up-proof';\n\n/**\n * `SOCIAL_STEP_UP_UNMET` for a flow whose provider no longer supports the\n * step-up it asked for (the configuration changed between `start` and the\n * callback): refused before the provider is called.\n */\nexport function unsupportedStepUp(meta: FlowMeta, where: string): SocialError {\n\treturn new SocialError(\n\t\t'SOCIAL_STEP_UP_UNMET',\n\t\t`${where}: the flow asked for a step-up and the provider does not support it`,\n\t\t{ provider: meta.provider, returnTo: meta.returnTo, flowSpent: true },\n\t);\n}\n\n/**\n * The proof to echo for this flow: `null` for a plain flow, the proof for one\n * whose identity holds up its step-up request, else `SOCIAL_STEP_UP_UNMET`\n * (`reason` for logs). Neither the asked nor the reported `acr` is in the\n * message.\n */\nexport function stepUpOutcome(\n\tmeta: FlowMeta,\n\tidentity: Pick<SocialIdentity, 'acr' | 'authTime'>,\n\tnow: Date,\n\twhere: string,\n): SocialStepUpProof | null {\n\tif (meta.stepUp === null) return null;\n\tconst proof = proveStepUp(meta.stepUp, identity, now);\n\tif (typeof proof !== 'string') return proof;\n\tthrow new SocialError(\n\t\t'SOCIAL_STEP_UP_UNMET',\n\t\t`${where}: the provider's answer does not prove the step-up the flow asked for`,\n\t\t{\n\t\t\tprovider: meta.provider,\n\t\t\treason: proof,\n\t\t\treturnTo: meta.returnTo,\n\t\t\tflowSpent: true,\n\t\t},\n\t);\n}\n",
|
|
192
|
+
"/** `social.complete`: the callback of a sign-in or a link. */\n\nimport type { Context } from '../context';\nimport { deviceHint } from '../devices';\nimport type { Finish } from '../email-sign-in';\nimport type { SignInOptions } from '../types';\nimport { completeLink } from './complete-link';\nimport type { Ending } from './finish';\nimport { callProvider, checkIdentity } from './provider-call';\nimport { redeemFlow } from './redeem';\nimport { signInAccount } from './sign-in';\nimport { stepUpOutcome, unsupportedStepUp } from './step-up';\n\nconst WHERE = 'social.complete';\n\n/**\n * Completes the flow the cookie holds with the provider's callback.\n *\n * 1. The cookie and the `state` are checked and the flow spent (`redeem.ts`).\n * 2. The provider trades the callback for an identity; whatever it throws\n * becomes `PROVIDER_ERROR`.\n * 3. A flow that asked for a step-up must have it proven (`step-up.ts`).\n * 4. A link flow links the account to its user (`complete-link.ts`); a\n * sign-in flow signs in the account's user, a user matched by a verified\n * e-mail, or a new one (`sign-in.ts`).\n */\nexport async function completeFlow(\n\tcontext: Context,\n\tfinishers: ReadonlyMap<string, Finish>,\n\tinput: {\n\t\treadonly callback: URLSearchParams;\n\t\treadonly flow: unknown;\n\t\treadonly purpose?: unknown;\n\t\treadonly current?:\n\t\t\t| { readonly user: { readonly id: string } }\n\t\t\t| null\n\t\t\t| undefined;\n\t},\n\toptions: SignInOptions | undefined,\n) {\n\tif (!(input?.callback instanceof URLSearchParams)) {\n\t\tthrow new TypeError(\n\t\t\t`${WHERE}: callback must be the URLSearchParams of the callback URL — new URL(request.url).searchParams`,\n\t\t);\n\t}\n\tconst { purpose } = input;\n\tif (purpose !== undefined && purpose !== 'signIn' && purpose !== 'link') {\n\t\tthrow new TypeError(\n\t\t\t`${WHERE}: purpose must be 'signIn' or 'link' when given`,\n\t\t);\n\t}\n\tconst device = deviceHint(context, options, WHERE);\n\tconst redeemed = await redeemFlow(\n\t\tcontext,\n\t\t{\n\t\t\tcallback: input.callback,\n\t\t\tflow: input.flow,\n\t\t\tcurrent: input.current ?? null,\n\t\t\tpurpose,\n\t\t},\n\t\tWHERE,\n\t);\n\tconst { type, meta, values, provider: configured } = redeemed;\n\tconst finish = finishers.get(type.name);\n\tif (finish === undefined) {\n\t\tthrow new TypeError(\n\t\t\t`${WHERE}: the user type lost its social configuration`,\n\t\t);\n\t}\n\n\tif (meta.stepUp !== null && configured.supportsStepUp !== true) {\n\t\tthrow unsupportedStepUp(meta, WHERE);\n\t}\n\tconst identity = checkIdentity(\n\t\tawait callProvider(\n\t\t\t() =>\n\t\t\t\tconfigured.exchange({\n\t\t\t\t\tcallback: input.callback,\n\t\t\t\t\t...values,\n\t\t\t\t\tstepUp: meta.stepUp,\n\t\t\t\t}),\n\t\t\tmeta.provider,\n\t\t\tWHERE,\n\t\t\tmeta,\n\t\t),\n\t\tmeta.provider,\n\t\tWHERE,\n\t\tmeta,\n\t);\n\tconst stepUp = stepUpOutcome(meta, identity, context.clock.now(), WHERE);\n\tconst ending: Ending = {\n\t\tcontext,\n\t\ttype,\n\t\tfinish,\n\t\tdevice,\n\t\treturnTo: meta.returnTo,\n\t\tstepUp,\n\t\twhere: WHERE,\n\t};\n\treturn redeemed.userId === null\n\t\t? signInAccount(ending, meta.provider, identity)\n\t\t: completeLink(ending, redeemed.userId, meta.provider, identity);\n}\n",
|
|
193
|
+
"import { SocialError } from '../../errors/janus-error';\n\n/** Longer than any path the application means to come back to. */\nconst MAX_LENGTH = 2048;\n\n/** Printable ASCII only: no control character (C0 or C1), no non-ASCII look-alike of `/` or `\\\\`. */\nconst PRINTABLE_ASCII = /^[\\u0020-\\u007e]+$/;\n\n/**\n * No empty and no `.` or `..` segment before the query or fragment: a browser\n * reads `/.//evil.test` as `//evil.test`. A trailing `/` is fine.\n */\nfunction hasPlainSegments(value: string): boolean {\n\tconst path = value.split(/[?#]/, 1)[0] ?? '';\n\tconst segments = path.split('/').slice(1);\n\treturn segments.every(\n\t\t(segment, index) =>\n\t\t\tsegment !== '.' &&\n\t\t\tsegment !== '..' &&\n\t\t\t(segment !== '' || index === segments.length - 1),\n\t);\n}\n\n/**\n * Whether `value` is a `returnTo` the core accepts: a path of this site. It\n * starts with a single `/`, is at most 2048 characters of printable ASCII\n * (no control character, C1 included, no look-alike of `/`), and holds no\n * `//`-start, no backslash and no empty, `.` or `..` segment, so no browser\n * reads it as another origin: `//evil.test`, `/\\evil.test`, `/.//evil.test`\n * and `https://evil.test` all fail. A query and a fragment are fine.\n *\n * Run it again before redirecting to a `returnTo` taken from anywhere.\n */\nexport function isReturnTo(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === 'string' &&\n\t\tvalue.length > 0 &&\n\t\tvalue.length <= MAX_LENGTH &&\n\t\tvalue.startsWith('/') &&\n\t\t!value.startsWith('//') &&\n\t\t!value.includes('\\\\') &&\n\t\tPRINTABLE_ASCII.test(value) &&\n\t\thasPlainSegments(value)\n\t);\n}\n\n/**\n * The `returnTo` of a flow: a path of this site the visitor comes back to,\n * or `null` for none (see `isReturnTo`). Checked at the start, before\n * anything is issued; `RETURN_TO_INVALID` otherwise.\n */\nexport function checkReturnTo(returnTo: unknown, where: string): string | null {\n\tif (returnTo === undefined || returnTo === null) return null;\n\tif (!isReturnTo(returnTo)) {\n\t\tthrow new SocialError(\n\t\t\t'RETURN_TO_INVALID',\n\t\t\t`${where}: returnTo must be a path of this site — starting with a single \"/\", with no \"\\\\\", no empty or \".\" segment and no scheme`,\n\t\t);\n\t}\n\treturn returnTo;\n}\n",
|
|
194
|
+
"/** Which user type a social call is for. */\n\nimport type { ResolvedType } from '../config';\nimport type { Context } from '../context';\n\n/** The user types that configure `social`, in declaration order. */\nexport function socialTypes(context: Context): ResolvedType[] {\n\treturn [...context.config.types.values()].filter(\n\t\t(type) => type.social !== null,\n\t);\n}\n\n/**\n * The type `social.start` is for: the one named, or the only one with\n * `social`. Both mistakes are the application's, never a request's, and a bare\n * `TypeError`.\n */\nexport function startType(\n\tcontext: Context,\n\tnamed: unknown,\n\twhere: string,\n): ResolvedType {\n\tif (named === undefined) {\n\t\tconst [only, ...others] = socialTypes(context);\n\t\tif (only === undefined || others.length > 0) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${where}: several user types configure social — say which one with type`,\n\t\t\t);\n\t\t}\n\t\treturn only;\n\t}\n\tconst type =\n\t\ttypeof named === 'string' ? context.config.types.get(named) : undefined;\n\tif (type?.social == null) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: type must name a user type that configures social`,\n\t\t);\n\t}\n\treturn type;\n}\n",
|
|
195
|
+
"/** `social.start` and `social.link`: the two ways a flow begins. */\n\nimport { SocialError } from '../../errors/janus-error';\nimport { isId } from '../../ids/id';\nimport type { Context } from '../context';\nimport { assertFresh } from '../sessions/fresh';\nimport type { Authenticated, SocialFlowStart } from '../types';\nimport { beginFlow, unknownProvider } from './begin';\nimport { checkReturnTo } from './return-to';\nimport { parseStepUp } from './step-up-request';\nimport { startType } from './types-of';\n\ninterface Options {\n\treadonly type?: unknown;\n\treadonly provider: unknown;\n\treadonly returnTo?: unknown;\n\treadonly stepUp?: unknown;\n}\n\n/** A sign-in flow for a provider of the type: the URL to send the visitor to, and the cookie. */\nexport async function startSignIn(\n\tcontext: Context,\n\toptions: Options,\n): Promise<SocialFlowStart> {\n\tconst where = 'social.start';\n\tconst type = startType(context, options?.type, where);\n\tif (typeof options.provider !== 'string') {\n\t\tthrow unknownProvider(options.provider, where);\n\t}\n\treturn beginFlow(context, type, {\n\t\tprovider: options.provider,\n\t\treturnTo: checkReturnTo(options.returnTo, where),\n\t\tuserId: null,\n\t\tstepUp: parseStepUp(options.stepUp, where),\n\t\twhere,\n\t});\n}\n\n/**\n * A link flow for the signed-in user: behind a fresh proof (`freshWithin`),\n * and bound to the user, so only they can complete it.\n */\nexport async function startLink(\n\tcontext: Context,\n\tcurrent: Authenticated<{ readonly id: string; readonly type: string }>,\n\toptions: Omit<Options, 'type'>,\n): Promise<SocialFlowStart> {\n\tconst where = 'social.link';\n\tconst type = context.config.types.get(current?.user?.type);\n\tif (type?.social == null || !isId(current.user.id)) {\n\t\tthrow new SocialError(\n\t\t\t'SOCIAL_PROVIDER_UNKNOWN',\n\t\t\t`${where}: this user's type configures no social provider`,\n\t\t);\n\t}\n\tassertFresh(current, type.social.freshWithinMs, context.clock);\n\tif (typeof options.provider !== 'string') {\n\t\tthrow unknownProvider(options.provider, where);\n\t}\n\treturn beginFlow(context, type, {\n\t\tprovider: options.provider,\n\t\treturnTo: checkReturnTo(options.returnTo, where),\n\t\tuserId: current.user.id,\n\t\tstepUp: parseStepUp(options.stepUp, where),\n\t\twhere,\n\t});\n}\n",
|
|
196
|
+
"/** `social.unlink` and `social.list`. */\n\nimport { SocialError } from '../../errors/janus-error';\nimport { isId } from '../../ids/id';\nimport { type Context, findRecord, refId } from '../context';\nimport { emit } from '../events';\nimport type { SocialLink, UserRef } from '../types';\nimport { linkStore, toSocialLink } from './attach';\n\n/**\n * Deletes one of a user's links. `false` for a link that is not theirs or\n * not there. **Refuses to leave the user no way to sign in**\n * (`LAST_SIGN_IN_METHOD`): a way is a password, another link, and — on a type\n * with no password — a verified e-mail.\n */\nexport async function unlinkAccount(\n\tcontext: Context,\n\tuser: UserRef,\n\tlink: { readonly provider: string; readonly accountId: string },\n): Promise<boolean> {\n\tconst id = refId(user);\n\tconst { provider, accountId } = link ?? {};\n\tif (\n\t\t!isId(id) ||\n\t\ttypeof provider !== 'string' ||\n\t\ttypeof accountId !== 'string'\n\t) {\n\t\treturn false;\n\t}\n\tconst record = await findRecord(context, id, null);\n\tconst type =\n\t\trecord === null ? undefined : context.config.types.get(record.type);\n\tif (record === null || type?.social == null) return false;\n\n\tconst store = linkStore(context);\n\tconst held = await store.findSocialLink(provider, accountId);\n\tif (held === null || held.userId !== record.id) return false;\n\n\tconst others = (await store.listUserSocialLinks(record.id)).filter(\n\t\t(other) => other.provider !== provider || other.accountId !== accountId,\n\t);\n\tconst ways =\n\t\t(record.password === null ? 0 : 1) +\n\t\tothers.length +\n\t\t(type.password === null && record.emailVerifiedAt !== null ? 1 : 0);\n\tif (ways === 0) {\n\t\tthrow new SocialError(\n\t\t\t'LAST_SIGN_IN_METHOD',\n\t\t\t\"social.unlink: this is the user's only way to sign in — set a password or link another account first\",\n\t\t\t{ provider, userId: record.id, userType: record.type },\n\t\t);\n\t}\n\n\tif (!(await store.deleteSocialLink(record.id, provider, accountId))) {\n\t\treturn false;\n\t}\n\tawait emit(context, 'user.socialUnlinked', record, context.clock.now(), {\n\t\tprovider,\n\t});\n\treturn true;\n}\n\n/** A user's links, oldest first; none for an unknown user. */\nexport async function listLinks(\n\tcontext: Context,\n\tuser: UserRef,\n): Promise<readonly SocialLink[]> {\n\tconst id = refId(user);\n\tif (!isId(id) || context.store.socialLinks === undefined) return [];\n\tconst records = await context.store.socialLinks.listUserSocialLinks(id);\n\treturn records\n\t\t.map(toSocialLink)\n\t\t.sort(\n\t\t\t(a, b) =>\n\t\t\t\ta.linkedAt.getTime() - b.linkedAt.getTime() ||\n\t\t\t\ta.provider.localeCompare(b.provider),\n\t\t);\n}\n",
|
|
197
|
+
"/** Wiring refusals for `social`: bare `TypeError`s, since only wiring produces one. */\n\nimport type { ResolvedConfig } from '../config';\nimport type { JanusStores } from '../port/types';\n\n/**\n * A user type that configures `social` needs `store.socialLinks`: the slot is\n * optional so an application without social sign-in carries none, and this is\n * where the one that has `social` is told which type needs it.\n */\nexport function refuseSocialWithoutSlot(\n\tresolved: ResolvedConfig,\n\tstore: JanusStores,\n\twhere: string,\n): void {\n\tif (store.socialLinks !== undefined) return;\n\tfor (const type of resolved.types.values()) {\n\t\tif (type.social !== null) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${where}: the user type \"${type.name}\" configures social and store.socialLinks is missing — createMemoryStores() has it; an adapter's stores need its social links table or collection`,\n\t\t\t);\n\t\t}\n\t}\n}\n",
|
|
198
|
+
"/**\n * Social sign-in: the flows `auth.social` answers (`start.ts`, `complete.ts`,\n * `unlink.ts`), the flow's secret, cookie and binding (`flow-secret.ts`,\n * `flow-cookie-value.ts`, `cookie.ts`), and the one place a provider's\n * failure is caught (`provider-call.ts`).\n *\n * Gathered here from the files beside this one.\n */\n\nimport type { Context } from '../context';\nimport type { Finish } from '../email-sign-in';\nimport { secondFactorFlows } from '../second-factor/flows';\nimport type { SocialApi } from '../types';\nimport { completeFlow } from './complete';\nimport { socialCookie } from './cookie';\nimport { startLink, startSignIn } from './start';\nimport { socialTypes } from './types-of';\nimport { listLinks, unlinkAccount } from './unlink';\n\nexport { refuseSocialWithoutSlot } from './wiring';\n\n/** `SocialApi`, degenericised: `janus()` casts it to the typed form once. */\ntype InternalSocialApi = SocialApi<\n\t{ readonly id: string; readonly type: string },\n\tstring,\n\tstring\n>['social'];\n\n/** The `social` of an instance where some user type configures it. */\nexport function socialApi(context: Context): InternalSocialApi {\n\tconst finishers = new Map<string, Finish>(\n\t\tsocialTypes(context).map((type) => [\n\t\t\ttype.name,\n\t\t\tsecondFactorFlows(context, type, (operation) => operation).finish,\n\t\t]),\n\t);\n\n\treturn {\n\t\tstart: (options) => startSignIn(context, options),\n\t\tlink: (current, options) => startLink(context, current, options),\n\t\tcomplete: (input, options) =>\n\t\t\tcompleteFlow(context, finishers, input, options) as never,\n\t\tunlink: (user, link) => unlinkAccount(context, user, link),\n\t\tlist: (user) => listLinks(context, user),\n\t\tcookie: socialCookie(context),\n\t};\n}\n",
|
|
199
|
+
"/** The methods every instance has, plus the optional ones its configuration turns on. */\n\nimport { apiKeysApi } from './api-keys';\nimport type { ResolvedConfig } from './config';\nimport type { Context } from './context';\nimport { invitationsApi } from './invitations';\nimport type { ApiKeyStore, InvitationStore } from './port/types';\nimport { sharedApi } from './sessions';\nimport { socialApi } from './social';\n\n/** `sharedApi`, with `apiKeys` when the instance has a key store and `social` when a type configures it. */\nexport function sharedSurface(\n\tcontext: Context,\n\tresolved: ResolvedConfig,\n\tapiKeys: ApiKeyStore | null,\n\tinvitations: InvitationStore | null = null,\n) {\n\tconst hasSocial = [...resolved.types.values()].some(\n\t\t(type) => type.social !== null,\n\t);\n\treturn {\n\t\t...sharedApi(context),\n\t\t...(apiKeys === null ? {} : { apiKeys: apiKeysApi(context, apiKeys) }),\n\t\t...(invitations === null\n\t\t\t? {}\n\t\t\t: { invitations: invitationsApi(context, invitations) }),\n\t\t...(hasSocial ? { social: socialApi(context) } : {}),\n\t};\n}\n",
|
|
200
|
+
"import { guardRelations, guardStore } from '../stores/guard';\nimport { systemClock } from '../time/clock';\nimport { anyTypeAvatar } from './avatar';\nimport {\n\ttype ApiKeysConfig,\n\ttype InvitationsConfig,\n\ttype JanusConfig,\n\tresolveConfig,\n} from './config';\nimport { warnThrottleWindow } from './config/warn-throttle-window';\nimport { createContext } from './context';\nimport { anyTypeChangeEmail } from './email-flows/any-type-change-email';\nimport { anyTypeResetPassword } from './email-flows/any-type-reset-password';\nimport { anyTypeVerifyEmail } from './email-flows/any-type-verify-email';\nimport { resolveEvents } from './events';\nimport { guardStores } from './outage';\nimport { refusePasskeysWithoutSlot } from './passkeys';\nimport { assertApiKeyStore } from './port/assert-api-keys';\nimport { assertInvitationStore } from './port/assert-invitations';\nimport { assertStores } from './port/assert-stores';\nimport type { ApiKeyStore, InvitationStore } from './port/types';\nimport { sharedSurface } from './shared-api';\nimport { refuseSocialWithoutSlot } from './social';\nimport type { Checked, Janus } from './types';\nimport { typeApi } from './users';\n\n/**\n * Wires the identities side over the stores the application opened. **Synchronous,\n * and does no I/O**: it connects to nothing.\n *\n * ```ts\n * // One user type\n * const auth = janus({\n * user: z.object({ email: z.email(), name: z.string() }),\n * password: { login: 'email' },\n * store: createMemoryStores(),\n * hasher: scryptHasher(),\n * });\n * const { user, token } = await auth.signUp({ email, name, password });\n *\n * // Several\n * const auth = janus({\n * users: {\n * patient: { schema: Patient, password: { login: 'email' } },\n * staff: { schema: Staff, password: { login: 'email' }, session: { lifespan: '8h' } },\n * },\n * store, hasher,\n * });\n * await auth.staff.signIn({ email, password });\n * const current = await auth.authenticate(request, { type: 'staff' });\n * ```\n *\n * The types refuse first, on the offending key: a login or an e-mail that\n * names no required string field, a schema declaring a field `janus` sets, a\n * user type named like a method. What follows at run time is the net for\n * JavaScript callers, each a bare `TypeError` because only wiring produces one:\n * a store slot missing or incomplete; a password type with no hasher — there\n * is no silent fallback; two hashers claiming the same prefix, which would make\n * verification depend on the order they were listed in; a type with `social`\n * and no `store.socialLinks`.\n */\nexport function janus<const C extends JanusConfig>(\n\tconfig: C & Checked<C>,\n): Janus<C> {\n\tconst where = 'janus';\n\tconst resolved = resolveConfig(config, where);\n\twarnThrottleWindow(resolved, where);\n\tconst capabilities = assertStores(config.store, where);\n\trefuseSocialWithoutSlot(resolved, config.store, where);\n\trefusePasskeysWithoutSlot(resolved, config.store, where);\n\n\tconst hasher = config.hasher ?? null;\n\tconst verifiers = [\n\t\t...(hasher === null ? [] : [hasher]),\n\t\t...(config.verifiers ?? []),\n\t];\n\tconst prefixes = new Set<string>();\n\tfor (const verifier of verifiers) {\n\t\tif (typeof verifier?.prefix !== 'string' || verifier.prefix === '') {\n\t\t\tthrow new TypeError(`${where}: every hasher needs a non-empty prefix`);\n\t\t}\n\t\tif (prefixes.has(verifier.prefix)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${where}: two hashers claim the prefix \"${verifier.prefix}\" — which one verifies would depend on their order`,\n\t\t\t);\n\t\t}\n\t\tprefixes.add(verifier.prefix);\n\t}\n\n\tconst relations = config.relations ?? null;\n\tif (\n\t\trelations !== null &&\n\t\ttypeof (relations as { deleteEntity?: unknown }).deleteEntity !== 'function'\n\t) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: relations must be a relation store — relations.deleteEntity is missing`,\n\t\t);\n\t}\n\n\tconst { apiKeys, invitations } = wireOptionalStores(config, resolved, where);\n\n\tconst context = createContext(\n\t\tresolved,\n\t\tguardStores(config.store),\n\t\trelations === null ? null : guardRelations(relations),\n\t\tcapabilities,\n\t\tconfig.clock ?? systemClock,\n\t\thasher,\n\t\tverifiers,\n\t\tresolveEvents(config.events, where),\n\t\tapiKeys,\n\t\tinvitations,\n\t);\n\n\tconst shared = sharedSurface(context, resolved, apiKeys, invitations);\n\tconst types = Object.fromEntries(\n\t\t[...resolved.types.values()].map((type) => [\n\t\t\ttype.name,\n\t\t\ttypeApi(context, type),\n\t\t]),\n\t);\n\n\t// The one cast at the boundary: every field was validated against its\n\t// type's schema before any of these answers was built.\n\tconst surface = resolved.single\n\t\t? { ...shared, ...types['user'] }\n\t\t: {\n\t\t\t\t...shared,\n\t\t\t\t...types,\n\t\t\t\t...anyTypeAvatar(context),\n\t\t\t\t...anyTypeChangeEmail(context),\n\t\t\t\t...anyTypeVerifyEmail(context),\n\t\t\t\t...anyTypeResetPassword(context),\n\t\t\t};\n\treturn surface as unknown as Janus<C>;\n}\n\n/** The stores of the opt-in blocks `apiKeys` and `invitations`, each `null` without its block. */\nfunction wireOptionalStores(\n\tconfig: JanusConfig,\n\tresolved: ReturnType<typeof resolveConfig>,\n\twhere: string,\n): { apiKeys: ApiKeyStore | null; invitations: InvitationStore | null } {\n\treturn {\n\t\tapiKeys:\n\t\t\tresolved.apiKeys === null\n\t\t\t\t? null\n\t\t\t\t: wireApiKeyStore(config.apiKeys as ApiKeysConfig, where),\n\t\tinvitations:\n\t\t\tresolved.invitations === null\n\t\t\t\t? null\n\t\t\t\t: wireInvitationStore(config.invitations as InvitationsConfig, where),\n\t};\n}\n\n/** The API key store, checked and guarded: an outage there is `STORE_FAILED` too. */\nfunction wireApiKeyStore(config: ApiKeysConfig, where: string): ApiKeyStore {\n\tassertApiKeyStore(config.store, `${where}: apiKeys.store`);\n\treturn guardStore('apiKeys', config.store);\n}\n\n/** The invitation store, checked and guarded: an outage there is `STORE_FAILED` too. */\nfunction wireInvitationStore(\n\tconfig: InvitationsConfig,\n\twhere: string,\n): InvitationStore {\n\tassertInvitationStore(config.store, `${where}: invitations.store`);\n\treturn guardStore('invitations', config.store);\n}\n",
|
|
201
|
+
"import { resolveSealer, type SealingKey } from './sealing';\n\n/** What {@link parseSealingKeys} can be told. */\nexport interface ParseSealingKeysOptions {\n\t/**\n\t * Key ids to refuse, such as a development key committed to the repository:\n\t * `{ refuse: ['dev'] }` in production. Secrets sealed under a key anyone can\n\t * read are not sealed. An id is matched exactly, case-sensitive, on any\n\t * entry — the one that seals or one that only opens.\n\t */\n\treadonly refuse?: readonly string[];\n\t/** Names the setting in every refusal, e.g. `'TOTP_KEYS'`. */\n\treadonly where?: string;\n}\n\n/**\n * Reads `\"id:key,id:key\"` — the form a key list takes in one environment\n * variable — into the `keys` of `janus({ secondFactor: { keys } })`: the first\n * seals, every one opens.\n *\n * Refuses, with a `TypeError` that never echoes a key, an empty list, an entry\n * that is not `id:key`, an id outside letters, digits, `_` and `-` (at most 42 here, 64 for\n * `janus()`; a longer one looks like key material, `key:id` swapped, and is refused\n * without being echoed), a duplicate id, a key that is not 32 bytes in base64 or base64url, and\n * any id named in `options.refuse`.\n */\nexport function parseSealingKeys(\n\tlist: string,\n\toptions: ParseSealingKeysOptions = {},\n): [SealingKey, ...SealingKey[]] {\n\tconst where = options.where ?? 'parseSealingKeys';\n\tif (typeof list !== 'string') {\n\t\tthrow new TypeError(`${where}: expected a string — \"id:key,id:key\"`);\n\t}\n\tconst refused = new Set(options.refuse);\n\tconst keys = list\n\t\t.split(',')\n\t\t.map((entry) => entry.trim())\n\t\t.filter((entry) => entry !== '')\n\t\t.map((entry, index): SealingKey => {\n\t\t\tconst at = entry.indexOf(':');\n\t\t\tif (at < 1) {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t`${where}: entry ${index + 1} is not id:key — \"id:key,id:key\", the first seals`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst id = entry.slice(0, at);\n\t\t\t// janus() accepts ids up to 64; this parser, new, keeps to 42 so a\n\t\t\t// swapped key:id is caught here and never echoed.\n\t\t\tif (id.length >= 43) {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t`${where}: entry ${index + 1} has an id that looks like key material — write id:key, the id first`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (refused.has(id)) {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t`${where}: the key \"${id}\" is refused here — make a real one with openssl rand -base64 32`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn { id, key: entry.slice(at + 1) };\n\t\t});\n\t// Id, length and duplicates are resolveSealer's, so a list parsed here is\n\t// one janus() accepts.\n\tresolveSealer(keys, where);\n\treturn keys as [SealingKey, ...SealingKey[]];\n}\n",
|
|
202
|
+
"import { isStorable } from '../stores/storable';\nimport { derivedKey } from './derived-keys';\nimport { resolveSealer, type SealingKey, seal, unseal } from './sealing';\n\n/**\n * Seals and opens an application's own secrets at rest, under keys derived\n * for one purpose.\n */\nexport interface PurposeSealer {\n\t/**\n\t * Seals `plaintext` under the first key, bound to `id` (the record it\n\t * belongs to): `v1.<key id>.<iv>.<ciphertext and tag>`.\n\t */\n\tseal(id: string, plaintext: string): string;\n\t/**\n\t * Opens `sealed` for `id`, or answers `null` when it does not open: another\n\t * id, a sealed value altered or copied from another purpose, a key no longer\n\t * held, or text that is not a sealed value. Never throws.\n\t */\n\tunseal(id: string, sealed: string): string | null;\n\t/** The id of the key that seals new values: the first of `keys`. */\n\treadonly sealWith: string;\n\t/**\n\t * Whether `sealed` was sealed under a key other than the first, so the\n\t * caller can seal it again after a rotation. `false` for text that is not a\n\t * sealed value.\n\t */\n\tneedsReseal(sealed: string): boolean;\n}\n\n/** The longest purpose: HKDF's info is limited, and a name never needs more. */\nconst MAX_PURPOSE = 256;\n/** An id this long may be a key written first: never echoed (as in sealing.ts). */\nconst KEY_LENGTH = 43;\n/** Unknown key ids warned about at most this many times per sealer. */\nconst MAX_WARNED = 32;\n\n/**\n * Warns once per key id that `sealed` names and the sealer does not hold: a\n * key dropped before its values were sealed again, or a value from elsewhere.\n * The warning names the id only, never a value.\n */\nfunction warnUnknownKey(\n\tsealed: string,\n\tkeys: ReadonlyMap<string, Buffer>,\n\twarned: Set<string>,\n): void {\n\tconst parts = sealed.split('.');\n\tconst keyId = parts[1];\n\tif (\n\t\tparts.length !== 4 ||\n\t\tparts[0] !== 'v1' ||\n\t\tkeyId === undefined ||\n\t\t!/^[A-Za-z0-9_-]{1,64}$/.test(keyId) ||\n\t\tkeys.has(keyId) ||\n\t\twarned.has(keyId) ||\n\t\twarned.size >= MAX_WARNED\n\t) {\n\t\treturn;\n\t}\n\twarned.add(keyId);\n\t// An id this long may be key material written in its place (key:id): it is\n\t// named by its length, as sealing.ts does, and never echoed.\n\tconst named =\n\t\tkeyId.length >= KEY_LENGTH\n\t\t\t? `a key id of ${keyId.length} characters`\n\t\t\t: `the key \"${keyId}\"`;\n\tprocess.emitWarning(\n\t\t`janus: a value sealed with ${named} was given to sealerFor, which no longer holds that key — keep a key until no value is sealed with it`,\n\t\t{ code: 'JANUS_SEALER_UNKNOWN_KEY' },\n\t);\n}\n\n/**\n * A sealer for `purpose`, from the same `keys` as `janus({ secondFactor: {\n * keys } })` or `parseSealingKeys`: AES-256-GCM, the first key seals, every\n * key opens, and the id is the additional data.\n *\n * The key of each entry is derived for `purpose` (HKDF-SHA-256), never used as\n * it is, so a value sealed here does not open under another purpose or under\n * the keys of the second factor. Keep a purpose stable: renamed, what was\n * sealed no longer opens. Rotation is by key id: put the new key first and keep\n * the old one until no value is sealed with it.\n *\n * Refuses, with a `TypeError`, an empty, longer than 256 characters or\n * badly formed `purpose` (a NUL or a lone surrogate), and any list\n * `parseSealingKeys` refuses. `seal` refuses non-strings, an empty plaintext\n * and a badly formed id or plaintext the same way.\n */\nexport function sealerFor(\n\tkeys: readonly SealingKey[],\n\tpurpose: string,\n): PurposeSealer {\n\tif (\n\t\ttypeof purpose !== 'string' ||\n\t\tpurpose === '' ||\n\t\tpurpose.length > MAX_PURPOSE ||\n\t\t!isStorable(purpose)\n\t) {\n\t\tthrow new TypeError(\n\t\t\t`sealerFor: purpose must be a well-formed string of 1 to ${MAX_PURPOSE} characters`,\n\t\t);\n\t}\n\tconst base = resolveSealer(keys, 'sealerFor');\n\t// Prefixed, so no purpose of an application can equal one the library keeps.\n\tconst named = `janus/sealer/v1/${purpose}`;\n\tconst unknown = new Set<string>();\n\tconst derived = new Map(\n\t\t[...base.keys.keys()].map((keyId) => [\n\t\t\tkeyId,\n\t\t\tderivedKey(base, named, keyId) as Buffer,\n\t\t]),\n\t);\n\tconst sealer = { sealWith: base.sealWith, keys: derived };\n\treturn {\n\t\tsealWith: sealer.sealWith,\n\t\tseal(id, plaintext) {\n\t\t\tif (typeof id !== 'string' || typeof plaintext !== 'string') {\n\t\t\t\tthrow new TypeError('sealerFor: seal(id, plaintext) takes two strings');\n\t\t\t}\n\t\t\tif (plaintext === '' || !isStorable(id) || !isStorable(plaintext)) {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t'sealerFor: seal(id, plaintext) takes a well-formed id and a non-empty, well-formed plaintext',\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn seal(sealer, plaintext, id);\n\t\t},\n\t\tunseal(id, sealed) {\n\t\t\tif (typeof id !== 'string' || typeof sealed !== 'string') return null;\n\t\t\tif (!isStorable(id)) return null;\n\t\t\twarnUnknownKey(sealed, sealer.keys, unknown);\n\t\t\t// The one catch here wraps a decipher, never a store: a value that does\n\t\t\t// not open is an answer (`null`), not a failure.\n\t\t\ttry {\n\t\t\t\treturn unseal(sealer, sealed, id, 'sealerFor').plain;\n\t\t\t} catch {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t},\n\t\tneedsReseal(sealed) {\n\t\t\tif (typeof sealed !== 'string') return false;\n\t\t\tconst [version, keyId] = sealed.split('.');\n\t\t\treturn (\n\t\t\t\tsealed.split('.').length === 4 &&\n\t\t\t\tversion === 'v1' &&\n\t\t\t\tkeyId !== sealer.sealWith\n\t\t\t);\n\t\t},\n\t};\n}\n",
|
|
203
|
+
"/** Where a failure is reported; `console.error` by default. */\nexport type BackgroundLog = (line: string) => void;\n\n/** What `background()` returns. */\nexport type Background = {\n\t/**\n\t * Starts `task` on a later microtask and returns at once. A failure, thrown\n\t * or rejected, is logged as `${name} failed in the background: ${error}` and\n\t * never reaches the caller.\n\t */\n\trun(name: string, task: () => unknown): void;\n\t/**\n\t * Resolves once no task is running, including the tasks started while it\n\t * waits. A spec awaits it before reading what the tasks wrote.\n\t */\n\tsettled(): Promise<void>;\n};\n\n/**\n * A fire-and-forget runner for work that must not delay a response, such as\n * the mail of a flow that answers the same whether the account exists or not.\n */\nexport function background(\n\tlog: BackgroundLog = (line) => console.error(line),\n): Background {\n\tconst running = new Set<Promise<void>>();\n\n\treturn {\n\t\trun(name, task) {\n\t\t\tconst job: Promise<void> = Promise.resolve()\n\t\t\t\t.then(task)\n\t\t\t\t.then(\n\t\t\t\t\t() => undefined,\n\t\t\t\t\t(error: unknown) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tlog(`${name} failed in the background: ${error}`);\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t// A log that throws must not become an unhandled rejection.\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t\t.finally(() => running.delete(job));\n\t\t\trunning.add(job);\n\t\t},\n\t\tasync settled() {\n\t\t\twhile (running.size > 0) await Promise.all([...running]);\n\t\t},\n\t};\n}\n"
|
|
204
|
+
],
|
|
205
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASO,IAAM,gBAAgB;AAG7B,IAAM,UAAU,MAAM,KAAK,KAAK;AA0BhC,IAAM,OAAO;AAGb,SAAS,QAAQ,CAAC,QAAgB,MAA6B;AAAA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