Help us shape the future of Go! Take the 2026 Go Developer Survey

mfapostgres

package module
v0.0.0-...-789096f Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 46 Imported by: 0

README

PostgreSQL MFA authority (in development)

Passkey primary with an enrolled independent TOTP

PersistPasskeyContinuation requires the exact original PasskeyCommandID from the passkey Work and retains it through the canonical stored scope. Build the child using the core continuation's CapabilityPayload; do not patch its correlation afterward. Password/magic-link owners reject this separate origin. Old stored rows omit the field and keep their original bytes and deadlines.

RecoverPasskeyContinuation supplies only the MFA participant's historical vote in the exact passkey owner's borrowed recovery Work. Completed/revoked/ expired state does not erase original commitment. Missing rows vote noncommit only to the sole coordinator; conflicting child, immutable scope or original lineage stays unknown. It returns no credential and never authenticates a factor, retries an assertion or renews a challenge. Keep original rows until an owned retained-outcome mechanism replaces their recovery responsibility.

RequirePasskeySigninFactors fences a positive original factor generation and an actually confirmed TOTP row in the exact registered passkey owner's challenge-only signin Work. It requires the self-user, original command record and mfa.challenge.created.v1 zero-to-one lifecycle. Call in Apply and final checks; propagate every error to abort. Empty, changed, pending or foreign state cannot satisfy it. The existing single-factor/known-empty guards are unchanged.

This is a stored-authority guard, not passkey or TOTP authentication. The native owner must verify the original UV assertion, bind browser and primary expiry, create only the original MFA continuation/child, and complete the independent factor before any session issuance. No password purpose is borrowed, factor is enrolled, authority generation advanced or session produced by this function.

Current-session additional passkey enrollment

RequirePasskeySessionFactors admits the selected native enrollment phases from passkey/postgres only: register-options.session-assertion-options-v1, register-options.session-registration-options-v1 and register-verify.session-registration-v1 (all prefixed identity.passkey.). Their exact creation lifecycles are respectively passkey.reauthentication.started.v1, passkey.registration.started.v1 and identity.passkey.create_credential, each version 0 to 1. Call the guard in Apply and final precommit checks and propagate every error to abort Work.

The guard locks the original verified passkey session's known-empty factor generation, never initializes or adopts one, and denies active or changed MFA state. The native/protocol owners still authenticate genuine UV, enforce current session/CSRF and bind original intent and authorization expiry through all phases. This prerequisite grants no authentication, enrollment or HTTP endpoint by itself; password-proof and enrolled-factor profiles remain distinct.

Passkey-only signup authority

After real WebAuthn verification and kernel prospective account creation in the original identity.passkey.register-verify.signup-v1 Work, the native kernel.PasskeyRegistrationContributor calls InitializePasskeySignup. It uses Work.PasskeyRegistrationUser, so a current row, caller-selected ID or missing factor state cannot substitute for this command's actual new account. The initial known-empty generation is insert-only, with original command/purpose provenance. It does not invent an email, password, factor or recovery method.

Call RequirePasskeySignupFactors in Apply and the final precommit check. It repeats kernel creation/current-reference checks and locks that exact initial factor generation and provenance. Missing, enrolled or changed state denies without adopting another generation. Every error must abort the complete native account/protocol/session transaction. Neither function grants signup permission, WebAuthn assurance, session issuance or independent transaction ownership. Work remains borrowed, serial and invocation-bound.

Append PasskeySignupMigrationSource after the factor-authority history and selected historical magic-link/username successors. Previous migration bytes and rows are preserved; no empty-factor backfill is performed. This storage and owner seam alone does not expose a usable signup endpoint.

Selected email-OTP disable

NewOTPDisableService reuses the existing native factor mutation coordinator with explicit email-reset recovery and disable-purpose signed evidence. Select OTPActiveStepUpConfig.AllowedPurposes to include identity.mfa.disable and compose an OTP issuance owner with the same selected purposes. Empty purposes preserve the original factor-update-only identity. Install OTPDisableMigrationSource after OTP proof/management/removal history and the existing session-disable effect history before accepting disable. No installed migration bytes or TOTP profile are changed.

The supported profile has one active email-OTP factor. OneFactor preserves unconfirmed OTP siblings and returns only their safe metadata; AllFactors erases them. Both erase selected recipient references, retire selected recovery sets, consume the original proof, advance factor authority and revoke sessions with required events in the same Work. Recovery is original-command metadata, not renewed proof, another recovery-policy decision or repeat erasure. No HTTP, replacement, mixed-method active set or trusted-device profile is enabled. All-target supports at most 63 retained pending siblings beside the active OTP factor. Expired rows still in pending state count toward that bound. Overflow rolls back all effects; it does not partially erase the selected set or skip old rows. One-target retains untargeted pending history and recovery sets.

RequireOTPSessionFactor is the OTP-specific same-Work authority fence for native session self-logout. It requires the actual session-revoke-one owner, original enrollment/account versions and a still-verified matching recipient. It reads neither a code nor an expired login continuation, grants no new MFA action and never checks an OTP identity against the TOTP table. The session owner must first fence directory, password credential and policy authority; propagate any fence error so the existing coordinator aborts the whole command.

For explicitly selected verified-phone/password plus TOTP, the password owner retains its distinct original primary and browser. RequirePasswordSigninFactors and its method-bound variant admit only independent confirmed TOTP for that phone origin, never the phone/SMS itself as a second factor. Apply PhoneContinuationMigrationSource after the installed continuation history, setting UsernameSignin/VerificationSignin to its actual predecessor selections. Existing rows/checksums remain unchanged; an incorrect predecessor fails rather than dropping an unknown constraint. This suffix does not compare passwords, authorize another factor, issue a session or enable HTTP.

At initial phone-reset preparation, TOTPFactorReader.SelectForPhoneRecovery selects the lowest immutable confirmed TOTP ID for the genuinely resolved account and reads its encrypted snapshot. The existing recovery history supplies the subject-keyed factor lookup. Freeze that exact factor in the canonical grant; retry/completion uses ReadForPhoneRecovery for the original ID and must not select another factor after withdrawal. Selection is structural custody, not phone possession, factor verification or recovery authorization.

The bounded phone-password-reset integration reads the original confirmed encrypted factor using TOTPFactorReader.ReadForPhoneRecovery; this is structural custody, not recovery authorization, a fabricated login continuation or session. NewPhoneRecoveryTOTPVerifier takes the existing secret-envelope service plus an independent comparison key and positive retained key version. Prepare binds the exact joint input or generated command and decrypts outside database locks. Its exclusive original authority deadline must be microsecond-exact. Always defer PreparedPhoneRecoveryTOTP.Destroy, including when execution never starts. Copies share one-shot custody; verification moves the Secret under a short lock, does SQL without that lock, and clears it on every return. Destroy waits for an active bounded use outside the lock. A consuming phase must prepare afresh.

The exact native command retains phone.reset.factor-id (text), phone.reset.factor-version (enrollment uint64) and phone.reset.factor-authority-version (aggregate uint64), derived by the phone owner from its verified original reset capability. VerifyPhoneRecoveryTOTPAttempt accepts only the exact sealed input or generated command matching its prepared custody through the registered OTPAttemptWork owner, never a generic feature; its opaque, live-bound Accepted classification performs actual core TOTP verification but never advances replay. Only an actual crypto mismatch/replay is a false classification; stale or unavailable authority is an error. The OTP owner alone decides/debits the existing SMS challenge budget. There is no MFA-specific recovery budget, caller-writable successful-factor flag or scalar-step API.

The OTP reservation wrapper calls RequirePhoneRecoveryTOTPReservation and its first protected check calls RequirePhoneRecoveryTOTPApply after primary/flow admission, before challenge/lockout exclusions. Their exact live owner/command checks lock current user, aggregate and encrypted factor without comparison. VerifyAndRecordPhoneRecoveryTOTP independently rechecks the generated command and current database time, verifies the original opaque code, then advances only the internally verified replay step in the existing coordinator Work. Require its opaque completion's RequireRecorded inside the same Apply immediately before password effects. This rechecks the locks already acquired by the protected OTP check and fences exact ciphertext, profile, enrollment, row, replay and authority. The OTP owner's repeated commit check uses the actual opaque completion's RequireOTPApplyRecorded to fence only its verified successor. Kernel-owned RequireFeatureOrigin checks the exact same private Work and registered owners before and after those current factor/time locks; no general retained Work access is used. Ordinary RequireRecorded remains Apply-only. No decryption or provider callback runs under those locks. The parent phone/password workflow must still authenticate the canonical reset capability, exact phone/pre-auth/OTP/attempt/risk binding and current password authority and atomically commit all consumption, password/session effects and replay. These helpers alone enable no reset service or endpoint; unknown outcomes use the parent coordinator's existing original-command recovery. Encrypted factor/enrollment storage and retained-factor behavior are unchanged.

ReadPhoneFactors supplies preliminary actual known-empty factor metadata for the selected existing-account phone enrollment, replacement and removal profiles. Freeze that positive generation as the phone.factor-version uint64 field in the original command. RequirePhoneFactors admits only the exact self-user identity/phone/postgres owner's identity.phone.send-verification, identity.phone.verify, identity.phone.update and identity.phone.remove native-v1 schemas under identity.phone contract v1. Replacement sending additionally selects exactly identity.phone.send-verification.change.native-v1, without attaching a new identifier. Other schema aliases remain rejected. It rejects changed/missing generation fields and unknown phone.factor-* variants. Acquire original account/session locks first and call the guard in every protected admission phase, mutation and final precommit check; its actual factor row lock lasts until Work closes. Missing, enrolled, changed or corrupt authority denies without initialization, weaker fallback, proof issuance or renewal of original validity. The selected native owner must retain the original field through preparation and completion; these seams do not themselves implement phone or OTP enrollment.

RequireActionPrimaryFactors supplies the selected known-empty-factor fence for native username rename and organization ownership transfer. Freeze actual ReadPasswordSigninFactors generations as action-primary.actor-factor-version and action-primary.target-factor-version uint64 command fields. Rename is self- only; transfer binds distinct actor and target. Freeze the bounded observations before original intent. In every protected preparation stage that exists, and at least in mutation and final admission, acquire user/credential locks in canonical subject order before this guard. No separate preparation transaction is required. It locks actual factor rows at their original versions; first-factor activation, changed generation or unavailable state denies even if the original password session remains live. No MFA-bearing transfer/rename profile, proof issuance or factor initialization is enabled by this guard.

The same guard admits exact self-only identity.passkey.register-options, identity.passkey.register-verify and identity.passkey.update operations from the passkey/postgres contributor. Each retains its distinct .native-v1 schema and equal original actor/target factor generations. Update does not select deletion or weaken active-factor denial; the passkey owner still proves the exact signed action and applies metadata inside its sole protected Work.

Required-email username signup reuses InitializeSignup under the exact native password contributor's identity.username.signup/username-signup v1 scope. It requires actual account creation and original registration evidence in the same Work; a caller-supplied user ID or missing state cannot initialize absence. Append UsernameSignupMigrationSource after factor authorities and any selected historical magic-link suffix. It preserves all old rows and purpose arms and backfills nothing. Actual signin still reads/fences current factor authority; this initialization is not a proof, MFA bypass or permission to issue a session.

RequirePasswordSigninFactors also admits the exact native identity.username.signin/username-signin v1 password custody for known-empty factor admission. The owning password contributor must lock and fence the original generation through Apply and final commit. This does not enable a username MFA challenge: nonempty, missing or changed factor authority denies. The separate RequirePasswordSigninFactorMethods challenge path admits exact username/TOTP-only custody, and PersistPasswordContinuation retains that original action and immutable scope. Install UsernameContinuationMigrationSource after password continuations, with VerificationSignin set only when that verification-origin predecessor is installed. Mismatched history fails rather than silently adopting or rewriting a constraint. These seams do not compare passwords, enroll factors, issue sessions or enable another fallback method.

PersistPasskeyContinuation retains an explicitly selected UV-passkey primary's original TOTP-only continuation during the exact protected native challenge Apply. Its full frozen child scope, original primary command and current confirmed factor generation must agree. The assertion owner still proves the original browser, genuine WebAuthn result and primary expiry; this method issues no capability or session and never renews attempts or lifetime. Install PasskeyContinuationMigrationSource after the existing continuation history; its password/verification/username/phone flags describe already installed predecessors, not new authentication opt-ins. Default flags preserve only the original magic-link origin alongside the newly selected passkey origin.

The post-registration-verification signin profile uses ReadEmailVerificationSigninFactors and fences its unchanged generation with RequireEmailVerificationSigninFactors in Apply and final commit admission. Missing, nonempty, changed or corrupt primary state denies; nothing initializes or infers an empty account here. This is a known-empty profile, not enrolled MFA continuation or permission to downgrade a required factor.

The separately selected enrolled-TOTP profile uses ReadEmailVerificationMFAFactors and RequireEmailVerificationTOTPChallenge. PersistEmailVerificationContinuation accepts only its exact native owner and retains the separately committed confirmation ID in the signed scope. Install VerificationContinuationMigrationSource after the existing password-origin continuation history, at a new permanent version. Legacy persistence methods reject verification-origin scopes. These APIs do not authenticate the original signup proof or issue a session; the capability/session/native owners must authenticate that parent and repeat current checks in the sole transaction.

For TOTP-protected email change, explicitly set TOTPActiveStepUpConfig.EmailChange and install EmailChangeFactorMigrationSource after existing factor-proof history at a new forward version. NewEmailChangeFactorSource borrows that selected issuer. Its opaque admission authenticates exact original signed evidence; it is not an authorization ticket. The registered email owner must call Admit/Consume inside protected request Work and CheckConsumed on confirmation and final checks. It must separately fence original session, directory, credential and authorization policy. Prepare and Restore also take the consumer's frozen original session: a password/TOTP or password/recovery source retains its own factor enrollment and authority, even when step-up used a different factor. Protected checks and scanner discovery validate both original factor bindings. Reuse of the proof store/use marker is atomic with the email mutation; no second store, automatic verification consumption or fallback is provided. Zero/unselected configuration retains MFA-management-only purposes.

ReadEmailOTPFactors supplies only the actual known-empty factor generation for pending-email OTP preparation. RequireEmailOTPFactors must fence that same generation in the registered native OTP Send/completion Work. Missing, enrolled or changed authority denies before code use; neither method initializes account authority, grants a factor proof or weakens MFA. They borrow the existing pool or Work and retain its cancellation/lock lifetime.

RequireAdministrativeEmailFactors fences both the actual human actor and target at their independently retained known-empty generations inside the existing email-removal Work. Acquire canonical subject locks first. Missing, changed or nonempty authority denies; this API never initializes factors or grants a proof.

RequireActionPrimaryFactors also admits exact self-only organization archive/ restore under the organization-lifecycle schema and existing organization participant. Freeze equal actor/target generation fields from one actual known-empty actor read. It locks that one row, not an administrative target; an enrolled, changed or missing generation denies without password-only fallback. This guard does not implement organization lifecycle policy or effects.

NewOTPFactorReader reads confirmed owned OTP factors and their exact verified recipients only under a real live OTP-enabled child grant. Metadata and Recipient are original version/recipient custody, not code verification or session permission. Protected sending/completion must repeat current account, factor, identifier, policy, browser and absolute-time fences. Pending/revoked, foreign, exhausted, stale or unavailable authority denies. Public OTP login send/completion composition is supplied by the reference module for the selected password-origin profile; constructing or reading this factor alone is not login.

OTP factor storage under development

FactorReferenceMigrationSource follows existing TOTP/recovery history; OTPFactorMigrationSource follows those references and the kernel identifier history. Allocate permanent versions in the owned MFA namespace. Neither source changes prior migration bytes or selects an HTTP feature. The shared namespace contains immutable identity/method only, not verification or active-factor policy. Per-method records and current native admission remain authoritative.

The forward reference migration backfills TOTP identities under table locks. Existing TOTP inserts register the same identity transactionally. Recovery sets retain their original TOTP default and gain a method-bound reference; generated per-method references preserve factor-deletion restrictions without duplicating the recovery store. New OTP recovery writes must explicitly select factor_method otp. OTP rows bind exact identifier/verification versions; confirmation requires attribution and revocation clears recipient references. None of this proves possession of a code, recipient ownership, enrollment or authentication.

The migrations scan/backfill and acquire blocking DDL locks. Set bounded lock and statement timeouts and plan headroom before adoption. Security-invoker registration requires the native MFA writer's SELECT/INSERT privileges on the new reference table; no privileged definer or runtime business callback is added. Current local tests do not establish production-scale rollout or latency budgets. NewOTPEnrollmentConfig and NewOTPEnrollmentService explicitly select native pending enrollment without selecting a TOTP algorithm or generating its secret. Supply the same actual TOTPEnrollmentPrimarySource port implemented by the password primary adapter (including its cookie/CSRF variant), protected risk and counter owners, keyring and coordinator/request-key configuration. The historical port name does not create a second primary-proof authority. The constructor does no IO and does not initialize unknown account factor state.

Call Enable with FactorPolicy.Method="otp", a bounded recovery-code count and OTPEnrollmentSelection containing an existing verified identifier ID and its email/SMS channel. Native preparation freezes its versions; protected admission locks/rechecks them. First-factor enrollment requires known-empty active-factor authority and permits at most eight live pending TOTP/OTP ceremonies combined. Primary proof use, pending factor, inactive recovery codes, audit and lifecycle commit together. Only a fresh, error-free commit returns reveal-once recovery material. Destroy each returned secret after its explicit delivery.

An identical retry preserves the original outcome and returns no recovery codes; a known rolled-back command is not repeated under the same key. A new attempt requires a new key and current admission. RecoverEnable takes the original non-secret command scope and current result-access policy, not a password, code or bearer. Changing recipient or configured counter namespace cannot restore a retained original request. This pending service proves no OTP possession and does not activate a factor or issue a session. Sending and confirmation are separately selected below; OTP login and HTTP/reference remain under development.

Native pending-OTP sending

Append OTPSendMigrationSource after OTP factors (selected MFA history versions 13/14/15 for factor references/factors/send attribution). Historical prefixes remain unchanged. Select NewOTPEnrollmentSendService with the same OTPEnrollmentService, password's actual OTPEnrollmentSendPrimarySource, an otp/postgres.NewMFAEnrollmentIssuer and exact HTTPS origins. Initialize the issuer's stable keys against installed OTP and delivery histories first.

Call OtpSend with the pending factor ID, exact enrolled channel, idempotency key, trusted caller/origin/network and OTPEnrollmentContext containing the original session and synchronizer. The server assigns one command/challenge ID; no recipient, expiry or command ID is request-selectable. Current original primary, consumed enable proof, pending factor/recipient versions and protected risk must admit before generation and commit. Unknown outcomes retain the original command; retry cannot select a successor code or recipient.

Challenge creation, factor send attribution and encrypted delivery commit or roll back together. A committed StateQueued is historical queue acceptance, not provider delivery or confirmation. The actual delivery worker invokes the selected sender separately. RecoverOtpSend takes original non-secret scope and current result-access policy, never code, bearer or primary proof. Partial-login sends, confirmation, OTP session completion and HTTP are not supplied by this pending-enrollment-only service.

Native pending-OTP confirmation

Select NewOTPEnrollmentConfirmationService(sender, OTPEnrollmentConfirmationConfig{Primary: primary, AttemptKeyVersion: version}) with password's actual OTPEnrollmentConfirmationPrimarySource. The sender supplies the same real OTP owner and exact origin allowlist. Install OTP's ConsumingMigrationSource after its challenge history; retain the selected attempt key and all original wrapping, session, enrollment and digest keys.

Call OtpVerify with a new command ID, the pending factor ID, actual delivered code, original OTPEnrollmentContext and trusted caller/origin/network. The client cannot choose a challenge, recipient, parent proof or authority version. The service authenticates the committed original send's complete static root and encrypted output from existing request/preparation custody. It retains one random server-owned attempt in that same journal, never in another intent store. Wrong submissions debit the real OTP budget once; exact retry replays history. Changed same-command code or intent conflicts instead of creating another attempt.

Protected native primary/CSRF, factor, recipient, account and risk admission precedes comparison and is fenced again after waits. Confirmation atomically activates the pending OTP factor and its existing recovery set, advances factor authority and finalizes OTP, audit and lifecycle effects. Activation failure rolls those effects back and releases its original consuming reservation; the charged admission remains historical and a released challenge cannot be reused. An unknown outcome carries no enrollment metadata and requires original recovery.

RecoverOtpVerify accepts original code/proof/session-free scope with current result-access authorization. It never compares, debits, sends, reactivates or reveals a code. Successful confirmation returns historical enrollment metadata, not a login session or step-up proof. Trusted-device requests and login-child variants deny. This service confirms enrollment only. The reference module and opt-in HTTP handlers supply the selected password-primary continuation, sending and atomic session completion. OTP management, other channels and full release qualification remain pending; enrollment confirmation never issues a session.

Authenticated email-OTP factor rename

Select NewOTPActiveStepUpService over the actual OTP enrollment owner and otp/postgres.NewMFAActiveIssuer. Its consuming PurposeStepUp policy is separate from enrollment/login. Supply the actual native session primary, allowed origins, retained attempt/signature keys and bounded TTL. Install OTPFactorVerificationMigrationSource after the selected OTP histories.

OtpSend takes StepUp session/CSRF custody, the confirmed factor and an idempotency key. Process delivery through the existing worker. OtpVerify requires the exact original send, a new command and the delivered code, and returns one signed identity.mfa.factor-update proof. It does not issue a session or renew primary authentication. Wrong codes use the existing counted budget.

Select NewOTPFactorUpdateService with the same enrollment/step-up owners, actual factor-update primary and session effects. Append OTPFactorManagementMigrationSource and the selected session disposition histories. FactorUpdate(Rename) requires that original proof, source session, CSRF and optimistic inventory version. Proof use, label/version, account factor epoch, session revocation and required events commit atomically. The old session is no longer usable; a fresh password/OTP signin retains the renamed factor. Use NewOTPFactorManagementListReader for its safe managed labels, optionally including an independently selected TOTP management owner.

For sole-active email-OTP removal, explicitly select FactorUpdateConfig.RemovalRecoveryPath = authentication.RecoveryPathEmail and borrow password/postgres.NewFactorRemovalRecoverySource from a fully selected reset request/completion owner. Append OTPFactorRemovalMigrationSource after the installed OTP management history. FactorUpdate(Remove) takes the original fresh action proof and optimistic version with an empty name. It fences current usable email/password recovery, erases all three recipient references, retires the factor's recovery set, advances factor authority and revokes sessions in the same commit. Missing recovery or another active factor denies without mutation. The caller must sign in again; recovery never creates a session.

Retries and recovery disclose historical outcome, not another proof or fresh factor projection. Unsupported SMS, disable, replacement and HTTP variants remain separate; no TOTP fallback or new transaction engine is selected.

Native disable

NewDisableService(enrollment, stepup, DisableConfig) selects a distinct native disable operation, not a factor-update alias. Provide real DisablePrimarySource, session effects and the actual selected email-reset request/completion recovery owner; both maximum ages are positive and at most five minutes. Missing, changed or unavailable authority denies without fallback. Native calls own no private transactions or new proof journal; the existing coordinator owns atomicity.

Install DisableMigrationSource at permanently allocated MFA version11 after proof8/management9/removal10. Older histories and retained update receipts are unchanged. Select the corresponding session-disposition v3 extension. One/all are retained as distinct immutable request/effect scopes. All-target bounds older pending enrollments before erasure, supporting at most63 pending siblings beside the sole active TOTP, not arbitrary additional active factor methods. One-target leaves untargeted pending factors and their recovery sets unchanged. Its fresh result includes up to100 unexpired pending projections captured inside the same protected transaction, excluding revoked history. Unknown/replayed outcomes never return this snapshot. Safe metadata failure rolls back the mutation. Any overflow or unsupported authority rolls back all effects.

Safe selected-profile inventory

NewTOTPListReader(enrollment) borrows the existing real TOTP enrollment owner and its primary pool/read budget. Compose it with mfa.NewListService and the actual session/authorization owners; the reader alone is not an access endpoint. Install the existing factor/recovery histories. Listing creates no new schema, transaction, journal or goroutine and selects no ciphertext, verifier or replay counter. One bounded primary snapshot validates known authority and complete active recovery sets before reporting unused counts. Initial set epochs retain their existing interpretation; they are not equal to global factor generations.

This explicit TOTP-only profile has no trusted-device issuance or security-key owner. Its empty device projection is not fabricated empty unsupported storage. Unexpected active-factor inventory, incomplete code rows, missing authority or overflow fail without a partial result. Labels and usage times not stored by this profile remain absent. Full trusted-device/security-key support and release qualification remain required by the complete MFA goal.

