@playstack/mfa
Passkey-first MFA, TOTP, recovery codes, recent-auth proofs, and trusted-device decisions.
Reference: @playstack/mfa@0.1.0-beta.5 · TypeScript · MIT licence
Free. MIT licensed. Check preview availability before installing. See package access.
@playstack/mfa provides passkey-first step-up authentication, TOTP, recovery codes, recent-auth proofs, trusted-device decisions, and account policy without taking session ownership from @playstack/auth.
Install
npm install @playstack/mfa @playstack/core @playstack/crypto @playstack/eventsInstall @simplewebauthn/server only when using the optional Node adapter.
Install @playstack/devices only when selecting its remembered-device bridge;
it is not required for passkeys, TOTP or recovery.
Compose the service
import { createMfa } from '@playstack/mfa'
import { simpleWebAuthnPasskeys } from '@playstack/mfa/webauthn'
export const mfa = createMfa({
persistence,
crypto: applicationCrypto,
webCrypto: globalThis.crypto,
recoveryHasher: passwordGradeRecoveryHasher,
passkeys: simpleWebAuthnPasskeys(),
limiter: mfaAttemptLimiter,
events,
clock,
ids,
issuer: 'Example App',
rpId: 'app.example.com',
rpName: 'Example App',
origins: ['https://app.example.com'],
// Optional: trustedDevices: devices,
})Configuration reference
MfaOptions property | Required | Purpose |
|---|---|---|
persistence | Yes | Transactional credentials, challenges, recovery sets, and replay locks. |
crypto | Yes | Encryption plus purpose-bound recent-auth signing and verification. |
webCrypto | Yes | TOTP HMAC and secure random bytes. |
recoveryHasher | Yes | Password-grade recovery-code hash and verify bridge. |
passkeys | Yes | WebAuthn options and ceremony verification bridge. |
limiter | Yes | Fail-closed attempt limiter by method and user. |
codeFailureScope | No | Owned, transaction-bound failure budget for the combined active TOTP/recovery challenge. |
events, clock, ids | Yes | Typed security events and deterministic primitives. |
issuer | Yes | TOTP issuer, maximum 200 characters. |
rpId, rpName | Yes | WebAuthn relying-party ID and display name. |
origins | Yes | One or more exact HTTPS WebAuthn origins. |
trustedDevices | No | Device trust lookup and grant bridge. |
challengeTtlMs | No | Positive WebAuthn challenge lifetime; defaults to five minutes. |
recentAuthTtl | No | Signed proof lifetime; defaults to 5m. |
recoveryCodeCount | No | Codes per set; defaults to 10 and cannot exceed 50. |
maxTrustedDeviceTtlMs | No | Trust-grant ceiling; defaults to 30 days. |
preparationTtlMs | No | One-attempt preparation lifetime, 1–300 seconds; defaults to 60 seconds. |
authorizeOperation | No | Read-only current product authorization on the identity transaction before MFA child locks; pending-enrollment abort also repeats it after evidence. |
authorizePendingEnrollmentAbort | Required for abort | Default-deny worker permission for the exact user, credential and optional expected recovery set on the supplied transaction. |
authorizeChallengeCleanup | Required for challenge cleanup | Default-deny global maintenance permission for the frozen effective limit, captured cutoff and optional context on the original transaction. |
Passkey bridge
PasskeyAdapter builds registration/authentication options and verifies both ceremonies against the service-supplied challenge, exact origins, RP ID, credential public key, and sign count. The service owns challenge lifetime and single use, credential uniqueness, discovery, and persisted sign counts.
The included simpleWebAuthnPasskeys adapter defaults user verification to required, prefers discoverable credentials, requests no attestation, hashes internal user IDs into fixed-size handles, and omits the allowlist for discoverable sign-in. Use userVerification: 'preferred' only if another factor provides verification.
The adapter keeps opaque stored challenges and applies the same UTF-8-to-base64url encoding as SimpleWebAuthn when verifying both ceremonies. Browser responses must be returned unchanged; no alternate challenge encoding is accepted. Exact challenge/origin/RP checks, user verification and single-use consumption remain enforced.
Local packed qualification uses real SimpleWebAuthn 13.3.2 and 13.3.3, valid none-attestation registration and P-256 authentication signatures. It covers binding refusals, replay/expiry and memory-transaction rollback/preparation. Actual browser/device and application database qualification remain separate.
Other bridge contracts
| Contract | Key members |
|---|---|
MfaPersistence | Transactional credentials, single-use challenges, recovery sets, and locked recovery-code consumption. |
MfaCrypto | Random tokens, encryption, and purpose-bound sign/verify; compatible with @playstack/crypto. |
RecoveryCodeHasher | hash(code) and verify(hash, code) using a password-grade algorithm. |
MfaAttemptLimiter | consume(method, userId) returning allowed and optional retryAt. |
MfaCodeFailureScope | Retains one user/IP budget and the original identity/factor transaction through a combined code attempt. |
TrustedDeviceManager | isTrusted and trust; implemented structurally by @playstack/devices. |
Security behavior
- TOTP uses HMAC-SHA1, a 30-second period, six digits, a one-step window, encrypted secrets, and counter replay prevention.
- Recovery codes are displayed once, activated only after acknowledgement, consumed atomically, and retained after use.
- Regenerating codes does not invalidate the previous set until the replacement is acknowledged.
- Sign-count regressions are persisted for detection but do not hard-lock synced passkeys.
MfaService implements auth’s StepUpVerifier. Register auth’s MFA-change handler for both enrollment and disable events so credential changes revoke existing sessions atomically. Route mfa.verification.locked to security notifications as a transactional event that bypasses preferences.
Transaction-bound workflows
Credential, challenge and recovery mutations accept a caller transaction as the last argument, after an optional operation context where present. They join that live handle; they do not commit an independent MFA unit of work. Publish results only after the outer transaction commits, and propagate failures for rollback.
For expensive verification, call prepareVerifyTotp,
prepareVerifyRecoveryCode, prepareFinishPasskeyAuthentication,
prepareConfirmTotpEnrollment, prepareFinishPasskeyRegistration or
prepareRegenerateRecoveryCodes before opening the protected transaction.
The returned server-only capability exposes commit(transaction) and permits
one attempt, including rollback. Short snapshot reads finish before expensive
hash/passkey work. Commit rechecks current credentials, challenge/set/code
identity, replay state and original deadlines under identity-first locks.
A preparation's TTL cannot extend a challenge, TOTP window or recent-auth proof.
Proof signing and factor consumption share the commit transaction; signing or
required evidence failure restores replay authority. Enrollment/disable events
can revoke Auth sessions on that same handle through the existing MFA-change
handler. Configure authorizeOperation for current application identity/policy
checks or perform an active-user check on the caller transaction. MFA does not
own account or suspension policy.
Standalone failed passkey ceremonies retain challenge burning. Prepared validation consumes no challenge until commit. Attempt budgets and denied-attempt evidence remain preparation admission effects. Direct caller methods may do expensive work while the caller holds locks; prepare first when that matters. Existing recent-auth proofs remain stateless and reusable until expiry. A proof leaked before outer rollback is not cryptographically revoked, so keep results private until commit. External remembered-device grants are not implicitly atomic with MFA, and no host routes or step-up flow are enabled by this API.
Abort one pending enrollment
abortPendingEnrollment({ userId, credentialId, recoverySetId? }, context?, tx?)
erases one pending credential and its exact unacknowledged enrollment recovery
set and hashes. A background worker does not need an already-active factor,
recent-auth proof, secret decryption or a login-attempt limiter call. Configure
authorizePendingEnrollmentAbort explicitly: it defaults to denial and receives
the owned exact identifiers plus optional context. Identifiers and a system-actor
label do not grant permission by themselves. If configured, ordinary
authorizeOperation must also admit abortPendingEnrollment.
The native adapter locks User before the credential, associated recovery set and hash rows. Cleanup permission runs before dependent rows and repeats after required evidence; ordinary authorization repeats last on the same handle. An explicit caller transaction can join Casters-style cleanup-receipt deletion and Audit evidence to erasure. Propagate errors to roll the whole unit back and expose results only after commit. Later host writes or waits need a final host authority check afterward. The native User must still exist; missing User refuses.
A changed result is { status: 'aborted', userId, credentialId, recoverySetId? }.
{ status: 'not-found' } means both targeted records are absent, not that earlier
ownership or deletion was proven. Repeated cleanup has no new event. Register the
required transactional Audit handler for mfa.enrollment.aborted; its payload
contains identifiers only. Persistence, Audit, final-policy and caller failure
restore erased data and joined host receipt changes together. This is not a
mfa.credential.disabled event and does not revoke unrelated sessions.
Native immutable RecoveryCodeSet.enrollmentCredentialId binds an initial recovery
set to one exact credential. Omission of the expected recoverySetId discovers
that association; supplying an ID never authorizes erasing another same-user set.
acknowledgeEnrollment requires the exact user/credential/set pair. Generic
acknowledgeRecoveryCodes accepts independent, unbound regeneration sets only.
Origin metadata remains after acknowledgement. An exactly bound, owned,
unacknowledged orphan set can be cleaned when its credential is already absent.
Active/disabled credentials, acknowledged sets, mismatched users or pairs, corrupt hash ownership and verified pending credentials without native binding refuse before deletion. Unrelated active factors, active recovery sets and trusted-device decisions are preserved. Confirmation-first can leave a still-pending bound pair eligible for cleanup; acknowledgement-first protects active state. Abort-first makes stale confirmation, acknowledgement and prepared commit refuse without restoring credential data.
Adopt the pending-enrollment schema
Refresh the managed mfa.prisma artifact and schema hash, review/apply the migration
adding nullable unique MfaRecoveryCodeSet.enrollmentCredentialId, then regenerate
the application client before using the new persistence build. The origin is a
scalar, with no new cascading credential FK or changed User reverse relations.
Custom persistence must implement association lookup/immutability and guarded
credential/set deletion, including atomic hash deletion and User-first ordering.
There is no inferred association, automatic backfill or old-format reader. Existing confirmed pending enrollment requires an explicitly reviewed association import from application-owned enrollment evidence, or an application-reviewed cleanup decision. Do not classify unknown-origin enrollment state as independent regeneration. Active factors retain their ordinary authentication support.
This operation does not fence enrollment requests not yet admitted, sweep anonymous passkey challenges or cancel external work. Transaction-admission fencing and bounded native challenge cleanup remain separate refinements. It removes database state, not volatile copies, database history/WAL or backups, and is not a general user purge. Worker policy, schema adoption, publication and full application qualification remain host/owner responsibilities. The package train remains beta.5.
Purge expired WebAuthn challenges
purgeExpiredChallenges({ limit? }, context?, tx?) removes expired registration
and authentication challenges, including anonymous sign-in challenges. The default
row limit is 100; accepted limits are 1–1000. The package captures one validated
trusted-clock cutoff before awaited work. Callers cannot choose a future cutoff,
and later-expiring rows remain for subsequent batches. Observed clock regression
fails closed. Consumed but unexpired challenges remain stored.
Enable authorizeChallengeCleanup explicitly and register the transactional MFA
Audit handlers. The service checks event readiness before deletion. The worker
hook receives a frozen { limit, expiresAtOrBefore, context? } and the same live
transaction, before work and after required evidence. It authorizes global
maintenance of this store; context metadata does not scope deletion to an account
or grant permission. Use trusted worker attribution rather than request JSON.
const mfa = createMfa({
...options,
authorizeChallengeCleanup: (input, tx) => authorizeMaintenanceWorker(input, tx),
});
const result = await mfa.purgeExpiredChallenges({ limit: 100 }, {
actor: { type: 'system', id: 'expired-mfa-challenges' },
});Results contain only { deleted }. Changed batches emit transactional
mfa.challenges.purged with that count and trusted context; empty batches emit
nothing. PostgreSQL atomically selects by expiry/ID and deletes bounded rows with
FOR UPDATE SKIP LOCKED. Another ceremony/worker can hold expired rows, so a zero
or partial count never proves exhaustion. Schedule bounded retries and configure
database deadlines/concurrency independently of the row limit.
This global maintenance path never acquires User/factor locks or calls
authorizeOperation, because anonymous challenges have no user. Worker and Audit
callbacks must not acquire identity/factor locks after challenge locks; native
ceremonies retain User-first order. Supply a caller transaction to join host writes
and required evidence atomically. Failures must roll back the whole unit, and
results remain provisional until outer commit. Later host work owns its final
authority check.
Credentials, recovery material, sessions, receipts and live challenges are
preserved. Prepared completion revalidates the original locked challenge and
cannot recreate a purged expired row. Keep IDs nonreusable. Custom persistence
implements purgeExpiredChallenges({ expiresAtOrBefore, limit }, tx) with the same
bounded/skip-locked semantics; memory remains a single-writer test profile.
The existing expiry index is reused, with no new schema or artifact hash. This
does not retire unadmitted enrollment requests or erase volatile copies/backups.
Worker scheduling, artifact publication and application qualification remain
separate.
Failure-only code challenges
verifyCodeChallenge({ userId, code, ip, allowRecoveryCode }, context?) tries
active TOTP and then an explicitly permitted acknowledged recovery code. Only
a final failed proof consumes one shared failure budget. Success does not clear
earlier failures; a successful recovery fallback spends no quota. Results are
verified (with a recent-auth proof), invalid, unavailable or limited
(with an optional retry time).
Configure codeFailureScope with createMfaCodeFailureScope. The native Prisma
rolling-budget composition supplies its original transaction, retaining budget
locks before identity/factor locks. Factor consumption, proof signing, required
evidence and the mfa.verification.locked outbox event share that unit. Negative
outcomes commit as data before host error mapping. The scope sees no signed
proof; MFA returns it only after acknowledged commit. Never automatically replay
an uncertain commit, which can have consumed a recovery code without returning
its proof.
verifyCodeChallengeWithEffect(input, effect, context?) lets a trusted host join
pending-login consumption, transactional Auth session issuance and required
evidence to successful factor consumption. The callback receives a frozen
{ userId, method } fact and the same transaction, without the signed proof.
Await only database work on that handle; do not open another transaction or
send responses/network effects from the callback. Native policy and TOTP freshness
are checked again after the callback. Failure rolls back host and factor writes
together. Only acknowledged commit returns { kind: 'verified', verification, value }; negative outcomes skip the callback and retain their existing shape.
The scope sees neither private output, and an uncertain commit must not be replayed.
This profile holds locks during verification: bound concurrency and configure transaction/verifier deadlines. It has no external caller-transaction or prepared overload. Existing attempt-limited, prepared, enrollment and passkey operations retain their behavior. Pending enrollment, transport/IP admission, Auth session issuance and product login policy remain host-owned.
Native Prisma transaction admission
Both new PrismaMfaPersistence(client, options?) and
prismaMfaPersistence(client, options?) accept PrismaMfaPersistenceOptions from
@playstack/mfa/prisma. Its optional admitTransaction assertion runs before
native relation access, including User locking, transactional lists, the initial
passkey-owner lookup, anonymous challenge creation and cleanup. For a qualified
public PrismaPg factory:
import { prismaMfaPersistence } from '@playstack/mfa/prisma';
import { assertPrismaPgTransactionFence } from '@playstack/prisma-runtime/prisma-pg';
const persistence = prismaMfaPersistence(client, {
admitTransaction: ({ handle }) => assertPrismaPgTransactionFence(owningFence, handle),
});Here client and owningFence come from the same exclusively owned factory.
Database URLs, versions and handle shape do not establish ownership. Admission
resolves without a value or throws; this assertion does not return a boolean.
Unexpected results and callback failures refuse with fixed policy_rejected
diagnostics. Root/malformed handles fail before the callback; structural checks
repeat afterward. The native adapter captures/freezes the transaction wrapper and
retains the same handle through all SQL. Write fields, passkey bytes and cleanup
bounds are detached before the awaited hook.
The callback is captured at construction, runs at internal transaction entry and
before each native transactional operation's first statement, and is never cached
for a handle. Keep it limited to physical transaction admission; do not open
another transaction, call a provider or acquire User/factor locks from it. Native
SQL and lock ownership stay in MFA. Product policy remains in authorizeOperation
after the User lock; worker cleanup permissions remain separate.
Unbound listCredentials and findPasskeyByCredentialId still read through the
root client without admission. Supply a transaction when the ownership check is
required. Omitting this option retains structural transaction checks without an
owning-factory assertion. The option changes no schema/hash/dependency and does
not activate application MFA. Refresh matching artifacts, configure the reviewed
factory assertion, and qualify application flows before removing a local ownership
adapter. Results and required host evidence retain the existing outer-commit
boundary.
Persistence and testing
@playstack/mfa/prisma provides locked PostgreSQL persistence. The required
lockUser port serializes the identity before MFA rows; native adapters reject
root/autocommitting handles. Custom adapters must implement equivalent locking.
The memory adapter has no identity directory and uses its single-writer profile.
Caller composition itself needs no schema change; pending-enrollment abort requires
the origin-column migration described above. The managed,
security-critical fragment is non-ejectable and declares its reverse User
relations as model extensions. playstack database sync composes those fields
into the selected managed auth artifact and validates the complete Prisma
relation graph before writing. If an application owns the User model, it must
supply the extension target explicitly. Applications still own migrations.
@playstack/mfa/testing provides in-memory persistence and deterministic bridge
fakes.
Boundary
MFA does not identify devices, issue sessions, choose account policy, or send lockout notifications. The Workers-safe core accepts any passkey adapter; Node-only WebAuthn support remains an optional subpath.
API entry points and requirements
Reference snapshot: @playstack/mfa@0.1.0-beta.5. Import only the entry point your runtime needs. Paths below are relative to the installed package; use Go to Definition in your editor to inspect exact parameters, return types and overloads. Do not import the declaration-file paths directly.
| Public entry point | Declaration file |
|---|---|
@playstack/mfa | ./dist/index.d.ts |
@playstack/mfa/errors | ./dist/errors.d.ts |
@playstack/mfa/prisma | ./dist/prisma.d.ts |
@playstack/mfa/testing | ./dist/testing.d.ts |
@playstack/mfa/webauthn | ./dist/webauthn.node.d.ts |
@playstack/mfa/playstack.artifacts.json | No TypeScript declaration (asset or metadata export). |
@playstack/mfa/package.json | No TypeScript declaration (asset or metadata export). |
Node.js engine requirement: >=20. This is not a claim that every entry point works in browsers or Workers.
Peer dependencies
Keep existing framework versions that satisfy these ranges. Install optional peers only when using the corresponding adapter. The package manager resolves ordinary dependencies separately.
| Peer | Compatible range | When needed |
|---|---|---|
@playstack/crypto | 0.1.0-beta.5 | Required by the package. |
@playstack/devices | 0.1.0-beta.5 | Optional; only for the entry points that use it. |
@simplewebauthn/server | ^13.3.2 | Optional; only for the entry points that use it. |
For a complete first program, start with Getting started. For API lookup and partial-example conventions, see Reading the reference. Provider failures, lifecycle requirements and application responsibilities remain described in the guide above; types alone do not establish production safety.