@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
package/README.md
CHANGED
|
@@ -1,3 +1,2929 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @softistx/janus
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Identities and permissions as an **embeddable** TypeScript library: your
|
|
4
|
+
process, your database, behind a port you can implement. Use **identities**
|
|
5
|
+
alone, **permissions** alone, or both — see [Three ways to use it](#three-ways-to-use-it).
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { z } from 'zod';
|
|
9
|
+
import { createMemoryStores, janus, scryptHasher } from '@softistx/janus';
|
|
10
|
+
|
|
11
|
+
const auth = janus({
|
|
12
|
+
user: z.object({ email: z.email(), name: z.string() }),
|
|
13
|
+
password: { login: 'email' },
|
|
14
|
+
store: createMemoryStores(),
|
|
15
|
+
hasher: scryptHasher(),
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
const { user, token } = await auth.signUp({ email, name, password });
|
|
19
|
+
const current = await auth.authenticate(request); // { user, session, token, renewed } | null (a key-shaped bearer: null)
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
> **0.x.** A minor version may still change the surface; the changelog says how.
|
|
23
|
+
|
|
24
|
+
## Install
|
|
25
|
+
|
|
26
|
+
Public on npmjs:
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
bun add @softistx/janus
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
**Migrating from `@nxgt/janus*`:** these packages were published on npm under
|
|
33
|
+
`@nxgt/janus*`. Swap each name for its `@softistx/janus*` twin in
|
|
34
|
+
`package.json` and in your imports.
|
|
35
|
+
|
|
36
|
+
No runtime dependency. `typescript` (6 or 7) is a required peer. Your tsconfig resolves as a
|
|
37
|
+
bundler does (`"moduleResolution": "bundler"`, which Bun and every bundler
|
|
38
|
+
use): the declarations import without extensions, so `nodenext` is not
|
|
39
|
+
supported.
|
|
40
|
+
|
|
41
|
+
## Subpaths
|
|
42
|
+
|
|
43
|
+
| Import | What it holds |
|
|
44
|
+
| --- | --- |
|
|
45
|
+
| `@softistx/janus` | **Identities**: `janus()`, the identity stores' port and its in-memory reference (`createMemoryStores`), the hashers, the user events (`UserEvent`, `UserEventListener`, `UserEventType`), the `PasskeyVerifier` port a WebAuthn library implements and its types (`PasskeyRelyingParty`, `PasskeyRegistration`, `PasskeyAssertion`, `PasskeyRefusal`, `PasskeyRefusalReason`). And the **shared vocabulary**: errors, subjects and the tuple notation, ids, pagination, time, the `background` runner |
|
|
46
|
+
| `@softistx/janus/permissions` | **Permissions**: `defineModel`, `fromField`, `when`, `permissions()` — `can`, `list`, `grant`, `revoke`, `replace` — the relation store's port and its in-memory reference (`createMemoryRelations`) |
|
|
47
|
+
| `@softistx/janus/testing` | **For your tests**: `totpCode(secret, at?)`, the code an authenticator app shows for a base32 secret |
|
|
48
|
+
| `@softistx/janus/conformance` | **For adapters**: the suites a store runs — `describeJanusStores` (with the optional `socialLinks` and `passkeys` groups), `describeRelationStores`, `describeApiKeyStores` — their cases as data, and the reference harnesses |
|
|
49
|
+
|
|
50
|
+
A subpath appears in `exports` only once it exports something you should call:
|
|
51
|
+
a published entry point is a promise.
|
|
52
|
+
|
|
53
|
+
## Three ways to use it
|
|
54
|
+
|
|
55
|
+
Janus has two sides. **Identities** answers *who is this?* — users, their
|
|
56
|
+
logins and passwords, codes and links sent by e-mail, a TOTP second factor, sessions, one-time tokens. **Permissions** answers *may
|
|
57
|
+
they?* — a model, the tuples stored against it, and `can`. Each side is usable
|
|
58
|
+
alone, and neither loads the other's code: a spec reads the import graph of
|
|
59
|
+
each entry point and fails if one reaches into the other.
|
|
60
|
+
|
|
61
|
+
**Identities only** — users, logins, passwords, sessions, one-time tokens:
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
import { z } from 'zod';
|
|
65
|
+
import { createMemoryStores, janus, scryptHasher } from '@softistx/janus';
|
|
66
|
+
|
|
67
|
+
const auth = janus({
|
|
68
|
+
user: z.object({ email: z.email() }),
|
|
69
|
+
password: { login: 'email' },
|
|
70
|
+
store: createMemoryStores(),
|
|
71
|
+
hasher: scryptHasher(),
|
|
72
|
+
});
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
**Permissions only** — your users live elsewhere; name their types as the
|
|
76
|
+
subjects:
|
|
77
|
+
|
|
78
|
+
```ts
|
|
79
|
+
import {
|
|
80
|
+
createMemoryRelations,
|
|
81
|
+
defineModel,
|
|
82
|
+
permissions,
|
|
83
|
+
} from '@softistx/janus/permissions';
|
|
84
|
+
|
|
85
|
+
const access = permissions({
|
|
86
|
+
model: defineModel({
|
|
87
|
+
subjects: ['user'],
|
|
88
|
+
types: {
|
|
89
|
+
document: {
|
|
90
|
+
related: { owners: ['user'], viewers: ['user'] },
|
|
91
|
+
permits: { view: ['owners', 'viewers'] },
|
|
92
|
+
},
|
|
93
|
+
},
|
|
94
|
+
}),
|
|
95
|
+
store: createMemoryRelations(),
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
await access.grant({ type: 'document', id: 'd1' }, 'viewers', { type: 'user', id: 'u1' });
|
|
99
|
+
await access.can({ type: 'user', id: 'u1' }, 'view', { type: 'document', id: 'd1' }); // true
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
**Both** — the user types become the subjects, and deleting a user deletes
|
|
103
|
+
every tuple naming them:
|
|
104
|
+
|
|
105
|
+
```ts
|
|
106
|
+
import { z } from 'zod';
|
|
107
|
+
import { createMemoryStores, janus, scryptHasher } from '@softistx/janus';
|
|
108
|
+
import {
|
|
109
|
+
createMemoryRelations,
|
|
110
|
+
defineModel,
|
|
111
|
+
permissions,
|
|
112
|
+
} from '@softistx/janus/permissions';
|
|
113
|
+
|
|
114
|
+
const relations = createMemoryRelations();
|
|
115
|
+
|
|
116
|
+
const auth = janus({
|
|
117
|
+
user: z.object({ email: z.email() }),
|
|
118
|
+
password: { login: 'email' },
|
|
119
|
+
store: createMemoryStores(),
|
|
120
|
+
relations,
|
|
121
|
+
hasher: scryptHasher(),
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
const access = permissions({
|
|
125
|
+
model: defineModel({
|
|
126
|
+
subjects: auth.types,
|
|
127
|
+
types: {
|
|
128
|
+
document: {
|
|
129
|
+
related: { owners: ['user'] },
|
|
130
|
+
permits: { view: ['owners'] },
|
|
131
|
+
},
|
|
132
|
+
},
|
|
133
|
+
}),
|
|
134
|
+
store: relations,
|
|
135
|
+
});
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
The words used throughout — side, subject, tuple, identity stores, relation
|
|
139
|
+
store, adapter — are defined once, in
|
|
140
|
+
[the shared vocabulary](docs/guide/vocabulary.md#words).
|
|
141
|
+
|
|
142
|
+
## The one rule
|
|
143
|
+
|
|
144
|
+
**An absence is `null`. A failure throws.**
|
|
145
|
+
|
|
146
|
+
Everything else in this package is downstream of that sentence. A store that
|
|
147
|
+
cannot answer — a refused connection, a timeout, a primary stepping down, a bug
|
|
148
|
+
in the adapter — **throws**, and a caller answers 503. Mapping that to a 404, to
|
|
149
|
+
`null` or to `false` turns an outage into a silent lockout: every user is told
|
|
150
|
+
they do not exist. That has been measured twice in this organisation,
|
|
151
|
+
two days apart, which is why it is a term of the port here rather than a note in
|
|
152
|
+
the documentation.
|
|
153
|
+
|
|
154
|
+
## API
|
|
155
|
+
|
|
156
|
+
### Errors
|
|
157
|
+
|
|
158
|
+
```ts
|
|
159
|
+
import { JanusError, StoreFailure, NotFoundError, type JanusErrorCode } from '@softistx/janus';
|
|
160
|
+
|
|
161
|
+
async function signIn(email: string, password: string): Promise<Response> {
|
|
162
|
+
try {
|
|
163
|
+
const { token } = await auth.signIn({ email, password });
|
|
164
|
+
return Response.json({ token });
|
|
165
|
+
} catch (error) {
|
|
166
|
+
if (error instanceof JanusError && error.code === 'CREDENTIALS_INVALID') {
|
|
167
|
+
return new Response(null, { status: 401 });
|
|
168
|
+
}
|
|
169
|
+
throw error; // STORE_FAILED included: that is your 503, never a 401
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
`JanusError` is the base of everything thrown at call time. It extends `Error`,
|
|
175
|
+
so no consumer has to order their `catch` blocks. `code` is a union of thirty-four
|
|
176
|
+
string literals, so a `switch` over it is exhaustive and adding a code breaks the
|
|
177
|
+
compilation of callers that exhaust it. `statusOf(code)` answers the status
|
|
178
|
+
below, as `JanusErrorStatus` — a union of the ten literals, which a
|
|
179
|
+
framework's own status type accepts:
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
import { JanusError, statusOf } from '@softistx/janus';
|
|
183
|
+
|
|
184
|
+
if (error instanceof JanusError) {
|
|
185
|
+
return Response.json({ code: error.code }, { status: statusOf(error.code) }); // STORE_FAILED → 503
|
|
186
|
+
}
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
| Code | Answer it deserves |
|
|
190
|
+
| --- | --- |
|
|
191
|
+
| `STORE_FAILED` | **503.** Never a negative answer |
|
|
192
|
+
| `NOT_FOUND` | 404 |
|
|
193
|
+
| `LOGIN_TAKEN`, `VERSION_CONFLICT` | 409 |
|
|
194
|
+
| `EMAIL_CHANGE_NEEDS_PROOF` | 409 — `update` would move the e-mail of a user who holds a second factor (active or waiting) or a passkey: nothing is written. Use `changeEmail`, which proves the new address and keeps them. `userId`, `userType` |
|
|
195
|
+
| `USER_INVALID` | 400, field by field from `issues` |
|
|
196
|
+
| `AVATAR_ID_INVALID` | 400 — the id given to `avatar.set` is not a non-empty string of at most 512 characters that every store can keep |
|
|
197
|
+
| `PASSWORD_TOO_SHORT`, `HASH_UNSUPPORTED` | 400 |
|
|
198
|
+
| `CREDENTIALS_INVALID` | 401 — one code for an unknown login, no password, a wrong one, a login throttled for too many, and a passkey sign-in that was not accepted (`reason: 'passkey'`, for your logs); `retryAfter`, when set, belongs in the body and a `Retry-After` header |
|
|
199
|
+
| `CODE_INVALID` | 401 — a one-time code that does not match: a second factor's, or one sent by e-mail; `attemptsLeft` from either `confirm` belongs in the body, and `retryAfter` when `reason` is `'throttled'` (the user's app-code window, or the account's second-step window, is spent: wait, a new challenge does not help) |
|
|
200
|
+
| `SECOND_FACTOR_NOT_ENROLLED`, `SECOND_FACTOR_ACTIVE` | 409 — the factor is not in the state the call needs |
|
|
201
|
+
| `USER_INACTIVE` | 403 |
|
|
202
|
+
| `EMAIL_UNVERIFIED` | 403 — the right password on an address never verified, on a type with `password.requireVerifiedEmail`; no session was opened. Also `secondFactor.enroll` / `activate` and `passkeys.registrationOptions` / `register` for a user of a type that holds an e-mail never verified: nothing is written. The password case is told only to somebody who knows the password. Also a social sign-up whose provider does not vouch for the e-mail: nobody is created |
|
|
203
|
+
| `MAIL_THROTTLED` | 429 — too many e-mails asked for one address or one user in the window; `retryAfter` belongs in the body and a `Retry-After` header. Tell the visitor to use the last e-mail they received (it still works) or to wait. Safe to show: it reveals nothing about accounts |
|
|
204
|
+
| `STEP_UP_REQUIRED` | 403 — the session proved who it is too long ago for this action: ask for a step-up, then send the request again. With `reason: 'apiKey'` the caller is an API key, which is never fresh: a step-up does not help |
|
|
205
|
+
| `TOKEN_UNKNOWN`, `TOKEN_SPENT`, `TOKEN_EXPIRED`, `TOKEN_STALE` | 400 |
|
|
206
|
+
| `INVALID_CURSOR` | 400 |
|
|
207
|
+
| `CURSOR_FILTER_MISMATCH` | 400 |
|
|
208
|
+
| `UNSUPPORTED` | 501 — a wiring mistake, and the message names the store to change |
|
|
209
|
+
| `PERMISSION_DEPTH` | 500 — a permission check or list walked past `maxDepth`; not a denial |
|
|
210
|
+
| `API_KEY_LIMIT` | 409 — the user holds `maxActive` API keys; `maxActive` belongs in the body, and they revoke one first |
|
|
211
|
+
| `API_KEY_INVALID` | 400 — a key's name, lifetime, scopes or bound object is refused; `field` says which |
|
|
212
|
+
| `INVITATION_INVALID` | 400 — a code that names no pending invitation (one code for unknown, malformed, accepted, revoked and lapsed, told apart by `reason`), or an invitation field that cannot be kept (`field`) |
|
|
213
|
+
| `INVITATION_LIMIT` | 409 — the scope holds `maxPending` invitations; `maxActive` belongs in the body |
|
|
214
|
+
| `INVITATION_NOT_PENDING` | 409 — `resend` or `revoke` on an invitation that is accepted or revoked |
|
|
215
|
+
| `INVITATION_REFUSED` | 403 — `invitations.beforeAccept` refused the acceptance before anything was written; the invitation stays pending |
|
|
216
|
+
| `INVITATION_PENDING` | 409 — a store refused a write that would make a second pending invitation for a scope and address, a concurrent `issue` won the place first; `issue` retries only while the place frees up or the invitation it replaces moved, and of concurrent issues exactly one wins and the others throw `INVITATION_PENDING` |
|
|
217
|
+
| `PASSWORD_REQUIRED` | 400 — `invitations.accept` needs a password (a new user, or an e-mail never proved) and got none; the invitation stays pending |
|
|
218
|
+
| `PASSKEY_INVALID` | 400 — a passkey registration's response does not verify (`reason` is for your logs) or its name is refused (`field: 'name'`) |
|
|
219
|
+
| `PASSKEY_TAKEN` | 409 — the credential is already registered |
|
|
220
|
+
| `PASSKEY_LIMIT` | 409 — the user holds `passkeys.maxPerUser` passkeys; `maxActive` carries the cap |
|
|
221
|
+
| `FLOW_EXPIRED`, `FLOW_MISMATCH`, `FLOW_PURPOSE_MISMATCH`, `RETURN_TO_INVALID` | 400 — a social flow that lapsed or was spent; a callback that is not the cookie's flow (also an older instance reading the six-part cookie of a flow started with `stepUp` during a rolling deploy); a flow of the other kind than the `purpose` (`'signIn'` or `'link'`) passed to `social.complete`; a `returnTo` that leaves the site. Start again |
|
|
222
|
+
| `PROVIDER_ERROR` | 502 — the social provider failed, refused or was unreachable; `reason` (`denied`, `refused`, `unreachable`) is for your logs, never a body |
|
|
223
|
+
| `MAGIC_LINK_DISABLED` | 404 — `magicLink.request`, `prepare` or `confirm` with `magicLink: { enabled: false }`; refused before any store access |
|
|
224
|
+
| `SOCIAL_PROVIDER_UNKNOWN` | 404 — a provider the user type does not configure; `provider` |
|
|
225
|
+
| `SOCIAL_STEP_UP_UNMET` | 403 — a social flow asked for a `stepUp` and the identity does not prove it (or the provider no longer supports it); the flow is spent. `provider`, `returnTo`; `reason` (`acr`, `authTime`) for your logs only |
|
|
226
|
+
| `SIGN_UP_DISABLED` | 403 — nobody holds the social account's e-mail and the type has no `social.signUp` |
|
|
227
|
+
| `EMAIL_NOT_VERIFIED_FOR_LINK`, `SOCIAL_ACCOUNT_TAKEN`, `LAST_SIGN_IN_METHOD` | 409 — an e-mail match that either side does not vouch for; an account linked to another user; an unlink that would leave no way in. `provider` |
|
|
228
|
+
|
|
229
|
+
Each code has its class, all exported: `StoreFailure`, `StoreConflict` (`on:
|
|
230
|
+
'login' | 'version'`), `NotFoundError`, `UserInvalidError`, `AvatarIdInvalidError`, `CredentialError`,
|
|
231
|
+
`UserInactiveError`, `EmailChangeNeedsProofError` (`EMAIL_CHANGE_NEEDS_PROOF`), `StepUpRequiredError`, `MailThrottledError`, `MagicLinkDisabledError` (`MAGIC_LINK_DISABLED`), `TokenError` (the `TOKEN_*` codes and `CODE_INVALID`),
|
|
232
|
+
`SecondFactorError`, `InvalidCursorError`, `CursorFilterMismatchError`, `UnsupportedError`,
|
|
233
|
+
`PermissionDepthError`, `ApiKeyLimitError`, `ApiKeyInvalidError`, `PasskeyError` (`PASSKEY_INVALID`, `PASSKEY_TAKEN`), `PasskeyLimitError` (`PASSKEY_LIMIT`) and `SocialError` (the ten social codes). `StoreFailure` and `StoreConflict` are exported
|
|
234
|
+
**because an adapter throws them**. An adapter defines no error class of its own, so `instanceof` holds
|
|
235
|
+
across the two packages.
|
|
236
|
+
|
|
237
|
+
**No message ever holds a secret** — not a password, not a hash, not a session
|
|
238
|
+
token, not a token's hash, not a challenge, a code or a TOTP secret, and not a
|
|
239
|
+
connection URI, because a connection string
|
|
240
|
+
holds a password. Nor a login: a message reports a shape, never a value, so
|
|
241
|
+
`LOGIN_TAKEN` names the login in `error.login`, not in its message.
|
|
242
|
+
|
|
243
|
+
A refusal that can only come from how you wired the library — a lifespan that is
|
|
244
|
+
not a duration, a store missing a method — throws a bare `TypeError` instead. No
|
|
245
|
+
request handler should ever answer one, so no handler needs to tell it apart.
|
|
246
|
+
|
|
247
|
+
### Subjects
|
|
248
|
+
|
|
249
|
+
```ts
|
|
250
|
+
import { type Subject, subjectOf, setOf, formatTuple, parseTuple, isSubjectSet } from '@softistx/janus';
|
|
251
|
+
|
|
252
|
+
subjectOf(user); // { type: 'staff', id: '…' }: the user IS the subject
|
|
253
|
+
setOf(user, 'managers'); // { type: 'staff', id: '…', relation: 'managers' }: everyone who manages them
|
|
254
|
+
formatTuple({
|
|
255
|
+
object: { type: 'record', id: 'r1' },
|
|
256
|
+
relation: 'members',
|
|
257
|
+
subject: { type: 'team', id: 't2', relation: 'members' },
|
|
258
|
+
});
|
|
259
|
+
// 'team:t1#members@team:t2#members'
|
|
260
|
+
parseTuple('team:t1#members@staff:u1'); // the RelationTuple back
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
`formatEntity`, `formatSubject` and `parseSubject` do the same for one part,
|
|
264
|
+
and `isSubjectSet` tells `{ type, id, relation }` from `{ type, id }` by
|
|
265
|
+
shape alone: pass a user through `subjectOf` first, so a field named
|
|
266
|
+
`relation` does not read as a set. `isSetOf` answers whether `setOf` made a
|
|
267
|
+
value — what `can()` and `grant()` read on a user type. The types are
|
|
268
|
+
`Entity`, `SubjectSet`, `Subject` (either), `SetOf` (what `setOf` answers) and
|
|
269
|
+
`RelationTuple`.
|
|
270
|
+
|
|
271
|
+
A user passed as it is, is that user, even with a field named `relation`:
|
|
272
|
+
**`setOf` is the one way to write a set on a user type** the model also
|
|
273
|
+
declares as an object type — `grant(note, 'readers', setOf(bob, 'managers'))`.
|
|
274
|
+
On an object type, `{ type, id, relation }` written out is a set too.
|
|
275
|
+
`parseSubject` and `parseTuple` answer a set as `setOf` makes it — frozen, and
|
|
276
|
+
marked — so compare a parsed set with `setOf(…)` or through `formatSubject`,
|
|
277
|
+
not with a plain `{ type, id, relation }`.
|
|
278
|
+
|
|
279
|
+
In Ory, the equality between a Kratos identity id and Keto's `subject_id` is a
|
|
280
|
+
comment and a convention, restated in three repositories and enforced nowhere.
|
|
281
|
+
Here it is a type and a one-line function — and that shared vocabulary is the
|
|
282
|
+
reason identities and permissions are one package rather than two.
|
|
283
|
+
|
|
284
|
+
**Subjects are typed**, unlike Keto's: `{ type, id }` for one entity, and
|
|
285
|
+
`{ type, id, relation }` for a subject set. One application has patients and
|
|
286
|
+
staff, and an object can hold a relation too, so a bare id does not say who.
|
|
287
|
+
`type` is the same word as a user's own.
|
|
288
|
+
|
|
289
|
+
### Ids
|
|
290
|
+
|
|
291
|
+
```ts
|
|
292
|
+
import { type Id, mintId, isId, mintedAt } from '@softistx/janus';
|
|
293
|
+
|
|
294
|
+
const id: Id = mintId(); // '0199…': a UUIDv7
|
|
295
|
+
isId(id); // true — and false for anything this package could not have minted
|
|
296
|
+
mintedAt(id); // a Date, to the millisecond
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
UUIDv7, **minted by the core and not by the store**. Ids sort in creation order
|
|
300
|
+
as strings, so the pagination cursor *is* the last id: one index, and the
|
|
301
|
+
ordering is already total. `insertUser` becomes idempotent under retry, and
|
|
302
|
+
every adapter reports the same shape. The price, stated plainly: an adapter
|
|
303
|
+
cannot reuse an existing numeric primary key.
|
|
304
|
+
|
|
305
|
+
### Pagination and time
|
|
306
|
+
|
|
307
|
+
```ts
|
|
308
|
+
import { fixedClock, parseDuration } from '@softistx/janus';
|
|
309
|
+
|
|
310
|
+
let cursor: string | null = null;
|
|
311
|
+
do {
|
|
312
|
+
const page = await auth.list({ after: cursor, limit: 100 }); // CursorPage<User>
|
|
313
|
+
cursor = page.nextCursor;
|
|
314
|
+
} while (cursor);
|
|
315
|
+
|
|
316
|
+
const clock = fixedClock(Date.UTC(2026, 0, 1)); // .now(), .advance(ms), .set(at)
|
|
317
|
+
parseDuration('8h', 'session.lifespan'); // 28800000
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
The types are `CursorPage<T>`, `Clock` and `Duration` (`'15m'`, `'8h'`, `'7d'`,
|
|
321
|
+
or milliseconds). `DEFAULT_PAGE_SIZE` (20), `MAX_PAGE_SIZE` (100), `pageLimit` and
|
|
322
|
+
`invalidCursor` are what an adapter uses to page the way the core does;
|
|
323
|
+
`systemClock` is the default `Clock`.
|
|
324
|
+
|
|
325
|
+
`CursorPage` has `items` and `nextCursor`, and **no `total`**: a count over a
|
|
326
|
+
cursor-paged collection is a second query whose answer is stale by the time you
|
|
327
|
+
read it. Where you do show a total, ask for it apart: `auth.count()`, or
|
|
328
|
+
`auth.count({ emailPrefix: 'ad' })` beside `auth.list({ emailPrefix: 'ad' })`
|
|
329
|
+
(a case-insensitive, index-backed e-mail prefix; see
|
|
330
|
+
[users](docs/guide/users.md#searching-by-e-mail-prefix)), and `namePrefix` the
|
|
331
|
+
same way for the display name
|
|
332
|
+
([users](docs/guide/users.md#searching-by-display-name)). `nextCursor` is `string | null` with no `undefined`, so `while (cursor)`
|
|
333
|
+
is the loop.
|
|
334
|
+
|
|
335
|
+
`fixedClock` is **shipped, not test-only** — testing session expiry needs it, and
|
|
336
|
+
so do your own tests.
|
|
337
|
+
|
|
338
|
+
### Background work — `background`
|
|
339
|
+
|
|
340
|
+
```ts
|
|
341
|
+
import { background } from '@softistx/janus';
|
|
342
|
+
|
|
343
|
+
const jobs = background(); // background(log) to log elsewhere than console.error
|
|
344
|
+
|
|
345
|
+
// Anti-enumeration: answer first, send the mail after, the same time either way.
|
|
346
|
+
const user = await auth.findByEmail(email);
|
|
347
|
+
if (user) jobs.run('reset mail', () => sendResetMail(user));
|
|
348
|
+
const response = new Response(null, { status: 202 });
|
|
349
|
+
|
|
350
|
+
// In a spec: wait for the mail before reading the outbox.
|
|
351
|
+
await jobs.settled();
|
|
352
|
+
```
|
|
353
|
+
|
|
354
|
+
`run(name, task)` starts the task on a later microtask and never throws: a
|
|
355
|
+
failure is logged as `reset mail failed in the background: Error: …`.
|
|
356
|
+
`settled()` resolves once nothing runs, tasks started meanwhile included. See
|
|
357
|
+
[the guide](docs/guide/vocabulary.md#background-work).
|
|
358
|
+
|
|
359
|
+
### Identities — `janus()`
|
|
360
|
+
|
|
361
|
+
```ts
|
|
362
|
+
import { z } from 'zod';
|
|
363
|
+
import { createMemoryStores, janus, scryptHasher } from '@softistx/janus';
|
|
364
|
+
|
|
365
|
+
// One user type
|
|
366
|
+
const auth = janus({
|
|
367
|
+
user: z.object({ email: z.email(), name: z.string() }),
|
|
368
|
+
password: { login: 'email' },
|
|
369
|
+
store: createMemoryStores(),
|
|
370
|
+
hasher: scryptHasher(),
|
|
371
|
+
});
|
|
372
|
+
|
|
373
|
+
await auth.signUp({ email, name, password }); // { status: 'signedIn', user, session, token }
|
|
374
|
+
await auth.signIn({ email, password }); // { status: 'signedIn', user, session, token }
|
|
375
|
+
await auth.authenticate(request); // { user, session, token, renewed } | null (a key-shaped bearer: null)
|
|
376
|
+
await auth.signOut(request);
|
|
377
|
+
await auth.verifyEmail.send(user); // { token, email, expiresAt } — sending it is yours
|
|
378
|
+
await auth.verifyEmail.confirm(token); // several types: also at the root, see Confirming a link at the root
|
|
379
|
+
await auth.verifyEmail.confirm(token, { user: session.user }); // bound to the signed-in user (see Traps): another's link is TOKEN_UNKNOWN, not spent
|
|
380
|
+
await auth.verifyEmail.confirm(token, { firstProof: true }); // the link is a first proof: drops a squatter's password and factor
|
|
381
|
+
await auth.verifyEmail.proveFirst(user); // privileged: FirstProof — { user, proved }; drops a squatter's password and factor
|
|
382
|
+
await auth.setEmailVerified(user, true); // an admin vouches for the address: the flag alone, credentials and sessions kept
|
|
383
|
+
// { token, email, expiresAt } — email is the NEW address; gate it behind a fresh sign-in
|
|
384
|
+
await auth.changeEmail.send(user, newEmail);
|
|
385
|
+
await auth.changeEmail.confirm(token); // the user, moved to the new address and verified
|
|
386
|
+
await auth.resetPassword.request(email); // … | null
|
|
387
|
+
await auth.resetPassword.confirm(token, newPassword); // several types: also at the root, see Confirming a link at the root
|
|
388
|
+
await auth.signInCode.request(email); // { code, challenge, email, expiresAt, user } | null
|
|
389
|
+
await auth.signInCode.confirm(challenge, code); // { status: 'signedIn', user, session, token }
|
|
390
|
+
await auth.magicLink.request(email); // { token, email, expiresAt, user } | null
|
|
391
|
+
await auth.magicLink.confirm(token); // { status: 'signedIn', user, session, token }
|
|
392
|
+
await auth.magicLink.prepare(email); // counted, nobody looked up: { send() } — and signInCode, resetPassword
|
|
393
|
+
await auth.findByEmail(email); // User | null — server-side only, counts nothing; every type with an e-mail
|
|
394
|
+
await auth.findOrCreate(key, () => input); // { user, created } — by login (e-mail without a password); input() only when nobody holds the key
|
|
395
|
+
await auth.signInProven(user.id); // privileged: after a proof YOUR server verified — { status: 'signedIn', … }
|
|
396
|
+
await auth.stepUp.request(user); // { via: 'email', code, challenge, email, expiresAt, user }
|
|
397
|
+
await auth.stepUp.confirm(request, challenge, code); // the request's session, authenticatedAt: now
|
|
398
|
+
|
|
399
|
+
// Several user types
|
|
400
|
+
const clinic = janus({
|
|
401
|
+
users: {
|
|
402
|
+
patient: { schema: Patient, password: { login: 'email' } },
|
|
403
|
+
staff: {
|
|
404
|
+
schema: Staff,
|
|
405
|
+
password: { login: 'username' },
|
|
406
|
+
session: { lifespan: '8h', renewAfter: false },
|
|
407
|
+
},
|
|
408
|
+
},
|
|
409
|
+
store,
|
|
410
|
+
hasher,
|
|
411
|
+
});
|
|
412
|
+
|
|
413
|
+
await clinic.staff.signIn({ username, password });
|
|
414
|
+
const current = await clinic.authenticate(request);
|
|
415
|
+
if (current?.user.type === 'staff') current.user.service; // narrowed by type
|
|
416
|
+
await clinic.authenticate(request, { type: 'staff' }); // a patient's session → null
|
|
417
|
+
|
|
418
|
+
// Several users by id, in one query: a 100-row staff list, one round trip
|
|
419
|
+
const members = await clinic.staff.findMany(rows.map((row) => row.staffId));
|
|
420
|
+
const byId = new Map(members.map((member) => [member.id, member]));
|
|
421
|
+
const shown = rows.map((row) => ({ ...row, active: byId.get(row.staffId)?.active ?? false }));
|
|
422
|
+
```
|
|
423
|
+
|
|
424
|
+
`janus()` assembles **synchronously and with no I/O**: it checks that every
|
|
425
|
+
store answers every method of the port, and connects to nothing. Everything
|
|
426
|
+
else reaches the store and is asynchronous.
|
|
427
|
+
|
|
428
|
+
- **A user is your schema's fields, at the top level**, plus what `janus` sets:
|
|
429
|
+
`id`, `type`, `emailVerified`, `active`, `hasPassword`, `hasSecondFactor`,
|
|
430
|
+
`avatar`, `version`, `createdAt`, `updatedAt`. A schema declaring one of those, or a `password`, is
|
|
431
|
+
refused at compile time. The password hash never reaches a user.
|
|
432
|
+
`avatar` is `{ id, updatedAt } | null`: janus keeps only the opaque `id` your
|
|
433
|
+
application chose, and the image itself lives in your own storage; write it
|
|
434
|
+
with [`avatar.set`](#avatars--avatar).
|
|
435
|
+
- **Schemas** are any [Standard Schema](https://standardschema.dev) — Zod 4,
|
|
436
|
+
Valibot, ArkType. There is no validation peer. The output must be JSON, and a
|
|
437
|
+
schema producing a `Date` is refused at compile time.
|
|
438
|
+
- **Several user types** live in one instance: `auth.patient.*`, `auth.staff.*`,
|
|
439
|
+
and one `authenticate` whose answer is a union narrowed by `user.type`. A
|
|
440
|
+
login is unique **per type**: the same e-mail may hold a patient user and a
|
|
441
|
+
staff user.
|
|
442
|
+
- **`password.login`** names a top-level, required string field. A typo is a
|
|
443
|
+
compile error on `login`, and the message lists the fields you could have
|
|
444
|
+
meant. It is normalised with `'lowercaseTrim'` unless you say otherwise.
|
|
445
|
+
- **`email`** defaults to the field named `email`. A type without one has no
|
|
446
|
+
`findByEmail`, no `verifyEmail`, no `resetPassword`, no `signInCode` and
|
|
447
|
+
no `magicLink` and no `changeEmail` — they are absent from its type, not
|
|
448
|
+
failing at run time. Changing the e-mail with `update` sets `emailVerified`
|
|
449
|
+
back to `false` — and refuses with `EMAIL_CHANGE_NEEDS_PROOF` for a user who
|
|
450
|
+
holds a second factor or a passkey; to move a user to an address they have proved, use
|
|
451
|
+
[`changeEmail`](#changing-an-e-mail--changeemail).
|
|
452
|
+
- **Per type**: `create`, `find` (or `null`), `findMany`, `get` (or
|
|
453
|
+
`NOT_FOUND`), `list`, `update(user, patch)` — merged over the stored fields,
|
|
454
|
+
then validated whole — `setActive`, `delete` and `signInProven` (below);
|
|
455
|
+
with an e-mail, `findByEmail` (below), password or not; with a password,
|
|
456
|
+
`signUp`, `signIn`, `findByLogin`, `setPassword` and `changePassword`.
|
|
457
|
+
Every write but `delete` takes an optional `ifVersion`.
|
|
458
|
+
- **`findMany(ids)`** answers the type's users **in the order the ids were
|
|
459
|
+
given**, each once — a repeated id at its first place. An id `find` answers
|
|
460
|
+
`null` for — malformed, unknown, another type's — is **left out**, so match
|
|
461
|
+
by `user.id`, never by position. `[]` answers `[]` without reaching the
|
|
462
|
+
store; a long list is read 100 ids per query. One query when the users store
|
|
463
|
+
implements the optional `findUsers` (the reference store, `janus-drizzle`,
|
|
464
|
+
`janus-mongo`); otherwise `findUser`, ten at a time
|
|
465
|
+
([users](docs/guide/users.md#several-users-at-once--findmany)).
|
|
466
|
+
- **`delete(user)`** deletes the user together with every session and one-time
|
|
467
|
+
token they had, so nothing of theirs is kept: a token holds the e-mail it was
|
|
468
|
+
sent to. The user goes first, so an outage half-way leaves only sessions and
|
|
469
|
+
tokens that authenticate nobody. It is idempotent, and calling it again
|
|
470
|
+
finishes the job. It answers `false` for an unknown id, or for one of another
|
|
471
|
+
type, and leaves that user untouched.
|
|
472
|
+
- **Shared**: `authenticate`, `signOut`, `signOutEverywhere(user, { except, issuedBefore })`, `sessions.list(user)` and `sessions.revoke(user, sessionId)` ([guide](docs/guide/sessions.md#listing-and-revoking-one-users-sessions--authsessions)), with `{ deviceLabel }` on any sign-in
|
|
473
|
+
(`issuedBefore` ends only the sessions created **strictly before** that
|
|
474
|
+
`Date`: one opened at that very millisecond stands, and anything but a valid
|
|
475
|
+
`Date` throws a `TypeError`),
|
|
476
|
+
`findUser` and `getUser` across types, `cookie.serialize(token, session)` and
|
|
477
|
+
`cookie.clear()` — `HttpOnly; SameSite=Lax; Secure` unless you say otherwise
|
|
478
|
+
— and `collectExpired`, which deletes lapsed sessions and lapsed one-time
|
|
479
|
+
tokens.
|
|
480
|
+
- **Password guessing is throttled**, on by default: past ten passwords
|
|
481
|
+
tried at one login in a 15-minute window, `signIn` refuses every one — the
|
|
482
|
+
right password included — with `CREDENTIALS_INVALID`, `reason:
|
|
483
|
+
'throttled'` and `retryAfter`, the seconds until the next window. Nothing
|
|
484
|
+
locks, a login nobody holds is counted alike, and a password sign-in that
|
|
485
|
+
opens a session — after its second factor, when one is active — starts
|
|
486
|
+
the count again. `changePassword` counts in the same budget: a wrong
|
|
487
|
+
`current` is one more password tried at the login, and past the limit it
|
|
488
|
+
is refused alike, with `retryAfter`. `signIn: { throttle: { attempts, window } }`
|
|
489
|
+
changes it, `signIn: { throttle: false }` turns it off; a store that
|
|
490
|
+
cannot count throws `STORE_FAILED`
|
|
491
|
+
([passwords](docs/guide/passwords.md#password-guessing-is-throttled)).
|
|
492
|
+
|
|
493
|
+
```ts
|
|
494
|
+
janus({ user, password: { login: 'email' }, store, hasher, signIn: { throttle: { attempts: 5, window: '1h' } } });
|
|
495
|
+
```
|
|
496
|
+
- **Requests that send e-mail are throttled**, on by default: past five
|
|
497
|
+
e-mails asked in a 10-minute window, a request refuses with
|
|
498
|
+
`MailThrottledError` (`MAIL_THROTTLED`, 429) and `retryAfter`, and issues,
|
|
499
|
+
spends and rotates nothing: the last link or code sent still works.
|
|
500
|
+
**Each flow counts on its own**: per address for
|
|
501
|
+
`magicLink.request`, `signInCode.request` and `resetPassword.request` — an
|
|
502
|
+
address nobody holds is counted and refused alike — and per user for
|
|
503
|
+
`verifyEmail.send`, `changeEmail.send` (and, for its new address, per
|
|
504
|
+
address too) and for `stepUp.request` when it e-mails a code.
|
|
505
|
+
`prepare` counts as `request` does, in the same window
|
|
506
|
+
([requests in two steps](#requests-in-two-steps--prepare)).
|
|
507
|
+
`mail: { throttle: { attempts, window } }` changes it, `mail: { throttle:
|
|
508
|
+
false }` turns it off; a store that cannot count throws `STORE_FAILED` and
|
|
509
|
+
nothing is issued
|
|
510
|
+
([e-mail flows](docs/guide/email-flows.md#requests-that-send-e-mail-are-throttled)).
|
|
511
|
+
|
|
512
|
+
```ts
|
|
513
|
+
janus({ user, store, mail: { throttle: { attempts: 3, window: '1h' } } });
|
|
514
|
+
```
|
|
515
|
+
- **Sessions** last `'7d'` and slide: `authenticate` renews one once `renewAfter`
|
|
516
|
+
(`'1d'`) has passed, writing at most once per period, and says so with
|
|
517
|
+
`renewed`. The token is handed back once; the store only holds its `sha256`.
|
|
518
|
+
`session: { absolute: '30d' }` adds a cap from sign-in that no use extends
|
|
519
|
+
([sessions](docs/guide/sessions.md#an-absolute-cap)).
|
|
520
|
+
|
|
521
|
+
**Hashers.** `scryptHasher()` runs on Node and on Bun, with no dependency and
|
|
522
|
+
OWASP's parameters (N = 2^17, r = 8, p = 1). `bunHasher()` is argon2id through
|
|
523
|
+
`Bun.password`, on Bun only. Each hasher caps how many hashes and verifies run at
|
|
524
|
+
once, because every call holds memory (about 128 MiB for scrypt, 64 MiB for
|
|
525
|
+
argon2id): `{ concurrency }` defaults to 2 for `scryptHasher()` and 4 for
|
|
526
|
+
`bunHasher()`, and calls past the cap wait their turn. There is no silent
|
|
527
|
+
fallback: a user type with a password and no `hasher` is refused at wiring. Hashes describe themselves
|
|
528
|
+
(`$scrypt$ln=17,r=8,p=1$…`, `$argon2id$…`). Wire the hashers a database was
|
|
529
|
+
written with as `verifiers`, and every one of them can verify while exactly one
|
|
530
|
+
hashes.
|
|
531
|
+
|
|
532
|
+
**Rehash on sign-in.** When a password matches a stale hash, `signIn` rewrites
|
|
533
|
+
it with `hasher`. A hash is stale when a `verifiers` hasher wrote it, or when
|
|
534
|
+
`hasher` wrote it with other parameters than it uses now: a raised scrypt
|
|
535
|
+
`cost`, or argon2id parameters other than the pinned `m=65536,t=2,p=1`. Moving
|
|
536
|
+
off a hasher, or raising its cost, therefore reaches every active user with no
|
|
537
|
+
migration to run. The password's `updatedAt` is kept, since the password did not
|
|
538
|
+
change; the user's `version` moves. The write happens only at the version just
|
|
539
|
+
read. If a concurrent update wins, the sign-in still succeeds and the next
|
|
540
|
+
sign-in tries again. An outage on that write still fails the sign-in.
|
|
541
|
+
|
|
542
|
+
**The port.** `JanusStores` is three stores — `UserStore`, `SessionStore`,
|
|
543
|
+
`TokenStore`, whose records are `UserRecord`, `SessionRecord` and
|
|
544
|
+
`TokenRecord` — in the slots `users`, `sessions`, `tokens`,
|
|
545
|
+
cut where atomicity is not required, so sessions can live in Redis while users
|
|
546
|
+
live in MongoDB. `createMemoryStores()` is the reference implementation. It is
|
|
547
|
+
shipped for your own tests, and it is what to compare against when writing an
|
|
548
|
+
adapter. `assertStores(store, where)` is the check `janus()` runs on it, for an
|
|
549
|
+
adapter that wants to fail as early. The six rules an adapter keeps are
|
|
550
|
+
written on the port's types.
|
|
551
|
+
|
|
552
|
+
**An optional fourth slot, `socialLinks`.** `JanusStores.socialLinks?` is a
|
|
553
|
+
`SocialLinkStore` — the accounts a user has linked to an external provider,
|
|
554
|
+
a `SocialLinkRecord` each: `{ provider, accountId, userId, email, createdAt }`.
|
|
555
|
+
It is new in 0.38 and **optional**: an adapter that does not write it still
|
|
556
|
+
compiles, and `assertStores` checks it only when it is there. The pair
|
|
557
|
+
`(provider, accountId)` is unique and compared byte for byte, so `insertSocialLink` is
|
|
558
|
+
one atomic insert-if-absent that answers the stored record — its own, or the
|
|
559
|
+
holder's when the pair was already linked, in which case nothing is written;
|
|
560
|
+
`deleteSocialLink` is conditional on the owner. Deleting a user deletes their
|
|
561
|
+
links (`deleteUserSocialLinks`) after their API keys. `createMemoryStores()`
|
|
562
|
+
provides the slot; the Mongo and Drizzle adapters wire it too.
|
|
563
|
+
|
|
564
|
+
**An optional fifth slot, `passkeys`.** `JanusStores.passkeys?` is a
|
|
565
|
+
`PasskeyStore` — the WebAuthn credentials a user registered, a `PasskeyRecord`
|
|
566
|
+
each: `{ credentialId, userId, publicKey, counter, transports, aaguid,
|
|
567
|
+
backupEligible, backedUp, name, createdAt, lastUsedAt }`. `credentialId` is
|
|
568
|
+
unique and compared byte for byte, so `insertPasskey` is one atomic
|
|
569
|
+
insert-if-absent that answers the stored record (the holder's when the
|
|
570
|
+
credential was already registered); `publicKey` (COSE, base64url) round-trips
|
|
571
|
+
byte for byte. `recordPasskeyUse(userId, credentialId, { counter, backedUp,
|
|
572
|
+
lastUsedAt }, ifCounter)` is one conditional write: it answers the updated
|
|
573
|
+
record, or `null` when the counter is no longer `ifCounter` (so two concurrent
|
|
574
|
+
uses cannot both pass), the passkey is another user's, or there is none.
|
|
575
|
+
`renamePasskey` and `deletePasskey` are conditional on the owner and answer
|
|
576
|
+
`true` or `false`. Deleting a user deletes their passkeys
|
|
577
|
+
(`deleteUserPasskeys`). `createMemoryStores()` provides the slot; the flows that
|
|
578
|
+
use it are [`auth.passkeys`](#passkeys-as-a-second-factor-or-the-first).
|
|
579
|
+
|
|
580
|
+
**The `PasskeyVerifier` port.** The core does no WebAuthn: it makes and stores
|
|
581
|
+
the challenge, and calls a `PasskeyVerifier` for the rest —
|
|
582
|
+
`registrationOptions` and `authenticationOptions` shape the JSON the browser
|
|
583
|
+
needs, `verifyRegistration` and `verifyAuthentication` check what it answered.
|
|
584
|
+
**A refusal is an answer, a failure throws**: a response that does not verify
|
|
585
|
+
is `{ ok: false, reason }` with `reason` one of `malformed`, `challenge`,
|
|
586
|
+
`origin`, `rpId`, `userVerification`, `signature`, `counterRegression` (the
|
|
587
|
+
counter went backwards; a counter of `0` is never one) or `unsupported`; only
|
|
588
|
+
an unexpected failure of the library or the infrastructure throws, and the
|
|
589
|
+
core lets it propagate. Success is `PasskeyRegistration` (the fields of a
|
|
590
|
+
`PasskeyRecord`) or `PasskeyAssertion` (`counter`, `backedUp`,
|
|
591
|
+
`userVerified`). `@softistx/janus-passkeys` implements it on
|
|
592
|
+
`@simplewebauthn/server`; so can your own code.
|
|
593
|
+
|
|
594
|
+
The port holds what one-time codes need: a user's `secondFactor` (a TOTP
|
|
595
|
+
secret the core seals before a store sees it, or `null`), a token's
|
|
596
|
+
`codeHash` and `attempts`, and `TokenStore.countAttempt`, which counts one
|
|
597
|
+
attempt in one conditional write:
|
|
598
|
+
|
|
599
|
+
```ts
|
|
600
|
+
import { createMemoryStores, mintId } from '@softistx/janus';
|
|
601
|
+
|
|
602
|
+
const { tokens } = createMemoryStores();
|
|
603
|
+
const tokenHash = 'a'.repeat(64); // the core stores sha256 of the secret
|
|
604
|
+
await tokens.insertToken({
|
|
605
|
+
tokenHash,
|
|
606
|
+
kind: 'signInCode',
|
|
607
|
+
userId: mintId(),
|
|
608
|
+
address: 'ada@example.test',
|
|
609
|
+
codeHash: 'c'.repeat(64),
|
|
610
|
+
attempts: 0,
|
|
611
|
+
expiresAt: new Date(Date.now() + 10 * 60_000),
|
|
612
|
+
spentAt: null,
|
|
613
|
+
createdAt: new Date(),
|
|
614
|
+
});
|
|
615
|
+
|
|
616
|
+
await tokens.countAttempt(tokenHash, 'signInCode'); // { …, attempts: 1 }
|
|
617
|
+
await tokens.countAttempt(tokenHash, 'verifyEmail'); // null: no token of that kind
|
|
618
|
+
```
|
|
619
|
+
|
|
620
|
+
`spendUserTokens(userId, kind, at, except?)` spends the unspent tokens of one
|
|
621
|
+
user and one kind — but the one whose hash is `except` — and answers how many:
|
|
622
|
+
what issuing a sign-in code and writing a password call:
|
|
623
|
+
|
|
624
|
+
```ts
|
|
625
|
+
const userId = mintId();
|
|
626
|
+
const now = new Date();
|
|
627
|
+
const code = (tokenHash: string) => ({
|
|
628
|
+
tokenHash,
|
|
629
|
+
kind: 'signInCode' as const,
|
|
630
|
+
userId,
|
|
631
|
+
address: 'ada@example.test',
|
|
632
|
+
codeHash: 'c'.repeat(64),
|
|
633
|
+
attempts: 0,
|
|
634
|
+
expiresAt: new Date(now.getTime() + 10 * 60_000),
|
|
635
|
+
spentAt: null,
|
|
636
|
+
createdAt: now,
|
|
637
|
+
});
|
|
638
|
+
const kept = code('d'.repeat(64));
|
|
639
|
+
await tokens.insertToken(kept);
|
|
640
|
+
await tokens.insertToken(code('e'.repeat(64)));
|
|
641
|
+
await tokens.spendUserTokens(userId, 'signInCode', now, kept.tokenHash); // 1: the other one
|
|
642
|
+
await tokens.spendUserTokens(userId, 'signInCode', now); // 1: `kept`, now
|
|
643
|
+
await tokens.spendUserTokens(userId, 'signInCode', now); // 0: none left unspent
|
|
644
|
+
```
|
|
645
|
+
|
|
646
|
+
`session.amr` lists the RFC 8176 methods a session proved (`pwd`, `otp`,
|
|
647
|
+
`hwk` + `user`, `fed`, `mfa`), extended by each step-up; `authenticatedAt` is
|
|
648
|
+
the last proof. `AMR` is the mapping and `isMultiFactor(session)` answers
|
|
649
|
+
whether more than one factor was proved ([guide](docs/guide/sessions.md#what-the-session-proved--amr)):
|
|
650
|
+
|
|
651
|
+
```ts
|
|
652
|
+
import { isMultiFactor } from '@softistx/janus';
|
|
653
|
+
|
|
654
|
+
const current = await auth.authenticate(request);
|
|
655
|
+
current?.session.amr; // ['pwd', 'otp', 'mfa']
|
|
656
|
+
current && isMultiFactor(current.session); // true
|
|
657
|
+
```
|
|
658
|
+
|
|
659
|
+
`reauthenticateSession(id, at, amr?)` moves a standing session's `authenticatedAt`
|
|
660
|
+
— what a step-up writes once a signed-in user proved again who they are —
|
|
661
|
+
and, when `amr` is given, replaces the session's `amr` (the RFC 8176 methods
|
|
662
|
+
proved, [`session.amr`](docs/guide/sessions.md#what-the-session-proved--amr)),
|
|
663
|
+
and answers `null` for a revoked one, which it never brings back:
|
|
664
|
+
|
|
665
|
+
```ts
|
|
666
|
+
const { sessions } = createMemoryStores();
|
|
667
|
+
const session = {
|
|
668
|
+
id: mintId(),
|
|
669
|
+
tokenHash: 'f'.repeat(64),
|
|
670
|
+
userId: mintId(),
|
|
671
|
+
authenticatedAt: new Date('2026-01-01T00:00:00.000Z'),
|
|
672
|
+
expiresAt: new Date(Date.now() + 86_400_000),
|
|
673
|
+
revokedAt: null,
|
|
674
|
+
createdAt: new Date('2026-01-01T00:00:00.000Z'),
|
|
675
|
+
};
|
|
676
|
+
await sessions.insertSession(session);
|
|
677
|
+
await sessions.reauthenticateSession(session.id, new Date()); // { …, authenticatedAt: now }
|
|
678
|
+
```
|
|
679
|
+
|
|
680
|
+
A token of kind `stepUp` is that confirmation's challenge: kept apart from
|
|
681
|
+
`signInCode`, so neither is ever redeemed as the other. A token of kind
|
|
682
|
+
`magicLink`, new in 0.15, is a sign-in link's, kept apart from `signInCode`
|
|
683
|
+
the same way: a sign-in code's challenge is held by whoever asked for it,
|
|
684
|
+
and must never sign anyone in as a link. A store that lists the kinds — a
|
|
685
|
+
`CHECK`, a validator's enum — adds `magicLink`. A token of kind
|
|
686
|
+
`changeEmail`, new in 0.23, is the link sent to a user's new address: its
|
|
687
|
+
`address` is that new address and its `codeHash` the address it replaces,
|
|
688
|
+
kept apart from `verifyEmail` so neither is redeemed as the other. The same
|
|
689
|
+
store adds `changeEmail`. A token of kind `socialFlow`, new in 0.38, is the
|
|
690
|
+
state of a social sign-in or link between the redirect to the provider and its
|
|
691
|
+
callback: its `address` is `''` and its `codeHash` the keyed hash that binds the
|
|
692
|
+
flow cookie's contents. The same stores add `socialFlow`. A token of kind
|
|
693
|
+
`passkeyRegistration` is the challenge of one passkey registration in progress;
|
|
694
|
+
the same stores add it. A store that lists kinds (a `CHECK`, an enum) must
|
|
695
|
+
accept each new kind **before** the version that writes it is deployed.
|
|
696
|
+
|
|
697
|
+
An adapter written against `@softistx/janus` 0.3 does not compile against this
|
|
698
|
+
port until it implements `countAttempt`, nor one written against 0.6 until it
|
|
699
|
+
implements `spendUserTokens`, nor one written against 0.11 until it
|
|
700
|
+
implements `reauthenticateSession`, and `janus()` refuses each at wiring —
|
|
701
|
+
[Writing an adapter](docs/guide/adapters.md) has the contracts:
|
|
702
|
+
[`countAttempt`](docs/guide/adapters.md#tokenstorecountattempt),
|
|
703
|
+
[`spendUserTokens`](docs/guide/adapters.md#tokenstorespendusertokens) and
|
|
704
|
+
[`reauthenticateSession`](docs/guide/adapters.md#sessionstorereauthenticatesession).
|
|
705
|
+
A store that lists the token kinds — a `CHECK`, a validator's enum — adds
|
|
706
|
+
`stepUp`.
|
|
707
|
+
|
|
708
|
+
### Several issuers — `createJanusIssuers`
|
|
709
|
+
|
|
710
|
+
One process, several tenants: a bounded in-process cache of `janus()` instances,
|
|
711
|
+
one per issuer, chosen per request. It builds each instance once (concurrent
|
|
712
|
+
first requests share the build), rebuilds it when `resolve` answers a new
|
|
713
|
+
`version`, and drops the least recently used past `cache.max`.
|
|
714
|
+
|
|
715
|
+
```ts
|
|
716
|
+
import { createJanusIssuers, janus } from '@softistx/janus';
|
|
717
|
+
|
|
718
|
+
const issuers = createJanusIssuers({
|
|
719
|
+
resolve: (request) => tenants.byHost(new URL(request.url).host), // { issuer, version } | null
|
|
720
|
+
build: (tenant) => janus({ user, store: stores.for(tenant.issuer), hasher }),
|
|
721
|
+
cache: { max: 100, idle: '1h' }, // the defaults
|
|
722
|
+
});
|
|
723
|
+
|
|
724
|
+
const auth = await issuers.forRequest(request); // the built instance, typed; null: no such issuer
|
|
725
|
+
issuers.evict('acme'); // the next request builds it again
|
|
726
|
+
```
|
|
727
|
+
|
|
728
|
+
A failing `resolve` or `build` rejects and is never read as `null`. See
|
|
729
|
+
[Several issuers](docs/guide/issuers.md).
|
|
730
|
+
|
|
731
|
+
### Second factor — `secondFactor`
|
|
732
|
+
|
|
733
|
+
```ts
|
|
734
|
+
import { z } from 'zod';
|
|
735
|
+
import { createMemoryStores, janus, scryptHasher } from '@softistx/janus';
|
|
736
|
+
|
|
737
|
+
const auth = janus({
|
|
738
|
+
user: z.object({ email: z.email() }),
|
|
739
|
+
password: { login: 'email' },
|
|
740
|
+
store: createMemoryStores(),
|
|
741
|
+
hasher: scryptHasher(),
|
|
742
|
+
secondFactor: {
|
|
743
|
+
issuer: 'Example', // shown in the authenticator app
|
|
744
|
+
keys: [{ id: '2026-09', key: process.env.TOTP_KEY ?? '' }], // openssl rand -base64 32
|
|
745
|
+
},
|
|
746
|
+
});
|
|
747
|
+
|
|
748
|
+
const { secret, uri } = await auth.secondFactor.enroll(user); // show uri as a QR code, secret beside it
|
|
749
|
+
const { recoveryCodes } = await auth.secondFactor.activate(user, code); // the first code: the factor is active
|
|
750
|
+
// recoveryCodes: ten, 'xxxxx-xxxxx' — show them now, no call answers them again
|
|
751
|
+
|
|
752
|
+
const result = await auth.signIn({ email, password });
|
|
753
|
+
if (result.status === 'secondFactor') {
|
|
754
|
+
// no session yet: keep result.challenge for the next request — never in a URL or a log
|
|
755
|
+
const signedIn = await auth.secondFactor.confirm(result.challenge, code); // { status: 'signedIn', … }
|
|
756
|
+
// phone gone? a recovery code instead, spent once:
|
|
757
|
+
// await auth.secondFactor.recover(result.challenge, recoveryCode) // { …, recoveryCodesLeft: 9 }
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
await auth.secondFactor.recoveryCodesLeft(user); // 9, or null without an active factor
|
|
761
|
+
await auth.secondFactor.regenerateRecoveryCodes(user, code); // { user, recoveryCodes }: ten new, the old ones end
|
|
762
|
+
await auth.secondFactor.spendRecoveryCode(user, recoveryCode); // { user, recoveryCodesLeft }: no session, no event, same attempts
|
|
763
|
+
await auth.secondFactor.reseal({ batch: 100, after: null }); // after a key rotation: { scanned, resealed, current, skipped, unreadable, nextCursor }
|
|
764
|
+
await auth.secondFactor.disable(user); // the factor and its recovery codes
|
|
765
|
+
```
|
|
766
|
+
|
|
767
|
+
A TOTP second factor — the six-digit codes of any authenticator app — for
|
|
768
|
+
every user type with a password, and every passwordless type with an e-mail. A challenge takes five codes, and an account ten per 15 minutes across all its challenges (`secondFactor: { throttle: { attempts, window } }`, `false` to turn it off; [guide](docs/guide/second-factor.md#attempts)).
|
|
769
|
+
|
|
770
|
+
The `secondFactor.throttle` window is separate from the one `regenerateRecoveryCodes` counts in (shared with an app-code `stepUp.confirm`): neither spends the other's attempts.
|
|
771
|
+
|
|
772
|
+
Keeping the keys in one variable (`"id:key,id:key"`)? `parseSealingKeys(process.env.TOTP_KEYS ?? '', { refuse: ['dev'], where: 'TOTP_KEYS' })` (`where` names the variable in a refusal) returns the `keys`, first seals, every one opens, and refuses a malformed list or a named development key ([guide](docs/guide/second-factor.md#keeping-the-list-in-one-variable)).
|
|
773
|
+
|
|
774
|
+
Sealing a secret of your own with the same keys? `sealerFor(keys, 'integration-keys')` returns `{ seal(id, plaintext), unseal(id, sealed), sealWith, needsReseal(sealed) }` with a key derived for that purpose, so it never shares one with the second factor; `unseal` answers `null` on any failure ([guide](docs/guide/second-factor.md#sealing-your-own-secrets-sealerfor)).
|
|
775
|
+
|
|
776
|
+
- **`signIn` answers a union once `secondFactor` is configured**:
|
|
777
|
+
`{ status: 'signedIn', user, session, token }`, or
|
|
778
|
+
`{ status: 'secondFactor', challenge, expiresAt, userId }` for a user whose factor
|
|
779
|
+
is active. Switch on `status`: reading `token` before that is a compile
|
|
780
|
+
error. Without `secondFactor`, `signIn` answers a session, as before.
|
|
781
|
+
- **A factor is enrolled, then active.** `enroll` answers the secret and its
|
|
782
|
+
`otpauth://` URI once; enrolling again replaces a factor still waiting.
|
|
783
|
+
`activate` checks a first code, and only then does `signIn` ask for one —
|
|
784
|
+
`hasSecondFactor` says so.
|
|
785
|
+
- **`confirm(challenge, code)`** opens the session. A challenge lives `'5m'`
|
|
786
|
+
(`secondFactor.challenge`) and takes five attempts: a wrong code is
|
|
787
|
+
`CODE_INVALID` with `attemptsLeft`, and the fifth spends the challenge. A
|
|
788
|
+
code is accepted once, so a replay is `CODE_INVALID` too.
|
|
789
|
+
- **Recovery codes, for a lost phone.** `activate` answers a
|
|
790
|
+
`RecoveryCodesIssued` — `{ user, recoveryCodes }`, ten single-use codes,
|
|
791
|
+
shown once, stored only as keyed hashes. `recover(challenge, code)` redeems a
|
|
792
|
+
sign-in's challenge with one instead of the app's code, sharing its five
|
|
793
|
+
attempts, and answers a `RecoveredSignIn`: the session with
|
|
794
|
+
`recoveryCodesLeft`. `recoveryCodesLeft(user)` reads that count again —
|
|
795
|
+
for a `user.recoveryCodeUsed` listener, which has the id only — and
|
|
796
|
+
answers `null` for a user with no active factor.
|
|
797
|
+
`regenerateRecoveryCodes(user, code)` replaces them all,
|
|
798
|
+
on a fresh code from the app, and answers a `RecoveryCodesIssued` too;
|
|
799
|
+
`disable` removes them. `regenerateRecoveryCodes` takes five attempts per user per 15-minute
|
|
800
|
+
window, counted by the store: a wrong code is `CODE_INVALID` with
|
|
801
|
+
`attemptsLeft`, and past the fifth every call is refused until the next
|
|
802
|
+
window, with `reason: 'throttled'` and `retryAfter`, the seconds until it
|
|
803
|
+
frees (`stepUp.confirm` with an app's code shares the window).
|
|
804
|
+
`spendRecoveryCode(user, code)` spends one outside a sign-in — to turn the
|
|
805
|
+
factor off from a standing session — and answers
|
|
806
|
+
`{ user, recoveryCodesLeft }`: no session, no event, the same five
|
|
807
|
+
attempts per window as `regenerateRecoveryCodes`.
|
|
808
|
+
- **`keys` seal every TOTP secret** with AES-256-GCM before a store sees it,
|
|
809
|
+
and key the recovery codes' hashes. The first seals and every key opens, so
|
|
810
|
+
keys rotate: put the new one first, keep the old one until no secret is
|
|
811
|
+
sealed and no recovery code hashed with it.
|
|
812
|
+
- **The first proof of an e-mail by a sign-in code or link removes the
|
|
813
|
+
factor too**, active or waiting, with its recovery codes: whoever enrolled
|
|
814
|
+
it had not proved the address. Send `verifyEmail` before offering
|
|
815
|
+
`enroll`, and an owner's factor is never dropped this way.
|
|
816
|
+
- **Asking for a password or a code before `enroll`, `disable` or
|
|
817
|
+
`regenerateRecoveryCodes` is your policy**, not the library's — a recent
|
|
818
|
+
`session.authenticatedAt` is one rule. `regenerateRecoveryCodes` asks for
|
|
819
|
+
the app's code itself.
|
|
820
|
+
|
|
821
|
+
[The second factor guide](docs/guide/second-factor.md) has every option,
|
|
822
|
+
error and state, recovery codes, key rotation, and sign-in routes with the
|
|
823
|
+
challenge in a cookie.
|
|
824
|
+
|
|
825
|
+
### Sign-in codes — `signInCode`
|
|
826
|
+
|
|
827
|
+
```ts
|
|
828
|
+
import { z } from 'zod';
|
|
829
|
+
import { createMemoryStores, janus } from '@softistx/janus';
|
|
830
|
+
|
|
831
|
+
const auth = janus({
|
|
832
|
+
user: z.object({ email: z.email(), name: z.string() }), // no password: codes only
|
|
833
|
+
store: createMemoryStores(),
|
|
834
|
+
});
|
|
835
|
+
|
|
836
|
+
const issued = await auth.signInCode.request(email); // null for nobody, or an inactive user
|
|
837
|
+
if (issued !== null) {
|
|
838
|
+
await sendMail(issued.email, `Your sign-in code: ${issued.code}`); // the code, and only the code
|
|
839
|
+
}
|
|
840
|
+
// answer the same page either way; keep issued.challenge with the visitor — a cookie, never a URL
|
|
841
|
+
|
|
842
|
+
const signedIn = await auth.signInCode.confirm(challenge, code); // { status: 'signedIn', user, session, token }
|
|
843
|
+
```
|
|
844
|
+
|
|
845
|
+
A six-digit code sent to the user's e-mail signs them in, with no password.
|
|
846
|
+
|
|
847
|
+
- **On every user type with an e-mail**, with a password or without one. A
|
|
848
|
+
type with no password signs in by code alone; a type with no e-mail has no
|
|
849
|
+
`signInCode` at all.
|
|
850
|
+
- **`request(email)` answers `null`** when nobody of this type holds that
|
|
851
|
+
e-mail, or the user is inactive — never say which. It answers the `code`
|
|
852
|
+
for the e-mail and the `challenge` for the visitor; the code's hash is
|
|
853
|
+
stored, keyed by the challenge.
|
|
854
|
+
- **`confirm(challenge, code)`** marks the e-mail verified and opens the
|
|
855
|
+
session. A challenge lives `'10m'` (`tokens.signInCode`) and takes five
|
|
856
|
+
attempts: a wrong code is `CODE_INVALID` with `attemptsLeft`, and the fifth
|
|
857
|
+
spends it. An e-mail changed since is `TOKEN_STALE`; a user deactivated
|
|
858
|
+
since is `USER_INACTIVE`.
|
|
859
|
+
- **An e-mail proved for the first time drops the password and the second
|
|
860
|
+
factor, signs out every session and revokes every API key** before the new one opens, as
|
|
861
|
+
`resetPassword.confirm` does for the password: whoever registered the
|
|
862
|
+
address without holding its inbox keeps nothing, and the owner is asked
|
|
863
|
+
for no factor they never set. `user.passwordChanged` follows
|
|
864
|
+
`user.emailVerified` when a password was dropped, then
|
|
865
|
+
`user.secondFactorDisabled` when an active factor was. An e-mail already
|
|
866
|
+
verified changes nothing.
|
|
867
|
+
- **An active second factor is still asked for** on an e-mail already
|
|
868
|
+
verified: with `secondFactor` configured, `confirm` answers `SignInResult`
|
|
869
|
+
on a type with a password or an e-mail, and a user whose factor is active gets a
|
|
870
|
+
challenge for `secondFactor.confirm` — switch on `status`, as after
|
|
871
|
+
`signIn`.
|
|
872
|
+
|
|
873
|
+
[The sign-in code guide](docs/guide/sign-in-code.md) has the request that
|
|
874
|
+
tells nobody who exists, the challenge in a cookie, every error, and a test.
|
|
875
|
+
|
|
876
|
+
### Sign-in links — `magicLink`
|
|
877
|
+
|
|
878
|
+
```ts
|
|
879
|
+
const issued = await auth.magicLink.request(email); // null for nobody, or an inactive user
|
|
880
|
+
if (issued !== null) {
|
|
881
|
+
const link = `https://app.example/sign-in/link?token=${issued.token}`; // a page of yours
|
|
882
|
+
await sendMail(issued.email, `Sign in: ${link}`); // the token in the e-mail, and nowhere else
|
|
883
|
+
}
|
|
884
|
+
// answer the same page either way: nothing reaches the visitor, so there is nothing to forge
|
|
885
|
+
|
|
886
|
+
// the page's button POSTs the token back — never confirm on the link's GET
|
|
887
|
+
const signedIn = await auth.magicLink.confirm(token); // { status: 'signedIn', user, session, token }
|
|
888
|
+
```
|
|
889
|
+
|
|
890
|
+
A link sent to the user's e-mail signs them in: a sign-in code with nothing
|
|
891
|
+
to type.
|
|
892
|
+
|
|
893
|
+
- **On every user type with an e-mail**, with a password or without one, as
|
|
894
|
+
`signInCode`. A type with no e-mail has no `magicLink` at all.
|
|
895
|
+
- **`request(email)` answers `null`** when nobody of this type holds that
|
|
896
|
+
e-mail, or the user is inactive — never say which. It answers a `token` of
|
|
897
|
+
32 random bytes, base64url, for a link; only its hash is stored. One link
|
|
898
|
+
is live per user: a new `request` spends the ones before. A link and a
|
|
899
|
+
code are separate: asking for one leaves the other live.
|
|
900
|
+
- **`confirm(token)`** spends the token in one conditional write — of two
|
|
901
|
+
confirmations at once, one signs in — marks the e-mail verified and opens
|
|
902
|
+
the session. A link lives `'15m'` (`tokens.magicLink`); there are no
|
|
903
|
+
attempts, since there is nothing to guess. `TOKEN_STALE`, `USER_INACTIVE`,
|
|
904
|
+
an active second factor and **an e-mail proved for the first time — the
|
|
905
|
+
password, the second factor and the avatar dropped, every session signed out, every API key revoked** — are
|
|
906
|
+
handled as for a code.
|
|
907
|
+
- **Not ended by a password write, nor limited by the sign-in throttle**:
|
|
908
|
+
the password proves nothing a link does, and that throttle counts
|
|
909
|
+
passwords. The mail throttle counts `request` per address, five per
|
|
910
|
+
10 minutes (`MAIL_THROTTLED`); the last link sent still works. Limit it per
|
|
911
|
+
client yourself.
|
|
912
|
+
- **`magicLink: { enabled: false }`** in `janus()` switches it off (`true`
|
|
913
|
+
when absent, so nothing changes). `request`, `prepare` and `confirm` then
|
|
914
|
+
throw `MAGIC_LINK_DISABLED` (404) before any store access: no throttle
|
|
915
|
+
count, no token issued or spent, nothing to send. `auth.magicLink.enabled`
|
|
916
|
+
is the state, to hide the button without a second flag.
|
|
917
|
+
|
|
918
|
+
[The sign-in link guide](docs/guide/magic-link.md) has the page that
|
|
919
|
+
confirms from a `POST` so mail scanners spend nothing, every error, routes
|
|
920
|
+
and a test.
|
|
921
|
+
|
|
922
|
+
### Changing an e-mail — `changeEmail`
|
|
923
|
+
|
|
924
|
+
```ts
|
|
925
|
+
// Gate it: only a user who just proved who they are (assertFresh, or a step-up).
|
|
926
|
+
const issued = await auth.changeEmail.send(user, newEmail); // { token, email, expiresAt }
|
|
927
|
+
const link = `https://app.example/email/confirm?token=${issued.token}`;
|
|
928
|
+
await sendMail(issued.email, link); // the NEW address; say "ignore it if it was not you"
|
|
929
|
+
|
|
930
|
+
// the page's button POSTs the token back — never confirm on the link's GET
|
|
931
|
+
const changed = await auth.changeEmail.confirm(token); // now at the new address, verified
|
|
932
|
+
```
|
|
933
|
+
|
|
934
|
+
A link sent to the **new** address moves the user there: nothing changes
|
|
935
|
+
until it is followed, and following it proves the address.
|
|
936
|
+
|
|
937
|
+
**Confirming moves the requester's whole account to the new address** — the
|
|
938
|
+
password, the avatar and the second factor go with it, so whoever holds the new inbox
|
|
939
|
+
and follows the link signs in with them. The mail to the new address should
|
|
940
|
+
say so, and say "ignore it if it was not you".
|
|
941
|
+
|
|
942
|
+
**Send the link to the new address with `@softistx/janus-mail` 0.10.0 or later**:
|
|
943
|
+
`mail.changeEmail(issued, { name })` (its `links.changeEmail` is the page
|
|
944
|
+
above), and it sends the notice to the former address, `emailChanged`, once
|
|
945
|
+
the link is redeemed. `mail.verifyEmail(issued)` is not the change-of-e-mail
|
|
946
|
+
mail: it would tell the new address to verify, not that the account moves
|
|
947
|
+
there. Without janus-mail, send it with your own mailer.
|
|
948
|
+
|
|
949
|
+
- **On every user type with an e-mail**, with a password or without one. The
|
|
950
|
+
address is validated by the type's schema as `update` would: a malformed
|
|
951
|
+
one is `USER_INVALID` at `send`, and so is the user's current address
|
|
952
|
+
(equal once normalised): a change moves to another one, and verifying the
|
|
953
|
+
current one is `verifyEmail`'s job. That refusal spends nothing.
|
|
954
|
+
- **`send(user, email)`** takes a user you hold, so it is yours to gate:
|
|
955
|
+
behind `assertFresh` or a step-up, since whoever changes the e-mail takes
|
|
956
|
+
over password resets. An inactive user is `USER_INACTIVE`. One link is
|
|
957
|
+
live per user: a new `send` spends the ones before. It lives `'1h'`
|
|
958
|
+
(`tokens.changeEmail`). Throttled per new address and per user, five per
|
|
959
|
+
10 minutes each (`MAIL_THROTTLED`, carrying the user's id), before anything
|
|
960
|
+
is issued. The user is counted first, so an account past its own count
|
|
961
|
+
exhausts no address; an address other people exhausted costs the asking
|
|
962
|
+
user one of their own.
|
|
963
|
+
- **Whether the address is taken is not asked at `send`**: it would tell who
|
|
964
|
+
has an account. `confirm` writes, and the store's own unique constraint
|
|
965
|
+
answers `LOGIN_TAKEN` — the token already spent, nothing written.
|
|
966
|
+
- **`confirm(token)`** spends the token, moves the user to the address and
|
|
967
|
+
marks it verified. The password, the second factor and the sessions are
|
|
968
|
+
untouched. A link whose e-mail is no longer the one `send` was asked from
|
|
969
|
+
is `TOKEN_SPENT` after an `update` that moved it (`update` spends the
|
|
970
|
+
links) or after a newer link; `TOKEN_STALE` comes from a write outside
|
|
971
|
+
janus, or from a `send` racing an `update`, and is checked again on the
|
|
972
|
+
record written. A write racing `confirm` is `VERSION_CONFLICT`, after the
|
|
973
|
+
token is spent.
|
|
974
|
+
- **Events**: `user.emailChanged`, carrying `formerEmail`, then
|
|
975
|
+
`user.emailVerified`. An `update` that moves the e-mail spends the
|
|
976
|
+
user's pending links, so a move back to the old address revives none.
|
|
977
|
+
- **With several user types**, `auth.admin.changeEmail.confirm(token)` answers
|
|
978
|
+
`TOKEN_UNKNOWN` for a token issued to a user of another type — and the token
|
|
979
|
+
is spent. A confirmation page that does not know the type calls the root's
|
|
980
|
+
instead, which reads the user the token was issued to, whatever their type,
|
|
981
|
+
and confirms exactly as their type does (`send` stays on each type):
|
|
982
|
+
|
|
983
|
+
```ts
|
|
984
|
+
await auth.admin.changeEmail.send(admin, newEmail);
|
|
985
|
+
const changed = await auth.changeEmail.confirm(token); // changed.type === 'admin'
|
|
986
|
+
```
|
|
987
|
+
|
|
988
|
+
It exists when at least one type has an e-mail, so a type cannot be named
|
|
989
|
+
`changeEmail`. Its type is `AnyTypeChangeEmailApi`.
|
|
990
|
+
|
|
991
|
+
[The e-mail flows guide](docs/guide/email-flows.md#changeemail) has a Hono
|
|
992
|
+
route for each step, with the notice to the former address.
|
|
993
|
+
|
|
994
|
+
### Confirming a link at the root of several types
|
|
995
|
+
|
|
996
|
+
`confirm(token, { user })` binds a link to one user: see the trap under [Traps](#traps), *A sign-up with `signUp.prepare` can squat somebody's address*.
|
|
997
|
+
|
|
998
|
+
A type's own `confirm` — `auth.admin.verifyEmail.confirm`,
|
|
999
|
+
`auth.admin.resetPassword.confirm`, `auth.admin.changeEmail.confirm` — answers
|
|
1000
|
+
`TOKEN_UNKNOWN` for another type's token, **and spends it**. A page that
|
|
1001
|
+
follows a link without knowing the type calls the root's, from a `POST`:
|
|
1002
|
+
|
|
1003
|
+
```ts
|
|
1004
|
+
await auth.admin.verifyEmail.send(admin);
|
|
1005
|
+
const verified = await auth.verifyEmail.confirm(token); // AnyTypeVerifyEmailApi: a type has an e-mail
|
|
1006
|
+
const reset = await auth.resetPassword.confirm(token, newPassword); // AnyTypeResetPasswordApi: a type has a login and an e-mail
|
|
1007
|
+
const changed = await auth.changeEmail.confirm(token); // AnyTypeChangeEmailApi: a type has an e-mail
|
|
1008
|
+
```
|
|
1009
|
+
|
|
1010
|
+
Each reads the user the token was issued to, whatever their type, and does
|
|
1011
|
+
what their type's `confirm` does: the same write, events and refusals, and
|
|
1012
|
+
`type` in the answer says which type it was. `send`, `proveFirst`, `request`
|
|
1013
|
+
and `prepare` stay on each type. No type may be named `verifyEmail`,
|
|
1014
|
+
`resetPassword` or `changeEmail`. **The root reset checks the password against
|
|
1015
|
+
the strictest `minLength`** before it spends the link — see
|
|
1016
|
+
[Traps](#traps).
|
|
1017
|
+
|
|
1018
|
+
### Requests in two steps — `prepare`
|
|
1019
|
+
|
|
1020
|
+
```ts
|
|
1021
|
+
// In the visitor's request: counted, nobody looked up — the same time for any address.
|
|
1022
|
+
// Past the limit it throws MailThrottledError: answer 429 with retryAfter, which
|
|
1023
|
+
// @softistx/janus-hono's janusErrors() and @softistx/janus-graphql do for you.
|
|
1024
|
+
const pending = await auth.magicLink.prepare(email); // { send() }
|
|
1025
|
+
|
|
1026
|
+
// Off the visitor's request: looked up, issued, mailed — or nothing, for nobody.
|
|
1027
|
+
void (async () => {
|
|
1028
|
+
const issued = await pending.send(); // what request answers: { token, email, expiresAt, user } | null
|
|
1029
|
+
if (issued !== null) {
|
|
1030
|
+
await sendMail(issued.email, `Sign in: https://app.example/sign-in/link?token=${issued.token}`);
|
|
1031
|
+
}
|
|
1032
|
+
})().catch(reportError); // a STORE_FAILED here reaches nobody: log it
|
|
1033
|
+
|
|
1034
|
+
// the same page for everybody, whoever holds the address
|
|
1035
|
+
```
|
|
1036
|
+
|
|
1037
|
+
`magicLink.prepare(email)`, `signInCode.prepare(email)` and
|
|
1038
|
+
`resetPassword.prepare(email)` are `request(email)` cut in two at the mail
|
|
1039
|
+
throttle's count, so `MAIL_THROTTLED` reaches the visitor while the e-mail
|
|
1040
|
+
still goes out off their request.
|
|
1041
|
+
|
|
1042
|
+
- **`prepare(email)` validates, counts the address, and looks nobody up**:
|
|
1043
|
+
the same store calls whoever holds the address, none with
|
|
1044
|
+
`mail: { throttle: false }`. Past the limit it is `MailThrottledError`
|
|
1045
|
+
with `retryAfter`, and nothing is issued. It shares its count with
|
|
1046
|
+
`request`: one window per flow and address.
|
|
1047
|
+
- **`send()` does the rest of `request`, once** — looks the address up,
|
|
1048
|
+
issues, spends the earlier tokens — and answers what `request` answers,
|
|
1049
|
+
`null` for nobody. It counts nothing: the count was `prepare`'s. A second
|
|
1050
|
+
call is a `TypeError`, and so is a call after one that failed: prepare
|
|
1051
|
+
again, which counts again.
|
|
1052
|
+
- **`signInCode.prepare` also answers the `challenge`**, minted before the
|
|
1053
|
+
lookup, so the visitor's cookie is set now, whoever holds the address —
|
|
1054
|
+
it replaces the decoy an unknown address needed; for nobody it confirms as
|
|
1055
|
+
`TOKEN_UNKNOWN`. `send()` answers the code issued under it.
|
|
1056
|
+
- Typed per flow: `PreparedRequest<IssuedToken & { user }>` for a link and
|
|
1057
|
+
a reset, `PreparedCode<User>` for a code. `verifyEmail.send`,
|
|
1058
|
+
`changeEmail.send` and `stepUp.request` have no `prepare`: they take a user the application
|
|
1059
|
+
already holds, so their time tells nothing about who has an account.
|
|
1060
|
+
|
|
1061
|
+
[The e-mail flows guide](docs/guide/email-flows.md#requests-in-two-steps)
|
|
1062
|
+
has a route for each flow, with Hono.
|
|
1063
|
+
|
|
1064
|
+
### Verifying at sign-up without revealing taken addresses
|
|
1065
|
+
|
|
1066
|
+
Three pieces answer the same page for a new address and a taken one, and keep
|
|
1067
|
+
an unverified address from signing in:
|
|
1068
|
+
|
|
1069
|
+
```ts
|
|
1070
|
+
const auth = janus({
|
|
1071
|
+
user: User,
|
|
1072
|
+
password: { login: 'email', requireVerifiedEmail: true }, // EMAIL_UNVERIFIED after the right password, no session
|
|
1073
|
+
// ...
|
|
1074
|
+
});
|
|
1075
|
+
|
|
1076
|
+
// In the visitor's request: validated (USER_INVALID, PASSWORD_TOO_SHORT), counted per
|
|
1077
|
+
// address (MAIL_THROTTLED), nobody looked up.
|
|
1078
|
+
const pending = await auth.signUp.prepare({ email, name, password });
|
|
1079
|
+
|
|
1080
|
+
// Off the request: created, or found taken. No session either way.
|
|
1081
|
+
void pending.send().then(async (outcome) => {
|
|
1082
|
+
if (outcome.status === 'created') {
|
|
1083
|
+
await sendMail(outcome.issued.email, `Verify: https://app.example/verify?token=${outcome.issued.token}`);
|
|
1084
|
+
} else {
|
|
1085
|
+
await sendMail(outcome.user.email, 'Somebody tried to sign up with your address');
|
|
1086
|
+
}
|
|
1087
|
+
}).catch(reportError);
|
|
1088
|
+
|
|
1089
|
+
// An anonymous resend, counted per address; the visitor's answer never depends on the address.
|
|
1090
|
+
const again = await auth.verifyEmail.prepare(email);
|
|
1091
|
+
void again.send().then((issued) => issued && sendMail(issued.email, `Verify: …?token=${issued.token}`));
|
|
1092
|
+
```
|
|
1093
|
+
|
|
1094
|
+
- **`password.requireVerifiedEmail: true`** (a type with an e-mail field; a schema without one is refused at compile time): after a correct password, an
|
|
1095
|
+
address never verified is `EMAIL_UNVERIFIED` (403) and no session opens. A
|
|
1096
|
+
wrong password, an unknown login and a throttled one answer
|
|
1097
|
+
`CREDENTIALS_INVALID` exactly as without the option, so the new code is
|
|
1098
|
+
told only to somebody who knows the password. `false` when absent.
|
|
1099
|
+
- **`signUp.prepare(input)`** validates the fields and the password policy and
|
|
1100
|
+
counts the attempt per address (`signUp.prepare` shares nothing with the
|
|
1101
|
+
other flows' windows), looking nobody up. Its `send()`, once, answers
|
|
1102
|
+
`{ status: 'created', user, issued }` (the account exists, `issued` is the
|
|
1103
|
+
verification token to mail, nobody is signed in) or
|
|
1104
|
+
`{ status: 'taken', user }` (nothing written: mail the holder a notice).
|
|
1105
|
+
It exists only on a type whose **login is its e-mail field**, so the
|
|
1106
|
+
address typed is the holder's; elsewhere the type has no `prepare` and a
|
|
1107
|
+
call is a `TypeError`. `signUp` itself is unchanged.
|
|
1108
|
+
- **`verifyEmail.prepare(email)`** counts the address; its `send()` issues
|
|
1109
|
+
for the active, unverified user of that type holding it and answers `null`
|
|
1110
|
+
for anybody else.
|
|
1111
|
+
|
|
1112
|
+
See [the e-mail flows guide](docs/guide/email-flows.md#verifying-at-sign-up-without-revealing-taken-addresses).
|
|
1113
|
+
|
|
1114
|
+
### Signing in on your own proof — `signInProven`
|
|
1115
|
+
|
|
1116
|
+
```ts
|
|
1117
|
+
// Accepting an invitation: the proof is the invitation token YOUR server issued and verified.
|
|
1118
|
+
const invitation = await invitations.redeem(body.invitationToken); // yours: one use, expiring, hashed at rest
|
|
1119
|
+
if (invitation === null) return new Response(null, { status: 404 });
|
|
1120
|
+
|
|
1121
|
+
// The invitation reached the inbox: call verifyEmail.proveFirst before this — see below.
|
|
1122
|
+
const result = await auth.signInProven(invitation.userId, { device: deviceCookie ?? null });
|
|
1123
|
+
if (result.status === 'secondFactor') return askForCode(result.challenge); // switch on status, as after signIn
|
|
1124
|
+
// result: { status: 'signedIn', user, session, token, newDevice, deviceToken }
|
|
1125
|
+
```
|
|
1126
|
+
|
|
1127
|
+
Signs in a user **the application proved by its own means** — an invitation
|
|
1128
|
+
token it issued and the person followed, a channel of its own it verified —
|
|
1129
|
+
with no password, code or link. Every user type has it.
|
|
1130
|
+
|
|
1131
|
+
- **Privileged: janus checks no credential, your server carries the
|
|
1132
|
+
proof.** Call it only after that proof was verified, and **never with an
|
|
1133
|
+
id a request supplied**: whoever chooses the id signs in as anybody. No
|
|
1134
|
+
route of `@softistx/janus-hono` or `@softistx/janus-graphql` exposes it.
|
|
1135
|
+
- **It finishes as every sign-in does**: an active second factor answers a
|
|
1136
|
+
challenge for `secondFactor.confirm` (`SignInResult`, the same union as
|
|
1137
|
+
`signIn`'s); `device` answers `newDevice` and `deviceToken` and sends
|
|
1138
|
+
`user.newDeviceSignedIn` for a new one; an inactive user is
|
|
1139
|
+
`USER_INACTIVE`.
|
|
1140
|
+
- **Takes the user, or their id** (`UserRef`). A malformed id, an unknown
|
|
1141
|
+
one, a deleted user or one of another type is `NOT_FOUND`, as for `get`:
|
|
1142
|
+
a sign-in that found nobody throws rather than answer something to read
|
|
1143
|
+
past.
|
|
1144
|
+
- **Sends nothing, counts nothing, spends nothing**: no e-mail, no token,
|
|
1145
|
+
no mail-throttle or sign-in-throttle count — so a loop of anonymous
|
|
1146
|
+
`magicLink.request` on the invitee's address cannot make it answer 429 —
|
|
1147
|
+
and links or codes already in the person's inbox still work. It proves
|
|
1148
|
+
no e-mail either: `emailVerified` stays as it was, and nothing is dropped
|
|
1149
|
+
as on a first proof by link — call `verifyEmail.proveFirst` before it
|
|
1150
|
+
when your proof reached the inbox, as an invitation does.
|
|
1151
|
+
|
|
1152
|
+
[Sessions](docs/guide/sessions.md#signing-in-on-your-own-proof--signinproven)
|
|
1153
|
+
has the invitation route in full, and what to verify before the call.
|
|
1154
|
+
|
|
1155
|
+
### Finding a user by e-mail — `findByEmail`
|
|
1156
|
+
|
|
1157
|
+
```ts
|
|
1158
|
+
// Accepting an invitation sent to an address: the account may already exist, on a type with no password.
|
|
1159
|
+
const invitation = await invitations.redeem(body.invitationToken); // yours: verified first
|
|
1160
|
+
if (invitation === null) return new Response(null, { status: 404 });
|
|
1161
|
+
|
|
1162
|
+
const member =
|
|
1163
|
+
(await auth.member.findByEmail(invitation.email)) ?? // User | null — counts nothing, sends nothing
|
|
1164
|
+
(await auth.member.create({ email: invitation.email, name: '' }));
|
|
1165
|
+
await auth.member.verifyEmail.proveFirst(member); // the invitation reached the inbox: before signInProven
|
|
1166
|
+
const result = await auth.member.signInProven(member, { device: deviceCookie ?? null });
|
|
1167
|
+
```
|
|
1168
|
+
|
|
1169
|
+
The user of this type holding the address, or `null` — on **every type with
|
|
1170
|
+
an e-mail, password or not**. A type with no password has no `findByLogin`,
|
|
1171
|
+
and needs no password login to be found: declaring one would open the
|
|
1172
|
+
password and reset flows on it.
|
|
1173
|
+
|
|
1174
|
+
- **Normalised as the e-mail flows normalise**: trimmed and lowercased,
|
|
1175
|
+
whatever the type's login. A type that signs in with a username is still
|
|
1176
|
+
found by its e-mail, and a username that only looks like an address is
|
|
1177
|
+
nobody's — the same holder `magicLink.request` and `resetPassword.request`
|
|
1178
|
+
would find.
|
|
1179
|
+
- **Read-only**: counts nothing in the mail or the sign-in throttle,
|
|
1180
|
+
issues nothing, writes nothing. An inactive user is answered, as by
|
|
1181
|
+
`find` — `signInProven` then refuses them with `USER_INACTIVE`.
|
|
1182
|
+
- **A value that is no address is nobody's**: not a string, empty once
|
|
1183
|
+
trimmed, or holding a NUL or a lone surrogate answers `null` without
|
|
1184
|
+
asking the store, as `find` answers a malformed id. An outage is
|
|
1185
|
+
`STORE_FAILED`, never `null`.
|
|
1186
|
+
- **Server-side only**: it tells whether an account exists. See *Traps*.
|
|
1187
|
+
|
|
1188
|
+
### Finding a user, or creating them — `findOrCreate`
|
|
1189
|
+
|
|
1190
|
+
```ts
|
|
1191
|
+
// Accepting an invitation: the account may exist; if not, it is created only when a password was given.
|
|
1192
|
+
const invitation = await invitations.redeem(body.invitationToken); // yours: verified first
|
|
1193
|
+
if (invitation === null) return new Response(null, { status: 404 });
|
|
1194
|
+
|
|
1195
|
+
const { user } = await auth.findOrCreate(invitation.email, () => {
|
|
1196
|
+
if (body.password === undefined) throw new Error('a password is required'); // refused: nothing is written
|
|
1197
|
+
return { email: invitation.email, name: body.name }; // no password here: proveFirst drops it, setPassword sets it once
|
|
1198
|
+
});
|
|
1199
|
+
await auth.verifyEmail.proveFirst(user); // drops a squatter's password, factor and sessions: first
|
|
1200
|
+
if (typeof body.password === 'string') await auth.setPassword(user, body.password); // then the invitee's own
|
|
1201
|
+
const result = await auth.signInProven(user); // last
|
|
1202
|
+
```
|
|
1203
|
+
|
|
1204
|
+
The user of this type holding `key`, or the one `input()` describes,
|
|
1205
|
+
created — in one call, with the lost race handled. Typed by the exported
|
|
1206
|
+
`FindOrCreateApi`; the
|
|
1207
|
+
[users guide](docs/guide/users.md#finding-a-user-or-creating-them--findorcreate)
|
|
1208
|
+
has the details. On **every type with a
|
|
1209
|
+
login or an e-mail**: the key is the login, normalised as `findByLogin`
|
|
1210
|
+
normalises it, on a type with a password, and the e-mail, normalised as
|
|
1211
|
+
`findByEmail` does, on a type without one. On a type whose login is a
|
|
1212
|
+
username, an e-mail key finds an existing user (e-mails are stored as
|
|
1213
|
+
logins) but can never create one: the input's username is not the key, so
|
|
1214
|
+
it is `USER_INVALID`.
|
|
1215
|
+
|
|
1216
|
+
- **Found: nothing else happens.** The user is answered
|
|
1217
|
+
`{ user, created: false }` — an inactive one included — `input` is not
|
|
1218
|
+
called and nothing is written.
|
|
1219
|
+
- **`input` is the refusal point.** It runs only when nobody holds the key,
|
|
1220
|
+
and what it throws propagates with nothing written: refuse there what the
|
|
1221
|
+
caller must refuse before a write, such as a missing password.
|
|
1222
|
+
- **The key is a string.** Any other value is `USER_INVALID` before `input()`
|
|
1223
|
+
runs.
|
|
1224
|
+
- **The input must name the key.** Once validated, its login (its e-mail,
|
|
1225
|
+
without a password) must equal the normalised `key`, or the call is
|
|
1226
|
+
`USER_INVALID` before the write.
|
|
1227
|
+
- **A lost race is not an error.** When another call created the user between
|
|
1228
|
+
the read and the write, the store's `LOGIN_TAKEN` is followed by one more
|
|
1229
|
+
read of the key; the winner is answered `{ user, created: false }`. The
|
|
1230
|
+
`LOGIN_TAKEN` is rethrown only when that read finds nobody — another login
|
|
1231
|
+
of the new user is taken.
|
|
1232
|
+
- **Created as `create` creates**: the same validation, the same hashing,
|
|
1233
|
+
`PASSWORD_TOO_SHORT` below the policy, and `user.created` sent only when
|
|
1234
|
+
this call created. Signs nobody in.
|
|
1235
|
+
- **Server-side only**, an account-existence oracle as `findByEmail` is.
|
|
1236
|
+
|
|
1237
|
+
### Marking an e-mail verified as an administrator — `setEmailVerified`
|
|
1238
|
+
|
|
1239
|
+
```ts
|
|
1240
|
+
await auth.setEmailVerified(user, true); // checked out of band: the flag alone
|
|
1241
|
+
await auth.setEmailVerified(user, false, { ifVersion: 3 }); // clear it; a user written since is VERSION_CONFLICT
|
|
1242
|
+
```
|
|
1243
|
+
|
|
1244
|
+
`setEmailVerified(user, verified, options?)` answers the `User` and is on every
|
|
1245
|
+
type with an e-mail. It writes `emailVerified` and nothing else: the password,
|
|
1246
|
+
avatar and second factor stay, and no session, API key or token is revoked.
|
|
1247
|
+
Turning the flag on sends `user.emailVerified`; a flag already as asked is no
|
|
1248
|
+
write and no event, and turning it off sends no event.
|
|
1249
|
+
|
|
1250
|
+
**It is not `proveFirst`.** `proveFirst` is the first proof of an address on
|
|
1251
|
+
*your server's proof of the inbox* and it removes what a squatter set (password,
|
|
1252
|
+
avatar, second factor, sessions). `setEmailVerified` has no takeover-proofing:
|
|
1253
|
+
anything that trusts a verified e-mail then acts on the address as it is. Use
|
|
1254
|
+
`proveFirst` for a person who just proved the inbox (an invitation) and
|
|
1255
|
+
`setEmailVerified` for an administrator's decision about an account that stays
|
|
1256
|
+
as it is. Call it only with an id your server chose.
|
|
1257
|
+
|
|
1258
|
+
### Proving an e-mail on your own proof — `verifyEmail.proveFirst`
|
|
1259
|
+
|
|
1260
|
+
```ts
|
|
1261
|
+
// Accepting an invitation: the token YOUR server mailed to the address proves the inbox.
|
|
1262
|
+
const user = (await auth.findByEmail(invitation.email)) ?? (await auth.create({ email: invitation.email, name }));
|
|
1263
|
+
const { proved } = await auth.verifyEmail.proveFirst(user); // 1. first: drops a squatter's password, factor, sessions
|
|
1264
|
+
await auth.setPassword(user, body.password); // 2. then the invitee's own password, if the type has one
|
|
1265
|
+
const result = await auth.signInProven(user); // 3. last: proveFirst revokes every session
|
|
1266
|
+
```
|
|
1267
|
+
|
|
1268
|
+
Answers `FirstProof<User>` — `{ user, proved }`, exported. Applies **the
|
|
1269
|
+
first proof of an e-mail** that `magicLink.confirm` and
|
|
1270
|
+
`signInCode.confirm` apply, when the proof is the application's — an
|
|
1271
|
+
invitation token it mailed to the address and the person followed. On every
|
|
1272
|
+
type with an e-mail; `signInProven` alone proves nothing.
|
|
1273
|
+
|
|
1274
|
+
- **On an e-mail never proved, in one write**: marks it verified and drops
|
|
1275
|
+
the password and the second factor — active or waiting, with its recovery
|
|
1276
|
+
codes — and the avatar (`user.avatarRemoved` carries its `formerAvatarId`,
|
|
1277
|
+
so delete the image). It revokes every session and every API key and spends the reset links and
|
|
1278
|
+
second-factor challenges, before the write and after it, and sends
|
|
1279
|
+
`user.emailVerified`, then `user.passwordChanged` when a password was
|
|
1280
|
+
dropped and `user.secondFactorDisabled` when an active factor was.
|
|
1281
|
+
Answers `{ user, proved: true }`.
|
|
1282
|
+
- **On an e-mail already proved, nothing**: no write, no event, no session
|
|
1283
|
+
revoked — `{ user, proved: false }`.
|
|
1284
|
+
- **Sends nothing, counts nothing**: no e-mail, no token, no mail-throttle
|
|
1285
|
+
or sign-in-throttle count.
|
|
1286
|
+
- **Refused as `signInProven` refuses**: an inactive user is
|
|
1287
|
+
`USER_INACTIVE`; a malformed id, an unknown one or one of another type is
|
|
1288
|
+
`NOT_FOUND`. A write landing between the read and the proof is
|
|
1289
|
+
retried once on a fresh read (`proved: false` when that write proved the
|
|
1290
|
+
e-mail); `VERSION_CONFLICT`, with nothing proved, when it changed the
|
|
1291
|
+
address or the retry conflicts too; an outage is `STORE_FAILED`.
|
|
1292
|
+
- **The address you hold is checked.** Given a `User` (an object carrying
|
|
1293
|
+
the type's e-mail field), it compares that address, normalised as e-mails
|
|
1294
|
+
are, with the one it reads, on the first read and on the retry read:
|
|
1295
|
+
another address is `VERSION_CONFLICT` and nothing is proved. Given a bare
|
|
1296
|
+
id, or an object without the e-mail field, it proves the current address.
|
|
1297
|
+
- **Privileged, and the order matters**: see *Traps*.
|
|
1298
|
+
|
|
1299
|
+
[E-mail flows](docs/guide/email-flows.md#proving-an-e-mail-on-your-own-proof--provefirst)
|
|
1300
|
+
has the details; [sessions](docs/guide/sessions.md#accepting-an-invitation)
|
|
1301
|
+
has the invitation route in full.
|
|
1302
|
+
|
|
1303
|
+
### Step-up — `stepUp` and `assertFresh`
|
|
1304
|
+
|
|
1305
|
+
```ts
|
|
1306
|
+
import { assertFresh } from '@softistx/janus';
|
|
1307
|
+
|
|
1308
|
+
// A sensitive route asks for a recent proof: signed in, or confirmed since.
|
|
1309
|
+
const current = await auth.authenticate(request);
|
|
1310
|
+
if (current === null) return new Response(null, { status: 401 });
|
|
1311
|
+
assertFresh(current.session, '10m'); // StepUpRequiredError, STEP_UP_REQUIRED (403), past ten minutes
|
|
1312
|
+
|
|
1313
|
+
// The client, told STEP_UP_REQUIRED, asks for a step-up:
|
|
1314
|
+
const issued = await auth.stepUp.request(current.user);
|
|
1315
|
+
if (issued.via === 'email') await sendMail(issued.email, `Confirm it is you: ${issued.code}`);
|
|
1316
|
+
// …keeps issued.challenge, and sends it back with the code:
|
|
1317
|
+
const session = await auth.stepUp.confirm(request, challenge, code); // authenticatedAt: now
|
|
1318
|
+
```
|
|
1319
|
+
|
|
1320
|
+
A signed-in user proves again who they are before something a stolen
|
|
1321
|
+
session should not do alone.
|
|
1322
|
+
|
|
1323
|
+
- **On every user type with an e-mail**, as `signInCode`. A type with no
|
|
1324
|
+
e-mail has no `stepUp`.
|
|
1325
|
+
- **`request(user)` answers `via: 'email'`** — a six-digit `code` to send to
|
|
1326
|
+
`email` — or, for a user whose second factor is active, **`via:
|
|
1327
|
+
'secondFactor'`**: nothing to send, ask for their app's code. A step-up is
|
|
1328
|
+
never weaker than the sign-in the account asks for. One step-up is live
|
|
1329
|
+
per user; a challenge lives `'10m'` (`tokens.stepUp`).
|
|
1330
|
+
- **`confirm(request, challenge, code)` stamps the session the request
|
|
1331
|
+
presents**: its `authenticatedAt` moves to now, and it is answered. It
|
|
1332
|
+
opens no session and hands out no token. Five attempts per challenge; an
|
|
1333
|
+
app's codes are also counted per user, five per 15-minute window, with
|
|
1334
|
+
`regenerateRecoveryCodes`. A request whose session is not a standing one
|
|
1335
|
+
of the challenge's user is `TOKEN_UNKNOWN`.
|
|
1336
|
+
- **`assertFresh(session, maxAge, clock?)`** (also takes the principal of `authenticate(request, { apiKey: true })`: a key always throws with `reason: 'apiKey'`) reads `authenticatedAt` and
|
|
1337
|
+
nothing else: `STEP_UP_REQUIRED` (403) when it is `maxAge` old or more. A
|
|
1338
|
+
fresh sign-in is fresh too.
|
|
1339
|
+
|
|
1340
|
+
[The step-up guide](docs/guide/step-up.md) has the two requests, every
|
|
1341
|
+
error, and the codes an app confirms.
|
|
1342
|
+
|
|
1343
|
+
### API keys — `apiKeys`
|
|
1344
|
+
|
|
1345
|
+
```ts
|
|
1346
|
+
import { createMemoryApiKeys } from '@softistx/janus';
|
|
1347
|
+
|
|
1348
|
+
const auth = janus({
|
|
1349
|
+
user: User,
|
|
1350
|
+
password: { login: 'email' },
|
|
1351
|
+
store,
|
|
1352
|
+
hasher,
|
|
1353
|
+
apiKeys: { store: createMemoryApiKeys(), prefix: 'sl_', lifetimes: ['30d', '90d'] },
|
|
1354
|
+
});
|
|
1355
|
+
|
|
1356
|
+
const current = await auth.authenticate(request); // a fresh session
|
|
1357
|
+
if (current === null) return new Response(null, { status: 401 });
|
|
1358
|
+
const { apiKey, token } = await auth.apiKeys.create(current, { name: 'CI', lifetime: '90d' });
|
|
1359
|
+
const { items } = await auth.apiKeys.list(current.user);
|
|
1360
|
+
const one = await auth.apiKeys.get(apiKey.id, { owner: current.user }); // ApiKey | null
|
|
1361
|
+
await auth.apiKeys.revoke(apiKey.id, { owner: current.user });
|
|
1362
|
+
```
|
|
1363
|
+
|
|
1364
|
+
Personal keys that act as their user. **Opt-in**: without the `apiKeys`
|
|
1365
|
+
block there is no `auth.apiKeys`, in the type too. The token (`sl_…`) is shown
|
|
1366
|
+
once and only its hash is stored; every key expires, from the `lifetimes` you
|
|
1367
|
+
list; `create` needs a session fresh within `freshWithin` (`'10m'`) and
|
|
1368
|
+
refuses past `maxActive` (`10`) keys with `API_KEY_LIMIT`. `resetPassword.confirm`
|
|
1369
|
+
revokes the user's keys unless `revokeOnPasswordReset: false`, and always does
|
|
1370
|
+
when the link proved the e-mail. The first proof of an e-mail (sign-in code,
|
|
1371
|
+
sign-in link, `verifyEmail` with `firstProof`, `proveFirst`) revokes them too.
|
|
1372
|
+
`create` refuses a user whose e-mail is not verified with `EMAIL_UNVERIFIED`
|
|
1373
|
+
when the type holds an e-mail. A key is read from `Authorization: Bearer`
|
|
1374
|
+
only, never from the cookie or `X-Session-Token`. `get(id, { owner })` reads one
|
|
1375
|
+
key (`null` for an unknown id or another user's key): **without `owner` it is
|
|
1376
|
+
not user-scoped, an administrator's read, never to be answered to a request
|
|
1377
|
+
without checking `userId`**. A revoked or lapsed key is answered as it is.
|
|
1378
|
+
`list(user, { bound })` filters on a bound object (`null`: the unbound keys).
|
|
1379
|
+
|
|
1380
|
+
Keys are accepted **only where you ask**. Without `apiKey: true`, a key-shaped
|
|
1381
|
+
bearer answers `null`:
|
|
1382
|
+
|
|
1383
|
+
```ts
|
|
1384
|
+
const principal = await auth.authenticate(request, { apiKey: true });
|
|
1385
|
+
if (principal === null) return new Response(null, { status: 401 });
|
|
1386
|
+
if (principal.via === 'apiKey') principal.apiKey.id; // principal.session is null
|
|
1387
|
+
else principal.session.expiresAt;
|
|
1388
|
+
|
|
1389
|
+
assertFresh(principal, '10m'); // a key always throws STEP_UP_REQUIRED, reason 'apiKey'
|
|
1390
|
+
```
|
|
1391
|
+
|
|
1392
|
+
A key is never fresh and renews nothing; `lastUsedAt` is written at most once
|
|
1393
|
+
per `lastUsedEvery`; an outage is `STORE_FAILED`.
|
|
1394
|
+
|
|
1395
|
+
A key can carry `scopes` and be `bound` to one object; both come back on the
|
|
1396
|
+
principal, and your route enforces them. `listBound`, `revokeAllBound`,
|
|
1397
|
+
`expiring` and `markExpiryNotified` serve them and the expiry notices:
|
|
1398
|
+
|
|
1399
|
+
```ts
|
|
1400
|
+
await auth.apiKeys.create(current, {
|
|
1401
|
+
name: 'Assistant',
|
|
1402
|
+
lifetime: '30d',
|
|
1403
|
+
scopes: ['tools:read'],
|
|
1404
|
+
bound: { type: 'workspace', id },
|
|
1405
|
+
});
|
|
1406
|
+
principal.scopes; // ['tools:read'] on a key principal, null on an unscoped key
|
|
1407
|
+
await auth.apiKeys.revokeAllBound(user, { type: 'workspace', id }); // → how many
|
|
1408
|
+
```
|
|
1409
|
+
|
|
1410
|
+
[The API keys guide](docs/guide/api-keys.md) has every option and error.
|
|
1411
|
+
|
|
1412
|
+
### Invitations — `invitations`
|
|
1413
|
+
|
|
1414
|
+
```ts
|
|
1415
|
+
import { createMemoryInvitations } from '@softistx/janus';
|
|
1416
|
+
|
|
1417
|
+
const auth = janus({
|
|
1418
|
+
user: z.object({ email: z.email(), name: z.string() }),
|
|
1419
|
+
password: { login: 'email' },
|
|
1420
|
+
store,
|
|
1421
|
+
hasher,
|
|
1422
|
+
invitations: {
|
|
1423
|
+
store: createMemoryInvitations(), // or createMongoInvitations(db), createDrizzleInvitations(db, { tables })
|
|
1424
|
+
create: (invitation) => ({ email: invitation.email, name: invitation.name }),
|
|
1425
|
+
// Runs before anything is written; `false` leaves the invitation pending (INVITATION_REFUSED).
|
|
1426
|
+
beforeAccept: async ({ invitation, user }) => {
|
|
1427
|
+
return directory.stillExists(invitation.email);
|
|
1428
|
+
},
|
|
1429
|
+
onAccepted: async ({ invitation, user }) => {
|
|
1430
|
+
await memberships.add({ scope: invitation.scope, userId: user.id, role: invitation.role });
|
|
1431
|
+
},
|
|
1432
|
+
},
|
|
1433
|
+
});
|
|
1434
|
+
|
|
1435
|
+
// The inviter's session; whether they may invite into this scope is yours to check.
|
|
1436
|
+
const { invitation, code } = await auth.invitations.issue({
|
|
1437
|
+
scope: 'school-1', email: 'ada@example.com', name: 'Ada', role: 'teacher', invitedBy: current.user,
|
|
1438
|
+
ref: person.id, // optional: an opaque reference to your own record (1 to 100 characters)
|
|
1439
|
+
// type: 'guardian', // required when `invitations.type` lists several user types
|
|
1440
|
+
});
|
|
1441
|
+
|
|
1442
|
+
// From a script or a migration, with no user to be the inviter: the system issues it.
|
|
1443
|
+
await auth.invitations.issue({ scope: 'school-1', email: 'root@example.com', name: 'Root', role: 'admin', invitedBy: null });
|
|
1444
|
+
// invitation.invitedBy is null, and so is the `invitedBy` of its events
|
|
1445
|
+
// put `code` in the e-mail's link now (@softistx/janus-mail: mail.invitation); it is never readable again
|
|
1446
|
+
|
|
1447
|
+
await auth.invitations.resend({ id: invitation.id, scope: 'school-1' }); // { invitation, code }: a new code
|
|
1448
|
+
await auth.invitations.revoke({
|
|
1449
|
+
id: invitation.id, scope: 'school-1',
|
|
1450
|
+
by: current.user.id, // optional: who acted, kept as revokedBy / resentBy
|
|
1451
|
+
}); // takes it back
|
|
1452
|
+
const { items, nextCursor } = await auth.invitations.list('school-1', { status: 'pending' });
|
|
1453
|
+
// Filter on `role` and `ref`, newest first, and count (same filters, no paging):
|
|
1454
|
+
await auth.invitations.list('school-1', { ref: person.id, order: 'desc' });
|
|
1455
|
+
const pending = await auth.invitations.count('school-1', { status: 'pending' });
|
|
1456
|
+
// Leave lapsed ones out ('exclude': pending past expiresAt; every other record stays),
|
|
1457
|
+
// or keep only them ('only'); list and count take it, and a cursor is bound to it:
|
|
1458
|
+
const live = await auth.invitations.list('school-1', { lapsed: 'exclude' });
|
|
1459
|
+
const lapsedTotal = await auth.invitations.count('school-1', { lapsed: 'only' });
|
|
1460
|
+
// One invitation by id: one store read; `null` when it is absent from that scope.
|
|
1461
|
+
const one = await auth.invitations.get({ id: invitation.id, scope: 'school-1' });
|
|
1462
|
+
|
|
1463
|
+
// Moving from an older system: copy its history in (no mail, no code, no event), dry run first.
|
|
1464
|
+
const report = await auth.invitations.importHistory(
|
|
1465
|
+
[{ key: 'inv-42', scope: 'school-1', email: 'ada@example.com', name: 'Ada', role: 'teacher',
|
|
1466
|
+
status: 'accepted', createdAt, acceptedAt, acceptedBy: ada.id }],
|
|
1467
|
+
{ dryRun: true },
|
|
1468
|
+
); // { dryRun, inserted, present, refused, items: [{ key, id, outcome, reason? }] }
|
|
1469
|
+
|
|
1470
|
+
// The invitee's page: preview on GET (spends nothing), accept on POST.
|
|
1471
|
+
const shown = await auth.invitations.preview(code); // { id, scope, email, name, role, locale, type, expiresAt, needsPassword }
|
|
1472
|
+
const accepted = await auth.invitations.accept({ code, password });
|
|
1473
|
+
if (accepted.status === 'signedIn') accepted.token; // put it in the cookie
|
|
1474
|
+
else if (accepted.status === 'secondFactor') accepted.challenge; // a second factor to prove first, as for any sign-in
|
|
1475
|
+
else if (accepted.status === 'signIn') redirect('/sign-in'); // the address already had a proved account
|
|
1476
|
+
```
|
|
1477
|
+
|
|
1478
|
+
Inviting somebody into a scope (an organization of yours) with a role of yours.
|
|
1479
|
+
**Opt-in**: without the `invitations` block there is no `auth.invitations`, in
|
|
1480
|
+
the type too, and the user type must have an e-mail and either no password (the
|
|
1481
|
+
invitee is signed in with the link) or a password whose login is that e-mail.
|
|
1482
|
+
`type` can be a **list** of user types (`type: ['staff', 'guardian']`), each
|
|
1483
|
+
invitation issued for one (`issue({ type })`, answered as `invitation.type`;
|
|
1484
|
+
list first the type older invitations were issued for).
|
|
1485
|
+
The code is 32 random bytes shown once, only its sha256 is stored, and
|
|
1486
|
+
it is good for `lifetime` (`'7d'`). One pending invitation per scope and
|
|
1487
|
+
address: issuing again revokes the old link (of concurrent issues exactly one wins; the others throw `INVITATION_PENDING`). `accept` claims the invitation
|
|
1488
|
+
first (of two concurrent accepts one wins), then creates the user with the
|
|
1489
|
+
e-mail proved and the chosen password, or, for an e-mail never proved, proves it
|
|
1490
|
+
(which drops the old password, second factor, avatar and sessions), or, for a proved
|
|
1491
|
+
account, leaves it alone and answers `signIn`. `onAccepted` then adds the user
|
|
1492
|
+
to the scope; if it throws, the invitation is released and the retry answers
|
|
1493
|
+
`signIn`. Events (`invitation.issued`, `resent`, `revoked`, `accepted`) go to
|
|
1494
|
+
`invitations.events` and never carry the address or the code.
|
|
1495
|
+
|
|
1496
|
+
`importHistory` takes at most 1000 records per call and is **idempotent by
|
|
1497
|
+
(`scope`, `key`)**: the id is derived from them, so a re-run reports the records
|
|
1498
|
+
`present`. Accepted, revoked and lapsed pending records are imported; a live
|
|
1499
|
+
pending one is refused (`live-pending`: issue it), and so is one whose scope and
|
|
1500
|
+
address already hold a pending invitation (`pending-held`). **An imported
|
|
1501
|
+
record has no usable code**: it is listed and counted, never previewed or
|
|
1502
|
+
accepted. Concurrent runs may both report `inserted`. With
|
|
1503
|
+
`@softistx/janus-mongo`, keep the history past its TTL with the sync's
|
|
1504
|
+
`keepAccepted`, `keepRevoked` and `keepLapsed`; `deleteExpiredInvitations` of
|
|
1505
|
+
`@softistx/janus-drizzle` deletes every status, so do not call it unscoped.
|
|
1506
|
+
[Migrating invitations](docs/guide/migrating-invitations.md) walks through it.
|
|
1507
|
+
|
|
1508
|
+
Traps: **authorise the inviter yourself**; **rate-limit `preview` and `accept`**,
|
|
1509
|
+
janus does not; **a GET on the accept page must spend nothing**, mail scanners
|
|
1510
|
+
open links; **the accept page must handle `signIn`**, after an error too; and
|
|
1511
|
+
`INVITATION_INVALID` is one code for an unknown, accepted, revoked and lapsed
|
|
1512
|
+
code, with `error.reason` (`unknown`, `expired`, `accepted`, `revoked`). [The invitations guide](docs/guide/invitations.md) has every option, the
|
|
1513
|
+
e-mail recipe and every error.
|
|
1514
|
+
|
|
1515
|
+
### Devices — `devices`
|
|
1516
|
+
|
|
1517
|
+
```ts
|
|
1518
|
+
import { z } from 'zod';
|
|
1519
|
+
import { createMemoryStores, janus, scryptHasher } from '@softistx/janus';
|
|
1520
|
+
|
|
1521
|
+
const auth = janus({
|
|
1522
|
+
user: z.object({ email: z.email() }),
|
|
1523
|
+
password: { login: 'email' },
|
|
1524
|
+
store: createMemoryStores(),
|
|
1525
|
+
hasher: scryptHasher(),
|
|
1526
|
+
devices: { keys: [{ id: '2026-09', key: process.env.DEVICES_KEY ?? '' }] }, // openssl rand -base64 32
|
|
1527
|
+
});
|
|
1528
|
+
|
|
1529
|
+
// `cookie`: the device cookie the request carries — string | undefined
|
|
1530
|
+
const signedIn = await auth.signIn({ email, password }, { device: cookie ?? null });
|
|
1531
|
+
// { status: 'signedIn', user, session, token, newDevice, deviceToken }
|
|
1532
|
+
// keep signedIn.deviceToken in a long-lived HttpOnly cookie; newDevice: true sent user.newDeviceSignedIn
|
|
1533
|
+
```
|
|
1534
|
+
|
|
1535
|
+
A sign-in from a device the user had not signed in from is told apart, so
|
|
1536
|
+
you can tell the user. **Nothing is stored**: the client keeps a device
|
|
1537
|
+
token janus signs, and presents it at its next sign-in.
|
|
1538
|
+
|
|
1539
|
+
- **`{ device }` is the last argument** of `signUp`, `signIn`,
|
|
1540
|
+
`secondFactor.confirm`, `secondFactor.recover`, `signInCode.confirm` and
|
|
1541
|
+
`magicLink.confirm` — a `SignInOptions`: the token the client holds, or
|
|
1542
|
+
`null` when it holds none. **Absent, the call is not tracked**:
|
|
1543
|
+
`newDevice: false`, `deviceToken: null`, no event.
|
|
1544
|
+
- **Every answer that opens a session carries `newDevice` and
|
|
1545
|
+
`deviceToken`.** `signUp` mints the first token and is never new. A
|
|
1546
|
+
malformed, forged or another user's token is a new device, never an error.
|
|
1547
|
+
- **`user.newDeviceSignedIn`** is sent for a new device, once the sign-in is
|
|
1548
|
+
complete, with the new session's `sessionId`.
|
|
1549
|
+
- **`devices: { keys }`** — a `DevicesConfig` — wires it; the keys take
|
|
1550
|
+
`secondFactor.keys`' format. The first signs,
|
|
1551
|
+
every one checks: a token signed by an older key is known, and handed back
|
|
1552
|
+
signed with the first. **Removing a key is the only way to forget devices,
|
|
1553
|
+
and it forgets every device that key signed.**
|
|
1554
|
+
|
|
1555
|
+
[`@softistx/janus-mail`](https://github.com/softistx/nxgt-janus/tree/develop/packages/janus-mail)'s
|
|
1556
|
+
`newSignIn` sends the notice, and
|
|
1557
|
+
[`@softistx/janus-hono`](https://github.com/softistx/nxgt-janus/tree/develop/packages/janus-hono)'s
|
|
1558
|
+
`deviceOf` and `sendSession` keep the cookie.
|
|
1559
|
+
`@softistx/janus` itself exports the cookie they share: `deviceFromCookieHeader(header, options?)`
|
|
1560
|
+
answers the token a `Cookie` header holds (or `null`), `deviceCookie(token, options?)` the
|
|
1561
|
+
`Set-Cookie` value that sets it, with `DEVICE_COOKIE` (`'janus-device'`) and `DeviceCookieOptions`:
|
|
1562
|
+
|
|
1563
|
+
```ts
|
|
1564
|
+
headers.append('Set-Cookie', deviceCookie(signedIn.deviceToken)); // 400 days, HttpOnly, Secure, Lax
|
|
1565
|
+
const device = deviceFromCookieHeader(request.headers.get('cookie')); // string | null
|
|
1566
|
+
```
|
|
1567
|
+
|
|
1568
|
+
[The devices guide](docs/guide/devices.md) has the cookie, the second
|
|
1569
|
+
factor, the e-mail, key rotation, every error and a test.
|
|
1570
|
+
|
|
1571
|
+
### Avatars — `avatar`
|
|
1572
|
+
|
|
1573
|
+
Janus stores **only the id** your application chose for a user's avatar —
|
|
1574
|
+
never the image. Upload the bytes to your own storage under a **fresh id**,
|
|
1575
|
+
then point the user at it:
|
|
1576
|
+
|
|
1577
|
+
```ts
|
|
1578
|
+
const auth = janus({
|
|
1579
|
+
...config,
|
|
1580
|
+
// Once the record points at the new image, delete the one it let go.
|
|
1581
|
+
async events(event) {
|
|
1582
|
+
if (
|
|
1583
|
+
(event.type === 'user.avatarChanged' || event.type === 'user.avatarRemoved') &&
|
|
1584
|
+
event.formerAvatarId != null
|
|
1585
|
+
) {
|
|
1586
|
+
await store.remove({ imageId: event.formerAvatarId });
|
|
1587
|
+
}
|
|
1588
|
+
},
|
|
1589
|
+
});
|
|
1590
|
+
|
|
1591
|
+
const id = crypto.randomUUID(); // a fresh id for every upload
|
|
1592
|
+
await store.replace({ imageId: id }, bytes); // the bytes first …
|
|
1593
|
+
const user = await auth.avatar.set(userId, { id }); // … then the record
|
|
1594
|
+
user.avatar; // { id, updatedAt }
|
|
1595
|
+
|
|
1596
|
+
await auth.avatar.remove(userId); // user.avatar is null
|
|
1597
|
+
```
|
|
1598
|
+
|
|
1599
|
+
`store` is your image storage (`store.replace`, `store.remove` and
|
|
1600
|
+
`store.bytes` are the names [the guide](docs/guide/avatars.md) uses). `avatar`
|
|
1601
|
+
is on every user type: `auth.avatar` in the single-type form, `auth.patient.avatar`
|
|
1602
|
+
with several types, and with several types at the root too — `auth.avatar.set(userId,
|
|
1603
|
+
{ id })` finds the user's type from the record, for a page that holds only an
|
|
1604
|
+
id. Its type is `AvatarApi`, and `user.avatar` is a `UserAvatar | null`. The user comes back as `user.avatar`, from `get`, `find`, `getUser` and
|
|
1605
|
+
`findUser` alike.
|
|
1606
|
+
|
|
1607
|
+
| Call | Does | Rejects with |
|
|
1608
|
+
| --- | --- | --- |
|
|
1609
|
+
| `avatar.set(user, { id }, { ifVersion? })` | writes `{ id, updatedAt: now }` and answers the user; the id the user already has writes and sends nothing; else sends `user.avatarChanged` with `formerAvatarId` | `AVATAR_ID_INVALID` before anything is read, `NOT_FOUND`, `VERSION_CONFLICT` |
|
|
1610
|
+
| `avatar.remove(user, { ifVersion? })` | writes `null` and answers the user; a user with none writes and sends nothing; else sends `user.avatarRemoved` with `formerAvatarId` | `NOT_FOUND`, `VERSION_CONFLICT` |
|
|
1611
|
+
|
|
1612
|
+
The `id` is a non-empty string of at most 512 characters that every store can keep; janus never parses
|
|
1613
|
+
it. The name `avatar` can no longer name a user type. The routes around it —
|
|
1614
|
+
upload, remove, a proxy that streams the image behind your session, and who
|
|
1615
|
+
may see it — are in [the avatars guide](docs/guide/avatars.md).
|
|
1616
|
+
|
|
1617
|
+
### Social sign-in — `social`
|
|
1618
|
+
|
|
1619
|
+
```ts
|
|
1620
|
+
import { z } from 'zod';
|
|
1621
|
+
import { createMemoryStores, janus, scryptHasher, type SocialProvider } from '@softistx/janus';
|
|
1622
|
+
|
|
1623
|
+
declare const google: SocialProvider; // a provider: yours, or the ready-made package (see the guide)
|
|
1624
|
+
|
|
1625
|
+
const auth = janus({
|
|
1626
|
+
user: z.object({ email: z.email(), name: z.string() }),
|
|
1627
|
+
password: { login: 'email' },
|
|
1628
|
+
store: createMemoryStores(),
|
|
1629
|
+
hasher: scryptHasher(),
|
|
1630
|
+
social: {
|
|
1631
|
+
providers: { google },
|
|
1632
|
+
signUp: (profile) => ({ email: profile.email ?? '', name: profile.name ?? 'Unnamed' }), // omit it: a stranger is SIGN_UP_DISABLED
|
|
1633
|
+
},
|
|
1634
|
+
});
|
|
1635
|
+
|
|
1636
|
+
// GET /auth/google — send the visitor to the provider, with the flow in an HttpOnly cookie
|
|
1637
|
+
const start = await auth.social.start({ provider: 'google', returnTo: '/dashboard' });
|
|
1638
|
+
const redirect = new Headers({ location: start.url });
|
|
1639
|
+
redirect.append('set-cookie', start.setCookie);
|
|
1640
|
+
|
|
1641
|
+
// GET /auth/google/callback — the provider sends the visitor back
|
|
1642
|
+
const flow = (request.headers.get('cookie') ?? '').match(/(?:^|; )(?:__Host-)?janus-social-flow=([^;]*)/)?.[1] ?? '';
|
|
1643
|
+
const done = await auth.social.complete({ callback: new URL(request.url).searchParams, flow });
|
|
1644
|
+
const headers = new Headers({ location: done.returnTo ?? '/' });
|
|
1645
|
+
headers.append('set-cookie', auth.social.cookie.clear()); // the flow is spent: clear its cookie
|
|
1646
|
+
if (done.status === 'signedIn') headers.append('set-cookie', auth.cookie.serialize(done.token, done.session));
|
|
1647
|
+
// done.status 'secondFactor': keep done.challenge, then auth.secondFactor.confirm
|
|
1648
|
+
|
|
1649
|
+
// Linking another account to a signed-in user, behind a fresh session
|
|
1650
|
+
const current = await auth.authenticate(request); // Authenticated | null
|
|
1651
|
+
if (current !== null) {
|
|
1652
|
+
await auth.social.link(current, { provider: 'google', returnTo: '/settings' }); // answers like start: redirect, with its setCookie
|
|
1653
|
+
// … the callback: auth.social.complete({ callback, flow, current }) → { status: 'linked', link, … }
|
|
1654
|
+
}
|
|
1655
|
+
|
|
1656
|
+
await auth.social.list(user); // SocialLink[], oldest first
|
|
1657
|
+
await auth.social.unlink(user, { provider: 'google', accountId }); // true | false; LAST_SIGN_IN_METHOD when it is the only way in
|
|
1658
|
+
isReturnTo('/billing'); // true; false for '//x', '/.//x', 'https://x': the check start() applies, to run again before a redirect
|
|
1659
|
+
```
|
|
1660
|
+
|
|
1661
|
+
The core does **no HTTP and knows no protocol**: a provider is an object with
|
|
1662
|
+
two calls, `authorizationUrl` and `exchange`, the `SocialProvider` interface.
|
|
1663
|
+
Ready-made providers (Google, GitHub, Microsoft, any OpenID Connect or OAuth 2.0
|
|
1664
|
+
one) come in `@softistx/janus-social`; to write your own, implement the
|
|
1665
|
+
interface (the guide has a skeleton and a fake for tests). `state`, `nonce` and the PKCE verifier are derived from a secret the
|
|
1666
|
+
core keeps, so the provider only checks them.
|
|
1667
|
+
|
|
1668
|
+
```ts
|
|
1669
|
+
interface SocialFlowStart { readonly url: string; readonly flow: string; readonly expiresAt: Date; readonly setCookie: string }
|
|
1670
|
+
type SocialCompleted<U, Challenge extends SecondFactorRequired = SecondFactorRequired> =
|
|
1671
|
+
| (SignedIn<U> & { provider: string; created: boolean; linked: boolean; returnTo: string | null; stepUp: SocialStepUpProof | null })
|
|
1672
|
+
| (Challenge & { provider: string; returnTo: string | null; stepUp: SocialStepUpProof | null })
|
|
1673
|
+
| SocialLinked<U>;
|
|
1674
|
+
interface SocialLinked<U> { status: 'linked'; user: U; link: SocialLink; returnTo: string | null; stepUp: SocialStepUpProof | null }
|
|
1675
|
+
interface SocialStepUpProof { acrValues: readonly string[] | null; maxAge: number | null; acr: string | null; authTime: Date | null }
|
|
1676
|
+
interface SocialLink { provider: string; accountId: string; email: string | null; linkedAt: Date }
|
|
1677
|
+
```
|
|
1678
|
+
|
|
1679
|
+
- **`social: { providers?, resolveProvider?, signUp?, freshWithin? }`** (one of `providers` and `resolveProvider` required) on a user type
|
|
1680
|
+
(`users: { patient: { schema, social } }` for several). `providers` maps the
|
|
1681
|
+
application's name for each provider (lowercase letters, digits and `-`,
|
|
1682
|
+
starting with a letter, at most 32) to its `SocialProvider`. `resolveProvider(name)` (`SocialProviderResolver`, answering `Promise<SocialProvider | null>`)
|
|
1683
|
+
looks up a provider kept outside the configuration, at `start`, `link` and
|
|
1684
|
+
`complete`: a name in `providers` (of any user type) wins, a name that fails the pattern never
|
|
1685
|
+
reaches it, `null` is `SOCIAL_PROVIDER_UNKNOWN`, a throw propagates untouched
|
|
1686
|
+
(see the social guide). `providers` may then be left out. `signUp(profile)`
|
|
1687
|
+
answers the fields of a new user, whose e-mail must be the provider's; absent or
|
|
1688
|
+
`false`, a stranger is refused. `freshWithin` (`'10m'`) is how recent the
|
|
1689
|
+
session must be to `link`. `tokens: { socialFlow }` (`'10m'`) is how long a
|
|
1690
|
+
flow waits for its callback. The store needs the `socialLinks` slot.
|
|
1691
|
+
- **`social.start`** answers `{ url, flow, expiresAt, setCookie }`; `type` is
|
|
1692
|
+
needed only when several user types configure `social`. `returnTo` must be a
|
|
1693
|
+
path of your site, else `RETURN_TO_INVALID`. `stepUp: { acrValues?, maxAge? }`
|
|
1694
|
+
(also on `social.link`) asks the provider for a stronger or more recent
|
|
1695
|
+
sign-in on this flow: the provider opts in with `supportsStepUp` (else a
|
|
1696
|
+
`TypeError`), the core checks the `acr` and `authTime` the identity reports
|
|
1697
|
+
on its own clock, and a flow that does not prove it is
|
|
1698
|
+
`SOCIAL_STEP_UP_UNMET`. Every `social.complete` answer carries `stepUp`: the
|
|
1699
|
+
proof, or `null` for a plain flow. See
|
|
1700
|
+
[step-up per request](docs/guide/social.md#step-up-per-request).
|
|
1701
|
+
- **Writing a provider that supports it**: set `SocialProvider.supportsStepUp`,
|
|
1702
|
+
read `flow.stepUp` (`SocialStepUpRequest | null`) on `authorizationUrl` and
|
|
1703
|
+
`exchange`, and report `SocialIdentity.acr` / `authTime`; the option type is
|
|
1704
|
+
`SocialStepUp`. Details in [the guide](docs/guide/social.md#step-up-per-request).
|
|
1705
|
+
- **`social.complete({ callback, flow, current?, purpose? }, options?)`** takes the
|
|
1706
|
+
callback's query parameters and the cookie's value (`purpose`: `'signIn'` or
|
|
1707
|
+
`'link'`, the kind of flow the endpoint accepts, else `FLOW_PURPOSE_MISMATCH`;
|
|
1708
|
+
see [social sign-in](docs/guide/social.md)), and answers
|
|
1709
|
+
`signedIn` (`created`: a user was made; `linked`: this call linked the
|
|
1710
|
+
account), `secondFactor` (a challenge; same as `signIn`) or `linked`. It takes
|
|
1711
|
+
the `SignInOptions` of every sign-in (`device`).
|
|
1712
|
+
- **Refusals**: `FLOW_EXPIRED`, `FLOW_MISMATCH`, `FLOW_PURPOSE_MISMATCH`,
|
|
1713
|
+
`RETURN_TO_INVALID`, `PROVIDER_ERROR`, `SOCIAL_PROVIDER_UNKNOWN`, `SOCIAL_STEP_UP_UNMET`, `SIGN_UP_DISABLED`,
|
|
1714
|
+
`EMAIL_NOT_VERIFIED_FOR_LINK`, `SOCIAL_ACCOUNT_TAKEN`, `LAST_SIGN_IN_METHOD`
|
|
1715
|
+
(all `SocialError`), and `EMAIL_UNVERIFIED`, `USER_INACTIVE` and
|
|
1716
|
+
`STEP_UP_REQUIRED` from the existing classes. See [Errors](#errors).
|
|
1717
|
+
- **Events**: `user.socialLinked` and `user.socialUnlinked`, carrying
|
|
1718
|
+
`provider`.
|
|
1719
|
+
- **Rate-limit the start route.** `social.start` is anonymous and writes a
|
|
1720
|
+
token per request, so anyone can fill the token store. Put a rate limit in
|
|
1721
|
+
front of it, for example with `@softistx/redis`.
|
|
1722
|
+
|
|
1723
|
+
[The social sign-in guide](docs/guide/social.md) has every case, the second
|
|
1724
|
+
factor, writing a provider, and a test with a fake one.
|
|
1725
|
+
|
|
1726
|
+
### User events — `events`
|
|
1727
|
+
|
|
1728
|
+
```ts
|
|
1729
|
+
import { z } from 'zod';
|
|
1730
|
+
import { createMemoryStores, janus, scryptHasher, type UserEvent } from '@softistx/janus';
|
|
1731
|
+
|
|
1732
|
+
const auth = janus({
|
|
1733
|
+
user: z.object({ email: z.email() }),
|
|
1734
|
+
password: { login: 'email' },
|
|
1735
|
+
store: createMemoryStores(),
|
|
1736
|
+
hasher: scryptHasher(),
|
|
1737
|
+
async events(event: UserEvent) {
|
|
1738
|
+
// { id, type: 'user.created', occurredAt, userId, userType }
|
|
1739
|
+
await queue.add(event.type, event, { jobId: event.id }); // deliver it once
|
|
1740
|
+
},
|
|
1741
|
+
});
|
|
1742
|
+
|
|
1743
|
+
await auth.signUp({ email, password }); // the listener has the event before this answers
|
|
1744
|
+
```
|
|
1745
|
+
|
|
1746
|
+
`janus({ events })` hears what happened to a user, once it is written:
|
|
1747
|
+
|
|
1748
|
+
| `type` | Sent by |
|
|
1749
|
+
| --- | --- |
|
|
1750
|
+
| `user.created` | `create`, `signUp` |
|
|
1751
|
+
| `user.emailVerified` | `verifyEmail.confirm` (with `{ firstProof: true }` it also drops a squatter's password and factor, like the next), `verifyEmail.proveFirst` and `setEmailVerified` (turning the flag on); `changeEmail.confirm`, `resetPassword.confirm`, `magicLink.confirm` and `signInCode.confirm`, whose link or code proves the e-mail too — never for an e-mail already verified |
|
|
1752
|
+
| `user.passwordReset` | `resetPassword.confirm` |
|
|
1753
|
+
| `user.passwordChanged` | `changePassword`, `setPassword` (`first: true` when the user had no password before — skip the "changed" notice); `signInCode.confirm`, `magicLink.confirm` and `verifyEmail.proveFirst` when their first proof of the e-mail dropped a password — never a reset, which is `user.passwordReset` alone |
|
|
1754
|
+
| `user.emailChanged` | `update` and `changeEmail.confirm`, when they changed the e-mail — carrying `formerEmail`, the address before (`null` for none) |
|
|
1755
|
+
| `user.secondFactorEnabled` | `secondFactor.activate`, once the factor is active — not `enroll`, which leaves it waiting |
|
|
1756
|
+
| `user.secondFactorDisabled` | `secondFactor.disable`, when it removed an active factor; `signInCode.confirm`, `magicLink.confirm` and `verifyEmail.proveFirst` when their first proof of the e-mail removed one, after `user.emailVerified` and any `user.passwordChanged` — never for a user who had none, or one still waiting |
|
|
1757
|
+
| `user.recoveryCodesRegenerated` | `secondFactor.regenerateRecoveryCodes` — not `activate`, whose codes come with `user.secondFactorEnabled` |
|
|
1758
|
+
| `user.recoveryCodeUsed` | `secondFactor.recover`, once the recovery code is spent: a sign-in without the user's phone |
|
|
1759
|
+
| `user.newDeviceSignedIn` | `signIn`, `secondFactor.confirm`, `secondFactor.recover`, `signInCode.confirm` and `magicLink.confirm`, given a `device` its token did not prove, once the sign-in is complete — carrying `sessionId`, the new session's. Never `signUp`, nor a call given no device |
|
|
1760
|
+
| `user.avatarChanged` | `avatar.set`, when it wrote a different id — carrying `formerAvatarId`, the id replaced (`null` for a first avatar) |
|
|
1761
|
+
| `user.avatarRemoved` | `avatar.remove`, when the user had one — carrying `formerAvatarId` |
|
|
1762
|
+
| `user.socialLinked` | `social.complete`, when it linked an account: a link flow, a user matched by a verified e-mail, or the user a social sign-up created — carrying `provider`. Not for an account already linked to that user |
|
|
1763
|
+
| `user.socialUnlinked` | `social.unlink`, when it deleted a link — carrying `provider` |
|
|
1764
|
+
| `user.passkeyAdded` | `passkeys.register`, once the passkey is stored — carrying `passkey: { credentialId, name }` |
|
|
1765
|
+
| `user.passkeyRemoved` | `passkeys.remove`, when it deleted a passkey; `secondFactor.disable`, once per passkey it removed with the factor — carrying `passkey` |
|
|
1766
|
+
| `user.passkeyCloneSuspected` | `secondFactor.confirmPasskey` or `stepUp.confirmPasskey`, when an assertion's counter did not move forward (both counters non-zero) — carrying `passkey`; the call is refused and the passkey stays active |
|
|
1767
|
+
| `user.apiKeyCreated` | `apiKeys.create`, once the key is stored |
|
|
1768
|
+
| `user.apiKeyRevoked` | every call that revoked keys (`apiKeys.revoke`, `revokeAll`, `revokeAllBound`, a password reset, the first proof of an e-mail) — **one event per call**, carrying `count`; none when it revoked nothing |
|
|
1769
|
+
| `user.deleted` | `delete`, once — a replay that deletes nobody sends nothing |
|
|
1770
|
+
|
|
1771
|
+
- **The user is named by id, and nothing else**: no login, no field, no
|
|
1772
|
+
password, no token. Whoever receives the event reads the rest from where it
|
|
1773
|
+
is kept, if they may. Four exceptions: `user.emailChanged` carries
|
|
1774
|
+
`formerEmail`, which nothing keeps once the write landed, so a notice can
|
|
1775
|
+
reach the inbox the account just left; `user.newDeviceSignedIn`
|
|
1776
|
+
carries `sessionId`, the session the new device holds; the two avatar
|
|
1777
|
+
events carry `formerAvatarId`, the image the write let go; and the two social
|
|
1778
|
+
events carry `provider`, the application's name for it — never the account's id.
|
|
1779
|
+
`@softistx/janus-webhooks` posts none of them.
|
|
1780
|
+
- **Each event has an `id` of its own**, a UUIDv7: the key to deliver it once.
|
|
1781
|
+
- **The listener runs after the write, and is awaited** before the
|
|
1782
|
+
flow answers, so a durable queue has the event by then. `occurredAt` is the
|
|
1783
|
+
write's own time. A refused flow sends nothing.
|
|
1784
|
+
- **Typed**: `events` is a `UserEventListener`; `UserEventType` is the closed
|
|
1785
|
+
union of the twenty types, so a `switch` on `event.type` is exhaustive —
|
|
1786
|
+
and a new type, like the two recovery-code ones in 0.10, the two change
|
|
1787
|
+
ones in 0.14, `user.newDeviceSignedIn` in 0.17, the two avatar ones in 0.29 or
|
|
1788
|
+
the two social ones in 0.38,
|
|
1789
|
+
breaks it until handled.
|
|
1790
|
+
- **A listener that throws fails no flow** — the write happened. It is a
|
|
1791
|
+
`JANUS_EVENT_FAILED` warning naming the event's type, its id and the user's
|
|
1792
|
+
id, never the failure's message.
|
|
1793
|
+
|
|
1794
|
+
To tell the user their password or e-mail changed, their second factor was
|
|
1795
|
+
turned on or off, that a recovery code was used, or that a new device signed
|
|
1796
|
+
in, send
|
|
1797
|
+
[`@softistx/janus-mail`](https://github.com/softistx/nxgt-janus/tree/develop/packages/janus-mail)'s notice
|
|
1798
|
+
from the listener — or from a queue it feeds:
|
|
1799
|
+
|
|
1800
|
+
```ts
|
|
1801
|
+
// `mail` is janusMail({ … }), and the user schema holds a name and a locale.
|
|
1802
|
+
async events(event) {
|
|
1803
|
+
if (event.type === 'user.emailChanged' && event.formerEmail != null) {
|
|
1804
|
+
const user = await auth.get(event.userId);
|
|
1805
|
+
// To the former address: the new one belongs to whoever changed it.
|
|
1806
|
+
await mail.emailChanged({ name: user.name, locale: user.locale, formerEmail: event.formerEmail, newEmail: user.email });
|
|
1807
|
+
}
|
|
1808
|
+
if (event.type === 'user.secondFactorDisabled') {
|
|
1809
|
+
const user = await auth.get(event.userId);
|
|
1810
|
+
await mail.twoFactorDisabled({ name: user.name, locale: user.locale, email: user.email });
|
|
1811
|
+
}
|
|
1812
|
+
if (event.type === 'user.recoveryCodeUsed') {
|
|
1813
|
+
const user = await auth.get(event.userId);
|
|
1814
|
+
const recoveryCodesLeft = await auth.secondFactor.recoveryCodesLeft(user); // the event has the id only
|
|
1815
|
+
if (recoveryCodesLeft === null) return; // the factor was turned off since
|
|
1816
|
+
const when = new Intl.DateTimeFormat(user.locale, { dateStyle: 'long', timeStyle: 'short', timeZone }).format(
|
|
1817
|
+
event.occurredAt,
|
|
1818
|
+
); // timeZone: the user's, from your own data
|
|
1819
|
+
await mail.recoveryCodeUsed({ name: user.name, locale: user.locale, email: user.email }, { when, recoveryCodesLeft });
|
|
1820
|
+
}
|
|
1821
|
+
},
|
|
1822
|
+
```
|
|
1823
|
+
|
|
1824
|
+
To post them as signed webhooks:
|
|
1825
|
+
[`@softistx/janus-webhooks`](https://github.com/softistx/nxgt-janus/tree/develop/packages/janus-webhooks).
|
|
1826
|
+
[The user events guide](docs/guide/events.md) has the listener, the twenty
|
|
1827
|
+
types, mail for a recovery code used or a password or e-mail changed, what a failure costs, and a test.
|
|
1828
|
+
|
|
1829
|
+
### Permissions — `@softistx/janus/permissions`
|
|
1830
|
+
|
|
1831
|
+
```ts
|
|
1832
|
+
import { defineModel, fromField, when, permissions, createMemoryRelations } from '@softistx/janus/permissions';
|
|
1833
|
+
|
|
1834
|
+
export const model = defineModel({
|
|
1835
|
+
subjects: clinic.types, // 'patient' | 'staff': a user type is a subject type
|
|
1836
|
+
types: {
|
|
1837
|
+
team: {
|
|
1838
|
+
related: { members: ['staff', 'team#members'], leads: ['staff'] },
|
|
1839
|
+
permits: { manage: ['leads'], view: ['members', 'manage'] },
|
|
1840
|
+
},
|
|
1841
|
+
record: {
|
|
1842
|
+
related: {
|
|
1843
|
+
doctors: fromField('doctorId', 'staff', { lookup: (staffId) => db.records.idsByDoctor(staffId) }),
|
|
1844
|
+
patients: fromField('patientId', 'patient', { lookup: (patientId) => db.records.idsByPatient(patientId) }),
|
|
1845
|
+
teams: ['team'],
|
|
1846
|
+
},
|
|
1847
|
+
permits: {
|
|
1848
|
+
view: ['doctors', 'patients', 'teams->view'],
|
|
1849
|
+
review: ['teams->leads'],
|
|
1850
|
+
edit: [when('doctors', (ctx: { onShift: boolean }) => ctx.onShift)],
|
|
1851
|
+
},
|
|
1852
|
+
},
|
|
1853
|
+
},
|
|
1854
|
+
});
|
|
1855
|
+
|
|
1856
|
+
// staff: a user from clinic.staff; record: a row carrying doctorId and patientId.
|
|
1857
|
+
const access = permissions({ model, store: createMemoryRelations() });
|
|
1858
|
+
await access.grant({ type: 'team', id: 't1' }, 'members', staff);
|
|
1859
|
+
await access.can(staff, 'edit', { type: 'record', ...record }, { ctx: { onShift } }); // boolean
|
|
1860
|
+
await access.list(staff, 'view', 'record', { limit: 50 }); // CursorPage<string>; view reaches no condition
|
|
1861
|
+
await access.revoke({ type: 'team', id: 't1' }, 'members', staff); // idempotent
|
|
1862
|
+
```
|
|
1863
|
+
|
|
1864
|
+
Zanzibar's model — relations between objects and subjects, permissions
|
|
1865
|
+
computed from them — **without its infrastructure**: the tuples live in your
|
|
1866
|
+
database, so a read follows a write and there is nothing to cache or to
|
|
1867
|
+
sequence. An object type declares its relations under `related` and its
|
|
1868
|
+
permissions under `permits` — Keto's words — and relation names are plural by convention (`defineModel`
|
|
1869
|
+
does not enforce it).
|
|
1870
|
+
Subject sets (`'team#members'`), arrows (`'teams->view'`: whoever can view one
|
|
1871
|
+
of the record's teams; `'teams->leads'`: whoever leads one) and permissions
|
|
1872
|
+
naming permissions are Zanzibar's. Two things are not:
|
|
1873
|
+
|
|
1874
|
+
- **`fromField`** reads a relation from the object's own data — a record's
|
|
1875
|
+
`doctorId` — instead of a tuple kept in sync with it. `can()` is given the
|
|
1876
|
+
object, and the compiler requires every field a `fromField` of its type
|
|
1877
|
+
reads. `list()` cannot read a field of objects it has not found, so it asks
|
|
1878
|
+
the `lookup`;
|
|
1879
|
+
- **`when`** puts a condition written in TypeScript on a rule. Its `ctx` is
|
|
1880
|
+
what `can()` and `list()` then require — and only for the permissions whose
|
|
1881
|
+
rules reach it.
|
|
1882
|
+
|
|
1883
|
+
**A denial is `false`, a failure throws.** A relation store that cannot answer
|
|
1884
|
+
is `STORE_FAILED`; a walk that crosses more than `maxDepth` relations (`25`) is
|
|
1885
|
+
`PERMISSION_DEPTH`. Neither is ever `false`, which would deny everybody
|
|
1886
|
+
everything during an outage and say nothing. A cycle in the data — a team
|
|
1887
|
+
member of itself — is cut, and is not an error. `null` is anonymous: `false`,
|
|
1888
|
+
or an empty page, before any store call.
|
|
1889
|
+
|
|
1890
|
+
**Everything is typed from the model.** A relation naming a type that does not
|
|
1891
|
+
exist, a rule naming nothing, an arrow to a permission its target lacks, a
|
|
1892
|
+
permission asked of the wrong type, an object missing a field, a missing
|
|
1893
|
+
`ctx`, a `grant` of a relation read from a field or to a holder it does not
|
|
1894
|
+
admit, a subject set naming a relation its type lacks or a user type not
|
|
1895
|
+
declared under `types`, a `list()` through a `fromField` without a `lookup`: each is a compile
|
|
1896
|
+
error, on the offending argument. So are the keys before 0.2, `relations` and
|
|
1897
|
+
`permissions`: the error names the new one — `team.relations is now related:
|
|
1898
|
+
rename the key` — and `defineModel` refuses them the same way at run time. `defineModel` refuses with a `TypeError`
|
|
1899
|
+
what only running it can see: names that are not camelCase, a permission that
|
|
1900
|
+
reaches itself without crossing a relation, a subject set or an arrow that
|
|
1901
|
+
would have to read another object's field.
|
|
1902
|
+
|
|
1903
|
+
**A function of your own around `can()`** refuses the same mistakes through
|
|
1904
|
+
`Can<C>`, its signature, and `CheckArgs<C, T, P>`, its options argument —
|
|
1905
|
+
`ctx` required exactly when a `when` is reachable. Declare `T` and `P`
|
|
1906
|
+
`const`, or the permission widens and the `ctx` requirement is lost; the
|
|
1907
|
+
[permissions guide](docs/guide/permissions.md#a-function-of-your-own-around-can)
|
|
1908
|
+
has the example.
|
|
1909
|
+
|
|
1910
|
+
**Sync a relation to a wanted list with `replace`.** When the application
|
|
1911
|
+
holds the list a group's members should match, `replace(object, relation,
|
|
1912
|
+
subjects)` adds the missing holders and removes the others in one write, and
|
|
1913
|
+
answers the tuples added and the tuples removed:
|
|
1914
|
+
|
|
1915
|
+
```ts
|
|
1916
|
+
const wanted = await db.staff.membersOf('cardiology'); // your own source of truth
|
|
1917
|
+
const { added, removed } = await access.replace({ type: 'team', id: 'cardiology' }, 'members', wanted); // RelationTuple[] each
|
|
1918
|
+
await access.replace({ type: 'team', id: 'cardiology' }, 'members', []); // empties the group
|
|
1919
|
+
```
|
|
1920
|
+
|
|
1921
|
+
The subjects are typed as `grant`'s is, as an array, and every one is checked
|
|
1922
|
+
before anything is read, so a refusal writes nothing. Duplicates count once,
|
|
1923
|
+
holders already right are not written (no write at all when nothing changes),
|
|
1924
|
+
and a subject set is not its entity. Other relations and objects are untouched.
|
|
1925
|
+
**Two concurrent `replace` calls on one object and relation are not
|
|
1926
|
+
serialised**: each reads, then writes its diff, so the result can hold the
|
|
1927
|
+
union of both adds — serialise them yourself when one must win. A relation
|
|
1928
|
+
store must answer every holder of a relation to `findEntities` and
|
|
1929
|
+
`findSubjectSets`, since `replace` reads them all; the
|
|
1930
|
+
[permissions guide](docs/guide/permissions.md#replace) has the details.
|
|
1931
|
+
|
|
1932
|
+
To list who holds a relation, by pages and with a search, use `holders` — the
|
|
1933
|
+
`@softistx/janus-mongo` and `@softistx/janus-drizzle` stores page it in the database:
|
|
1934
|
+
|
|
1935
|
+
```ts
|
|
1936
|
+
const page = await access.holders({ type: 'platform', id: 'main' }, 'admins', { first: 20, search: 'ada' });
|
|
1937
|
+
const next = await access.holders({ type: 'platform', id: 'main' }, 'admins', { first: 20, after: page.nextCursor });
|
|
1938
|
+
```
|
|
1939
|
+
|
|
1940
|
+
A filter on what the relation store cannot see is `matches` (one holder) or
|
|
1941
|
+
`matchesMany` (a batch of up to 100, so one user query per page); a call looks
|
|
1942
|
+
at most `scanLimit` holders (500 by default), then answers what it kept with a
|
|
1943
|
+
`nextCursor` to resume, so a page can hold fewer than `first`. Follow
|
|
1944
|
+
`nextCursor` until it is `null`.
|
|
1945
|
+
|
|
1946
|
+
```ts
|
|
1947
|
+
const page = await access.holders(platform, 'admins', {
|
|
1948
|
+
first: 20,
|
|
1949
|
+
scanLimit: 200,
|
|
1950
|
+
matchesMany: async (hs) => {
|
|
1951
|
+
const found = await users.findMany(hs.map((h) => h.id));
|
|
1952
|
+
return hs.map((h) => found.some((u) => u.id === h.id && u.active));
|
|
1953
|
+
},
|
|
1954
|
+
});
|
|
1955
|
+
```
|
|
1956
|
+
|
|
1957
|
+
The [permissions guide](docs/guide/permissions.md#holders) has the options.
|
|
1958
|
+
|
|
1959
|
+
**A user type may also be an object type**: declare `staff` under `types`, and
|
|
1960
|
+
a staff member is an object too — who may edit them is a relation on them. See
|
|
1961
|
+
[permissions on a user](docs/guide/permissions.md#permissions-on-a-user).
|
|
1962
|
+
|
|
1963
|
+
**Wire the relation store into `janus()` too** — `janus({ …, relations })` —
|
|
1964
|
+
and deleting a user deletes every tuple naming them. Deleting an object's
|
|
1965
|
+
tuples is `store.deleteEntity({ type, id })`, from your own code.
|
|
1966
|
+
|
|
1967
|
+
The port is `RelationStore`: six methods answering one-hop questions about
|
|
1968
|
+
stored tuples (`write`, `has`, `findSubjectSets`, `findEntities`,
|
|
1969
|
+
`findObjects`, `deleteEntity`). The traversal is the core's, written once.
|
|
1970
|
+
|
|
1971
|
+
### Testing — `@softistx/janus/testing`
|
|
1972
|
+
|
|
1973
|
+
```ts
|
|
1974
|
+
import { totpCode } from '@softistx/janus/testing';
|
|
1975
|
+
|
|
1976
|
+
// `auth` is your janus({ secondFactor, clock }) under test, `user` a signed-up
|
|
1977
|
+
// user, `clock` the fixedClock you passed to janus().
|
|
1978
|
+
const { secret } = await auth.secondFactor.enroll(user);
|
|
1979
|
+
await auth.secondFactor.activate(user, totpCode(secret, clock.now()));
|
|
1980
|
+
```
|
|
1981
|
+
|
|
1982
|
+
`totpCode(secret, at?)` is RFC 6238 as an authenticator app computes it
|
|
1983
|
+
(HMAC-SHA-1, six digits, thirty seconds); `at` defaults to now. A secret that
|
|
1984
|
+
is not base32, or an invalid `at`, throws a `TypeError`. The
|
|
1985
|
+
[second-factor guide](docs/guide/second-factor.md#in-a-test) has a full test.
|
|
1986
|
+
|
|
1987
|
+
### Conformance — `@softistx/janus/conformance`
|
|
1988
|
+
|
|
1989
|
+
If you write an adapter, you run this suite against it:
|
|
1990
|
+
|
|
1991
|
+
```ts
|
|
1992
|
+
import { describe, it } from 'bun:test';
|
|
1993
|
+
import { describeJanusStores } from '@softistx/janus/conformance';
|
|
1994
|
+
|
|
1995
|
+
describeJanusStores({
|
|
1996
|
+
name: 'my adapter',
|
|
1997
|
+
runner: { describe, it },
|
|
1998
|
+
harness: {
|
|
1999
|
+
async open() {
|
|
2000
|
+
const db = await freshDatabase(); // one per case, never shared
|
|
2001
|
+
return {
|
|
2002
|
+
stores: myStores(db),
|
|
2003
|
+
faults: { fail: (slot, method) => db.failNext(method) },
|
|
2004
|
+
close: () => db.drop(),
|
|
2005
|
+
};
|
|
2006
|
+
},
|
|
2007
|
+
},
|
|
2008
|
+
});
|
|
2009
|
+
```
|
|
2010
|
+
|
|
2011
|
+
There are 101 cases. They cover:
|
|
2012
|
+
- round-trip, byte for byte — including every edge character the core lets
|
|
2013
|
+
through (control characters, U+FFFF, a surrogate pair);
|
|
2014
|
+
- uniqueness, as a constraint: of twenty concurrent inserts of one login,
|
|
2015
|
+
exactly one is accepted — and a login is unique per user type; the refusal
|
|
2016
|
+
carries the login in `error.login`, never in its message;
|
|
2017
|
+
- versions: a refused update writes nothing;
|
|
2018
|
+
- **omission**, named after the Kratos `PUT` trap;
|
|
2019
|
+
- pagination;
|
|
2020
|
+
- sessions: `reauthenticateSession` moves `authenticatedAt` (and replaces `amr` only when given) and nothing else,
|
|
2021
|
+
and never brings back a revoked session, even one revoked at the same
|
|
2022
|
+
moment; `revokeUserSessions` with `issuedBefore` revokes only the sessions
|
|
2023
|
+
created strictly before the cut-off (one created at it stands), with or
|
|
2024
|
+
without an `except`;
|
|
2025
|
+
- one-time tokens (a second-factor challenge keeps its optional `amr`): a token of every kind the port names is stored, counted
|
|
2026
|
+
and spent — a `CHECK` or an enum that forgot `stepUp`, `magicLink`, `changeEmail`, `socialFlow` or `passkeyRegistration` fails
|
|
2027
|
+
here — and neither a step-up nor a sign-in link is ever counted, spent nor
|
|
2028
|
+
answered as a sign-in code, nor an e-mail change as a verification; of twenty
|
|
2029
|
+
concurrent redemptions, exactly one succeeds; of twenty concurrent
|
|
2030
|
+
`countAttempt` calls, each answers a distinct count, and none is counted
|
|
2031
|
+
once a racing redemption spent the token;
|
|
2032
|
+
- spending a user's tokens of one kind — `spendUserTokens` — spends only the
|
|
2033
|
+
unspent ones of that user and kind, spares the one named by `except`, and
|
|
2034
|
+
never spends the same token as a racing redemption;
|
|
2035
|
+
- a second-factor challenge, whose address is `''`, kept, counted and spent;
|
|
2036
|
+
- a user's second factor: round-trip, kept by a patch that does not name it,
|
|
2037
|
+
removed by one that names `null`;
|
|
2038
|
+
- deletion: a user's logins are freed, and every session and token of theirs
|
|
2039
|
+
goes, with a replay answering `false` or `0` rather than failing;
|
|
2040
|
+
- the optional `users.findUsers`: each stored user once, whatever its type, an
|
|
2041
|
+
id nobody holds left out, and `[]` — never `null` — when nobody holds any;
|
|
2042
|
+
- the optional `tokens.deleteExpiredTokens`: lapsed tokens deleted, spent or
|
|
2043
|
+
not, and a token one millisecond short of lapsing kept, still spent when it
|
|
2044
|
+
was;
|
|
2045
|
+
- the optional `socialLinks` slot (8 cases, skipped with their reason when the
|
|
2046
|
+
stores lack it): a link round-trips verbatim, `Abc` and `abc` are two accounts,
|
|
2047
|
+
a pair is linked once (the second user is answered the holder's record and
|
|
2048
|
+
nothing is written; of twenty concurrent inserts, one is stored and all are
|
|
2049
|
+
answered it), a link is deleted only by its owner, and a user's links go
|
|
2050
|
+
together and are counted;
|
|
2051
|
+
- the optional `passkeys` slot (12 cases, skipped with their reason when the
|
|
2052
|
+
stores lack it): a passkey and its public key round-trip byte for byte, a
|
|
2053
|
+
credential is registered once (of twenty concurrent inserts, one is stored and
|
|
2054
|
+
all are answered it), a use is recorded only if the counter is still
|
|
2055
|
+
`ifCounter` (of twenty concurrent uses, one passes), rename and delete are
|
|
2056
|
+
owner-only, and a user's passkeys go together and are counted;
|
|
2057
|
+
- a social flow's token, kept apart from a verification;
|
|
2058
|
+
- **outages**, one case for each of the twenty-nine methods whose honest answer can
|
|
2059
|
+
be "nothing".
|
|
2060
|
+
|
|
2061
|
+
**An optional method a store lacks skips its cases, with the reason** — a
|
|
2062
|
+
store without `sessions.deleteExpiredSessions`, `tokens.deleteExpiredTokens`,
|
|
2063
|
+
`users.findUsers`, the whole `socialLinks` slot or the whole `passkeys` slot passes the suite. A case's `needs` names what it cannot run without, one `CaseNeed` or a list
|
|
2064
|
+
(`outage.findUsers` needs `['faults', 'findUsers']`).
|
|
2065
|
+
|
|
2066
|
+
The suite imports no test framework and no assertion library. It runs under
|
|
2067
|
+
`bun test`, vitest and jest. Its cases are also exported as data
|
|
2068
|
+
(`allCases`, or by store: `userStoreCases`, `sessionStoreCases`,
|
|
2069
|
+
`tokenStoreCases`, `socialLinkStoreCases`, `passkeyStoreCases`, `outageCases`), with `runCase` to run one without any
|
|
2070
|
+
runner. `skip: { [caseId]: reason }` skips a case and reports why;
|
|
2071
|
+
`SKIP_REASONS` holds the reasons the suite gives itself.
|
|
2072
|
+
|
|
2073
|
+
**`faults` is optional, and its absence is reported, never passed over.**
|
|
2074
|
+
Without it, the outage cases are skipped under the reason *"faults not
|
|
2075
|
+
provided: the outage invariant is not proven for this adapter"*. Make your database fail the way it
|
|
2076
|
+
really fails — for MongoDB, the `failCommand` failpoint with code 91. A wrapper
|
|
2077
|
+
that throws in front of your adapter proves the wrapper, not the adapter.
|
|
2078
|
+
Fail **only the method named**: `outage.write` reads the store back afterwards,
|
|
2079
|
+
to prove the rejected write changed nothing.
|
|
2080
|
+
|
|
2081
|
+
`referenceHarness()` runs the suite against the reference store, and is the
|
|
2082
|
+
example to copy.
|
|
2083
|
+
|
|
2084
|
+
A relation store has its own suite, `describeRelationStores({ name, harness })`
|
|
2085
|
+
— 16 cases: round-trip, a subject whose `relation` is `undefined` read as its
|
|
2086
|
+
entity, ids of edge characters kept exactly, absence, idempotent writes, a
|
|
2087
|
+
tuple stored once, one write's removals and additions applied together, the
|
|
2088
|
+
one-hop reads, the reverse index in pages, `deleteEntity`, and an outage for
|
|
2089
|
+
each of the six methods — a write that rejects must have changed nothing.
|
|
2090
|
+
`referenceRelationHarness()` is its example; `allRelationCases`,
|
|
2091
|
+
`relationStoreCases`, `relationOutageCases` and `runRelationCase` are the
|
|
2092
|
+
runner-less layer.
|
|
2093
|
+
|
|
2094
|
+
The API key store, `ApiKeyStore`, is a **separate, optional port**: no adapter
|
|
2095
|
+
has to implement it, and `JanusStores` does not change. Its suite is
|
|
2096
|
+
`describeApiKeyStores({ name, harness })` (`referenceApiKeyHarness()` is the
|
|
2097
|
+
example; `assertApiKeyStore` and `createMemoryApiKeys()` are its guard and
|
|
2098
|
+
reference store). Three capabilities are optional:
|
|
2099
|
+
`bound` (`listBoundApiKeys`, `revokeBoundApiKeys`; a store with it also keeps
|
|
2100
|
+
`scopes` and `bound` on the record), `userBound` (`listUserBoundApiKeys`, one
|
|
2101
|
+
method that needs `bound`: `list(user, { bound })` in one read, else the core
|
|
2102
|
+
reads the user's keys and filters) and `expiryNotice` (`listExpiringApiKeys`,
|
|
2103
|
+
`markApiKeyExpiryNotified`), typed `ApiKeyBoundMethods`,
|
|
2104
|
+
`ApiKeyUserBoundMethods` and `ApiKeyExpiryNoticeMethods` over `ApiKeyStoreBase`:
|
|
2105
|
+
an adapter with one writes `implements ApiKeyStore, ApiKeyBoundMethods`. Half a pair is refused; the suite skips the cases
|
|
2106
|
+
of a capability the store lacks, with its reason. The flows that use it are in
|
|
2107
|
+
the [API keys guide](./docs/guide/api-keys.md).
|
|
2108
|
+
|
|
2109
|
+
The invitation store, `InvitationStore`, is a separate, optional port in the
|
|
2110
|
+
same way. Its suite is `describeInvitationStores({ name, harness })`
|
|
2111
|
+
(`referenceInvitationHarness()` is the example; `assertInvitationStore` and
|
|
2112
|
+
`createMemoryInvitations()` are its guard and reference store). The flows that
|
|
2113
|
+
use it are in the [invitations guide](./docs/guide/invitations.md). A store may
|
|
2114
|
+
implement the optional `findPendingInvitation(scope, email)`; without it the
|
|
2115
|
+
core pages through the scope's pending invitations.
|
|
2116
|
+
|
|
2117
|
+
### Passkeys as a second factor, or the first
|
|
2118
|
+
|
|
2119
|
+
A passkey (a WebAuthn credential) is a second factor **beside TOTP, never
|
|
2120
|
+
instead of it**: only a user whose TOTP is active may register one — unless
|
|
2121
|
+
you opt in to `firstFactor: true` (below). The core
|
|
2122
|
+
makes the challenge and keeps the rules; a `PasskeyVerifier` — `simpleWebAuthnVerifier()`
|
|
2123
|
+
from `@softistx/janus-passkeys`, or your own — does the WebAuthn. Needs
|
|
2124
|
+
a store with the `passkeys` slot, and `secondFactor` unless `firstFactor: true`;
|
|
2125
|
+
a type refuses the configuration without them. A user who holds one can answer a sign-in's
|
|
2126
|
+
second factor with it (`secondFactor.confirmPasskey`) and confirm a step-up
|
|
2127
|
+
with it (`stepUp.request(user, { via: 'passkey' })`)
|
|
2128
|
+
([guide](docs/guide/passkeys.md)).
|
|
2129
|
+
|
|
2130
|
+
```ts
|
|
2131
|
+
import { simpleWebAuthnVerifier } from '@softistx/janus-passkeys';
|
|
2132
|
+
|
|
2133
|
+
const auth = janus({
|
|
2134
|
+
user, password: { login: 'email' }, store, hasher,
|
|
2135
|
+
secondFactor: { issuer: 'Clinic', keys },
|
|
2136
|
+
passkeys: {
|
|
2137
|
+
rpId: 'example.com', // a host: no scheme, port or path
|
|
2138
|
+
rpName: 'Clinic', // what the browser shows
|
|
2139
|
+
origins: ['https://app.example.com'], // https (http://localhost, http://*.localhost or http://127.0.0.1 in dev), on rpId
|
|
2140
|
+
// relatedOrigins: ['https://portal.customer.org'] origins on another host (https, no path); serve /.well-known/webauthn on the rpId host
|
|
2141
|
+
verifier: simpleWebAuthnVerifier(),
|
|
2142
|
+
// userVerification: 'preferred' | 'required' | 'discouraged' ('preferred')
|
|
2143
|
+
// freshWithin: '10m' how recent the session must be to register or remove
|
|
2144
|
+
// maxPerUser: 10 passkeys one user may hold
|
|
2145
|
+
// firstFactor: false true: a passkey alone signs in, see below
|
|
2146
|
+
},
|
|
2147
|
+
// tokens: { passkeyRegistration: '5m' } how long the challenge waits
|
|
2148
|
+
events, // user.passkeyAdded, user.passkeyRemoved, user.passkeyCloneSuspected
|
|
2149
|
+
});
|
|
2150
|
+
|
|
2151
|
+
const { options, challenge } = await auth.passkeys.registrationOptions(user); // options → navigator.credentials.create({ publicKey })
|
|
2152
|
+
// `response` is what navigator.credentials.create() resolved to, as JSON (PublicKeyCredential.toJSON()), sent by the page
|
|
2153
|
+
const passkey = await auth.passkeys.register(current, { challenge, response, name: 'Laptop' }); // fresh session
|
|
2154
|
+
await auth.passkeys.list(user); // Passkey[], oldest first — no public key, no counter
|
|
2155
|
+
await auth.passkeys.rename(user, passkey.credentialId, 'Work laptop'); // true | false
|
|
2156
|
+
await auth.passkeys.remove(current, passkey.credentialId); // true | false; fresh session
|
|
2157
|
+
|
|
2158
|
+
// Sign-in: `signIn` answers a challenge that says what can answer it.
|
|
2159
|
+
const result = await auth.signIn({ email, password });
|
|
2160
|
+
if (result.status === 'secondFactor') {
|
|
2161
|
+
result.methods; // ['totp'] or ['totp', 'passkey']
|
|
2162
|
+
result.passkeyOptions; // → navigator.credentials.get({ publicKey }); only with 'passkey'
|
|
2163
|
+
// `assertion` is what navigator.credentials.get() resolved to, as JSON, sent by the page
|
|
2164
|
+
const signedIn = await auth.secondFactor.confirmPasskey(result.challenge, assertion, { device });
|
|
2165
|
+
}
|
|
2166
|
+
|
|
2167
|
+
// Step-up: nothing is sent, the options come back.
|
|
2168
|
+
const issued = await auth.stepUp.request(user, { via: 'passkey' }); // { via: 'passkey', challenge, options, expiresAt, user }
|
|
2169
|
+
const session = await auth.stepUp.confirmPasskey(request, issued.challenge, assertion); // stamps the session
|
|
2170
|
+
```
|
|
2171
|
+
|
|
2172
|
+
**Passkey as the first factor (passwordless sign-in).** With
|
|
2173
|
+
`passkeys: { …, firstFactor: true }` (default `false`; `secondFactor` is optional
|
|
2174
|
+
with it, needed only for a TOTP) a user needs no TOTP to register a passkey, which is then asked
|
|
2175
|
+
discoverable with user verification required, and signs in with it alone:
|
|
2176
|
+
|
|
2177
|
+
```ts
|
|
2178
|
+
// 1. Anonymous: nothing says who the visitor is.
|
|
2179
|
+
const { options, challenge, expiresAt } = await auth.passkeys.signInOptions();
|
|
2180
|
+
// options -> navigator.credentials.get({ publicKey }); keep `challenge` with the visitor.
|
|
2181
|
+
|
|
2182
|
+
// 2. What the browser answered; the same result as a password sign-in.
|
|
2183
|
+
const { user, session, token } = await auth.passkeys.signIn(challenge, response, { device });
|
|
2184
|
+
```
|
|
2185
|
+
|
|
2186
|
+
A refused assertion is `CREDENTIALS_INVALID` with `reason: 'passkey'` (for
|
|
2187
|
+
your logs, never a body); a bad, spent or lapsed challenge is a `TOKEN_*` error; no TOTP is asked.
|
|
2188
|
+
`signInOptions` is anonymous and stores a token per call: rate-limit it. A type
|
|
2189
|
+
with an e-mail registers a passkey, beside a TOTP or as a first factor, only once
|
|
2190
|
+
the e-mail is verified (`EMAIL_UNVERIFIED`), so an address squatter holds none; the assertion must
|
|
2191
|
+
carry its user handle; and the two flows are on the type only with a literal
|
|
2192
|
+
`firstFactor: true`, which also types the whole `auth.passkeys` surface for a
|
|
2193
|
+
type with no password login. See the [guide](docs/guide/passkeys.md#passkey-as-the-first-factor).
|
|
2194
|
+
|
|
2195
|
+
The types are `PasskeySignInApi` (the `secondFactor.confirmPasskey` addition),
|
|
2196
|
+
`StepUpPasskeyApi` (the `stepUp.request(…, { via: 'passkey' })` and
|
|
2197
|
+
`stepUp.confirmPasskey` addition), `StepUpByPasskey` (what that request
|
|
2198
|
+
answers) and `SecondFactorMethod` (`'totp' | 'passkey'`, the items of
|
|
2199
|
+
`methods`); all exist only with the `passkeys` block.
|
|
2200
|
+
|
|
2201
|
+
The WebAuthn challenge is **an HMAC of the sign-in's (or step-up's) token
|
|
2202
|
+
secret**, derived per purpose from the sealing keys: nothing else is stored.
|
|
2203
|
+
`confirmPasskey` takes the same five attempts per challenge as `confirm` and
|
|
2204
|
+
`recover` — an assertion that does not verify, or names a credential that is
|
|
2205
|
+
not the user's, is `CODE_INVALID` with `attemptsLeft`, the fifth spends the
|
|
2206
|
+
challenge — and opens the session, with the same new-device handling. A counter
|
|
2207
|
+
of `0` (stored or received) is always accepted; a counter that did not move
|
|
2208
|
+
forward (both non-zero) is refused the same way **and** emits
|
|
2209
|
+
`user.passkeyCloneSuspected` — the passkey stays active. On success the
|
|
2210
|
+
passkey's `counter`, `backedUp` and `lastUsedAt` are updated.
|
|
2211
|
+
|
|
2212
|
+
`PASSKEY_INVALID` (400) is a response that does not verify (`reason` says why:
|
|
2213
|
+
`challenge`, `origin`, `rpId`, `signature`, …) or a name that is not 1 to 100
|
|
2214
|
+
characters (`field: 'name'`); `PASSKEY_TAKEN` (409) a credential already
|
|
2215
|
+
registered; `PASSKEY_LIMIT` (409) a user at `maxPerUser`. A user without an active TOTP gets `SECOND_FACTOR_NOT_ENROLLED` (unless `firstFactor` is on); a
|
|
2216
|
+
stale session `STEP_UP_REQUIRED`; the challenge `TOKEN_UNKNOWN`, `TOKEN_SPENT`
|
|
2217
|
+
or `TOKEN_EXPIRED`.
|
|
2218
|
+
|
|
2219
|
+
## Traps
|
|
2220
|
+
|
|
2221
|
+
**A provider resolved at request time is looked up on every `start` and `complete`.**
|
|
2222
|
+
`social.resolveProvider(name)` is called each time, so keep it cheap (read one record,
|
|
2223
|
+
cache what is slow); a throw (a `StoreFailure`) reaches the caller
|
|
2224
|
+
as it is, never as an unknown provider, and at the callback it forces the user to
|
|
2225
|
+
restart, since the flow is spent before the lookup. A name another user type
|
|
2226
|
+
configures statically never reaches it. Answer the provider for
|
|
2227
|
+
exactly the name asked: one provider for every name merges accounts across
|
|
2228
|
+
connections. Never reuse a name for another identity
|
|
2229
|
+
provider while links to it exist: the link is keyed by the name, so the new
|
|
2230
|
+
provider's accounts would meet the old one's links.
|
|
2231
|
+
|
|
2232
|
+
**`background()` waits only for its own tasks, and a task outlives the request.**
|
|
2233
|
+
`settled()` waits for the tasks of the runner it is called on, so build one
|
|
2234
|
+
runner per process (or per test) and share it. A task runs after the response:
|
|
2235
|
+
it must not read anything tied to the request (a body stream, a transaction, a
|
|
2236
|
+
scoped connection), or it fails and logs `<name> failed in the background: …`.
|
|
2237
|
+
Copy what it needs before calling `run`.
|
|
2238
|
+
|
|
2239
|
+
**`sealerFor` answers a silent `null` when a value cannot open.** Renaming a
|
|
2240
|
+
`purpose`, or dropping a key before every value sealed with it was sealed
|
|
2241
|
+
again, makes `unseal` answer `null` for those values, as it does for any
|
|
2242
|
+
failure. The only trace is a `JANUS_SEALER_UNKNOWN_KEY` warning, once per
|
|
2243
|
+
unknown key id, naming the id and never a value. Keep a purpose for good, keep
|
|
2244
|
+
a key until `needsReseal` is `false` everywhere, and treat a `null` for a
|
|
2245
|
+
stored value as an incident, not as "no value". Build the sealer once, at
|
|
2246
|
+
start: the warning cap is per sealer.
|
|
2247
|
+
|
|
2248
|
+
**Janus never enforces an API key's scopes or bound object.** `create` stores
|
|
2249
|
+
`scopes` and `bound` and `authenticate` answers them on the key principal
|
|
2250
|
+
(`principal.scopes`, `principal.bound`), but no call refuses a request for
|
|
2251
|
+
them: a key scoped to `tools:read` authenticates on every route like any
|
|
2252
|
+
other. Check them in your own handler, and treat `null` as you decide (a key
|
|
2253
|
+
created without scopes is not a key with every scope unless you say so).
|
|
2254
|
+
|
|
2255
|
+
**`magicLink.enabled` only guards the core calls.** With `magicLink: { enabled:
|
|
2256
|
+
false }` the three calls refuse with `MAGIC_LINK_DISABLED`, and a link already
|
|
2257
|
+
e-mailed before the switch works again if the switch goes back on within its
|
|
2258
|
+
TTL (`confirm` refuses before it reads the token, so it is not spent). Your own page must still read
|
|
2259
|
+
`auth.magicLink.enabled` to hide the button; the adapters mount no magic-link
|
|
2260
|
+
route and map the error to 404 by the code's status.
|
|
2261
|
+
|
|
2262
|
+
**Invitation types: list the former type first, and never reorder while legacy
|
|
2263
|
+
invitations are pending.** An invitation stored without a `type` reads as the
|
|
2264
|
+
first type listed in `invitations.type`. Putting a passwordless type first would
|
|
2265
|
+
make the pending password invitations of before acceptable with the code alone,
|
|
2266
|
+
with no password chosen.
|
|
2267
|
+
|
|
2268
|
+
**`@softistx/janus-mongo`: run `syncMongoInvitations(db)` before deploying the
|
|
2269
|
+
release that adds `type`** (and `revokedBy`/`resentBy`): the collection's strict
|
|
2270
|
+
validator refuses the new fields until it runs. `@softistx/janus-drizzle` needs
|
|
2271
|
+
its migration first, too.
|
|
2272
|
+
|
|
2273
|
+
**The `type` of `invitations.issue` is checked at compile time** against the
|
|
2274
|
+
names `invitations.type` lists (required with several, optional with one); a
|
|
2275
|
+
value that comes from a request is still refused at run time as
|
|
2276
|
+
`INVITATION_INVALID` (`field: 'type'`).
|
|
2277
|
+
|
|
2278
|
+
**A custom `SessionStore` on the old signature ends every session once
|
|
2279
|
+
`issuedBefore` is passed.** `revokeUserSessions(userId, at, except?)` still
|
|
2280
|
+
compiles, but a store that ignores the fourth argument revokes every session
|
|
2281
|
+
of the user, the ones opened after the cut-off included. Honour
|
|
2282
|
+
`createdAt < issuedBefore`, run `describeJanusStores` (the
|
|
2283
|
+
`sessions.revokeUserIssuedBefore` case fails on it), and upgrade the adapters
|
|
2284
|
+
together with the core.
|
|
2285
|
+
|
|
2286
|
+
**A custom `TokenStore` must honour `userId` in `consumeToken`.**
|
|
2287
|
+
`consumeToken(tokenHash, kind, at, userId?)` is one conditional write: with
|
|
2288
|
+
`userId`, a token of another user is answered `null` and left unspent. janus
|
|
2289
|
+
fails closed when a store answers another user's token (`TOKEN_UNKNOWN` and a
|
|
2290
|
+
`JANUS_TOKEN_STORE_IGNORES_USER_ID` warning, once per store), but that store
|
|
2291
|
+
has already spent the token, so the owner's link is lost. Put `userId` in the
|
|
2292
|
+
condition beside the hash and the kind, run `describeJanusStores` (the
|
|
2293
|
+
`tokens.consumeBound` case fails on it), and upgrade the adapters together
|
|
2294
|
+
with the core.
|
|
2295
|
+
|
|
2296
|
+
**A sign-up with `signUp.prepare` can squat somebody's address.**
|
|
2297
|
+
Anybody can register an address they do not own and choose its password. If
|
|
2298
|
+
the real owner then confirms the verification mail that went to it, the
|
|
2299
|
+
address is verified and the squatter's password stays on the account
|
|
2300
|
+
(account pre-hijacking). Two habits close it: the `taken` notice carries a
|
|
2301
|
+
`resetPassword` link — a reset proves the address and replaces the password —
|
|
2302
|
+
and every verification mail says to ignore it if the visitor did not ask for
|
|
2303
|
+
it. Keep the password: `firstProof: true` would drop every honest signer's
|
|
2304
|
+
password too, so it fits only an application whose users set the password
|
|
2305
|
+
after proving the address (or that signs in by link or code).
|
|
2306
|
+
`signUp.prepare` exists only on a type
|
|
2307
|
+
whose login is its e-mail field: with a username as the login, a taken
|
|
2308
|
+
username would reveal an account and mail a stranger.
|
|
2309
|
+
|
|
2310
|
+
The third habit is to **confirm only behind a session, always passing
|
|
2311
|
+
`session.user`**: `verifyEmail.confirm(token, { user: session.user })`
|
|
2312
|
+
(a `User` or an id, as `send` takes; on each type and at the root). A link
|
|
2313
|
+
issued to another user is `TOKEN_UNKNOWN` — the same error and message as an
|
|
2314
|
+
unknown token — **it is not spent and nothing is written**, so the real
|
|
2315
|
+
owner's own link, opened signed in as themselves, still works. The check is
|
|
2316
|
+
part of the store's atomic spend, so a race cannot spend a mismatched token.
|
|
2317
|
+
A `user` key that holds nothing (`{ user: session?.user }` with no session)
|
|
2318
|
+
binds to nobody and is refused, never confirmed unbound. **An anonymous
|
|
2319
|
+
confirmation stays open to whoever holds the link**: its defences are
|
|
2320
|
+
`firstProof: true` and the reset link above.
|
|
2321
|
+
|
|
2322
|
+
**Upgrading: `avatar` is reserved, and a stored `fields.avatar` stops being read.**
|
|
2323
|
+
A schema field or a user type called `avatar` is refused, and the
|
|
2324
|
+
`fields.avatar` rows already hold is no longer read: `user.avatar` is janus's
|
|
2325
|
+
own answer. Rename the field, move the stored values, and deploy the adapter's
|
|
2326
|
+
migration or sync (`syncMongoStores(db)`, the drizzle migration) before the
|
|
2327
|
+
new janus, or with it. The move overwrites a target key a row already holds, so
|
|
2328
|
+
pick a name no row uses, or check first. The snippets are in
|
|
2329
|
+
[troubleshooting](docs/troubleshooting.md#avatar-is-a-field-janus-sets-itself-rename-it).
|
|
2330
|
+
|
|
2331
|
+
**An avatar needs a fresh id for every upload, and its image stored first.**
|
|
2332
|
+
`avatar.set` records the id; it stores nothing. Write the bytes to your storage
|
|
2333
|
+
under a new id (`crypto.randomUUID()`), then call `set`: if the call fails the
|
|
2334
|
+
image is an orphan nobody points at, never a record pointing at missing bytes.
|
|
2335
|
+
Reusing the id of the current image lets a storage `replace` overwrite the
|
|
2336
|
+
image the user is showing, and the later removal of the former image — the
|
|
2337
|
+
same id — delete the new one. The former id is in `user.avatarChanged` and
|
|
2338
|
+
`user.avatarRemoved` as `formerAvatarId`; `@softistx/janus-webhooks` does not carry
|
|
2339
|
+
it, so delete the image from the `janus({ events })` listener.
|
|
2340
|
+
|
|
2341
|
+
**`avatar.set` and `avatar.remove` check nothing about who asks.** They are
|
|
2342
|
+
server-side methods, like `update`: no session, no step-up, no ownership. Who
|
|
2343
|
+
may change a user's avatar, and who may see one, is the application's to
|
|
2344
|
+
decide before it calls them — janus holds an id, not an access rule.
|
|
2345
|
+
|
|
2346
|
+
**A type's own `confirm` spends another type's token; the root's does not
|
|
2347
|
+
need the type.** With several user types, `auth.admin.verifyEmail.confirm`,
|
|
2348
|
+
`resetPassword.confirm` and `changeEmail.confirm` answer `TOKEN_UNKNOWN` for a
|
|
2349
|
+
token issued to a member, and the token is spent — the right type then answers
|
|
2350
|
+
`TOKEN_SPENT`. A page that does not know the type calls the root's `confirm`
|
|
2351
|
+
([Confirming a link at the root](#confirming-a-link-at-the-root-of-several-types)).
|
|
2352
|
+
|
|
2353
|
+
**The root `resetPassword.confirm` applies the strictest `minLength` of the
|
|
2354
|
+
types with a password** — a password type with no e-mail counts too, since the
|
|
2355
|
+
root cannot tell: it can never be reset, but its rule still applies at the
|
|
2356
|
+
root. It checks the password before the token is spent, so a refused password
|
|
2357
|
+
never costs the link; a type with a shorter rule sees the stricter one at the
|
|
2358
|
+
root only, and `PASSWORD_TOO_SHORT` reports that `minLength` and the `userType`
|
|
2359
|
+
that set it. The type's own `confirm` applies its own.
|
|
2360
|
+
|
|
2361
|
+
**Once `secondFactor` is configured, switch on `signIn`'s `status`** — and
|
|
2362
|
+
on `signInCode.confirm`'s, `magicLink.confirm`'s and `signInProven`'s. A user whose factor is active gets
|
|
2363
|
+
`{ status: 'secondFactor', challenge, expiresAt, userId }`, with no `token`
|
|
2364
|
+
and no `session`: an e-mailed code or link proves the e-mail, not the factor.
|
|
2365
|
+
`userId` is for your logs and rate limits — answer the visitor the
|
|
2366
|
+
challenge alone.
|
|
2367
|
+
`if (result.status === 'secondFactor') …` before anything reads them.
|
|
2368
|
+
|
|
2369
|
+
**A challenge is a secret, like a session token** — `signIn`'s and
|
|
2370
|
+
`signInCode.request`'s alike. Keep it in a short-lived `HttpOnly` cookie or
|
|
2371
|
+
the body of the code form — never in the e-mail, never in a URL, where logs,
|
|
2372
|
+
proxies and the `Referer` header see it, and never in a log. The e-mail holds
|
|
2373
|
+
the code and nothing else.
|
|
2374
|
+
|
|
2375
|
+
**Confirm a step-up on the request that asked for it.** `stepUp.confirm`
|
|
2376
|
+
stamps the session the request presents, and only a standing session of
|
|
2377
|
+
the challenge's user: a challenge carried to another browser, or confirmed
|
|
2378
|
+
after a sign-out, is `TOKEN_UNKNOWN`. Its challenge is a secret like
|
|
2379
|
+
`signInCode`'s — and check freshness on the server with `assertFresh`, never
|
|
2380
|
+
from a flag the client keeps.
|
|
2381
|
+
|
|
2382
|
+
**`stepUp.request` is throttled per user, only when it e-mails.** An
|
|
2383
|
+
e-mailed code gets five guesses per challenge and a new challenge takes only
|
|
2384
|
+
a new `request`, so a stolen session could keep asking and fill the user's
|
|
2385
|
+
inbox: the mail throttle refuses the sixth in a window with `MAIL_THROTTLED`; the code
|
|
2386
|
+
last sent still works.
|
|
2387
|
+
A step-up confirmed with the app (`via: 'secondFactor'`) sends nothing and is
|
|
2388
|
+
not counted.
|
|
2389
|
+
|
|
2390
|
+
**Answer `signInCode.request` the same whether it issued a code or not** —
|
|
2391
|
+
the same status, body and cookie: set a random challenge when it answered
|
|
2392
|
+
`null`. The code route then still tells a decoy (`TOKEN_UNKNOWN`) from a
|
|
2393
|
+
real challenge (`CODE_INVALID`, `attemptsLeft`, or `TOKEN_SPENT` once a later
|
|
2394
|
+
request spent it): answer its refusals alike
|
|
2395
|
+
where addresses must stay secret. The request is throttled **per
|
|
2396
|
+
address**, counted before anything is looked up, so an unknown address is
|
|
2397
|
+
refused past the limit as a registered one is. At most one code is live per
|
|
2398
|
+
user — a new `request` spends the one before — so the throttle bounds how
|
|
2399
|
+
often anyone who knows an address can fill its inbox or cancel its owner's
|
|
2400
|
+
code; it does not stop it.
|
|
2401
|
+
|
|
2402
|
+
**`signInProven` trusts the id you give it — give it only one your server
|
|
2403
|
+
proved.** It checks no credential: an id read off a request body, a query
|
|
2404
|
+
string or a cookie the client wrote signs in whoever sent it, as that user.
|
|
2405
|
+
Call it right after verifying a proof you issued — an invitation token
|
|
2406
|
+
(single use, expiring, stored hashed), a channel of your own — and take the
|
|
2407
|
+
id from that proof's record. For an invitation, it replaces
|
|
2408
|
+
`magicLink.request` + `confirm`, which counts against the mail throttle:
|
|
2409
|
+
five anonymous requests for the invitee's address would make the
|
|
2410
|
+
acceptance answer 429.
|
|
2411
|
+
|
|
2412
|
+
**Call `verifyEmail.proveFirst` first: it drops the password and revokes
|
|
2413
|
+
every session.** On an e-mail never proved, it does what a first sign-in by
|
|
2414
|
+
link does, so a password set before it is erased — the invitee's own,
|
|
2415
|
+
chosen on your acceptance form, included — and a session opened before it
|
|
2416
|
+
is revoked. Accept an invitation in this order: `findOrCreate` (find or
|
|
2417
|
+
create in one call; `findByEmail` then `create` does the same in two), then
|
|
2418
|
+
`verifyEmail.proveFirst`, then `setPassword` on a type with
|
|
2419
|
+
a password, then `signInProven`. Called after `setPassword`, the person
|
|
2420
|
+
signs in once and then finds `signIn` answering `CREDENTIALS_INVALID`
|
|
2421
|
+
(`reason: 'noPassword'`). **It is privileged, like `signInProven`**: it
|
|
2422
|
+
checks no credential, so call it only right after your server verified
|
|
2423
|
+
its own proof of the inbox — an invitation token it mailed to that
|
|
2424
|
+
address — on the user that proof names, whose e-mail is the address the
|
|
2425
|
+
proof reached; never with an id a request supplied, or anybody can wipe
|
|
2426
|
+
anybody's password, second factor and avatar and sign them out.
|
|
2427
|
+
|
|
2428
|
+
**`findByEmail` and `findOrCreate` are account-existence oracles — never
|
|
2429
|
+
expose either to an anonymous client.** `findByEmail` answers whether
|
|
2430
|
+
somebody of the type holds an address, at once, with no throttle;
|
|
2431
|
+
`findOrCreate` is worse, since it also creates accounts: an address nobody
|
|
2432
|
+
holds becomes one. Call `findOrCreate` on the server only, after your own
|
|
2433
|
+
proof, with the key read from that proof's record. A route that calls
|
|
2434
|
+
`findByEmail` on an address a visitor typed tells anybody who has an account.
|
|
2435
|
+
Call `findByEmail` on the server, after
|
|
2436
|
+
a proof of your own — an invitation token your server issued and just
|
|
2437
|
+
verified — with the address read from that proof's record, never from the
|
|
2438
|
+
request. A visitor who types an address goes through `magicLink.request` or
|
|
2439
|
+
`signInCode.request` instead: throttled per address, and answered with the
|
|
2440
|
+
same page whether they issued or not.
|
|
2441
|
+
|
|
2442
|
+
**Confirm a sign-in link from a `POST`, never from its `GET`.** Mail
|
|
2443
|
+
scanners open every link in an e-mail before the user does: a route that
|
|
2444
|
+
calls `magicLink.confirm` on the link's `GET` spends it for the scanner, and
|
|
2445
|
+
the user's click answers `TOKEN_SPENT`. Link to a page that spends nothing,
|
|
2446
|
+
whose button posts the token — and echo into that page only a token of the
|
|
2447
|
+
token's shape. Refuse that `POST` from another site — check its `Origin`,
|
|
2448
|
+
or `Sec-Fetch-Site: same-origin` — or any page can sign a visitor into an
|
|
2449
|
+
account whose link it holds. Send that page with
|
|
2450
|
+
`Referrer-Policy: strict-origin`, not `no-referrer`, which makes its form's
|
|
2451
|
+
`Origin` `null` and the check refuse its own button. Whoever opens the link signs in, on the device
|
|
2452
|
+
that opened it: where the sign-in must complete in the browser that asked,
|
|
2453
|
+
send a code.
|
|
2454
|
+
|
|
2455
|
+
**The first sign-in by link or code drops the password and the second
|
|
2456
|
+
factor.** `signUp` does not wait for the address to be proved, so anyone can
|
|
2457
|
+
register somebody else's e-mail with a password of theirs. When `signInCode.confirm` or `magicLink.confirm`
|
|
2458
|
+
proves an e-mail never verified, it drops the password, the avatar and the second factor
|
|
2459
|
+
— active or waiting, with its recovery codes — and signs out every session
|
|
2460
|
+
before opening its own — so a user who signed
|
|
2461
|
+
up, never verified, and then signs in by code has no password afterwards,
|
|
2462
|
+
and `signIn` answers `CREDENTIALS_INVALID` (`reason: 'noPassword'`). Offer
|
|
2463
|
+
`setPassword` after such a sign-in, or send `verifyEmail` at sign-up. An
|
|
2464
|
+
e-mail changed by `update` is unverified again, and its first proof by link
|
|
2465
|
+
or code drops both too. **A factor cannot be enrolled before that
|
|
2466
|
+
proof any more**: `secondFactor.enroll`, `secondFactor.activate` and the passkey
|
|
2467
|
+
registration refuse a user whose e-mail is never verified with
|
|
2468
|
+
`EMAIL_UNVERIFIED`, so send `verifyEmail` before offering them (a type with no
|
|
2469
|
+
e-mail is not asked). **`update` cannot move the e-mail of a user who holds a
|
|
2470
|
+
factor or a passkey** (`EMAIL_CHANGE_NEEDS_PROOF`, nothing written): use
|
|
2471
|
+
`changeEmail`, which proves the new address. Only a factor stored before these
|
|
2472
|
+
rules is still dropped. An e-mail already verified keeps both — and
|
|
2473
|
+
`changeEmail.confirm` verifies the new address itself, so the first proof
|
|
2474
|
+
afterwards drops nothing.
|
|
2475
|
+
|
|
2476
|
+
**Gate `changeEmail.send`, and tell the former address.** Whoever changes the
|
|
2477
|
+
e-mail takes over every password reset and sign-in link: call `send` behind
|
|
2478
|
+
`assertFresh` or a step-up, never on a session alone, and mail the address the
|
|
2479
|
+
user had from `user.emailChanged` (`formerEmail`) — once the change landed it
|
|
2480
|
+
is kept nowhere else.
|
|
2481
|
+
|
|
2482
|
+
**Run the adapter's migration before using `changeEmail`.** The tokens store
|
|
2483
|
+
must list the `changeEmail` kind (janus-drizzle 0.8's migration, janus-mongo
|
|
2484
|
+
0.9's `syncMongoAdapter`); until then every `send` is `STORE_FAILED`.
|
|
2485
|
+
|
|
2486
|
+
**Run the adapter's migration before the version that writes `socialFlow`
|
|
2487
|
+
tokens or uses the `socialLinks` slot.** The tokens store must list the
|
|
2488
|
+
`socialFlow` kind and the links table or collection must exist (janus-drizzle
|
|
2489
|
+
0.14's migration, janus-mongo 0.15's `syncMongoAdapter`); until then the first
|
|
2490
|
+
write of a `socialFlow` token is `STORE_FAILED`. janus-drizzle wires the slot
|
|
2491
|
+
only when you pass it the `socialLinks` table, so an application that does not
|
|
2492
|
+
use social sign-in applies nothing.
|
|
2493
|
+
|
|
2494
|
+
**Every `janus()` that signs users in needs the same `secondFactor`.** An
|
|
2495
|
+
instance without keys never signs in a user whose factor is active: `signIn`
|
|
2496
|
+
throws a `TypeError` rather than open a session on the password alone. Build
|
|
2497
|
+
the configuration once and import it everywhere.
|
|
2498
|
+
|
|
2499
|
+
**Never remove a sealing key while a secret is sealed or a recovery code
|
|
2500
|
+
hashed with it, nor change a key under the same id.** That user's next
|
|
2501
|
+
sign-in is a `TypeError`, not a refusal — or, for a key changed, recovery
|
|
2502
|
+
codes that silently match nothing. For a recovery code, only
|
|
2503
|
+
`secondFactor.recover` throws; `regenerateRecoveryCodes` still works while
|
|
2504
|
+
the key sealing the secret is held, and is the way out: it hashes the new
|
|
2505
|
+
codes with the first key. Put the new key first and keep the old one
|
|
2506
|
+
until your database holds no secret and no recovery code starting
|
|
2507
|
+
`v1.<old id>.`: recovery codes are never hashed again, so a user who does not
|
|
2508
|
+
regenerate them keeps the old key in use.
|
|
2509
|
+
|
|
2510
|
+
**`activate` answers `{ user, recoveryCodes }`, not the user** (since 0.10).
|
|
2511
|
+
`(await activate(user, code)).hasSecondFactor` no longer compiles; read
|
|
2512
|
+
`.user`. The codes are shown **once** — no call answers them again — so show
|
|
2513
|
+
them on that response, sent with `Cache-Control: no-store`, and never log them.
|
|
2514
|
+
|
|
2515
|
+
**`enroll`, `disable` and `regenerateRecoveryCodes` do not know who is
|
|
2516
|
+
calling.** Whether the user proves their password or a code first is yours
|
|
2517
|
+
to decide; without a check, a stolen session can switch the factor off.
|
|
2518
|
+
`regenerateRecoveryCodes` asks for the app's code, and nothing else.
|
|
2519
|
+
|
|
2520
|
+
**Past five wrong codes, `regenerateRecoveryCodes` refuses the right one
|
|
2521
|
+
too**. The attempts are counted per user, in the store, in
|
|
2522
|
+
15-minute windows: the sixth call in a window is `CODE_INVALID` with
|
|
2523
|
+
`attemptsLeft: 0`, `reason: 'throttled'` and `retryAfter` (seconds until the
|
|
2524
|
+
window frees), and the message *too many codes tried*, whatever code it
|
|
2525
|
+
carries, and nothing is written. `stepUp.confirm` with an app's code shares
|
|
2526
|
+
the count and refuses the same way. Tell the user to wait `retryAfter`
|
|
2527
|
+
seconds — a new challenge does not help; a challenge whose own five tries are
|
|
2528
|
+
spent carries no `reason`: request a new one; a code accepted —
|
|
2529
|
+
a regenerate, or a sign-in finished with the app — starts the count again.
|
|
2530
|
+
A thief with the session can therefore spend a user's five attempts and
|
|
2531
|
+
hold them off for a window: that is the price of bounding the guesses.
|
|
2532
|
+
|
|
2533
|
+
**Two sign-ins with the same recovery code at once open one session.** The
|
|
2534
|
+
other rejects with `VERSION_CONFLICT`, not `CODE_INVALID`: answer it as "sign
|
|
2535
|
+
in again". Two *different* codes typed on one challenge at once are another
|
|
2536
|
+
matter: the later one can still be removed from the user before it finds the
|
|
2537
|
+
challenge spent, so two codes go for the one session the challenge opens.
|
|
2538
|
+
|
|
2539
|
+
**A sign-in given no `device` tracks nothing.** Absent, `newDevice` is
|
|
2540
|
+
`false`, `deviceToken` is `null` and no event is sent — not "a new device".
|
|
2541
|
+
Pass `{ device: null }` for a client that holds no token yet, or it is never
|
|
2542
|
+
given one.
|
|
2543
|
+
|
|
2544
|
+
**`undefined` is not `null`.** A cookie read as `string | undefined` and
|
|
2545
|
+
passed as `device` is untracked whenever the cookie is missing — a compile
|
|
2546
|
+
error under `exactOptionalPropertyTypes`, silent without it. Write
|
|
2547
|
+
`{ device: cookie ?? null }`.
|
|
2548
|
+
|
|
2549
|
+
**Give the device again to `secondFactor.confirm` and `recover`.** The
|
|
2550
|
+
challenge `signIn`, `signInCode.confirm` or `magicLink.confirm` answers
|
|
2551
|
+
carries no device, so a confirmation called without `{ device }` is
|
|
2552
|
+
untracked, whatever the sign-in was given:
|
|
2553
|
+
`auth.secondFactor.confirm(challenge, code, { device: cookie ?? null })`.
|
|
2554
|
+
|
|
2555
|
+
**Every `janus()` that signs users in needs the same `devices`.** An instance
|
|
2556
|
+
without `devices` throws a `TypeError` for any `device`, and one whose keys
|
|
2557
|
+
differ reports every other instance's devices as new.
|
|
2558
|
+
|
|
2559
|
+
**One device cookie holds one user's token.** Two people sharing a browser
|
|
2560
|
+
who take turns signing in each present the other's token, which proves
|
|
2561
|
+
nothing for them: each gets a new token, and a notice, at every turn.
|
|
2562
|
+
|
|
2563
|
+
**Removing a device key forgets every device it signed.** Each is reported
|
|
2564
|
+
new once, at its next sign-in. It is the only way to forget devices — there
|
|
2565
|
+
is no per-device forget — so rotate by putting a new key first and keeping
|
|
2566
|
+
the old one.
|
|
2567
|
+
|
|
2568
|
+
**A device token is not a credential.** It proves only that this user signed
|
|
2569
|
+
in on this device before. Never authenticate a request with it, and never
|
|
2570
|
+
let it skip a password or a second factor.
|
|
2571
|
+
|
|
2572
|
+
**A `SignedIn` built by hand needs `newDevice` and `deviceToken`** (since
|
|
2573
|
+
0.17): a test double that answers `{ status, user, session, token }` no
|
|
2574
|
+
longer compiles — add `newDevice: false, deviceToken: null`.
|
|
2575
|
+
|
|
2576
|
+
**On a user type, only `setOf` makes a set.** A user passed as it is — or
|
|
2577
|
+
`{ type: 'staff', id, relation: 'managers' }` written out — is that one user,
|
|
2578
|
+
even with a field named `relation`. The compiler refuses the written-out set
|
|
2579
|
+
in `grant()` and `revoke()` where the relation admits one. From JavaScript it grants that user, silently,
|
|
2580
|
+
where the relation also admits the user — and is refused where it does not.
|
|
2581
|
+
`grant(note, 'readers', setOf(bob, 'managers'))`. A spread of a set is still
|
|
2582
|
+
the set; **through `JSON` or `structuredClone` it comes back as the user** —
|
|
2583
|
+
call `setOf` again, or `parseSubject` on its notation (`staff:u1#managers`).
|
|
2584
|
+
|
|
2585
|
+
**Narrowing a model hides stored tuples; it does not delete them.** A tuple
|
|
2586
|
+
the model no longer admits grants nothing, and `revoke()` refuses it — remove
|
|
2587
|
+
it with `relations.write({ remove: [tuple] })`, or widening the model again
|
|
2588
|
+
brings it back.
|
|
2589
|
+
|
|
2590
|
+
**The first session credential present wins, not the first valid one.**
|
|
2591
|
+
`Authorization: Bearer`, then `X-Session-Token`, then the cookie. A client that
|
|
2592
|
+
sends a lapsed bearer beside a live cookie is anonymous, and it should fix its
|
|
2593
|
+
header rather than be rescued in silence.
|
|
2594
|
+
|
|
2595
|
+
**An outage is not anonymous.** `authenticate` rejects with `STORE_FAILED` when
|
|
2596
|
+
the store cannot answer. Answer 503: a 401 would sign everybody out during an
|
|
2597
|
+
outage, and send them to a sign-in page that cannot work either.
|
|
2598
|
+
|
|
2599
|
+
**Never put a `CREDENTIALS_INVALID`'s `reason` in a response body.**
|
|
2600
|
+
`unknownLogin` is an account-enumeration oracle. `signIn` compares against a
|
|
2601
|
+
dummy hash when nobody holds the login, so the hashing time does not tell.
|
|
2602
|
+
**The store's own latency still does**, and that limit is stated rather than
|
|
2603
|
+
denied. `resetPassword.request` answers `null` for an unknown e-mail for the
|
|
2604
|
+
same reason: answer the visitor the same page either way.
|
|
2605
|
+
|
|
2606
|
+
**`request` sent off the visitor's request swallows `MAIL_THROTTLED`.** A
|
|
2607
|
+
`request` for an address with an account looks it up and writes tokens; one
|
|
2608
|
+
for an address nobody holds stops at the lookup — so an application that
|
|
2609
|
+
must not tell the two apart by time runs `request` in the background, where
|
|
2610
|
+
its refusal reaches nobody. Call `prepare(email)` in the visitor's request
|
|
2611
|
+
instead — counted, nobody looked up, the same time for any address — and
|
|
2612
|
+
answer its `MAIL_THROTTLED`; run `send()` in the background. **Never await
|
|
2613
|
+
`send()` in the visitor's request**: its time is `request`'s. And it runs
|
|
2614
|
+
once — a second `send()`, or one after a failed one, is a `TypeError`:
|
|
2615
|
+
`prepare` again.
|
|
2616
|
+
|
|
2617
|
+
**`resetPassword.confirm` signs the user out everywhere, and opens no session.**
|
|
2618
|
+
Whoever had the old password loses their sessions, and a sign-in they left
|
|
2619
|
+
waiting on its second factor is spent with them — as it is by `setPassword`
|
|
2620
|
+
and `changePassword`; what the visitor does next is
|
|
2621
|
+
your policy. A password refused for its length does not spend the token.
|
|
2622
|
+
|
|
2623
|
+
**Only the last reset link works, and only until the password changes.** A
|
|
2624
|
+
`resetPassword.request` spends the user's earlier links, and any password
|
|
2625
|
+
written — by a link, `changePassword` or `setPassword` — spends every link
|
|
2626
|
+
still live, so an older e-mail's link answers `TOKEN_SPENT`. Tell the visitor
|
|
2627
|
+
to use the latest e-mail. Each request cancels the link before it, so the
|
|
2628
|
+
mail throttle bounds `resetPassword.request` per address, five per 10
|
|
2629
|
+
minutes.
|
|
2630
|
+
|
|
2631
|
+
**`signIn` throttles each login, not each client.** Ten passwords per login
|
|
2632
|
+
per 15 minutes, then `CREDENTIALS_INVALID` with `retryAfter` until the window
|
|
2633
|
+
ends — the right password too, so tell the visitor to wait `retryAfter`
|
|
2634
|
+
seconds rather than that the password is wrong. `CredentialRefusal` gained
|
|
2635
|
+
`'throttled'`: an exhaustive `switch` over `error.reason` must handle it.
|
|
2636
|
+
`changePassword` counts in the same budget, so wrong current passwords can
|
|
2637
|
+
make `signIn` answer throttled, and the other way round. A
|
|
2638
|
+
test that tries more than ten wrong passwords at one login over a
|
|
2639
|
+
`fixedClock` is throttled too: advance the clock past `retryAfter`, or wire
|
|
2640
|
+
`signIn: { throttle: false }`. **Somebody who knows a login can keep its
|
|
2641
|
+
password sign-in shut**, ten tries a window; a sign-in code or link, when you wire them, still opens it — the throttle counts passwords, never those.
|
|
2642
|
+
On a store with no TTL (PostgreSQL through `@softistx/janus-drizzle`), schedule
|
|
2643
|
+
`collectExpired()`: every login tried adds a row per window, and it deletes them. One password tried against
|
|
2644
|
+
many logins is not counted: rate-limit `signIn` per client address yourself
|
|
2645
|
+
([passwords](docs/guide/passwords.md#what-you-still-limit-yourself)). The
|
|
2646
|
+
counts live in the tokens store: a flushed or evicting Redis forgets them,
|
|
2647
|
+
and a tokens store that cannot answer fails every password sign-in with
|
|
2648
|
+
`STORE_FAILED`.
|
|
2649
|
+
|
|
2650
|
+
**The mail throttle counts each flow on its own, and it is not a per-client
|
|
2651
|
+
limit.** Five requests per window for one address (`magicLink.request`,
|
|
2652
|
+
`signInCode.request`, `resetPassword.request`) or one user
|
|
2653
|
+
(`verifyEmail.send`, `changeEmail.send`, and `stepUp.request` when it e-mails), then
|
|
2654
|
+
`MailThrottledError`: answer 429 with `Retry-After: retryAfter`. It is safe to
|
|
2655
|
+
show the visitor — it reveals nothing about accounts, unlike `reason`. A refused
|
|
2656
|
+
request is counted too, but the window is fixed and cannot be extended.
|
|
2657
|
+
**A refused request spends, invalidates and rotates nothing**: the last link or
|
|
2658
|
+
code sent, by anyone's request, still confirms until it expires, so somebody
|
|
2659
|
+
who knows an address cannot shut its e-mailed sign-in or reset — at most they
|
|
2660
|
+
fill the inbox, five e-mails per window per flow. Tell the visitor to use the
|
|
2661
|
+
last e-mail they received, or to wait `retryAfter` seconds. The default window
|
|
2662
|
+
(`'10m'`) is no longer than the shortest default token lifetime; if you set a
|
|
2663
|
+
`tokens.*` lifetime shorter than `mail.throttle.window`, the last code can
|
|
2664
|
+
expire first, so keep the window no longer than the shortest you use — `janus()` warns for
|
|
2665
|
+
it, once per call, through `process.emitWarning` with the code
|
|
2666
|
+
`JANUS_THROTTLE_WINDOW` ([troubleshooting](docs/troubleshooting.md#janus-tokensflow-is-5m-shorter-than-mailthrottlewindow-10m-)). `janus`
|
|
2667
|
+
never sees IP addresses, so one client asking for many addresses is not
|
|
2668
|
+
counted: add a per-IP ceiling with `@softistx/redis` rate limits
|
|
2669
|
+
(`defineRateLimit`, `bindRateLimit`; `enforce()` throws `GuardError`
|
|
2670
|
+
`RATE_LIMITED`, `retryAfter` in milliseconds —
|
|
2671
|
+
[example](docs/guide/email-flows.md#requests-that-send-e-mail-are-throttled)). A test suite that requests more than five of
|
|
2672
|
+
one flow for one address or user over a `fixedClock` is throttled: advance the
|
|
2673
|
+
clock past `retryAfter`, or wire `mail: { throttle: false }`. The counts live
|
|
2674
|
+
in the tokens store, so on a store with no TTL (PostgreSQL through `@softistx/janus-drizzle`) schedule
|
|
2675
|
+
`collectExpired()`, which deletes them; a
|
|
2676
|
+
flushed or evicting Redis forgets them, and a tokens store that cannot count
|
|
2677
|
+
throws `STORE_FAILED` with nothing issued
|
|
2678
|
+
([e-mail flows](docs/guide/email-flows.md#requests-that-send-e-mail-are-throttled)).
|
|
2679
|
+
|
|
2680
|
+
**`collectExpired()` also collects lapsed one-time tokens, and a custom
|
|
2681
|
+
tokens store has to implement `deleteExpiredTokens` for it.** Without the
|
|
2682
|
+
method, only the sessions are collected — or `UNSUPPORTED`, when the sessions
|
|
2683
|
+
store has none either — and the throttles' counts pile up on a database with
|
|
2684
|
+
no TTL. Once a lapsed token is collected, its link answers `TOKEN_UNKNOWN`
|
|
2685
|
+
instead of `TOKEN_EXPIRED` or `TOKEN_SPENT`: a page that tells the two apart
|
|
2686
|
+
should treat the third as "this link is no longer valid"
|
|
2687
|
+
([sessions](docs/guide/sessions.md#collectexpired)).
|
|
2688
|
+
|
|
2689
|
+
**A sign-in can move a user's `version`.** Rewriting a stale hash is a write. A
|
|
2690
|
+
user object read before that sign-in, and then passed as `ifVersion`, gets
|
|
2691
|
+
`VERSION_CONFLICT`. That is the conflict doing its job: read the user again.
|
|
2692
|
+
|
|
2693
|
+
**Expiry is decided by the core, not by the store.** A store may still hold a
|
|
2694
|
+
lapsed session, and `authenticate` answers it as anonymous. A TTL index keeps
|
|
2695
|
+
storage tidy; it is not the expiry mechanism.
|
|
2696
|
+
|
|
2697
|
+
**`update` merges, then validates the whole.** The patch is spread over the
|
|
2698
|
+
stored fields and the result is checked against the schema, so a patch can
|
|
2699
|
+
never leave a user that the schema would refuse. Pass `ifVersion` to make the
|
|
2700
|
+
write conditional on what you read. A patch that moves the e-mail of a user
|
|
2701
|
+
holding a second factor (active or waiting) or a passkey is refused with
|
|
2702
|
+
`EMAIL_CHANGE_NEEDS_PROOF` before any write: the new address is unproved, and
|
|
2703
|
+
its first proof would drop them. Use `changeEmail`. The passkeys are listed
|
|
2704
|
+
just before the write, so a passkey registered in that instant can still
|
|
2705
|
+
slip through; `passkeys.register` re-reads the user after its insert and
|
|
2706
|
+
withdraws when the e-mail is unproved, or is not the address (or the
|
|
2707
|
+
verification date) it checked, so none survives. That fails closed: a
|
|
2708
|
+
`changeEmail.confirm` (or a `verifyEmail` re-proof of the same address) landing in that instant withdraws a legitimate passkey
|
|
2709
|
+
(`EMAIL_UNVERIFIED`) and the user registers again.
|
|
2710
|
+
|
|
2711
|
+
**`findMany` answers fewer users than ids, never `null` in their place.** An
|
|
2712
|
+
unknown, malformed or other type's id is left out and a repeated one answered
|
|
2713
|
+
once, so `users[i]` is not the user of `ids[i]`: build a `Map` by `user.id`.
|
|
2714
|
+
An outage is `STORE_FAILED`, never a shorter list — a row whose user is
|
|
2715
|
+
missing from the answer is one nobody holds.
|
|
2716
|
+
|
|
2717
|
+
**Under `bun test`, pass `runner: { describe, it }`.** Measured: Bun gives a
|
|
2718
|
+
test file `describe` and `it` as bare identifiers, not as properties of
|
|
2719
|
+
`globalThis`. jest, and vitest with `globals: true`, are found without it.
|
|
2720
|
+
|
|
2721
|
+
**`undefined` is not an absence here.** Every method that can find nothing
|
|
2722
|
+
answers `null`. `undefined` is what a missing property *and* a function with no
|
|
2723
|
+
`return` both produce, so a store that forgot to answer would report "not found"
|
|
2724
|
+
by accident. `null` has to be written on purpose.
|
|
2725
|
+
|
|
2726
|
+
**The notation is typed, and refuses Keto's untyped subject.**
|
|
2727
|
+
`team:t1#members@staff:u1`, and `team:t1#members@team:t2#members` for a subject
|
|
2728
|
+
set. No part may hold `@`, `#` or a parenthesis, and a type may not hold a `:`,
|
|
2729
|
+
so every string reads one way. `parseTuple` refuses `team:t1#members@grace`,
|
|
2730
|
+
and its message says what a subject is.
|
|
2731
|
+
|
|
2732
|
+
**`parseTuple` throws a bare `TypeError`, not a `JanusError`.** Nothing in this
|
|
2733
|
+
package reads a tuple off the network, so a malformed string came from your own
|
|
2734
|
+
code — a wiring mistake, and no handler should answer one.
|
|
2735
|
+
|
|
2736
|
+
**`mintedAt` is not `createdAt`.** The sequence may have borrowed a millisecond
|
|
2737
|
+
and a clock that stepped backwards is held rather than followed, so it is
|
|
2738
|
+
accurate to the millisecond and no further.
|
|
2739
|
+
|
|
2740
|
+
**`mintId(now)` steers ids forward, never back.** The last millisecond is
|
|
2741
|
+
module state, so passing a `now` earlier than an id already minted in this
|
|
2742
|
+
process does not produce an earlier id — it holds the last one and keeps counting,
|
|
2743
|
+
because a decreasing id would break the pagination cursor, which is the whole
|
|
2744
|
+
reason the core mints ids at all. A test that needs a fixed instant wants
|
|
2745
|
+
`fixedClock`, not this argument.
|
|
2746
|
+
|
|
2747
|
+
**Error codes are `SCREAMING_SNAKE`, everything else is `camelCase`.** The codes
|
|
2748
|
+
are data values, not keys. There is no `snake_case` key anywhere in this package,
|
|
2749
|
+
unlike Ory — a Biome naming-convention rule holds it.
|
|
2750
|
+
|
|
2751
|
+
**`list()` costs what the subject can reach, every round.** It walks backwards
|
|
2752
|
+
from the subject — every page of `findObjects` for every id each step reaches —
|
|
2753
|
+
and repeats a round whenever a relation loops back on itself (a folder
|
|
2754
|
+
viewable through its parent) until a round finds nothing new. Fine for what one
|
|
2755
|
+
user can see; not for a subject set holding most of the database, which wants
|
|
2756
|
+
a query of your own.
|
|
2757
|
+
|
|
2758
|
+
**`can()` wants the loaded object, spread.** `{ type: 'record', ...record }`: a
|
|
2759
|
+
`fromField` reads its field there, and a field missing at run time is a
|
|
2760
|
+
`TypeError`, never a denial. `null` in the field holds nobody.
|
|
2761
|
+
|
|
2762
|
+
**A `lookup` is your code, and not guarded.** A lookup that throws rejects
|
|
2763
|
+
`list()` with its own error, as it threw. Never answer `[]` for a database that
|
|
2764
|
+
could not answer: that is a denial made of an outage.
|
|
2765
|
+
|
|
2766
|
+
**A user event is sent at most once, from the process that wrote.** It is
|
|
2767
|
+
handed to the listener after the write, in the same process: a crash between
|
|
2768
|
+
the two loses it, and nothing sends it later. Build what must not miss one
|
|
2769
|
+
— a billing sync, a search index — to also read the users themselves now and
|
|
2770
|
+
then, and treat events as the fast path. A slow listener slows every flow
|
|
2771
|
+
that sends one, since it is awaited: queue the event and return.
|
|
2772
|
+
|
|
2773
|
+
**The flow cookie is a secret.** `social.start` answers `setCookie`, an
|
|
2774
|
+
`HttpOnly`, `SameSite=Lax` cookie (`Strict` would not travel on the provider's
|
|
2775
|
+
redirect) holding the flow: keep it out of URLs and logs, and send
|
|
2776
|
+
`auth.social.cookie.clear()` once `complete` has run, unless it refused with
|
|
2777
|
+
`flowSpent: false` (a missing cookie or a foreign `state`: the real callback may
|
|
2778
|
+
still come). Its name is `auth.social.cookie.name` — `__Host-janus-social-flow`
|
|
2779
|
+
when the session cookie has no `Domain`, is `Secure` and has `Path=/`, else
|
|
2780
|
+
`janus-social-flow`. A refusal raised after the flow was authenticated carries
|
|
2781
|
+
`returnTo`, the path the flow was started with (not for logs); `FLOW_MISMATCH`
|
|
2782
|
+
and `FLOW_EXPIRED` never do.
|
|
2783
|
+
|
|
2784
|
+
**A flow is single-use.** Once the `state` matched, every outcome (a refusal
|
|
2785
|
+
included) spends it, and so does a cookie whose contents were changed or a
|
|
2786
|
+
flow that lapsed: a second callback is `FLOW_EXPIRED`, so start again. A
|
|
2787
|
+
callback with no cookie, or a foreign `state`, is `FLOW_MISMATCH` and leaves
|
|
2788
|
+
the flow unspent. Behind a BFF, `flow` may live in the BFF's own cookie instead
|
|
2789
|
+
of `setCookie`; it is the same secret.
|
|
2790
|
+
|
|
2791
|
+
**An e-mail match links only when both sides vouch.** A user the provider's
|
|
2792
|
+
e-mail names is linked and signed in only if the provider reports
|
|
2793
|
+
`emailVerified` **and** the local account verified its e-mail; otherwise
|
|
2794
|
+
`EMAIL_NOT_VERIFIED_FOR_LINK`. That code and `SIGN_UP_DISABLED` tell the
|
|
2795
|
+
visitor an account exists, as `findByEmail` does: show them with that in mind.
|
|
2796
|
+
|
|
2797
|
+
**A pre-squatted, unverified local account blocks the auto-link.** Somebody
|
|
2798
|
+
who registered the address first is not displaced by a sign-in with the
|
|
2799
|
+
provider. The real owner recovers with `resetPassword`, or `verifyEmail` with
|
|
2800
|
+
`{ firstProof: true }`, which prove the address and drop the squatter's
|
|
2801
|
+
password; the next social sign-in then links.
|
|
2802
|
+
|
|
2803
|
+
**One provider account links to one user per instance**, whatever the type:
|
|
2804
|
+
the second is `SOCIAL_ACCOUNT_TAKEN`. One Google account cannot be both a
|
|
2805
|
+
patient and a staff member.
|
|
2806
|
+
|
|
2807
|
+
**Check `result.stepUp` when a step-up matters.** A plain flow and a flow
|
|
2808
|
+
started with `stepUp` complete at the same callback, so a visitor can swap a
|
|
2809
|
+
plain cookie into it: it is genuine, and signs in with `stepUp: null`. Allow
|
|
2810
|
+
the sensitive action only when `result.stepUp !== null`. A flow that asked for
|
|
2811
|
+
a step-up and did not get it never reaches you as a sign-in: it is
|
|
2812
|
+
`SOCIAL_STEP_UP_UNMET`, and a provider that reports no `acr` or `authTime` is
|
|
2813
|
+
refused, not trusted (`acr_values` is only a request). `maxAge: 0` means
|
|
2814
|
+
"within about a minute" (60 s of tolerance each way, on the core's clock). A
|
|
2815
|
+
provider without `supportsStepUp` (GitHub, a plain OAuth one) cannot be asked.
|
|
2816
|
+
|
|
2817
|
+
**`LAST_SIGN_IN_METHOD` is checked, not locked.** It counts a password, the
|
|
2818
|
+
user's other links and, on a type with no password, a verified e-mail. Two
|
|
2819
|
+
concurrent unlinks of a user's last two links can both pass.
|
|
2820
|
+
|
|
2821
|
+
**`social.signUp` exists only on a type whose login is its e-mail** (no
|
|
2822
|
+
password, or `password.login` naming the e-mail field): any other is refused at
|
|
2823
|
+
compile time, and a `TypeError` at wiring.
|
|
2824
|
+
|
|
2825
|
+
**A type that configures `social` needs the `socialLinks` slot**, else
|
|
2826
|
+
`janus()` throws a `TypeError` naming the type. `createMemoryStores()` has it.
|
|
2827
|
+
|
|
2828
|
+
**`social.link` takes the `Authenticated` session**, not a `UserRef`: freshness
|
|
2829
|
+
belongs to the session, and an older one than `social.freshWithin` (`'10m'`)
|
|
2830
|
+
is `STEP_UP_REQUIRED`. Pass the same `current` to `complete`.
|
|
2831
|
+
|
|
2832
|
+
**Events carry the provider, never the account id.** Keep `accountId` out of
|
|
2833
|
+
logs too; `PROVIDER_ERROR`'s `reason` is for logs, never for a response body.
|
|
2834
|
+
|
|
2835
|
+
**A passkey challenge is spent by `register`, verified or not.** One challenge
|
|
2836
|
+
makes one attempt: a response that does not verify costs the challenge, and the
|
|
2837
|
+
page asks for new options. A bad name, a stale session and a user without an
|
|
2838
|
+
active TOTP are refused before it is spent. Keep `challenge` with the user —
|
|
2839
|
+
the page's state or a short-lived cookie — and send it back with the browser's
|
|
2840
|
+
answer; it is not secret, it is single-use.
|
|
2841
|
+
|
|
2842
|
+
**`confirmPasskey` answers a refusal as a code that does not match.** A wrong,
|
|
2843
|
+
unknown or other user's credential, a counter that went backwards and a
|
|
2844
|
+
response that does not verify are all `CODE_INVALID` with `attemptsLeft` —
|
|
2845
|
+
the visitor learns nothing more, and `passkeyOptions` is the only place the
|
|
2846
|
+
user's credential ids appear (answer it only to someone who proved the first
|
|
2847
|
+
factor, which `signIn` just checked). The WebAuthn challenge is derived from
|
|
2848
|
+
the first sealing key: rotating the keys between `signIn` and the assertion
|
|
2849
|
+
(a five-minute window) refuses that one sign-in, and the user signs in again.
|
|
2850
|
+
A counter regression is not a lockout: listen to `user.passkeyCloneSuspected`
|
|
2851
|
+
and decide (notify the user, remove the passkey).
|
|
2852
|
+
|
|
2853
|
+
**`stepUp.request(user)` is still the app's code.** A passkey step-up is asked
|
|
2854
|
+
for with `{ via: 'passkey' }`; a user with no passkey is refused
|
|
2855
|
+
(`SECOND_FACTOR_NOT_ENROLLED`) rather than silently sent a code. It exists on
|
|
2856
|
+
types with an e-mail, like every step-up, and only counts its challenge's five
|
|
2857
|
+
attempts, not the per-user window the app's codes share.
|
|
2858
|
+
|
|
2859
|
+
**Disabling the TOTP removes the user's passkeys.** A passkey only stands
|
|
2860
|
+
beside an active TOTP, so `secondFactor.disable` (and a first proof that
|
|
2861
|
+
removes an active TOTP) deletes them all and sends one `user.passkeyRemoved`
|
|
2862
|
+
each. A user holds at most `passkeys.maxPerUser` (10) passkeys:
|
|
2863
|
+
`register` refuses the next with `PASSKEY_LIMIT` (409) before it spends the
|
|
2864
|
+
challenge.
|
|
2865
|
+
|
|
2866
|
+
**`rpId` and `origins` are a promise to the browser.** A credential made for
|
|
2867
|
+
`example.com` is useless from another domain, and changing `rpId` later strands
|
|
2868
|
+
every registered passkey. Each origin must be on `rpId` (the same host or a
|
|
2869
|
+
subdomain) and `https`, except `http://localhost`, `http://<name>.localhost` (such as `http://tenant.app.localhost`) and `http://127.0.0.1` (any port) for development.
|
|
2870
|
+
|
|
2871
|
+
## Documentation
|
|
2872
|
+
|
|
2873
|
+
- [Guides](docs/README.md) — one page per area, every option with an example
|
|
2874
|
+
- [Account avatars](docs/guide/avatars.md) — the upload, remove and proxy routes, who may see an image, and the failure order
|
|
2875
|
+
- [Devices](docs/guide/devices.md) — a sign-in from a new device: the token, the cookie, the notice
|
|
2876
|
+
- [Several issuers](docs/guide/issuers.md) — one `janus()` instance per tenant in one process: `createJanusIssuers`, the resolve and build, version rebuilds, the bounded cache
|
|
2877
|
+
- [Invitations](docs/guide/invitations.md) — inviting into an organization: issue, resend, revoke, list, preview and accept, the e-mail link, the errors and the traps
|
|
2878
|
+
- [Migrating invitations](docs/guide/migrating-invitations.md) — importing an older system's invitation history: the field mapping, dry run, re-running and what keeps it
|
|
2879
|
+
- [Passkeys](docs/guide/passkeys.md) — registering, listing, renaming and removing a second-factor passkey: the configuration, the two-step registration, freshness, the errors and a test with a fake verifier
|
|
2880
|
+
- [Social sign-in](docs/guide/social.md) — the flow, every sign-in case, linking, writing a provider, a test with a fake
|
|
2881
|
+
- [Troubleshooting](docs/troubleshooting.md) — by the error message you see
|
|
2882
|
+
- [Roadmap](docs/roadmap.md) — what is next, and what is not planned
|
|
2883
|
+
|
|
2884
|
+
## Type safety, counted
|
|
2885
|
+
|
|
2886
|
+
**Three hundred and forty-six plausible mistakes, three hundred and forty-six refused at compile time — and
|
|
2887
|
+
two gaps, named.**
|
|
2888
|
+
|
|
2889
|
+
The lists are typechecked and never run, with one `@ts-expect-error` per
|
|
2890
|
+
mistake beside the shapes that must keep compiling. Two are single files:
|
|
2891
|
+
`test/types/refusals.ts` (sixteen, on the shared vocabulary) and `test/types/issuers.ts` (four, on `createJanusIssuers`: no `resolve`, no `build`, a numeric `version`, an instance read without its `null`). The other four
|
|
2892
|
+
are folders with one file per behaviour: `test/types/port/` (forty-nine, on
|
|
2893
|
+
the identity stores' port, from the point of view of the person implementing
|
|
2894
|
+
it), `test/types/auth/` (one hundred and ninety-six, on `janus()`, from the point of view of
|
|
2895
|
+
the application — thirteen of them on the second factor, three on sign-in codes,
|
|
2896
|
+
five on user events, four on step-ups, six on the sign-in throttle, five on the mail throttle, three on the second-factor throttle, four on
|
|
2897
|
+
sign-in links, six on devices, seven on reading and writing users (two of them on `findMany`), five on requests in two steps, three on signing in on the application's proof, three on finding a user by e-mail, three on proving an e-mail on the application's proof, six on changing an e-mail, sixteen on confirming a link at the root of several types and binding it to a user, twelve on the wiring of `janus()` (reserved type names included), six on signing up and in, four on `findOrCreate`, five on avatars, five on verified sign-up, two on the cut-off of `signOutEverywhere`, nine on API keys (five on scopes, bound objects and expiry notices), thirty-two on invitations — a `beforeAccept` that answers an object, a user type with no e-mail, a login that is not the e-mail, several types and no `type`, a `type` that is none of them, `accept` without the block, a `get` without its `scope`, a numeric `id`, an `issue` that leaves `invitedBy` out, a `ref`, `order`, `status`, `role` or `lapsed` of the wrong type, a `by` that is no string on `revoke` or `resend`, a list of types with an unknown name, a login that is not the e-mail or no e-mail, an empty list, a name listed twice, and an `issue` whose `type` is not a string, is none of the listed types or is missing with several types, and an `importHistory` record that is accepted without `acceptedAt`, revoked without `revokedAt`, of an unknown status, with no `key`, with a `type` that is not listed or a `createdAt` that is a string, and a `dryRun` that is no boolean — twenty on passkeys and four on the magic-link switch) `test/types/social/` (twenty, on `auth.social`: a `social` block with neither providers nor a resolver, a `resolveProvider` that answers a name or undefined, or is not async, a step-up whose `acrValues` is a string, whose `maxAge` is no number, that asks for nothing or that has a third key, a misspelled provider, a type without social, social without an e-mail, a `signUp` on the wrong login or answering the wrong fields, a link given a bare user and a result switch missing a status and a `linked` result read for a session token) and `test/types/permissions/` (sixty, on the
|
|
2898
|
+
permission model and the questions asked of it). The rule comes from
|
|
2899
|
+
`nxgt-data`, and so does the reason to distrust the claim without the files:
|
|
2900
|
+
when it was last measured on `@softistx/mongo`, *seven of twelve plausible
|
|
2901
|
+
mistakes still compiled*. A count that goes down is a visible regression.
|
|
2902
|
+
|
|
2903
|
+
Refusing a wrong name is half of it; offering the right ones is the other.
|
|
2904
|
+
`src/permissions/completions.model.spec.ts` asks the TypeScript language
|
|
2905
|
+
service — the one every editor asks — what it completes inside `defineModel`:
|
|
2906
|
+
subject types and subject sets in a relation, subject types in `fromField`,
|
|
2907
|
+
relations, permissions and arrows in a rule and in `when`; and
|
|
2908
|
+
`completions.questions.spec.ts`, in the questions, what `can`, `list` and
|
|
2909
|
+
`grant` accept for the object's type. The first also checks that a wrong
|
|
2910
|
+
name's error lists the names it could have been.
|
|
2911
|
+
|
|
2912
|
+
The gaps, since a measurement that only reports wins is not a measurement:
|
|
2913
|
+
|
|
2914
|
+
- `'30 m'` **satisfies `Duration`**, because TypeScript's `${number}`
|
|
2915
|
+
placeholder tolerates trailing whitespace inside the number.
|
|
2916
|
+
`parseDuration` refuses it, and `duration.spec.ts` asserts that.
|
|
2917
|
+
- **`can()` and `list()` accept `{ type: 'staff', id, relation: 'managers' }`
|
|
2918
|
+
written out** on a user type that is also an object type, and ask about that
|
|
2919
|
+
one user — `grant()` and `revoke()` refuse it (case 42). The anonymous
|
|
2920
|
+
`null` their subject also takes turns off TypeScript's check of the object
|
|
2921
|
+
literal, and a check of its own would refuse a user whose schema has a
|
|
2922
|
+
`relation` field. `engine.user-objects.spec.ts` asserts the run time reads it as the
|
|
2923
|
+
user. Write the set with `setOf`.
|
|
2924
|
+
|
|
2925
|
+
Each is written down rather than omitted.
|
|
2926
|
+
|
|
2927
|
+
## Licence
|
|
2928
|
+
|
|
2929
|
+
MIT
|