NewOTPListReader(otpEnrollment) selects both native OTP and TOTP metadata from the OTP owner's installed shared histories, retaining the same complete- snapshot bounds and aggregate checks. It includes unexpired pending and retained revoked factors and counts only unused codes in active sets belonging to confirmed factors of the matching method. No OTP destination or secret is selected. NewOTPManagementListReader(otpEnrollment, totpManagement) additionally reads the selected TOTP manager's stored labels; both owners must borrow the same primary pool. This does not add OTP rename/removal, trusted-device or security-key support. The existing TOTP-only selection remains unchanged.

Native authenticated step-up and recovery replacement

Compose NewTOTPActiveStepUpService over the actual selected enrollment graph with the native current-session primary owner, exact allowed origins, fixed comparison key/version and original-evidence Ed25519 signing/retained public keys. It borrows the graph's pool, encryption, risk/counters and transaction coordinator; it starts no goroutine or independent journal. Persist original evidence using FactorVerificationMigrationSource. In selected reference graphs this is MFA version8, preserving password-continuation version7.

ActiveStepUpRateSource reads original authenticated session/factor custody without decrypting, comparing, consuming or issuing. Retain its exclusive deadline. Protected verification compares the actual enrolled TOTP and commits replay advancement, original signed evidence and audit/lifecycle together. Original prepared ciphertext is reused on retry; terminal replay/recovery cannot disclose proof again. Retain verification keys for historical evidence.

Compose NewRecoveryRegenerationService with that same step-up/enrollment graph, the native current-session primary and the session-owned replacement effects. Count is 1..64 and maximum proof age is positive, at most five minutes. The service uses authentication's existing original-proof validator, then locks and consumes actual stored proof use in protected Work. It retires all preceding sets, installs independent random128/base64url codes, advances factor authority and enlists bounded session revocation and events in one transaction. Neither source reads nor retries renew proof/session timestamps. Only the fresh known commit returns secrets; destroy them after delivery. Recovery is metadata-only.

The reference graph supplies native owners and migrations through MFAEnrollment.ActiveStepUp/.Regeneration; HTTP remains separately opt-in. These operations do not provide the remaining OTP, trusted-device, security-key or administrative-recovery workflows, nor complete module release qualification.

Install MigrationSource with a permanent version in the identity_mfa migration namespace after the kernel user and command histories. The source deliberately does not backfill existing users as having no factors. An unmanaged schema fails.

The native password owner invokes InitializeSignup after genuine same-transaction registration. Neutral collisions, foreign invocations and pre-existing users cannot initialize an empty generation. Rollback removes the account and generation together; retries use the kernel command journal, not an MFA retry journal.

RequireEmailRecovery runs only in an unchanged native reset invocation. It locks the subject's factor authority until coordinator commit/rollback. Missing state, active factors and stale expected generations deny. Completion must provide the nonzero factor version authenticated by original issuance custody. Propagate all errors to the coordinator; do not retain returned views outside Work.

RequireEmailRecoveryRequestPreparation selects known-empty state inside the exact anonymous native request preparation. Generation then binds that version into original issuance; final application calls RequireEmailRecovery with the same version. Neither preparation nor retry initializes missing authority.

Future factor writers must lock this same root and increment its version while applying required proof invalidation, session effects and audits. This initial module does not provide enrollment writers, protocol verification, recovery-code storage, session issuance or a complete reset service. Existing-account authority reconciliation remains necessary before email recovery is available to them.

Partial-authentication continuation storage

ContinuationMigrationSource appends the MFA continuation table after the factor-authority history. It preserves prior migration bytes and does not backfill or reset existing factor state. Continuations contain original scope metadata and proof digests, never bearer credentials or plaintext factor secrets.

The native magic-link challenge owner calls PersistMagicLinkContinuation only in its protected Apply invocation, after provisional primary consumption. The stored subject, original primary proof, browser flow, immutable scope digest, policy/factor generations and absolute times must match the kernel's frozen challenge. Missing, empty or changed factor authority denies. Duplicate insertion fails rather than resetting lifetime or attempts. Native current-method, browser, account, risk and policy checks remain the invoking workflow's responsibility.

The coordinator commits continuation, primary use, exact child issuance, audit and lifecycle together; a late failure rolls them all back. This storage API does not authenticate factors, complete a continuation, deliver a challenge or issue a session. Public MFA challenge/completion remains in development.

ContinuationReader restores exact original scope only for an already verified child grant and current primary authority. It is read-only, bounded and uncached; its result is not permission to complete MFA or issue a session.

Encrypted TOTP storage

Append TOTPFactorMigrationSource after the existing MFA history with a permanent new migration version. Pending enrollment, confirmed active factor and revoked factor are distinct states. Active factors require confirmation; revocation must erase encrypted custody. No users or enrollments are backfilled or activated.

TOTPFactorReader accepts a verified live TOTP-enabled child continuation and restores one confirmed factor's immutable encrypted snapshot. Foreign, pending, revoked or stale authority denies. Metadata is a version fence, not a proof; Envelope and EncryptionContext expose only encrypted custody and its exact versioned tenant/user/factor/enrollment/profile binding. Changing that profile cannot decrypt the original ciphertext. Wrapping-key rotation preserves context.

The MFA service decrypts outside locked callbacks and owns transient plaintext cleanup and opaque-secret destruction. The reader never verifies a code, spends an attempt, advances replay, activates a factor or issues a session. Final native completion must recheck the entire snapshot under its protected transaction. Enrollment writers, the public completion service and session wiring remain unfinished; installing this schema or reading ciphertext is not usable MFA.

Within the exact native counted-denial callback, LockTOTPAttempt acquires account, factor-authority, continuation and factor locks in that order. It checks the original browser scope, generations, absolute expiry and complete encrypted snapshot. Decrypt before entering the callback; the native MFA owner uses VerificationState and the original opaque code for bounded local comparison and separately checks current policy and primary-proof authority. No provider or application callback may run under these locks.

On actual rejection call RecordTOTPAttemptDenial and return MFAAttemptDenied. Propagate every error: the sole coordinator commits the shared-budget charge with denial audit and the original aborted command, or rolls them all back. Exact journal replay precedes comparison; exhaustion revokes the continuation without advancing successful factor replay or using the child. These serial-use handles deny after return or charge. Correct code must follow the independently protected successful-completion path; this denial-only storage API never authenticates a session.

Within the successful protected Apply, LockTOTPCompletion accepts only the unchanged original TOTP command and exact registered MFA owner, after provisional child consumption. It takes the same authority and full-snapshot locks as denial accounting. The native MFA service verifies the original opaque code against VerificationState using its already decrypted owned secret, then calls RecordTOTPCompletion with the resulting counter. A counter alone is not proof: zero, foreign, returned and already-recorded custody deny. The store never verifies a factor on the caller's behalf or authorizes a session from a scalar.

Successful replay advancement and terminal continuation completion spend one shared attempt and persist together in this transaction. Success on the final attempt records Completed, not Revoked. Original scope, remember policy and absolute lifetime are unchanged. Propagate any error and invoke the original- primary session owner in this same transaction; a later denial must roll back factor replay, continuation, child and session effects. The kernel owns exact retry/unknown-outcome recovery; this adapter creates no second journal.

The native session composition calls RequireRecordedTOTPCompletion with the same locked handle, Work, exact owner and unchanged command after recording. It verifies that this invocation actually advanced factor replay and completed the original continuation, with unchanged authority and committed original primary-command provenance. Zero, foreign, unrecorded or returned custody cannot be replaced by scalar session metadata. Returned original scope and pre-completion metadata are structural projections, not reusable proof.

RequireTOTPSessionFactor is the MFA-owned current factor fence for selected native session logout. It requires the exact registered session participant's live Work, original enrollment and factor generation, and locks the account, factor authority and confirmed factor. It starts no transaction, reads no secret and does not revive an expired child or renew session evidence. Directory, verified identifier and policy fences remain separately mandatory. Public reference integration exercises this owner with protected rollback and recovery.

RecordMissingTOTPAttemptDenial handles an authenticated missing/ineligible factor candidate in the exact live native attempt callback. The native owner supplies the original command-bound factor selection after browser, primary, directory, recipient and policy admission. The MFA owner independently locks and rechecks the account-wide factor epoch, original pending continuation and that factor's eligibility within the account before spending the existing shared budget. It does not accept an absence assertion or fabricated snapshot. A now-confirmed factor, stale authority, corrupt confirmed record or outage cannot be charged as absence; there is no successful verification/generation arm. The coordinator commits the provisional charge with protected counters, required denial audit and original terminal journal, or rolls them all back.

The owning MFA service must still verify the actual original opaque code before recording, enforce primary/browser/current policy, and persist the original- primary session in this same transaction. Positive native composition and its session effect remain in development; a guard or mapping alone is not MFA login.

Native factor label management

NewFactorUpdateService borrows the same enrollment and active-step-up owners, real native primary source and enlisted session effect. It owns no new pool, transaction, journal or goroutine. Positive primary/factor maximum ages are explicit and at most five minutes; earliest original proof, primary and authoritative observation expiry wins without renewal.

Install FactorManagementMigrationSource after the factor-verification history and the selected session factor-update disposition suffix. MFA v9 adds a bounded label and retained effects without modifying factor secrets or prior migrations. The default profile supports confirmed TOTP rename. Optimistic versions, current authority and one-time proof fences give one mutation winner; lifecycle failure rolls back label, proof and sessions. An unknown commit acknowledgement requires original-command outcome recovery, never proof or metadata redelivery.

NewTOTPManagementListReader explicitly borrows this selected manager to read the new safe label. Base NewTOTPListReader remains compatible with the previous schema. Neither reader infers authority from optional fields or reads secrets.

To additionally select removal of the sole confirmed TOTP, set FactorUpdateConfig.RemovalRecoveryPath to authentication.RecoveryPathEmail and borrow password/postgres.NewFactorRemovalRecoverySource from the actual selected native reset request/completion service. The source checks verified email and exactly one usable password reference under protected Work, retaining current row locks. Missing, ambiguous, blocked or unavailable recovery denies; there is no fallback or scalar assertion of recovery availability. Install the optional FactorRemovalMigrationSource v10 suffix after v9. Remove consumes the original factor proof, erases secret/replay material, retires dependent code sets, advances authority to known-empty and revokes all subject sessions atomically. Historical outcome recovery reads the retained removal disposition, not today's mutable email eligibility. Unsupported recovery paths and general multi-factor removal remain denied.

Selected pending TOTP replacement

Set FactorUpdateConfig.Replacement to TOTPReplacementConfig{RecoveryCodes: 10} (allowed count1..64). Nil preserves rename/removal configuration identity and does not enable replacement. Install optional TOTPReplacementMigrationSource v12 after the existing MFA history, without rewriting installed prefixes. The supported profile replaces the sole active confirmed TOTP using its original fresh factor-update proof, observed row version and actual recent primary session. Password/TOTP and password/recovery source sessions retain their existing factor fences through continuation; they do not fall back to single-factor admission. The initial optimistic version must be at most MaxUint64-2, reserving both initiation and retirement increments. Exhaustion denies before proof consumption or successor creation; rename/removal retain their original one-step bounds.

Initiation consumes the management proof but does not advance factor authority, retire old codes or revoke sessions. It creates one pending successor and returns its recovery material once. Explicitly compose TOTPReplacementContinuationConfig into URI and confirmation configuration, borrowing the same management owner, native original-session primary source and replacement session effect. The reference graph supplies these concrete owners; no caller-created enable record or forged password proof is needed. URI disclosure remains one-use and confirmation requires the pending successor's actual code, not the old factor's code.

Continuations retain the original session, proof, predecessor and parent-command identity. They acquire an actual current authority observation bounded at20seconds; copies never renew freshness. Original primary/proof age and enrollment expiry remain absolute ceilings. Benign predecessor replay updates are accepted while unchanged management authority is fenced; account blocking, revocation, factor epoch change or unavailable authority denies. Confirmation atomically retires old factor/code sets, advances the epoch and revokes every bounded subject session. Historical recovery authenticates retained effects without reviving a session or repeating URI/code delivery. Multi-factor/device/admin replacement is not provided by this selected sole-TOTP profile.

Native OTP-only signin admission

ReadOTPSigninFactors supplies preliminary known-empty state for the exact native identity.otp.signin/identity-otp-signin v1 consume profile. Freeze the original positive generation in encrypted native signin custody. The native owner must call RequireOTPSigninAttemptFactors before comparison or charging, RequireOTPSigninReservationFactors before reservation/rebind, RequireOTPSigninApplyFactors during protected admission, and RequireOTPSigninFinalizeFactors before finalization. Each accepts only its exact live opaque phase and registered native owner; no general Work is exposed. Supply the actual recipient authenticated by original custody, not the anonymous flow identifier. Missing, enrolled, corrupt or changed factor state denies; the same MFA row stays locked until the coordinator transaction closes. These guards never initialize state, enable weaker-factor fallback, renew authority, or alter historical recovery/release. Propagate every error to the coordinator.

Documentation

Overview

Package mfapostgres owns durable second-factor authority. It borrows the identity coordinator's protected transaction; it never starts its own.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FactorAuthorityKey

func FactorAuthorityKey(tenant identity.TenantID, user identity.UserID) (string, error)

FactorAuthorityKey derives the version-one account-factor scope key from exact canonical tenant/user IDs, without normalization or IO. It is lookup metadata, not authentication or a current generation. The key is "factor:v1:" plus unpadded base64url SHA-256 of "golib.identity.mfa.authority.v1\x00" and each ID framed by its big-endian uint16 UTF-8 byte length. This owned stable profile distinguishes tenant/user framing and never aliases a session or credential dimension. Invalid input returns zero and a redacted error.

func InitializeMagicLinkSignup

func InitializeMagicLinkSignup(ctx context.Context, w kernel.Work, owner kernel.FeatureExecutionContributor, command identity.Command, user identity.UserID) error

InitializeMagicLinkSignup establishes empty factor authority only for the account genuinely created by this original consuming Work, after provisional capability consumption. Existing/missing/foreign registration evidence and duplicate initialization deny, never upsert or erase enrollment. Account, factor, proof and session effects must commit together under the coordinator.

func InitializePasskeySignup

func InitializePasskeySignup(ctx context.Context, w kernel.Work, owner kernel.PasskeyRegistrationContributor, command identity.Command) error

InitializePasskeySignup establishes known-empty factor authority only after the kernel actually creates this original prospective passkey-only account in the native signup Apply. It never infers absence from a missing row or resets an existing generation. Duplicate initialization fails, not upserts. Real WebAuthn verification, signup policy and session issuance remain with the native owner. Propagate every error to abort the sole borrowed Work.

func InitializeSignup

func InitializeSignup(ctx context.Context, w kernel.Work, owner kernel.FeatureExecutionContributor, command identity.Command, user identity.UserID) error

InitializeSignup establishes known empty factor state only for the account genuinely created by this unchanged signup in the current coordinator Work. Call after kernel registration and before commit; neutral acceptance and pre-existing users cannot initialize state. Duplicate calls fail, not upsert or erase enrollment. The coordinator owns rollback/replay and resource life. This does not enroll, verify or disable a factor or grant recovery permission.

func PersistEmailVerificationContinuation

func PersistEmailVerificationContinuation(ctx context.Context, w kernel.Work, owner kernel.EmailVerificationMFAChallengeContributor, command identity.Command, c mfa.PartialAuthContinuation) error

PersistEmailVerificationContinuation stores the original pending challenge after separately committed verification, only in its exact native owner's protected Apply. The owner must authenticate its parent and original browser before this call. Full immutable scope, subject and current factor generation must match; no parent consumption, password evidence or session is invented. Duplicate insertion denies without resetting attempts or expiry. Every error must abort the sole Work with its child issuance, audit and lifecycle effects.

func PersistMagicLinkContinuation

func PersistMagicLinkContinuation(ctx context.Context, w kernel.Work, owner kernel.MagicLinkMFAChallengeContributor, command identity.Command, c mfa.PartialAuthContinuation) error

PersistMagicLinkContinuation stores one original challenge only during the exact native owner's protected Apply, after same-Work primary consumption. Frozen child scope, primary identity/expiry and enrolled factor generation must match. It starts no transaction, issues no capability/session and stores no bearer or factor secret. Return every error to the coordinator; all effects still depend on its final authority checks, child issuance and sole commit. Duplicate insertion denies instead of renewing lifetime or resetting attempts.

func PersistPasskeyContinuation

func PersistPasskeyContinuation(ctx context.Context, w kernel.Work, owner kernel.PasskeyMFAChallengeContributor, command identity.Command, c mfa.PartialAuthContinuation) error

PersistPasskeyContinuation stores the original pending TOTP-only challenge during its registered native UV assertion owner's protected Apply. The owner must first prove the genuine assertion and original browser in this Work. Frozen child scope, original primary identity and current enrolled factor generation must agree. This neither authenticates an assertion nor issues a capability/session. Duplicate insertion never resets attempts or expiry; propagate every error to the sole coordinator for atomic rollback.

func PersistPasswordContinuation

func PersistPasswordContinuation(ctx context.Context, w kernel.Work, owner kernel.PasswordMFAChallengeContributor, command identity.Command, c mfa.PartialAuthContinuation) error

PersistPasswordContinuation stores the original pending password-first challenge only within its comparison owner's exact protected Apply. The password owner must validate and persist its non-final signed primary in the same Work before calling this operation. This function neither compares a password nor issues a capability/session. It binds the frozen child scope and active factor generation; all errors must propagate to the sole coordinator. Duplicate insertion denies without resetting attempts or extending expiry.

func ReadAnonymousUpgradeFactors

func ReadAnonymousUpgradeFactors(ctx context.Context, pool *database.Pool, tenant identity.TenantID, user identity.UserID, maximumDuration time.Duration) (mfa.FactorAuthority, error)

ReadAnonymousUpgradeFactors reads the permanent target's actual known-empty MFA generation before the native owner freezes its upgrade. It is metadata, not target authentication, permission or a positive validity lease. Preserve the generation in mfa.anonymous-upgrade.factor-version and repeat its exact protected fence. Missing/enrolled state denies; it is never initialized here. The borrowed primary pool and 1ms..5s budget retain the existing factor owner's cancellation/resource semantics; no transaction, retry or goroutine is created.

func ReadEmailOTPFactors

func ReadEmailOTPFactors(ctx context.Context, pool *database.Pool, tenant identity.TenantID, user identity.UserID, maximumDuration time.Duration) (mfa.FactorAuthority, error)

ReadEmailOTPFactors reads the current native known-empty generation for preparation of an authenticated user's email-verification OTP target. It is preliminary metadata, not an authentication proof, cached lease or permission to issue/consume. The same generation MUST be fenced by RequireEmailOTPFactors in issuance and completion Work. Missing/enrolled/corrupt state denies; this never initializes rows or falls back to another recovery path. The pool is borrowed; no transaction, retries or goroutines are owned. MaximumDuration is explicit, 1ms..5s; earlier cancellation wins and provider errors are redacted.

func ReadEmailVerificationMFAFactors

func ReadEmailVerificationMFAFactors(ctx context.Context, pool *database.Pool, tenant identity.TenantID, user identity.UserID, maximum time.Duration) (mfa.FactorAuthority, error)

ReadEmailVerificationMFAFactors reads known current primary factor state for explicitly selected verification-origin MFA. Unlike the unchanged known-empty profile, enrolled state may select a challenge, never a session. Missing or corrupt authority denies; no absence is inferred or initialized. The native owner must fence the same generation in Work. Pool is borrowed; maximum is 1ms..5s and earlier cancellation wins. No callback or goroutine is owned.

func ReadEmailVerificationSigninFactors

func ReadEmailVerificationSigninFactors(ctx context.Context, pool *database.Pool, tenant identity.TenantID, user identity.UserID, maximum time.Duration) (mfa.FactorAuthority, error)

ReadEmailVerificationSigninFactors reads known-empty primary factor state for the explicitly selected post-registration-verification signin profile. Missing, enrolled or corrupt state denies without initializing or inferring absence. This is preliminary metadata, not authentication or a freshness lease. Fence the same generation with RequireEmailVerificationSigninFactors in protected Work. The borrowed pool is never closed; duration is 1ms..5s and earlier cancellation wins. No callbacks, transactions, retries or goroutines are owned.

func ReadMagicLinkChallengeOutcome

func ReadMagicLinkChallengeOutcome(ctx context.Context, pool *database.Pool, r identity.CommandResult, maximum time.Duration) (bool, error)

ReadMagicLinkChallengeOutcome classifies a previously authorized committed native receipt without exposing subject, factor or proof metadata. The caller must first obtain the receipt through the coordinator's current result-access policy. It is historical outcome metadata, never authentication permission. This bounded primary read owns no pool lifetime, mutation or provider callback.

func ReadMagicLinkChallengeRequired

func ReadMagicLinkChallengeRequired(ctx context.Context, pool *database.Pool, grant capability.Grant, maximum time.Duration) (bool, error)

ReadMagicLinkChallengeRequired selects a branch from primary factor state matching the verified original magic-link grant. Missing/stale state denies; absence never means no MFA. This bounded read grants no authentication and retains no freshness lease. Protected admission/execution must fence it again.

func ReadMagicLinkRequestFactors

func ReadMagicLinkRequestFactors(ctx context.Context, w kernel.Work, owner kernel.FeatureExecutionContributor, command identity.Command, user identity.UserID, expectedVersion uint64) (mfa.FactorAuthority, error)

ReadMagicLinkRequestFactors selects and locks actual factor generation for the explicitly MFA-enabled native request owner. It permits known enrolled state only to issue a primary email link, never a session or MFA proof. The consuming owner must independently fence this generation and require the enrolled second factor. Missing/foreign/stale state denies. Work retains the lock through commit; this starts no transaction, callback or retry.

func ReadOTPSigninFactors

func ReadOTPSigninFactors(ctx context.Context, pool *database.Pool, tenant identity.TenantID, user identity.UserID, maximum time.Duration) (mfa.FactorAuthority, error)

ReadOTPSigninFactors reads the current known-empty factor generation for the native OTP-only signin profile. Missing, enrolled or corrupt state denies; nothing initializes or infers absence. This is preliminary metadata, not authentication or a freshness lease. Freeze it in original native custody and fence the same generation in each counted, reservation and protected phase. The pool is borrowed; duration is 1ms..5s and earlier cancellation wins. No transaction, retry or goroutine is owned and provider errors are redacted.

func ReadPasskeySessionFactors

func ReadPasskeySessionFactors(ctx context.Context, pool *database.Pool, record session.Session, maximum time.Duration) error

ReadPasskeySessionFactors requires the record's original positive known-empty factor generation on the primary. Missing, enrolled, foreign or newer state denies; it never selects a replacement generation. The pool is borrowed and maximum is 1ms..5s, bounded by earlier cancellation. Success is neither authentication nor a freshness lease. The native passkey owner must retain its read-start time before contributing IO and fence again in protected Work.

func ReadPasswordSigninFactors

func ReadPasswordSigninFactors(ctx context.Context, pool *database.Pool, tenant identity.TenantID, user identity.UserID, maximum time.Duration) (uint64, bool, error)

ReadPasswordSigninFactors selects known primary factor state after password comparison. It grants no authentication or freshness lease; the native owner must fence the returned generation in its protected Work. Missing state denies rather than implying no MFA. The pool is borrowed and the read is bounded.

func ReadPhoneFactors

func ReadPhoneFactors(ctx context.Context, pool *database.Pool, tenant identity.TenantID, user identity.UserID, maximumDuration time.Duration) (mfa.FactorAuthority, error)

ReadPhoneFactors reads actual known-empty factor authority before the native existing-account phone owner freezes its original command. It is preliminary metadata, not authentication, enrollment or permission to issue/consume OTP. Retain its positive generation as the uint64 phone.factor-version command field and fence it using RequirePhoneFactors in protected admission, mutation and final checks. Missing, enrolled or corrupt state denies without initializing authority. The pool is borrowed; maximumDuration is explicit, 1ms..5s, and earlier cancellation wins. No transaction, retry or goroutine is created.

func RecordMissingTOTPAttemptDenial

func RecordMissingTOTPAttemptDenial(ctx context.Context, w kernel.MFATOTPAttemptWork, owner kernel.MFATOTPAttemptContributor, factorID string) error

RecordMissingTOTPAttemptDenial rechecks an authenticated absent/ineligible factor candidate under the exact registered live attempt owner. It locks the current account, factor authority and original continuation, then checks the submitted factor within that account. A now-confirmed factor, changed epoch, expired continuation, corrupt confirmed record or outage cannot be charged. One shared attempt is provisional; return MFAAttemptDenied to the coordinator so counters, denial audit and original journal commit atomically. No secret, successful replay, child use or session is read/created. No transaction starts.

func RecordOTPCompletion

func RecordOTPCompletion(ctx context.Context, w kernel.Work, owner kernel.MFACompletionContributor, command identity.Command, c LockedOTPCompletion) error

RecordOTPCompletion atomically spends one shared attempt and completes this original continuation after actual consuming OTP/child checks. OTP replay state stays at its native owner. Errors abort all provisional effects; copies cannot record again, and no token or session is created by this helper.

func RecordOTPCompletionAttemptDenial

func RecordOTPCompletionAttemptDenial(ctx context.Context, w kernel.MFAOTPAttemptWork, owner kernel.MFAOTPAttemptContributor, locked LockedOTPCompletionAttempt) error

RecordOTPCompletionAttemptDenial debits the same original shared MFA budget only after the coordinator reports an actual native OTP denial. OTP debit, this CAS, protected risk, audit and terminal command commit atomically there. Correct-code probing rolls both owners back. No OTP code is compared here. Copies cannot debit twice; propagate every error to abort the transaction.

func RecordOTPLoginSendSource

func RecordOTPLoginSendSource(ctx context.Context, w kernel.Work, owner kernel.FeatureExecutionContributor, command identity.Command, expected OTPFactorMetadata, primary identity.CommandID) error

RecordOTPLoginSendSource attaches this send to its original child in the same protected Work as actual OTP/delivery persistence. The registered native owner must already have persisted those effects and admitted original primary, cookie, factor, recipient, policy and risk; this helper grants none of them. Exact current factor/child fences repeat before the write. No scope, version, deadline, primary, attempts, child uses or session is changed. Retry/recovery never writes attribution. Resends select a new committed send atomically.

func RecordRecoveryAttemptDenial

RecordRecoveryAttemptDenial charges one shared attempt only after this same live callback's actual comparison found no unused matching code. Correct, foreign, zero, spent or returned custody denies. The coordinator commits this charge with protected risk, denial audit and original journal receipt; any error must abort. It does not consume the code/child or advance TOTP replay.

func RecordRecoveryCompletion

func RecordRecoveryCompletion(ctx context.Context, w kernel.Work, owner kernel.MFACompletionContributor, a LockedRecoveryCompletion) error

RecordRecoveryCompletion burns the same just-compared unused code and completes its original continuation, spending one shared attempt even on the final allowed attempt. Set versions, child, session, audit and risk must commit or roll back together through the sole coordinator. Foreign, returned, repeated or stale custody denies. Every error must abort; no independent commit occurs.

func RecordTOTPAttemptDenial

RecordTOTPAttemptDenial provisionally charges exactly one shared attempt for the locked original continuation after the native owner actually denies the opaque TOTP code. It advances version and revokes on exhaustion without touching encrypted factor/replay, child consumption or sessions. The caller must return MFAAttemptDenied to the sole coordinator; audit, journal and the charge commit together there. Any error must abort, never be ignored. Copies cannot charge twice; this handle is serial-use and invalidated after success.

func RecordTOTPCompletion

func RecordTOTPCompletion(ctx context.Context, w kernel.Work, owner kernel.MFACompletionContributor, a LockedTOTPCompletion, step uint64) error

RecordTOTPCompletion persists the native owner's just-verified counter and terminal continuation in the same borrowed transaction. A counter is not authentication: the exact owner must first verify the original opaque code against VerificationState inside this Apply. The store enforces current window, replay, row/continuation versions and shared budget, but does not decide factor policy or issue sessions. All errors must abort. Session, child finalization, audit and these provisional effects commit or roll back together through the sole coordinator; no separate transaction is started.

func RecoverEmailChangeUse

RecoverEmailChangeUse reads only durable consumption metadata for the exact registered email request. It grants no authority or replacement proof; the sole command journal resolves a committed/unknown result independently.

func RecoverMagicLinkChallenge

RecoverMagicLinkChallenge compares durable original continuation evidence with the exact frozen native challenge. It reads only through the sole coordinator's recovery Work. Mutable attempt/state updates do not renew or erase original issuance evidence. It cannot return credentials or authorize a factor/session. Missing rows contribute no committed effect; only the coordinator's complete participant set can establish transaction rollback. Corrupt evidence remains unknown. Original continuation records are retained authority evidence and must not be pruned without a retained outcome owner.

func RecoverPasskeyContinuation

RecoverPasskeyContinuation compares retained MFA-owned evidence with the exact registered native passkey owner's original challenge in recovery Work. It grants no assertion, factor, session or credential-disclosure permission. Completed, revoked and expired challenges retain their original commitment evidence; recovery never resets state, attempts or expiry. Missing evidence votes only for this participant's noncommit; the sole coordinator must still reconcile every participant. Conflicting or corrupt evidence stays Unknown. Original rows must not be pruned without a retained outcome owner. No pool, transaction, callback, goroutine or rows are retained beyond this invocation.

func RequireActionPrimaryFactors

func RequireActionPrimaryFactors(ctx context.Context, w kernel.Work, owner kernel.FeatureExecutionContributor, command identity.Command, actorVersion, targetVersion uint64) error

RequireActionPrimaryFactors fences original known-empty MFA generations for selected native username rename, organization transfer/lifecycle and self-only passkey enrollment, credential-label update and self-deletion. Read the generations using ReadPasswordSigninFactors before freezing command intent; bind both action-primary.actor-factor-version and action-primary.target-factor-version as uint64 fields. Username rename is self-only and requires equal versions, as do archive and restore. Transfer requires distinct subjects. Missing, changed or enrolled state denies; no factor is initialized and no password-only fallback is inferred from session metadata.

Freeze the bounded observations before original intent. In every protected preparation stage that exists, and at least in Apply and final precommit admission, acquire user/credential locks in canonical subject order before calling this guard. No separate preparation transaction is required. Factor locks follow canonical subject order and last until Work closes. Errors must abort Work. This guard creates no proof, transaction, callback, resource or goroutine and never refreshes retained authority.

func RequireAdministrativeEmailFactors

func RequireAdministrativeEmailFactors(ctx context.Context, w kernel.Work, owner kernel.FeatureExecutionContributor, command identity.Command, actorVersion, targetVersion uint64) error

RequireAdministrativeEmailFactors fences independently known-empty actor and target MFA generations for the explicit native administrative removal profile. The command must bind both generations and its distinct actor/target scope; arbitrary role flags, missing rows or target factor state never establish actor eligibility. Enrolled/changed/unknown state denies without downgrade. User rows must already be acquired through RequireEmailRemovalSubjects; factor locks follow the same canonical subject order until Work closes. No proof is created/consumed, state initialized or command scope rewritten.

func RequireAnonymousUpgradeFactors

func RequireAnonymousUpgradeFactors(ctx context.Context, w kernel.Work, owner kernel.FeatureExecutionContributor, command identity.Command, expectedVersion uint64) (mfa.FactorAuthority, error)

RequireAnonymousUpgradeFactors locks the original permanent target's known- empty generation in either exact native issuance admission or protected upgrade. Guest state cannot select the target's factors. Call after canonical account/session locks and repeat during final checks; the row remains locked until the sole coordinator closes Work. Missing, changed, enrolled or corrupt authority denies without fallback, initialization or renewed freshness.

func RequireEmailOTPFactors

func RequireEmailOTPFactors(ctx context.Context, w kernel.Work, owner kernel.FeatureExecutionContributor, command identity.Command, expectedVersion uint64) (mfa.FactorAuthority, error)

RequireEmailOTPFactors fences the original known-empty factor generation for the exact registered authenticated-session OTP sender, native email-verify or email-change-confirm owner. It is valid in preparation, Apply and final checks. The factor lock remains held until the sole coordinator Work closes. It grants no session, code, address or mutation authority and never renews original validity.

func RequireEmailRecovery

func RequireEmailRecovery(ctx context.Context, w kernel.Work, owner kernel.FeatureExecutionContributor, command identity.Command, user identity.UserID, expectedVersion uint64) (mfa.FactorAuthority, error)

RequireEmailRecovery locks the current MFA generation for this native reset until the sole coordinator commits or rolls back. Missing or enrolled state denies; no absence is inferred from schema installation or session metadata. Request permits expectedVersion=0 to select current known-empty state; completion requires the nonzero generation authenticated by original custody. Account/email/risk/capability admission remain independently required. Return errors to the coordinator. A returned view must not be cached or used after Work closes. This function starts no transaction, retry or goroutine.

func RequireEmailRecoveryPreparation

func RequireEmailRecoveryPreparation(ctx context.Context, w kernel.Work, owner kernel.FeaturePreparationContributor, command identity.Command, user identity.UserID, expectedVersion uint64) (mfa.FactorAuthority, error)

RequireEmailRecoveryPreparation fences the signed original factor generation before reset-completion generation. Only the exact registered preparation owner's active Work and unchanged reset input scope are accepted. It retains the primary row lock through that admission transaction; final mutation must independently call RequireEmailRecovery again, since generation runs outside the transaction. It never infers absence, initializes state or authorizes hashing, capability consumption or password replacement by itself.

func RequireEmailRecoveryRequestPreparation

func RequireEmailRecoveryRequestPreparation(ctx context.Context, w kernel.Work, owner kernel.FeaturePreparationContributor, command identity.Command, user identity.UserID) (mfa.FactorAuthority, error)

RequireEmailRecoveryRequestPreparation selects and locks current known-empty factor authority for the exact anonymous native reset-request preparation. Missing or enrolled authority denies; it never initializes or infers state. The selected generation must enter original signed issuance and be fenced again at final Work because generation runs outside this transaction.

func RequireEmailVerificationSigninFactors

func RequireEmailVerificationSigninFactors(ctx context.Context, w kernel.Work, owner kernel.FeatureExecutionContributor, command identity.Command, expectedVersion uint64) (mfa.FactorAuthority, error)

RequireEmailVerificationSigninFactors locks the unchanged known-empty factor generation only for the exact email-owned post-verification signin command. Apply and final commit admission must both check it; errors abort Work. The lock lasts until the sole coordinator closes Work. Other email verification, password, OTP and magic-link profiles cannot select this fence. No proof, session or authentication authority is produced or renewed.

func RequireEmailVerificationTOTPChallenge

func RequireEmailVerificationTOTPChallenge(ctx context.Context, w kernel.Work, owner kernel.EmailVerificationMFAChallengeContributor, command identity.Command, version uint64) error

RequireEmailVerificationTOTPChallenge locks the unchanged enrolled factor generation for the exact native verification challenge owner, in preparation, Apply or final admission. A genuine confirmed TOTP secret must exist. Other methods cannot substitute for it, and this reader grants no possession, challenge, factor attempt or session authority. Locks share the sole Work; propagate every error. No transaction, provider or callback is started.

func RequireMFAPasskeySessionFactors

func RequireMFAPasskeySessionFactors(ctx context.Context, w kernel.Work, owner kernel.FeatureExecutionContributor, record session.Session) error

RequireMFAPasskeySessionFactors fences the original confirmed TOTP enrollment and account-wide factor generation of a completed passkey/TOTP session, only in exact native passkey label-update, additional-key enrollment or removal Work. It does not broaden the known-empty guard or permit signin.

The registered native owner must authenticate possession and fence directory, credential, policy and original session/family, and require genuine fresh action-bound UV for the mutation. Call in Apply and final checks, before RP mapping locks, returning any error to abort the coordinator's transaction. Account/factor locks remain owned by that coordinator. No factor secret, replay counter, generation, proof or freshness lease is created or changed.

func RequireMagicLinkFactors

func RequireMagicLinkFactors(ctx context.Context, w kernel.Work, owner kernel.FeatureExecutionContributor, command identity.Command, user identity.UserID, expectedVersion uint64) (mfa.FactorAuthority, error)

RequireMagicLinkFactors locks the real MFA generation for the exact native anonymous magic-link owner in its active preparation/execution Work. Missing or enrolled state denies; this single-factor email path cannot bypass MFA. Request may select current known-empty state with expectedVersion zero; consume must match a positive generation authenticated by original issuance. Retain the returned version in original custody and recheck at final Work. This does not initialize, enroll or remove factors, authenticate a browser, consume a link or issue a session. Return every error to the coordinator.

func RequireMagicLinkTOTPChallenge

func RequireMagicLinkTOTPChallenge(ctx context.Context, w kernel.Work, owner kernel.MagicLinkMFAChallengeContributor, c identity.Command, user identity.UserID, version uint64) error

RequireMagicLinkTOTPChallenge fences enrolled authority and an actually confirmed TOTP method for the exact native challenge-only consuming owner. It is permitted in original preparation and protected final execution, never single-factor/session or request phases. Factor row locking stabilizes method state through Work. No secret, provider, proof, session or mutation is exposed.

func RequireManagedEmailFactors

func RequireManagedEmailFactors(ctx context.Context, w kernel.Work, owner kernel.FeatureExecutionContributor, command identity.Command, expectedVersion uint64) (mfa.FactorAuthority, error)

RequireManagedEmailFactors fences known empty MFA at its exact retained generation for the registered self-user email owner. It is valid during preparation, Apply and final checks, but grants no proof or mutation authority. Missing/enrolled/changed state denies; no initialization or absence inference occurs. The sole Work retains the primary factor lock until it closes.

func RequireOTPLoginSendFactor

func RequireOTPLoginSendFactor(ctx context.Context, w kernel.Work, owner kernel.FeatureExecutionContributor, command identity.Command, expected OTPFactorMetadata, primary identity.CommandID) error

RequireOTPLoginSendFactor fences the native owner's original confirmed factor, verified recipient and live explicitly OTP-enabled continuation in its sole protected Work. expected/primary must originate from the actual reader/signed child and authenticated original preparation, never transport projections. Metadata is not proof: the owner separately checks original browser/password, directory, policy, child validity and risk. Locks follow account, factor authority, continuation, factor/identifier order and last until Work closes. No code, budget, child, session, timestamp or enrollment is mutated/renewed. Zero/foreign/returned ownership and changed authority deny; propagate errors.

func RequireOTPSessionFactor

func RequireOTPSessionFactor(ctx context.Context, w kernel.Work, owner kernel.FeatureExecutionContributor, user identity.UserID, factorID string, expected OTPSessionFactorState) error

RequireOTPSessionFactor fences the original confirmed OTP enrollment, current verified recipient and account-wide factor epoch inside native session-revoke- one or explicitly selected active-OTP MFA Work. It grants no OTP comparison, TOTP fallback or factor-mutation authority. Directory, primary credential and policy must already be fenced by that owner. Locks follow account, factor authority, then factor/recipient and remain owned by the coordinator until commit/rollback. Missing, stale or unavailable state denies; propagate every error to abort. Historical login-child expiry is not session validity, and this operation changes no OTP or replay counter.

func RequireOTPSigninApplyFactors

func RequireOTPSigninApplyFactors(ctx context.Context, w kernel.OTPApplyWork, owner kernel.OTPReservationContributor, user identity.UserID, expectedVersion uint64) error

RequireOTPSigninApplyFactors locks the unchanged original known-empty MFA generation during native OTP signin protected admission, without exposing the code or general Work. The actual custody-authenticated recipient is required; errors abort the coordinator transaction and the lock lasts until it closes. Finalization must independently repeat this fence. No authority is renewed.

func RequireOTPSigninAttemptFactors

func RequireOTPSigninAttemptFactors(ctx context.Context, w kernel.OTPAttemptWork, owner kernel.OTPAttemptContributor, user identity.UserID, expectedVersion uint64) error

RequireOTPSigninAttemptFactors fences the original known-empty MFA generation before the exact live native OTP signin owner compares or charges an attempt. The supplied user must be the actual recipient authenticated by original native custody, including for anonymous-flow commands. Errors must abort the coordinator phase; the row lock lasts until its transaction closes. It grants no code, session or authentication authority and owns no transaction or retry.

func RequireOTPSigninFinalizeFactors

func RequireOTPSigninFinalizeFactors(ctx context.Context, w kernel.OTPFinalizeWork, owner kernel.OTPReservationContributor, user identity.UserID, expectedVersion uint64) error

RequireOTPSigninFinalizeFactors repeats the original known-empty generation fence immediately before native OTP signin finalization. It accepts only the exact owner's live finalization handle and custody-authenticated recipient. Propagate errors to roll back all protected effects; the coordinator retains the factor lock through its sole commit. Recovery and release are unaffected.

func RequireOTPSigninReservationFactors

func RequireOTPSigninReservationFactors(ctx context.Context, w kernel.OTPReservationWork, owner kernel.OTPReservationContributor, user identity.UserID, expectedVersion uint64) error

RequireOTPSigninReservationFactors fences the unchanged original known-empty generation before native OTP signin reservation or rebind. Only the exact live owner and consume profile are accepted. The recipient, error propagation and transaction-owned lock rules match RequireOTPSigninAttemptFactors; this does not authorize comparison, consumption, a session, or a recovery downgrade.

func RequirePasskeySessionFactors

func RequirePasskeySessionFactors(ctx context.Context, w kernel.Work, owner kernel.FeatureExecutionContributor, record session.Session) error

RequirePasskeySessionFactors locks the original known-empty MFA generation only in exact native identified passkey signin, action-bound label-update or additional-enrollment/removal phases, or self-session revoke-one Work. The registered owner must already bind the genuine original command and record and fence directory, credential, policy and RP/mapping authority. Signin targets this exact new record; revocation also permits the caller's same-user source session when its target is a sibling. Call in Apply and final checks, returning every error to abort. Locks belong to the sole coordinator until commit/abort. No authentication, transaction, generation adoption, factor mutation, proof consumption or journal is created here.

func RequirePasskeySigninFactors

func RequirePasskeySigninFactors(ctx context.Context, w kernel.Work, owner kernel.PasskeyMFAChallengeContributor, command identity.Command, user identity.UserID, version uint64) error

RequirePasskeySigninFactors locks the original positive factor generation in an exact self-user native passkey-primary challenge Work. A confirmed TOTP is required; a passkey primary is not itself an enrolled second factor. Call in Apply and final checks, returning every error to abort the sole transaction. The registered owner must separately verify its genuine assertion and bind original expiry, browser, policy, credential/passkey epochs and continuation. Missing, empty, changed or unrelated state denies. No factor is enrolled, generation adopted, attempt consumed, proof minted or session issued here. Work/resources remain borrowed; earlier cancellation wins over the owner bound.

func RequirePasskeySignupFactors

func RequirePasskeySignupFactors(ctx context.Context, w kernel.Work, owner kernel.PasskeyRegistrationContributor, command identity.Command) (mfa.FactorAuthority, error)

RequirePasskeySignupFactors locks the known-empty initial factor generation and its exact signup-command provenance during native Apply or final Check. The kernel must independently retain this Work's actual created user and credential reference. Missing/enrolled/changed/foreign state denies; it never selects a newer generation or supplies authentication/recovery permission. The returned projection is provisional, not a cacheable validity lease. Return every error to the coordinator so all account/session effects abort.

func RequirePasswordSigninFactorMethods

func RequirePasswordSigninFactorMethods(ctx context.Context, w kernel.Work, owner kernel.FeatureExecutionContributor, command identity.Command, user identity.UserID, version uint64, methods []string) error

RequirePasswordSigninFactorMethods fences explicit password-first TOTP/OTP selection in the native challenge transaction. Supply the unchanged methods from the authenticated original continuation, not request-selected strings. At least one selected primary factor must be confirmed; recovery alone is not enrollment. OTP additionally requires its owned verified identifier at exact retained versions/channel. Missing selected storage denies. Neither verified email nor an unrelated enrolled method authorizes a challenge. The borrowed slice must not be mutated during this call. No method, proof or session is issued here; completion repeats its own current authority and budget fences.

func RequirePasswordSigninFactors

func RequirePasswordSigninFactors(ctx context.Context, w kernel.Work, owner kernel.FeatureExecutionContributor, command identity.Command, user identity.UserID, version uint64, challenge bool) error

RequirePasswordSigninFactors locks the exact current generation through the sole password transaction. A challenge requires its closed native owner and a confirmed TOTP method; SFA requires known empty state. No secret or session is returned and every error must abort Work. Original expectedVersion is never replaced by the latest generation. Both Apply and final commit checks may use this guard; it creates no transaction, callback, enrollment or factor attempt.

func RequirePhoneFactors

func RequirePhoneFactors(ctx context.Context, w kernel.Work, owner kernel.FeatureExecutionContributor, command identity.Command, expectedVersion uint64) (mfa.FactorAuthority, error)

RequirePhoneFactors fences the original known-empty factor generation for the exact registered self-user native phone enrollment, replacement or removal owner, including replacement's non-attaching send schema. The command must retain phone.factor-version as uint64 equal to expectedVersion; unknown phone.factor-* fields deny. Acquire original account/session locks first and repeat this check in every protected admission phase and final precommit check. The actual factor row stays locked until coordinator Work closes. Missing, changed, enrolled or corrupt authority denies; no row is initialized, original validity renewed, or weaker fallback selected. This grants no phone/OTP mutation or authentication proof. Errors must abort Work; the function owns no transaction, retry, callback, resource or goroutine.

func RequirePhoneRecoveryTOTPApply

func RequirePhoneRecoveryTOTPApply(ctx context.Context, w kernel.OTPApplyWork, owner kernel.OTPReservationContributor, snapshot TOTPFactorSnapshot, until time.Time) error

RequirePhoneRecoveryTOTPApply reacquires the full original encrypted factor fence in the protected transaction BEFORE the OTP owner acquires its shared lockouts/challenge exclusions. Reservation's locks ended with its transaction. Only the exact registered owner's live consuming OTPApplyWork and closed code-free phone-reset scope are accepted. It locks active user, aggregate then factor, checking original enrollment/authority/ciphertext/profile/replay and current database time without decrypting, comparing, advancing replay, or granting factor proof. Errors must abort. The feature's later Apply must still independently verify the actual TOTP and CAS replay through its MFA owner.

func RequirePhoneRecoveryTOTPReservation

func RequirePhoneRecoveryTOTPReservation(ctx context.Context, w kernel.OTPReservationWork, owner kernel.OTPReservationContributor, command identity.Command, snapshot TOTPFactorSnapshot, until time.Time) error

RequirePhoneRecoveryTOTPReservation fences the original encrypted factor for the exact registered OTP reservation owner and unchanged generated joint command. Call BEFORE the OTP owner acquires lockout/exclusion/challenge locks: this locks current active user, aggregate and factor in canonical order until the parent coordinator closes its transaction. It checks original deadline, enrollment/aggregate/row/profile/ciphertext/replay without decrypting, comparing a code, advancing replay, charging a budget or granting factor proof. Errors must abort. Apply independently verifies the actual TOTP and replay CAS; no transaction, callback, renewal, successful-factor scalar or retry is created.

func RequirePhoneResetIssuance

func RequirePhoneResetIssuance(ctx context.Context, w kernel.Work, owner kernel.FeatureExecutionContributor, command identity.Command, snapshot TOTPFactorSnapshot, original session.PreAuthTransaction) error

RequirePhoneResetIssuance repeats the full original factor fence in the exact phone request's live Apply Work. It grants no factor proof, capability, risk allowance or permission to issue SMS by itself. Every error must abort the parent transaction. No SQL transaction, callback, crypto or retry is created.

func RequirePhoneResetIssuancePreparation

func RequirePhoneResetIssuancePreparation(ctx context.Context, w kernel.Work, owner kernel.FeaturePreparationContributor, command identity.Command, snapshot TOTPFactorSnapshot, original session.PreAuthTransaction) error

RequirePhoneResetIssuancePreparation locks the original confirmed encrypted TOTP factor for the exact registered phone-reset request preparation. Call after primary, original pre-auth and verified-recipient admission, before OTP send-family/lockout/challenge locks. It retains user→aggregate→factor locks only in the borrowed Work, without decryption, comparison or replay mutation. Original is the actual recovery pre-auth admitted by its native owner, not an application clearance. Its original absolute expiry is never extended. This is eligibility only; Apply must independently repeat all current fences.

func RequireTOTPSessionFactor

func RequireTOTPSessionFactor(ctx context.Context, w kernel.Work, owner kernel.FeatureExecutionContributor, user identity.UserID, factorID string, expected TOTPSessionFactorState) error

RequireTOTPSessionFactor fences the original confirmed TOTP enrollment and account-wide factor generation inside exact native session-revoke-one or authenticated MFA-action Work. Directory, primary and policy must already be fenced. Locks are account, factor authority, then selected factor; the coordinator owns their lifetime and rollback. No secret, child or replay counter is read or changed, and historical continuation expiry is not session validity. Missing, changed or unavailable authority denies; return any error to abort.

Types

type ContinuationMigrationSource

type ContinuationMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

ContinuationMigrationSource appends durable partial-authentication state to the existing MFA history. Base must install factor authority after kernel users/commands. Allocate Version permanently after Base in its namespace. Existing factors and continuations are not inferred, reset or backfilled.

func (ContinuationMigrationSource) Load

Load preserves prior migration bytes and returns forward-only SQL without IO. Zero, typed-nil Base, empty history and conflicting version order deny.

type ContinuationReader

type ContinuationReader struct {
	// contains filtered or unexported fields
}

ContinuationReader restores original scope from primary PostgreSQL authority. It owns no connection, transaction or cache. Concurrent reads are safe; the caller owns the pool lifetime. A returned projection is not factor proof or permission to issue a session: protected execution must recheck authority and atomically consume the child and factor under the sole coordinator.

func NewContinuationReader

func NewContinuationReader(pool *database.Pool, maximumDuration time.Duration) (*ContinuationReader, error)

NewContinuationReader borrows a primary pool and limits each read to at most five seconds. Earlier caller deadlines win. No database work occurs here.

func (*ContinuationReader) Read

Read requires an already verified child grant and the configured issuer. It restores exact original scope and current attempt state without reserving, consuming or renewing anything. Missing, expired, inactive, uncommitted or changed factor authority denies. Storage failures fail closed; cancellation is preserved. No bearer or factor secret is returned.

type DisableConfig

type DisableConfig struct {
	Primary                       DisablePrimarySource
	Sessions                      RecoveryRegenerationSessionEffects
	RecoveryPath                  auth.RecoveryPath
	Recovery                      FactorRemovalRecoverySource
	MaximumAge, PrimaryMaximumAge time.Duration
}

DisableConfig selects a native sole-active-factor/email-reset profile through the method-specific constructor (TOTP or email OTP). One/all scopes are distinct immutable intents. Additional active factor methods/counts deny rather than silently being skipped. RecoveryPath must be Email and Recovery must borrow the actual selected reset request/completion owner. Both maximum ages are positive and at most five minutes.

func (DisableConfig) Format

func (DisableConfig) Format(s fmt.State, _ rune)

Format prevents implicit borrowed configuration traversal.

func (DisableConfig) MarshalJSON

func (DisableConfig) MarshalJSON() ([]byte, error)

MarshalJSON rejects implicit native policy/owner export.

func (DisableConfig) MarshalText

func (DisableConfig) MarshalText() ([]byte, error)

MarshalText rejects implicit text/map-key policy export.

type DisableMigrationSource

type DisableMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

DisableMigrationSource appends distinct disable-purpose proof use and retained explicit target scope after removal history. Existing receipt bytes stay valid.

func (DisableMigrationSource) Load

Load preserves the exact prefix and returns only forward migration semantics.

type DisablePrimarySource

DisablePrimarySource authenticates real current source-session/CSRF custody and restores only MFA-authenticated original input. It cannot renew primary authentication or supply factor proof/recovery authority. Borrowed owners must be concurrency-safe and retain neither credentials nor protected Work.

type DisableService

type DisableService struct {
	// contains filtered or unexported fields
}

DisableService owns disable-purpose proof consumption and protected native factor/code/session invalidation through the existing coordinator. It creates no private transaction, proof journal, replacement credential or goroutine.

func NewDisableService

func NewDisableService(enrollment *TOTPEnrollmentService, stepup *TOTPActiveStepUpService, c DisableConfig) (*DisableService, error)

NewDisableService freezes explicit native disable without IO. Install the forward disable MFA/session migrations after the existing histories. The enrollment and proof issuer must share exact authority and original custody.

func NewOTPDisableService

func NewOTPDisableService(enrollment *OTPEnrollmentService, stepup *OTPActiveStepUpService, c DisableConfig) (*DisableService, error)

NewOTPDisableService selects sole-active email-OTP disable with distinct one/all intent and a real selected email-reset recovery path. The step-up owner must explicitly allow disable-purpose evidence. Install forward OTP disable and session-effect histories; existing TOTP/default profiles are not changed. Owners are borrowed and construction performs no IO. All-target supports at most 63 retained pending siblings, including expired pending rows; overflow rolls back rather than partially erasing the set.

func (*DisableService) Disable

func (s *DisableService) Disable(ctx context.Context, r mfa.DisableRequest) (out mfa.DisableResult, err error)

Disable requires original signed disable proof and recent primary custody. A fresh committed result exposes safe remaining unexpired pending factors; all-target returns an empty set after erasing pending siblings. The profile supports only one active factor of its selected method. Errors/unknown/replay expose no projections or new credentials.

func (*DisableService) RecoverDisable

RecoverDisable reads the retained original outcome under current access policy without replaying proof use or rechecking today's recovery eligibility.

type EmailChangeFactorAdmission

type EmailChangeFactorAdmission struct {
	// contains filtered or unexported fields
}

EmailChangeFactorAdmission retains authenticated original factor custody, not permission to mutate an email. Zero denies. Copies cannot renew proof age, change its factor/session/action, or bypass protected consumption.

func (EmailChangeFactorAdmission) Admit

Admit additionally locks the unused original proof for request preparation or Apply. The coordinator retains its locks until commit/rollback. It never consumes during discovery, signature validation or source restoration.

func (EmailChangeFactorAdmission) AuthorityVersion

func (a EmailChangeFactorAdmission) AuthorityVersion() (uint64, error)

AuthorityVersion is the original observed account-wide factor generation.

func (EmailChangeFactorAdmission) CheckAuthority

CheckAuthority locks the original confirmed enrollment and exact factor generation, and rechecks original proof validity with authoritative database time. Only the registered self-user change-request or change-confirm Work can call it. It grants no primary-session, directory or email authority.

func (EmailChangeFactorAdmission) CheckConsumed

CheckConsumed requires original consumption by the authenticated originating change-request command, plus current unchanged factor authority and original validity. Confirmation does not reconsume or accept an unused proof. The caller obtains origin from authenticated retained email intent, not the wire.

func (EmailChangeFactorAdmission) Consume

Consume marks the original evidence once, atomically with the email owner's pending attachment, link/delivery, audit and lifecycle. Apply-only; propagate any error to abort. The final callback must also call CheckConsumed.

func (EmailChangeFactorAdmission) Digest

func (a EmailChangeFactorAdmission) Digest() ([32]byte, error)

Digest binds original signed evidence and its immutable factor generation. It is provenance metadata, never a substitute for signature validation.

func (EmailChangeFactorAdmission) Format

Format hides original factor evidence.

func (EmailChangeFactorAdmission) MarshalJSON

func (EmailChangeFactorAdmission) MarshalJSON() ([]byte, error)

MarshalJSON rejects implicit original-evidence export.

func (EmailChangeFactorAdmission) MarshalText

func (EmailChangeFactorAdmission) MarshalText() ([]byte, error)

MarshalText rejects implicit original-evidence export.

func (EmailChangeFactorAdmission) Original

Original returns a copy of signed original evidence, not current authority.

type EmailChangeFactorMigrationSource

type EmailChangeFactorMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

EmailChangeFactorMigrationSource appends email-request proof consumption to the existing MFA evidence owner. Prior history and used records are preserved; no proof, factor, authority or second journal is created or backfilled.

func (EmailChangeFactorMigrationSource) Load

Load validates the existing MFA source/version contract and appends only forward SQL. The selected base must already contain factor-verification DDL.

type EmailChangeFactorSource

type EmailChangeFactorSource struct {
	// contains filtered or unexported fields
}

EmailChangeFactorSource borrows the explicitly selected active-TOTP issuer's original evidence and signing trust. It owns no transaction, store, retry or goroutine. Prepare authenticates original evidence; the registered email participant must fence current authority and consume it in protected Work.

func NewEmailChangeFactorSource

func NewEmailChangeFactorSource(stepup *TOTPActiveStepUpService) (*EmailChangeFactorSource, error)

NewEmailChangeFactorSource selects only identity.email.change-request from an issuer configured with EmailChange. Construction is IO-free. The caller retains pool/issuer lifetime; authentication owns the existing signed frame. Its authority authenticator accepts at most32 retained keys (authentication's copyAuthorityKeys bound); a larger issuer ring cannot select this consumer.

func (*EmailChangeFactorSource) CheckCurrent

CheckCurrent performs scanner-safe original-consumption/current-factor discovery without a lock, debit or mutation. Explicit completion must repeat these checks inside Work. IO is bounded by the original source read budget; the proof's original validity is checked at the end, never refreshed.

func (EmailChangeFactorSource) Format

func (EmailChangeFactorSource) Format(s fmt.State, _ rune)

Format hides original correlated evidence and borrowed native owners.

func (EmailChangeFactorSource) MarshalJSON

func (EmailChangeFactorSource) MarshalJSON() ([]byte, error)

MarshalJSON rejects implicit native-owner export.

func (EmailChangeFactorSource) MarshalText

func (EmailChangeFactorSource) MarshalText() ([]byte, error)

MarshalText rejects implicit native-owner export.

func (*EmailChangeFactorSource) Prepare

Prepare authenticates a committed original TOTP proof for the exact email action/session/audience and bounded MaximumAge. It neither consumes nor infers current factor or session authority. Original must be the separately authenticated session frozen by the consumer. Its own factor provenance is retained even when the fresh step-up used a different enrolled factor. IO observes the issuer's bounded read budget and earlier cancellation. Invalid or unavailable evidence denies.

func (*EmailChangeFactorSource) Restore

Restore authenticates the same original proof and exact digest retained by the email owner's encrypted committed request. Historical lookup never renews expiry or waives current-authority/consumption checks. The caller must obtain id/digest/use and original session from authenticated origin custody, never request fields. The original session's factor is retained separately from the action proof's factor; neither is replaced by current metadata.

type FactorManagementMigrationSource

type FactorManagementMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

FactorManagementMigrationSource appends safe presentation metadata and retained mutation effects after the existing factor-verification history. It preserves cryptographic and command bytes and does not enroll, reactivate or fabricate factors. Allocate Version permanently in the same namespace.

func (FactorManagementMigrationSource) Load

Load preserves the exact populated prefix and returns forward-only SQL. Nil/canceled context, missing Base or conflicting versions deny without IO.

type FactorReferenceMigrationSource

type FactorReferenceMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

FactorReferenceMigrationSource appends a shared immutable factor-identity namespace after existing TOTP/recovery history. This is reference integrity, not enrolled-factor state, policy or authentication. It preserves historical TOTP identities and recovery rows; future methods use the same recovery owner. Allocate Version after every installed MFA migration. The atomic migration locks/scans the factor and recovery tables: operators must bound lock/statement waits and provision backfill headroom. No production latency budget is implied.

func (FactorReferenceMigrationSource) Load

Load returns owned forward-only SQL without IO. The existing source contract rejects missing, typed-nil, cancelled, empty or conflicting history. The old schema must contain TOTP factors and recovery sets; unexpected schema drift fails during application rather than silently relaxing integrity.

type FactorRemovalMigrationSource

type FactorRemovalMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

FactorRemovalMigrationSource appends removal disposition metadata without rewriting installed management history or treating old renames as removals. Version belongs to the shared MFA namespace; no downgrade is supplied.

func (FactorRemovalMigrationSource) Load

Load returns the exact installed prefix plus the explicit forward suffix.

type FactorRemovalRecoverySource

type FactorRemovalRecoverySource interface {
	FactorRemovalRecoveryIdentity() [32]byte
	CheckFactorRemovalRecovery(context.Context, kernel.Work, kernel.FeatureExecutionContributor, identity.Command) error
}

FactorRemovalRecoverySource borrows the selected native recovery workflow. It must fence current usable recovery authority in the caller's exact Work, not return a cached absence assertion or open another transaction. Identity versions its immutable selected policy; checks retain no Work or credentials.

type FactorUpdateConfig

type FactorUpdateConfig struct {
	Primary           FactorUpdatePrimarySource
	Sessions          RecoveryRegenerationSessionEffects
	MaximumAge        time.Duration
	PrimaryMaximumAge time.Duration
	// Zero preserves rename-only compatibility. Email requires a composed native
	// request/completion owner; unsupported paths and missing authority deny.
	RemovalRecoveryPath auth.RecoveryPath
	RemovalRecovery     FactorRemovalRecoverySource
	// Replacement explicitly selects same-profile pending TOTP replacement.
	// Nil preserves rename/removal-only behavior and retained config identity.
	Replacement *TOTPReplacementConfig
}

FactorUpdateConfig selects bounded primary/factor freshness and real enlisted session effects. Both ages are positive and at most five minutes. Primary and Sessions borrow native owners; they cannot open transactions or retain Work. Default selection supports TOTP rename; explicit email recovery selection adds removal of the sole active TOTP. Explicit Replacement adds a pending same-profile successor. NewOTPFactorUpdateService selects confirmed email OTP rename and, with explicit email recovery, sole-active-OTP removal; it rejects replacement configuration.

func (FactorUpdateConfig) Format

func (FactorUpdateConfig) Format(s fmt.State, _ rune)

Format redacts borrowed native owners and deployment policy.

func (FactorUpdateConfig) MarshalJSON

func (FactorUpdateConfig) MarshalJSON() ([]byte, error)

MarshalJSON rejects implicit native configuration export.

func (FactorUpdateConfig) MarshalText

func (FactorUpdateConfig) MarshalText() ([]byte, error)

MarshalText rejects implicit native configuration export.

type FactorUpdatePrimarySource

type FactorUpdatePrimarySource interface {
	PrepareFactorUpdate(context.Context, mfa.FactorUpdateRequest, identity.CommandID) (TOTPActivePrimary, session.GetResult, error)
	RestoreFactorUpdate(context.Context, mfa.FactorUpdateRequest, identity.CommandID, []byte) (TOTPActivePrimary, error)
}

FactorUpdatePrimarySource authenticates actual current session/CSRF custody for the owner-derived keyed command. Restore accepts only input bytes already authenticated by MFA's original envelope. Neither operation verifies or uses a factor proof; protected current-state checks remain mandatory.

type FactorUpdateService

type FactorUpdateService struct {
	// contains filtered or unexported fields
}

FactorUpdateService owns keyed, optimistic native factor metadata management with original proof consumption, session revocation and lifecycle/audit. It borrows existing enrollment, step-up and coordinator owners and creates no private transaction, journal, authority or goroutine. Explicit replacement borrows existing enrollment generation for its pending successor.

func NewFactorUpdateService

func NewFactorUpdateService(enrollment *TOTPEnrollmentService, stepup *TOTPActiveStepUpService, c FactorUpdateConfig) (*FactorUpdateService, error)

NewFactorUpdateService freezes native composition without IO. Enrollment and step-up must share their exact original owner. Install management metadata, proof-use and selected session-effect migrations before calls begin.

func NewOTPFactorUpdateService

func NewOTPFactorUpdateService(enrollment *OTPEnrollmentService, stepup *OTPActiveStepUpService, c FactorUpdateConfig) (*FactorUpdateService, error)

NewOTPFactorUpdateService selects confirmed email-OTP factor rename with original action-proof consumption and required session revocation. Enrollment and step-up must share their exact native owner. Explicit email recovery adds sole-active-factor removal; it requires a real selected recovery owner and the OTP removal history. Disable/replacement remain unselected. Install OTP management, proof and session-effect histories before use. Owners are borrowed; no IO, credential comparison, journal or background lifetime is created here.

func (*FactorUpdateService) FactorUpdate

FactorUpdate reuses the existing immutable keyed input and protected command owner. Fresh rename consumes the exact signed factor proof, updates metadata optimistically and revokes subject sessions atomically. Retry/unknown/recovery never repeat mutation or fabricate fresh metadata. Unsupported actions deny.

func (*FactorUpdateService) RecoverFactorUpdate

RecoverFactorUpdate resolves historical outcome under current access policy without credentials, proof reuse, fresh metadata or new session issuance.

func (*FactorUpdateService) RemovalConfigured

func (s *FactorUpdateService) RemovalConfigured() bool

RemovalConfigured reports immutable profile selection for migration and transport composition, not current recovery eligibility or authentication.

func (*FactorUpdateService) ReplacementConfigured

func (s *FactorUpdateService) ReplacementConfigured() bool

ReplacementConfigured reports explicit immutable pending-replacement selection, not current factor authority or completion of the ceremony.

type FactorVerificationMigrationSource

type FactorVerificationMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

FactorVerificationMigrationSource appends immutable original active-factor proof evidence and its atomic use marker in the existing MFA namespace. It creates no new command journal, grants or factor authority. Version must follow the selected TOTP/factor/recovery history; no records are backfilled.

func (FactorVerificationMigrationSource) Load

Load preserves predecessor history and returns forward-only owned SQL. Version/context/nil-source checks follow the existing MFA source contract.

type FactorVerificationSigningKey

type FactorVerificationSigningKey struct {
	// contains filtered or unexported fields
}

FactorVerificationSigningKey owns immutable Ed25519 custody for the existing authentication original-reauthentication frame. It is not an access-token key or a new signature format. Copies share immutable custody; erase caller bytes.

func NewFactorVerificationSigningKey

func NewFactorVerificationSigningKey(id string, key ed25519.PrivateKey) (FactorVerificationSigningKey, error)

NewFactorVerificationSigningKey copies a complete consistent private key. Rotation must retain the public key while original journal evidence exists.

func (FactorVerificationSigningKey) Format

Format redacts cryptographic custody and correlated configuration.

func (FactorVerificationSigningKey) MarshalJSON

func (FactorVerificationSigningKey) MarshalJSON() ([]byte, error)

MarshalJSON rejects implicit key export.

func (FactorVerificationSigningKey) MarshalText

func (FactorVerificationSigningKey) MarshalText() ([]byte, error)

MarshalText rejects implicit key export.

type FactorVerificationSource

type FactorVerificationSource struct {
	// contains filtered or unexported fields
}

FactorVerificationSource reads original signed active-factor evidence through authentication's existing method-neutral ReauthenticationSource contract. Only committed native issuance is visible. This source does not validate signatures, current session/factor authority or one-use status and cannot renew original proof timestamps. Those checks belong to the configured authentication validator and protected consuming workflow. It owns no transaction, cache, goroutine or pool lifetime; concurrent reads are safe.

func NewFactorVerificationSource

func NewFactorVerificationSource(pool *database.Pool, maximumDuration time.Duration) (*FactorVerificationSource, error)

NewFactorVerificationSource borrows primary PostgreSQL with a read budget of at most five seconds. It performs no IO or schema initialization. Install the owned factor-verification history before use; missing storage fails closed.

func NewOTPFactorVerificationSource

func NewOTPFactorVerificationSource(pool *database.Pool, maximumDuration time.Duration) (*FactorVerificationSource, error)

NewOTPFactorVerificationSource selects only committed native active-OTP action evidence (factor-update or explicitly selected disable) in its distinct method-owned storage. Install OTPFactorVerificationMigrationSource first. It otherwise retains the existing source's bounded reads, errors, immutable signed history and borrowed pool lifetime. It grants no current authentication, permission or one-time use. It cannot read TOTP, pending enrollment or partial-login evidence as OTP.

func (*FactorVerificationSource) Format

func (*FactorVerificationSource) Format(s fmt.State, _ rune)

Format hides borrowed pool and deployment state.

func (*FactorVerificationSource) MarshalJSON

func (*FactorVerificationSource) MarshalJSON() ([]byte, error)

MarshalJSON rejects implicit runtime-resource export.

func (*FactorVerificationSource) MarshalText

func (*FactorVerificationSource) MarshalText() ([]byte, error)

MarshalText rejects implicit runtime-resource export.

func (*FactorVerificationSource) Reauthentication

Reauthentication selects the immutable original proof by its globally unique random128 ID, which is also the native issuance command ID. Pending, aborted, absent and retired commands all return ErrInvalidProof without partial data. Corrupt or oversized evidence, missing schema and unavailable primary return redacted Unavailable; cancellation retains the original context error. Consumed evidence may still be read as history, but this never permits its reuse. Native consumers must exclusively lock/check its use marker together with current owners and apply their mutation in the same protected commit.

type LockedOTPCompletion

type LockedOTPCompletion struct {
	// contains filtered or unexported fields
}

LockedOTPCompletion borrows exact native factor/continuation fences only after the coordinator has checked consuming OTP and provisionally consumed this child in the same Work. It is not transferable proof or session authority. Copies share one provisional transition; returned/foreign handles deny.

func LockOTPCompletion

LockOTPCompletion requires both actual consuming owners and locks the exact current shared continuation/factor/recipient. The MFA owner must separately admit original password/browser, directory, credential, policy and risk. No code is compared, budget spent, child finalized or session issued here.

func (LockedOTPCompletion) Format

func (LockedOTPCompletion) Format(s fmt.State, _ rune)

Format redacts borrowed authority and original factor/child correlation.

func (LockedOTPCompletion) MarshalJSON

func (LockedOTPCompletion) MarshalJSON() ([]byte, error)

MarshalJSON denies implicit transactional custody export.

func (LockedOTPCompletion) MarshalText

func (LockedOTPCompletion) MarshalText() ([]byte, error)

MarshalText denies implicit textual custody export.

func (LockedOTPCompletion) VerificationState

func (c LockedOTPCompletion) VerificationState() (OTPFactorMetadata, time.Time, error)

VerificationState returns original factor metadata and locked primary time only before this same live callback records completion. The code has already been checked by OTP's actual consuming owner, not a caller boolean.

type LockedOTPCompletionAttempt

type LockedOTPCompletionAttempt struct {
	// contains filtered or unexported fields
}

LockedOTPCompletionAttempt retains the original shared continuation lock in one counted native MFA callback. It is not OTP verification or successful factor proof. Copies share the single provisional debit and serial-use Work; returned/foreign handles deny. No private transaction or new budget is owned.

func LockOTPCompletionAttempt

LockOTPCompletionAttempt fences the current account/factor generation and exact original pending continuation before the real OTP owner compares. It requires explicitly allowed "otp", original absolute expiry and remaining cross-method budget. The native MFA owner separately admits consumed-primary cookie/provenance, selected confirmed factor/recipient and current policy. Locks belong to the sole coordinator. No attempt, child or session is consumed.

func (LockedOTPCompletionAttempt) Format

Format redacts original continuation identity and native callback authority.

func (LockedOTPCompletionAttempt) MarshalJSON

func (LockedOTPCompletionAttempt) MarshalJSON() ([]byte, error)

MarshalJSON rejects callback custody export.

func (LockedOTPCompletionAttempt) MarshalText

func (LockedOTPCompletionAttempt) MarshalText() ([]byte, error)

MarshalText rejects callback custody export.

type LockedRecoveryAttempt

type LockedRecoveryAttempt struct {
	// contains filtered or unexported fields
}

LockedRecoveryAttempt borrows actual recovery comparison custody exclusively during one native denial callback. A successful comparison is not a factor proof: it permits neither code burn nor session issuance. Copies share the serial-use lifetime and one provisional denial charge; returned handles deny.

func CompareRecoveryAttempt

CompareRecoveryAttempt locks original account/factor/continuation authority, then bounded active sets and compares the unchanged native opaque recovery input against digest-only custody. The owner must first fence current policy, original primary/browser and protected risk. Missing keys or corrupt sets fail closed. No external callback, generation, burn, session or transaction occurs. A false match can be charged only through RecordRecoveryAttemptDenial; true must roll back this probe and be reverified in protected completion.

func (LockedRecoveryAttempt) Format

func (LockedRecoveryAttempt) Format(s fmt.State, _ rune)

Format redacts borrowed callback authority and comparison results.

func (LockedRecoveryAttempt) MarshalJSON

func (LockedRecoveryAttempt) MarshalJSON() ([]byte, error)

MarshalJSON rejects borrowed custody export.

func (LockedRecoveryAttempt) MarshalText

func (LockedRecoveryAttempt) MarshalText() ([]byte, error)

MarshalText rejects borrowed custody export.

func (LockedRecoveryAttempt) MatchedSet

MatchedSet returns non-secret preparation metadata only for this same live callback's unused matching code. Zero, wrong-code, spent and returned custody deny. The projection may plan the original prospective session, but is not authentication or permission to consume a code/child. Protected completion must independently compare the original code and recheck the exact set/factor versions in its own locked Work; no caller-selected factor is substituted.

type LockedRecoveryCompletion

type LockedRecoveryCompletion struct {
	// contains filtered or unexported fields
}

LockedRecoveryCompletion retains actual unused-code comparison custody inside the exact protected MFA Apply. It is not reusable factor proof. Copies share one serial-use burn and the borrowed Work's lifetime; returned handles deny.

func LockRecoveryCompletion

LockRecoveryCompletion compares the original opaque code under current shared account/factor/continuation and active-set locks during protected Apply, after the coordinator provisionally consumes the child. Correct counted probing is never reused as proof. Missing, consumed or changed custody denies. The owner separately fences policy, original primary/browser and risk before calling. No attempt, code or session is mutated and no transaction/callback is started.

func (LockedRecoveryCompletion) Format

func (LockedRecoveryCompletion) Format(s fmt.State, _ rune)

Format redacts credential and borrowed transaction authority.

func (LockedRecoveryCompletion) MarshalJSON

func (LockedRecoveryCompletion) MarshalJSON() ([]byte, error)

MarshalJSON rejects borrowed custody export.

func (LockedRecoveryCompletion) MarshalText

func (LockedRecoveryCompletion) MarshalText() ([]byte, error)

MarshalText rejects borrowed custody export.

type LockedTOTPAttempt

type LockedTOTPAttempt struct {
	// contains filtered or unexported fields
}

LockedTOTPAttempt borrows current factor/continuation locks during one native counted-denial callback. It is not successful factor proof or permission to consume a child or issue a session. Copies share serial-use custody and the single provisional charge. No handle remains usable after callback return.

func LockTOTPAttempt

LockTOTPAttempt rechecks the reader's complete encrypted factor fence and original continuation under the exact live registered native owner. Locks are acquired account, factor authority, continuation, then factor, and held by the sole coordinator. Missing/stale/foreign/expired authority denies. No secret is decrypted, no attempt is spent, no successful replay advances, and no child or session is consumed here. The owner must separately fence current policy and original primary-proof authority. No transaction or retry is started.

func (LockedTOTPAttempt) Format

func (LockedTOTPAttempt) Format(s fmt.State, _ rune)

Format prevents diagnostic export of callback authority and factor identity.

func (LockedTOTPAttempt) MarshalJSON

func (LockedTOTPAttempt) MarshalJSON() ([]byte, error)

MarshalJSON rejects implicit authority export.

func (LockedTOTPAttempt) MarshalText

func (LockedTOTPAttempt) MarshalText() ([]byte, error)

MarshalText rejects implicit authority export.

func (LockedTOTPAttempt) VerificationState

func (a LockedTOTPAttempt) VerificationState() (TOTPFactorMetadata, time.Time, error)

VerificationState returns fenced factor metadata and primary database time only while the original native callback is live. The MFA owner compares the original opaque code using an already decrypted owned secret; no provider IO or caller callback is permitted while locks are held. This is not a proof.

type LockedTOTPCompletion

type LockedTOTPCompletion struct {
	// contains filtered or unexported fields
}

LockedTOTPCompletion borrows the current factor and continuation fences in the exact registered MFA owner's protected Apply. It is not factor proof or session authority. Copies share serial-use custody; returned callbacks deny.

func LockTOTPCompletion

LockTOTPCompletion fences account, factor authority, original continuation and exact encrypted factor in the same lock order as counted denials. Only the unchanged TOTP command in the actual protected MFA invocation is accepted, after the coordinator provisionally consumes the existing child. No code is verified, attempt spent, replay advanced or session issued by this method. The owner separately checks current policy and original primary authority.

func (LockedTOTPCompletion) Format

func (LockedTOTPCompletion) Format(s fmt.State, _ rune)

Format prevents accidental disclosure of borrowed authority and identity.

func (LockedTOTPCompletion) MarshalJSON

func (LockedTOTPCompletion) MarshalJSON() ([]byte, error)

MarshalJSON denies export of borrowed transactional custody.

func (LockedTOTPCompletion) MarshalText

func (LockedTOTPCompletion) MarshalText() ([]byte, error)

MarshalText denies export of borrowed transactional custody.

func (LockedTOTPCompletion) VerificationState

func (a LockedTOTPCompletion) VerificationState() (TOTPFactorMetadata, time.Time, error)

VerificationState returns the locked exact factor and primary database time only in the live protected Apply. The native MFA owner must verify the unchanged command's opaque code here with its already decrypted owned secret. No provider IO, decryption or application callback may run under these locks.

type MagicLinkSignupMigrationSource

type MagicLinkSignupMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

MagicLinkSignupMigrationSource preserves the original MFA history and adds passwordless creation provenance. Base must install MigrationSource; allocate Version after Base in its namespace. It does not backfill empty factor state.

func (MagicLinkSignupMigrationSource) Load

Load returns additive history without SQL IO or a destructive downgrade.

type MigrationSource

type MigrationSource struct{ Version migrations.Version }

MigrationSource installs factor generations after kernel users and commands in the separately owned identity_mfa migration namespace. Version must be allocated permanently in that namespace. Zero denies; Load is pure and concurrent-safe. Existing accounts deliberately receive no empty-factor backfill: their state remains unknown until authoritative reconciliation.

func (MigrationSource) Load

Load returns additive installation SQL without destructive downgrade SQL. Existing unmanaged objects fail rather than being implicitly adopted.

type OTPActiveFactorMetadata

type OTPActiveFactorMetadata struct {
	Factor         OTPFactorMetadata
	SessionID      string
	SessionVersion uint64
	ValidUntil     time.Time
}

OTPActiveFactorMetadata preserves a confirmed factor, recipient versions and the real session owner's original observation deadline. Factor's login-child fields remain zero: this profile does not reinterpret a completed/expired login continuation as current authority. No metadata grants factor proof.

func (OTPActiveFactorMetadata) Format

func (OTPActiveFactorMetadata) Format(s fmt.State, _ rune)

Format prevents diagnostic traversal of correlated factor/session metadata.

func (OTPActiveFactorMetadata) MarshalJSON

func (OTPActiveFactorMetadata) MarshalJSON() ([]byte, error)

MarshalJSON rejects implicit custody export.

func (OTPActiveFactorMetadata) MarshalText

func (OTPActiveFactorMetadata) MarshalText() ([]byte, error)

MarshalText rejects implicit custody export.

type OTPActiveFactorSnapshot

type OTPActiveFactorSnapshot struct {
	// contains filtered or unexported fields
}

OTPActiveFactorSnapshot is immutable active-factor/verified-recipient custody for authenticated step-up, distinct from pending enrollment and partial login. It contains no generated/submitted code and owns no resources. Copies cannot renew the original session observation. Native use must repeat current fences.

func (OTPActiveFactorSnapshot) Format

func (OTPActiveFactorSnapshot) Format(s fmt.State, _ rune)

Format prevents diagnostic traversal of recipient or original custody.

func (OTPActiveFactorSnapshot) MarshalJSON

func (OTPActiveFactorSnapshot) MarshalJSON() ([]byte, error)

MarshalJSON rejects implicit custody export.

func (OTPActiveFactorSnapshot) MarshalText

func (OTPActiveFactorSnapshot) MarshalText() ([]byte, error)

MarshalText rejects implicit custody export.

func (OTPActiveFactorSnapshot) Metadata

Metadata returns original scalar custody, not a fresh authorization lease.

func (OTPActiveFactorSnapshot) Recipient

Recipient returns the exact verified destination only for native encrypted delivery preparation. It must not be included in responses or diagnostics.

type OTPActiveIssuanceOwner

type OTPActiveIssuanceOwner interface {
	PrepareStepUpSend(context.Context, *database.Pool, identity.CommandBinding, session.Session, kernel.RecipientRecord, time.Time, time.Time) ([]byte, error)
	GenerateStepUpSend(context.Context, identity.Command, []byte, uint64) ([]byte, error)
	RestoreStepUpSend(context.Context, identity.Command, []byte, uint64, []byte) (OTPEnrollmentPreparedSend, error)
	RecoverStepUpSend(context.Context, kernel.RecoveryWork, kernel.FeatureExecutionContributor) (kernel.RecoveryStatus, error)
	RestoreStepUpVerification(context.Context, identity.Command, []byte, uint64, []byte) (OTPActiveVerification, error)
	ConfirmationContributor() kernel.OTPExecutionContributor
	ValidateConfirmationKey(uint32) error
	DeliveryContributor() *deliverypg.Contributor
	Configuration() ([32]byte, error)
}

OTPActiveIssuanceOwner is the real OTP owner's explicit authenticated step-up profile. MFA retains current session/CSRF, factor, action and risk admission in its sole Work. OTP owns generation, digest/challenge storage, shared send limits, consuming attempts and encrypted delivery. Original records must remain in MFA's existing authenticated preparation; they are neither an independent journal nor live permission. No pending-enrollment or partial-login owner can silently select this profile.

type OTPActivePrimary

type OTPActivePrimary interface {
	TOTPURIPrimary
	Snapshot() ([]byte, error)
}

OTPActivePrimary retains actual current-session custody for active OTP sending or verification. Its method-neutral participant vocabulary is the same as other MFA actions; it neither verifies OTP nor supplies factor proof. Snapshot contains no bearer and may only be restored after authenticating the native MFA envelope. Original deadlines cannot be renewed by restoration.

type OTPActivePrimarySource

OTPActivePrimarySource prepares the real current session for the explicit authenticated StepUp request arm. Send uses the request-key owner's assigned command; verify uses the submitted command and exact original SendCommandID. Neither method translates the request into enrollment or TOTP authority. Restores are IO-free custody checks over native-envelope-authenticated bytes; actual current owners, synchronizer and original deadline remain mandatory in the sole protected Work. Owners and request inputs are borrowed.

type OTPActiveStepUpConfig

type OTPActiveStepUpConfig struct {
	// AllowedPurposes is a closed explicit selection of factor-update and/or
	// disable. Empty preserves the original factor-update-only profile and its
	// configuration identity. Selection grants no proof or recovery authority.
	AllowedPurposes               []auth.Purpose
	Primary                       OTPActivePrimarySource
	Issuance                      OTPActiveIssuanceOwner
	AllowedOrigins                []string
	AttemptKeyVersion             uint32
	SigningKey                    FactorVerificationSigningKey
	VerificationKeys              map[string]ed25519.PublicKey
	Issuer, Environment, Audience string
	TTL                           time.Duration
}

OTPActiveStepUpConfig selects authenticated email-OTP factor-update proof issuance. It enables neither enrollment/login nor HTTP routes. Primary and Issuance must be real native owners. Signing uses the existing authentication frame; retain public keys for original recovery. TTL caps challenge and proof lifetime at 1s..5min; the OTP policy and original session may impose earlier limits. Origins are exact HTTPS origins. Owners are borrowed and immutable.

func (OTPActiveStepUpConfig) Format

func (OTPActiveStepUpConfig) Format(s fmt.State, _ rune)

Format redacts cryptographic policy and borrowed native owners.

func (OTPActiveStepUpConfig) MarshalJSON

func (OTPActiveStepUpConfig) MarshalJSON() ([]byte, error)

MarshalJSON rejects implicit configuration export.

func (OTPActiveStepUpConfig) MarshalText

func (OTPActiveStepUpConfig) MarshalText() ([]byte, error)

MarshalText rejects implicit configuration export.

type OTPActiveStepUpService

type OTPActiveStepUpService struct {
	// contains filtered or unexported fields
}

OTPActiveStepUpService sends a purpose-bound challenge and atomically consumes it with original signed action evidence using the existing native coordinator, risk, OTP and delivery owners. It issues no session or renewed primary proof. Concurrent calls own separate phases; borrowed dependencies must outlive them.

func NewOTPActiveStepUpService

func NewOTPActiveStepUpService(enrollment *OTPEnrollmentService, c OTPActiveStepUpConfig) (*OTPActiveStepUpService, error)

NewOTPActiveStepUpService freezes the selected native composition without IO or generation. Install OTPFactorVerificationMigrationSource and selected OTP/send/delivery histories first, and initialize the real issuance keys.

func (OTPActiveStepUpService) Format

func (OTPActiveStepUpService) Format(s fmt.State, _ rune)

Format redacts immutable native composition.

func (OTPActiveStepUpService) MarshalJSON

func (OTPActiveStepUpService) MarshalJSON() ([]byte, error)

MarshalJSON rejects implicit service export.

func (OTPActiveStepUpService) MarshalText

func (OTPActiveStepUpService) MarshalText() ([]byte, error)

MarshalText rejects implicit service export.

func (*OTPActiveStepUpService) OtpSend

OtpSend accepts only the explicit authenticated StepUp arm. A keyed retry retains the original session/factor/recipient/input and never regenerates a code. Queued is not provider delivery. Denial/unknown returns no challenge.

func (*OTPActiveStepUpService) OtpVerify

OtpVerify consumes only the exact original active send. Actual OTP attempt accounting and signed proof persistence are atomic. Replayed or ambiguous commands never redeliver proof, and no branch creates a login session.

func (*OTPActiveStepUpService) RecoverOtpSend

RecoverOtpSend reconciles original metadata under current result-access permission. It never generates a successor code or delivery.

func (*OTPActiveStepUpService) RecoverOtpVerify

RecoverOtpVerify returns historical outcome only, never original factor proof.

type OTPActiveVerification

type OTPActiveVerification interface{ OTPEnrollmentConfirmation }

OTPActiveVerification lends the real OTP attempt participant for the exact original active send. Its preparation vocabulary is shared, not enrollment authority: the native owner must bind the original send, source session, factor and action and atomically consume OTP with signed factor evidence. Prepare/RestorePrepared do not compare or debit a code or renew freshness.

type OTPDisableMigrationSource

type OTPDisableMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

OTPDisableMigrationSource appends distinct disable-purpose proof use and explicit one/all disposition after OTP removal history. Installed prefix bytes, existing rename/removal receipts and TOTP history remain unchanged.

func (OTPDisableMigrationSource) Load

Load appends one forward-only step without IO. Missing/canceled context, absent Base and conflicting versions fail closed.

type OTPEnrollmentConfig

type OTPEnrollmentConfig struct {
	ConfigurationID, PolicyID string
	MaximumDuration, TTL      time.Duration
	Primary                   TOTPEnrollmentPrimarySource
	Coordinator               kernel.CoordinatorConfig
	RequestKeys               kernel.RequestKeyConfig
	Risk                      risk.ProtectedProviderAdmissionCustodyConfig
	Counters                  riskpg.Config
	ActiveEnvelopeKeyID       string
	RecoveryKeyVersion        uint32
	// contains filtered or unexported fields
}

OTPEnrollmentConfig explicitly selects pending OTP enrollment. It shares native primary, protected counters and opaque recovery custody with TOTP but has no TOTP algorithm/secret profile. Configure through NewOTPEnrollmentConfig and then fill the public fields. All owners remain borrowed and must outlive calls; missing known-empty account authority denies. The selected verified recipient is bound by native admission, never inferred from a login email.

func NewOTPEnrollmentConfig

func NewOTPEnrollmentConfig(keys kernel.RequestKeyConfig, intent, recovery [32]byte, recoveryVersion uint32, envelopeKey string) (OTPEnrollmentConfig, error)

NewOTPEnrollmentConfig retains independent original-intent and recovery keys using the existing enrollment custody profile. It performs no IO, generation or admission. Retain this configuration and keys through pending recovery.

func (OTPEnrollmentConfig) Format

func (OTPEnrollmentConfig) Format(s fmt.State, _ rune)

Format redacts borrowed owners and opaque startup custody.

func (OTPEnrollmentConfig) MarshalJSON

func (OTPEnrollmentConfig) MarshalJSON() ([]byte, error)

MarshalJSON denies implicit configuration export.

func (OTPEnrollmentConfig) MarshalText

func (OTPEnrollmentConfig) MarshalText() ([]byte, error)

MarshalText denies implicit textual configuration export.

type OTPEnrollmentConfirmation

type OTPEnrollmentConfirmation interface {
	Prepare(context.Context, *database.Pool, identity.Command, auth.OneTimeCode, uint32) (identity.Command, kernel.OTPAttemptPlan, error)
	// RestorePrepared authenticates the original code-free mapped metadata
	// retained in MFA's encrypted preparation, conserves its attempt/version,
	// and independently matches the submitted code and actual session bearer.
	// It performs no IO, comparison, debit, remapping or freshness renewal.
	RestorePrepared(context.Context, identity.Command, auth.OneTimeCode, identity.FeatureCommandSpec) (identity.Command, kernel.OTPAttemptPlan, error)
	Contributor() kernel.OTPExecutionContributor
}

OTPEnrollmentConfirmation retains opaque original issuance at the OTP owner. Prepare reads the exact challenge version, creates a fresh server-owned attempt and maps the submitted code onto the already frozen MFA root. It performs no comparison or mutation. The selected retained attempt key must exist; never replace it or the original expiry with a current default. Contributor is the real reservation/check/finalize/recovery participant. MFA must enlist it in its sole coordinator and enforce current original primary, pending factor, recipient and risk before comparison and protected activation. The pool and request inputs are borrowed for the bounded call; no handles are retained. Copies of the returned command do not grant execution authority.

type OTPEnrollmentConfirmationConfig

type OTPEnrollmentConfirmationConfig struct {
	Primary           OTPEnrollmentConfirmationPrimarySource
	AttemptKeyVersion uint32
}

OTPEnrollmentConfirmationConfig selects the original native primary source and retained OTP attempt key. Origins, issuance, original custody and store owners are inherited from the actual sender, not new request-selected policy.

func (OTPEnrollmentConfirmationConfig) Format

func (OTPEnrollmentConfirmationConfig) MarshalJSON

func (OTPEnrollmentConfirmationConfig) MarshalJSON() ([]byte, error)

func (OTPEnrollmentConfirmationConfig) MarshalText

func (OTPEnrollmentConfirmationConfig) MarshalText() ([]byte, error)

type OTPEnrollmentConfirmationOwner

type OTPEnrollmentConfirmationOwner interface {
	RestoreEnrollmentConfirmation(context.Context, identity.Command, []byte, uint64, []byte) (OTPEnrollmentConfirmation, error)
	ConfirmationContributor() kernel.OTPExecutionContributor
	// ValidateConfirmationKey checks retained native key availability without
	// IO, generation, disclosure or selecting a replacement key version.
	ValidateConfirmationKey(uint32) error
}

OTPEnrollmentConfirmationOwner restores only the actual original send's authenticated issuance. MFA supplies its original root and retained input and output after authenticating its existing encrypted preparation. Restoration generates nothing, renews no validity and grants no comparison/admission. The real OTP adapter implements this port; applications do not supply stores.

type OTPEnrollmentConfirmationPrimarySource

type OTPEnrollmentConfirmationPrimarySource interface {
	RestoreEnrollmentForOTPConfirmation(context.Context, mfa.OtpVerifyRequest, identity.CommandID, uint64, []byte) (TOTPURIPrimary, error)
}

OTPEnrollmentConfirmationPrimarySource restores the original enable/session and synchronizer only for authenticated pending OTP confirmation. It cannot consume the primary proof again, select login custody or renew freshness.

type OTPEnrollmentConfirmationService

type OTPEnrollmentConfirmationService struct {
	// contains filtered or unexported fields
}

OTPEnrollmentConfirmationService confirms a pending OTP factor without a login session, another primary-proof consumption or trusted-device issuance. It borrows immutable native owners; concurrent calls use separate phases.

func NewOTPEnrollmentConfirmationService

func NewOTPEnrollmentConfirmationService(sender *OTPEnrollmentSendService, c OTPEnrollmentConfirmationConfig) (*OTPEnrollmentConfirmationService, error)

NewOTPEnrollmentConfirmationService freezes native composition without IO, code generation or activation. The sender must own actual retained MFA/OTP custody and a complete consuming contributor. Install OTP consuming history before use. Missing risk, original primary, key or selected owner denies.

func (OTPEnrollmentConfirmationService) Format

func (OTPEnrollmentConfirmationService) MarshalJSON

func (OTPEnrollmentConfirmationService) MarshalJSON() ([]byte, error)

func (OTPEnrollmentConfirmationService) MarshalText

func (OTPEnrollmentConfirmationService) MarshalText() ([]byte, error)

func (*OTPEnrollmentConfirmationService) OtpVerify

OtpVerify accepts only explicit pending enrollment. It authenticates the actual original send and primary, retains one server-owned OTP attempt in the existing preparation, then atomically activates factor/recovery authority and finalizes OTP. Wrong submissions charge once; replay/recovery create no code, factor successor, session, proof, delivery or renewed original lifetime.

func (*OTPEnrollmentConfirmationService) RecoverOtpVerify

RecoverOtpVerify reconciles original code/session/proof-free history under current result-access authorization. Complete frozen native participants, including OTP, must agree; absence or expired live custody is not rollback.

type OTPEnrollmentIssuanceOwner

type OTPEnrollmentIssuanceOwner interface {
	PrepareEnrollmentSend(context.Context, *database.Pool, identity.CommandBinding, session.Session, kernel.RecipientRecord, time.Time, time.Time) ([]byte, error)
	GenerateEnrollmentSend(context.Context, identity.Command, []byte, uint64) ([]byte, error)
	RestoreEnrollmentSend(context.Context, identity.Command, []byte, uint64, []byte) (OTPEnrollmentPreparedSend, error)
	RecoverEnrollmentSend(context.Context, kernel.RecoveryWork, kernel.FeatureExecutionContributor) (kernel.RecoveryStatus, error)
	DeliveryContributor() *deliverypg.Contributor
	Configuration() ([32]byte, error)
}

OTPEnrollmentIssuanceOwner is the narrow native OTP port for pending-factor sending. Use the real OTP adapter, not application-written code/delivery/risk stores. MFA owns original parent/CSRF/factor/risk admission and the sole Work; OTP owns generation, same-code custody, shared send limits and digest storage. Original preparation bytes are code/bearer-free and may only be restored after MFA authenticates its existing encrypted original request binding.

type OTPEnrollmentPreparedSend

type OTPEnrollmentPreparedSend interface {
	Plan() (kernel.DeliveryPlan, error)
	Persist(context.Context, kernel.Work, kernel.FeatureExecutionContributor, identity.Command) error
}

OTPEnrollmentPreparedSend retains the real OTP/delivery effect, not an authentication result. Persist must use only this exact native MFA root and borrowed Work; return errors to the coordinator and recheck current original parent, factor, recipient, risk and lifetime after waits before commit.

type OTPEnrollmentSendConfig

type OTPEnrollmentSendConfig struct {
	Primary        OTPEnrollmentSendPrimarySource
	Issuance       OTPEnrollmentIssuanceOwner
	AllowedOrigins []string
}

OTPEnrollmentSendConfig selects the real primary, OTP and delivery owners for authenticated pending-factor sending. It does not enable partial-login sending or register HTTP routes. Owners are borrowed and must outlive calls. AllowedOrigins are exact HTTPS origins, copied at construction.

func (OTPEnrollmentSendConfig) Format

func (OTPEnrollmentSendConfig) Format(s fmt.State, _ rune)

Format redacts borrowed primary/OTP and origin configuration.

func (OTPEnrollmentSendConfig) MarshalJSON

func (OTPEnrollmentSendConfig) MarshalJSON() ([]byte, error)

MarshalJSON denies implicit configuration export.

func (OTPEnrollmentSendConfig) MarshalText

func (OTPEnrollmentSendConfig) MarshalText() ([]byte, error)

MarshalText denies implicit configuration export.

type OTPEnrollmentSendPrimarySource

type OTPEnrollmentSendPrimarySource interface {
	RestoreEnrollmentForOTPSend(context.Context, mfa.OtpSendRequest, identity.CommandID, identity.CommandID, uint64, []byte) (TOTPURIPrimary, error)
}

OTPEnrollmentSendPrimarySource restores the exact original enable/session custody for native pending OTP sending. assigned is the sole request-key owner's command ID. Restoration grants no factor or delivery authority; current Admit/Check and unchanged synchronizer/parent consumption are required.

type OTPEnrollmentSendService

type OTPEnrollmentSendService struct {
	// contains filtered or unexported fields
}

OTPEnrollmentSendService sends a purpose-bound challenge for an existing pending OTP enrollment through the sole native coordinator. It creates no session, confirmation, proof use, transaction owner or private journal. Concurrent calls require immutable configuration and borrowed request inputs.

func NewOTPEnrollmentSendService

func NewOTPEnrollmentSendService(enrollment *OTPEnrollmentService, c OTPEnrollmentSendConfig) (*OTPEnrollmentSendService, error)

NewOTPEnrollmentSendService freezes composition without IO or generation. Install OTP send attribution and the selected OTP/delivery histories first; initialize the OTP issuer's stable keys before serving requests. Missing protected risk, primary/CSRF, issuance, delivery or exact-origin owners deny.

func (OTPEnrollmentSendService) Format

func (OTPEnrollmentSendService) Format(s fmt.State, _ rune)

Format redacts borrowed native owners and deployment policy.

func (OTPEnrollmentSendService) MarshalJSON

func (OTPEnrollmentSendService) MarshalJSON() ([]byte, error)

MarshalJSON denies implicit service export.

func (OTPEnrollmentSendService) MarshalText

func (OTPEnrollmentSendService) MarshalText() ([]byte, error)

MarshalText denies implicit service export.

func (*OTPEnrollmentSendService) OtpSend

OtpSend retains server-assigned original command/recipient/input custody before risk or generation, then atomically stores the challenge and encrypted queue intent. Matching retries never select another recipient or code. Queued is not provider delivery or factor confirmation. Partial-login variants deny.

func (*OTPEnrollmentSendService) RecoverOtpSend

RecoverOtpSend reconciles the exact original code/proof-free outcome. It neither compares a code, regenerates output, sends again nor confirms a factor. Current result-access authorization remains required; the outcome is historical.

type OTPEnrollmentService

type OTPEnrollmentService struct {
	// contains filtered or unexported fields
}

OTPEnrollmentService is the OTP-selected view of the sole existing enrollment engine. It creates only pending factor/recovery state: no code, delivery, factor activation or session. Confirmation and authentication require the separately selected native OTP owners. It owns no connections/goroutines.

func NewOTPEnrollmentService

func NewOTPEnrollmentService(pool *database.Pool, c OTPEnrollmentConfig, keys *keyring.Provider) (*OTPEnrollmentService, error)

NewOTPEnrollmentService freezes explicit composition without IO. Install shared factor references, OTP factors and selected kernel/risk histories. Primary is the same native mfa.enable port used by TOTP, not a new proof owner.

func (*OTPEnrollmentService) Enable

Enable consumes exact native primary evidence and creates pending factor and inactive recovery codes atomically. An error-free fresh commit reveals recovery material once; retry/recovery returns no codes. Verified identifier possession is necessary but does not itself enroll or authenticate an OTP factor.

func (OTPEnrollmentService) Format

func (OTPEnrollmentService) Format(s fmt.State, _ rune)

Format redacts borrowed native owners.

func (OTPEnrollmentService) MarshalJSON

func (OTPEnrollmentService) MarshalJSON() ([]byte, error)

MarshalJSON denies implicit service export.

func (OTPEnrollmentService) MarshalText

func (OTPEnrollmentService) MarshalText() ([]byte, error)

MarshalText denies implicit textual service export.

func (*OTPEnrollmentService) RecoverEnable

RecoverEnable reconciles the exact original pending enrollment without codes, password, bearer, fresh enrollment or repeated proof use. Result-access policy remains required; the returned outcome is historical, not current authority.

type OTPFactorManagementMigrationSource

type OTPFactorManagementMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

OTPFactorManagementMigrationSource appends OTP presentation metadata and original mutation effects after its OTP proof history. Existing TOTP and OTP credential/recipient bytes remain unchanged. It enables no management route or permission. Version is permanently allocated; rollback is unsupported.

func (OTPFactorManagementMigrationSource) Load

Load appends owned SQL without IO, preserving the exact installed prefix. Missing/canceled context, nil Base and conflicting versions fail closed.

type OTPFactorMetadata

type OTPFactorMetadata struct {
	TenantID                                              identity.TenantID
	UserID                                                identity.UserID
	FactorID                                              string
	EnrollmentVersion, RowVersion, FactorAuthorityVersion uint64
	IdentifierID                                          identity.IdentifierID
	IdentifierVersion, VerificationVersion                uint64
	Channel                                               delivery.Channel
	ContinuationID                                        mfa.ContinuationID
	ContinuationVersion                                   uint64
	ScopeDigest                                           [32]byte
}

OTPFactorMetadata is original confirmed-factor/recipient version custody, not successful OTP proof or a current authorization lease. Native send/completion must fence all identities/versions and original child scope in protected Work.

func RequireRecordedOTPCompletion

RequireRecordedOTPCompletion proves this same live Work's provisional shared transition before session persistence. Returned original scope/factor/primary metadata is not reusable proof. The session owner must independently admit original password/browser and current directory/credential/policy, and commit its effect atomically with OTP and child finalization. Errors abort the Work.

func (OTPFactorMetadata) Format

func (OTPFactorMetadata) Format(s fmt.State, _ rune)

Format redacts correlated factor/recipient metadata.

func (OTPFactorMetadata) MarshalJSON

func (OTPFactorMetadata) MarshalJSON() ([]byte, error)

MarshalJSON rejects implicit metadata export.

func (OTPFactorMetadata) MarshalText

func (OTPFactorMetadata) MarshalText() ([]byte, error)

MarshalText rejects implicit metadata export.

type OTPFactorMigrationSource

type OTPFactorMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

OTPFactorMigrationSource appends pending/confirmed OTP-factor storage after shared factor references. It stores exact identifier/version references, not destinations, generated/submitted codes or authentication decisions. The OTP owner retains its challenge/digest/attempt state. Existing TOTP history and writers remain separate; selecting this history does not enable an OTP route.

func (OTPFactorMigrationSource) Load

Load returns forward-only owned SQL without IO. Base must contain factor references and the kernel identifier history; absent objects fail during application. Version is permanently allocated in the owned MFA namespace.

type OTPFactorReader

type OTPFactorReader struct {
	// contains filtered or unexported fields
}

OTPFactorReader borrows the primary pool and current continuation reader. It owns no transaction/cache/background work and is safe for concurrent reads.

func NewOTPFactorReader

func NewOTPFactorReader(pool *database.Pool, maximum time.Duration) (*OTPFactorReader, error)

NewOTPFactorReader freezes a bounded, at most five-second shared read budget without IO. Missing selected OTP storage is unavailable, never known empty MFA.

func (*OTPFactorReader) Read

func (r *OTPFactorReader) Read(ctx context.Context, grant capability.Grant, issuer, factorID string) (OTPFactorSnapshot, error)

Read resolves a confirmed owned OTP factor and its exact currently verified recipient only under an actual live child explicitly permitting OTP. Missing, foreign, pending/revoked, blocked, exhausted or stale scope/recipient denies. This does not authenticate browser possession, verify a code, charge attempts or renew original primary/child time. Concurrent changes invalidate this snapshot; protected native use must repeat the complete fence. Earlier ctx deadlines win, rows close before return, and no retries are performed.

func (*OTPFactorReader) ReadForStepUp

func (r *OTPFactorReader) ReadForStepUp(ctx context.Context, original session.GetResult, factorID string) (OTPActiveFactorSnapshot, error)

ReadForStepUp reads a confirmed owned email OTP factor under a real current SessionService.Get result obtained by the configured native adapter. A caller projection or Authenticated flag cannot replace its private observation. This performs bounded primary reads, not code comparison, permission, risk admission or mutation. Final use must fence the same factor, recipient, session and primary owners together after waits in the sole protected Work. Unsupported SMS, missing/changed/foreign state and expired observations deny; outages and corrupt storage fail closed. Borrowed pool lifetime is unchanged.

func (*OTPFactorReader) ReadLoginSend

func (r *OTPFactorReader) ReadLoginSend(ctx context.Context, grant capability.Grant, issuer string) (OTPLoginSendSource, error)

ReadLoginSend restores the current committed send selected by the native MFA continuation, never by a client factor/challenge override or an account-wide latest-row search. Exact tenant/user, child scope/version, OTP policy and live shared budget remain required. Missing or retired/uncommitted attribution denies. It creates no attempt, generation, transaction or freshness renewal; original input/output authentication and protected checks still own authority.

type OTPFactorRemovalMigrationSource

type OTPFactorRemovalMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

OTPFactorRemovalMigrationSource appends explicit removal/recovery disposition to installed OTP management history. Existing effects remain renames; no recipient, credential, proof or installed migration bytes change. Select email recovery and install this forward history before accepting removals.

func (OTPFactorRemovalMigrationSource) Load

Load preserves the installed prefix and appends one owned forward-only step. Missing/cancelled context, nil Base and conflicting versions fail closed.

type OTPFactorSnapshot

type OTPFactorSnapshot struct {
	// contains filtered or unexported fields
}

OTPFactorSnapshot retains immutable owned-factor/recipient custody under the verified original child. Copies share read-only state. It owns no resources, code, bearer or session authority; zero denies and diagnostics are redacted.

func (OTPFactorSnapshot) Format

func (OTPFactorSnapshot) Format(s fmt.State, _ rune)

Format redacts original factor/recipient custody.

func (OTPFactorSnapshot) MarshalJSON

func (OTPFactorSnapshot) MarshalJSON() ([]byte, error)

MarshalJSON rejects snapshot export.

func (OTPFactorSnapshot) MarshalText

func (OTPFactorSnapshot) MarshalText() ([]byte, error)

MarshalText rejects snapshot export.

func (OTPFactorSnapshot) Metadata

func (s OTPFactorSnapshot) Metadata() (OTPFactorMetadata, error)

Metadata returns an owned non-secret projection, never current factor proof.

func (OTPFactorSnapshot) Recipient

func (s OTPFactorSnapshot) Recipient() (kernel.RecipientRecord, error)

Recipient returns the original verified recipient for native encrypted delivery preparation only. Never expose/log its address as a client response. Changing the projection cannot mutate the snapshot. Protected use repeats exact selected identity/verification and account-security version checks.

type OTPFactorVerificationMigrationSource

type OTPFactorVerificationMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

OTPFactorVerificationMigrationSource appends original signed active-OTP action evidence after the selected OTP factor and kernel histories. It does not alter existing TOTP proofs, issue a challenge or enable a workflow. Version must follow Base permanently; rollback is unsupported. Construction and Load perform no IO. Actual application fails if required owners are absent.

func (OTPFactorVerificationMigrationSource) Load

Load preserves all predecessor bytes and appends one owned forward migration. Missing/canceled context, nil Base and conflicting versions fail closed.

type OTPListReader

type OTPListReader struct {
	// contains filtered or unexported fields
}

OTPListReader reads safe native TOTP/OTP metadata from one coherent primary snapshot. The OTP enrollment history includes both factor owners. It grants no authentication, mutation or permission to omit another active method; unsupported inventories fail the shared aggregate-count check. It owns no pool, transaction, cache or goroutine and is safe for concurrent calls.

func NewOTPFactorManagementListReader

func NewOTPFactorManagementListReader(enrollment *OTPEnrollmentService, management, totpManagement *FactorUpdateService) (*OTPListReader, error)

NewOTPFactorManagementListReader selects OTP labels from the actual OTP management owner. Optional totpManagement retains separately selected TOTP labels too; nil requires no TOTP management schema. All selected owners must borrow the same primary pool. The earliest whole-read budget wins. This does not authorize mutations or permit partial inventories.

func NewOTPListReader

func NewOTPListReader(enrollment *OTPEnrollmentService) (*OTPListReader, error)

NewOTPListReader borrows the actual native OTP enrollment owner without IO. Install its selected shared TOTP/OTP histories first. The caller authenticates and authorizes the subject and must recheck original validity after reading. Labels remain empty unless management metadata is explicitly selected.

func NewOTPManagementListReader

func NewOTPManagementListReader(enrollment *OTPEnrollmentService, management *FactorUpdateService) (*OTPListReader, error)

NewOTPManagementListReader additionally selects the existing TOTP owner's managed labels, without requiring or inventing OTP label storage. Both owners must borrow the same primary pool. The earlier whole-read budget wins.

func (*OTPListReader) ReadFactors

ReadFactors returns complete bounded safe metadata or no result. Unknown authority, overflow, corruption, cancelled context and unavailable storage fail closed. No secret, recipient address, OTP, proof or credential is read.

type OTPLoginSendMigrationSource

type OTPLoginSendMigrationSource struct{ Version migrations.Version }

OTPLoginSendMigrationSource appends the current OTP challenge reference to the existing MFA continuation. Allocate Version after the selected OTP-factor, send and password-continuation histories. It owns no code, digest, delivery, transaction journal or credential authority. Existing records retain NULL attribution: no original send may be inferred or backfilled for them.

func (OTPLoginSendMigrationSource) Load

Load returns one forward-only atomic migration without IO. Original scopes, versions, attempt budgets, times and terminal records remain unchanged.

type OTPLoginSendSource

type OTPLoginSendSource struct {
	CommandID      identity.CommandID
	FactorID       mfa.FactorID
	ContinuationID mfa.ContinuationID
}

OTPLoginSendSource is exact committed send attribution under one original child, not OTP possession, verification, a validity lease or a session grant. The completion owner must authenticate the existing encrypted input/output, its generation and original browser/password/child/factor/recipient custody. IDs alone cannot select a destination, another factor or a newer primary.

func (OTPLoginSendSource) Format

func (OTPLoginSendSource) Format(s fmt.State, _ rune)

Format redacts original challenge and factor correlation.

func (OTPLoginSendSource) MarshalJSON

func (OTPLoginSendSource) MarshalJSON() ([]byte, error)

MarshalJSON denies implicit source-custody export.

func (OTPLoginSendSource) MarshalText

func (OTPLoginSendSource) MarshalText() ([]byte, error)

MarshalText denies implicit textual source-custody export.

type OTPSendMigrationSource

type OTPSendMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

OTPSendMigrationSource appends current-send attribution to existing pending factors. Prior OTP/TOTP histories remain byte-identical. No code, destination, challenge digest or attempt state is copied from OTP's owning schema. Install after OTPFactorMigrationSource; startup does not run migrations.

func (OTPSendMigrationSource) Load

Load returns the forward-only owned migration without IO. Version must be permanently allocated after the selected OTP-factor history.

type OTPSessionFactorReader

type OTPSessionFactorReader struct {
	// contains filtered or unexported fields
}

OTPSessionFactorReader borrows the primary pool and bounded read budget. It owns no transaction, cache, goroutine, code or child. Concurrent reads are safe.

func NewOTPSessionFactorReader

func NewOTPSessionFactorReader(pool *database.Pool, maximum time.Duration) (*OTPSessionFactorReader, error)

NewOTPSessionFactorReader validates an at most five-second primary budget without IO. Pool remains caller-owned; close it only after calls finish.

func (*OTPSessionFactorReader) Format

func (*OTPSessionFactorReader) Format(s fmt.State, _ rune)

func (*OTPSessionFactorReader) MarshalJSON

func (*OTPSessionFactorReader) MarshalJSON() ([]byte, error)

func (*OTPSessionFactorReader) MarshalText

func (*OTPSessionFactorReader) MarshalText() ([]byte, error)

func (*OTPSessionFactorReader) Read

Read resolves current confirmed OTP authority independently of a completed or expired login child. Exact active account, enrollment and verified current recipient are required; revoked/pending/foreign/stale recipients deny. Outage and corruption return redacted unavailable errors, never absence or fallback. Earlier deadlines win and no read renews authentication or evidence freshness.

type OTPSessionFactorState

type OTPSessionFactorState struct{ EnrollmentVersion, AuthorityVersion uint64 }

OTPSessionFactorState is current confirmed enrollment/account epoch metadata, not a proof or renewable lease. Compare exact original factor/enrollment and retain the earliest authoritative-read deadline when validating a session.

type PasskeyContinuationMigrationSource

type PasskeyContinuationMigrationSource struct {
	Base                                                            migrations.Source
	Version                                                         migrations.Version
	PasswordSignin, VerificationSignin, UsernameSignin, PhoneSignin bool
}

PasskeyContinuationMigrationSource appends the selected native passkey-primary origin to the existing continuation table. Base must be nonempty and Version must follow it. Flags describe already installed predecessor profiles, not new opt-ins: selecting the wrong named predecessor fails during migration. Existing scopes, states, attempts and original deadlines remain unchanged.

func (PasskeyContinuationMigrationSource) Load

Load returns copied forward-only history without database IO or implicit discovery. It never authenticates or backfills an existing continuation.

type PasskeySignupMigrationSource

type PasskeySignupMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

PasskeySignupMigrationSource extends factor-initialization provenance for prospective passkey-only signup without backfilling any existing identity. Base installs factor authority and selected historical magic-link/username successors. Allocate Version after every Base version in the MFA namespace.

func (PasskeySignupMigrationSource) Load

Load preserves predecessor bytes and populated state, performing no SQL IO. Missing prerequisite schema fails when applied; no downgrade is provided.

type PasswordContinuationMigrationSource

type PasswordContinuationMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

PasswordContinuationMigrationSource extends the installed continuation history to genuine password-first challenges. Allocate Version after Base; existing migration bytes and original pending/terminal records stay unchanged. No primary is backfilled and no attempts or expiry are reset.

func (PasswordContinuationMigrationSource) Load

Load returns a forward-only constraint extension without accessing a database. Missing, empty or misordered Base histories deny as with other MFA extensions.

type PendingOTPMetadata

type PendingOTPMetadata struct {
	TenantID                                                 identity.TenantID
	UserID                                                   identity.UserID
	FactorID                                                 string
	IdentifierID                                             identity.IdentifierID
	Channel                                                  delivery.Channel
	AuthorityVersion, IdentifierVersion, VerificationVersion uint64
	CreatedAt, ExpiresAt                                     time.Time
}

PendingOTPMetadata is the exact original code-free enrollment projection. Identifier/version fields must come from native verified-recipient admission, not from treating a client selection as authority. AuthorityVersion is fenced in the owning transaction; timestamps retain the original database lifetime. Construction alone proves neither persistence, enrollment nor authentication.

type PendingTOTPMetadata

type PendingTOTPMetadata struct {
	TenantID             identity.TenantID
	UserID               identity.UserID
	FactorID             string
	AuthorityVersion     uint64
	Profile              mfa.TOTPProfile
	CreatedAt, ExpiresAt time.Time
}

PendingTOTPMetadata is an immutable non-secret preparation projection. It is not proof of persistence, active enrollment or current account authority.

type PhoneContinuationMigrationSource

type PhoneContinuationMigrationSource struct {
	Base                               migrations.Source
	Version                            migrations.Version
	UsernameSignin, VerificationSignin bool
}

PhoneContinuationMigrationSource adds the explicitly selected phone-password origin to the existing non-final continuation store. Allocate Version after Base. UsernameSignin and VerificationSignin describe the installed predecessor; selecting a different constraint fails at migration rather than dropping an unknown constraint. Scope, factor, attempt, replay and expiry records are not changed or backfilled. Construction and Load perform no database operations.

func (PhoneContinuationMigrationSource) Load

Load returns copied forward-only history. Base must be nonempty and Version must follow it; nil, cancellation, invalid bounds and ordering fail closed.

type PhoneRecoveryTOTPAttempt

type PhoneRecoveryTOTPAttempt struct {
	// contains filtered or unexported fields
}

PhoneRecoveryTOTPAttempt classifies actual cryptographic comparison only in its original live OTP owner callback. It is not consuming proof and carries no replay counter. Copies expire when the callback returns; no attempt budget is owned here. The OTP owner alone debits its existing SMS budget on denial.

func VerifyPhoneRecoveryTOTPAttempt

VerifyPhoneRecoveryTOTPAttempt locks active user, aggregate factor authority, then the original confirmed factor BEFORE the caller locks OTP/challenge exclusions. It verifies the exact sealed input or generated command's TOTP with the core verifier at current database time, without advancing replay or any budget. A wrong/replayed code yields a live classification of false; stale authority, expiry and unavailable storage yield errors. Every error must abort the parent callback. No caller/provider callback, decryption, transaction or retry occurs under locks. Prepared plaintext is destroyed on every return.

func (PhoneRecoveryTOTPAttempt) Accepted

Accepted rechecks the exact owner, Work and frozen command generation before revealing the comparison. Zero, foreign and returned handles deny; this observation can never be supplied to the consuming verification API.

func (PhoneRecoveryTOTPAttempt) Format

func (PhoneRecoveryTOTPAttempt) Format(s fmt.State, _ rune)

func (PhoneRecoveryTOTPAttempt) MarshalJSON

func (PhoneRecoveryTOTPAttempt) MarshalJSON() ([]byte, error)

func (PhoneRecoveryTOTPAttempt) MarshalText

func (PhoneRecoveryTOTPAttempt) MarshalText() ([]byte, error)

type PhoneRecoveryTOTPCompletion

type PhoneRecoveryTOTPCompletion struct {
	// contains filtered or unexported fields
}

PhoneRecoveryTOTPCompletion is opaque nonsecret custody for one actual replay CAS in the same protected Work as the parent password mutation. It cannot be constructed from a scalar counter, accepted flag, attempt handle or metadata. It is not a committed result. RequireRecorded is Apply-only; the separate RequireOTPApplyRecorded method accepts only the kernel-correlated final OTP check in this same still-live transaction. No general Work access is exposed.

func VerifyAndRecordPhoneRecoveryTOTP

func VerifyAndRecordPhoneRecoveryTOTP(ctx context.Context, w kernel.Work, owner kernel.FeatureExecutionContributor, command identity.Command, prepared PreparedPhoneRecoveryTOTP) (PhoneRecoveryTOTPCompletion, error)

VerifyAndRecordPhoneRecoveryTOTP independently verifies the exact generated joint phone-reset command at current database time and atomically advances only the internally verified step. The OTP reservation owner must first call RequirePhoneRecoveryTOTPReservation before acquiring downstream OTP locks; this Apply rechecks those account/aggregate/factor locks. The phone owner gates its protected mutation on RequireRecorded in this same Apply and abort on every error. The sole parent coordinator commits/rolls back/reconciles unknown outcomes; this helper never retries or claims rollback. Prepared plaintext is destroyed on every return; no decryption or application callback runs under row locks.

func (PhoneRecoveryTOTPCompletion) Format

func (PhoneRecoveryTOTPCompletion) MarshalJSON

func (PhoneRecoveryTOTPCompletion) MarshalJSON() ([]byte, error)

func (PhoneRecoveryTOTPCompletion) MarshalText

func (PhoneRecoveryTOTPCompletion) MarshalText() ([]byte, error)

func (PhoneRecoveryTOTPCompletion) RequireOTPApplyRecorded

RequireOTPApplyRecorded fences only the successor written by this receipt's actual TOTP verification/CAS, during the later native OTP check in the SAME protected transaction. The kernel correlates the exact registered owners, private Work identity and completed phone Apply before and after all locks. The originating Work is retained privately solely for that no-IO guard; this method borrows SQL only from the current OTPApplyWork. It rechecks active user, original enrollment/aggregate/ciphertext/profile, exact verified replay step and current database time/deadline. No code is compared, replay advanced, authority renewed, scalar verdict accepted or transaction opened. Errors must abort; zero/foreign/returned/expired and other-profile receipts deny. This is neither independent factor proof nor a committed result.

func (PhoneRecoveryTOTPCompletion) RequireRecorded

RequireRecorded verifies the actual provisional replay write and original live owner/command/generation, current user/factor authority and original deadline. It grants no independently reusable reset or session permission. Call only inside the same Apply, immediately before the protected mutation.

type PhoneRecoveryTOTPVerifier

type PhoneRecoveryTOTPVerifier struct {
	// contains filtered or unexported fields
}

PhoneRecoveryTOTPVerifier owns transient cryptographic configuration, not a factor engine, attempt budget, session or transaction. Its envelope service is borrowed and must honor bounded contexts. Concurrent preparations are safe when that service is safe. Decryption happens only in Prepare, outside Work.

func NewPhoneRecoveryTOTPVerifier

func NewPhoneRecoveryTOTPVerifier(crypto *envelope.Service, comparisonKey [32]byte, comparisonKeyVersion uint32) (*PhoneRecoveryTOTPVerifier, error)

NewPhoneRecoveryTOTPVerifier retains the existing envelope service and copies a nonzero independent comparison key into the core verifier. Its positive version is retained in the comparison scope across rotation. It does no IO.

func (*PhoneRecoveryTOTPVerifier) Format

func (*PhoneRecoveryTOTPVerifier) Format(s fmt.State, _ rune)

func (*PhoneRecoveryTOTPVerifier) MarshalJSON

func (*PhoneRecoveryTOTPVerifier) MarshalJSON() ([]byte, error)

func (*PhoneRecoveryTOTPVerifier) MarshalText

func (*PhoneRecoveryTOTPVerifier) MarshalText() ([]byte, error)

func (*PhoneRecoveryTOTPVerifier) Prepare

Prepare decrypts the exact encrypted snapshot before any coordinator locks. until is the original exclusive validity deadline selected by the native phone owner from its authenticated reset/pre-auth/risk authority; this helper cannot authenticate or renew it. It must be microsecond-exact. IO is bounded to five seconds or the earlier caller deadline. Preparation itself grants no permission: both native phases independently lock/recheck the full current factor fence and verify the actual original code at database time. Failed preparation clears all plaintext.

type PreparedOTPEnrollment

type PreparedOTPEnrollment struct {
	// contains filtered or unexported fields
}

PreparedOTPEnrollment retains immutable original metadata, not a generated OTP or a successful factor proof. Codes/digests/delivery stay with OTP's real owners. Copies are safe for concurrent reads; projections cannot mutate them.

func NewPreparedOTPEnrollment

func NewPreparedOTPEnrollment(m PendingOTPMetadata) (PreparedOTPEnrollment, error)

NewPreparedOTPEnrollment validates bounded metadata without IO, entropy, hashing, policy inference or clock reads. Native admission must authenticate and fence its origin/current state before any protected persistence. Zero versions, unadvanceable authority and non-microsecond/invalid lifetimes deny.

func (PreparedOTPEnrollment) Fields

Fields returns owned static command intent with exact recipient/channel and version bindings. No destination, code, bearer or caller-selected authority success flag is encoded; native original custody and primary admission remain required. Changing these fields cannot authorize changing the preparation.

func (PreparedOTPEnrollment) Format

func (PreparedOTPEnrollment) Format(s fmt.State, _ rune)

Format redacts original factor and identifier metadata.

func (PreparedOTPEnrollment) LogValue

func (PreparedOTPEnrollment) LogValue() slog.Value

LogValue redacts pending-enrollment metadata in structured logs.

func (PreparedOTPEnrollment) MarshalJSON

func (PreparedOTPEnrollment) MarshalJSON() ([]byte, error)

MarshalJSON denies implicit original-metadata export.

func (PreparedOTPEnrollment) MarshalText

func (PreparedOTPEnrollment) MarshalText() ([]byte, error)

MarshalText denies implicit textual metadata export.

func (PreparedOTPEnrollment) Metadata

Metadata returns caller-owned original metadata, not current admission.

func (PreparedOTPEnrollment) Persist

Persist consumes the original native primary and stores a pending OTP factor in the sole coordinator Work. It locks account factor authority before the exact verified recipient and method rows, fences original versions/lifetime, limits total live TOTP/OTP pending ceremonies to eight, and advances authority without activating a factor. It generates no code, secret or delivery and opens no transaction. Native risk/CSRF and recovery persistence remain the registered enrollment participant's responsibility; return every error.

type PreparedPhoneRecoveryTOTP

type PreparedPhoneRecoveryTOTP struct {
	// contains filtered or unexported fields
}

PreparedPhoneRecoveryTOTP is owned plaintext custody for one exact original or generated phone-reset command. Copies share one terminal lifetime. Destroy is required after preparation even when execution never starts; verification also destroys it on every return. No plaintext/code/counter can be extracted. Verification is serial and must not race a caller's command-owner destruction.

func (PreparedPhoneRecoveryTOTP) Destroy

func (p PreparedPhoneRecoveryTOTP) Destroy()

Destroy terminally clears the owned primitive Secret for every alias. It is idempotent, including zero. It waits for an in-flight bounded verification.

func (PreparedPhoneRecoveryTOTP) Format

func (PreparedPhoneRecoveryTOTP) Format(s fmt.State, _ rune)

func (PreparedPhoneRecoveryTOTP) MarshalJSON

func (PreparedPhoneRecoveryTOTP) MarshalJSON() ([]byte, error)

func (PreparedPhoneRecoveryTOTP) MarshalText

func (PreparedPhoneRecoveryTOTP) MarshalText() ([]byte, error)

type PreparedTOTPEnrollment

type PreparedTOTPEnrollment struct {
	// contains filtered or unexported fields
}

PreparedTOTPEnrollment retains only encrypted factor custody behind an immutable closure. Copies share owned immutable bytes; returned envelopes and scalar fields cannot change them. It grants no primary admission, disclosure, transaction or activation. Zero denies. Destroy transient plaintext after use.

func (PreparedTOTPEnrollment) EncryptionContext

func (p PreparedTOTPEnrollment) EncryptionContext() (envelope.Context, error)

EncryptionContext returns the original immutable authenticated context.

func (PreparedTOTPEnrollment) Envelope

Envelope returns immutable encrypted custody without decrypting it.

func (PreparedTOTPEnrollment) Fields

Fields returns non-secret static intent fields. Generation instants and ciphertext are retained by encrypted preparation, not resampled retry input.

func (PreparedTOTPEnrollment) Format

func (PreparedTOTPEnrollment) Format(s fmt.State, _ rune)

Format redacts encrypted custody and identity metadata.

func (PreparedTOTPEnrollment) MarshalJSON

func (PreparedTOTPEnrollment) MarshalJSON() ([]byte, error)

MarshalJSON denies implicit custody export.

func (PreparedTOTPEnrollment) MarshalText

func (PreparedTOTPEnrollment) MarshalText() ([]byte, error)

MarshalText denies implicit custody export.

func (PreparedTOTPEnrollment) Metadata

Metadata returns owned scalar preparation data, never current authority.

func (PreparedTOTPEnrollment) Persist

Persist creates one pending factor with primary-proof use and the existing command/audit/lifecycle owner in the same transaction. It never activates a factor or reveals a secret. Account-factor authority is locked before factor rows; unknown, stale or already-active state denies this first-factor profile. At most eight live pending enrollments are permitted per account. Creation advances the factor generation but keeps active_factors zero.

The exact MFA participant must enforce policy/risk and browser CSRF/origin, restore original encrypted generation on retries, call Check after later waits and return every error to the coordinator. No transaction, callback registration, entropy, encryption or private journal is created here.

func (PreparedTOTPEnrollment) Recover

Recover reconciles only this exact original pending-factor creation. Combine it with primary-proof and required lifecycle recovery; it is not complete enrollment or current factor authority. No secret is returned or regenerated. Confirmed/revoked successors retain creation identity; terminal command receipts remain the historical authority after privacy/retention cleanup.

type RecoveryMigrationSource

type RecoveryMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

RecoveryMigrationSource appends pending/active recovery sets and digest-only single-use codes after the owned TOTP factor history. Version is a permanent allocation in that namespace. Existing rows/history bytes are preserved and never backfilled into recovery authority. Activation remains a separate protected transition; pending codes cannot satisfy a recovery operation.

func (RecoveryMigrationSource) Load

Load returns independently owned forward-only history without IO. Missing, invalid or conflicting history and cancellation use the existing owned migration-source contract. No destructive down migration is provided.

type RecoveryRegenerationConfig

type RecoveryRegenerationConfig struct {
	Primary    RecoveryRegenerationPrimarySource
	Sessions   RecoveryRegenerationSessionEffects
	CodeCount  uint32
	MaximumAge time.Duration
}

RecoveryRegenerationConfig selects replacement count and fresh-proof policy at startup, not through the request. Count is 1..64; MaximumAge is positive and at most five minutes. The real session adapter owns all session writes. Digest/envelope/risk/coordinator custody comes from the borrowed enrollment graph; original factor signing trust comes from the selected step-up service.

func (RecoveryRegenerationConfig) Format

Format redacts borrowed current-authority ownership.

func (RecoveryRegenerationConfig) MarshalJSON

func (RecoveryRegenerationConfig) MarshalJSON() ([]byte, error)

MarshalJSON rejects implicit configuration export.

func (RecoveryRegenerationConfig) MarshalText

func (RecoveryRegenerationConfig) MarshalText() ([]byte, error)

MarshalText rejects implicit configuration export.

type RecoveryRegenerationPrimarySource

type RecoveryRegenerationPrimarySource interface {
	PrepareRegeneration(context.Context, mfa.RecoveryRegenerateRequest) (TOTPActivePrimary, session.GetResult, error)
	RestoreRegeneration(context.Context, mfa.RecoveryRegenerateRequest, []byte) (TOTPActivePrimary, error)
}

RecoveryRegenerationPrimarySource supplies actual current session/cookie custody for replacement, not a fabricated TOTP or login request. Restoration accepts only MFA-envelope-authenticated original snapshot bytes. Current owner checks and proof consumption remain protected transaction work.

type RecoveryRegenerationService

type RecoveryRegenerationService struct {
	// contains filtered or unexported fields
}

RecoveryRegenerationService replaces all predecessor recovery sets atomically with one fresh factor proof use, factor-authority advancement, session effects, audit and lifecycle. It owns no goroutines, private transaction or journal. Only a fresh known commit can return replacement material, exactly once.

func NewRecoveryRegenerationService

func NewRecoveryRegenerationService(enrollment *TOTPEnrollmentService, stepup *TOTPActiveStepUpService, c RecoveryRegenerationConfig) (*RecoveryRegenerationService, error)

NewRecoveryRegenerationService freezes complete native composition without IO or entropy. The selected signing-trust ring must fit authentication's 32-key bound. Install the factor evidence and selected session-effect histories.

func (RecoveryRegenerationService) Format

Format redacts native runtime ownership.

func (RecoveryRegenerationService) MarshalJSON

func (RecoveryRegenerationService) MarshalJSON() ([]byte, error)

MarshalJSON rejects implicit service export.

func (RecoveryRegenerationService) MarshalText

func (RecoveryRegenerationService) MarshalText() ([]byte, error)

MarshalText rejects implicit service export.

func (*RecoveryRegenerationService) RecoverRecoveryRegenerate

RecoverRecoveryRegenerate resolves code/proof-free historical outcome under current access policy. It cannot recreate or redeliver replacement material.

func (*RecoveryRegenerationService) RecoveryRegenerate

RecoveryRegenerate validates genuine original factor evidence and current session/CSRF, generates retained encrypted replacement material outside SQL, then atomically consumes the proof and replaces all sets in native Work. Retries reuse original preparation; ambiguity and historical outcomes carry no plaintext. All returned Secret owners must be destroyed after delivery.

type RecoveryRegenerationSessionEffects

RecoveryRegenerationSessionEffects is the session owner's enlisted bounded disposition contract. Apply revokes affected subject sessions and retains exact command-bound evidence in the same Work. Check validates the original source's intentional revocation and primary authority, not continuing access. Recover reads only that owner's durable effect evidence. No callback may open a transaction, retain Work, reveal credentials or perform external IO.

type RecoverySetMetadata

type RecoverySetMetadata struct {
	TenantID                identity.TenantID
	UserID                  identity.UserID
	FactorID, SetID         string
	SetVersion, RowVersion  uint64
	FactorEnrollmentVersion uint64
	KeyVersion, CodeCount   uint32
}

RecoverySetMetadata is non-secret original set/version correlation, not proof that any code is valid or unused. Epoch is immutable across consumption and changes when regeneration creates a replacement set. RowVersion fences state.

func RequireRecordedRecoveryCompletion

RequireRecordedRecoveryCompletion confirms the actual provisional code burn and continuation completion in this same protected invocation. It returns original non-secret set/scope correlation and the durable primary command for native session mapping, not reusable proof. Unrecorded, foreign, returned, changed or expired custody denies. Current primary/policy/session authority and rollback on every error remain required; this read creates no transaction.

type RecoveryVerificationKeys

type RecoveryVerificationKeys struct {
	// contains filtered or unexported fields
}

RecoveryVerificationKeys owns an immutable, bounded retained digest-key ring. It performs no IO and is safe for concurrent use. A missing stored key version fails closed; key rotation must retain versions while their sets remain active. Keys must be independent of intent, envelope and command-fingerprint keys.

func NewRecoveryVerificationKeys

func NewRecoveryVerificationKeys(keys map[uint32][32]byte) (RecoveryVerificationKeys, error)

NewRecoveryVerificationKeys copies one to 64 nonzero versioned keys into opaque custody. Mutating the caller's map does not rotate retained sets. Zero denies.

func (RecoveryVerificationKeys) Format

func (RecoveryVerificationKeys) Format(s fmt.State, _ rune)

Format prevents diagnostics from disclosing cryptographic custody.

func (RecoveryVerificationKeys) MarshalJSON

func (RecoveryVerificationKeys) MarshalJSON() ([]byte, error)

MarshalJSON rejects key export.

func (RecoveryVerificationKeys) MarshalText

func (RecoveryVerificationKeys) MarshalText() ([]byte, error)

MarshalText rejects key export.

type TOTPActivationMigrationSource

type TOTPActivationMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

TOTPActivationMigrationSource appends durable confirmation attribution. Existing active factors retain their historical state without fabricated command ownership. Version must follow the URI reveal migration.

func (TOTPActivationMigrationSource) Load

Load preserves prior history and returns owned forward-only migration SQL.

type TOTPActiveFactorMetadata

type TOTPActiveFactorMetadata struct {
	Factor         TOTPFactorMetadata
	SessionID      string
	SessionVersion uint64
	ValidUntil     time.Time
}

TOTPActiveFactorMetadata preserves the confirmed factor fence and original authenticated session observation. ValidUntil is that observation's exclusive deadline, not a fresh factor lease. Neither metadata nor a matching TOTP counter is step-up proof; native protected issuance must recheck all owners.

type TOTPActiveFactorSnapshot

type TOTPActiveFactorSnapshot struct {
	// contains filtered or unexported fields
}

TOTPActiveFactorSnapshot is encrypted active-factor custody for authenticated step-up, not anonymous login or pending enrollment. It cannot be converted to their snapshot types. Copies retain immutable ciphertext; plaintext belongs to the native service to decrypt outside locks and clear after verification.

func (TOTPActiveFactorSnapshot) EncryptionContext

func (s TOTPActiveFactorSnapshot) EncryptionContext() (envelope.Context, error)

EncryptionContext retains the unchanged existing factor-envelope binding.

func (TOTPActiveFactorSnapshot) Envelope

Envelope returns a freshly parsed encrypted factor, never plaintext.

func (TOTPActiveFactorSnapshot) Format

func (TOTPActiveFactorSnapshot) Format(s fmt.State, _ rune)

Format redacts ciphertext and correlated source/factor metadata.

func (TOTPActiveFactorSnapshot) MarshalJSON

func (TOTPActiveFactorSnapshot) MarshalJSON() ([]byte, error)

MarshalJSON rejects implicit custody export.

func (TOTPActiveFactorSnapshot) MarshalText

func (TOTPActiveFactorSnapshot) MarshalText() ([]byte, error)

MarshalText rejects implicit custody export.

func (TOTPActiveFactorSnapshot) Metadata

Metadata returns independently owned scalar/profile data without renewing original session validity or asserting that verification committed.

type TOTPActivePrimary

type TOTPActivePrimary interface {
	TOTPURIPrimary
	Snapshot() ([]byte, error)
}

TOTPActivePrimary retains the original authenticated session and synchronizer binding for native active-factor verification. Snapshot contains no bearer. Admit borrows preparation Work; Check requires the exact final Apply command. Neither operation verifies a factor or renews the original observation.

type TOTPActivePrimarySource

type TOTPActivePrimarySource interface {
	PrepareStepUp(context.Context, mfa.TotpVerifyRequest) (TOTPActivePrimary, session.GetResult, error)
	RestoreStepUp(context.Context, mfa.TotpVerifyRequest, []byte) (TOTPActivePrimary, error)
}

TOTPActivePrimarySource is the native current-session boundary. Prepare must use a real primary session adapter and return its owned observation unchanged. Restore accepts only snapshot bytes authenticated by the native MFA envelope; it is IO-free and rechecks submitted bearer/CSRF possession. Protected current owner checks remain mandatory even after a successful restore.

type TOTPActiveStepUpConfig

type TOTPActiveStepUpConfig struct {
	Primary                       TOTPActivePrimarySource
	AllowedOrigins                []string
	ComparisonKey                 [32]byte
	ComparisonKeyVersion          uint32
	SigningKey                    FactorVerificationSigningKey
	VerificationKeys              map[string]ed25519.PublicKey
	Issuer, Environment, Audience string
	TTL                           time.Duration
	// EmailChange explicitly permits identity.email.change-request proof
	// issuance. Zero preserves the existing MFA-only action set. This grants
	// no email mutation authority; its owner must consume the original proof.
	EmailChange bool
}

TOTPActiveStepUpConfig explicitly selects authenticated TOTP for management actions. Issuer/environment/audience and lifetime are startup policy, never request overrides. Comparison and signing keys must be independent of lookup, envelope, recovery and command keys. Origins are exact HTTPS origins. Counters, risk, coordinator and encryption use the borrowed enrollment graph.

func (TOTPActiveStepUpConfig) Format

func (TOTPActiveStepUpConfig) Format(s fmt.State, _ rune)

Format redacts cryptographic custody and correlated configuration.

func (TOTPActiveStepUpConfig) MarshalJSON

func (TOTPActiveStepUpConfig) MarshalJSON() ([]byte, error)

MarshalJSON rejects implicit configuration export.

func (TOTPActiveStepUpConfig) MarshalText

func (TOTPActiveStepUpConfig) MarshalText() ([]byte, error)

MarshalText rejects implicit configuration export.

type TOTPActiveStepUpService

type TOTPActiveStepUpService struct {
	// contains filtered or unexported fields
}

TOTPActiveStepUpService verifies a real enrolled factor and persists original signed evidence together with replay advancement, audit and lifecycle effects. It never issues a session. Calls have private participants; borrowed owners must remain available until calls drain. No background work or private journal.

func NewTOTPActiveStepUpService

func NewTOTPActiveStepUpService(enrollment *TOTPEnrollmentService, c TOTPActiveStepUpConfig) (*TOTPActiveStepUpService, error)

NewTOTPActiveStepUpService freezes selected native composition without IO. Install FactorVerificationMigrationSource before calling the service.

func (*TOTPActiveStepUpService) ActiveStepUpRateSource

func (s *TOTPActiveStepUpService) ActiveStepUpRateSource(ctx context.Context, r mfa.TotpVerifyRequest) (lifetime time.Duration, until time.Time, err error)

ActiveStepUpRateSource authenticates current native session/CSRF and confirmed encrypted factor custody without decrypting secrets, comparing codes, issuing proof or reserving/debiting an attempt. It returns the fixed startup step-up policy lifetime and earliest original primary/session deadline, not a renewed lease. TotpVerify independently checks current authority and atomic effects.

func (TOTPActiveStepUpService) Format

func (TOTPActiveStepUpService) Format(s fmt.State, _ rune)

Format redacts borrowed native owners.

func (TOTPActiveStepUpService) MarshalJSON

func (TOTPActiveStepUpService) MarshalJSON() ([]byte, error)

MarshalJSON rejects implicit service export.

func (TOTPActiveStepUpService) MarshalText

func (TOTPActiveStepUpService) MarshalText() ([]byte, error)

MarshalText rejects implicit service export.

func (*TOTPActiveStepUpService) RecoverTotpVerify

RecoverTotpVerify resolves historical issuance without a factor code or proof redelivery. It never advances replay or reconstructs current authority.

func (*TOTPActiveStepUpService) TotpVerify

TotpVerify accepts only the explicit authenticated StepUp arm. Original encrypted preparation is reused before current-source reads on retry. Actual TOTP verification and signature persistence run in one protected transaction; known terminal replay, ambiguity, cancellation and recovery return no proof.

type TOTPConfirmationConfig

type TOTPConfirmationConfig struct {
	Primary              TOTPConfirmationPrimarySource
	AllowedOrigins       []string
	ComparisonKey        [32]byte
	ComparisonKeyVersion uint32
	// Nil preserves the original enrollment profile. Replacement additionally
	// requires exact native whole-subject session disposition ownership.
	Replacement *TOTPReplacementContinuationConfig
}

TOTPConfirmationConfig selects original-session custody and exact HTTPS origins. ComparisonKey is a dedicated retained key, independent of factor encryption and recovery digests; key version and bytes must remain unchanged while original commands/preparations can be retried.

func (TOTPConfirmationConfig) Format

func (TOTPConfirmationConfig) Format(s fmt.State, _ rune)

Format redacts retained configuration and key custody.

func (TOTPConfirmationConfig) MarshalJSON

func (TOTPConfirmationConfig) MarshalJSON() ([]byte, error)

MarshalJSON rejects implicit configuration export.

func (TOTPConfirmationConfig) MarshalText

func (TOTPConfirmationConfig) MarshalText() ([]byte, error)

MarshalText rejects implicit configuration export.

type TOTPConfirmationPrimary

type TOTPConfirmationPrimary interface{ TOTPURIPrimary }

TOTPConfirmationPrimary shares the bounded primary method vocabulary but requires custody for the enrollment-confirmation schema/lifecycle only. An implementation must reject using this value in a URI or login command.

type TOTPConfirmationPrimarySource

type TOTPConfirmationPrimarySource interface {
	RestoreEnrollmentForConfirmation(context.Context, mfa.TotpVerifyRequest, identity.CommandID, uint64, []byte) (TOTPConfirmationPrimary, error)
}

TOTPConfirmationPrimarySource restores the same original enable provenance for code-confirmed activation, not URI disclosure or login-child completion. It must enforce original session/synchronizer and retained parent proof use. Restoration grants no activation: MFA still owns actual code verification, current factor/recovery policy and atomic required session effects.

type TOTPConfirmationService

type TOTPConfirmationService struct {
	// contains filtered or unexported fields
}

TOTPConfirmationService confirms a pending enrollment through the existing coordinator, risk, audit and lifecycle owners. It issues no session, recovery codes or factor secret. Install TOTPActivationMigrationSource before use. Borrowed owners must remain available until concurrent bounded calls drain.

func NewTOTPConfirmationService

func NewTOTPConfirmationService(enrollment *TOTPEnrollmentService, c TOTPConfirmationConfig) (*TOTPConfirmationService, error)

NewTOTPConfirmationService freezes composition without IO or activation. Missing primary, origin, key or protected velocity ownership denies setup.

func (*TOTPConfirmationService) EnrollmentConfirmationRateSource

func (s *TOTPConfirmationService) EnrollmentConfirmationRateSource(ctx context.Context, r mfa.TotpVerifyRequest) (lifetime time.Duration, until time.Time, err error)

EnrollmentConfirmationRateSource authenticates the exact original pending enrollment and session/synchronizer without TOTP comparison, secret decryption, attempt debit, reservation or activation. It returns the immutable enrollment interval and earliest original primary/enrollment deadline. Copies and later transport work must not renew that deadline. Metadata grants no mutation authority: TotpVerify independently fences current native owners and code.

func (TOTPConfirmationService) Format

func (TOTPConfirmationService) Format(s fmt.State, _ rune)

Format redacts borrowed runtime ownership.

func (TOTPConfirmationService) MarshalJSON

func (TOTPConfirmationService) MarshalJSON() ([]byte, error)

MarshalJSON rejects implicit runtime export.

func (TOTPConfirmationService) MarshalText

func (TOTPConfirmationService) MarshalText() ([]byte, error)

MarshalText rejects implicit runtime export.

func (*TOTPConfirmationService) RecoverTotpVerify

RecoverTotpVerify resolves secret-free historical activation under current result-access policy. It does not verify a code, restore expired primary authority, reactivate a factor or issue a session.

func (*TOTPConfirmationService) TotpVerify

TotpVerify accepts only the explicit enrollment variant. Current original session/CSRF, pending epoch, code and risk are checked atomically; competing or stale activations deny. Unknown outcomes return no activation metadata. Matching retries reconstruct the same original command, never a successor.

type TOTPEnrollmentConfig

type TOTPEnrollmentConfig struct {
	ConfigurationID, PolicyID string
	MaximumDuration           time.Duration
	TTL                       time.Duration
	Profile                   mfa.TOTPProfile
	Primary                   TOTPEnrollmentPrimarySource
	Coordinator               kernel.CoordinatorConfig
	RequestKeys               kernel.RequestKeyConfig
	Risk                      risk.ProtectedProviderAdmissionCustodyConfig
	Counters                  riskpg.Config
	ActiveEnvelopeKeyID       string
	RecoveryKeyVersion        uint32
	// contains filtered or unexported fields
}

TOTPEnrollmentConfig selects first-factor enrollment with an explicit native primary source, durable protected counters and provider-only risk policy. Pool/keyring/source ownership stays with the caller. Profile/TTL and policy identity are trusted startup settings, never request overrides. Only TOTP without UV/trusted-device issuance is selected here; other profiles deny. Construct cryptographic custody with NewTOTPEnrollmentConfig, then fill the public composition fields before NewTOTPEnrollmentService freezes them.

func NewTOTPEnrollmentConfig

func NewTOTPEnrollmentConfig(keys kernel.RequestKeyConfig, intent, recovery [32]byte, recoveryVersion uint32, envelopeKey string) (TOTPEnrollmentConfig, error)

NewTOTPEnrollmentConfig retains independent nonzero intent and recovery digest keys in opaque immutable custody. Neither key may equal the other; deployment must additionally keep them independent of envelope, lookup and command-fingerprint keys. The original namespace/key profile must remain available while pending commands or recovery sets depend on it. This pure constructor performs no IO, callback, generation or bootstrap.

func (TOTPEnrollmentConfig) Format

func (TOTPEnrollmentConfig) Format(s fmt.State, _ rune)

Format redacts key/provider configuration for every verb.

func (TOTPEnrollmentConfig) MarshalJSON

func (TOTPEnrollmentConfig) MarshalJSON() ([]byte, error)

MarshalJSON denies implicit sensitive configuration export.

func (TOTPEnrollmentConfig) MarshalText

func (TOTPEnrollmentConfig) MarshalText() ([]byte, error)

MarshalText denies implicit sensitive configuration export.

type TOTPEnrollmentPreparation

type TOTPEnrollmentPreparation struct {
	TenantID         identity.TenantID
	UserID           identity.UserID
	FactorID         string
	AuthorityVersion uint64
	Profile          mfa.TOTPProfile
	CreatedAt        time.Time
	TTL              time.Duration
}

TOTPEnrollmentPreparation is trusted native generation input, never a client DTO. AuthorityVersion is the actual known-empty factor generation selected during admission. CreatedAt is the original UTC-compatible database instant, at microsecond precision; TTL is 1 second..15 minutes at that precision. IDs/profile/TTL must enter original command custody before generation.

type TOTPEnrollmentPreparer

type TOTPEnrollmentPreparer struct {
	// contains filtered or unexported fields
}

TOTPEnrollmentPreparer borrows a local keyring and owns no IO, clock, pool, goroutine or retry authority. Generate outside protected database locks. Concurrent calls are safe under the keyring's contract. Retain decrypting keys through pending enrollments, journal recovery and their retention policy.

func NewTOTPEnrollmentPreparer

func NewTOTPEnrollmentPreparer(keys *keyring.Provider, key string) (*TOTPEnrollmentPreparer, error)

NewTOTPEnrollmentPreparer configures local encryption without generating a secret or touching storage. No remote key provider or application callback can be selected in this profile. Key presence is checked during generation.

func (TOTPEnrollmentPreparer) Format

func (TOTPEnrollmentPreparer) Format(s fmt.State, _ rune)

Format redacts local key/provider configuration.

func (TOTPEnrollmentPreparer) MarshalJSON

func (TOTPEnrollmentPreparer) MarshalJSON() ([]byte, error)

MarshalJSON denies implicit configuration export.

func (TOTPEnrollmentPreparer) MarshalText

func (TOTPEnrollmentPreparer) MarshalText() ([]byte, error)

MarshalText denies implicit configuration export.

func (*TOTPEnrollmentPreparer) Prepare

Prepare generates a 256-bit random factor and seals it under the existing totp-secret-v1 tenant/user/factor/enrollment/profile context. It returns no plaintext or provisioning URI. Restore original encrypted preparation on retries; calling Prepare again is new entropy, not idempotent generation. Earlier cancellation wins; crypto failures are redacted Unavailable errors.

type TOTPEnrollmentPrimary

TOTPEnrollmentPrimary extends the protected primary participant with original request preparation and secret-free recovery. Snapshot exports only transient provenance for native authenticated encryption; it is never naked authority. Original supplies immutable historical session metadata, not current access. Methods are bounded and do not own transactions, clocks, caches or goroutines.

type TOTPEnrollmentPrimaryAdmission

TOTPEnrollmentPrimaryAdmission is the narrow consumer-owned boundary for a real configured primary adapter. Password's native source implements it without making MFA depend on password/session storage. Consume must fence current primary owners and use original proof once in this same Work; Check must recheck original freshness after waits. An application-written no-op is not an authentication adapter. Browser CSRF/origin and risk remain required.

type TOTPEnrollmentPrimarySource

TOTPEnrollmentPrimarySource is the consumer-owned native primary boundary. Select a real platform adapter, not a consumer-written authentication callback. PrepareEnrollment validates original signed evidence and current possession outside Work. RestoreEnrollment is IO-free and accepts only provenance the native enrollment owner has authenticated under its complete encrypted input binding. Neither return value grants mutation: the protected participant must consume/check exact primary authority atomically with pending-factor effects. The original request, factor identity and evidence cannot change on retry.

type TOTPEnrollmentService

type TOTPEnrollmentService struct {
	// contains filtered or unexported fields
}

TOTPEnrollmentService borrows one primary pool and immutable native owners. It owns no goroutines, private transaction, journal or connection. Every call has its own comparable participant and encrypted original preparation. Concurrent calls require immutable inputs and concurrent-safe dependencies. Install the owned pending-factor/recovery and selected kernel/risk histories before use. Construction does not initialize missing account factor state.

func NewTOTPEnrollmentService

func NewTOTPEnrollmentService(pool *database.Pool, c TOTPEnrollmentConfig, keys *keyring.Provider) (*TOTPEnrollmentService, error)

NewTOTPEnrollmentService validates explicit native composition without IO or secret generation. Durable lockout admission is mandatory; provider facts cannot substitute for protected velocity. Missing/unsupported owners deny. Existing account factor absence is never interpreted as known-empty state.

func (*TOTPEnrollmentService) Enable

Enable retains original code-free input before risk or secret generation, then executes one native pending-factor/recovery mutation through the existing prepared coordinator. Matching retry never looks up a new original primary or generates successor material. Only an error-free fresh known commit returns recovery output; URI revelation and factor confirmation are separate commands. All borrowed inputs must remain immutable until return. Errors preserve cancellation and ambiguous outcomes and never include credentials.

func (TOTPEnrollmentService) Format

func (TOTPEnrollmentService) Format(s fmt.State, _ rune)

Format redacts native configuration and borrowed owners.

func (TOTPEnrollmentService) MarshalJSON

func (TOTPEnrollmentService) MarshalJSON() ([]byte, error)

MarshalJSON denies implicit native service export.

func (TOTPEnrollmentService) MarshalText

func (TOTPEnrollmentService) MarshalText() ([]byte, error)

MarshalText denies implicit native service export.

func (*TOTPEnrollmentService) RecoverEnable

RecoverEnable uses only the exact original non-secret command scope and the current result-access policy. It never asks for a password/code/bearer, restores expired authorization, generates material, reveals codes or repeats enrollment. All native proof/factor/recovery/counter/audit/lifecycle participants must agree before pending ambiguity can terminalize. Terminal receipts remain historical.

type TOTPFactorMetadata

type TOTPFactorMetadata struct {
	TenantID                                              identity.TenantID
	UserID                                                identity.UserID
	FactorID                                              string
	EnrollmentVersion, RowVersion, FactorAuthorityVersion uint64
	ContinuationID                                        mfa.ContinuationID
	ContinuationVersion                                   uint64
	ScopeDigest                                           [32]byte
	Profile                                               mfa.TOTPProfile
	Replay                                                mfa.TOTPReplayState
}

TOTPFactorMetadata is a trusted reader's non-secret version fence. It is not factor proof or session permission. Native completion must recheck all these identities/versions and atomically advance Replay in the protected Work.

func RequireRecordedTOTPCompletion

RequireRecordedTOTPCompletion confirms this same borrowed handle's actual provisional replay/continuation write during the exact original native Apply. Zero, foreign, unrecorded, returned or finalized custody denies. Original scope and pre-completion factor metadata are returned for exhaustive session mapping, along with the durable original primary command. These projections are not reusable proof. Native policy, primary/browser and session authority remain required, and every error must abort the sole transaction. No retry, transaction, consumption, lease or authentication is created here.

type TOTPFactorMigrationSource

type TOTPFactorMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

TOTPFactorMigrationSource appends encrypted factor/enrollment and replay storage after existing MFA history. Allocate Version permanently in that namespace. It preserves existing bytes and performs no enrollment/backfill.

func (TOTPFactorMigrationSource) Load

Load returns forward-only SQL. Zero, typed-nil or empty/conflicting histories deny. The source owns no IO and is safe for concurrent calls with a safe Base.

type TOTPFactorReader

type TOTPFactorReader struct {
	// contains filtered or unexported fields
}

TOTPFactorReader borrows primary PostgreSQL and owns no transaction, cache, goroutine or pool lifetime. Concurrent reads are safe. It reveals encrypted custody only for a verified, live child continuation permitting TOTP.

func NewTOTPFactorReader

func NewTOTPFactorReader(pool *database.Pool, maximumDuration time.Duration) (*TOTPFactorReader, error)

NewTOTPFactorReader configures one shared read budget, at most five seconds; earlier caller deadlines win. It performs no IO.

func (*TOTPFactorReader) Read

func (r *TOTPFactorReader) Read(ctx context.Context, grant capability.Grant, issuer, factorID string) (TOTPFactorSnapshot, error)

Read restores confirmed, encrypted TOTP custody under original continuation scope and current primary authority. It never verifies a code, spends an attempt, advances replay or grants session issuance. Concurrent changes may invalidate the snapshot: final protected execution must recheck its complete fence. Missing, foreign, pending, revoked or stale state denies; unavailable storage fails closed. No plaintext, unbounded read, renewal or retry occurs.

func (*TOTPFactorReader) ReadForPhoneRecovery

func (r *TOTPFactorReader) ReadForPhoneRecovery(ctx context.Context, tenant identity.TenantID, user identity.UserID, factorID string) (TOTPFactorSnapshot, error)

ReadForPhoneRecovery reads one confirmed encrypted factor without inventing a login continuation or authenticated session. Tenant/user/factor select only structural custody, never recovery authorization. The native phone owner must authenticate the original reset capability and all phone/pre-auth/risk and password authority, then match its original factor generations. Missing, inactive, foreign or corrupt state denies. The shared reader budget bounds IO; no secret is decrypted, attempt charged or replay advanced here.

func (*TOTPFactorReader) ReadForStepUp

func (r *TOTPFactorReader) ReadForStepUp(ctx context.Context, original session.GetResult, factorID string) (TOTPActiveFactorSnapshot, error)

ReadForStepUp reads confirmed encrypted factor custody for the exact subject of an owned current SessionService.Get result. The native composition must obtain that result from its configured real session adapter using the actual submitted token and enforce action policy before calling. A client-supplied Authenticated flag or Session value cannot replace its private custody.

This reads no code, grants no step-up authority and performs no mutation. It preserves the original observation deadline across the bounded primary read. Final protected execution still requires original bearer/CSRF possession, current primary/factor authority, exact encrypted-factor fence and replay advancement with actual code verification. Missing/unsupported state denies; unavailable/corrupt storage fails closed. Borrowed pool ownership is unchanged.

func (*TOTPFactorReader) SelectForPhoneRecovery

func (r *TOTPFactorReader) SelectForPhoneRecovery(ctx context.Context, tenant identity.TenantID, user identity.UserID) (TOTPFactorSnapshot, error)

SelectForPhoneRecovery selects the lowest immutable confirmed TOTP factor ID for a resolved tenant/user, then reads its original encrypted custody. This request-only deterministic policy never selects SMS or an unconfirmed factor. Install the existing recovery history, whose subject-unique factor key also supports this bounded lookup. No new migration, factor or permission is made.

The phone owner must first authenticate its original browser and resolve the verified phone/current password account. Capture this selection in the issued reset grant; retries/completion must read that exact original factor rather than select another. Concurrent withdrawal fails closed at the read or later protected fences. One shared timeout covers both reads; no secret is decrypted, replay changed, factor proof produced or validity interval renewed.

type TOTPFactorSnapshot

type TOTPFactorSnapshot struct {
	// contains filtered or unexported fields
}

TOTPFactorSnapshot retains immutable encrypted custody behind an opaque closure; diagnostics cannot traverse ciphertext or account metadata. Zero denies. Copies share immutable custody and concurrent reads are safe. It carries no plaintext and cannot authenticate or consume a continuation.

func (TOTPFactorSnapshot) EncryptionContext

func (s TOTPFactorSnapshot) EncryptionContext() (envelope.Context, error)

EncryptionContext returns the exact authenticated tenant/user/factor/ enrollment/profile binding, unchanged across wrapping-key rotation.

func (TOTPFactorSnapshot) Envelope

func (s TOTPFactorSnapshot) Envelope() (envelope.Envelope, error)

Envelope returns a fresh immutable encrypted envelope and never decrypts it. The consuming MFA service owns bounded secret-envelope decryption and must clear plaintext and destroy its opaque password.Secret after computation.

func (TOTPFactorSnapshot) Metadata

Metadata returns an owned scalar profile/version projection. A populated value is not proof of current storage authority or successful verification.

type TOTPListReader

type TOTPListReader struct {
	// contains filtered or unexported fields
}

TOTPListReader borrows the existing TOTP-only enrollment owner and primary pool. That profile explicitly does not issue trusted devices or security-key factors. An unexpected active-factor count denies instead of omitting another owner's state. Empty trusted-device output describes this selected profile, not a claim that unsupported device storage is an authoritative empty store. No secret, envelope, verifier, replay counter or credential is selected. This structural reader is not an authentication or enumeration endpoint.

func NewTOTPListReader

func NewTOTPListReader(enrollment *TOTPEnrollmentService) (*TOTPListReader, error)

NewTOTPListReader selects the existing native TOTP metadata profile without IO. Enrollment supplies the immutable whole-read bound and primary owner; callers must keep it and its pool alive until all reads finish. This does not select a route, initialize missing authority or grant access to another user.

func NewTOTPManagementListReader

func NewTOTPManagementListReader(management *FactorUpdateService) (*TOTPListReader, error)

NewTOTPManagementListReader selects safe labels from the separately composed factor-management metadata schema. It borrows that exact mutation owner's native enrollment state; it does not infer optional columns or swallow a missing migration as an empty label. The base reader remains schema-compatible with profiles that have not selected management. Construction performs no IO.

func (*TOTPListReader) ReadFactors

ReadFactors reads one bounded, coherent primary snapshot of safe TOTP metadata and unused active-set recovery counts. It has no mutations, private transaction or retries. The outer service authenticates/authorizes and rechecks its original session before disclosure. Missing subject/authority denies; corrupt, oversized or unsupported inventories and outages return no partial data. Consumed codes, pending/retired sets and revoked factors never contribute remaining counts.

type TOTPReplacementConfig

type TOTPReplacementConfig struct {
	RecoveryCodes uint32
}

TOTPReplacementConfig selects the complete pending successor recovery set. RecoveryCodes is 1..64; zero is not a default or a permission to omit recovery. The existing enrollment owner supplies the immutable TOTP profile and TTL.

type TOTPReplacementContinuationConfig

type TOTPReplacementContinuationConfig struct {
	Management *FactorUpdateService
	Primary    TOTPReplacementPrimarySource
	// Sessions is required for confirmation and unused by URI revelation.
	Sessions RecoveryRegenerationSessionEffects
}

TOTPReplacementContinuationConfig explicitly selects the same native management owner that created the successor and its original-session adapter. Owners are borrowed and must outlive all bounded continuation calls.

type TOTPReplacementMigrationSource

type TOTPReplacementMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

TOTPReplacementMigrationSource appends explicit predecessor/successor provenance and pending-initiation effects. Install after management/removal metadata; disable is independently optional. Old migration SQL is unchanged.

func (TOTPReplacementMigrationSource) Load

Load preserves populated history and appends only the forward replacement schema. No downgrade, generated authority or installed receipt rewriting.

type TOTPReplacementPrimary

type TOTPReplacementPrimary interface {
	TOTPURIPrimary
	ReadCurrent(context.Context) error
	OriginalDeadline() (time.Time, error)
}

TOTPReplacementPrimary separates immutable authenticated parent custody from a new bounded authoritative observation. ReadCurrent runs before protected locks and retains its first actual read deadline; repeated calls must not renew that observation. OriginalDeadline identifies the unchanged parent's initial observation, not continuing permission. Historical outcome replay restores original custody without requiring a still-active source session.

type TOTPReplacementPrimarySource

type TOTPReplacementPrimarySource interface {
	RestoreReplacementForURI(context.Context, mfa.TotpUriRequest, []byte, time.Time) (TOTPReplacementPrimary, error)
	RestoreReplacementForConfirmation(context.Context, mfa.TotpVerifyRequest, []byte, time.Time) (TOTPReplacementPrimary, error)
}

TOTPReplacementPrimarySource restores an original active-session snapshot only after MFA authenticates its committed factor-update parent. Neither method translates it into password-enable evidence, creates factor proof or renews the retained validity deadline. MFA fences original replacement lineage and current predecessor authority in the protected Work.

type TOTPSessionFactorReader

type TOTPSessionFactorReader struct {
	// contains filtered or unexported fields
}

TOTPSessionFactorReader borrows the primary pool and creates no transaction, cache, goroutine or factor secret. Concurrent reads are safe; the caller closes the pool only after calls finish. Unknown or unconfirmed factors fail closed.

func NewTOTPSessionFactorReader

func NewTOTPSessionFactorReader(pool *database.Pool, maximumDuration time.Duration) (*TOTPSessionFactorReader, error)

NewTOTPSessionFactorReader freezes a bounded primary read budget (at most five seconds) without IO. Earlier caller deadlines win. Reading cannot enroll, complete, recover or authorize changing a factor.

func (*TOTPSessionFactorReader) Format

func (*TOTPSessionFactorReader) Format(s fmt.State, _ rune)

Format prevents diagnostic traversal into pool/configuration state.

func (*TOTPSessionFactorReader) MarshalJSON

func (*TOTPSessionFactorReader) MarshalJSON() ([]byte, error)

MarshalJSON rejects implicit pool/configuration export.

func (*TOTPSessionFactorReader) MarshalText

func (*TOTPSessionFactorReader) MarshalText() ([]byte, error)

MarshalText rejects implicit export and map-key disclosure.

func (*TOTPSessionFactorReader) Read

Read requires exact canonical stored identities and a canonical random128 factor ID. It reads confirmed active factor and current account-wide epoch in one primary statement. Revoked, unconfirmed, missing or blocked state denies; corruption/outage returns a redacted unavailable error. No child lifetime, ciphertext, code, replay counter, cache expiry or authentication is returned.

type TOTPSessionFactorState

type TOTPSessionFactorState struct {
	EnrollmentVersion, AuthorityVersion uint64
}

TOTPSessionFactorState projects the current confirmed factor's enrollment and account-wide factor epoch from primary storage. It is not a proof or lease. The session owner must compare its exact original tenant/user/factor and enrollment, include AuthorityVersion in the complete current vector, and preserve the earliest contributing authoritative read's validity deadline.

type TOTPURIConfig

type TOTPURIConfig struct {
	Primary        TOTPURIPrimarySource
	AllowedOrigins []string
	// Nil preserves initial-enrollment-only provenance and configuration bytes.
	Replacement *TOTPReplacementContinuationConfig
}

TOTPURIConfig explicitly selects the original-session synchronizer adapter and exact HTTPS origins. No route is registered. All owners and key custody are borrowed from the configured enrollment service; keep them alive until calls drain. The same original configuration must remain available on retry. The account label prefers the verified primary email. With no such primary, exactly one verified email may label the URI; multiple candidates deny. Selecting a display label never makes that identifier primary or recovery authority. Its value, version and primary status are bound and fenced.

func (TOTPURIConfig) Format

func (TOTPURIConfig) Format(s fmt.State, _ rune)

Format redacts borrowed primary ownership and deployment configuration.

func (TOTPURIConfig) MarshalJSON

func (TOTPURIConfig) MarshalJSON() ([]byte, error)

MarshalJSON denies implicit native configuration export.

func (TOTPURIConfig) MarshalText

func (TOTPURIConfig) MarshalText() ([]byte, error)

MarshalText denies implicit native configuration export.

type TOTPURIPrimary

TOTPURIPrimary is original-session custody for a separate pending-enrollment disclosure. Admit must fence current primary owners, the retained synchronizer and the exact parent enrollment's consumed verification record in the borrowed Work. It cannot consume another proof or renew any original freshness boundary.

type TOTPURIPrimarySource

type TOTPURIPrimarySource interface {
	RestoreEnrollmentForURI(context.Context, mfa.TotpUriRequest, identity.CommandID, uint64, []byte) (TOTPURIPrimary, error)
}

TOTPURIPrimarySource restores only provenance authenticated by the native enrollment owner's original encrypted request binding. Parent command and row version come from the pending factor, not transport-supplied metadata. Origin policy, factor expiry, risk and atomic revelation remain MFA's owners.

type TOTPURIService

type TOTPURIService struct {
	// contains filtered or unexported fields
}

TOTPURIService atomically consumes pending enrollment disclosure through the existing command/preparation/risk/audit/lifecycle owners. It creates no secret, proof, successor enrollment, goroutine or private transaction. Install URIRevealMigrationSource first. Concurrent immutable calls are supported.

func NewTOTPURIService

func NewTOTPURIService(enrollment *TOTPEnrollmentService, c TOTPURIConfig) (*TOTPURIService, error)

NewTOTPURIService freezes explicit composition without IO or generation. Missing primary/CSRF ownership, protected risk classification or origin policy denies setup; no bearer-only or unclassified-risk fallback is permitted.

func (TOTPURIService) Format

func (TOTPURIService) Format(s fmt.State, _ rune)

Format prevents implicit traversal of native owners and configuration.

func (TOTPURIService) MarshalJSON

func (TOTPURIService) MarshalJSON() ([]byte, error)

MarshalJSON denies implicit runtime export.

func (TOTPURIService) MarshalText

func (TOTPURIService) MarshalText() ([]byte, error)

MarshalText denies implicit runtime export.

func (*TOTPURIService) RecoverTotpUri

RecoverTotpUri reconciles exact secret-free historical scope under current result-access policy. It never restores possession, decrypts a factor, reveals material or repeats consumption; every native participant must agree.

func (*TOTPURIService) TotpUri

func (s *TOTPURIService) TotpUri(ctx context.Context, r mfa.TotpUriRequest) (out mfa.TotpUriResult, err error)

TotpUri binds the original enrollment/session to one separate stable command, admits current owners and protected risk, and returns material only from an error-free first committed reveal. Matching retries and recovery return none. Unknown outcomes never reveal or allocate a successor. Earlier cancellation wins; caller-owned borrowed input must remain immutable until return.

func (*TOTPURIService) TotpUriRateSource

func (s *TOTPURIService) TotpUriRateSource(ctx context.Context, r mfa.TotpUriRequest) (lifetime time.Duration, until time.Time, err error)

TotpUriRateSource authenticates original enrollment/session/CSRF custody and reads its immutable quota lifetime and earliest disclosure deadline. It uses the same retained native input as TotpUri, without decrypting the TOTP secret, comparison, generation, reservation, debit or reveal consumption. Returned metadata is not mutation permission. The transport must retain this original deadline; a later source read cannot renew it. Native mutation independently fences current authority. Unsupported, expired or foreign custody denies.

type URIRevealMigrationSource

type URIRevealMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

URIRevealMigrationSource appends exact reveal-command attribution without changing prior migrations or resetting historical reveal_consumed markers. Historical consumed rows without attribution remain non-revealable. Version must follow the owned recovery history. No factor is enrolled or backfilled.

func (URIRevealMigrationSource) Load

Load returns forward-only owned SQL using the existing MFA migration bounds.

type UsernameContinuationMigrationSource

type UsernameContinuationMigrationSource struct {
	Base               migrations.Source
	Version            migrations.Version
	VerificationSignin bool
}

UsernameContinuationMigrationSource appends the explicit username-origin continuation profile after password continuations. VerificationSignin selects the already installed verification-origin predecessor; a mismatched selection fails rather than dropping an unknown constraint or rewriting older history. Base is optional for an operator-owned suffix namespace; otherwise Version must follow it. Existing scopes, attempts, states and deadlines stay unchanged.

func (UsernameContinuationMigrationSource) Load

Load returns copied forward-only history without database access or implicit predecessor discovery. No existing record is relabeled or made authenticated.

type UsernameSignupMigrationSource

type UsernameSignupMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

UsernameSignupMigrationSource adds exact username-signup initialization provenance. Base installs factor authorities and any selected historical magic-link suffix; Version follows all Base versions. This successor retains both prior purpose arms and changes no factor/account row. It never infers that an existing account has no enrolled factors.

func (UsernameSignupMigrationSource) Load

Load performs the same bounded immutable-history validation as the earlier signup suffix, replacing only its uninstalled last migration with this one.

type VerificationContinuationMigrationSource

type VerificationContinuationMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

VerificationContinuationMigrationSource appends verification-origin MFA to installed continuation history. A selected Base requires Version after it; nil Base returns one independent suffix for an operator-owned namespace. Existing migration bytes, original scopes, attempt budgets and deadlines remain unchanged; no primary, challenge or session is backfilled or reinterpreted.

func (VerificationContinuationMigrationSource) Load

Load returns a forward-only constraint extension without database access. Zero versions, nil contexts and selected empty/misordered bases fail closed.

Source Files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL