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

postgres

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: 36 Imported by: 0

README

PostgreSQL session storage

Organization-selected password sessions

Selection is a logical organization operation, not a second session command. OrganizationSelectionFields freezes the exact original session, explicit organization/clear and exclusive admission deadline. Its inverse reconstructs structure only, never bearer custody, permission or renewed authority.

Install OrganizationSelectionMigrationSource at an unused permanent version after the session history. NewOrganizationSelectionEffect lets the native organization participant enlist one exact session CAS in its original Work: authenticate the bearer, call Lock before organization/member locks, require the target's actual active membership and policy, call Apply, then call Check from its final commit phase. Declare session.organization_changed.v1 with the exact source/successor session versions and required protected identity.organization.change_active audit. The existing coordinator owns the sole command, transaction and required audit/outbox. Recovery delegates the session participant's vote to Recover; it never replays the mutation.

The organization PostgreSQL owner must supply OrganizationSessionAuthority: derive a canonical tenant-plus-organization key, use its aggregate authority epoch (not a member epoch), require current active membership, and fence both in the same Work. Configure identical OrganizationPasswordSessionAdmission in SelectedSessionAdmissionConfig.OrganizationPassword and RevokeOneExecutorConfig.OrganizationPassword. Ordinary readers remain opted out. Selected reads retain every original primary dimension and the earliest contributing evidence deadline, at most20 seconds; removal/archive, changed epochs, missing authority and expiry deny without stale or unselected fallback.

Only single-factor password/bearer selection is enabled by this adapter profile. Cookie, MFA and passkey selection require their own explicit owner composition; they are not downgraded. A selector changes only one session version/vector; token, family, original authentication, activity and expiry remain unchanged. This module supplies the session-owned effect and authority seam, not a complete organization selector endpoint or an application-written membership store.

Passkey primary with confirmed TOTP

MFAPasskeySessionAdmission explicitly selects RP mapping plus the MFA owner's current confirmed TOTP enrollment and account-factor generation. It is separate from PasskeySessionAdmission, which requires known-empty MFA. Use the same selection in NewMFAPasskeySessionService (or SelectedSessionAdmissionConfig) and RevokeOneExecutorConfig.MFAPasskey; neither may fall back to a single-factor reader. The borrowed MFAPasskeySessionAuthority supplies mapping evidence only, not factor proof. Primary reads retain the earliest contributing 20-second validity bound, including cached paths; copying cannot renew it.

NewMFAPasskeyTOTPCompletionEffect persists the original projected session only after real native TOTP completion was recorded in the same protected Work. The native owner must first authenticate the original assertion, browser and child, authorize the operation, and take directory/credential/policy fences. Acquire factor authority before RP mapping locks, matching native passkey signin/enrollment. Call the effect's Check in the original CheckFeatureCommit after audit/outbox waits; an original credential can expire while those wait. The native passkey MFA challenge leaves its browser issued. At admission, RequirePreAuth fences that exact original record and expiry. During protected completion, use ReserveMFAPasskeyPreAuth, apply the recorded factor/session effects, then FinalizeMFAPasskeyPreAuth in the same Work. These sealed APIs retain distinct original-passkey and MFA command/policy identities; generic ReservePreAuth cannot substitute one for the other. Late failure rolls back browser, child, factor and session effects together. The older RequireMFAPasskeyConsumedPreAuth only checks an already-consumed-primary profile; it cannot admit the issued browser from native MFA signin. No email recipient or password evidence is invented. This effect is not a login service.

Install PasskeyMFAMigrationSource after the actual selected v6-v9 record and matching credential-continuation constraints, with a permanently allocated version. The transactional forward suffix validates populated rows and preserves the existing predicate and records, adding only the closed passkey/TOTP branch. Upgrade readers before enabling issuance. Existing password and known-empty passkey profiles retain their separate semantics.

Prospective passkey-only signup

PasskeySignupSessionFields retains a complete initial UV-passkey session in the original anonymous signup command. PasskeySignupSession binds its user to kernel-owned registration.user and its authenticating credential to the command's credential subject. Initial user/credential/policy/factor/passkey epochs must be one; deployment epochs remain their original observed values. No email, password, factor enrollment or recovery assurance is invented.

NewPasskeySignupEffect participates only in the exact native signup Work after the kernel actually creates that prospective account. The owned native adapter supplies PasskeySignupSessionAuthority to lock the current RP/key mapping and the known-empty factor generation initialized by this same signup. The effect fences actual kernel and authorization authority, writes the initial session, family and domain-separated issuance evidence, then stages that exact session's creation in the original kernel Work. The selected outbox must implement PasskeySignupSessionLifecycleContributor and persist account, credential and session events atomically; an older account-only adapter denies this profile. The effect repeats admission in Check after downstream effects. It does not verify WebAuthn, authenticate a pre-auth cookie, issue a bearer, own pre-auth consumption or replace required lifecycle persistence. Those remain atomic obligations of the native signup composition. This storage seam alone does not expose a usable public signup endpoint.

Append PasskeySignupMigrationSource to the selected installed session history, naming its actual issuance-purpose PreviousConstraint; it may follow the passkey-signin suffix or another supported selected predecessor. The validated old purpose expression and live rows are preserved. The migration runner owns transactional DDL and bounded lock/statement budgets; install before enabling the new purpose. Retire readers that cannot decode passkey sessions first.

Recover is original coordinator participation, not disclosure permission. ReadPasskeySignupIdentity retains the original user/session/family tuple even after payload pruning, but returns no bearer, live authority or complete command outcome. Native recovery must establish the original commit and disclosure custody; neither method renews freshness or permits reveal-again retries.

Identified UV-passkey session composition

PasskeySigninSessionFields and PasskeySigninSession retain the complete prospective session without bearer or assertion bytes. The native verification command's RecordID is the new session ID, not its separate WebAuthn ceremony ID, so required session lifecycle/audit effects identify their actual subject. NewPasskeySigninEffect stages that session/family and domain-separated retained issuance evidence in the passkey owner's existing Work. The owned passkey adapter must first verify the real opaque assertion and commit its protocol counter, mapping, risk and required effects atomically. Call Check after downstream effects and Recover only through original coordinator recovery.

NewPasskeySessionService and RevokeOneExecutorConfig.Passkey explicitly select the same trusted RP namespace and owned PasskeySessionAuthority. The port verifies RP/credential mapping, passkey authority and the exact known-empty MFA generation. A present factor epoch in this profile is an original lifecycle fence, not completed secondary MFA; MFAAuthentication remains absent. Both epochs survive issuance, reads and logout. No password fallback or original epoch refresh is permitted. Positive evidence ends at the earliest contributing owner deadline, at most20s after its original authoritative read begins.

For a common reader, select SelectedSessionAdmissionConfig.Passkey with that same PasskeySessionAdmission alongside the desired password/OTP/magic-link/MFA profiles. NewSelectedSessionService makes one primary token lookup and uses the stored method and authority dimensions, not caller selection or fallback. All selected owners must share deployment, policy namespace and audience. Pass the identical admission to RevokeOneExecutorConfig.Passkey for logout. Passkey-only selection is also supported. Adding this owner changes the selected cache profile; leaving it absent preserves legacy custody exactly. Selection does not enable signup, HTTP routes or completed passkey-plus-secondary MFA.

Append PasskeySigninMigrationSource after the complete installed session history, with PreviousConstraint naming its actual issuance-purpose constraint and a new permanently allocated version. PostgreSQL preserves that existing validated purpose expression and adds only passkey assertion issuance. No other method, anonymous or device history is required. The transactional change takes an exclusive table lock and validates populated rows; use the migration runner's bounded statement/lock budgets. Unknown, missing, already-replaced or non-purpose constraints fail. Old migration SQL/checksums remain unchanged. Keep unaware readers out of passkey-serving routes before activation; older purpose suffixes cannot run afterward. These components alone are not a usable passkey workflow or permission to supply an application-written authority store.

Native password/OTP self-logout retains the sealed factor method and uses the MFA owner's RequireOTPSessionFactor, including current recipient verification and original enrollment/account versions. It does not fall back to TOTP or single-factor admission. Use the matching MFA adapter; existing session records and migration bytes are unchanged.

Anonymous creation session effects

AnonymousSigninSessionFields freezes the complete initial anonymous session before command fingerprinting. AnonymousSigninEffect consumes only the exact native anonymous command, actual same-Work kernel creation and original user epochs. The anonymous owner must separately persist its lifecycle/TTL, admit action-specific risk and initialize the explicit guest authorization namespace. The session effect never invents a credential, verified proof, policy permission or expiry authority. Call Check during the owner's final read-only commit phase; Recover inspects retained original issuance evidence without delivering a bearer or renewing authentication.

Append AnonymousSigninMigrationSource last among selected issuance-purpose extensions. Predecessor and optional suffix flags must describe the installed history exactly. The base-issuance profile requires no OTP/password/MFA methods; combined profiles preserve every selected older purpose. Wrong predecessor selection fails rather than adopting another installed constraint. No old migration bytes or retained digests change. This component alone enables no anonymous endpoint, lifecycle cleanup, deletion, upgrade or session reader.

Anonymous self-disposal

AnonymousSourceSessionFields and its exact inverse preserve only a complete existing anonymous source, including unchanged remember/authority/lookup/CSRF; they do not widen verified-user OriginalSessionFields or prove possession. The workflow must prove the original bearer/CSRF and current primary owners. NewAnonymousDisposalEffect then requires actual kernel disposal in that exact delete invocation before terminally revoking every anonymous session and family, including expired active-state siblings. A permanent-method sibling denies the entire disposal rather than deleting its sessions. The bounded set is atomic: more than100000 session/family rows fails, not partial success.

Append session AnonymousDisposalMigrationSource after installed anonymous issuance history. Required retained effect evidence belongs here, not a second workflow journal. Call Check in the final same-Work phase and Recover only through the existing coordinator. Recovery inspects original evidence after live session cleanup, issues no credential and grants no live access. Native anonymous retention, risk and kernel/lifecycle disposal are separately mandatory.

Anonymous upgrade session effects

AnonymousUpgradeSessionFields binds complete retained guest and prospective permanent records with domain-separated commitments using the existing session codec. Keep the target's complete source-session.* vocabulary unchanged for the password proof owner. Three flattened records exceed the shared command limit; these commitments preserve complete metadata without widening that bound or accepting arbitrary JSON. The native authenticated preparation must retain both full records and compare them again in the sole Work. Fields authenticate nothing and cannot reconstruct a bearer or create a new validity lease.

NewAnonymousUpgradeEffect selects only an existing single-factor password target with no organization, factor, passkey or credential continuation. Apply requires the exact registered typed upgrade contributor, real provisional capability consumption and kernel guest disposal. It revokes every guest session/family, then persists one permanent session in a genuinely new family. The permanent target remains separate from guest RecordID; its original source session, credential/owner epochs and historical authentication remain unchanged. Guest remember policy is preserved, not copied from another target preference. Call Check after downstream waits; the original earliest deadline is exclusive and never renewed. The issuer separately controls post-commit credential delivery.

Append AnonymousUpgradeMigrationSource{AnonymousSignin: installedProfile, Version: nextVersion} after both selected anonymous signin and disposal histories. Its installed profile preserves every optional earlier issuance purpose without rewriting predecessor SQL or existing evidence. No older purpose suffix may be installed afterward. Recover reconciles retained revocation AND issuance evidence, even after live session cleanup; mixed evidence remains unknown and no credential is disclosed. Guest/target bearer/CSRF possession, fresh action-specific target reauthentication, risk, retention, merge and actual one-use proof verification/consumption must still be composed by the native anonymous workflow. This component alone exposes no usable upgrade endpoint.

Explicit phone/password and confirmed TOTP

NewMFAPhonePasswordTOTPCompletionEffect selects only the exact verified-phone password primary and independent confirmed TOTP. The real native MFA owner must authenticate the original signed primary/browser, repeat current authority and record TOTP in the same protected Work. The session effect requires its original phone browser purpose and verified-phone recipient; the existing email factory continues rejecting phone recipients. No secondary SMS/recovery fallback or HTTP route is implicit. Install the selected password/MFA session histories and the phone primary/continuation forward suffixes through their actual owners.

Explicit sessionless recovery pre-authentication

PreAuthIssueExecutorConfig.Purpose must match the core issuer's explicit PreAuthPhonePasswordRecovery selection. This uses existing pre-auth storage, issuance evidence, audit/outbox and command recovery, with no session or remember choice. Existing login bytes and installed SQL remain unchanged; older binaries reject the new purpose rather than loading it as login. Apply the existing pre-auth/issuance histories before selection. This is not a phone-reset service: its owner still must consume the original flow and all required proofs with the protected credential mutation.

Only the exact native phone-reset completion can reserve/finalize this original request flow. Its policy ID/version and tenant must remain unchanged, and its credential-scoped command must retain the full coordinator fingerprint and generation. Request issuance cannot consume the flow, and ordinary login/email profiles cannot borrow it. Original cookie, identifier commitment and exclusive expiry are not rewritten; live native proof/factor/risk checks remain mandatory.

The canonical PasswordResetEffect also accepts that exact joint phone-reset command through the registered password owner. It revokes the complete active session set with no preservation choice; its retained receipt remains atomic with the password replacement. Install the session-owned PhonePasswordResetMigrationSource after PasswordResetMigrationSource before selecting phone recovery. The forward suffix preserves existing email-reset rows and history; neither the effect nor its migration authorizes recovery.

PasswordSigninSession restores the same closed session fields from exact username-signin paired custody. It does not turn a username into a verified delivery address or supply the native workflow's current admission. Enabling native username signin also requires its forward issuance-purpose history; installing this structural mapping does not activate a login route. UsernameSigninMigrationSource.Predecessor selects the exact installed purpose history. For a v7 verification predecessor, retain its original MFASignin selection: that constraint has both verification-only and MFA-first variants. The distinct v8 verification-first/MFA successor already includes MFA. No older purpose migration may be installed after this suffix.

Registration verification signin

EmailVerificationSigninEffect and EmailVerificationSigninSession support only the exact identity.email.verification-signin operation. The separately committed confirmation ID is its retained parent, not the new session ID. Install EmailVerificationSigninMigrationSource at an unused permanent version after MagicLinkSigninMigrationSource; set MFASignin only when the MFA issuance predecessor is already installed. Retain that immutable choice/history; do not insert an older purpose migration afterward. The forward extension preserves old rows and enforces one child per tenant/parent. It creates no replay journal. The native password owner supplies actual original-browser, risk and known-empty factor admission. Select the email-grant primary reader and matching revoke profile explicitly; this effect does not enable general magic-link login.

Verification-origin TOTP completion explicitly uses NewMFAVerificationTOTPCompletionEffect with the actual MFA owner, consumed original signup authority and separately committed verification parent. It preserves email-possession provenance rather than manufacturing password proof. For verification-first installations append EmailVerificationMFASigninMigrationSource after the unchanged verification history; do not replay the older MFA issuance migration. Existing MFA-first installations retain their original history. The reference graph requires a permanent explicit lineage selection and composes matching session read/logout.

Disable custody and disposition

PasswordActiveTOTPPrimarySource separately implements PrepareDisable and RestoreDisable for exact original cookie/CSRF/session possession. Original snapshot restore cannot renew freshness or authenticate arbitrary bytes. The MFA owner authenticates its original signed proof and current factor generation.

NewMFADisableSessionEffect admits only identity.mfa.disable / mfa-disable and the canonical factor.removed.v1 transition. It uses the existing bounded 1024-session all-subject disposition, primary/current-authority fences and historical result evidence. Install MFADisableSessionMigrationSource at v3 after v1/v2; no historical SQL or receipt is rewritten. No revoked source or replacement session is made usable by successful mutation or recovery.

Native TOTP completion composition

MFATOTPCompletionEffect composes the real MFA store's recorded completion with session, family and retained issuance writes in the coordinator's single transaction. The native owner must acquire directory, verified-recipient and authorization fences before locking the factor, verify the unchanged opaque code, and call RecordTOTPCompletion before the effect. A late denial rolls back factor replay, continuation completion, session creation and child use. Original primary authentication time and remember policy remain unchanged.

Before factor verification or charging a denial, compare the submitted original cookie against its retained digest and call RequireMFAConsumedPreAuth or RequireMFAConsumedPreAuthAttempt under the exact sealed native owner. These guards lock the already-consumed flow and its committed primary command, matching the original fingerprint and generation. The original action remains exactly magic-link, email-password or username-password signin; none is relabeled as another origin. They neither consume it again nor renew its absolute expiry. The attempt guard runs before the shared budget is charged; the existing coordinator retains wrong-code receipts for retry safety.

Install MFAMigrationSource and MFASigninMigrationSource after their existing magic-link predecessors, the selected MFA continuation/TOTP histories, native preparation histories, and the complete selected capability adapter history. Installing only its first one-use migration is insufficient for original child issuance and supersession fencing.

The transaction composition is integration-tested with real PostgreSQL, signed child issuance and encrypted factors. Browser/policy admission and audit sinks in that test are explicit fixtures. This is not yet a public MFA login service; native public completion, reference session-reader selection and HTTP wiring remain unfinished. Do not enable enrolled MFA from this effect alone.

For issued magic-link/TOTP sessions, NewMFAMagicLinkSessionService composes the primary session, directory, authorization and confirmed-factor readers. Configure MFAMagicLinkSessionServiceConfig with the same deployment, policy namespace and audience used for issuance. The factor reader does not decrypt a secret or consume another code. Missing/revoked enrollment and changed factor generation deny; the original primary time remains the freshness origin. The completed child's expiry is historical, not the issued session's expiry.

This factory has a distinct MFA cache profile. NewMagicLinkSessionService and NewSingleFactorSessionService do not admit its records or cached evidence. Read and copy/promotion paths retain the original earliest-authority deadline; expired evidence plus failed bounded refresh cannot fall back to stale access.

Password/TOTP session reads

NewMFAPasswordSessionService takes the existing SessionServiceConfig with the password credential profile and explicitly selects completed password/TOTP records. It requires the original password credential and exact confirmed factor enrollment to remain active, with current directory and authorization authority. Single-factor records are rejected; NewSessionService still rejects MFA records. Factor reads do not renew the original at-most-20-second authority deadline.

Install PasswordMFAMigrationSource at a new permanent version after MFAMigrationSource in the same session history. It adds schemas11/12 without rewriting older migrations or records. Upgrade readers first. This is a native session-reading API, not the still-unfinished password challenge/login service.

Install MagicLinkSigninMigrationSource at a new permanent version after PasswordSignupMigrationSource, preserving the existing issuance history. MagicLinkSigninSessionFields freezes the complete initial session into the native owner's command before fingerprinting. MagicLinkSigninSession restores that exact anonymous consume profile without selecting a user in command scope.

Configure NewMagicLinkSigninEffect with the trusted primary schema, bounded duration and MagicLinkAdmissionConfig. The exact registered identity.magiclink native owner calls Apply within its consuming Work, after the real capability participant provisionally consumes the original grant. Session/family writes, pre-auth consumption and retained method-specific evidence share that transaction; a later denial rolls them back. Original grant expiry, verified email versions and current account/authorization authority are checked without renewing authentication time.

The native owner must authenticate the original signed grant/issuance, cookie possession and full callback/remember intent, enforce current factor/risk policy, and repeat final temporal admission in CheckFeatureCommit. Propagate every error to abort; disclose no session bearer before reconciled commitment. Recover examines retained evidence even after session payload cleanup but grants no current access or permission to recover a bearer. These public adapter seams are not a complete passwordless workflow or HTTP endpoint.

Install MagicLinkMigrationSource at a new permanent version after CredentialContinuationMigrationSource in the same schema/history. It admits schemas 7/8 without rewriting existing records or earlier SQL/checksums. Upgrade readers and writers before enabling the profile: old readers reject it. Never reinterpret magic-link metadata as OTP or a persistent password.

NewMagicLinkSessionService explicitly selects native magic-link reads using MagicLinkSessionServiceConfig. Configure the exact global authority, user policy namespace, audience and bounded validation/key profile. The borrowed primary pool remains caller-owned. Reads require the original verified email, identifier/verification versions and every current authority dimension; blocking, revocation or a security epoch change denies. Positive evidence expires within 20 seconds of read start and cache copies cannot renew it. This reader does not authenticate a link or implement atomic issuance; native magic-link consumption and selected reference composition remain under development.

All native factories select a closed authentication method and bind their schema, global authority, policy namespace and remaining selected admission configuration into encrypted-cache context. Another method or selected profile cannot borrow a warm positive, even with shared wrapping/lookup keys. Earlier unbound cache entries miss and refresh from primary; stored session records do not change. Distinct physical databases must use distinct explicit encrypted cache issuer/environment/deployment contexts.

Original-signin hash upgrades

PasswordSigninEffect.PrepareHashUpgrade admits the frozen prospective session's directory before reserving exclusive predecessor user/credential locks through the kernel. Call it in the registered password owner's original Apply invocation, before shared recipient/credential or password-material locks. Freeze the kernel-owned predecessor fields and successor-bound signed proof/session into that same original paired command before fingerprinting. Native password comparison, original cookie/risk/policy verification and bounded replacement generation happen before opening Work.

After preparation, the native owner performs material CAS and the kernel's ApplyPasswordHashUpgrade in that Work. ApplyHashUpgrade obtains the actual successor directly from Work and compares the prospective credential reference and independent security epochs before staging the unchanged session/pre-auth effects. Both ApplyHashUpgrade and direct Apply enforce exact original command custody through the kernel before reading the session payload. A reconstructed or substituted command poisons Work, even if its binding and successor epochs match; ignoring that denial cannot commit an earlier upgrade. It accepts no caller-created successor recipient. Original observation and authentication times are not renewed; previous credential-bound sessions are not silently preserved. Propagate every error to coordinator abort.

These are provisional transactional effects, not a credential verifier, token delivery path or separate password-change command. The native owner must use its exact original command and repeat final temporal/risk admission. Recovery keeps its original retained-command semantics without recreating a bearer. Existing original-command non-upgrade behavior, Recover, mapping and migration history remain unchanged. Full native signin hash-upgrade composition is a separate consuming implementation, not provided by this seam alone.

Password-signin session mapping

PasswordSigninSessionFields(record) freezes the complete prospective session into the closed session.result.* vocabulary. Include these fields in the password owner's native command before fingerprinting and reservation, then bind that exact paired command to the prepared password issuer. PasswordSigninSession(command) restores only that paired profile, including the actual selected tenant/user without changing anonymous command scope.

The initial profile supports single-factor password authentication, initial session version one, original remember policy and optional synchronizer state. Organization, factor, passkey, OTP and credential-continuation profiles deny. Missing, unknown, wrongly typed or noncanonical owned fields deny. Returned fields are caller-owned copies; raw password, pre-auth cookie and session bearer are not scalar fields. Other command fields remain the password owner's duty.

This is structural mapping, not proof of successful password comparison, pre-auth possession, current owner state or commitment. The native password owner must compare the selected credential and enforce current policy in the same transaction as pre-auth/risk consumption, signed original authentication, session/family issuance and audit/outbox. That atomic consuming composition is still under development; this mapping alone does not enable login or recovery.

Continued password-session records

Install CredentialContinuationMigrationSource{Schema: "session_store", Version: allocatedVersion} after OTPMigrationSource, using the same migration runner and a permanent version. It validates populated rows transactionally and changes no existing payload, receipt or applied migration. Upgrade all relevant readers and writers before enabling continuation: older binaries reject the new schemas 5/6, while schemas 1–4 retain their original representation.

Durable records and native command mappings preserve the original password authentication independently of EffectiveCredentialVersion(). Current admission uses that effective credential reference and the continued credential-authority epoch; it does not advance user authority or refresh login time, lifetime, remember policy or freshness. Rotation, metadata updates and revoking other sessions preserve this linkage. Neither stored metadata nor reconstruction certifies that a password change committed or substitutes for current owner checks. Fresh credential-proof issuance rejects continuation, including direct scalar commands: an old unused login proof cannot select a newer effective credential version by supplying continuation metadata.

The native session effect below stages selective continuation in the original password transaction. Its consuming public password service is not yet wired. Do not implement this with a separate application transaction or refresh a stale session from current authority.

PasswordChangeSessionFields(original, disposition, maximum) freezes that selection alongside CredentialReplacementFields before command reservation. Choose PasswordChangePreserveSessions, PasswordChangeRevokeOtherSessions, or PasswordChangeRevokeAllSessions explicitly; zero is invalid. The whole-set bound is 1–100000 active-state rows, including stale/expired rows, not a page size. This initial profile admits only single-factor password sources without selected organization, factor or passkey dimensions. Mapping owns its returned fields and preserves historical authentication, effective credential linkage, remember and CSRF custody. It performs no SQL and cannot authorize or complete session effects. The consuming password-service integration is still pending.

Native password-change session effect

Password reset is distinct

NewPasswordResetEffect(sessionConfig) is lent the exact native CredentialResetContributor and its original Work; it accepts no pool or authenticated source session. Install PasswordResetMigrationSource after kernel CredentialResetMigrationSource and the session history. It terminally revokes every active-state row for the tenant/user, including expired and other-method records. The whole-set limit is 100000, with locked keyset pages of 16; overflow aborts all effects. An empty set is valid. No session is preserved or issued. Original effect evidence is retained with command history, separately from disposable session payloads, and Recover reveals no bearer.

The reset owner still must authenticate original issuer custody, current account/identifier/factor authority, risk/HIBP and one-use consumption. Propagate every error to the existing coordinator. This effect is not a public reset endpoint; that complete native workflow remains in development.

Authenticated password change

Install PasswordChangeMigrationSource at a permanently allocated version after the credential-continuation and kernel credential-replacement histories. It adds command-linked retained session evidence without changing prior migration bytes or live records. Retain this evidence with command tombstones; session payload cleanup must not delete it. The existing owner-order index supports the bounded selection; no new coordinator, journal, background worker or index is introduced.

Construct NewPasswordChangeEffect(sessionConfig, passwordAdmissionProfile) at trusted composition. The exact registered password contributor calls effect.Apply(ctx, originalWork, itself, originalCommand) during its native feature invocation, before the kernel advances credential epochs. Its constructor accepts no pool, coordinator or application-written store. The password owner must verify bearer possession, fresh credential-specific reauthentication, HIBP/reuse and one-use proof consumption in this same transaction. Propagate every error so the coordinator aborts; the returned receipt is provisional, not commit evidence.

The effect compares current directory, user, identifier, credential and policy authority, locks the source/family, and selects all active-state rows for the exact tenant/user in bytewise keyset pages of 16. The original whole-set cap includes expired and stale rows; exceeding it rolls back all staged changes. Preservation continues supported current password rows without changing their session version, historical authentication, lifetime, activity, remember, lookup or CSRF state. Stale/expired/family-denied supported rows are revoked, never promoted. Already revoked rows remain unchanged. Preservation of a different credential or optional organization/factor/passkey profile denies until those real owners are composed; revoke-other/all may terminally revoke them without granting authority.

The password owner's RecoverParticipant calls effect.Recover(ctx, originalRecoveryWork, itself) and reconciles that result with its other retained effects. Only the original coordinator can conclude the whole command outcome. Recovery uses original binding, selection, predecessor, source and ordered-result commitments rather than live payloads or present authority. Absent effects support negative recovery only through that coordinator; corrupt evidence or missing infrastructure remains unknown. It neither authenticates current access nor reveals a replacement session or bearer.

Original-session admission mapping

Native feature adapters use OriginalSessionFields(original) to bind the complete original session into their command's source-session.* fields. Select only that namespace and pass it to OriginalSessionFromFields(tenant, user, fields) during execution. Each native feature must exhaustively validate its other fields; this mapper does not validate an entire foreign command. Field order is irrelevant, but missing, duplicate, unknown and noncanonical tagged-union values deny.

Credential and OTP authentication retain distinct complete historical metadata. Remember policy, exact times/versions, lookup commitment, every authority dimension and optional CSRF state round-trip through the existing session-owned codec. Anonymous sessions use a different admission profile and are rejected. Returned slices are owned copies; these correlated projections must not be logged or exposed as transport credentials.

Mapping is not authentication or authorization. Native workflows must prove the separate submitted bearer, compare every current authority under the original coordinator transaction, and call RequireSession with the same frozen record. Do not replace the record with a newer observation, refresh its timestamps or accept its metadata as a reauthentication proof.

Retained sign-in identity

Repository.ReadPasswordSigninIdentity(ctx, originalBinding) provides trusted primary inspection of the original password-signin user/session/family IDs. It validates the complete original binding and password-specific commitment; it does not depend on a live session payload. Anonymous commands retain their original anonymous scope, with the selected user returned separately. Missing evidence returns ErrRecordAbsent; corrupt evidence returns ErrInvalidRecord. The native password workflow must authenticate original cookie possession, authorize historical disclosure and obtain the sole coordinator's outcome before exposing these IDs. Inspection alone cannot authenticate, recover a command, recreate a session or issue credentials. Earlier deadlines win, and errors and implicit formatting/serialization reveal no retained identity.

Repository.ReadOTPSigninIdentity(ctx, originalBinding) reads the original user/session/family tuple from existing retained issuance evidence. It works after live payload cleanup, including anonymous flows whose command user is empty. Every binding field and the original record commitment must match. Missing evidence returns ErrRecordAbsent; corrupt evidence returns ErrInvalidRecord; operational failures are redacted typed identity errors.

This is trusted structural inspection like Get, not a public endpoint or authentication/recovery authority. The native OTP service must first authenticate original possession, authorize historical disclosure and reconcile the original consuming command. The tuple contains no bearer, digest or partial session and cannot enable credential redelivery. Formatting is redacted; implicit JSON/text export is refused. No new schema or recovery journal is introduced.

OTP sign-in command mapping

The native OTP owner includes OTPSigninSessionFields(originalSession) alongside its own closed fields before fingerprinting and reserving the consuming command. OTPSigninSession(command) decodes the session-owned session.result.* fields for the exact record-free v1 identity.otp.signin operation. Unknown, missing, wrong-kind or noncanonical owned scalars deny. Other fields must be exhaustively validated by the OTP owner; this decoder does not validate its entire command.

The mapping retains the selected user independently of an anonymous command's flow scope, exact nanosecond times and uint64 versions, original remember policy, the full authority vector and optional synchronizer digest. It contains no raw code or bearer and grants no authentication, consumption or issuance authority. Existing proof-based issue/revocation command mappings remain unchanged. Public sign-in/recovery is still being implemented; applications must not bridge them with separate transactions or custom stores.

Native consuming OTP session effect

NewOTPSigninEffect(Config{...}, OTPAdmissionConfig{...}) creates the immutable session-owned effect used by the native OTP feature. It performs no IO and owns no pool or coordinator. Install OTPIssueMigrationSource{Schema: "session_store", Version: allocatedVersion} after the existing issuance and OTP record histories before enabling this profile. The forward migration extends the purpose constraint under the migration runner's table lock; old rows and digests remain unchanged. Allocate a permanent version; do not rewrite applied history.

The registered OTP feature must lend its exact consuming Work, original command and original verified recipient to Apply. The OTP owner exhaustively validates Send/pre-auth/remember custody and finalizes those owners in the same transaction. The effect checks the checked consuming scope, original authority, current directory/recipient/authorization, session/family state and database-time expiry after downstream waits. The complete session, family and issuance evidence are provisional until the sole coordinator commits; propagate every error so it aborts. Never register another session command or independently commit a session. Unsupported organization/factor/passkey profiles deny.

Recover accepts only the owning feature's original sealed RecoveryWork. It verifies retained command and selected user/session/family/record commitments even after live session payload deletion. It returns participant evidence only, not a session, bearer, current authentication or disclosure permission. Missing evidence is not a public rollback decision: the coordinator must reconcile all participants. The native public OTP service remains responsible for code-free, currently authorized outcome/session-identity recovery; that composition is not yet available. Applications must not supply that orchestration themselves.

Explicit OTP session authentication

NewOTPSessionService(pool, OTPSessionServiceConfig{...}) selects the owned primary reader for single-factor email/phone OTP sessions. Configure the trusted deployment, authorization namespace and audience through OTPAdmissionConfig; repository and validation budgets/keys retain NewSessionService semantics. Apply directory, user security, identifier, authorization and OTP-capable session migrations first, including OTPMigrationSource after the installed CSRF history. The borrowed primary pool remains caller-owned. Construction performs no IO.

The reader checks the exact original verified identifier and verification versions, active user/directory, all three user security epochs, authorization epoch and session/family state. It reuses the identity owner's bounded identifier and recipient queries, requiring the session's actual user, not an address-only lookup or fabricated password credential. Removing/reassigning the identifier, blocking the user, changing any authority or revoking the session denies use. The 128-identifier limit fails closed on incomplete projections. Database failures never become positive fallback or suppressed successful authentication.

Positive evidence expires within20 seconds of the original read beginning; later owner reads and response delay cannot restart it. Original OTP continuation expiry is historical provenance: it does not expire an already issued live session or renew its authentication time. Organization, MFA and passkey profiles remain explicitly unsupported. The existing factory stays proof-only; selecting the OTP factory does not implicitly enable proof credentials or a combined multi-method deployment profile.

This is authoritative reader composition, not OTP issuance. Public atomic consumption/Signin and code-free recovery of original outcome/session identity remain pending. Applications must not fill those gaps with their own stores or separate transactions.

Use NewCookieRevokeOneExecutor(pool, configuration, eligibleCSRFKeys) with the exact owned primary SessionService. Pass that executor to the existing session.NewSignOutService, then select session.NewCookieSignOutService with the same eligible dedicated keys. Construction performs no IO, copies mutable configuration and accepts no application store or transaction callback. Apply the existing kernel/authorization/session/revocation/audit/outbox histories, including CSRFMigrationSource, before selecting this profile.

The strict executor checks original opaque caller custody and selects only the state-named trusted key. It carries the token in an invocation-private native participant, never a shared request map, context payload or durable command field. The command retains only a strict-profile discriminator and the existing digest-only session projection. Within the original coordinator invocation, ordered source/target write fences precede RequireCSRF, then mutation, audit and lifecycle commit atomically. Failure audits are retained on denied commands; successful revocation/lifecycle effects roll back. Original primary deadlines are not refreshed. Concurrent calls do not share ephemeral token custody.

ExecuteRevokeOneWithCSRF is the explicit strict dispatch. Direct ExecuteRevokeOne on this strict executor always denies. The existing NewRevokeOneExecutor remains available for trusted direct calls and rejects CSRF-bearing requests before reservation rather than silently downgrading them. Historical recovery returns only the original outcome under current access policy; it cannot issue a credential, renew authority or authorize execution.

HTTP must still enforce trusted origin, canonical cookie extraction and one CSRF channel before invoking the strict service. These endpoint/browser boundaries and full release qualification remain unfinished.

Transactional synchronizer-token admission

RequireCSRF composes the core token/key check with RequireSession on the borrowed original primary transaction. It compares the complete frozen record, locks the active session/family until transaction closure, and checks database time after locking. Legacy tokenless state cannot bypass token protection. The helper creates no transaction, validity lease or authorization decision.

Trusted native participants must abort or poison the owner transaction on every error, preserve directory/credential/policy checks, and recheck temporal validity at their existing terminal boundary. Acquire any session write fence before admission; do not upgrade shared locks afterwards. Never call through a replica, cache or autocommit pool. HTTP token-channel/origin checks, pre-auth one-time state and integration into protected native executors remain required separately.

OTP authentication storage

Apply OTPMigrationSource{Schema: "session_store", Version: allocatedVersion} after CSRFMigrationSource, in the same owned migration history, before writing OTP sessions. Upgrade all relevant readers and writers first: older binaries fail closed on the new schema-3 (OTP) and schema-4 (OTP plus CSRF) records. The migration validates populated rows transactionally without rewriting historical schema-1/2 payloads or recovery hashes. It has no destructive down SQL. Constraint replacement takes an exclusive table lock and validates all stored rows. Use the migration runner's bounded context and an appropriate maintenance window for a large installation; local fixture success is not production-scale lock-duration evidence. A failed or canceled migration rolls back both changes.

Durable reconstruction retains the original Send/sign-in, challenge/attempt, identifier/verification versions, authentication time and continuation expiry. It also preserves Remember, the complete authority vector and any synchronizer binding. The continuation expiry is historical, not the session expiry or a renewable authoritative validity lease. Reconstruction cannot authenticate an OTP, manufacture a proof or grant permission. Native OTP session issuance and the opt-in primary authentication reader remain separate implementation work; installing this migration does not enable them.

Synchronizer CSRF storage

Apply CSRFMigrationSource{Schema: "session_store", Version: allocatedVersion} after the base session migration through the existing migrations Runner. It extends the record constraint in place without changing historical migration checksums, tokenless record bytes or retained command identities. Upgrade all relevant readers/writers before opting into native CSRF issuance: old binaries can still handle tokenless schema-1 records but reject CSRF-bearing schema-2 records. Rollback requires disabling new issuance, not dropping state.

Stored records and closed native command projections preserve the separate Session.CSRFState() alongside the original Session.Bindings(). Rotation preserves exact source/successor state; bearer rotation and version-changing metadata invalidation clear it according to the core lifecycle. Retained digest-only history is not current authorization. RequireSession fences and compares the complete active primary record, including this state; it does not validate a browser CSRF token or its Origin. Protected-work token enforcement, OTP custody and HTTP composition remain in development. Do not substitute a cached structural token check for those missing boundaries.

Original-session admission expectations

IdentifierAdmissionConfig.Validate checks the configured owner profile. OriginalSessionAdmission derives exact directory, credential and user authorization expectations from a frozen session and command binding. It preserves original keys and epochs, rejects unsupported optional authority dimensions and performs no IO. It neither authenticates a bearer nor grants permission. Native participants must separately authenticate possession, use primary RequireSession checks, and recheck original freshness after waits.

OriginalDeviceGrantAdmission selects the exact native-device-v1 password profile for client-authenticated token polling. It derives those same original human owner expectations without modifying the client command's actor or anonymous flow. Original credential continuation and authentication times remain unchanged. The native owner must bind and match the complete original source to its locked approved grant, require current directory and session authority and the kernel's RequireOAuthDeviceGrantSource, then check client/consent and every original deadline. The pure mapping does not authenticate the human or client, grant consent/permission, or support other authentication profiles implicitly.

OriginalMFAPasswordSessionAdmission is the explicit password/MFA counterpart. It preserves the password-primary linkage and factor authority scope; it does not turn MFA provenance into a single-factor record. Consumers must additionally fence the original session's factor ID, enrollment and account-wide generation through the actual factor owner, even if a fresh action proof uses another factor. It performs no IO and grants no authentication or mutation permission.

Canonical pre-auth state

An optional original PreAuthIntent.IdentifierBinding commitment is retained in the canonical record and initiation command. Zero preserves existing storage and command bytes; bound flows add one exact 32-byte field. Older binaries reject the extended record instead of dropping its binding. Deploy compatible readers before enabling bound flows, and retain the selected workflow's identifier-key profile for their lifetime. No migration or alternate journal is required. The consuming workflow must compare the original commitment before password work; this adapter preserves custody, not canonicalization or credential authority.

Install PreAuthMigrationSource after the base session schema in the single migration history. It adds a separate canonical private bytea record and digest index, retaining the complete original flow binding and nanosecond UTC timeline. No raw cookie or credential proof is stored. Existing session rows, positional inserts and migration checksums are unchanged.

InsertPreAuth, RequirePreAuth, ReservePreAuth and FinalizePreAuth are bounded native participant operations on the original primary transaction, not public endpoints or a new command engine. The owning platform participant must derive PreAuthUse from its live sealed coordinator handle, fence current policy/scope and abort or poison the unit on every error. Never pass autocommit pools, replicas, client-supplied custody or consumer-written workflow callbacks. The borrowed query/write shape also accepts generation-bound WorkRows.

Admission locks and compares the exact private record, indexed scope/version, cookie commitment and original exclusive expiry; primary time is sampled after locking. Reservation has one winner and binds exact command/fingerprint/ generation. Finalization checks that owner and original deadline again, then consumes in the same transaction as protected session/link effects. Rollback leaves both effects uncommitted. Terminal replay denies; receipt replay belongs to the sole kernel journal, not these operations. No path automatically releases reserved state or renews its validity after timeout, retry or connection loss.

ReadPreAuth restores the exact original record and checks its physical indexes; it does not authenticate a flow or admit expired, reserved or terminal state. RequireReservedPreAuth locks and checks the exact reserved owner for apply. RebindPreAuth changes only the generation from an exact predecessor to its immediate successor, using the coordinator's live sealed takeover invocation. Neither elapsed time nor connection failure authorizes transfer. The original deadline still applies, and rollback restores predecessor ownership. These operations must use the same borrowed primary transaction as other participants.

These native operations do not authenticate a user, expose a cookie or constitute complete usable initiation. Owned issuance/recovery, proven-noncommit reservation coordination and OTP/other workflow registration remain under development. The internal initiation command vocabulary freezes every original record field as closed typed scalars, including nanosecond UTC times and resolved remember policy. It binds the anonymous-flow namespace separately from the service actor and rejects inconsistent command/record scope. Structural decoding does not authenticate the actor, authorize initiation or persist/recover a command.

Compose NewPreAuthIssueExecutor with a borrowed PRIMARY pool, current service authorization, bounded clock/coordinator configuration and one exact trusted action/origin/callback/policy profile. Empty callback explicitly disables redirection. Actor identity is fixed at configuration, not selected by a request. session.PreAuthIssueCommand carries the server-prepared original flow and stable command identity; the adapter alias retains the same storage-neutral value. Never decode it directly from HTTP input or provide a consumer-written store.

Install PreAuthIssueMigrationSource at a later permanent history slot after the kernel and initial pre-auth migration. It creates retained native effect evidence, not another journal; it has no live-flow FK and a permanent per-tenant flow-ID uniqueness fence. Retain that evidence with the original command history. Payload retirement cannot prove rollback or permit ID resurrection. Existing rows and applied migration checksums stay unchanged; no down migration or automatic evidence pruning is provided.

ExecutePreAuthIssue applies current configured service policy before reserving the exact original command. Original flow, native evidence, audit, lifecycle and receipt commit together. Primary locked time rejects expired originals. Exact replay returns historical metadata without reissuing; changed intent conflicts. ExecutePreAuthIssuance runs that same owned path and additionally returns session.PreAuthIssueExecution: only the acquired coordinator reservation clears Replayed. Pending observations, conflict, terminal replay and pre-reservation failure cannot claim original execution. Concurrent identical commands have one newly committed result, even when other callers observe the same historical committed receipt. This metadata contains no cookie and alone is not delivery authority; core issuance must validate the exact receipt, original expiry and error/cancellation before revealing a credential. RecoverPreAuthIssue observes/reconciles complete original anonymous-flow scope under current configured service policy, without a cookie, new reservation or lease renewal. Unknown requires recovery, not a new command. Detached kernel cleanup retains its own bounded budget and may outlive the caller deadline. These native methods do not generate entropy or deliver cookies. Compose them with session.NewPreAuthIssuer to own original ID/nonce/cookie preparation and commit-gated reveal-once delivery metadata. Use matching trusted profile and a dedicated retained flow key; pass the resolved final-session remember choice unchanged. Core cookies stay within original 1..10-minute flow TTL for both choices. Restart recovery returns only exact command outcome, never a credential or caller-reconstructed flow payload. Native OTP continuation registration and complete browser login remain pending. Retain original digest keys and terminal records until the owned retention and recovery policies authorize retirement; no cleanup/down migration is provided.

Install PreAuthReleaseMigrationSource in a later allocated history slot after PreAuthMigrationSource. This forward transactional constraint replacement adds distinct released terminal state, scans existing rows and requires a bounded maintenance window. Existing issued, reserved and consumed rows stay unchanged. Never rewrite the applied initial migration or renumber either history slot.

ReleasePreAuth accepts only the registered owner's live sealed identitypostgres.OTPReleaseWork. The existing coordinator supplies rollback or unanimous primary noncommit authority; neither scalar custody nor timeout does. Release preserves the original record and terminalizes the exact previous reservation, even after original flow expiry. It permits the unchanged rollback generation or coordinator's immediate recovery successor only. It does not reissue/reactivate a flow, reveal a cookie, authenticate a user or register a native OTP workflow. The callback must abort on any error and cannot retain its handle. Receipt replay and ambiguity remain the sole coordinator's responsibility.

Owned self-session device labels

Install UpdateMigrationSource{Schema: "session_store", Version: allocatedSlot} after the existing kernel/session migrations, through the single migration runner. This additive install creates separate metadata/evidence tables; existing positional session inserts and the closed session codec stay unchanged. Listing also requires this migration. The transactional install needs an explicit deployment window; never renumber an applied migration.

Compose NewUpdateExecutor(pool, UpdateExecutorConfig{Execution: nativeConfig, Sessions: authenticatingReader}) with session.NewSessionUpdater. The exact reader must have authenticated the original cookie/bearer. Prepare selects that session's exact current version and a label of at most128 UTF-8 bytes without control runes; empty clears it. A label is untrusted display text, not device trust, a credential, a factor or authorization. Escape it at rendering.

Native execution checks current policy and every supported primary owner, locks the source, and commits label plus session/vector version, audit, lifecycle and receipt in the existing kernel transaction. It preserves bearer, activity, authentication, remember choice and all other authority. Exact retry observes the historical successor without applying again; changed intent conflicts. Original admission's exclusive deadline bounds the entire mutation. Errors never return apparent successful display metadata; commit ambiguity requires recovery rather than guessing rollback or issuing a different command.

RecoverUpdate retains original request custody; RecoverUpdateCommand supports process restart with the complete safe original scope and a trusted current caller. Both observe historical outcomes under current access policy, never return a label/session, renew authentication, mutate metadata or reserve missing commands. Terminal evidence survives payload deletion and retains only the label digest; current label plaintext cascades with session deletion. Retained session records share the existing command-evidence retention policy; they are not a current authorization source or a second journal. General privacy retention/anonymization and remaining session profiles are still pending.

Pool, reader, authorization and clock dependencies are borrowed, immutable and must remain alive until calls finish. Use PRIMARY only. Calls are concurrency safe, use bounded contexts and start no goroutines; detached kernel cleanup retains its documented independent bounded budget. HTTP routing, origin/CSRF policy and request key parsing belong to the explicit HTTP composition.

Owned source-bound rotation

Compose NewRotationExecutor(pool, RotationExecutorConfig{Execution: nativeConfig, Sessions: authenticatingReader}) with the core session.NewSessionRotator. The reader must be the exact trusted service that authenticated the original cookie/bearer. Core preparation privately generates the successor; native execution compares current primary owners, locks the original source and commits its one-version successor, old-digest retirement, required audit/lifecycle and command receipt together. The absolute caller deadline also bounds commit. Rotation preserves original issuance/authentication/remember policy, family and every non-session authority. It cannot repair or renew a stale authority vector.

Install RotationMigrationSource{Schema: schema, Version: permanentVersion} after the existing base/issuance/revocation history, through the sole migration runner. Its transaction takes a session-table write lock, backfills one token claim per populated session and installs invoker-only writer guards. Budget the complete populated installation in a reviewed maintenance window; this is not an online chunked backfill. Existing session payloads and older checksums remain unchanged. Guards prevent digest reassignment and irreversible retired-digest resurrection even through older binaries/direct writers. Deleting a payload also terminally retires its digest. Runtime writer roles must not have TRUNCATE, trigger-disable or schema-alter privileges; these guards are not a security boundary against a privileged database owner. No destructive downgrade or retirement/evidence deletion is supported. Terminal claims and retained rotation metadata outlive prunable live payloads; privacy retention obligations remain part of the unfinished full lifecycle implementation.

ExecuteRotation accepts only the original opaque request. MapRotationRequest is an exact structural projection, not substitute authentication; raw MapCommand/Apply rotation remains forbidden because it lacks that admission. RecoverRotation uses current result-access policy and exact retained complete intent, including original deadline and transport. It works without a live old session/admission, never reserves a missing command or replays effects, and returns historical receipt/session metadata only. Corrupt or missing ancillary evidence fails closed without erasing known commitment. Core replay/recovery never deliver a token/cookie; only a new error-free commit can reveal once.

After process restart, RecoverRotationCommand(ctx, exactRecoveryQuery, trustedCurrentCaller) returns the exact historical command/version/audit receipt without the original request, admission, reader instance or bearer. Reconstruct the public reader/executor configuration; do not manufacture a new rotation request. Supply every original safe query scope field and an independently authenticated current caller. Current policy governs disclosure. Missing/denied queries return no history and never reserve a command. Live pending does not renew its lease; expired pending reconciles through the sole kernel owner and frozen participants. Missing/conflicting evidence cannot prove rollback. Pruning live payloads does not erase committed receipts. No session, credential, current authority or permission to retry is returned.

Retired-token denial and explicitly composed family-replay revocation are implemented. Selected organization/factor/passkey profiles, complete cleanup/privacy handling and whole-unit release gates remain unfinished; ordinary rotation is not a claim of full session lifecycle parity.

Protective retired-token replay checking

Explicitly compose NewFamilyReplayGuard(pool, FamilyReplayGuardConfig{Execution: nativeConfig, LookupKeys: retainedValidationKeys, ActorID: trustedServiceActor}). Use the same one to four retained HMAC keys as the primary reader and a configured service-account actor whose current policy permits protective family revocation. Install the existing family, rotation, kernel, audit and lifecycle migrations; the guard adds no tables or journal. Configuration borrows the primary pool and policy dependencies and starts no goroutines.

CheckReplay(ctx, FamilyReplayInput{TenantID: tenant, Token: parsedToken, CommandID: stableID, CorrelationID: correlation}) derives the owner and family only from exact primary retired-token lineage. The caller cannot choose them. It authenticates nobody: the operation is a denial-only protective mutation. Current service policy, original absolute expiry, locked family-version CAS, protected service audit and lifecycle effects govern the sole transaction. Concurrent distinct commands have one winner; exact retries preserve the original receipt and changed intent cannot borrow a previous success. Blocking the human owner does not disable this protective action. All retained keys, input tokens and guard configuration deny JSON export and diagnostic traversal.

A zero result with nil error means no eligible replay was observed. Active, absent, foreign-tenant and absolutely expired tokens reserve no command. This does not authenticate a token or prove that an earlier command rolled back. Original idle expiry is not the retention cutoff: rotation extends idle activity while preserving absolute lifetime. Application-clock/policy latency cannot extend the primary expiry or final commit budget.

Keep the returned safe binding whenever the outcome is uncertain. After restart or absolute token expiry, RecoverReplayCommand(ctx, exactRecoveryQuery, trustedCurrentServiceCaller) returns only historical command/version/audit metadata under current access policy, without needing the token. Live pending does not renew its lease; expired pending uses existing participant recovery. Missing or inconsistent evidence remains uncertain and never authorizes retry.

Ordinary SessionService.Get remains read-only and still denies retired tokens. The explicitly enabled transport owner must invoke this guard on presented credentials and enforce origin/CSRF and source/transport policy before mutation. This is not automatic HTTP wiring, an authentication endpoint or a new authority cache; these transport/composition requirements remain separate platform work.

Bounded expiry cleanup

Install CleanupMigrationSource{Schema: schema, Version: permanentVersion} after the complete base/rotation history. It adds an owner/expiry index and retained result evidence without changing populated records or earlier checksums. The transactional index build can block writes; budget its installation explicitly. Do not give runtime roles trigger-disable, schema-alter or TRUNCATE privileges. The existing rotation deletion trigger is required to terminally retire digests.

NewCleanupService(pool, CleanupServiceConfig{Execution: nativeConfig, ActorID: trustedServiceActor, MaximumBatch: batchLimit}) enables maintenance under the configured current service policy. MaximumBatch is 1..10000; the service borrows the existing primary/kernel/audit/lifecycle dependencies and starts no goroutine. Default repositories/readers expose no cleanup operation.

Call CleanupExpired(ctx, CleanupCommand{TenantID: tenant, UserID: owner, CommandID: stableID, CorrelationID: correlation, Limit: limit}) for an explicit owner partition. Current policy must permit that configured service actor to maintain the selected owner; input cannot select the actor or clock. A limit above the configured maximum or any invalid scope fails before reservation. This is maintenance, not an authentication endpoint or a global scheduler. Reference-server scheduling and broader privacy erasure remain separate work.

One existing-kernel transaction selects at most Limit indexed expired candidates using database time, locks and rechecks their current expiry, skips busy rows, and prunes live payloads with terminal digest retirement. It does not scan past locked candidates to fill a deletion quota. A concurrent refresh survives; other tenants/users and active payloads are untouched. Natural expiry does not increment session/family/user authority. Retained issuance, rotation, revocation, proof-use and command records are never removed by this operation.

The same transaction records historical count/lag evidence, service audit identity.session.expire with reason completed, and session.expired.v1 maintenance lifecycle metadata. The record-free receipt has zero before/after versions: it is not a new session authority. Audit failure rolls back deletion, tombstone changes and all effects. A zero-row pass is a committed observation, not proof that no locked or subsequently expired rows exist.

CleanupResult includes the command outcome and, only after verified success, Deleted, ObservedAt and RemainingLag for that partition. Lag includes locked expired rows, saturates at 8760 hours, and describes the database-time observation—not the live backlog at the time a caller reads a historical result. Exact retries return the original count/lag without deleting another batch; changed scope/correlation/limit under the same ID conflicts. New batches need new IDs. Retain safe command scope for RecoverCleanupCommand after restart or uncertain acknowledgement. Current trusted service access policy governs disclosure; live leases are not renewed and expired pending uses existing frozen-participant recovery. Missing/corrupt evidence never proves rollback or authorizes retry. An ancillary evidence error preserves known commitment but returns no invented counts or timestamps.

Owned session listing

NewListService(pool, ListServiceConfig{Sessions: primaryConfig, Listing: session.ListConfig{Authorization: policy, PolicyRevision: revision, MaximumDuration: budget}}) composes the real primary authentication reader, existing authorization service and one bounded joined page query. No application domain store is required. Its explicit repository budget cannot exceed the whole listing budget. Native authentication retains its single-factor profile; unsupported authority dimensions deny rather than being ignored.

Apply ListMigrationSource{Schema: schema, Version: permanentVersion} after the base session migration in the sole composition history. The new tenant/user/audience/session index supports bytewise exclusive keyset traversal. Its transactional build can block writes: size and schedule populated installs explicitly. It neither rewrites records nor changes historical SQL/checksums.

Pass tenant, actual cookie/bearer credential, safe correlation, Limit 1..100 and optional cursor/IncludeInactive to List. Current user/audience scope is derived from authentication, not request identifiers. The primary reader scans at most Limit+1 raw rows in one statement; the service returns at most Limit safe device projections. Filtering can yield an empty page with a continuation. Labels remain empty until the owned metadata writer is implemented. Revoked family/session and exact expiry metadata are not live authentication authority. Cancellation, corrupt records, current-policy denial and primary outage return no partial page or stale fallback. The pool is borrowed until calls finish.

Owned self-logout

NewSignOutService(pool, SignOutServiceConfig{Execution: execution, Validation: validation, Cookie: cookie, MaximumDuration: budget}) composes the primary reader, native executor and core service without application stores. Set validation.Clock to nil: execution.Clock owns both phases. Its schema, authority profile and policy are shared; existing validation key/audience and read-budget rules still apply. Install the selected kernel, authorization, session/issuance, revocation, audit and outbox migrations before calls. Final signin proof issuance is not a mandatory dependency of ordinary logout.

Pass a canonical host-generated command ID, correlation, tenant and explicit cookie/bearer transport to SignOut; the credential may be absent. Successful cookie results provide secure deletion metadata, not another token. Never clear transport state on an error or unknown outcome. Retain the returned recovery scope and use RevokeOneExecutor.RecoverRevokeOneCommand with current result access policy before attempting a replacement for an ambiguous command. The native executor can be reconstructed with the same pool/execution profile and an owned NewSessionService reader; historical recovery never requires the revoked credential or its expired private admission. The HTTP owner must still enforce canonical parsing, mixed-source rejection and origin/CSRF policy. Full session lifecycle and release verification remain pending.

Experimental Go 1.27 durable adapter. Forward-only migrations and bounded primary Get/digest Lookup reads preserve complete native session records, resolved lifetime limits, original nanosecond timelines, full uint64 authority versions and revocation tombstones. Native family revocation now participates in the sole identity PostgreSQL coordinator. Explicitly configured native authenticated issuance now checks current owners and atomically stages records and original proof use. Owned authenticated cookie issuance now composes real audit/outbox effects with the core's commit-gated token custody. General bearer issuance, browser-container policy, privacy cleanup, devices and complete session profiles remain unfinished. Single-factor stateful opaque validation now has owned primary composition; this is not yet a complete login service.

Bulk native revocation

The configured NewRepositoryWithIssueAdmission contributor registers revoke-other and revoke-all. Install RevokeSetMigrationSource{Schema: schema, Version: permanentVersion} after the base history, alongside the kernel, issuance and selected audit/outbox migrations. This forward migration retains command result counts and adds an active-owner selection index. Existing records and historical checksums are unchanged; the transactional index build can block writes and requires explicit populated-deployment scheduling.

NewSetRevocationService(pool, SetRevocationServiceConfig{Execution: execution, Validation: validation, MaximumSessions: maximum, MaximumDuration: budget}) composes credential authentication, current policy and native atomic mutation. Set validation.Clock to nil: execution.Clock owns both phases. It starts no goroutines and accepts no application domain stores or transaction callbacks. Use RevokeOther/RevokeAll with actual tenant-bound cookie/bearer credentials, host command/correlation IDs and, for all, explicit source disposition and exact positive user-authority CAS. Final-signin issuance is not a bootstrap dependency.

MapRevokeSetRequest structurally maps an original opaque core request; it does not authenticate or authorize execution. Raw MapCommand cannot supply the source-admission deadline. NewRevokeSetExecutor accepts the exact trusted reader that prepared requests and the same execution profile. Native deadline conversion uses primary time and cannot extend admission during audit/outbox persistence. Do not substitute an application transaction or caller-ID workflow.

RecoverRevokeSetCommand on a reconstructed executor takes the exact original safe recovery scope plus currently trusted result-access policy context. It returns historical command metadata and retained count/version/disposition, never a bearer or permission to execute. Missing/foreign scope cannot reserve a command. Missing/corrupt retained metadata produces an error and zero success metadata, preserving a command commitment already proven by the journal. Payload pruning does not remove native evidence. Recover the original command rather than minting another ID after an unknown outcome or failed disclosure.

The native effect selects all active-state sessions for the authenticated user within the tenant, across audiences, in bounded bytewise keyset chunks. The configured maximum counts target rows, not pages: an excess row denies the entire mutation rather than truncating it. Expired/family-denied active-state records are also tombstoned. Corrupt records or current-owner denial abort the complete set. The kernel's existing tenant transaction mutex serializes owned issuance and mutation; there is no second lock or invalidation authority.

Revoke-other always preserves the source. Revoke-all has explicit source disposition. A preserved source retains bearer, lifetime, authentication and user authority, advancing only its session/snapshot version. Included sources and targets retain their original immutable payload behind terminal tombstones. Required audit, lifecycle and retained count/disposition evidence share the coordinator's sole transaction and rollback. Original admission remains bounded by the earlier freshness/expiry deadline; native checks cannot renew it. Retained scoped recovery evidence survives session payload cleanup, but corrupt or conflicting evidence never proves success or authorizes a new mutation.

Single-session native revocation

The explicitly configured NewRepositoryWithIssueAdmission contributor also supports the closed session.NewRevokeOneCommand variant. Install the additive RevokeOneMigrationSource at a permanent version after the family history, merging it with issuance and kernel migrations in the existing single history. It does not rewrite historical SQL or populated session records.

Mapping retains the complete original record, policy and authority vector. The sole coordinator checks the exact registered invocation; the adapter locks current directory, credential, authorization, target and family state before mutating only the target. The physical record/version remains its original snapshot; session_revocations retains the terminal version successor and command binding independently of payload cleanup. Audit and lifecycle effects share that transaction. Missing infrastructure and ambiguous/corrupt recovery evidence never prove noncommit or authorize another transition.

This currently supports active single-factor self-service targets with the configured owner profile, not anonymous/factor/passkey or administrative variants. Construction and structural mapping do not authenticate a caller: the owned execution service supplies opaque current caller admission and policy before reservation. Public idempotent signout and revoked or expired-target management remain required work. No bearer is issued here.

NewRevokeOneExecutor(pool, RevokeOneExecutorConfig{Execution: ..., Sessions: reader}) owns the kernel/native/audit/outbox composition. reader is the exact trusted service that returned the positive caller result. The existing execution configuration supplies deployment profile, bounded clock, policy revisions and coordinator keys; final-signin proof composition is not required for revocation. Use reader.PrepareRevokeOne(caller, command) and pass that original opaque request to ExecuteRevokeOne. Structural MapRevokeOneRequest is not admission.

The mapped intent retains both complete caller and target records and the unchanged original deadline. The executor checks original custody/current policy before reservation, locks current source/target owners on the primary, orders both session locks deterministically, and checks original admission before commit. The transaction/commit budget cannot outlive the remaining original validity. Primary database time caps a monotonic deadline anchored before the clock query, so application-clock skew and slow audit/outbox work cannot extend that validity. Copies and retries do not restart that window. Exact replay returns the original retained receipt without another mutation or effect. RecoverRevokeOneCommand observes historical scoped metadata under current result-access policy, including after reconstructed executor composition; it does not reconstruct a bearer, authenticate the caller or authorize execution. Absent, expired and already-revoked public logout semantics remain unfinished.

Owned stateful authentication

NewSessionService(pool, SessionServiceConfig{Repository: ..., Profile: ..., Validation: ...}) returns the core service with the owned primary reader. Select session.StorageStatefulOpaque, audience, retained digest keys, trusted clock and explicit bounded read/clock budgets. The profile is the same trusted single-factor deployment/method/credential-owner profile as native admission. Repository's budget cannot exceed validation's. Construction has no IO.

Get performs exact tenant/digest lookup across at most four retained key versions and denies ambiguity. It checks live session/family tombstones, exact owner-derived scope keys, directory status/epochs, user security and identifier epochs, exact credential ID/kind/owner/version/expiry and current authorization epoch through public owner APIs. It never substitutes aggregate CAS versions, original authentication metadata or a stored record for current authority. Identifier projection uses its owner's finite 128-record bound; incomplete or corrupt owner state denies rather than becoming a partial positive result.

The earliest read-start sample precedes token lookup. Evidence lasts at most 20 seconds from that sample, capped by credential and session expiry and the core uncertainty deduction. Copies and delayed responses do not renew it. Missing infrastructure fails closed; there is no stale cache fallback. Authentication does not grant authorization, update activity, refresh a token, consume a proof or perform any durable mutation. Reuse requires the core result's private-custody ValidateAt with trusted current time.

Apply kernel directory/status/identifier/credential, authorization-authority and session migrations first; this constructor does not bootstrap them. Borrow the primary pool until all calls finish. The service starts no goroutines and supports concurrent calls. Organization, factor, passkey and anonymous profiles explicitly deny until their separate owners compose. Browser credential extraction, CSRF and container policy remain HTTP/core responsibilities. Automatic transport replay-guard wiring, remaining profiles and release gates remain pending.

Adoption and API

NewRepository(pool, Config{Schema: "identity_session", MaximumDuration: time.Second}) accepts the caller-owned go-postgres PRIMARY pool. It performs no IO. Apply migrations first and close the pool only after all calls finish.

MigrationSource{Schema: "identity_session", Version: 10} returns one atomic, forward-only install. The version is an example: the platform composition owns its permanent allocation in the single go-migrations history. Compose this source with the installed kernel history and run the owned migrations Runner and PostgreSQL backend. The kernel's identity.users table is a prerequisite. Never use independent competing ledgers, renumber applied versions or silently adopt an occupied schema. public, identity, information_schema, pg_* and noncanonical schema names are rejected. There is no destructive down SQL.

To enable native revocation, use RevocationMigrationSource{Base: MigrationSource{Schema: "identity_session", Version: 10}, Version: 11} with an additional permanent version greater than the base in the same history. This forward-only migration adds retained mutation bindings without changing the original session install or live records. The original two-field MigrationSource remains unchanged and returns only the read-only install. Register the repository alongside the owned kernel, audit and outbox contributors. Its descriptor is identity.session.store version 1 and it declares identity.session.revoke-family; the default constructor does not register issuance.

Protected native issuance

NewRepositoryWithIssueAdmission(pool, config, IssueAdmissionConfig{...}) freezes a trusted single-factor self-service profile: deployment authority, authorization namespace, audience, authentication method and credential kind/owner. Configure the coordinator's trusted final-authentication authority and namespace separately. Neither profile comes from request input. Organization, factor and passkey profiles deny until their native owners are composed; no applicable authority is dropped from the original record.

Compose IssueMigrationSource{Base: RevocationMigrationSource{...}, Version: ...} with kernel proof-use, directory, status/credential and authorization-authority migrations in one ordered permanent history. Issuance evidence survives session payload cleanup and cannot be silently pruned during command reconciliation.

Map the closed session.SessionCommand with MapCommand, then use the coordinator's PrepareAuthenticatedCommandPlan/ReserveAuthenticatedCommand with the same original opaque final-authentication proof. Ordinary reservation rejects issuance even when its structural command is valid. The adapter compares every original proof field and complete snapshot, locks current native owners, preserves original family issuance time and denies absent/stale/revoked families. A genuinely new family requires version1; concurrent uniqueness waits cannot overwrite a retained family or reset its authority. The same Work persists family, session, proof use, native issuance evidence, audit and lifecycle. Final comparison includes the complete stored session and primary expiry.

No raw bearer is generated, stored or returned by these adapter methods. Replay returns retained command metadata, not another credential. This native path is a prerequisite for the core issuer's reveal-once bearer custody and container policy, not a replacement for that unfinished service. Integration checks use the production session repository and real PostgreSQL; test-owned audit/outbox contributors prove transaction atomicity, not complete production delivery composition. Full coverage, mutation and release gates remain pending.

NewIssueExecutor(pool, IssueExecutorConfig{...}) owns composition of the native repository, kernel coordinator and production audit/outbox contributors. Supply the primary pool, Repository configuration, trusted Profile, retained Coordinator keys/final-authentication namespace, existing Authorization service, trusted Clock, PolicyID, positive PolicyVersion and AuditRetentionVersion. Execution work uses the coordinator's 1ms..30s maximum duration or any earlier caller deadline. Synchronous detached kernel cleanup may outlive that deadline; each cleanup phase has its own bounded coordinator budget, rather than one whole-call return deadline. Dependencies are borrowed, immutable and concurrency-safe; construction performs no IO and never runs migrations. Apply the kernel proof-use, directory/status/credential, authorization-authority, native session/issuance, audit and generic/identity outbox migrations first. Missing storage fails closed.

Pass this executor to session.NewSessionIssuer with the same trusted authenticator, independent session digest key, explicit cookie policy, token size and duration. The core generates and privately retains the original token in Prepare; the adapter receives only its opaque IssueRequest and exact digest-bound native record. Applications supply neither stores, transactions, registries nor workflow orchestration. Current self-service identity and policy are derived from the original authenticated command, not request-selected decision attributes. Issuance currently supports the configured single-factor profile; organization, factor, passkey and anonymous variants remain unavailable.

The executor checks current access before reservation. The native participant checks all selected authority dimensions under the protected transaction before effects and again before commit. Session, family, proof consumption, retained issuance evidence, audit and lifecycle notification commit together. Core delivery reveals the token only after a new exact committed result; cookie attributes have an empty value until an explicitly authorized transport combines them with that token. ExecuteIssue historical replay and RecoverIssue never deliver credentials. Recovery compares complete original input and current access, uses only the existing primary journal/recovery owner and cannot reserve missing input, renew live leases or refresh original proof authority.

Retain the original safe request/proof for exact-input recovery and fingerprint keys/policy versions while an outcome may require reconciliation. Never prepare a new token to retry an uncertain command. After a process restart, RecoverIssueCommand(ctx, exactRecoveryQuery, trustedCurrentCaller) returns historical command metadata without original proof or token custody. Supply all original safe scope fields and the independently authenticated current caller, not request-selected actor/tenant overrides. Current policy governs disclosure. Missing/denied commands are indistinguishable; recovery never reserves them. Live pending remains observational; expired pending uses the kernel's frozen participant reconciliation, and missing/conflicting evidence remains unresolved. Successful reconciliation does not return a session or any bearer/cookie and does not authorize retrying issuance. Structural historical sessions are not current authentication evidence. Browser maximum session/container policy, automatic transport replay-guard wiring and complete login composition remain required future work. Real PostgreSQL integration covers the owned executor and production audit/outbox path, unlike the contributor-only transaction fixture above. Full release coverage/mutation gates remain pending.

MapCommand(session.NewRevokeFamilyCommand(...)) maps the closed native command's complete expected-version intent. Prepare a native feature plan with subject session_family, security action identity.session.revoke, lifecycle session_family.revoked.v1, exact expected/successor versions and selected standard (or privileged protected) retention. The coordinator checks registry, budgets, digests and the native owner's mandatory declarations before reserving. Only its ApplyFeature invokes the registered repository. Direct Apply on a borrowed, foreign or returned Work fails; the constructor accepts no coordinator, transaction or registry. Authorization belongs to the owning service, before reservation. This trusted adapter is not a public revocation endpoint.

Revocation changes exactly one owned active family's tombstone and version, never its sessions' original snapshots. Missing, stale, already-revoked and foreign-owner targets return redacted conflict without disclosing foreign existence. Exact same-command replay is handled before mutation by the sole coordinator. Required audit/lifecycle effects and retained mutation evidence commit with the transition. Errors require coordinator Abort; a failed commit stays Unknown until primary recovery proves its original result. Recovery reads retained exact command bindings, never infers success from current family state. No adapter cleanup prunes those bindings; their journal FK prevents premature command retirement. Retention/privacy retirement remains a later owned policy boundary, not permission to treat pruned evidence as noncommit.

Get(ctx, tenant, sessionID) and Lookup(ctx, tenant, session.TokenDigest) return a structural StoredSession. Both use one joined primary query and a finite read budget. Earlier deadlines win; cancellation, deadline, absence and unavailability are redacted. No SQL diagnostic or partial record escapes.

RequireSession(ctx, work, Config{Schema: "identity_session", MaximumDuration: time.Second}, frozenSession) borrows the owning transaction's query cursor (identitypostgres.Work or a trusted primary pgx.Tx). Freeze the exact original session in the owning command before reservation. The native query compares physical indexes, complete stored snapshot, authentication linkage and lifetime without replacing any field. It requires active session/family state and exact versions, takes share locks on both, and checks database time after acquiring those locks. Earlier caller/Work deadlines win; rows close before return and locks remain until the original coordinator commits or aborts.

This is only session-owned admission, not full session authentication. Native participants must still check current global/tenant/user/identifier/credential, authorization and every applicable organization/factor/passkey authority, plus authentic proof and final temporal validity. Passing a pool/autocommit queryer cannot prove protected admission. The owning native participant must fence scope/lifetime and poison/abort Work on every failure, including ignored denial. No bearer, authority lease, policy decision, refresh or new session is returned. Missing/revoked/expired/unequal rows deny uniformly with identity.ForbiddenError; invalid inputs and storage/corrupt rows retain redacted typed classifications.

Native password-signin session effects

NewPasswordSigninEffect(Config, IdentifierAdmissionConfig) freezes the bounded single-factor password admission profile without IO. Install PasswordSigninMigrationSource after OTPIssueMigrationSource, using a permanent unused migration version in the existing single history. The forward constraint extension preserves populated session and retained issuance records.

The registered identity/password/postgres participant calls Apply only in its original coordinator Work, with the original paired password/pre-auth command, selected verified recipient and pre-auth snapshot. It must first verify actual password and cookie possession, authentic proof provenance, complete request intent and risk/policy admission. Structural session mapping is not authentication. The effect fences current directory, selected credential and authorization without retargeting anonymous command scope; it stages pre-auth consumption, family/session and retained issuance in that same Work. Original expiry is checked after waits. Every error must reach coordinator Abort; provisional success must not disclose a bearer before a known original commit.

Recover runs only during that participant's sealed recovery invocation. It checks retained original issuance commitments, including after session payload cleanup, but returns neither a credential nor current access authority. The coordinator reconciles all participants. This seam does not implement password comparison, public login orchestration or an HTTP endpoint.

Native password-signup session effects

PasswordSignupSessionFields and PasswordSignupSession preserve the complete original single-factor session, including remember policy and CSRF, in the closed paired signup command. Signin and ordinary metadata cannot substitute for signup custody. Mapping grants no authentication or signup policy decision.

NewPasswordSignupEffect borrows registration's exact native participant and sole coordinator Work. After the kernel registration domain has staged the new user, pending identifier and password reference, Apply matches their retained original-command binding and checks actual current directory, recipient/credential and selected-user authorization. The authorization owner must explicitly bootstrap the new subject in that same transaction; missing authority denies. Anonymous command scope remains unchanged. Session, family, issuance evidence and original pre-auth consumption commit or roll back together.

Install the kernel's credential and identifier-retirement histories, then its PasswordRegistrationMigrationSource. Install PasswordSignupMigrationSource after the session password-signin history, at an unused permanent version. Existing populated records and prior migration checksums remain unchanged.

The native password owner remains responsible for HIBP/hash/risk admission, password material, original cookie possession, field policy and authentic proof provenance. It must decide that verification and MFA are not required before selecting full-session issuance. Every effect error must abort the original Work; provisional success cannot reveal credentials. Repeat temporal admission after later owner/coordinator phases. This seam is not a public signup service.

Recover inspects the signup-specific retained commitment only during the participant's recovery invocation. ReadPasswordSignupIdentity provides bounded primary inspection of original user/session/family IDs, even after payload cleanup. Neither grants access, restores a bearer, authorizes disclosure or proves the whole command outcome. Signin/OTP commitments cannot satisfy signup.

Security and tradeoffs

  • These are trusted storage APIs, not unauthenticated public endpoints.
  • A found record is not authentication, authorization or current-validity evidence. Deny revoked records/families and compare every applicable current authority before accepting a credential. Neither timestamp nor construction proves a source read or renews the original freshness bound.
  • The returned native session retains its original family version. The current family's version/status are separate facts; they never replace the snapshot.
  • Only tenant/version-bound digests are indexed. Raw bearer tokens and opaque authenticated proofs are never stored or reconstructed. All returned digest bytes are compared in constant work; database lookup is not constant latency.
  • Schema-versioned bounded JSONB stores one complete explicit native projection. Missing, null, unknown and malformed fields fail closed on reconstruction. JSON numbers are decoded directly into integers, never through float64.
  • UTC, fixed-width nanosecond text preserves exact timeline precision and bytewise expiry ordering. Standard PostgreSQL timestamptz would round these native timestamps. Expiry indexes are preparation, not an implemented cleanup.
  • Protect database access, backups and retention: non-bearer authentication metadata and authority scope keys still correlate users. Do not log records, digests, query arguments or driver diagnostics.
  • PostgreSQL uniqueness/FKs enforce exact tenant/session/digest and parent relationships. Cross-tenant absence does not disclose a foreign record.

Operations, verification and FAQ

Use the integration build tag and an explicit task-owned loopback IDENTITY_SESSION_POSTGRES_TEST_DSN for tests. Missing selected infrastructure fails, never skips. Unit and fuzz tests cover reconstruction; integration tests use the real owned migration runner and PostgreSQL. Their parent-table fixture does not replace eventual full-kernel/reference composition evidence. Native revocation tests additionally compose the actual full kernel migrations, populated session upgrade and real contributor/coordinator. Audit/outbox SQL seams prove atomic rollback and visibility, not production adapter interoperability.

Can this adapter issue or authenticate sessions? The configured owned issuer and primary reader support the documented single-factor profile. Raw repository reads reconstruct structural data only. Final proof consumption and effects use the sole identity PostgreSQL coordinator, never a private issuance transaction.

Can a revoked session become active on reload? No: retained record and family tombstones are returned explicitly. Reading them never alters state or authority.

Can a deployment change remember-me defaults for existing sessions? No: reconstruction retains all resolved durations and rejects values needing new defaults or clamping.

See CHANGELOG.md. Complete mutation, coverage, API/catalog, clean-consumer, kernel/reference composition and release gates remain pending.

Native privacy eligibility

NewRepositoryWithPrivacyExportAdmission(pool, config, profile) explicitly opts the same store into identitypostgres.PrivacyExportAdmissionContributor. Use trusted deployment, policy namespace, audience and method/kind/owner fields as for identifier eligibility below. Existing constructors remain opted out of privacy; this constructor does not enable identifier admission.

CheckPrivacyExport reads only the exact selected live invocation. It derives all applicable primary owner keys from the original session and compares the request's expected user security authority version, not the identifier or aggregate identity version. Initial and final checks keep the same original session, credential linkage and authority versions; privacy allocation cannot refresh them. Directory, user/credential and authorization checks precede the complete session/family share locks and primary-time expiry check. There is no pool fallback, independent transaction, write, bearer issuance or policy engine.

The current native profile denies organization, factor and passkey applicability rather than omit their owners. Complete multi-owner platform support is still required. Eligibility alone is not fresh reauthentication, one-time proof consumption or queued export admission. Public privacy execution remains closed until native proof, all contributor cuts, effects and recovery are composed.

Native identifier eligibility

NewRepositoryWithIdentifierAdmission explicitly enables the same repository as identitypostgres.IdentifierAdmissionContributor. Existing NewRepository remains opted out. Register the same instance for the store descriptor and the plan's separate read-only role; do not register a second duplicate store owner. The constructor accepts only the primary pool, existing schema/read budget and trusted deployment/authorization/audience/credential profile, never Work, coordinator, registry, callbacks or an application-written domain store.

Repository.CheckIdentifier can run only under the selected live coordinator invocation. It reads the exact command-bound session ID/version, checks every required scope key, then uses the existing global/tenant, user/credential and authorization owners before locking and rechecking the exact session/family record and primary-clock expiry. Owner locks remain until the original Work closes. Session projection reads acquire no locks before those owners; the complete post-lock comparison rejects intervening changes. No replica, autocommit fallback, independent transaction or network callback is used.

Initial comparison uses the original snapshot. Final comparison changes only the identifier epoch supplied by the kernel's exact Work-owned mutation receipt; the stored snapshot, credential ID/version, original proof metadata, issued time and accepted activity stay unchanged. Reading a record does not authenticate its bearer or manufacture fresh reauthentication. This eligibility check is not a policy Allow, one-time proof consumption or complete workflow authorization. Public protected identifier execution remains disabled pending those phases and durable recovery composition.

SessionAuthorityKeys uses visible-ASCII canonical IDs under the session owner's existing profile. Family keys bind tenant/user/family; session keys add session ID. Versioned, length-framed SHA-256/base64url avoids delimiter aliases. Compare these keys together with identitypostgres.KernelAuthorityKeys and authorization's AuthorityScope.Key. Keys contain no versions or positive validity evidence and must not be logged. Historical custom keys are rejected by this profile, never silently transformed or adopted from a newer epoch.

Configure the exact authentication method and credential kind/owner used by the issuer. Currently only single-factor sessions without organization/factor/ passkey applicability are eligible. Anonymous, multifactor and passkey-owned sessions deny even if optional dimensions were omitted. Present unsupported dimensions also deny; they are not skipped. Full support remains required in the platform and needs the actual corresponding owners, not a configuration override. Zero/malformed profile and missing pool/configuration are InvalidInput; foreign, stale, revoked and unsupported sessions deny uniformly as Forbidden; corrupt storage and unavailable primary reads are redacted Unavailable. Earlier caller/Work deadlines win, and cancellation/deadline classifications remain.

MFA completion record development

NewSelectedSessionService can explicitly compose SingleFactor profiles and MFAMagicLink in one native primary reader. The MFA profile requires the same deployment, policy namespace and audience as the selected primary profiles. Immutable MFA provenance is dispatched first: failed or unavailable factor authority never falls back to single-factor magic-link admission. Selecting both profiles does not change the session's original authentication kind or remove its factor dimension. Cache custody binds the complete selected set; the original earliest authoritative-read deadline is retained. Omitting MFA preserves the existing single-factor profile. This read selection alone does not enable MFA logout; select RevokeOneExecutorConfig.MFAMagicLink with the same profile for native revocation. The reference graph selects both when MagicLink.TOTP is enabled. The MFA owner fences current confirmed enrollment and factor generation inside the sole logout transaction for caller and target.

NewMFATOTPCompletionEffect composes the session-owned effect for the exact native magic-link/TOTP completion profile. The MFA owner must authenticate original primary/browser/child and current factor policy, acquire directory, recipient and authorization fences before factor locks, verify the original opaque code and record its transition. Apply requires that same recorded TOTP handle and exhaustively compares original scope and command-bound session. The factor dimension uses the MFA owner's FactorAuthorityKey and generation; the single-factor admission profile still rejects factor applicability.

This initial profile preserves primary authentication at original continuation issuance and passes the original resolved remember policy unchanged. It does not consume the original grant or browser transaction again. Session/family and retained issuance evidence share the existing coordinator transaction. Recover votes from the retained tuple and complete record commitment, never a bearer or current live payload. Positive protected-path integration, public completion and reference selection remain pending; constructor/guard tests are not MFA login.

MFATOTPCompletionSessionFields binds the full prospective original-primary session into the TOTP completion command's session.result namespace before fingerprinting. MFATOTPCompletionSession restores only that closed anonymous completion profile; the original primary command remains distinct from the completion command. Missing or mixed fields deny. Mapping never verifies a code or supplies permission to persist a session: the actual native MFA owner must check original opaque custody and the recorded same-transaction factor result.

The record codec and OriginalSessionFields now retain separate original magic-link primary and TOTP completion metadata, with optional synchronizer state, in explicit schemas9/10. Decoding rejects missing/partial factor data, foreign primary linkage, changed remember policy and malformed scope digests. This mapping is structural, not proof of successful authentication.

Append MFAMigrationSource after MagicLinkMigrationSource in the existing session history to admit complete schemas9/10. It preserves legacy expressions and records; upgrade all readers first because older binaries reject this profile. Append MFASigninMigrationSource after MagicLinkSigninMigrationSource in the existing issuance history to admit the closed factor-completion purposes without creating another journal or changing previous rows.

Native password/TOTP and recovery-code completion/reference composition now exercise this profile through real public journeys; the remaining MFA capability set is unfinished. Applied migration bytes remain unchanged; installing these extensions alone does not authenticate a factor or issue a session.

MFA recovery-regeneration session effects

NewPasswordActiveTOTPPrimarySource supplies actual session/bearer/CSRF custody for native authenticated step-up and regeneration. Original encrypted snapshot restoration checks unchanged bearer/synchronizer possession without a new read or renewed freshness. Native protected fences retain current directory, credential, policy, factor, session and family authority.

MFARecoverySessionEffect is the sole session-write owner enlisted by native regeneration. Install MFARecoverySessionMigrationSource in the selected disposition migration history using the native session schema. The effect revokes active subject sessions in bounded stable pages (maximum1024), retaining command-bound original-source and disposition evidence in the same Work. Too many sessions roll the whole mutation back. Its final check permits the source's intentional revocation but requires exact original identity/version, no active subject sessions and still-current primary authority. Recovery reads retained effect evidence, not mutable current-session state. No caller pool, transaction, goroutine or session revival is owned by this effect.

For selected factor rename or removal, NewMFAFactorUpdateSessionEffect borrows that same bounded owner under the exact factor-update binding; it does not admit arbitrary actions or select regeneration. Install MFAFactorUpdateSessionMigrationSource after the base disposition v1 history. PrepareFactorUpdate and RestoreFactorUpdate retain actual primary session/synchronizer custody under the owner-generated keyed command. The source is intentionally revoked on commit, not refreshed or replaced; outcome recovery requires no live cookie. The same protected disposition admits exactly factor.updated.v1 or factor.removed.v1; removal must still be independently authorized by MFA's actual recovery policy. Both revoke the complete bounded subject-session set, not only the session that supplied the proof, and recovery never revives it.

Pending TOTP replacement uses the same primary owner through RestoreReplacementForURI/RestoreReplacementForConfirmation, preserving the original bearer and synchronizer while ReadCurrent obtains an actual native session-authority observation. That observation expires within20seconds of its read start; repeat checks/copies never reset it or extend original absolute limits. Initiation preserves sessions. NewMFATOTPReplacementSessionEffect revokes the whole bounded subject set only with successor activation in the same Work. Install optional MFATOTPReplacementSessionMigrationSource v4 after the existing selected disposition history; independently optional disable v3 is not required. Recovery authenticates the original retained disposition; it does not require a live source cookie, disclose a new session or repeat revocation.

Service expiry and OIDC termination owner effects

AnonymousDisposalEffect.ApplyExpired accepts only the closed service-expiry command after actual kernel disposal. It revokes the complete guest set, including empty/pruned sets; it does not authenticate an expired guest. Install AnonymousExpiryMigrationSource last after the selected disposal/upgrade histories. Its Upgrade flag must describe the already-installed history.

NewOIDCEndSessionEffect selects exact-source password-session termination in the OAuth owner's existing transaction. OIDCEndSessionFields preserves the original session and microsecond-exact deadline; floor finer clock precision, never round up. Install OIDCEndSessionMigrationSource after single-session revocation history. Apply, final Check and original Recover share the existing session tombstone; siblings and family epochs remain unchanged. The protocol owner still authenticates the cookie, verifies the issued ID-token hint and current client/key/origin, and requires the protected OIDC audit plus session.revoked.v1 in that transaction. These effects enable no endpoint.

OIDCEndSessionRevoked is a bounded primary structural read, not authentication or a renewable positive lease. RequireNotRevoked fences that disposition in the selected native OAuth token Work. Only RP logout creates this disposition; ordinary signout does not silently change existing grant policy. Recovery uses retained original evidence even after source payload pruning, not active Get.

Documentation

Overview

Package postgres owns durable session storage. Structural record reads do not authenticate a bearer or authorize a session. Native family revocation and explicitly configured authenticated issuance use the sole coordinator. Complete bearer delivery, rotation and session authentication remain in development.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrInvalidRecord = errors.New("session/postgres: invalid stored record")

ErrInvalidRecord rejects incomplete, oversized or unknown stored projections. It contains no stored identifier, digest, authentication or driver diagnostic.

View Source
var ErrRecordAbsent = errors.New("session/postgres: record absent")

ErrRecordAbsent reports no structurally matching record in the exact tenant. These trusted storage reads are not a public enumeration or login endpoint.

Functions

func AnonymousSigninSession

func AnonymousSigninSession(command identity.Command) (session.Session, error)

AnonymousSigninSession restores only the complete session-owned projection of the closed anonymous-flow signin command. Missing/extra/foreign fields deny; other namespaces remain the anonymous owner's responsibility. It creates no authentication proof, renewal, command authority or permission to issue.

func AnonymousSigninSessionFields

func AnonymousSigninSessionFields(record session.Session) ([]identity.FeatureField, error)

AnonymousSigninSessionFields freezes the complete prospective unprivileged session in the session.result namespace before command fingerprinting. It retains original remember, anonymous creation time, every authority dimension and optional CSRF digest, never a bearer or verified credential. Only an initial anonymous record is supported. This mapping grants no risk, kernel creation, current authority or persistence admission; the native owner must establish all of those atomically in its original Work. Returned bytes belong to the caller and must not be logged or mutated during use.

func AnonymousSourceSessionFields

func AnonymousSourceSessionFields(original session.Session) ([]identity.FeatureField, error)

AnonymousSourceSessionFields freezes the existing anonymous session's full digest-only record in a separate closed namespace. This does not broaden the verified OriginalSessionFields profile. It authenticates nothing: the native workflow must prove bearer/CSRF possession and current primary owners before any protected transition. Caller owns returned fields; never log them.

func AnonymousSourceSessionFromFields

func AnonymousSourceSessionFromFields(tenant identity.TenantID, user identity.UserID, fields []identity.FeatureField) (session.Session, error)

AnonymousSourceSessionFromFields restores only the exact frozen anonymous projection for this tenant/user. Duplicates, unknown fields, inactive union data, omissions and oversized inputs deny. It grants no authentication, freshness, authorization, mutation or bearer re-disclosure.

func AnonymousUpgradeSessionFields

func AnonymousUpgradeSessionFields(guest, permanent session.Session) ([]identity.FeatureField, error)

AnonymousUpgradeSessionFields binds both complete original guest and prospective permanent records through the existing canonical session codec. Three flattened sessions exceed the shared 128-field command limit; retain the target's required source-session vocabulary and bind these two records by domain-separated commitments instead. This is not a JSON escape or authority: the native owner's authenticated preparation must retain the complete records, prove possession/current owners and compare them again inside sole Work. No bearer or positive-validity lease is encoded. Returned fields are owned.

func EmailVerificationSigninSession

func EmailVerificationSigninSession(command identity.Command) (session.Session, error)

EmailVerificationSigninSession restores the session-owned portion of an exact post-verification signin command. It reuses email-possession provenance, not password authentication or ordinary magic-link consumption. User must match command scope; RecordID names the distinct committed confirmation parent. Incomplete or mixed fields deny. This is pure structural restoration, not permission to issue: the native workflow must prove fresh committed original verification, browser possession, original remember choice and all current authority/risk/MFA fences.

func FinalizeMFAPasskeyPreAuth

func FinalizeMFAPasskeyPreAuth(ctx context.Context, w kernel.Work, owner kernel.MFACompletionContributor, command identity.Command, c Config, original session.PreAuthTransaction) error

FinalizeMFAPasskeyPreAuth consumes only this Work's original reservation, after successful native factor and session effects in the same transaction. It cannot consume an issued flow directly or reuse another command's custody. Later failure must abort all browser/child/factor/session effects together. Exact retries and ambiguous outcomes use the original coordinator receipt; never re-run this transition or release the browser on an uncertain commit.

func FinalizePreAuth

func FinalizePreAuth[R SessionRows](ctx context.Context, q PreAuthWriter[R], c Config, record session.PreAuthTransaction, use PreAuthUse) error

FinalizePreAuth consumes only the exact reserved owner, after locked primary time and complete original binding checks. Invoke in the same transaction as protected session/link effects. An error must abort the entire transaction. Terminal replay denies, even with the same command; the coordinator returns its original historical receipt instead of reexecuting this transition.

func InsertPreAuth

func InsertPreAuth[R SessionRows](ctx context.Context, q PreAuthWriter[R], c Config, record session.PreAuthTransaction) error

InsertPreAuth stages the original issued record inside the owned initiation command. It never reveals a cookie, samples/renews timestamps, closes the transaction or writes a command journal. Duplicate IDs/digests deny; they cannot overwrite or resurrect terminal flows. The issuance owner must recover ambiguous insertion by the existing command, not call this to mint another record. Public initiation/receipt recovery wiring is still separate work.

func MFAOTPCompletionSession

func MFAOTPCompletionSession(command identity.Command) (session.Session, error)

MFAOTPCompletionSession reconstructs only the exhaustive anonymous OTP completion projection. Native same-Work OTP/child/factor completion remains mandatory; metadata alone cannot authorize a session. Mixed methods deny.

func MFAOTPCompletionSessionFields

func MFAOTPCompletionSessionFields(record session.Session) ([]identity.FeatureField, error)

MFAOTPCompletionSessionFields freezes complete original-primary/OTP provenance, original remember and optional CSRF without code or bearer. It performs no authentication, consumption, persistence or renewal.

func MFARecoveryCompletionSession

func MFARecoveryCompletionSession(command identity.Command) (session.Session, error)

MFARecoveryCompletionSession restores only exact recovery-use v1 session metadata. Missing set epoch, partial fields or TOTP substitution denies. The native owner must authenticate original primary/browser/child and prove actual recorded recovery burn in the same transaction before persistence.

func MFARecoveryCompletionSessionFields

func MFARecoveryCompletionSessionFields(record session.Session) ([]identity.FeatureField, error)

MFARecoveryCompletionSessionFields freezes complete original-primary and recovery-set/factor provenance without submitted code or bearer custody. It is structural metadata, never permission to burn a code or issue a session.

func MFATOTPCompletionSession

func MFATOTPCompletionSession(command identity.Command) (session.Session, error)

MFATOTPCompletionSession restores only the complete session-owned projection of an anonymous TOTP completion v1 command. Completion identity and tenant must match; original primary identity remains distinct and cannot retarget the browser command. Missing, mixed, noncanonical or extra session fields deny. The native owner separately checks non-session fields and original opaque code/browser/child custody and actual recorded factor completion. Successful reconstruction is not authentication or permission to persist a session.

func MFATOTPCompletionSessionFields

func MFATOTPCompletionSessionFields(record session.Session) ([]identity.FeatureField, error)

MFATOTPCompletionSessionFields freezes the complete prospective password or magic-link primary/TOTP session before native command fingerprinting. It retains original primary, child/factor provenance, every authority dimension, resolved remember policy and optional CSRF, never a bearer or submitted code. Only the initial native TOTP completion profile is accepted. This bounded structural mapping performs no verification, reservation, IO or renewal.

func MagicLinkSigninSession

func MagicLinkSigninSession(command identity.Command) (session.Session, error)

MagicLinkSigninSession restores only the complete session-owned projection from the exact anonymous magic-link-consume v1 command. Original command identity and tenant must match; the selected user remains separately bound without retargeting anonymous scope. Missing, extra, mixed or noncanonical session fields deny with ErrInvalidSessionCommand. Other fields are checked by the magic-link owner. No proof authentication, consumption, freshness renewal or permission to issue is established. Inputs must remain immutable during this synchronous bounded call; returned state owns its bytes.

func MagicLinkSigninSessionFields

func MagicLinkSigninSessionFields(record session.Session) ([]identity.FeatureField, error)

MagicLinkSigninSessionFields freezes the complete prospective email-grant session into the session.result namespace before command fingerprinting. It preserves original grant, request, identifier versions, remember policy, authority and optional CSRF; it never contains a bearer or proof. Returned fields and bytes are caller-owned. Only initial single-factor magic-link sessions are accepted. This pure bounded mapping proves no consumption or current authority: the registered native owner must check both in its Work.

func MapCommand

func MapCommand(c session.SessionCommand) (identity.Command, error)

MapCommand exhaustively maps closed native issuance or family revocation to identity's shared immutable intent vocabulary. It performs no IO or authorization. All behavior-affecting input is bound; no arbitrary JSON, bearer or callback is admitted. Mapping is structural only: issuance cannot execute until its native admission/effect profile is registered, and must use the protected proof-bearing coordinator reservation rather than ordinary ReserveCommand.

func MapRevokeOneRequest

func MapRevokeOneRequest(request session.RevokeOneRequest) (identity.Command, error)

MapRevokeOneRequest freezes both original caller and target, including the caller's unchanged exclusive deadline, in the existing keyed command intent. It performs no IO or authentication. The owned executor must validate opaque request custody against its configured SessionService before reservation; this structural projection cannot replace that request or grant permission.

func MapRevokeSetRequest

func MapRevokeSetRequest(request session.RevokeSetRequest) (identity.Command, error)

MapRevokeSetRequest freezes the exact original source, disposition, whole-set bound and unchanged exclusive admission deadline in the existing keyed intent. This is structural mapping, never authentication or execution permission. Only the owned executor may admit the opaque request from its exact reader. No caller-selected target, bearer or arbitrary JSON enters the command.

func MapRotationRequest

func MapRotationRequest(request session.RotationRequest) (identity.Command, error)

MapRotationRequest binds the complete original record, exact permitted successor, original exclusive admission and transport to the keyed command intent. It performs no IO and grants no execution authority. The owned executor must validate the opaque request against its configured reader before reservation and commit; this projection cannot replace that custody. Successor deltas use the same canonical scalar vocabulary as the source, avoiding a second arbitrary JSON record or duplicated authority vector.

func MapUpdateRequest

func MapUpdateRequest(request session.UpdateCommandRequest) (identity.Command, error)

MapUpdateRequest binds exact source, label, original exclusive deadline and transport into the sole kernel intent. It neither restores opaque custody nor authorizes execution. The native executor must validate the original request against its exact authenticating reader before reservation/commit.

func NewListService

func NewListService(pool *database.Pool, c ListServiceConfig) (*session.ListService, error)

NewListService composes credential authentication, current self-list policy and bounded primary metadata reads without IO, writes or application stores. Apply kernel/authorization/session migrations first, including ListMigrationSource for indexed audience-scoped traversal. Borrow the PRIMARY pool until calls finish; never configure replicas. No goroutines, transactions or journals are created. Native authentication retains its documented single-factor profile; metadata rows are structural observations, not permission or live authority.

func NewMFAMagicLinkSessionService

func NewMFAMagicLinkSessionService(pool *database.Pool, c MFAMagicLinkSessionServiceConfig) (*session.SessionService, error)

NewMFAMagicLinkSessionService composes current primary owners without IO, writes, goroutines or caches. The original exact confirmed factor enrollment and generation remain mandatory; expired continuation/grant times are history after issuance, not renewed evidence or session expiry. Cache custody has a distinct MFA profile and cannot be promoted into a single-factor reader.

func NewMFAPasskeySessionService

func NewMFAPasskeySessionService(pool *database.Pool, c MFAPasskeySessionServiceConfig) (*session.SessionService, error)

NewMFAPasskeySessionService selects only completed passkey/TOTP records. Current directory, exact primary credential, RP mapping, session/family, authorization and confirmed TOTP enrollment/generation are all mandatory. Ordinary passkey/password records cannot enter this profile. Historical assertion/continuation expiry is not renewed or reused as current evidence. Install the selected MFA/session histories before use. Construction performs no IO, migrations, issuance, writes or goroutine creation; pool is borrowed.

func NewMFAPasswordSessionService

func NewMFAPasswordSessionService(pool *database.Pool, c SessionServiceConfig) (*session.SessionService, error)

NewMFAPasswordSessionService selects password plus confirmed TOTP/OTP/recovery records. Recovery-set consumption is historical; current authority remains the original confirmed factor enrollment and account-wide generation. It uses native current directory, password credential, authorization and exact factor enrollment owners. Single-factor records deny rather than upgrading; the ordinary password factory continues to deny MFA. Configuration and pool ownership follow SessionServiceConfig. Install MFA and session histories first. No IO, cache, goroutine, proof issuance or migration occurs at construction.

func NewMagicLinkSessionService

func NewMagicLinkSessionService(pool *database.Pool, c MagicLinkSessionServiceConfig) (*session.SessionService, error)

NewMagicLinkSessionService composes real bounded primary owner reads without IO, goroutines, writes or caches. It checks the original verified address and every current authority dimension. Original grant expiry is historical after issuance, not the session's expiry. Password/OTP factories remain disjoint; this factory neither certifies token consumption nor manufactures a session.

func NewOTPSessionService

func NewOTPSessionService(pool *database.Pool, c OTPSessionServiceConfig) (*session.SessionService, error)

NewOTPSessionService composes the owned primary OTP reader without IO. The borrowed pool must be primary and outlive calls; the caller closes it. There are no goroutines, caches or writes. The original verified identifier and all current authority dimensions must still agree. Original OTP expiry is history, not an issued session's expiry. Existing NewSessionService stays proof-only; neither factory manufactures issuance or accepts the other method implicitly.

func NewPasskeySessionService

func NewPasskeySessionService(pool *database.Pool, c PasskeySessionServiceConfig) (*session.SessionService, error)

NewPasskeySessionService selects identified phishing-resistant passkey reads. Every kernel, credential, session/family, authorization, RP/passkey and original known-empty MFA dimension must remain current. No single-factor password path is enabled. Historical ceremony/proof expiry is not renewed after issuance. Construct the owned Authority against the same primary database before use.

func NewSelectedSessionService

func NewSelectedSessionService(pool *database.Pool, c SelectedSessionServiceConfig) (*session.SessionService, error)

NewSelectedSessionService freezes all explicitly selected owner profiles without IO, writes or goroutines. One primary lookup dispatches on immutable stored provenance. Cache custody binds the complete selected set and retains the earliest contributing read deadline; selecting MFA cannot renew it. With no additional MFA/passkey selection, single-factor cache identity is unchanged. Passkey selection shares one lookup, not another reader fallback.

func NewSessionService

func NewSessionService(pool *database.Pool, c SessionServiceConfig) (*session.SessionService, error)

NewSessionService composes the owned primary reader with core credential validation without IO. The caller closes its pool only after all operations finish. There are no goroutines, caches, writes or independently owned stores. This profile rejects anonymous, organization, MFA and passkey records until their native authority owners are composed; it never drops a dimension.

func NewSetRevocationService

func NewSetRevocationService(pool *database.Pool, c SetRevocationServiceConfig) (*session.SetRevocationService, error)

NewSetRevocationService composes core credential-based revoke-other/all with the primary reader and native transaction owner without IO or consumer glue. Apply required kernel, authority, session, bulk-revocation, audit and outbox migrations first. The pool is borrowed. Final-signin issuance is not required; unsupported authority profiles fail closed rather than dropping dimensions.

func NewSignOutService

func NewSignOutService(pool *database.Pool, c SignOutServiceConfig) (*session.SignOutService, error)

NewSignOutService composes the owned primary reader and native one-session executor with core self-signout, without IO or application-written stores. Install kernel, authorization, session, revocation, audit and outbox migrations first. The borrowed PRIMARY pool and dependencies must outlive calls; close them only after operations finish. No goroutines or additional transaction, command journal, clock or policy owner are created. Ordinary logout does not require final-signin proof composition. Historical unknown-outcome recovery remains RecoverRevokeOneCommand on the same owned native executor profile.

func NewSingleFactorSessionService

func NewSingleFactorSessionService(pool *database.Pool, c SingleFactorSessionServiceConfig) (*session.SessionService, error)

NewSingleFactorSessionService freezes selected native profiles without IO, caches, goroutines or writes. One primary digest lookup identifies the record; only that method's selected owner path may authenticate it. A denial or outage never tries another profile. The caller closes the primary pool after calls finish. Cache custody binds the entire selected set and exact owner/store profiles, preserving the earliest original authority-read expiry.

func OIDCEndSessionFields

func OIDCEndSessionFields(source session.Session, until time.Time) ([]identity.FeatureField, error)

OIDCEndSessionFields freezes the exact original session and exclusive observation deadline in the protocol owner's command. It contains no bearer and grants no authentication, hint verification or permission to terminate. The native OAuth owner must preserve its original read-start budget (at most 20 seconds), independently authenticate the source, and validate its issued hint, current client/key and origin before this effect can be used. Until must be microsecond-exact for the shared command codec. If a native clock has finer precision, floor the original deadline before calling; rounding up would extend its authority window.

func OTPSigninSession

func OTPSigninSession(command identity.Command) (session.Session, error)

OTPSigninSession reconstructs the exact session-owned result of a closed v1 OTP signin command. Unknown or missing session fields fail closed. Other fields remain the OTP owner's responsibility. Anonymous command scope stays anonymous; the selected session user is separately bound in these fields. This structural decoder grants no consumption, issuance or recovery authority.

func OTPSigninSessionFields

func OTPSigninSessionFields(record session.Session) ([]identity.FeatureField, error)

OTPSigninSessionFields returns the closed scalar session-owned fields for an OTP signin command. It preserves the complete original session, authentication, authority, remember policy and optional CSRF digest, never a bearer or code. The OTP owner must include these fields before command fingerprinting and reservation, alongside its own exhaustively validated fields. Construction proves neither authentication nor permission to persist the session.

func OrganizationSelectionFields

func OrganizationSelectionFields(command session.OrganizationSelectionCommand, until time.Time) ([]identity.FeatureField, error)

OrganizationSelectionFields maps the complete original session, explicit selection/clear and original exclusive admission deadline into the native organization's command vocabulary. It contains no raw bearer or permission proof. The organization owner must authenticate custody and require actual current membership, lifecycle and policy inside the sole coordinator Work. Until must already be UTC/microsecond exact; never round its expiry upward. Returned fields are owned copies; no IO or validity renewal occurs.

func OrganizationSelectionFromFields

func OrganizationSelectionFromFields(b identity.CommandBinding, fields []identity.FeatureField) (session.OrganizationSelectionCommand, time.Time, error)

OrganizationSelectionFromFields reconstructs only structural original intent. It validates the kernel's bounded closed scalar union before allocating owned field copies. Unknown/duplicate/inactive selection or source-session members deny. Other valid field namespaces remain the organization's responsibility; this decoder neither admits their domain schema nor authorizes execution. Exact tenant, human actor, stable session ID and source CAS must still match. Original time/provenance survive reconstruction; no live admission is minted.

func OriginalDeviceGrantAdmission

OriginalDeviceGrantAdmission derives the approved human source's exact owner expectations while preserving a device-token command's actual client actor and anonymous-flow identity. Only the closed native-device-v1 password profile is supported. The complete original session must be frozen in the native command and matched to its locked approved grant, including source user.

This pure mapping grants no authentication, consent, permission or renewed freshness. The native owner must require current directory authority and Work.RequireOAuthDeviceGrantSource in its sole transaction, compare current client/grant/consent authority and preserve every original deadline. Browser approval still uses OriginalSessionAdmission, real possession and CSRF. Invalid, foreign or unsupported input returns zero expectations and Forbidden. Concurrent immutable use is safe; no IO or resource ownership is introduced.

func OriginalMFAPasskeySessionAdmission

OriginalMFAPasskeySessionAdmission derives the exact original directory, passkey credential and authorization expectations of a completed passkey/TOTP session. It retains primary-command linkage and original factor authority; ordinary passkey, password and organization profiles deny. An action's target never replaces the session's authenticating credential. This explicit profile does not broaden OriginalPasskeySessionAdmission.

No IO, authentication or freshness renewal occurs. Callers must authenticate possession, fence the original factor ID/enrollment/generation and RP mapping, require the same session/family in protected Work, and recheck time after waits. Mutations still need a genuine fresh action-bound WebAuthn assertion; these expectations grant no permission. Immutable reads are concurrency-safe.

func OriginalMFAPasswordSessionAdmission

OriginalMFAPasswordSessionAdmission derives the exact original password and authorization expectations of a completed password/MFA session. It retains the native password-primary linkage and factor scope checks; single-factor, organization and passkey records deny. This explicit profile does not broaden OriginalSessionAdmission. No IO, authentication or freshness renewal occurs.

Callers must separately authenticate possession, fence the original MFA factor ID/enrollment/authority through its native owner, require this same original session/family, and recheck validity in protected Work. Returned expectations alone grant no permission. Immutable reads are concurrency-safe.

func OriginalOrganizationPasswordSessionAdmission

OriginalOrganizationPasswordSessionAdmission derives the exact original directory, password and user-policy expectations without dropping a selected organization. Both selected and explicitly unselected single-factor password records are supported; MFA, passkey and other authentication methods deny. This does not broaden OriginalSessionAdmission or prove organization authority.

The caller must independently authenticate bearer possession, fence this same session/family and all returned owner expectations, and require the original organization/membership through its native owner in the same protected Work. Organization removal or archive must deny, not erase the original dimension. No IO, permission decision, mutation or renewal of freshness occurs. Invalid inputs return zero expectations and redacted Forbidden. Immutable concurrent reads are safe; the trusted profile must not be mutated concurrently.

func OriginalPasskeySessionAdmission

OriginalPasskeySessionAdmission derives the exact original primary directory, credential and authorization expectations of a passkey session. Unlike OriginalSessionAdmission it retains both RP/passkey and known-empty factor dimensions; password, completed-MFA and organization profiles deny. The action's target record never replaces the session's authenticating credential.

This pure derivation performs no IO, signature verification, authentication or freshness renewal. The native owner must separately authenticate possession, require this same session/family, fence the RP/mapping and factor generations through PasskeySessionAuthority, and recheck time after waits in protected Work. A fresh action also needs a genuine action-bound WebAuthn assertion; a session timestamp or these caller-owned expectations do not constitute that proof. Immutable profile and record reads support concurrent independent calls.

func OriginalSessionAdmission

OriginalSessionAdmission derives the session owner's exact original primary expectations for an already frozen record and its command subject/actor. Profile is trusted composition, not request input. Derivation validates every owner scope key and the supported single-factor credential/method pairing. Anonymous, organization, factor and passkey records deny until their owners are composed; no required dimension is omitted. Invalid inputs return zero expectations and redacted Forbidden. No IO, primary lookup, clock read, authentication, permission decision or freshness renewal occurs.

Native workflows must compare the returned expectations through their live primary owners, authenticate the separately submitted bearer, RequireSession against this same original record, and recheck temporal validity after waits. Neither reconstructed metadata nor these caller-owned expectations authorize use. Concurrent immutable reads are safe; do not mutate profile concurrently.

func OriginalSessionFields

func OriginalSessionFields(original session.Session) ([]identity.FeatureField, error)

OriginalSessionFields freezes the complete existing authenticated session into the owner's closed scalar vocabulary, under source-session. It preserves original authentication, remember policy, every authority dimension, lookup commitment and optional CSRF state; no raw bearer is exposed. Returned fields and byte slices are caller-owned. Credential, OTP and magic-link records retain their separate historical provenance. Zero and anonymous records deny with ErrInvalidSessionCommand; anonymous admission is a different profile. This pure bounded mapping performs no IO, freshness renewal or authentication. Native workflows must bind every field into their keyed command, authenticate the separate bearer and compare current owners and RequireSession on the sole coordinator transaction. Never log these correlated storage projections.

func OriginalSessionFromFields

func OriginalSessionFromFields(tenant identity.TenantID, user identity.UserID, fields []identity.FeatureField) (session.Session, error)

OriginalSessionFromFields reconstructs only the complete canonical vocabulary emitted by OriginalSessionFields for the exact tenant and user. Order is irrelevant; duplicates, omissions, unknown names, inactive union data and out-of-bounds inputs deny. At most128 fields, each name at most128 bytes and each text/byte value at most4096 bytes, are examined before reconstruction. Inputs must remain immutable during the call; the result retains owned copies. It grants no provenance, active-state assertion or protected-operation access. No IO, clock, callback or resource lifetime is introduced. Native consumers still need bearer possession, their exact admission profile and primary checks.

func PasskeySigninSession

func PasskeySigninSession(command identity.Command) (session.Session, error)

PasskeySigninSession restores only the complete canonical prospective record of the exact identified passkey assertion command. Mixed/unknown fields deny; other namespaces belong to the native passkey owner. Opaque WebAuthn custody, current RP/mapping/factor/risk and atomic protocol/session effects remain mandatory. A successful projection is not successful authentication.

func PasskeySigninSessionFields

func PasskeySigninSessionFields(record session.Session) ([]identity.FeatureField, error)

PasskeySigninSessionFields freezes the complete original prospective session before native intent fingerprinting. The closed session.result vocabulary retains authenticating credential, remember, all epochs and CSRF, not bearer bytes or a cryptographic assertion. Mapping never authenticates or authorizes.

func PasskeySignupSession

func PasskeySignupSession(command identity.Command) (session.Session, error)

PasskeySignupSession restores only the exact anonymous prospective-account profile, binding the selected session user to kernel-owned registration.user and its credential to the original lifecycle subject. Unknown session fields, missing fields, existing-account profiles and noninitial owner epochs deny. The native owner still must prove real WebAuthn verification and all current authorities, and stage account/protocol/session effects in the sole Work. Successful mapping grants no authentication, custody or freshness renewal.

func PasskeySignupSessionFields

func PasskeySignupSessionFields(record session.Session) ([]identity.FeatureField, error)

PasskeySignupSessionFields freezes the complete original prospective initial session in the existing closed session.result vocabulary. No bearer or WebAuthn response is projected. Known-empty MFA and initial RP authority are retained, not inferred or refreshed. This structural projection never proves successful registration, actual account creation or permission to issue.

func PasswordChangeSessionFields

func PasswordChangeSessionFields(original session.Session, disposition PasswordChangeSessionDisposition, maximum uint32) ([]identity.FeatureField, error)

PasswordChangeSessionFields returns owned scalar metadata binding complete original-session custody, disposition and a whole-set maximum of 1..100000. Append these to CredentialReplacementFields before constructing the original password-change command. Never replace the selection after reservation or infer it from retries. The maximum counts every selected active-state row, including expired/stale rows; it is not a per-page limit.

Only verified single-factor password sessions without organization, factor or passkey dimensions are admitted by this initial native profile. Their complete history, independent effective credential linkage, remember policy and CSRF state are retained. Other profiles require their real owner effects. No IO, callback, clock read, permission, current-owner check or session mutation occurs. Atomic same-Work execution and original-effect recovery are separately required; these fields alone cannot enable preservation. Concurrent immutable reads are safe; returned projections must not be logged or exposed to clients.

func PasswordSigninSession

func PasswordSigninSession(command identity.Command) (session.Session, error)

PasswordSigninSession restores only the exact session-owned projection from the closed paired password-signin v1 command. Missing, extra, malformed or cross-scope fields, ordinary/OTP variants and destroyed password owners deny with ErrInvalidSessionCommand. Other fields remain the password owner's responsibility. Anonymous command scope is never rewritten to the selected session user. Inputs must remain immutable during this synchronous bounded call. No comparison, provenance, freshness renewal or recovery authority is established: native execution must check the selected user and all owners in the original Work before staging this record. Do not log correlated fields. Exact username-signin custody uses the same projection without relabeling; the native workflow additionally owns current username admission.

func PasswordSigninSessionFields

func PasswordSigninSessionFields(record session.Session) ([]identity.FeatureField, error)

PasswordSigninSessionFields freezes the complete prospective password session into the closed session.result vocabulary before command fingerprinting. The selected tenant/user are explicit even when the command remains anonymous. Returned fields and bytes are caller-owned; no password, cookie or bearer is included. Only initial single-factor password issuance without organization, factor, passkey or credential-continuation authority is supported. Zero and unsupported records return ErrInvalidSessionCommand. This pure mapping does not authenticate, compare current owners, consume pre-auth or permit issuance.

func PasswordSignupSession

func PasswordSignupSession(command identity.Command) (session.Session, error)

PasswordSignupSession restores only the complete session-owned fields of the closed paired password-signup v1 command. Missing, malformed, foreign, mixed, ordinary and signin variants deny. No normalization, policy decision, flow consumption, authentication or freshness renewal occurs. Inputs must remain immutable during this bounded call; correlated fields must not be logged.

func PasswordSignupSessionFields

func PasswordSignupSessionFields(record session.Session) ([]identity.FeatureField, error)

PasswordSignupSessionFields freezes the complete prospective single-factor password session into session.result fields. It retains the new user separately from anonymous registration scope. No verifier, cookie or bearer is projected. Like signin's structural record mapping, this grants no authentication or verification/MFA policy admission. Native registration must retain all fields before fingerprinting and admit the exact original in its transaction.

func ReadPreAuth

ReadPreAuth loads the exact original private projection from the borrowed primary transaction. It checks physical index/record agreement but not active state, expiry, cookie possession, reservation or user authority. IDs alone cannot authenticate a flow. The native owner must freeze/verify original request intent and cookie, then invoke locked admission in the same unit. Retained reserved/terminal records remain structural historical data only. No time is sampled, validity renewed, lock acquired or callback invoked. Missing scope is Forbidden; corrupt/storage failures are Unavailable; malformed/nil inputs are InvalidInput. All errors are redacted and bounded.

func RebindPreAuth

func RebindPreAuth[R SessionRows](ctx context.Context, q PreAuthWriter[R], c Config, record session.PreAuthTransaction, previous PreAuthUse, next uint64) error

RebindPreAuth transfers only an exact reserved predecessor to its immediate positive successor generation under exclusion. The original record, version, cookie, policy and timeline remain unchanged; it never compares/meters a code, reactivates state or consumes a flow. Current primary expiry is checked after locking. Terminal, mismatched, skipped and overflowing ownership deny.

This is a native SQL operation, NOT takeover/noncommit authorization. The owner must derive predecessor and successor from the coordinator's live sealed takeover invocation and abort on any error. A lease timeout, caller generation or connection failure cannot independently authorize invocation. No journal, transaction closure, release mechanism or callback is introduced.

func ReleasePreAuth

ReleasePreAuth terminalizes an exact original reserved flow only within the registered owner's live sealed OTP noncommit callback. The coordinator proves rollback or unanimous primary noncommit; no data-only proof is accepted. Zero, foreign, expired callback and returned handles deny. Original flow expiry does not block terminal release and never authorizes it. The exact predecessor is released at its unchanged rollback generation or coordinator successor. Original cookie, policy, intent and timeline remain unchanged.

This borrows the callback's bounded transaction, closes all cursors, invokes no callbacks and retains no handles. The owner must abort on every error. Install PreAuthReleaseMigrationSource first. Malformed input is InvalidInput; absent/terminal/changed custody is Forbidden; storage is Unavailable and cancellation/deadline classifications are preserved. No initiation or native OTP contributor registration is performed by this storage operation.

func RequireCSRF

func RequireCSRF[R SessionRows](ctx context.Context, q SessionQueryer[R], c Config, expected session.Session, token session.CSRFToken, key session.CSRFKey) error

RequireCSRF checks a synchronizer token against the exact command-frozen session and fences that complete record and active family on the original primary transaction. A structural token match alone never grants admission. The named dedicated key must be selected by trusted policy; no alternate key version is tried. Missing state, wrong tokens and stale state deny as redacted Forbidden. Invalid configuration/session inputs are InvalidInput; storage failures and cancellation follow RequireSession's classifications.

This is a trusted participant helper, not a standalone authorization API. The owner MUST pass its original bounded transaction, abort or poison it on every error, retain the locks through protected work, and check all other applicable authorities and temporal validity before commit. It must acquire any session write fence before calling this helper, not upgrade shared locks afterwards. A replica, cache or autocommit pool cannot satisfy this contract. HTTP channel/origin policy and pre-auth one-use flows remain separate owners. Success does not renew freshness, consume a token, or issue any credential.

func RequireMFAConsumedPreAuth

func RequireMFAConsumedPreAuth(ctx context.Context, w kernel.Work, owner kernel.MFACompletionContributor, command identity.Command, c Config, original session.PreAuthTransaction, primary identity.CommandID) error

RequireMFAConsumedPreAuth fences the unchanged original browser flow already consumed by the committed password or magic-link primary. It is read-only: it neither reactivates nor consumes that flow again. Only the exact registered native TOTP/recovery completion owner, during its bounded preparation or Apply callback, may invoke it. Primary must come from verified original child issuance custody, never a request field. The native owner must separately compare the submitted opaque cookie digest, original origin/callback/Remember and signed child scope. This check alone is not browser possession, factor proof or session authority. Locks last until the sole coordinator closes Work; propagate every error.

func RequireMFAConsumedPreAuthAttempt

func RequireMFAConsumedPreAuthAttempt(ctx context.Context, w kernel.MFATOTPAttemptWork, owner kernel.MFATOTPAttemptContributor, c Config, original session.PreAuthTransaction, primary identity.CommandID) error

RequireMFAConsumedPreAuthAttempt applies the same original-browser fence in the sealed counted-TOTP callback, before any shared-budget charge. Invalid browser possession must not become a factor attempt. The owner separately authenticates cookie/scope as documented by RequireMFAConsumedPreAuth; this reader cannot consume a child, compare a code, charge a budget or issue a session. Zero/foreign/returned callback handles fail closed. The original journal and flow remain unchanged on both correct and rejected submissions.

func RequireMFAConsumedPreAuthRecoveryAttempt

func RequireMFAConsumedPreAuthRecoveryAttempt(ctx context.Context, w kernel.MFARecoveryAttemptWork, owner kernel.MFARecoveryAttemptContributor, c Config, original session.PreAuthTransaction, primary identity.CommandID) error

RequireMFAConsumedPreAuthRecoveryAttempt applies the same original-browser fence exclusively in the live registered recovery-code denial callback. The native owner must first authenticate original cookie and child scope; invalid browser possession cannot spend a factor attempt. This read grants no comparison, burn, child consumption or session authority. Propagate every error so the sole transaction aborts; returned/foreign handles fail closed.

func RequireMFAOTPConsumedPreAuth

func RequireMFAOTPConsumedPreAuth[R SessionRows](ctx context.Context, q SessionQueryer[R], b identity.CommandBinding, c Config, original session.PreAuthTransaction, primary identity.CommandID) error

RequireMFAOTPConsumedPreAuth is the read-only original-browser fence used by native OTP's distinct MFA continuation arm. Binding and primary must come from authenticated original attempt custody, not caller projections. The OTP owner separately verifies cookie possession; the MFA owner verifies the signed child, subject, factor, policy and shared budget. This reader alone grants no authentication, comparison, charge, reservation or permission to issue a session. It never reactivates/releases/finalizes the already-consumed primary. q borrows the caller's bounded transaction; all rows are closed before return, and primary time is sampled there without an injectable clock or renewal.

func RequireMFAPasskeyConsumedPreAuth

func RequireMFAPasskeyConsumedPreAuth(ctx context.Context, w kernel.Work, owner kernel.MFACompletionContributor, command identity.Command, c Config, original session.PreAuthTransaction, primary identity.CommandID) error

RequireMFAPasskeyConsumedPreAuth fences only the original browser consumed by the committed native passkey primary during protected TOTP completion. It does not authenticate an assertion, compare a cookie, consume again or issue a session. The exact MFA owner must authenticate original primary and child custody and compare the submitted cookie before calling. Propagate any error to abort; original expiry and command/fingerprint/generation remain fixed.

func RequireMFAVerificationConsumedPreAuth

func RequireMFAVerificationConsumedPreAuth(ctx context.Context, w kernel.Work, owner kernel.MFACompletionContributor, command identity.Command, c Config, original session.PreAuthTransaction, signup identity.CommandID) error

RequireMFAVerificationConsumedPreAuth fences genuine signup custody for the explicit TOTP completion of a verification-origin child. Signup is already consumed and is never reactivated. Its ID comes from the authenticated native primary, not the completion command or a caller-supplied parent assertion. The exact native factor owner separately authenticates cookie and child.

func RequireMFAVerificationConsumedPreAuthAttempt

func RequireMFAVerificationConsumedPreAuthAttempt(ctx context.Context, w kernel.MFATOTPAttemptWork, owner kernel.MFATOTPAttemptContributor, c Config, original session.PreAuthTransaction, signup identity.CommandID) error

RequireMFAVerificationConsumedPreAuthAttempt applies the same immutable signup fence before a counted TOTP comparison or shared-budget debit. Foreign or returned callbacks deny; this operation cannot compare or charge a factor, consume/reactivate signup, or create a session. Propagate every error.

func RequirePreAuth

func RequirePreAuth[R SessionRows](ctx context.Context, q SessionQueryer[R], c Config, record session.PreAuthTransaction) error

RequirePreAuth locks and admits only the exact original issued primary flow. It checks all binding fields, original version/cookie and database time AFTER lock acquisition. Success is not authentication or one-use consumption. Current access policy and credential owners remain the consuming workflow's checks. It retains no handle/cursor and performs no independent IO or write.

func RequireReservedPreAuth

func RequireReservedPreAuth[R SessionRows](ctx context.Context, q SessionQueryer[R], c Config, record session.PreAuthTransaction, use PreAuthUse) error

RequireReservedPreAuth performs read-only exact-owner admission under a share lock until the original transaction closes. The complete original binding, reservation command/fingerprint/generation and exclusive primary expiry must still match. It neither compares an OTP nor consumes/meters/renews the flow. The owning sealed callback checks all other current authority and must abort or poison on any error; zero/data-only custody grants no execution authority.

func RequireSession

func RequireSession[R SessionRows](ctx context.Context, q SessionQueryer[R], c Config, expected session.Session) error

RequireSession compares the exact frozen session record and active family under share locks retained until the original primary transaction closes. It checks database time after lock acquisition against original absolute and idle expiry. Expected must be frozen in the owning command before reservation; no caller input, cache promotion or retry may replace that record. An earlier context/Work deadline wins; Config supplies a finite maximum read budget.

This checks only session-owned state, not current global, tenant, user, credential, authorization, organization, factor or passkey authority. The owning workflow must check every applicable authority and authentic proof, and recheck temporal validity before commit. Success creates no validity evidence, freshness renewal, bearer, session or authorization decision. Missing, revoked, expired or unequal records return redacted Forbidden; malformed inputs are InvalidInput and corrupt/storage failures Unavailable. Cancellation/deadline classifications are preserved. It never retains a cursor/transaction, begins/closes a transaction, writes or invokes callbacks.

func RequireVerificationSignupPreAuth

func RequireVerificationSignupPreAuth(ctx context.Context, w kernel.Work, owner kernel.EmailVerificationMFAChallengeContributor, command identity.Command, c Config, original session.PreAuthTransaction, signup identity.CommandID) error

RequireVerificationSignupPreAuth fences the original browser already consumed by genuine signup, for the exact native verification-MFA challenge owner. It never consumes/reactivates signup or treats confirmation as signup. Original flow and signup ID must come from authenticated retained input; the owner separately proves submitted-cookie possession, parent and live factor. Preparation, Apply and final checks share the sole Work and its locks.

func ReserveMFAPasskeyPreAuth

func ReserveMFAPasskeyPreAuth(ctx context.Context, w kernel.Work, owner kernel.MFACompletionContributor, command identity.Command, c Config, original session.PreAuthTransaction) error

ReserveMFAPasskeyPreAuth reserves the original pending passkey browser for this exact protected TOTP completion. Acquire current account/credential and factor locks first, matching native passkey assertion order; do not take a browser share lock earlier in the same Work and then upgrade it. The native owner must authenticate original assertion/child/browser custody first and propagate every error. Only live Apply with provisionally consumed child and matching original-primary session metadata is admitted; preparation denies. This uses the existing pre-auth state machine and original timeline, not a new replay authority, transaction or authentication proof.

func ReservePreAuth

func ReservePreAuth[R SessionRows](ctx context.Context, q PreAuthWriter[R], c Config, record session.PreAuthTransaction, use PreAuthUse) error

ReservePreAuth changes issued to reserved exactly once under an update lock, binding the frozen command/fingerprint/generation. It does not authenticate or consume the flow. Commit/recovery is the existing coordinator's owner; expiration, retries and connection loss never release or renew a reservation.

func ValidateAnonymousUpgradeSessionIntent

func ValidateAnonymousUpgradeSessionIntent(command identity.Command, guest, permanent session.Session) error

ValidateAnonymousUpgradeSessionIntent compares complete retained records to their exact closed command commitments without IO, parsing or freshness renewal. Unknown fields in these two owned namespaces deny. Target credential and guest possession/current authority must still be checked by their native owners. This cannot reconstruct records, authenticate or authorize issuance.

Types

type AnonymousAdmissionConfig

type AnonymousAdmissionConfig struct {
	GlobalAuthorityID, PolicyNamespace, Audience string
}

AnonymousAdmissionConfig selects the actual directory, unprivileged policy namespace and session audience. It contains no credential/method pairing: an anonymous principal has no verified credential. Configuration is trusted composition, not request input, and never grants policy permission itself.

type AnonymousDisposalEffect

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

AnonymousDisposalEffect terminally revokes all of this anonymous user's sessions and families in the existing delete command's sole Work. It owns no transaction, callbacks or goroutines. The actual kernel disposal must already have applied, and the exact original source must still be active/unexpired. Immutable composition supports independent concurrent invocations.

func NewAnonymousDisposalEffect

func NewAnonymousDisposalEffect(c Config) (*AnonymousDisposalEffect, error)

NewAnonymousDisposalEffect validates trusted schema/budget without IO. Install AnonymousDisposalMigrationSource in the session and kernel owners first. A complete bounded set (at most100000 sessions/families) commits or all rolls back; no selected prefix may be reported as successful disposal.

func (*AnonymousDisposalEffect) Apply

Apply verifies exact original source custody and stages complete terminal revocation, including expired active-state siblings and empty families. Non-anonymous sibling records deny rather than erase a permanent identity's sessions. Risk, lifecycle and retention admission remain their owners' work. Returned receipt is provisional and contains no bearer.

func (*AnonymousDisposalEffect) ApplyExpired

ApplyExpired revokes the complete guest set without requiring a live source session. Only the exact trusted service-expiry invocation with an actual provisional kernel disposal is admitted. An empty or already-pruned set is valid; non-anonymous contamination or an excess bound aborts the entire Work. The native owner supplies expiry, service policy and retention fences.

func (*AnonymousDisposalEffect) Check

Check verifies terminal source/all-sibling/family state in the same final invocation, preserving original lifetime and admission deadline. It does not read a revoked source as current authentication or reopen a session.

func (*AnonymousDisposalEffect) CheckExpired

CheckExpired fences the absence of every active guest session and family in the original service admission window. No expired or invented source session is authenticated, and no observation deadline is renewed.

func (*AnonymousDisposalEffect) Format

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

func (*AnonymousDisposalEffect) MarshalJSON

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

func (*AnonymousDisposalEffect) MarshalText

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

func (*AnonymousDisposalEffect) Recover

Recover reads retained original effect evidence, not prunable live sessions. It neither grants current access nor restores tokens; the existing coordinator must reconcile every owner before declaring the command terminal.

func (*AnonymousDisposalEffect) RecoverExpired

RecoverExpired reads retained service-expiry effects even after every guest session payload is pruned. Absence is participant evidence only: the existing coordinator must reconcile all owners before declaring the original outcome. This returns no bearer and never re-executes cleanup.

type AnonymousDisposalMigrationSource

type AnonymousDisposalMigrationSource struct {
	Schema  string
	Version migrations.Version
}

AnonymousDisposalMigrationSource appends retained session-owned deletion effect evidence after the installed session/anonymous histories. It enables no endpoint, changes no predecessor SQL and offers no destructive downgrade.

func (AnonymousDisposalMigrationSource) Load

Load returns a forward migration without IO; cancellation and invalid schema or version deny. The existing explicit migration runner owns installation.

type AnonymousExpiryMigrationSource

type AnonymousExpiryMigrationSource struct {
	Schema  string
	Version migrations.Version
	Upgrade bool
}

AnonymousExpiryMigrationSource appends service-expiry evidence support after the installed anonymous-disposal history. Upgrade must exactly describe the optional already-installed upgrade suffix; install expiry last among these purpose extensions. The source changes no predecessor bytes or live records. Only service expiry permits absent source IDs and zero revocation counts.

func (AnonymousExpiryMigrationSource) Load

Load returns one forward-only suffix without IO. Installation against the wrong predecessor constraint fails rather than silently adopting its profile. The caller permanently allocates Version after all selected predecessors.

type AnonymousIssuancePredecessor

type AnonymousIssuancePredecessor uint8

AnonymousIssuancePredecessor names the actually installed session-issuance purpose constraint. It selects migration history, never authentication policy.

const (
	// AnonymousAfterBaseIssuance needs no password, OTP or other login method.
	AnonymousAfterBaseIssuance AnonymousIssuancePredecessor = 1
	// AnonymousAfterOTP preserves the installed OTP-only purpose extension.
	AnonymousAfterOTP AnonymousIssuancePredecessor = 2
	// AnonymousAfterPassword preserves the password-signin extension.
	AnonymousAfterPassword AnonymousIssuancePredecessor = 3
	// AnonymousAfterSignup preserves the password-signup extension.
	AnonymousAfterSignup AnonymousIssuancePredecessor = 4
	// AnonymousAfterMagicLink preserves the magic-link extension.
	AnonymousAfterMagicLink AnonymousIssuancePredecessor = 5
	// AnonymousAfterMFA preserves the MFA-before-verification extension.
	AnonymousAfterMFA AnonymousIssuancePredecessor = 6
	// AnonymousAfterVerification preserves the verification extension. MFASignin
	// additionally identifies its optional MFA-before-verification predecessor.
	AnonymousAfterVerification AnonymousIssuancePredecessor = 7
	// AnonymousAfterVerificationMFA preserves verification-first plus MFA.
	AnonymousAfterVerificationMFA AnonymousIssuancePredecessor = 8
)

type AnonymousSigninEffect

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

AnonymousSigninEffect persists the anonymous session in its owning feature's sole kernel Work. It owns no pool, transaction, policy callback or goroutine. The anonymous owner must first admit risk, persist its actual lifecycle/TTL, apply kernel creation and explicitly initialize the guest policy authority. This effect neither bootstraps authority nor makes a verified proof. Immutable configuration permits concurrent calls with independently owned Work values.

func NewAnonymousSigninEffect

func NewAnonymousSigninEffect(c Config, p AnonymousAdmissionConfig) (*AnonymousSigninEffect, error)

NewAnonymousSigninEffect freezes an explicit anonymous-only profile without IO. Install the selected issuance suffix plus actual kernel/directory/policy histories before use. It accepts no application store or transaction engine.

func (*AnonymousSigninEffect) Apply

Apply requires the exact original command and actual staged anonymous kernel record, then writes the initial family/session and retained issuance evidence through the existing session owner. No credential reference is manufactured. Risk, anonymous expiry and all feature-owned effects remain the native anonymous owner's responsibility. Every error must abort Work; success is provisional and never discloses a bearer. The owner must call Check again after later phases before commitment, preserving the original record/epochs.

func (*AnonymousSigninEffect) Check

Check repeats original directory/kernel/policy/session and database-time admission during the same feature's final read-only invocation. It does not replace original epochs, renew freshness, write or restore command custody.

func (*AnonymousSigninEffect) Format

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

func (*AnonymousSigninEffect) MarshalJSON

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

func (*AnonymousSigninEffect) MarshalText

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

func (*AnonymousSigninEffect) Recover

Recover reads immutable original session evidence in the exact native recovery invocation. It grants no current access and returns no bearer/session; missing payload is not rollback. The coordinator reconciles every participant.

type AnonymousSigninMigrationSource

type AnonymousSigninMigrationSource struct {
	Schema              string
	Version             migrations.Version
	Predecessor         AnonymousIssuancePredecessor
	MFASignin           bool
	UsernameSignin      bool
	PhonePasswordSignin bool
	PhoneOTPSignin      bool
}

AnonymousSigninMigrationSource appends the exact anonymous purpose to an explicitly selected installed issuance history. Optional suffix flags describe already installed histories, not mandatory login dependencies. Install last among selected purpose extensions; installing an older suffix afterward is invalid. Version is permanent and later than every supplied history version. No installed SQL, session record or retained issuance digest is rewritten.

func (AnonymousSigninMigrationSource) Load

Load returns one transactional forward suffix without IO. Wrong predecessor selection fails at the named installed constraint, never guesses or adopts another schema profile. The existing migration runner owns locks/commit.

type AnonymousUpgradeEffect

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

AnonymousUpgradeEffect owns all guest-session revocation and exactly one permanent session issuance in the native upgrade owner's sole kernel Work. It owns no transaction, pool, callbacks, background work or authentication. The native owner must authenticate both original sessions, consume fresh target reauthentication and the one-use transition, and apply merge and guest disposal before this effect. Immutable configuration permits concurrent calls with independently owned, serial-use Work values.

func NewAnonymousUpgradeEffect

func NewAnonymousUpgradeEffect(c Config, p IssueAdmissionConfig) (*AnonymousUpgradeEffect, error)

NewAnonymousUpgradeEffect freezes the existing single-factor password owner profile without IO. Install AnonymousUpgradeMigrationSource after the actual anonymous signin/disposal histories; unsupported factors and optional authority deny rather than being omitted. The target's original authentication age and guest's resolved remember policy are preserved, never minted or renewed here.

func (*AnonymousUpgradeEffect) Apply

Apply requires exact original command custody, actual provisional one-use consumption and kernel guest disposal. It revokes every active-state guest session/family (including expired siblings), then persists the complete new permanent session and immutable issuance evidence. Propagate every error to abort all owners. A provisional receipt reveals no credential; Check must run again after downstream waits, and the issuer retains final delivery custody.

func (*AnonymousUpgradeEffect) Check

Check repeats original target authority/session and the earliest unchanged deadline, proves no live guest session/family remains, and compares the exact persisted permanent session. It does not authenticate, refresh proof age or restore a guest. The enclosing native owner also fences its retention, factor, merge, risk and action-specific reauthentication owners before commitment.

func (*AnonymousUpgradeEffect) Format

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

Format redacts deployment/authority correlation.

func (*AnonymousUpgradeEffect) MarshalJSON

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

MarshalJSON rejects configuration disclosure.

func (*AnonymousUpgradeEffect) MarshalText

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

MarshalText rejects configuration disclosure and implicit map keys.

func (*AnonymousUpgradeEffect) Recover

Recover reconciles BOTH retained guest-revocation and permanent-issuance evidence after live payload cleanup. Mixed/missing votes are unknown, not a claim of rollback or commitment. Success grants no current authority, token reconstruction or redelivery; the coordinator must reconcile every owner.

type AnonymousUpgradeMigrationSource

type AnonymousUpgradeMigrationSource struct {
	AnonymousSignin AnonymousSigninMigrationSource
	Version         migrations.Version
}

AnonymousUpgradeMigrationSource appends guest revocation/permanent issuance purposes to already installed anonymous signin and disposal histories. AnonymousSignin describes that installed profile, including optional purpose extensions; it is not executed again. Version must be permanently allocated after both installed histories. No existing rows, SQL or digest domains change.

func (AnonymousUpgradeMigrationSource) Load

Load returns only the transactional forward suffix without IO. A mismatched installed constraint fails rather than silently adopting another history. Install this suffix last among selected issuance-purpose extensions. No destructive downgrade, alternate replay store or cleanup is provided.

type CSRFMigrationSource

type CSRFMigrationSource struct {
	Schema  string
	Version migrations.Version
}

CSRFMigrationSource extends the installed session record constraint to admit digest-only synchronizer state. Schema selects the existing owned namespace; Version is a permanent 1..MaxInt64 slot after MigrationSource in the sole migration history. It rewrites no historical SQL, payload or receipt hash. Apply before enabling CSRF issuance. Old binaries remain valid for tokenless sessions and fail closed on schema-2 records; upgrade all relevant readers and writers before selecting the new profile. Zero is invalid.

func (CSRFMigrationSource) Load

Load returns forward-only transactional SQL without IO. The migrations Runner owns locking, allocation and commitment; cancellation is preserved.

type CleanupCommand

type CleanupCommand struct {
	TenantID      identity.TenantID
	UserID        identity.UserID
	CommandID     identity.CommandID
	CorrelationID string
	Limit         uint32
}

CleanupCommand selects one exact tenant/user partition and at most Limit indexed expiry candidates (1..10000). CommandID is stable across retries; changing scope, correlation or limit under that ID conflicts. It carries no caller-selected time, authentication proof or bearer. Zero is invalid.

type CleanupMigrationSource

type CleanupMigrationSource struct {
	Schema  string
	Version migrations.Version
}

CleanupMigrationSource adds an owner/expiry index and retained cleanup result evidence at a permanent slot after base/rotation history. It never changes existing rows/checksums or supplies a destructive downgrade. Transactional index installation may block writes; budget populated rollout explicitly. Retained results have no session FK and outlive live-payload pruning.

func (CleanupMigrationSource) Load

Load returns one forward migration without IO; zero, invalid or cancelled input fails before composition. Apply through the sole migrations Runner.

type CleanupResult

type CleanupResult struct {
	Command      identity.CommandResult
	Deleted      uint32
	RemainingLag time.Duration
	ObservedAt   time.Time
}

CleanupResult carries a historical command receipt and, on verified success only, its retained deletion count and database-time backlog observation. RemainingLag is zero if no expired payload remained at ObservedAt; locked candidates remain included. It saturates at 8760 hours, is partition-scoped, and is not a claim that a later concurrent refresh/deletion did not change it. No result authenticates a user or permits retry of an uncertain command.

type CleanupService

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

CleanupService owns explicit bounded expiry commands, not a scheduler, pool, transaction, journal or background goroutine. Calls are concurrency-safe. Keep borrowed dependencies alive until all calls finish. Install the complete session/rotation and CleanupMigrationSource histories before use.

func NewCleanupService

func NewCleanupService(pool *database.Pool, c CleanupServiceConfig) (*CleanupService, error)

NewCleanupService freezes trusted composition without IO. Natural expiry prunes live payloads only; it never increments session/family/user authority or deletes retained command, proof-use, rotation or revocation evidence.

func (*CleanupService) CleanupExpired

func (s *CleanupService) CleanupExpired(ctx context.Context, input CleanupCommand) (out CleanupResult, err error)

CleanupExpired authorizes before reservation and commits one bounded locked primary-time cleanup, retained result, required audit and lifecycle together. An exact retry observes its original result instead of selecting more rows. SKIP LOCKED leaves concurrent refresh/cleanup candidates for a later command. Earlier caller deadlines win. Cancellation/panic/failed acknowledgement after reservation does not prove rollback; recover the returned safe scope instead.

func (CleanupService) Format

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

Format redacts runtime policy and service custody.

func (CleanupService) MarshalJSON

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

MarshalJSON denies implicit runtime export.

func (*CleanupService) RecoverCleanupCommand

RecoverCleanupCommand returns the original historical outcome/count/lag under current trusted service access policy, without selecting a new batch. Exact tenant/user/actor/operation scope is required; RecordID and LinkMode are empty. Missing/denied commands reveal nothing. Live leases are not renewed; expired pending reconciles only through the kernel's frozen participant evidence.

type CleanupServiceConfig

type CleanupServiceConfig struct {
	Execution    IssueExecutorConfig
	ActorID      identity.ActorID
	MaximumBatch uint32
}

CleanupServiceConfig enables native expiry maintenance under current policy for a trusted service ActorID, never an input-selected actor. MaximumBatch is 1..10000; per-call Limit cannot exceed it. Execution borrows the existing native primary/kernel/audit/lifecycle dependencies. Zero is invalid.

func (CleanupServiceConfig) Format

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

Format redacts borrowed configuration.

func (CleanupServiceConfig) MarshalJSON

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

MarshalJSON denies implicit configuration export.

type Config

type Config struct {
	Schema          string
	MaximumDuration time.Duration
}

Config selects the migrated dedicated Schema and a finite primary read budget, positive and at most one minute. An earlier caller deadline wins. Zero is invalid. Schema must match MigrationSource permanently.

type CookieRevokeOneExecutor

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

CookieRevokeOneExecutor selects original-transaction CSRF enforcement for cookie logout. It borrows the primary pool and trusted dependencies, copies configuration/eligible keys, starts no goroutines and is concurrency-safe. Each call registers a private native participant with ephemeral token custody; no shared request state, context payload, durable raw token or second command owner exists. The existing coordinator owns reservation, mutation and effects. Zero is invalid. Close borrowed dependencies only after all calls finish.

func NewCookieRevokeOneExecutor

func NewCookieRevokeOneExecutor(pool *database.Pool, c RevokeOneExecutorConfig, keys []session.CSRFKey) (*CookieRevokeOneExecutor, error)

NewCookieRevokeOneExecutor validates the same owned native composition as NewRevokeOneExecutor, with 1..4 eligible dedicated keys of distinct positive versions. It performs no IO. Install the same migrations first. Key retirement and overlap are explicit deployment policy; no alternate version is tried. Caller-owned maps, policy structs and the key slice are copied. Dependency implementations must remain bounded/concurrency-safe; do not mutate inputs during construction. The factory accepts no consumer transaction or store.

func (*CookieRevokeOneExecutor) ExecuteRevokeOne

ExecuteRevokeOne rejects direct/legacy dispatch. Browser callers must use the explicit strict method; this never reserves, performs IO or clears cookies.

func (*CookieRevokeOneExecutor) ExecuteRevokeOneWithCSRF

func (e *CookieRevokeOneExecutor) ExecuteRevokeOneWithCSRF(ctx context.Context, request session.RevokeOneRequest) (identity.CommandResult, error)

ExecuteRevokeOneWithCSRF revalidates original opaque caller custody and its exact state-named key before reservation. Within the original registered native invocation, it acquires ordered source/target mutation fences and checks the token against the exact active primary session/family before mutation. All errors abort; audit/outbox and terminal recovery use the existing coordinator. No token/key is persisted, revealed or refreshed. Cancellation, exclusive original admission expiry, panic and ambiguous outcome semantics match ExecuteRevokeOne on the legacy executor. Matching terminal replay is historical metadata, not fresh execution permission or cookie delivery.

func (CookieRevokeOneExecutor) Format

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

Format prevents traversal of trusted dependencies and secret configuration.

func (CookieRevokeOneExecutor) MarshalJSON

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

MarshalJSON rejects implicit runtime/secret export.

func (CookieRevokeOneExecutor) MarshalText

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

MarshalText rejects implicit runtime/secret text export.

func (*CookieRevokeOneExecutor) RecoverRevokeOneCommand

RecoverRevokeOneCommand observes the original receipt under current trusted access policy, without token custody or execution permission. It uses the same retained descriptor/command profile after restart; it never reserves/revokes.

type CredentialContinuationMigrationSource

type CredentialContinuationMigrationSource struct {
	Schema  string
	Version migrations.Version
}

CredentialContinuationMigrationSource admits continued password records in schemas 5/6. Allocate a permanent Version after OTPMigrationSource in the same owned Schema and sole migration history. Upgrade all relevant readers/writers before selecting continuation: old binaries reject these records. Existing rows and historical SQL/checksums are unchanged. This migration grants no authentication or password-change authority. Zero configuration is invalid.

func (CredentialContinuationMigrationSource) Load

Load returns one transactional forward migration without IO. The migration runner owns locking and commitment; malformed populated rows abort the entire upgrade. Context cancellation is preserved; configuration errors are redacted.

type EmailVerificationMFASigninMigrationSource

type EmailVerificationMFASigninMigrationSource struct {
	Schema  string
	Version migrations.Version
}

EmailVerificationMFASigninMigrationSource extends issuance after the installed verification-first v7 history. It preserves that history and all populated verification rows while adding the native factor-completion purposes under a new v8 constraint. Install MFAMigrationSource's session-record suffix first. This is not the historical MFA-before-verification lineage; never substitute it for an applied migration. The caller allocates an unused Version and the existing runner owns locks, validation and transactional commitment.

func (EmailVerificationMFASigninMigrationSource) Load

Load constructs one forward-only purpose extension without IO or callbacks. Missing predecessor constraints fail during apply; no baselining or IF EXISTS fallback is generated. Invalid configuration and cancellation retain their existing native migration error semantics.

type EmailVerificationSigninEffect

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

EmailVerificationSigninEffect owns session persistence under the selected post-verification native workflow's sole coordinator. It starts no transaction, callback, pool, goroutine or second replay journal. Its projections establish no authentication: the native owner must prove original signup/browser custody, fresh committed verification and current risk/MFA policy before admission. Each concurrent call requires an independent serial Work.

func NewEmailVerificationSigninEffect

func NewEmailVerificationSigninEffect(c Config, p MagicLinkAdmissionConfig) (*EmailVerificationSigninEffect, error)

NewEmailVerificationSigninEffect freezes bounded email-possession session ownership without IO. Install the email-grant session record history and EmailVerificationSigninMigrationSource before selecting this effect. No application-written stores or alternate transaction owners are accepted.

func (*EmailVerificationSigninEffect) Apply

Apply stages the exact complete session, new family and retained issuance in Work. RecordID binds the separately committed confirmation command; the native owner supplies its authenticated original receipt, never a recovered receipt as login permission. The retained issuance has a unique confirmation-parent constraint, so concurrent children cannot both commit. Propagate every error to abort Work. A provisional result grants no token or synchronizer disclosure. Final native admission must repeat CheckCurrent after downstream waits.

func (*EmailVerificationSigninEffect) CheckCurrent

CheckCurrent fences the exact registered command, parent/recipient versions, current primary directory/authorization and original authentication deadline. It is valid in Apply and final admission. It does not authenticate a caller, establish fresh verification or replace the native risk/factor checks. The same authority vector is compared, never refreshed after a lock wait.

func (*EmailVerificationSigninEffect) Format

Format redacts deployment and policy correlation.

func (*EmailVerificationSigninEffect) MarshalJSON

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

MarshalJSON rejects implicit configuration export.

func (*EmailVerificationSigninEffect) MarshalText

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

MarshalText rejects implicit configuration export and map keys.

func (*EmailVerificationSigninEffect) Recover

Recover votes from original retained session issuance only. A committed vote is historical metadata, never a fresh signin or permission to reveal a token. Cleanup of the live session cannot erase this command's retained evidence.

type EmailVerificationSigninMigrationSource

type EmailVerificationSigninMigrationSource struct {
	Schema  string
	Version migrations.Version
	// MFASignin describes the already-installed v6 purpose constraint, not an
	// authentication-policy toggle. False preserves the v5 purpose set exactly.
	MFASignin bool
}

EmailVerificationSigninMigrationSource extends retained session issuance after MagicLinkSigninMigrationSource, or after MFASigninMigrationSource when MFASignin is true. Select the installed predecessor once and retain that immutable history; installing an older purpose migration afterward is invalid. Allocate a permanent unused Version in the same schema. Existing rows and commitment domains are unchanged. This creates no additional replay store.

func (EmailVerificationSigninMigrationSource) Load

Load constructs one forward-only transactional populated upgrade without IO. The runner owns locks, validation and commit. Each separately committed verification can parent at most one signin within its tenant. A nullable parent preserves all old issuances without inventing historical lineage.

type FamilyReplayGuard

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

FamilyReplayGuard detects retired bearer reuse and atomically revokes its exact family through the sole command owner. It authenticates no principal, issues no credential and owns no transaction, journal or goroutine. It is concurrency-safe; callers close the borrowed primary pool after calls finish.

func NewFamilyReplayGuard

func NewFamilyReplayGuard(pool *database.Pool, c FamilyReplayGuardConfig) (*FamilyReplayGuard, error)

NewFamilyReplayGuard freezes explicit composition without IO. Install all native rotation/family, kernel, audit and lifecycle migrations first. Core hashing validates retained keys; no application store or proof issuer is used.

func (*FamilyReplayGuard) CheckReplay

func (g *FamilyReplayGuard) CheckReplay(ctx context.Context, input FamilyReplayInput) (out identity.CommandResult, err error)

CheckReplay hashes only through the core token primitive and derives owner, family and original absolute expiry from primary retired lineage. A zero result with nil error means no eligible replay was observed; it is neither authentication nor proof of noncommit of a previously submitted command. Expired/absent/foreign tokens create no command. Retain a returned Binding for RecoverReplayCommand when acknowledgement is uncertain or the token expires.

Eligible replay uses current service-actor policy and a full-intent command collision fence. Locked lineage, expiry, family CAS, protected audit and lifecycle commit together; retries reveal no token or renew any authority. Cancellation/panic after entry cannot prove rollback. Earlier caller deadlines win; synchronous detached kernel cleanup has its existing bounded budgets.

func (FamilyReplayGuard) Format

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

Format prevents diagnostic traversal of retained key and bearer custody.

func (FamilyReplayGuard) MarshalJSON

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

MarshalJSON denies implicit runtime or bearer configuration export.

func (*FamilyReplayGuard) RecoverReplayCommand

RecoverReplayCommand returns historical family-revocation metadata under current trusted result-access policy without the original bearer. Supply every original safe scope field and an independently authenticated service caller. It never grants session authority, reserves missing commands or renews leases.

type FamilyReplayGuardConfig

type FamilyReplayGuardConfig struct {
	Execution  IssueExecutorConfig
	LookupKeys []session.DigestKey
	ActorID    identity.ActorID
}

FamilyReplayGuardConfig explicitly enables protective family revocation. LookupKeys are the same 1..4 retained core keys used for session validation. ActorID is a trusted configured service-account identity, never the token's human owner. Execution selects current policy and existing native composition. Dependencies are borrowed and must outlive calls; zero is invalid.

func (FamilyReplayGuardConfig) Format

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

Format redacts retained key and policy configuration.

func (FamilyReplayGuardConfig) MarshalJSON

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

MarshalJSON denies implicit configuration export.

type FamilyReplayInput

type FamilyReplayInput struct {
	TenantID      identity.TenantID
	Token         session.Token
	CommandID     identity.CommandID
	CorrelationID string
}

FamilyReplayInput supplies a parsed opaque bearer, exact tenant and stable command identity. It selects no owner or family. HTTP must enforce origin/CSRF and selected transport policy before this explicit mutation, not during Get.

func (FamilyReplayInput) Format

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

Format redacts bearer custody and input scope.

func (FamilyReplayInput) MarshalJSON

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

MarshalJSON denies implicit bearer input export.

type IdentifierAdmissionConfig

type IdentifierAdmissionConfig struct {
	GlobalAuthorityID, PolicyNamespace, Audience, AuthenticationMethod string
	CredentialKind                                                     identity.CredentialKind
	CredentialOwner                                                    string
}

IdentifierAdmissionConfig opts the native session repository into protected identifier eligibility checks. All values come from trusted composition, not requests. The configured method/kind/owner pairing must describe the exact supported authentication profile; it never converts method metadata into a verified proof. Organization, factor and passkey profiles currently deny, rather than omit their required owner checks. Zero is invalid. This is not an access policy, credential verifier or session issuance configuration.

func (IdentifierAdmissionConfig) Format

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

Format hides correlated deployment/profile configuration.

func (IdentifierAdmissionConfig) MarshalJSON

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

MarshalJSON rejects accidental correlated configuration export.

func (IdentifierAdmissionConfig) Validate

func (profile IdentifierAdmissionConfig) Validate() error

Validate checks the trusted native admission profile without IO. It creates no proof, authority or permission. Zero/invalid fields return a redacted InvalidInput error; immutable concurrent reads are safe.

type IssueAdmissionConfig

type IssueAdmissionConfig IdentifierAdmissionConfig

IssueAdmissionConfig freezes the single-factor self-service issuance profile. Fields have IdentifierAdmissionConfig's trusted owner/scope semantics. This profile cannot omit organization, factor or passkey checks: those variants deny until their native owners are composed. No callback, verifier or pool transaction is supplied. Zero is invalid; configuration grants no policy Allow.

func (IssueAdmissionConfig) Format

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

Format redacts correlated deployment configuration.

func (IssueAdmissionConfig) MarshalJSON

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

MarshalJSON rejects implicit correlated configuration export.

type IssueExecutor

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

IssueExecutor owns native session, kernel, audit and lifecycle composition. It borrows the primary pool and immutable policy/authenticator dependencies; the caller closes them after all calls finish. It starts no goroutines and is concurrency-safe. It never owns or reveals a bearer. Zero is invalid.

func NewIssueExecutor

func NewIssueExecutor(pool *database.Pool, c IssueExecutorConfig) (*IssueExecutor, error)

NewIssueExecutor composes the sole authoritative command owner without IO. Install kernel, proof-use, authorization, session, issuance, audit and outbox migrations first. Missing infrastructure fails closed during execution; this constructor never applies migrations or registers policy grants. QueryPolicy is fixed to this same current service/clock/revision for receipt recovery. Existing native repository constructors retain their contributor-only API.

func (*IssueExecutor) ExecuteIssue

func (e *IssueExecutor) ExecuteIssue(ctx context.Context, request session.IssueRequest) (session.IssueExecution, error)

ExecuteIssue validates original opaque admission and current policy before reservation. The kernel compares current owners and final expiry, consumes the original proof and commits session/audit/outbox atomically. Exact terminal replay returns Replayed and cannot trigger bearer delivery. Cancellation or ambiguous execution is not inferred to prove rollback. Earlier deadlines bound execution work, but synchronous detached kernel cleanup may outlive them; each cleanup phase has its own bounded coordinator budget.

func (IssueExecutor) Format

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

Format prevents diagnostic traversal of runtime composition and retained keys.

func (IssueExecutor) MarshalJSON

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

MarshalJSON rejects implicit export of runtime composition.

func (*IssueExecutor) RecoverIssue

func (e *IssueExecutor) RecoverIssue(ctx context.Context, request session.IssueRequest) (session.IssueExecution, error)

RecoverIssue observes/reconciles the exact original request on the primary under current policy. Original expired proof provenance is historical only. It never reserves missing commands, renews leases, executes a session or reveals a bearer. This request-bearing path requires original opaque custody; use RecoverIssueCommand for restart-safe historical metadata reconciliation.

func (*IssueExecutor) RecoverIssueCommand

RecoverIssueCommand reconciles issuance after process restart without the original proof or bearer. Query must retain every original safe scope field; caller comes from trusted current authentication, never decoded client identity. The configured current policy independently authorizes disclosure. Only historical command metadata is returned, never a session, credential, current validity or permission to retry issuance. Missing/denied scope cannot reserve a command. Live pending does not renew its lease; expired pending reconciles only the frozen participants under the sole kernel recovery owner. Incomplete/conflicting evidence fails closed without reconstructing success. Execution work and detached cleanup have the same budgets as ExecuteIssue.

type IssueExecutorConfig

type IssueExecutorConfig struct {
	Repository                           Config
	Profile                              IssueAdmissionConfig
	Coordinator                          kernel.CoordinatorConfig
	Authorization                        authorization.Service
	Clock                                clock.Clock
	PolicyID                             string
	PolicyVersion, AuditRetentionVersion uint64
}

IssueExecutorConfig selects trusted single-factor self-service composition. Coordinator must configure the same final-authentication authority used by the core issuer. PolicyID and positive versions are retained while commands exist. Clock and Authorization must be bounded, concurrency-safe dependencies. Repository/Profile retain their native constructor semantics. No transaction, registry, domain store or consumer workflow is accepted. Zero is invalid.

func (IssueExecutorConfig) Format

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

Format redacts secret configuration for every formatting verb.

func (IssueExecutorConfig) MarshalJSON

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

MarshalJSON rejects implicit export of configuration and retained keys.

type IssueMigrationSource

type IssueMigrationSource struct {
	Base    RevocationMigrationSource
	Version migrations.Version
}

IssueMigrationSource appends immutable issuance evidence to the unchanged base/revocation history. Version is a permanent single-history allocation after Base.Version, at most MaxInt64. Kernel proof-use migrations must also be composed before protected issuance. Load performs no IO; no destructive down migration or payload cleanup is provided. Do not renumber applied versions.

func (IssueMigrationSource) Load

Load returns independently owned history and the forward-only issuance table.

type ListMigrationSource

type ListMigrationSource struct {
	Schema  string
	Version migrations.Version
}

ListMigrationSource is the forward-only, independently composed audience-page index. Schema must match the installed base; Version is its permanently allocated 1..MaxInt64 history slot after the base install. Load performs no IO. Install through the sole migrations Runner: the transactional index build can block session writes until complete, so size and schedule populated deployments explicitly. No record, base checksum or authority is rewritten; no destructive rollback is provided. Calls are safe concurrently and return owned migrations.

func (ListMigrationSource) Load

Load returns the bounded-query supporting index; nil or cancelled context and invalid schema/version fail before composition. Duplicate/unmanaged indexes fail at install rather than silently being adopted.

type ListServiceConfig

type ListServiceConfig struct {
	Sessions SessionServiceConfig
	Listing  session.ListConfig
}

ListServiceConfig composes the owned primary authentication reader and page reader with the existing authorization engine. Sessions owns the sole schema, audience, clock and authority profile. Listing selects an explicit policy revision and whole-call budget; its budget must cover the repository read budget. Configuration/dependencies must remain immutable during calls.

func (ListServiceConfig) Format

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

Format redacts keys, authority and policy configuration.

func (ListServiceConfig) MarshalJSON

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

MarshalJSON denies implicit configuration export.

type MFADisableSessionMigrationSource

type MFADisableSessionMigrationSource struct {
	Schema  string
	Version migrations.Version
}

MFADisableSessionMigrationSource appends the exact disable disposition purpose without changing installed regeneration/update SQL or retained result bytes.

func (MFADisableSessionMigrationSource) Load

Load returns one forward-only transactional extension without IO. Base disposition and factor-update extensions must already be installed.

type MFAFactorUpdateSessionMigrationSource

type MFAFactorUpdateSessionMigrationSource struct {
	Schema  string
	Version migrations.Version
}

MFAFactorUpdateSessionMigrationSource extends the existing native disposition table's closed purpose set for separately selected factor-update Work. The original whole-session effects history must already be installed. Existing evidence bytes and populated session records remain unchanged.

func (MFAFactorUpdateSessionMigrationSource) Load

Load returns one forward-only transactional extension without IO. The same schema/version/context validation as the original native history applies. This source is not a replacement bootstrap and grants no session authority.

type MFAMagicLinkSessionServiceConfig

type MFAMagicLinkSessionServiceConfig struct {
	Repository Config
	Profile    MagicLinkAdmissionConfig
	Validation session.ServiceConfig
}

MFAMagicLinkSessionServiceConfig explicitly selects original magic-link plus confirmed TOTP or recovery-code authentication. Recovery consumption is historical, not a requirement for another unused code. Single-factor factories remain disjoint. The primary pool outlives calls; install directory, authorization, MFA/TOTP and complete session histories. Validation retains its owned clock/key/budgets.

func (MFAMagicLinkSessionServiceConfig) Format

Format redacts deployment and key configuration.

func (MFAMagicLinkSessionServiceConfig) MarshalJSON

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

MarshalJSON rejects implicit correlated configuration export.

func (MFAMagicLinkSessionServiceConfig) MarshalText

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

MarshalText rejects implicit export and map-key disclosure.

type MFAMigrationSource

type MFAMigrationSource struct {
	Schema  string
	Version migrations.Version
}

MFAMigrationSource adds complete magic-link/TOTP record schemas9/10 after MagicLinkMigrationSource in the same owned history. Allocate Version once. Upgrade all readers before selecting this profile; older binaries deny it. Legacy records, historical SQL and issuance evidence are not rewritten. This source does not authenticate factors or enable native session issuance.

func (MFAMigrationSource) Load

Load returns one forward-only transactional constraint extension without IO. The existing runner owns locking, populated-state validation and atomic installation. Invalid configuration is redacted; cancellation is preserved.

type MFAOTPCompletionEffect

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

MFAOTPCompletionEffect persists an original-password session only after actual OTP and child checks and the shared MFA transition in this same Work. It owns no transaction, comparison, pool, goroutine or callback. Configuration remains immutable and calls borrow independent serial native Work handles.

func NewMFAPasswordOTPCompletionEffect

func NewMFAPasswordOTPCompletionEffect(c Config, p IdentifierAdmissionConfig) (*MFAOTPCompletionEffect, error)

NewMFAPasswordOTPCompletionEffect selects the closed password/secondary-OTP profile without IO, migration, authentication or issuance. Install selected OTP/factor/continuation, password-MFA session and issuance histories first. Original password/browser, current credential/policy and actual same-Work OTP/child consumption remain the native MFA service's responsibilities.

func (*MFAOTPCompletionEffect) Apply

Apply binds complete original primary/child/factor/remember provenance to actual recorded consuming OTP and continuation custody. Metadata or a TOTP/ recovery handle cannot substitute for that same-Work proof. All current authority/time fences repeat around writes; errors roll back session, OTP, child, shared attempt, risk, audit and lifecycle through the sole coordinator.

func (*MFAOTPCompletionEffect) Format

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

Format prevents diagnostic traversal of native configuration.

func (*MFAOTPCompletionEffect) MarshalJSON

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

MarshalJSON denies implicit configuration export.

func (*MFAOTPCompletionEffect) MarshalText

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

MarshalText denies implicit textual configuration export.

func (*MFAOTPCompletionEffect) Recover

Recover votes only from the exact historical OTP-specific issuance identity; it never compares, consumes, generates or redelivers a credential. The sole coordinator reconciles it with all original participants and the journal.

type MFAOTPRecordMigrationSource

type MFAOTPRecordMigrationSource struct {
	Schema  string
	Version migrations.Version
}

MFAOTPRecordMigrationSource appends closed secondary OTP record schemas17/18 for magic-link primary and19/20 for password primary after MFA recovery record history. Allocate Version permanently and upgrade readers before selection. Old TOTP/recovery checks and populated records remain unchanged. This selects storage only; actual native OTP/child/factor checks still own authentication.

func (MFAOTPRecordMigrationSource) Load

Load returns one forward-only transactional constraint extension without IO. Existing runner locking, cancellation and fail-closed validation are retained.

type MFAPasskeySessionAdmission

type MFAPasskeySessionAdmission struct {
	Profile   PasskeyAdmissionConfig
	Authority MFAPasskeySessionAuthority
}

MFAPasskeySessionAdmission selects the same trusted RP/mapping owner for combined session reading and revocation. It grants no authentication and cannot replace the native MFA owner's exact current factor checks.

func (MFAPasskeySessionAdmission) Format

Format redacts borrowed authority and deployment configuration.

func (MFAPasskeySessionAdmission) MarshalJSON

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

MarshalJSON rejects implicit correlated configuration disclosure.

type MFAPasskeySessionAuthority

type MFAPasskeySessionAuthority interface {
	ObserveMFAPasskeySession(context.Context, string, session.Session) (MFAPasskeySessionAuthorityObservation, error)
	RequireMFAPasskeySession(context.Context, kernel.Work, kernel.FeatureExecutionContributor, string, session.Session) error
}

MFAPasskeySessionAuthority is the consumer-owned RP/credential mapping port for completed passkey plus confirmed TOTP sessions. It is deliberately separate from PasskeySessionAuthority: enrolled TOTP must not be described as known-empty MFA. The MFA owner independently verifies the exact confirmed enrollment and account factor generation. Observe reads current primary mapping evidence; Require locks and compares the original mapping in the exact native completion or revocation owner's Work. Both methods honor ctx, and Require's caller must hold its actual factor fence before mapping locks, matching the native passkey signin/enrollment lock order. deny missing/changed authority and retain no Work, callbacks or goroutines. Neither authenticates an assertion/factor, mutates, commits or issues tokens.

type MFAPasskeySessionAuthorityObservation

type MFAPasskeySessionAuthorityObservation struct {
	PasskeyVersion            uint64
	ReadStartedAt, ValidUntil time.Time
}

MFAPasskeySessionAuthorityObservation is current primary mapping evidence, not authentication. PasskeyVersion is positive. ReadStartedAt precedes all contributing owner IO and ValidUntil is exclusive, no more than20s later. Copies, retries and promotion cannot reset this original evidence window. Factor authority is intentionally absent: the MFA owner supplies it directly.

type MFAPasskeySessionServiceConfig

type MFAPasskeySessionServiceConfig struct {
	Repository Config
	Profile    PasskeyAdmissionConfig
	Validation session.ServiceConfig
	Authority  MFAPasskeySessionAuthority
}

MFAPasskeySessionServiceConfig selects the original RP, borrowed native mapping owner and existing session/kernel/policy/MFA primary readers. Pool and Authority must outlive calls. Validation owns its clock/key/budget and immutable cache envelope policy. No application domain store is accepted.

func (MFAPasskeySessionServiceConfig) Format

Format redacts keys and correlated deployment configuration.

func (MFAPasskeySessionServiceConfig) MarshalJSON

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

MarshalJSON rejects implicit borrowed-authority and key disclosure.

type MFAPasskeyTOTPCompletionEffect

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

MFAPasskeyTOTPCompletionEffect selects original passkey plus recorded native TOTP completion. It retains the existing session mutation/recovery owner; it is not a factor verifier, assertion authenticator or public login service. No pool, transaction, callback, goroutine or borrowed Work is retained.

func NewMFAPasskeyTOTPCompletionEffect

func NewMFAPasskeyTOTPCompletionEffect(c Config, p MFAPasskeySessionAdmission) (*MFAPasskeyTOTPCompletionEffect, error)

NewMFAPasskeyTOTPCompletionEffect freezes an explicit RP/mapping selection. The actual native factor owner must authenticate original assertion/browser/ child, current policy, directory and credential. Acquire factor authority before RP mapping locks, matching native passkey signin/enrollment. Apply receives recorded factor custody and cannot manufacture these proofs. Install the selected MFA/session histories before use. The mapping owner is borrowed and must outlive calls; construction performs no IO.

func (*MFAPasskeyTOTPCompletionEffect) Apply

Apply persists only the unchanged passkey/TOTP session whose actual native replay/continuation completion was recorded on this same live Work. Projected metadata or a foreign/returned handle cannot substitute. Original primary time, expiry and Remember are immutable; no recipient/email proof is assumed. All errors abort the sole transaction with child/factor/session/audit effects.

func (*MFAPasskeyTOTPCompletionEffect) Check

Check must run in the same original owner's CheckFeatureCommit after later audit/outbox waits. It repeats current directory/credential/policy/RP admission, exact stored session and original proof freshness. Locks taken by the actual factor completion remain held; it never repeats factor comparison/consumption, adopts newer epochs or renews a credential or evidence deadline.

func (*MFAPasskeyTOTPCompletionEffect) Format

Format redacts borrowed authority and correlated deployment configuration.

func (*MFAPasskeyTOTPCompletionEffect) MarshalJSON

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

MarshalJSON rejects implicit correlated configuration disclosure.

func (*MFAPasskeyTOTPCompletionEffect) MarshalText

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

MarshalText rejects implicit configuration export and map-key disclosure.

func (*MFAPasskeyTOTPCompletionEffect) Recover

Recover contributes only the original retained session-issuance vote in the exact registered owner's recovery Work. It never repeats factor verification, authenticates a session, reconstructs credentials or renews a challenge.

type MFARecoveryCompletionEffect

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

MFARecoveryCompletionEffect persists original-primary sessions only after the actual recovery-code burn and continuation completion in this same Work. Configuration is immutable; it owns no transaction, pool, callback or goroutine. This is a native effect, not a public recovery-code authentication service.

func NewMFAPasswordRecoveryCompletionEffect

func NewMFAPasswordRecoveryCompletionEffect(c Config, p IdentifierAdmissionConfig) (*MFARecoveryCompletionEffect, error)

NewMFAPasswordRecoveryCompletionEffect selects original password-primary and credential custody instead of magic-link authority. It never compares a password or converts metadata into proof. Installation, ownership and bounded execution follow NewMFARecoveryCompletionEffect; configuration performs no IO.

func NewMFARecoveryCompletionEffect

func NewMFARecoveryCompletionEffect(c Config, p MagicLinkAdmissionConfig) (*MFARecoveryCompletionEffect, error)

NewMFARecoveryCompletionEffect selects genuine magic-link-primary/recovery issuance without IO. Install MFARecoveryMigrationSource and MFA issuance history after predecessors. The native owner must independently authenticate original primary/browser/child and current MFA policy before recording a burn.

func (*MFARecoveryCompletionEffect) Apply

Apply requires actual same-invocation recorded consumption, original primary and remember/factor/set provenance, current directory/credential/policy fences and remaining issuance lifetime. Projection-only or TOTP custody cannot substitute the handle. Burn, child, session, risk, audit and lifecycle commit or roll back through the sole coordinator. Return every error to abort.

func (*MFARecoveryCompletionEffect) Format

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

Format prevents traversal into deployment configuration.

func (*MFARecoveryCompletionEffect) MarshalJSON

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

MarshalJSON rejects implicit configuration export.

func (*MFARecoveryCompletionEffect) MarshalText

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

MarshalText rejects implicit export and map-key disclosure.

func (*MFARecoveryCompletionEffect) Recover

Recover votes only from original method-specific retained issuance evidence. It needs no current code, bearer or live session and cannot redeliver or repeat authentication. The coordinator reconciles the vote with the original journal and other participants; uncertain or unavailable evidence remains unknown.

type MFARecoveryMigrationSource

type MFARecoveryMigrationSource struct {
	Schema  string
	Version migrations.Version
}

MFARecoveryMigrationSource adds closed recovery-code session schemas13/14 (magic-link primary) and15/16 (password primary) after PasswordMFAMigrationSource in the same owned history. Allocate Version permanently and upgrade readers before selecting recovery sessions; old binaries reject the new profiles. Existing rows, historical migration SQL and issuance evidence are unchanged. Installing this source authenticates no code and creates no session authority.

func (MFARecoveryMigrationSource) Load

Load returns one transactional forward constraint extension without IO. The existing runner owns locking and populated-state validation; malformed current state fails installation atomically. Cancellation remains observable.

type MFARecoverySessionEffect

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

MFARecoverySessionEffect owns all-subject session revocation for exact native recovery regeneration Work. It owns no pool, transaction, cache or goroutine. The native MFA owner must have authenticated the source and consumed its fresh factor proof in this same Work before Apply. This never grants continuing access to a deliberately revoked source or issues replacement credentials.

func NewMFADisableSessionEffect

func NewMFADisableSessionEffect(c Config, p IdentifierAdmissionConfig) (*MFARecoverySessionEffect, error)

NewMFADisableSessionEffect selects exact disable-purpose disposition ownership. It does not accept update, regeneration or administrator-reset scope. Install MFADisableSessionMigrationSource after the existing disposition prefix.

func NewMFAFactorUpdateSessionEffect

func NewMFAFactorUpdateSessionEffect(c Config, p IdentifierAdmissionConfig) (*MFARecoverySessionEffect, error)

NewMFAFactorUpdateSessionEffect selects the same native session disposition owner for exact factor-update Work instead of recovery regeneration. It does not select regeneration, accept an arbitrary action or grant continuing session authority. Install MFAFactorUpdateSessionMigrationSource after the existing disposition history. All inherited caps and rollback rules apply.

func NewMFARecoverySessionEffect

func NewMFARecoverySessionEffect(c Config, p IdentifierAdmissionConfig) (*MFARecoverySessionEffect, error)

NewMFARecoverySessionEffect freezes native password/password-MFA ownership without IO. The whole-set cap is1024 active sessions; excess denies and rolls back every effect. Install MFARecoverySessionMigrationSource before use.

func NewMFATOTPReplacementSessionEffect

func NewMFATOTPReplacementSessionEffect(c Config, p IdentifierAdmissionConfig) (*MFARecoverySessionEffect, error)

NewMFATOTPReplacementSessionEffect selects session revocation only for code-confirmed successor activation. URI and pending initiation cannot use this disposition. Install MFATOTPReplacementSessionMigrationSource first.

func (*MFARecoverySessionEffect) Apply

Apply revokes every active subject session in stable bounded pages and persists original effect evidence atomically. MFA owns the factor-generation successor and proof use; this module alone writes its sessions. The existing coordinator tenant mutex precedes source/share and whole-set/write fences. Every error must abort all pending proof, recovery, session and event changes.

func (*MFARecoverySessionEffect) Check

Check validates this command's deliberate source revocation, retained whole- set evidence and still-current primary directory/credential/policy fences. The native MFA owner independently checks its exact factor successor and consumed proof. This is commit eligibility, never ongoing authentication.

func (*MFARecoverySessionEffect) Format

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

Format redacts profile and schema configuration.

func (*MFARecoverySessionEffect) MarshalJSON

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

MarshalJSON rejects implicit native configuration export.

func (*MFARecoverySessionEffect) MarshalText

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

MarshalText rejects implicit native configuration export.

func (*MFARecoverySessionEffect) Recover

Recover reads retained original disposition evidence, not today's mutable sessions or a newly inferred revocation. It cannot revoke, authenticate or disclose credentials; every native participant must agree before recovery.

type MFARecoverySessionMigrationSource

type MFARecoverySessionMigrationSource struct {
	Schema  string
	Version migrations.Version
}

MFARecoverySessionMigrationSource installs retained original whole-set session disposition evidence. Schema must match the selected session store. Allocate Version permanently in the selected physical history; no populated session row is changed or backfilled. Original effect evidence remains after session payload cleanup and follows protected command-retention ownership.

func (MFARecoverySessionMigrationSource) Load

Load returns independently owned forward-only transactional SQL without IO. Invalid ownership, nil/canceled context and version overflow return no history.

type MFASigninMigrationSource

type MFASigninMigrationSource struct {
	Schema  string
	Version migrations.Version
}

MFASigninMigrationSource extends the existing retained issuance purpose constraint after MagicLinkSigninMigrationSource. Allocate an unused permanent Version in that same schema/history. It preserves rows and commitment domains and creates no replay table. The closed factor-completion purposes are not proof of authentication; native owners must commit all required factor effects.

func (MFASigninMigrationSource) Load

Load returns one forward-only transactional extension without IO. The existing runner owns locks, populated-state validation and commit. Invalid owner/configuration is redacted and cancellation/deadlines are preserved.

type MFATOTPCompletionEffect

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

MFATOTPCompletionEffect persists an original-primary session only after the actual native TOTP transition in this same Work. It owns no transaction, callback, pool or goroutine. Configuration is immutable; independent calls require separate serial Work handles. It is not a public MFA login service.

func NewMFAPasswordTOTPCompletionEffect

func NewMFAPasswordTOTPCompletionEffect(c Config, p IdentifierAdmissionConfig) (*MFATOTPCompletionEffect, error)

NewMFAPasswordTOTPCompletionEffect selects genuine password-primary/TOTP issuance. Install PasswordMFAMigrationSource after the existing session MFA histories. The original signed non-final password primary, child/browser possession and current credential must be authenticated by the native owner; this effect never compares passwords or substitutes metadata for factor proof. Configuration and transaction ownership follow NewMFATOTPCompletionEffect.

func NewMFAPhonePasswordTOTPCompletionEffect

func NewMFAPhonePasswordTOTPCompletionEffect(c Config, p IdentifierAdmissionConfig) (*MFATOTPCompletionEffect, error)

NewMFAPhonePasswordTOTPCompletionEffect explicitly selects verified-phone password-primary plus independent TOTP. It requires the original phone browser purpose and verified phone recipient in the protected Work; email, username, SMS/recovery factors and magic-link origins cannot substitute. Original signed primary, current credential and recorded same-Work TOTP remain mandatory. Configuration, migrations and ownership follow NewMFAPasswordTOTPCompletionEffect.

func NewMFATOTPCompletionEffect

func NewMFATOTPCompletionEffect(c Config, p MagicLinkAdmissionConfig) (*MFATOTPCompletionEffect, error)

NewMFATOTPCompletionEffect freezes the native original magic-link/TOTP profile without IO. Install MFAMigrationSource and MFASigninMigrationSource after their predecessors, with directory, authorization and MFA histories. Current policy, original browser/primary authentication and actual code verification remain mandatory native-owner responsibilities.

func NewMFAVerificationTOTPCompletionEffect

func NewMFAVerificationTOTPCompletionEffect(c Config, p MagicLinkAdmissionConfig) (*MFATOTPCompletionEffect, error)

NewMFAVerificationTOTPCompletionEffect selects separately committed registration-verification provenance, not magic-link/password origin. It shares email-possession session storage but requires its immutable explicit verification-parent scope. The native owner authenticates that parent and original signup browser independently before this transaction can issue.

func (*MFATOTPCompletionEffect) Apply

Apply persists the exact command-bound session after a recorded TOTP completion on this same live native handle. Projection-only factor metadata cannot substitute the handle. The native owner must first authenticate the original primary/browser/child and current MFA policy, take directory/recipient/ authorization fences before factor locks, verify the original opaque code and record replay/continuation. Those fences are rechecked here before writes. This initial profile freezes primary authentication at original continuation issuance; completion cannot renew that time or Remember. No original primary grant or pre-auth flow is consumed again. Every error must abort; all session, factor, child, audit and lifecycle effects depend on the sole coordinator.

func (*MFATOTPCompletionEffect) Format

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

Format redacts correlated deployment configuration for every verb.

func (*MFATOTPCompletionEffect) MarshalJSON

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

MarshalJSON denies implicit configuration disclosure.

func (*MFATOTPCompletionEffect) MarshalText

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

MarshalText denies implicit export and map-key disclosure.

func (*MFATOTPCompletionEffect) Recover

Recover votes only from the original retained issuance tuple during this exact native recovery invocation. It needs no factor code, bearer or current live session payload and cannot execute or redeliver anything. The sole coordinator must reconcile this vote with all other participant outcomes.

type MFATOTPReplacementSessionMigrationSource

type MFATOTPReplacementSessionMigrationSource struct {
	Schema  string
	Version migrations.Version
}

MFATOTPReplacementSessionMigrationSource appends the exact confirmation disposition purpose without rewriting installed regeneration/update/disable histories. Disable remains independently optional; allocate a fixed suffix.

func (MFATOTPReplacementSessionMigrationSource) Load

Load returns one forward-only transactional migration without IO. Existing disposition and factor-update prefixes must already be installed.

type MagicLinkAdmissionConfig

type MagicLinkAdmissionConfig struct{ GlobalAuthorityID, PolicyNamespace, Audience string }

MagicLinkAdmissionConfig selects the trusted global authority, user policy namespace and audience for email-grant sessions. This single-factor profile rejects organization, factor and passkey projections until their actual owners are composed. Zero is invalid and configuration grants no authentication.

func (MagicLinkAdmissionConfig) Format

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

Format redacts correlated deployment configuration for every verb.

func (MagicLinkAdmissionConfig) MarshalJSON

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

MarshalJSON denies implicit correlated deployment export.

type MagicLinkMigrationSource

type MagicLinkMigrationSource struct {
	Schema  string
	Version migrations.Version
}

MagicLinkMigrationSource admits complete original magic-link provenance in schemas7/8 after CredentialContinuationMigrationSource in the same permanent migration history. Upgrade all readers/writers before selecting these records: older binaries reject them. Existing payloads, constraints' legacy semantics and historical checksums remain unchanged. It neither authenticates nor enables session issuance. Zero configuration is invalid; Load performs no IO.

func (MagicLinkMigrationSource) Load

Load returns one transactional forward-only migration. Populated malformed records abort the whole upgrade; the existing runner owns locks and commit. Configuration errors are redacted and caller cancellation is preserved.

type MagicLinkSessionServiceConfig

type MagicLinkSessionServiceConfig struct {
	Repository Config
	Profile    MagicLinkAdmissionConfig
	Validation session.ServiceConfig
}

MagicLinkSessionServiceConfig selects the explicit native stateful magic-link reader. The borrowed primary pool outlives calls; the caller closes it. Install directory/user/identifier/authorization histories and MagicLinkMigrationSource before use. Validation owns key/clock/read budgets. No arbitrary domain store, proof authority, sender or persistent password credential is accepted.

func (MagicLinkSessionServiceConfig) Format

Format redacts key and deployment configuration for every verb.

func (MagicLinkSessionServiceConfig) MarshalJSON

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

MarshalJSON denies implicit key/deployment export.

type MagicLinkSigninEffect

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

MagicLinkSigninEffect persists the original email-grant session and pre-auth use only within the consuming native owner's sole coordinator transaction. It owns no pool, transaction, callback or goroutine. Configuration is immutable; concurrent calls require independent serial Work handles. Zero is invalid. This native seam is neither a proof verifier nor a public login endpoint.

func NewMagicLinkSigninEffect

func NewMagicLinkSigninEffect(c Config, p MagicLinkAdmissionConfig) (*MagicLinkSigninEffect, error)

NewMagicLinkSigninEffect freezes a trusted single-factor email-grant profile without IO. Install MagicLinkSigninMigrationSource after the original retained password-signup issuance history, alongside directory, authorization, session and pre-auth histories. No caller-written store or transaction is accepted.

func (*MagicLinkSigninEffect) Apply

Apply stages the exact command-mapped session, family, pre-auth use and retained issuance evidence after the real capability participant provisionally consumes the original grant in this same Work. The native owner must first authenticate original proof/issuance, pre-auth cookie possession, callback and full intent, and enforce current factor/risk policy. These scalar projections cannot replace those checks. Anonymous command scope is preserved. Original grant/session expiry and current verified recipient are checked again after downstream waits. Every error must propagate to abort Work; provisional success permits no bearer disclosure. The owning CheckFeatureCommit must repeat final temporal/policy admission after any later participant waits before the coordinator commits.

func (*MagicLinkSigninEffect) Format

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

Format hides correlated deployment configuration for every verb.

func (*MagicLinkSigninEffect) MarshalJSON

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

MarshalJSON prevents implicit configuration disclosure.

func (*MagicLinkSigninEffect) MarshalText

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

MarshalText prevents configuration export and map-key disclosure.

func (*MagicLinkSigninEffect) Recover

Recover votes only from retained original issuance evidence during the exact recovery invocation. It neither reveals a bearer nor grants current access; missing payload or expired grant does not prove rollback. The coordinator must reconcile all participant votes before reporting the command outcome.

type MagicLinkSigninMigrationSource

type MagicLinkSigninMigrationSource struct {
	Schema  string
	Version migrations.Version
}

MagicLinkSigninMigrationSource admits consuming email-grant signin in the existing retained session-issuance table after PasswordSignupMigrationSource. Allocate a permanent unused Version in the same owned schema. Existing rows, commitment domains and migration checksums are unchanged. No new replay store or destructive downgrade is introduced. Install before enabling this effect.

func (MagicLinkSigninMigrationSource) Load

Load constructs one bounded forward-only transactional constraint extension. The migration runner owns IO, locking and populated-state validation.

type MigrationSource

type MigrationSource struct {
	Schema  string
	Version migrations.Version
}

MigrationSource owns the adapter's forward-only install. Schema selects an unoccupied dedicated namespace (not public/identity/pg_*); Version is the permanently assigned 1..MaxInt64 version in the composition's single history. Compose this source with the kernel history and the owned migrations Runner; the identity.users table must already exist. Never renumber an applied version. Zero is invalid. Load performs no IO and is safe for concurrent callers.

func (MigrationSource) Load

Load returns independently owned immutable SQL, with no destructive down migration. Existing/unmanaged schema objects fail rather than being adopted. Nil contexts and invalid source values fail; cancellation is preserved.

Example
package main

import (
	"context"
	"fmt"

	"github.com/faustbrian/go-identity/session/postgres"
)

func main() {
	// The owned composition allocates this immutable version after kernel history.
	source := postgres.MigrationSource{Schema: "identity_session", Version: 10}
	history, err := source.Load(context.Background())
	if err != nil {
		panic(err)
	}
	// Loading does not connect, create a ledger or execute SQL.
	fmt.Println(len(history), history[0].Version(), history[0].DownSQL() == "")
}
Output:
1 10 true

type OIDCEndSessionEffect

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

OIDCEndSessionEffect owns exact single-session invalidation inside the native OAuth participant's existing Work. It borrows no transaction or pool and starts no goroutines. It does not verify an ID token, authenticate a bearer, clear cookies or decide redirects. The OAuth owner must atomically require its protected end-session audit and session.revoked.v1 lifecycle effect. Immutable configuration supports independent concurrent calls.

func NewOIDCEndSessionEffect

func NewOIDCEndSessionEffect(c Config, p IdentifierAdmissionConfig) (*OIDCEndSessionEffect, error)

NewOIDCEndSessionEffect freezes the selected password/single-factor profile without IO. Unsupported factor, organization and passkey authority denies, never falls back. Install OIDCEndSessionMigrationSource after the existing single-session revocation history. This enables no endpoint by itself.

func (*OIDCEndSessionEffect) Apply

Apply rechecks original authority, locks the exact original active record and revokes only it through the existing session mutation/journal. No family or sibling version advances. Every error must abort the complete OAuth command; the receipt is provisional until required events and final checks commit.

func (*OIDCEndSessionEffect) Check

Check repeats current directory/credential/policy, exact terminal session, unchanged active family, retained original journal and original deadline in the sole commit fence. The revoked credential is not re-authenticated.

func (*OIDCEndSessionEffect) Format

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

func (*OIDCEndSessionEffect) MarshalJSON

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

func (*OIDCEndSessionEffect) MarshalText

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

func (*OIDCEndSessionEffect) Recover

Recover votes from the retained original single-session tombstone and exact original record digest. No live session, bearer, key publication or fresh authentication is required. It neither re-executes nor decides the whole command outcome; the existing coordinator reconciles all participant votes.

func (*OIDCEndSessionEffect) RequireNotRevoked

RequireNotRevoked fences this exact original source's RP-logout disposition in the existing OAuth token Work. Ordinary browser signout is intentionally not this disposition. The OAuth owner must supply its actual grant-associated source and current authority; this check alone authenticates nothing. The coordinator's tenant mutex serializes absence with every revocation writer.

type OIDCEndSessionMigrationSource

type OIDCEndSessionMigrationSource struct {
	Schema  string
	Version migrations.Version
}

OIDCEndSessionMigrationSource adds only the exact RP-logout purpose to the existing single-session revocation owner. It creates no protocol revocation journal and preserves every predecessor row, SQL checksum and uniqueness fence. Install after RevokeOneMigrationSource, allocating Version permanently. No workflow is enabled and no destructive downgrade is supplied.

func (OIDCEndSessionMigrationSource) Load

Load returns the forward-only suffix without IO. The existing migration runner fails on absent/mismatched predecessor constraints; invalid scope, version, nil context and cancellation fail before installation.

type OTPAdmissionConfig

type OTPAdmissionConfig struct {
	GlobalAuthorityID, PolicyNamespace, Audience string
}

OTPAdmissionConfig selects the exact trusted deployment, user authorization namespace and session audience. It admits only single-factor email/phone OTP records, without inventing a persistent credential reference. Organization, factor and passkey dimensions deny until their owners are composed. Zero is invalid; configuration is neither authentication nor a policy Allow decision.

func (OTPAdmissionConfig) Format

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

Format redacts correlated deployment configuration.

func (OTPAdmissionConfig) MarshalJSON

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

MarshalJSON rejects implicit correlated configuration export.

type OTPIssueMigrationSource

type OTPIssueMigrationSource struct {
	Schema  string
	Version migrations.Version
}

OTPIssueMigrationSource extends the retained issuance table to consuming OTP signin. Allocate a permanent Version after IssueMigrationSource and the OTP record migration in the same history. Schema names the same owned namespace. Existing rows, keys and digests are unchanged; no second replay journal or destructive down migration is created. Install before enabling OTP effects.

func (OTPIssueMigrationSource) Load

Load returns one bounded forward-only transactional constraint migration. The migration runner owns IO, table locking, populated-state validation and commitment; cancellation and malformed configuration fail before construction.

type OTPMigrationSource

type OTPMigrationSource struct {
	Schema  string
	Version migrations.Version
}

OTPMigrationSource admits complete historical OTP session projections with optional synchronizer state. Allocate a permanent Version after the existing CSRFMigrationSource in the sole migration history; Schema must name that same owned namespace. Apply before OTP writes and upgrade relevant readers/writers: older binaries reject schemas3/4. Existing payloads and receipt hashes remain unchanged. This migration neither enables OTP authentication nor issues a session. Zero is invalid; Load performs no IO and owns no transaction.

func (OTPMigrationSource) Load

Load returns one forward-only transactional migration. The migration runner owns locking, validation and commitment; malformed populated data aborts the complete upgrade. Invalid configuration is redacted and cancellation retained.

type OTPSessionServiceConfig

type OTPSessionServiceConfig struct {
	Repository Config
	Profile    OTPAdmissionConfig
	Validation session.ServiceConfig
}

OTPSessionServiceConfig selects the explicit native OTP stateful reader. Repository and Validation retain SessionServiceConfig's lifetime, ownership and finite read-budget rules. Install directory, user security, identifier, authorization and OTP-capable session migrations before use. No credential references, provider callbacks, alternate stores or transaction are accepted.

func (OTPSessionServiceConfig) Format

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

Format redacts profile and key configuration.

func (OTPSessionServiceConfig) MarshalJSON

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

MarshalJSON rejects implicit configuration export.

type OTPSigninEffect

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

OTPSigninEffect owns session writes within the OTP feature's original checked consuming Work. It owns no pool, coordinator, OTP participant, callbacks or goroutines. Configuration is immutable and concurrent calls use independent serial Work handles. Zero is invalid. This is a native adapter seam, not a public login endpoint, authentication proof or permission to reveal a bearer.

func NewOTPSigninEffect

func NewOTPSigninEffect(c Config, p OTPAdmissionConfig) (*OTPSigninEffect, error)

NewOTPSigninEffect validates and freezes trusted deployment configuration without IO. Install kernel/authorization/session and OTPIssueMigrationSource histories before use. The registered OTP feature alone lends the sole primary transaction during its synchronous callback; no application store is accepted.

func (*OTPSigninEffect) Apply

Apply stages the complete original command-mapped session, family and retained effect identity under the exact active feature invocation. The OTP owner must exhaustively validate original Send/pre-auth possession, recipient and remember custody before admission, and finalize OTP/pre-auth in this same coordinator transaction. This helper checks the checked consuming phase, exact recipient, every applicable current owner and original expiry after downstream waits. It creates no proof, bearer or validity lease and never closes/retains Work. Every error must be propagated from ApplyFeature so the coordinator aborts; provisional success cannot authorize credential delivery before commit.

func (*OTPSigninEffect) Format

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

Format redacts deployment and stored-owner configuration for every verb.

func (*OTPSigninEffect) MarshalJSON

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

MarshalJSON rejects implicit deployment configuration export.

func (*OTPSigninEffect) MarshalText

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

MarshalText rejects implicit export and map-key disclosure.

func (*OTPSigninEffect) Recover

Recover supplies only retained session-owned evidence during the original coordinator's recovery invocation. It does not disclose a session/bearer, authenticate current access, compare a code or infer rollback from expiry. The coordinator must reconcile all participants and enforce current disclosure policy. Session payload deletion does not erase this retained commitment.

type OTPSigninIdentity

type OTPSigninIdentity struct {
	UserID    identity.UserID
	SessionID string
	FamilyID  string
}

OTPSigninIdentity is the original session-owned issuance identity, retained independently of live session payloads. These scalar IDs identify historical effects only: they are not a session, bearer, authentication proof, current authority or permission to disclose metadata. Zero means no validated tuple. Native orchestration must authorize disclosure and correlate the original consuming command separately. Copying this value creates no live credential.

func (OTPSigninIdentity) Format

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

Format prevents implicit diagnostic disclosure of the retained tuple.

func (OTPSigninIdentity) MarshalJSON

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

MarshalJSON refuses implicit historical identity export.

func (OTPSigninIdentity) MarshalText

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

MarshalText refuses implicit text and map-key export.

type OrganizationPasswordSessionAdmission

type OrganizationPasswordSessionAdmission struct {
	Profile   IdentifierAdmissionConfig
	Authority OrganizationSessionAuthority
}

OrganizationPasswordSessionAdmission opts into the owned organization fence for genuine single-factor password sessions. Profile must equal the selected password deployment/policy/audience; Authority is borrowed until calls finish. Unselected records retain ordinary password checks. MFA/passkey/other methods are not enabled or downgraded by this selection. Configuration is immutable and grants no authentication, membership or permission itself.

func (OrganizationPasswordSessionAdmission) Format

Format redacts borrowed owner and deployment configuration.

func (OrganizationPasswordSessionAdmission) MarshalJSON

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

MarshalJSON denies implicit configuration/borrowed-owner export.

type OrganizationSelectionEffect

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

OrganizationSelectionEffect owns the exact session CAS inside the logical organization participant's sole coordinator Work. It never opens a transaction or grants membership/permission. The organization owner must authenticate the original bearer, require target membership/policy and protected audit/outbox, and invoke Lock before acquiring its organization/member mutation locks. Immutable configuration permits independent concurrent calls; no goroutines or resources are owned. Install OrganizationSelectionMigrationSource first.

func NewOrganizationSelectionEffect

func NewOrganizationSelectionEffect(c Config, p OrganizationPasswordSessionAdmission) (*OrganizationSelectionEffect, error)

NewOrganizationSelectionEffect freezes a single-factor password/bearer profile without IO. The borrowed organization authority must use the same primary database. Cookie/MFA/passkey variants remain disabled rather than silently losing provenance or browser protection. Zero/invalid input denies.

func (*OrganizationSelectionEffect) Apply

Apply performs the already-locked exact CAS and retains immutable session participant evidence. It changes only that session's version/vector, not its bearer, family, original authentication, activity or expiry. The organization participant must require target authority before this call and retain it through Check. No receipt or returned session is terminal before commit.

func (*OrganizationSelectionEffect) Check

Check fences the successor, never the now-obsolete source CAS, and compares retained original evidence in the final commit fence. Every original primary owner and selected organization/member must remain current. The original admission deadline remains exclusive; final checks do not renew freshness.

func (*OrganizationSelectionEffect) Format

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

Format redacts session and borrowed-owner configuration.

func (*OrganizationSelectionEffect) Lock

Lock authenticates no bearer. It fences original non-organization owners, acquires family SHARE then exact session UPDATE before organization locks, compares the complete original record and requires its original selection. The participant must call it before target organization/member admission. Every returned error must abort the participant's whole command.

func (*OrganizationSelectionEffect) MarshalJSON

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

MarshalJSON denies implicit effect disclosure.

func (*OrganizationSelectionEffect) Recover

Recover votes from retained session-owned original transition evidence in the existing coordinator recovery Work. It never re-executes a CAS, requires a still-live session, authenticates history access or determines the overall command result; the organization service and coordinator retain those duties.

type OrganizationSelectionMigrationSource

type OrganizationSelectionMigrationSource struct {
	Schema  string
	Version migrations.Version
}

OrganizationSelectionMigrationSource adds session-owned immutable CAS evidence for the organization's existing command journal. It creates no alternate command/retry authority or selection store. Source/successor omit raw credentials; retained evidence survives ordinary session payload cleanup. Allocate Version permanently after the existing session history. No old SQL checksum, payload, family or digest index changes; no downgrade is supplied.

func (OrganizationSelectionMigrationSource) Load

Load validates scope/version/cancellation and returns owned forward-only SQL without IO. Install through the existing sole migration runner before enabling selection. The identity command and session scalar domains must already exist.

type OrganizationSessionAuthority

type OrganizationSessionAuthority interface {
	ObserveOrganizationSession(context.Context, session.Session) (OrganizationSessionAuthorityObservation, error)
	RequireOrganizationSession(context.Context, kernel.Work, kernel.FeatureExecutionContributor, session.Session) error
}

OrganizationSessionAuthority is the narrow read/fence port implemented by the organization PostgreSQL owner. Observe must derive the exact tenant/org key and require current active organization and membership for the original session user. Require must compare its original positive epoch under retained organization/member locks in the given owner's existing Work. Neither may erase a selection, substitute another organization or renew original evidence.

The implementation borrows the same primary database and honors ctx; it must not write, commit, retain Work or start goroutines. Missing/archived/removed or unknown authority denies. The caller separately authenticates bearer custody and checks every non-organization dimension. Independent calls are concurrent.

type OrganizationSessionAuthorityObservation

type OrganizationSessionAuthorityObservation struct {
	OrganizationID            string
	Authority                 session.AuthorityBinding
	ReadStartedAt, ValidUntil time.Time
}

OrganizationSessionAuthorityObservation is current owner evidence, not a credential. Its exact organization ID/key must match the original selection; Authority.Version is the current positive organization aggregate epoch, not a membership or user-policy version. ReadStartedAt precedes all contributing IO and ValidUntil is exclusive, at most20s later. Copies cannot reset that bound.

type PasskeyAdmissionConfig

type PasskeyAdmissionConfig struct {
	GlobalAuthorityID, PolicyNamespace, Audience, RPNamespace string
}

PasskeyAdmissionConfig selects trusted native directory/user policy/audience and RP namespace. Browser input must never select RPNamespace. The passkey adapter must reject a different namespace and verify its owned scope keys. Session/kernel keys remain derived by their existing owners. Zero is invalid.

func (PasskeyAdmissionConfig) Format

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

Format redacts correlated deployment configuration.

func (PasskeyAdmissionConfig) MarshalJSON

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

MarshalJSON rejects implicit configuration disclosure.

type PasskeyMFAMigrationSource

type PasskeyMFAMigrationSource struct {
	Schema             string
	Version            migrations.Version
	PreviousConstraint string
}

PasskeyMFAMigrationSource adds completed passkey/TOTP schemas11/12 to an explicitly selected installed MFA record constraint. Existing password MFA records keep their closed method/purpose branch; no row or old migration is rewritten. PreviousConstraint must describe the installed v6-v9 record history, including its original MFA numeric constraints. Allocate Version permanently after all installed steps. Upgrade readers before enabling the profile. The existing runner owns the transaction; ALTER locks sessions and validates populated rows. This history grants no authentication or issuance.

func (PasskeyMFAMigrationSource) Load

Load returns one bounded forward-only migration without IO. Unknown, missing or unvalidated predecessor history fails, without downgrading old checks or adopting arbitrary expressions. Cancellation retains the original error.

type PasskeySessionAdmission

type PasskeySessionAdmission struct {
	Profile   PasskeyAdmissionConfig
	Authority PasskeySessionAuthority
}

PasskeySessionAdmission explicitly selects the identical trusted RP and borrowed owned authority for revocation. It grants no authentication itself.

func (PasskeySessionAdmission) Format

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

Format redacts deployment and borrowed authority configuration.

func (PasskeySessionAdmission) MarshalJSON

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

MarshalJSON rejects implicit borrowed-authority configuration export.

type PasskeySessionAuthority

type PasskeySessionAuthority interface {
	ObservePasskeySession(context.Context, string, session.Session) (PasskeySessionAuthorityObservation, error)
	RequirePasskeySession(context.Context, kernel.Work, kernel.FeatureExecutionContributor, string, session.Session) error
}

PasskeySessionAuthority is the narrow consumer-owned read/fence port supplied by the owned passkey PostgreSQL adapter, not an application domain store. Both methods must verify the exact trusted RP namespace, credential mapping, original passkey key and known-empty MFA key/generation. Observe reads primary authority; Require locks and compares it in the given original owner Work. Neither method authenticates a new assertion, writes, commits, issues a token, retains Work or starts a goroutine. Implementations must honor ctx and support concurrent independent calls. Missing, revoked, mismatched or unknown state denies; no password/MFA fallback or refreshed original epoch is permitted.

type PasskeySessionAuthorityObservation

type PasskeySessionAuthorityObservation struct {
	PasskeyVersion, FactorVersion uint64
	ReadStartedAt, ValidUntil     time.Time
}

PasskeySessionAuthorityObservation reports current primary owner epochs and their original positive-evidence window. Both epochs are nonzero and MFA is known-empty, not merely absent. ReadStartedAt precedes contributing IO; ValidUntil is exclusive and at most20s later. Copies cannot renew that bound. This is trusted owner evidence, never a client credential or authentication.

type PasskeySessionServiceConfig

type PasskeySessionServiceConfig struct {
	Repository Config
	Profile    PasskeyAdmissionConfig
	Validation session.ServiceConfig
	Authority  PasskeySessionAuthority
}

PasskeySessionServiceConfig composes owned current passkey authority with the existing session/kernel/authorization primary readers. Pool and Authority are borrowed and must outlive calls; no application transaction/store is accepted. The reader owns no resources or goroutines. Validation keeps its key, clock and immutable evidence-envelope policy; selected native read budgets must fit.

func (PasskeySessionServiceConfig) Format

Format redacts session keys and borrowed authority configuration.

func (PasskeySessionServiceConfig) MarshalJSON

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

MarshalJSON rejects implicit session/authority configuration export.

type PasskeySigninEffect

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

PasskeySigninEffect stages initial session/family/issuance effects in the passkey owner's original Work. It does not verify WebAuthn or issue bearer custody. The native owner must first finalize the genuine opaque assertion, its one-use counter/backup transition, risk and mapping in this same Work, then repeat Check after all later effects. No independent transaction, pool, goroutine or command journal is created. Configuration supports concurrent calls with independently owned serial-use Work values; Authority is borrowed.

func NewPasskeySigninEffect

func NewPasskeySigninEffect(c Config, p PasskeyAdmissionConfig, authority PasskeySessionAuthority) (*PasskeySigninEffect, error)

NewPasskeySigninEffect freezes explicit trusted native/RP composition without IO. Install the actual existing session history and passkey issuance suffix first. Authority must be the owned passkey adapter for this primary database; a metadata projection or application-written verifier is not a substitute.

func (*PasskeySigninEffect) Apply

Apply requires exact original command custody, all original current owners and the selected known-empty MFA/RP profile, then stages the complete initial session through the existing session SQL owner. Every error must abort Work. Success is provisional and cannot reveal a bearer or VerifiedAssertion.

func (*PasskeySigninEffect) Check

Check repeats original directory/credential/policy/RP/empty-factor authority, exact stored session and database-time freshness after downstream waits. It never adopts newer epochs or restarts the original assertion/proof lifetime.

func (*PasskeySigninEffect) Format

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

Format redacts correlated configuration and authority dependencies.

func (*PasskeySigninEffect) MarshalJSON

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

MarshalJSON rejects implicit configuration disclosure.

func (*PasskeySigninEffect) MarshalText

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

MarshalText rejects implicit configuration disclosure.

func (*PasskeySigninEffect) Recover

Recover reads immutable original issuance evidence in the exact registered recovery invocation. It discloses no bearer/session and grants no current access. The coordinator must reconcile protocol and every other participant; missing payload never proves rollback and cannot authorize a new assertion.

type PasskeySigninMigrationSource

type PasskeySigninMigrationSource struct {
	Schema             string
	Version            migrations.Version
	PreviousConstraint string
}

PasskeySigninMigrationSource appends one purpose to an explicitly selected already installed session-issuance constraint. PreviousConstraint must name that actual supported history; no login method, anonymous or device tables become dependencies. Allocate a permanent Version after every installed step. The existing validated purpose predicate is preserved from PostgreSQL's own expression tree, not reconstructed from optional feature guesses. Existing rows, original migration SQL/checksums and issuance commitments are unchanged. Install this suffix last and retire binaries that cannot read passkey sessions before enabling issuance. The existing runner owns the transaction/timeouts; ALTER takes an exclusive table lock and validates the additive CHECK.

func (PasskeySigninMigrationSource) Load

Load returns one forward-only transactional migration without IO. Unknown, unvalidated, missing or non-purpose predecessor checks fail visibly at apply; there is no downgrade, exception swallowing or schema-drift adoption.

type PasskeySignupEffect

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

PasskeySignupEffect writes the initial session/family and retained issuance binding for an actually created prospective account. It owns no transaction, pool, goroutine, pre-auth flow or cryptographic verifier. The native signup owner must first verify WebAuthn, initialize selected authorities, and admit original pre-auth cookie/remember/risk custody, then consume/finalize all required effects in the same Work. Immutable configuration supports concurrent independent calls; borrowed Work and dependencies must not be retained/closed.

func NewPasskeySignupEffect

NewPasskeySignupEffect freezes trusted configuration without IO. Install the actual kernel, MFA, authorization and session histories, including the selected PasskeySignupMigrationSource, before use. This enables no public signup route.

func (*PasskeySignupEffect) Apply

Apply stages only the complete original command-mapped session after fencing this Work's actual newly created account/credential, current deployment and authorization, and native RP/known-empty factor ownership. It cannot turn an existing account or a changed generation into signup. Every error must abort the enclosing native command. Success neither commits nor reveals a bearer.

func (*PasskeySignupEffect) Check

Check repeats original account/reference/RP/factor/authorization and session checks after later audit/outbox phases, with primary database time. It never refreshes the original proof, selects a newer generation or mints a session.

func (*PasskeySignupEffect) Format

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

Format redacts correlated configuration and borrowed authorities.

func (*PasskeySignupEffect) MarshalJSON

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

MarshalJSON refuses implicit configuration export.

func (*PasskeySignupEffect) MarshalText

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

MarshalText refuses implicit configuration export.

func (*PasskeySignupEffect) Recover

Recover reads immutable original issuance evidence in the exact registered native recovery invocation. It returns neither bearer nor current authority; the coordinator still reconciles every participant. Missing session payload is not rollback, and a recovered result must not renew access or reveal again.

type PasskeySignupIdentity

type PasskeySignupIdentity struct {
	UserID    identity.UserID
	SessionID string
	FamilyID  string
}

PasskeySignupIdentity identifies original retained signup issuance, not a session, bearer, current authority or complete command outcome. The native owner must establish the exact coordinator outcome and original disclosure custody before exposing IDs. Payload pruning never reauthorizes access.

func (PasskeySignupIdentity) Format

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

Format hides correlated historical identifiers for every formatting verb.

func (PasskeySignupIdentity) MarshalJSON

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

MarshalJSON rejects implicit historical identifier export.

func (PasskeySignupIdentity) MarshalText

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

MarshalText rejects implicit text and map-key export.

type PasskeySignupMigrationSource

type PasskeySignupMigrationSource struct {
	Schema             string
	Version            migrations.Version
	PreviousConstraint string
}

PasskeySignupMigrationSource appends only the prospective-account issuance purpose to an explicitly selected existing CHECK. It preserves PostgreSQL's actual predecessor expression and populated rows, rather than assuming which optional methods are installed. Version follows installed session history. Install this suffix before enabling native signup. Existing migration bytes and issuance commitments remain unchanged; no schema/payload backfill occurs.

func (PasskeySignupMigrationSource) Load

Load returns one forward-only migration without IO. The runner owns its transaction/timeouts. DDL locks session_issuances exclusively while validating the additive CHECK. Unknown, missing, unvalidated or wrong-column history fails at apply; no downgrade, exception swallowing or automatic history adoption occurs.

type PasskeySignupSessionAuthority

type PasskeySignupSessionAuthority interface {
	RequirePasskeySignupSession(context.Context, kernel.Work, kernel.PasskeyRegistrationContributor, identity.Command, string, session.Session) error
}

PasskeySignupSessionAuthority is supplied by the owned native passkey adapter, never an application-written verifier. It must lock the exact current RP/key mapping and the MFA generation initialized by this original signup command, using the borrowed Work. Metadata or a missing factor row is not authority. Errors abort Work; success is provisional, without a renewable validity lease.

type PasswordActiveTOTPPrimaryConfig

type PasswordActiveTOTPPrimaryConfig struct {
	Session  SessionServiceConfig
	CSRFKeys []session.CSRFKey
}

PasswordActiveTOTPPrimaryConfig selects native password and password/MFA session reads plus retained synchronizer keys. No application SessionReader or reauthentication callback is accepted. Cookie transport is mandatory in this profile; unsupported method/organization/passkey owners deny.

func (PasswordActiveTOTPPrimaryConfig) Format

Format redacts native primary ownership and synchronizer configuration.

func (PasswordActiveTOTPPrimaryConfig) MarshalJSON

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

MarshalJSON rejects implicit configuration export.

func (PasswordActiveTOTPPrimaryConfig) MarshalText

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

MarshalText rejects implicit configuration export.

type PasswordActiveTOTPPrimarySource

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

PasswordActiveTOTPPrimarySource borrows the primary pool and owns immutable native session/current-authority composition. It has no background workers, cache or transaction ownership. The pool must outlive concurrent bounded calls.

func NewPasswordActiveTOTPPrimarySource

func NewPasswordActiveTOTPPrimarySource(pool *database.Pool, c PasswordActiveTOTPPrimaryConfig) (*PasswordActiveTOTPPrimarySource, error)

NewPasswordActiveTOTPPrimarySource freezes actual primary adapter ownership. Install the selected password/MFA/session histories before use. Construction performs no IO, proof generation or session promotion.

func (*PasswordActiveTOTPPrimarySource) Format

Format redacts borrowed owners.

func (*PasswordActiveTOTPPrimarySource) MarshalJSON

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

MarshalJSON rejects implicit source export.

func (*PasswordActiveTOTPPrimarySource) MarshalText

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

MarshalText rejects implicit source export.

func (*PasswordActiveTOTPPrimarySource) PrepareDisable

PrepareDisable authenticates actual native cookie/synchronizer custody for exact disable, not a translated update request or caller's proof projection.

func (*PasswordActiveTOTPPrimarySource) PrepareFactorUpdate

PrepareFactorUpdate authenticates actual cookie/synchronizer custody for the keyed command selected by MFA's owner. It does not fabricate a regeneration request, authenticate a factor projection or renew the original observation.

func (*PasswordActiveTOTPPrimarySource) PrepareOTPSend

PrepareOTPSend authenticates actual current cookie custody for the keyed active-OTP action, not the historical pending enrollment. MFA must bind the original factor, action and verified recipient separately and perform current owner/CSRF checks in Work. The returned observation's deadline is unchanged.

func (*PasswordActiveTOTPPrimarySource) PrepareOTPVerify

PrepareOTPVerify reads the real current password/MFA session for the explicit active-OTP verification arm. It grants neither code comparison nor factor proof. The OTP/MFA owners must restore the exact send and independently bind its session, factor, action, recipient and original expiry before comparison.

func (*PasswordActiveTOTPPrimarySource) PrepareRegeneration

PrepareRegeneration authenticates a real current cookie/synchronizer without fabricating a TOTP request or treating an MFA session as a fresh factor proof. The native regeneration owner separately authenticates and consumes that proof.

func (*PasswordActiveTOTPPrimarySource) PrepareStepUp

PrepareStepUp authenticates the actual submitted cookie using the configured native primary reader, then checks its exact synchronizer and caller subject. The returned owned observation is unchanged, including its exclusive expiry. It verifies no factor and never upgrades or renews the source session.

func (*PasswordActiveTOTPPrimarySource) RestoreDisable

RestoreDisable checks retained original session possession without IO, current authorization or freshness renewal. MFA must authenticate wire first.

func (*PasswordActiveTOTPPrimarySource) RestoreFactorUpdate

RestoreFactorUpdate checks original possession against MFA-authenticated snapshot bytes and the retained keyed command without IO or new freshness. The mutation still must fence current owners in the actual protected Work.

func (*PasswordActiveTOTPPrimarySource) RestoreOTPSend

RestoreOTPSend verifies possession against only the MFA-authenticated original current-session snapshot. It performs no IO, pending-enrollment translation, factor verification or freshness renewal. Current Work checks remain required.

func (*PasswordActiveTOTPPrimarySource) RestoreOTPVerify

RestoreOTPVerify checks original current-session custody without IO or renewed authority. Only MFA-authenticated snapshot bytes are accepted here; this source does not establish that the submitted OTP or send is valid.

func (*PasswordActiveTOTPPrimarySource) RestoreRegeneration

RestoreRegeneration restores only native-envelope-authenticated original session metadata. It checks bearer/CSRF possession, not current authorization, and cannot renew the retained deadline or manufacture factor verification.

func (*PasswordActiveTOTPPrimarySource) RestoreReplacementForConfirmation

func (s *PasswordActiveTOTPPrimarySource) RestoreReplacementForConfirmation(ctx context.Context, r mfa.TotpVerifyRequest, wire []byte, ceiling time.Time) (mfapg.TOTPReplacementPrimary, error)

RestoreReplacementForConfirmation restores the same original active-session custody for the exact enrollment variant. Current owners and original exclusive deadline remain checked by the protected continuation Work.

func (*PasswordActiveTOTPPrimarySource) RestoreReplacementForURI

func (s *PasswordActiveTOTPPrimarySource) RestoreReplacementForURI(ctx context.Context, r mfa.TotpUriRequest, wire []byte, ceiling time.Time) (mfapg.TOTPReplacementPrimary, error)

RestoreReplacementForURI checks original bearer/synchronizer possession against the native factor-update snapshot already authenticated by MFA. It neither translates password-enable provenance nor renews freshness.

func (*PasswordActiveTOTPPrimarySource) RestoreStepUp

RestoreStepUp is an IO-free native restore of already envelope-authenticated snapshot bytes. It authenticates neither arbitrary bytes nor current owners. Submitted bearer/CSRF must still match the exact original record; final Work compares current owners and the original exclusive deadline before mutation.

type PasswordChangeEffect

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

PasswordChangeEffect owns session disposition inside the native password owner's original consuming Work. It owns no pool, coordinator, transaction, registry, callback or goroutine. Immutable configuration supports concurrent independent invocations; Work itself remains serial and borrowed. Zero is invalid. This seam is not a password verifier, proof or public change endpoint.

func NewPasswordChangeEffect

func NewPasswordChangeEffect(c Config, p IdentifierAdmissionConfig) (*PasswordChangeEffect, error)

NewPasswordChangeEffect freezes trusted single-factor password configuration without IO. Install CredentialContinuationMigrationSource and PasswordChangeMigrationSource alongside the kernel credential-replacement history before use. The registered password contributor alone lends the sole primary Work during its synchronous consuming invocation. No application store or independently managed transaction is accepted.

func (*PasswordChangeEffect) Apply

Apply stages the original command's bounded session choice before the kernel advances the password reference and independent credential-authority epoch. Source bearer/proof possession, HIBP, reuse and one-use proof consumption are mandatory native password-owner responsibilities in this same Work. This helper admits that exact participant, compares the source's current owners, locks the complete selected set in bounded bytewise keyset pages, then stages continuation/revocation and retained effect evidence. The original source must remain valid after waits. No timestamp, lifetime, proof, assurance, remember, lookup, CSRF or unrelated authority is renewed.

Preserve supports only the configured password reference and single-factor records without organization/factor/passkey dimensions. Mixed unsupported profiles deny preservation until their owners are composed. Stale, expired or family-denied supported rows are revoked, never upgraded. Revoke-other/all can terminally revoke other stored profiles without granting them authority. Already revoked rows are unchanged and excluded from the whole-set cap. Every error must propagate from ApplyFeature so the coordinator aborts all staged effects. Provisional success cannot authorize disclosure before commit.

func (*PasswordChangeEffect) Format

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

Format redacts deployment and authority configuration for every verb.

func (*PasswordChangeEffect) MarshalJSON

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

MarshalJSON rejects implicit configuration export.

func (*PasswordChangeEffect) MarshalText

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

MarshalText rejects implicit configuration export and map-key disclosure.

func (*PasswordChangeEffect) Recover

Recover supplies only the retained original session-effect commitment during the password participant's invocation-fenced recovery. It authenticates no current access, reveals no session and never infers rollback from expiry or live-payload absence. The original coordinator must reconcile all participants. Missing infrastructure/corrupt evidence remains unknown; retained commitment survives session cleanup. No Work/rows/transaction is retained or closed.

type PasswordChangeMigrationSource

type PasswordChangeMigrationSource struct {
	Schema  string
	Version migrations.Version
}

PasswordChangeMigrationSource adds retained session-owned effect evidence to the existing migration history. Schema must match the installed session store; allocate Version permanently after credential-continuation and kernel credential-replacement histories. Existing rows/checksums remain unchanged. Evidence belongs to original command retention, not live session payloads; no session FK or destructive down migration is provided. Load performs no IO.

func (PasswordChangeMigrationSource) Load

Load returns independently owned transactional forward SQL. The sole runner owns execution and commit. Nil/canceled context and invalid ownership deny without partial history. Concurrent immutable calls are safe.

type PasswordChangeSessionDisposition

type PasswordChangeSessionDisposition uint8

PasswordChangeSessionDisposition is an explicit selection frozen in the original password-change command. Zero is invalid; no default is inferred. These values express intent, not authentication or a completed durable effect.

const (
	// PasswordChangePreserveSessions continues eligible existing password
	// sessions. Stale or terminal records must never be upgraded into validity.
	PasswordChangePreserveSessions PasswordChangeSessionDisposition = iota + 1
	// PasswordChangeRevokeOtherSessions retains the authenticated source and
	// terminally revokes every other selected session of the same tenant/user.
	PasswordChangeRevokeOtherSessions
	// PasswordChangeRevokeAllSessions revokes the source and all other selected
	// sessions; no returned historical bearer remains authorized by this choice.
	PasswordChangeRevokeAllSessions
)

type PasswordMFAActionSessionGuard

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

PasswordMFAActionSessionGuard admits an original password session for native authenticated TOTP step-up or recovery-code regeneration. Existing MFA records retain their factor fence; they never enter a single-factor profile. This borrowed participant owns no transaction, pool, cache or goroutine. Immutable configuration is safe for concurrent independent invocations.

func NewPasswordMFAActionSessionGuard

func NewPasswordMFAActionSessionGuard(c Config, p IdentifierAdmissionConfig) (*PasswordMFAActionSessionGuard, error)

NewPasswordMFAActionSessionGuard freezes an explicit password profile without IO. Its current-owner checks reuse the native session reader's original password/TOTP and password/recovery mappings, not a fabricated revoke request. Unsupported method/organization/passkey dimensions fail closed.

func (*PasswordMFAActionSessionGuard) AdmitPreparation

AdmitPreparation repeats current-owner admission in the exact registered native preparation invocation before counters or encrypted output generation. It grants no final mutation permission; Apply must call Check again with the unchanged command, and the caller must propagate every denial.

func (*PasswordMFAActionSessionGuard) Check

Check verifies submitted bearer/CSRF possession, original command bindings, all current primary owners and the original session/family in the native MFA contributor's sole live Apply Work. It preserves the earliest original deadline; neither retries nor a fresh database clock renew it. Locks remain owned by the coordinator. The participant must propagate every error and abort.

Success is not fresh TOTP proof or regeneration authority. The native MFA owner still must verify the actual code, advance replay, persist signed evidence, enforce policy/risk and atomically consume the proof on mutation. No synchronizer is revealed or consumed by this check.

func (*PasswordMFAActionSessionGuard) Format

Format redacts correlated original-session and command configuration.

func (*PasswordMFAActionSessionGuard) MarshalJSON

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

MarshalJSON rejects implicit configuration export.

func (*PasswordMFAActionSessionGuard) MarshalText

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

MarshalText rejects implicit configuration export.

func (*PasswordMFAActionSessionGuard) RecheckCommit

RecheckCommit repeats current authority and expiry checks during the exact native owner's final commit callback. That owner must compare the callback's command with its retained original command; Apply custody cannot be borrowed outside Apply. No new mutation, proof or observation is created here.

type PasswordMFAActionSessionInput

type PasswordMFAActionSessionInput struct {
	Command    identity.Command
	Original   session.Session
	ValidUntil time.Time
	LookupKey  session.DigestKey
	CSRFToken  session.CSRFToken
	CSRFKey    session.CSRFKey
}

PasswordMFAActionSessionInput borrows exact command-frozen original session custody and separately submitted synchronizer. Keys are the original retained lookup and CSRF versions, selected by trusted composition, never request data. ValidUntil must match the command's original observation deadline. No field supplies fresh factor verification or permission to regenerate recovery codes.

func (PasswordMFAActionSessionInput) Format

Format redacts borrowed custody and correlated session metadata.

func (PasswordMFAActionSessionInput) MarshalJSON

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

MarshalJSON rejects implicit custody export.

func (PasswordMFAActionSessionInput) MarshalText

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

MarshalText rejects implicit custody export.

type PasswordMFAMigrationSource

type PasswordMFAMigrationSource struct {
	Schema  string
	Version migrations.Version
}

PasswordMFAMigrationSource adds closed password/TOTP schemas11/12 after MFAMigrationSource in the same owned history. Upgrade readers before selecting these records. Existing SQL, rows and original issuance evidence are retained; this migration neither authenticates a password nor completes a factor.

func (PasswordMFAMigrationSource) Load

Load returns a forward-only transactional constraint extension without IO. The existing runner owns locking, populated-state validation and commitment.

type PasswordResetEffect

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

PasswordResetEffect terminally revokes the complete active-state session set in the password reset owner's sole Work. Unlike password change, reset has no authenticated source session and permits no preservation. It owns no pool, transaction, callbacks or goroutines. Immutable instances permit concurrent independent invocations; each borrowed Work remains serial.

func NewPasswordResetEffect

func NewPasswordResetEffect(c Config) (*PasswordResetEffect, error)

NewPasswordResetEffect validates trusted storage configuration without IO. Install PasswordResetMigrationSource after the session and kernel histories. Each complete set is capped at 100000 rows; overflow fails the whole reset, rather than revoking a prefix and declaring success. All active-state rows, including expired and other-method sessions, count. Empty sets are valid.

func (*PasswordResetEffect) Apply

Apply stages revocation and hash-free original effect evidence. Only the exact registered native CredentialResetContributor can lend Work. The kernel has fenced the reset's aggregate, password reference and credential epoch; the native workflow must additionally verify original issuance, current account, identifier/factors, risk/HIBP and atomic capability consumption. This method is not reset authorization and never issues a session or upgrades authority. Propagate every error so the coordinator aborts password and session effects. A returned receipt is provisional until the complete command commits.

func (*PasswordResetEffect) Format

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

Format omits deployment configuration for all formatting verbs.

func (*PasswordResetEffect) MarshalJSON

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

MarshalJSON rejects implicit configuration export.

func (*PasswordResetEffect) MarshalText

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

MarshalText rejects implicit text and map-key export.

func (*PasswordResetEffect) Recover

Recover reconciles retained original effect evidence, not mutable session payloads. Cleanup and later logins cannot erase original commitment. Absence is NotCommitted only because insertion is atomic and evidence is not pruned independently. Corruption or unavailable infrastructure remains Unknown. This reveals no bearer and does not establish current result-access policy; the coordinator must reconcile all participants before disclosing an outcome.

type PasswordResetMigrationSource

type PasswordResetMigrationSource struct {
	Schema  string
	Version migrations.Version
}

PasswordResetMigrationSource adds session-owned original reset-effect evidence after the installed session and kernel histories. Schema must match the store; allocate Version permanently. Existing migrations and change receipts remain unchanged. These rows are effect evidence, not another reset intent journal, and must remain with original command retention after live-session cleanup.

func (PasswordResetMigrationSource) Load

Load returns forward transactional SQL without IO. Nil/canceled contexts and invalid schema/version deny; the existing migration runner owns execution.

type PasswordSigninEffect

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

PasswordSigninEffect stages session and pre-auth effects in the password owner's sole coordinator Work. It owns no pool, transaction, callback or goroutine. Immutable configuration supports concurrent independent Work calls; zero is invalid. This seam is not a credential verifier or login endpoint.

func NewPasswordSigninEffect

func NewPasswordSigninEffect(c Config, p IdentifierAdmissionConfig) (*PasswordSigninEffect, error)

NewPasswordSigninEffect freezes a trusted single-factor password profile without IO. Install PasswordSigninMigrationSource after the existing OTP issuance history and the original pre-auth, directory and authorization histories. No coordinator, caller-written store or transaction is accepted.

func (*PasswordSigninEffect) Apply

Apply reserves and consumes the exact original pre-auth flow with session, family and retained issuance evidence atomically. The exact registered native password owner MUST first verify the password, authenticating proof provenance, pre-auth cookie possession, complete request intent and risk/policy decision, and bind these original snapshots into keyed command custody. Structural command/session metadata alone cannot replace any of those checks. Current directory, selected recipient/credential, authorization and family checks use the original projection without changing anonymous command scope. Original proof/session/pre-auth expiry is rechecked after downstream waits. Every error must propagate to abort Work; success is provisional and cannot disclose credentials until the coordinator establishes the exact commit. The native owner must repeat temporal admission after any later owner or coordinator phases; an earlier sample cannot prove eligibility at commit.

func (*PasswordSigninEffect) ApplyHashUpgrade

ApplyHashUpgrade stages original signin effects only after the kernel's reserved upgrade has been applied in this same native invocation. It obtains the actual successor from Work, rather than accepting a caller-created successor recipient or renewing its observation. The prospective command's authentication/reference and independent security epochs must match exactly. The registered password owner must supply its unchanged original command, have completed material CAS and verified its successor-bound signed proof. Pre-auth, policy, family, CSRF, expiry, commit/recovery and pool ownership keep Apply's semantics; every error requires abort and output stays provisional.

func (*PasswordSigninEffect) Format

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

Format hides correlated deployment configuration.

func (*PasswordSigninEffect) MarshalJSON

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

MarshalJSON denies implicit configuration disclosure.

func (*PasswordSigninEffect) MarshalText

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

MarshalText denies implicit configuration disclosure.

func (*PasswordSigninEffect) PrepareHashUpgrade

PrepareHashUpgrade admits the original prospective signin's directory before reserving exclusive predecessor user/credential authority in Work. Call only during the registered password owner's original Apply invocation, before any shared recipient/credential or material lock. The native owner must already have verified the original password, cookie, proof provenance and policy/risk. It owns bounded replacement generation and material CAS, not this adapter. This method writes no session or credential and starts no transaction. Every error must abort the original Work. Success is neither authentication nor permission to disclose a bearer, preserve older sessions or renew freshness.

func (*PasswordSigninEffect) Recover

Recover inspects retained original issuance evidence during the exact native recovery invocation. Missing payload or expiry never proves rollback. It returns no bearer/session, grants no current access and renews no authority; the coordinator must reconcile every participant before reporting an outcome.

type PasswordSigninIdentity

type PasswordSigninIdentity struct {
	UserID    identity.UserID
	SessionID string
	FamilyID  string
}

PasswordSigninIdentity identifies original session-owned password issuance effects independently of live payload retention. It is neither a session, credential, current authority nor whole-command outcome. Native orchestration must authenticate original possession, authorize disclosure and correlate the sole coordinator receipt before exposing these independently owned IDs.

func (PasswordSigninIdentity) Format

func (PasswordSigninIdentity) Format(w fmt.State, _ rune)

Format prevents implicit diagnostic disclosure of historical identity.

func (PasswordSigninIdentity) MarshalJSON

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

MarshalJSON refuses implicit historical identity export.

func (PasswordSigninIdentity) MarshalText

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

MarshalText refuses implicit text and map-key export.

type PasswordSigninMigrationSource

type PasswordSigninMigrationSource struct {
	Schema  string
	Version migrations.Version
}

PasswordSigninMigrationSource admits password signin in the existing retained issuance table. Install after OTPIssueMigrationSource in the same owned schema, using a permanent unused Version. Existing rows and digest bytes are unchanged; no second journal, authority or destructive downgrade is introduced.

func (PasswordSigninMigrationSource) Load

Load constructs one bounded forward-only transactional constraint extension. The migration runner owns IO, table locking and populated-state validation.

type PasswordSignupEffect

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

PasswordSignupEffect stages session effects in registration's sole Work. It owns no transaction, pool, callback or goroutine. Immutable configuration supports independent concurrent invocations; zero denies. It is not signup policy, password verification, authorization bootstrap or a login service.

func NewPasswordSignupEffect

func NewPasswordSignupEffect(c Config, p IdentifierAdmissionConfig) (*PasswordSignupEffect, error)

NewPasswordSignupEffect freezes an explicit single-factor password profile without IO. Install the registration binding history, signup issuance extension, original pre-auth, directory and authorization histories first.

func (*PasswordSignupEffect) Apply

Apply correlates the exact original signup command with the newly staged registration binding, then fences its pending identifier, password reference, directory and selected-user authorization under that same Work. The native password owner must first admit original hash/HIBP/risk and cookie possession, persist password material, and decide that verification and MFA are NOT required. Structural creation/proof metadata cannot replace those decisions. Missing authorization denies; this effect never bootstraps it implicitly. Session/family/retained evidence and original pre-auth consumption are atomic. Every error must abort Work; success is provisional and reveals no secrets. The owner must repeat temporal admission after later coordinator phases.

func (*PasswordSignupEffect) Format

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

Format hides correlated deployment configuration.

func (*PasswordSignupEffect) MarshalJSON

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

MarshalJSON rejects implicit configuration disclosure.

func (*PasswordSignupEffect) MarshalText

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

MarshalText rejects implicit text configuration disclosure.

func (*PasswordSignupEffect) Recover

Recover inspects retained original signup issuance evidence in the exact native recovery invocation. Payload deletion/expiry never proves rollback. It returns no session/credential, grants no access and renews no authority; the coordinator must reconcile all participants before reporting an outcome.

type PasswordSignupIdentity

type PasswordSignupIdentity struct {
	UserID    identity.UserID
	SessionID string
	FamilyID  string
}

PasswordSignupIdentity identifies original session-owned password issuance effects independently of live payload retention. It is neither a session, credential, current authority nor whole-command outcome. Native orchestration must authenticate original possession, authorize disclosure and correlate the sole coordinator receipt before exposing these independently owned IDs.

func (PasswordSignupIdentity) Format

func (PasswordSignupIdentity) Format(w fmt.State, _ rune)

Format prevents implicit diagnostic disclosure of historical identity.

func (PasswordSignupIdentity) MarshalJSON

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

MarshalJSON refuses implicit historical identity export.

func (PasswordSignupIdentity) MarshalText

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

MarshalText refuses implicit text and map-key export.

type PasswordSignupMigrationSource

type PasswordSignupMigrationSource struct {
	Schema  string
	Version migrations.Version
}

PasswordSignupMigrationSource admits signup in the existing retained issuance table after PasswordSigninMigrationSource. Allocate a permanent unused Version. Existing rows and commitments are unchanged; no second journal is introduced.

func (PasswordSignupMigrationSource) Load

Load returns one forward-only transactional constraint extension without IO. The migration runner owns locking and populated-state validation.

type PhoneOTPSigninMigrationSource

type PhoneOTPSigninMigrationSource struct {
	Schema              string
	Version             migrations.Version
	Predecessor         UsernameSigninPredecessor
	MFASignin           bool
	UsernameSignin      bool
	PhonePasswordSignin bool
}

PhoneOTPSigninMigrationSource admits the distinct phone SMS-code signin purpose after an explicitly selected installed purpose history. Predecessor and MFASignin have UsernameSigninMigrationSource semantics. UsernameSignin and PhonePasswordSignin identify already-installed optional suffixes, not dependencies on those authentication methods. Install this last among the selected purpose suffixes; no existing issuance or installed SQL is rewritten.

func (PhoneOTPSigninMigrationSource) Load

Load returns one forward-only transactional migration. The caller owns the runner and transaction. A wrong predecessor fails at the installed constraint rather than guessing a broader profile. This enables no login endpoint.

type PhonePasswordResetMigrationSource

type PhonePasswordResetMigrationSource struct {
	Schema  string
	Version migrations.Version
}

PhonePasswordResetMigrationSource extends the existing all-session reset evidence purpose constraint. Install after PasswordResetMigrationSource in the same Schema and allocate Version after its installed history. Existing rows, migration checksums and effect digests remain unchanged. This suffix enables neither a recovery workflow nor independent revocation authority.

func (PhonePasswordResetMigrationSource) Load

Load returns forward transactional SQL without IO or destructive downgrade. Missing installed prerequisites fail when the existing runner applies it; nil/canceled contexts and invalid schema/version return no partial history.

type PhonePasswordSigninMigrationSource

type PhonePasswordSigninMigrationSource struct {
	Schema         string
	Version        migrations.Version
	Predecessor    UsernameSigninPredecessor
	MFASignin      bool
	UsernameSignin bool
}

PhonePasswordSigninMigrationSource adds phone/password session provenance to an explicitly selected installed purpose profile. Predecessor and MFASignin have UsernameSigninMigrationSource semantics. UsernameSignin selects the already-installed username suffix over that predecessor; it is not a dependency on username login. Install this after all selected predecessor purpose suffixes. No existing row, authentication, deadline or installed checksum is rewritten.

func (PhonePasswordSigninMigrationSource) Load

Load returns a single forward-only migration; caller owns its transaction and runner. An incorrectly selected installed constraint fails rather than guessing or admitting unrelated methods. This does not expose a phone signin endpoint.

type PreAuthIssueCommand

type PreAuthIssueCommand = session.PreAuthIssueCommand

PreAuthIssueCommand freezes a server-prepared original flow with a stable command identity and correlation. Record is structural, not authentication. Server initiation owns nonce, cookie commitment, original time and resolved remember policy; never decode this value directly from HTTP input. The same complete command must be retained across retries; no raw cookie is accepted.

type PreAuthIssueExecutor

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

PreAuthIssueExecutor owns native initiation and outcome-only restart recovery through the sole kernel coordinator. It opens no second journal and accepts no user-supplied store, transaction or workflow. Calls are concurrency-safe; keep its borrowed pool/policy/clock alive until all calls finish. Zero denies. Cookie generation/delivery belong to the storage-neutral initiation owner.

func NewPreAuthIssueExecutor

func NewPreAuthIssueExecutor(pool *database.Pool, c PreAuthIssueExecutorConfig) (*PreAuthIssueExecutor, error)

NewPreAuthIssueExecutor freezes one profile and native participants without IO. It does not authenticate a user, mint a cookie, apply migrations or grant policy access. Original persisted scope is distinct from verified actors.

func (*PreAuthIssueExecutor) ExecutePreAuthIssuance

func (e *PreAuthIssueExecutor) ExecutePreAuthIssuance(ctx context.Context, input PreAuthIssueCommand) (out session.PreAuthIssueExecution, err error)

ExecutePreAuthIssuance preserves ExecutePreAuthIssue's atomic execution and adds explicit original-versus-historical metadata. Only acquisition of the sole coordinator reservation clears Replayed; observing a committed receipt never does. Replayed remains true on conflicts, pending observations and pre-reservation failures. Cookie delivery also requires exact newly committed receipt validation, no error/cancellation and an unexpired original flow. Earlier deadlines and detached cleanup budgets match ExecutePreAuthIssue.

func (*PreAuthIssueExecutor) ExecutePreAuthIssue

func (e *PreAuthIssueExecutor) ExecutePreAuthIssue(ctx context.Context, input PreAuthIssueCommand) (identity.CommandResult, error)

ExecutePreAuthIssue authorizes trusted service scope, then commits the original flow, retained native evidence, audit/lifecycle and command receipt atomically. Exact replay returns only historical metadata, never a cookie or renewal. Changed intent conflicts; cancellation/failed acknowledgement cannot prove rollback. Recover the exact original command after Unknown. Earlier deadlines win; kernel detached cleanup retains its independently bounded budget.

func (PreAuthIssueExecutor) Format

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

Format redacts composition and private correlation for every formatting verb.

func (PreAuthIssueExecutor) MarshalJSON

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

MarshalJSON prevents automatic runtime composition disclosure.

func (*PreAuthIssueExecutor) RecoverPreAuthIssue

RecoverPreAuthIssue observes or reconciles one original anonymous-flow command under current configured service policy. It accepts no cookie, does not mint or renew state, reserve a missing command or infer noncommit from flow absence. Restart scope must retain tenant, flow, actor, operation and record exactly. Live pending retains its lease; expired pending uses frozen native evidence.

type PreAuthIssueExecutorConfig

type PreAuthIssueExecutorConfig struct {
	Repository                            Config
	Coordinator                           kernel.CoordinatorConfig
	Authorization                         authorization.Service
	Clock                                 clock.Clock
	ActorID                               identity.ActorID
	Action, Origin, CallbackURL, PolicyID string
	PolicyVersion, AuditRetentionVersion  uint64
	// Purpose selects only the matching core profile; zero preserves login.
	// Phone recovery has no session choice and requires identifier binding.
	Purpose session.PreAuthPurpose
}

PreAuthIssueExecutorConfig selects one server-owned initiation profile. Action, Origin and CallbackURL are exact trusted allowlist choices, not client-selected policy; empty CallbackURL explicitly disables redirection. ActorID is the trusted service actor, separate from the anonymous flow target. Authorization must bound callbacks and be concurrency-safe. Dependencies are borrowed; install kernel, pre-auth, issuance, audit and outbox migrations. Coordinator, policy and digest keys must be retained while commands exist.

func (PreAuthIssueExecutorConfig) Format

Format redacts borrowed configuration and keys.

func (PreAuthIssueExecutorConfig) MarshalJSON

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

MarshalJSON prevents automatic configuration/key disclosure.

type PreAuthIssueMigrationSource

type PreAuthIssueMigrationSource struct {
	Schema  string
	Version migrations.Version
}

PreAuthIssueMigrationSource installs retained native initiation evidence at a later permanent slot after the kernel and PreAuthMigrationSource histories. Evidence has no live-flow FK and must survive flow retirement. Apply through the sole migrations runner; it provides no destructive downgrade.

func (PreAuthIssueMigrationSource) Load

Load validates allocation and cancellation without IO and returns one atomic forward migration. Existing flow records and applied SQL remain unchanged.

type PreAuthMigrationSource

type PreAuthMigrationSource struct {
	Schema  string
	Version migrations.Version
}

PreAuthMigrationSource installs canonical session-owned unauthenticated flow state after the base session schema. Version is a permanent 1..MaxInt64 slot in the sole migration history. Existing session rows/history are unchanged. No raw cookie or authenticated proof is stored; terminal custody is retained. Load performs no IO; no destructive down migration or cleanup is supplied.

func (PreAuthMigrationSource) Load

Load returns an owned forward-only transaction; nil/canceled context and invalid schema/allocation deny before building SQL.

type PreAuthReleaseMigrationSource

type PreAuthReleaseMigrationSource struct {
	Schema  string
	Version migrations.Version
}

PreAuthReleaseMigrationSource adds distinct terminal noncommit state after PreAuthMigrationSource without modifying its applied checksum. Version is an allocated permanent slot in the sole history. The transactional constraint replacement scans existing rows and requires a bounded maintenance window. Original records, indexes and older state transitions remain unchanged. No destructive down migration is supplied.

func (PreAuthReleaseMigrationSource) Load

Load creates one forward transactional migration; invalid allocation and nil/canceled context deny before SQL generation. No IO runs here.

type PreAuthUse

type PreAuthUse struct {
	Command     identity.CommandBinding
	Fingerprint [32]byte
	Generation  uint64
}

PreAuthUse binds one pre-auth reservation to the exact frozen authenticated command, complete coordinator fingerprint and positive ownership generation. Values are structural correlation, not authentication or journal authority. The owning native participant derives them from its live sealed Work; never accept them from requests. Policy and tenant must match the original flow. Actions match directly except the closed phone-recovery request-to-completion relation; that relation preserves the original sessionless identifier binding.

func (PreAuthUse) Format

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

Format hides correlated custody.

func (PreAuthUse) MarshalJSON

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

MarshalJSON rejects implicit custody disclosure.

func (PreAuthUse) MarshalText

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

MarshalText rejects implicit custody disclosure.

type PreAuthWriter

type PreAuthWriter[R SessionRows] interface {
	SessionQueryer[R]
	Exec(context.Context, string, ...any) (int64, error)
}

PreAuthWriter borrows bounded query/write operations from the original sole coordinator transaction. Exec returns affected rows, never a transaction or commit operation. The owner must fence scope/lifetime and abort/poison on every error. Autocommit pools, replicas and independently begun transactions are forbidden in production composition; this interface does not prove that ownership and must never be supplied from client input.

type PrivacyExportAdmissionConfig

type PrivacyExportAdmissionConfig struct {
	GlobalAuthorityID, PolicyNamespace, Audience, AuthenticationMethod string
	CredentialKind                                                     identity.CredentialKind
	CredentialOwner                                                    string
}

PrivacyExportAdmissionConfig opts into native read-only privacy eligibility. Trusted deployment/profile fields have IdentifierAdmissionConfig's semantics. It supports single-factor self-service sessions; organization, factor and passkey applicability deny until their native owner checks are composed. Zero is invalid. Configuration is neither authentication nor access policy.

func (PrivacyExportAdmissionConfig) Format

Format hides deployment and authentication correlations.

func (PrivacyExportAdmissionConfig) MarshalJSON

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

MarshalJSON rejects accidental correlated configuration export.

type Repository

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

Repository owns no pool, transaction, cache or background goroutine. It reads one atomic joined record from the caller-owned PRIMARY pool; never configure replicas. It is safe for concurrent reads. The caller closes the pool after all operations finish. Zero is invalid. Native family revocation writes use only the active shared-coordinator invocation. Explicitly configured native issuance checks current owners and uses the protected proof-bearing profile; complete bearer delivery and rotation remain pending.

func NewRepository

func NewRepository(pool *database.Pool, c Config) (*Repository, error)

NewRepository validates configuration without IO. The database must already have its kernel and adapter migrations applied. It accepts no coordinator, transaction, Work, carrier or registry and does not manufacture domain stores.

func NewRepositoryWithIdentifierAdmission

func NewRepositoryWithIdentifierAdmission(pool *database.Pool, c Config, profile IdentifierAdmissionConfig) (*Repository, error)

NewRepositoryWithIdentifierAdmission validates and freezes an explicit native eligibility profile without IO. Existing NewRepository remains opted out. Pool ownership, schema and maximum duration retain Config's semantics. No coordinator, Work, registry, callback or caller-written store is accepted. The caller must apply the real kernel/session/authorization migrations and register this same Repository as the plan's read-only admission participant.

func NewRepositoryWithIssueAdmission

func NewRepositoryWithIssueAdmission(pool *database.Pool, config Config, profile IssueAdmissionConfig) (*Repository, error)

NewRepositoryWithIssueAdmission freezes the trusted issuance owner profile without IO. Config/pool ownership retain NewRepository's semantics. The same instance must be registered as the protected native feature contributor; requests cannot select another current-authority source or policy namespace.

func NewRepositoryWithPrivacyExportAdmission

func NewRepositoryWithPrivacyExportAdmission(pool *database.Pool, c Config, profile PrivacyExportAdmissionConfig) (*Repository, error)

NewRepositoryWithPrivacyExportAdmission freezes explicit privacy eligibility without IO. Pool lifetime, schema and read budgets retain Config's semantics. Existing constructors remain opted out of privacy. Register this same store instance as the coordinator's native read-only participant. No coordinator, Work, callback or consumer-written domain store is accepted.

func (*Repository) Apply

Apply requires this exact repository's active coordinator feature invocation. Configured authenticated issuance stages the complete session/family record and retained evidence after protected initial admission; the coordinator owns original opaque proof consumption and the required final eligibility check. Revocation stages one active-to-revoked family transition and a retained command binding through that Work, with a full-width checked successor. Every sibling is invalidated by the current family tombstone/version without rewriting its original session snapshot. Missing, foreign-owner, stale or revoked targets return redacted errors, never evidence of another user's existence. The caller must already be authorized by the owning service; no opaque proof or bearer is accepted, minted or revealed. The returned receipt is provisional. This method never begins/closes/retains a transaction or performs network IO; any error requires coordinator Abort. Calls on independent Work are safe.

func (*Repository) ApplyFeature

ApplyFeature is invoked only by the sole coordinator. It reconstructs the closed native command, then delegates to Apply. No audit/lifecycle is staged here: the coordinator owns their exact required phases and terminal receipt.

func (*Repository) CheckAuthenticatedFeature

func (r *Repository) CheckAuthenticatedFeature(ctx context.Context, w kernel.Work, command identity.Command, proof authentication.AuthenticatedProofSpec, final bool) error

CheckAuthenticatedFeature compares the original current owner vector under primary share locks before mutation and again before terminalization. It uses no independent transaction, network IO, snapshot refresh or proof mint. New sessions require a new family at version1 or an exact active existing family; final checks additionally compare the complete persisted session. Every applicable original dimension must agree; optional uncomposed profiles deny. The coordinator owns proof expiry/consumption and poisons failed Work.

func (*Repository) CheckIdentifier

func (r *Repository) CheckIdentifier(ctx context.Context, h kernel.IdentifierAdmissionWork) error

CheckIdentifier performs the registered read-only eligibility invocation on the original coordinator transaction. It reads the command's original active session, derives every applicable owner key, checks global/tenant, exact credential and user epochs, existing authorization authority, then locks and checks the session/family and authoritative expiry. Initial/final comparison uses the original snapshot; only the Work-owned identifier successor changes the final expected epoch. No snapshot, metadata or freshness is rewritten.

Reads are serial under the earlier caller/Work deadline and Config's finite budget. Primary owner locks remain until the coordinator closes Work. No pool access, independent transaction, write, retained handle or callback is used here. Errors deny the invocation and are redacted; the coordinator must poison/abort it. Success is not authentication, fresh reauthentication, policy Allow, proof consumption, issuance or complete protected workflow authority.

func (*Repository) CheckPrivacyExport

func (r *Repository) CheckPrivacyExport(ctx context.Context, h kernel.PrivacyExportAdmissionWork) error

CheckPrivacyExport uses only the selected live original Work: exact session projection, owner-derived scope keys, global/tenant, user/credential and authorization authority followed by session/family share locks and primary expiry. Initial and final checks retain the same original versions and proof metadata; privacy epoch allocation never renews session validity. Reads are serial and bounded by the earlier caller/Work deadline and Config budget. All locks remain until the original transaction closes. No pool IO, write, independent transaction, retained handle or network callback is used. Errors deny and the coordinator poisons/aborts Work. Success is not policy Allow, fresh reauthentication, proof consumption or runnable export admission.

func (*Repository) Descriptor

Descriptor returns the stable native session store identity. It performs no IO and supplies no Work, transaction, registry or execution authority.

func (*Repository) FeatureOperations

func (r *Repository) FeatureOperations() []identity.FeatureOperation

FeatureOperations declares native revocation and explicitly configured protected issuance and source-bound rotation. Issue registration cannot turn structural metadata into opaque proof admission or ordinary execution.

func (*Repository) Get

func (r *Repository) Get(ctx context.Context, tenant identity.TenantID, id string) (StoredSession, error)

Get reads the exact tenant/session ID, including retained revocation state. It is structural inspection only. It cannot certify live authority, emit a credential or disclose another tenant's record. Errors are redacted typed identity cancellation/deadline/unavailable errors or ErrRecordAbsent.

func (*Repository) Lookup

func (r *Repository) Lookup(ctx context.Context, tenant identity.TenantID, digest session.TokenDigest) (StoredSession, error)

Lookup performs one bounded indexed tenant/key-version/digest lookup, never a prefix scan or plaintext comparison. It verifies all 32 returned bytes in constant work and reconstructs the original complete record. Finding a row does not authenticate the bearer or imply expiry/revocation/authority approval. Digest is not an alternate client credential and must never be logged.

func (*Repository) OIDCEndSessionRevoked

func (r *Repository) OIDCEndSessionRevoked(ctx context.Context, tenant identity.TenantID, user identity.UserID, id string) (bool, error)

OIDCEndSessionRevoked reads only the exact source's retained RP-logout disposition from the primary, including after payload pruning. False means only absence of this tombstone, not active authentication or usable grant authority. Callers preserve their original authoritative read-start deadline; this method supplies no lease, cache renewal or stale fallback. Ordinary signout tombstones are deliberately distinct. Missing history fails closed.

func (*Repository) ReadOTPSigninIdentity

func (r *Repository) ReadOTPSigninIdentity(ctx context.Context, b identity.CommandBinding) (OTPSigninIdentity, error)

ReadOTPSigninIdentity performs one bounded structural PRIMARY read of the exact original consuming command's retained identity. It checks the complete binding commitment, actual user/session/family and original record digest. Anonymous-flow commands keep their original empty user target; the result separately identifies the actual recipient. Live payload deletion, expiry and revocation do not erase historical identity or restore credential authority.

Like Get, this is trusted storage inspection, not a public endpoint, disclosure policy, command outcome proof or recovery coordinator. Native callers must authenticate original possession and authorize/correlate the original command before exposing its result. It never writes, compares codes, reconstructs a session, issues a credential or retains resources. Earlier deadlines win; concurrent calls use independent borrowed connections. Missing evidence is ErrRecordAbsent, corrupt evidence is ErrInvalidRecord, and operational errors retain redacted identity cancellation/deadline/unavailable classifications.

func (*Repository) ReadPasskeySignupIdentity

func (r *Repository) ReadPasskeySignupIdentity(ctx context.Context, b identity.CommandBinding) (PasskeySignupIdentity, error)

ReadPasskeySignupIdentity performs bounded structural primary inspection of only the exact original anonymous passkey-signup binding. The existing retained issuance digest binds actual user/session/family and the original record hash; missing or revoked payload never becomes proof of rollback or renewed access. This read grants no disclosure permission and does not authenticate, issue or reconcile other owners. Missing evidence is ErrRecordAbsent; corrupt evidence is ErrInvalidRecord. Operational errors are redacted, errors return zero IDs, and earlier cancellation/deadline wins. Concurrent calls borrow independent connections without retaining the pool or any transaction.

func (*Repository) ReadPasswordSigninIdentity

func (r *Repository) ReadPasswordSigninIdentity(ctx context.Context, b identity.CommandBinding) (PasswordSigninIdentity, error)

ReadPasswordSigninIdentity performs bounded trusted PRIMARY inspection of the exact original password-signin binding and retained issuance commitment. The password-specific digest binds the actual user/session/family and original record hash; anonymous commands retain their empty user target. Live payload deletion, expiry or revocation never removes this historical identity or restores access. OTP and ordinary session issuance cannot satisfy this read.

This storage seam does not authorize disclosure, prove the complete command outcome, compare a password, reconcile effects or issue credentials. Missing evidence returns ErrRecordAbsent; corrupt evidence returns ErrInvalidRecord. Invalid inputs and operational errors are redacted; cancellation and deadline retain existing identity classifications. Errors return zero IDs. Earlier deadlines win; concurrent calls borrow and release independent connections.

func (*Repository) ReadPasswordSignupIdentity

func (r *Repository) ReadPasswordSignupIdentity(ctx context.Context, b identity.CommandBinding) (PasswordSignupIdentity, error)

ReadPasswordSignupIdentity performs bounded trusted PRIMARY inspection of the exact original password-signup binding and retained issuance commitment. The signup-specific digest binds the actual user/session/family and original record hash; anonymous commands retain their empty user target. Live payload deletion, expiry or revocation never removes this historical identity or restores access. Signin, OTP and ordinary issuance cannot satisfy this read.

This storage seam does not authorize disclosure, prove the complete command outcome, compare a password, reconcile effects or issue credentials. Missing evidence returns ErrRecordAbsent; corrupt evidence returns ErrInvalidRecord. Invalid inputs and operational errors are redacted; cancellation and deadline retain existing identity classifications. Errors return zero IDs. Earlier deadlines win; concurrent calls borrow and release independent connections.

func (*Repository) ReadSessionPage

ReadSessionPage reads at most Limit+1 exact tenant/user/audience rows from PRIMARY in one joined statement and returns at most Limit caller-owned records. It includes tombstones and expired records; core owns exact lifetime filtering. AfterSessionID is an exclusive bytewise marker, never authorization. The method is structural, not a public enumeration endpoint or authentication. Labels come from the non-authoritative owned metadata table; install UpdateMigrationSource even when only listing is selected. Never trust a label. Corrupt rows, interrupted reads and store failures return no partial page.

func (*Repository) RecoverParticipant

RecoverParticipant reads this invocation's exact retained mutation binding on the locked primary. Absence proves native noncommit only because these bindings are never pruned with session payloads and all writes share the sole coordinator transaction. Exact presence proves this participant committed, not the complete command receipt. Conflicting/corrupt/missing infrastructure stays Unknown; current family state is never used to reconstruct success.

func (*Repository) ValidateAuthenticatedFeature

func (r *Repository) ValidateAuthenticatedFeature(command identity.Command, original authentication.AuthenticatedProofSpec) error

ValidateAuthenticatedFeature compares every original credential/proof field with the exhaustively mapped native record. It is pure and grants no current eligibility or one-time use. The coordinator validates opaque provenance.

func (*Repository) ValidateFeatureCommand

func (r *Repository) ValidateFeatureCommand(c identity.Command, p identitypostgres.CommandPlan) error

ValidateFeatureCommand checks the complete native schema and exact mandatory security/lifecycle declarations before reservation. The coordinator separately checks registered contributors, budgets, binding digests and keyed intent. Standard or protected retention must be selected by the trusted operation policy; privileged callers require protected retention. This pure method neither authorizes a caller nor reads current family state.

type RevocationMigrationSource

type RevocationMigrationSource struct {
	Base    MigrationSource
	Version migrations.Version
}

RevocationMigrationSource composes the unchanged base install and the native revocation install in the composition's single migration history. Version is a permanent allocation greater than Base.Version and no greater than MaxInt64. Never renumber applied versions. This separate source preserves the original MigrationSource contract, including positional literals. Load performs no IO and is safe for concurrent callers; no destructive down migration is supplied.

func (RevocationMigrationSource) Load

Load returns the independently owned base history followed by the revocation migration. Invalid allocations and nil contexts fail; cancellation is preserved.

type RevokeOneExecutor

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

RevokeOneExecutor owns kernel/native/audit/outbox composition. It accepts no application stores, callbacks, transactions or command journals, starts no goroutines and is concurrency-safe. It authenticates original opaque caller custody and current policy before reservation. Historical receipts do not authenticate a caller. Public idempotent signout/absent handling is separate.

func NewRevokeOneExecutor

func NewRevokeOneExecutor(pool *database.Pool, c RevokeOneExecutorConfig) (*RevokeOneExecutor, error)

NewRevokeOneExecutor validates trusted composition without IO. Sessions must be the exact configured reader that prepared each request, not a request- supplied substitute. It grants no permission to a structural mapped command.

func (*RevokeOneExecutor) ExecuteRevokeOne

func (e *RevokeOneExecutor) ExecuteRevokeOne(ctx context.Context, request session.RevokeOneRequest) (result identity.CommandResult, err error)

ExecuteRevokeOne binds original source and target into one existing command. It checks opaque admission and current policy before reservation, then native primary source/target owner locks before mutation. The earlier caller budget, configured duration and original admission expiry bound the original Work and commit. Admission is checked again before Commit; audit/lifecycle failures roll back the same transaction. Replays return the retained original outcome, never a new transition. Panic, cancellation or lost commit acknowledgement do not prove rollback. Detached coordinator cleanup has its own bounded budget.

func (RevokeOneExecutor) Format

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

Format prevents traversal of runtime dependency/credential configuration.

func (RevokeOneExecutor) MarshalJSON

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

MarshalJSON rejects implicit runtime export.

func (*RevokeOneExecutor) RecoverRevokeOneCommand

RecoverRevokeOneCommand observes the original command under current trusted result-access policy after restart, without original bearer/admission memory. Query must retain every original safe scope field; caller comes from current trusted authentication, never decoded client identity. Missing/denied results do not reserve commands. Recovery returns historical metadata only, never execution permission, a renewed validity lease or a reconstructed session.

type RevokeOneExecutorConfig

type RevokeOneExecutorConfig struct {
	Execution IssueExecutorConfig
	Sessions  *session.SessionService
	// Admission explicitly enables native single-factor methods for caller and
	// target revocation. Nil retains the existing verified-only profile. Selected
	// deployment, namespace and audience must match Execution.Profile. The same
	// frozen selection must construct Sessions; configuration grants no authority.
	Admission *SingleFactorSessionAdmissionConfig
	// MFAMagicLink explicitly selects current confirmed TOTP authority for
	// magic-link source and target sessions. It never enables single-factor
	// fallback; the same profile must be selected by Sessions.
	MFAMagicLink *MagicLinkAdmissionConfig
	// MFAPassword retains current password credential and confirmed TOTP
	// authority for both caller and target. Select the identical native reader
	// profile; nil never downgrades an MFA session to single-factor admission.
	MFAPassword *IdentifierAdmissionConfig
	// Passkey selects the same trusted RP/current-authority port as the source
	// session reader. Nil keeps passkey callers/targets disabled; it never
	// converts their original factor/passkey dimensions into password authority.
	Passkey *PasskeySessionAdmission
	// MFAPasskey retains independent RP mapping and confirmed TOTP authority
	// for both caller and target. The identical profile must read Sessions.
	MFAPasskey *MFAPasskeySessionAdmission
	// OrganizationPassword selects the same owned current organization/member
	// fence as Sessions for single-factor password bearer callers/targets.
	// Nil retains rejection of selected sessions; cookie/MFA profiles deny.
	OrganizationPassword *OrganizationPasswordSessionAdmission
}

RevokeOneExecutorConfig selects the owned current single-factor execution profile and exact trusted session reader used for caller admission. Execution retains the existing policy, clock, audit and coordinator configuration; final signin proof composition is optional because revocation uses session custody. Install the kernel, authorization, session, revocation, audit and outbox migrations first. Dependencies are borrowed and must outlive calls.

func (RevokeOneExecutorConfig) Format

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

Format redacts runtime profile and key configuration.

func (RevokeOneExecutorConfig) MarshalJSON

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

MarshalJSON rejects implicit configuration export.

type RevokeOneMigrationSource

type RevokeOneMigrationSource struct {
	Base    RevocationMigrationSource
	Version migrations.Version
}

RevokeOneMigrationSource appends terminal single-session evidence to the unchanged base/family history. Version is a permanent allocation greater than Base.Version and at most MaxInt64; compose issuance separately when selected. No old record, snapshot or migration is rewritten. Load performs no IO; calls are concurrency-safe and have no destructive down migration.

func (RevokeOneMigrationSource) Load

Load returns independently owned forward-only history. Missing or invalid base/version and nil contexts fail; cancellation retains its classification.

type RevokeSetExecutor

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

RevokeSetExecutor owns native bulk execution and scoped historical result recovery. It starts no goroutines and accepts no application-written stores, transactions or journals. Configuration is immutable and concurrent calls are safe. Historical receipts never supply current authentication or admission.

func NewRevokeSetExecutor

func NewRevokeSetExecutor(pool *database.Pool, c RevokeSetExecutorConfig) (*RevokeSetExecutor, error)

NewRevokeSetExecutor validates explicit composition without IO. The primary pool and dependencies must outlive calls. Missing migrations fail closed at execution; construction never installs them or grants authority.

func (*RevokeSetExecutor) ExecuteRevokeSet

func (e *RevokeSetExecutor) ExecuteRevokeSet(ctx context.Context, request session.RevokeSetRequest) (out session.RevokeSetExecutionResult, err error)

ExecuteRevokeSet admits only original same-reader custody, authorizes before reservation, then delegates whole-set mutation and audit/lifecycle to the sole coordinator. Primary time narrows the unchanged deadline through final commit; slower effect persistence cannot renew it. Replay never executes another set. Known committed receipts remain committed if retained metadata cannot be read; such calls return an error and no count/disposition, never fabricated success. Detached terminal cleanup has the coordinator's separate bounded budget.

func (RevokeSetExecutor) Format

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

Format prevents diagnostic traversal of runtime keys and dependencies.

func (RevokeSetExecutor) MarshalJSON

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

MarshalJSON denies runtime export.

func (*RevokeSetExecutor) RecoverRevokeSetCommand

RecoverRevokeSetCommand authorizes current trusted result access and asks the existing command owner to reconcile the original scope. It works after process restart without bearer or request custody, never reserves missing commands, renews admission, reconstructs from live sessions or issues a replacement.

type RevokeSetExecutorConfig

type RevokeSetExecutorConfig struct {
	Execution IssueExecutorConfig
	Sessions  *session.SessionService
}

RevokeSetExecutorConfig selects the existing owned execution profile and the exact trusted reader that prepared each opaque request. Final-signin issuance is not required. Install kernel, authorization, session, set-revocation, audit and outbox migrations first. Dependencies are borrowed through calls.

func (RevokeSetExecutorConfig) Format

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

Format redacts execution configuration and reader custody.

func (RevokeSetExecutorConfig) MarshalJSON

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

MarshalJSON denies configuration export.

type RevokeSetMigrationSource

type RevokeSetMigrationSource struct {
	Schema  string
	Version migrations.Version
}

RevokeSetMigrationSource adds bounded bulk-command evidence and its selection index to an installed session schema through the sole migrations history. Schema must match the base; Version is a permanent later 1..MaxInt64 slot. Existing records/checksums are unchanged. The transactional index build may block writes on populated deployments; schedule that bounded rollout explicitly. No destructive down migration is provided. Calls perform no IO and are safe concurrently. Evidence has no session FK so payload pruning cannot erase it.

func (RevokeSetMigrationSource) Load

Load returns one independently owned forward migration; nil/cancelled context or invalid schema/version fails before composition. Install through Runner.

type RevokeSetRecoveryResult

type RevokeSetRecoveryResult struct {
	Command                        kernel.CommandRecord
	RevokedCount                   uint32
	SubjectVersion, SessionVersion uint64
	CurrentSessionRevoked          bool
}

RevokeSetRecoveryResult is historical scoped command metadata and, only on verified committed evidence, retained count/source disposition. It contains no credential or permission to execute. An accompanying error leaves count, versions and disposition zero while preserving a known command outcome.

func (RevokeSetRecoveryResult) Format

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

Format redacts correlated historical metadata.

func (RevokeSetRecoveryResult) MarshalJSON

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

MarshalJSON denies implicit historical disclosure; HTTP owns authorized DTOs.

type RotationExecutor

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

RotationExecutor owns atomic native rotation and safe historical recovery. It accepts no application store, journal or transaction, starts no goroutines, and is safe for concurrent calls. Only the core rotator can reveal credentials.

func NewRotationExecutor

func NewRotationExecutor(pool *database.Pool, c RotationExecutorConfig) (*RotationExecutor, error)

NewRotationExecutor validates explicit borrowed composition without IO. Sessions must be the authenticating reader that prepared each original request.

func (*RotationExecutor) ExecuteRotation

func (e *RotationExecutor) ExecuteRotation(ctx context.Context, request session.RotationRequest) (out session.RotationExecution, err error)

ExecuteRotation checks original opaque admission and current policy before reservation, then locks all native owners and performs one source CAS with digest retirement, successor, audit, lifecycle and receipt in the sole Work. Original absolute validity bounds both Work and commit; copies never renew it. Replays return the exact original outcome, not a second mutation or credential. Cancellation, panic and failed commit acknowledgement never prove rollback.

func (RotationExecutor) Format

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

Format redacts borrowed dependencies and runtime key/profile configuration.

func (RotationExecutor) MarshalJSON

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

MarshalJSON forbids implicit runtime export.

func (*RotationExecutor) RecoverRotation

RecoverRotation returns exact historical metadata under current result-access policy even after original admission expiry. It checks the complete retained source/successor, deadline and transport intent. It never reserves or replays effects, renews authentication, or reveals a bearer. Known commitment survives an ancillary evidence error, but no session payload is manufactured on error.

func (*RotationExecutor) RecoverRotationCommand

RecoverRotationCommand recovers historical rotation receipts after restart without the original opaque request, authentication admission or bearer. Query must retain every original safe scope field. Caller must come from trusted current authentication; client-selected actor or tenant overrides grant no access. The configured current policy governs disclosure.

Only command, version and audit metadata are returned, never a session or credential. This result is not current authentication or permission to retry rotation. Missing/denied queries never reserve commands. Live pending leases remain observational; expired pending uses the existing frozen participants and primary recovery owner. Missing/conflicting evidence stays unresolved. Earlier caller deadlines win; detached kernel cleanup retains its own bounded budgets. Borrowed dependencies and concurrency semantics match ExecuteRotation.

type RotationExecutorConfig

type RotationExecutorConfig struct {
	Execution IssueExecutorConfig
	Sessions  *session.SessionService
}

RotationExecutorConfig selects the exact trusted reader and existing native policy/kernel/audit/outbox composition. Final-signin issuance is not required. Install rotation and all prerequisite migrations before execution. Borrowed dependencies must outlive calls; construction performs no IO or grants.

func (RotationExecutorConfig) Format

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

Format redacts key/profile configuration.

func (RotationExecutorConfig) MarshalJSON

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

MarshalJSON forbids implicit configuration export.

type RotationMigrationSource

type RotationMigrationSource struct {
	Schema  string
	Version migrations.Version
}

RotationMigrationSource adds digest retirement and immutable terminal rotation evidence. Schema must match the installed base, and Version is a permanent 1..MaxInt64 slot after that base. It rewrites no existing payload or checksum. Install with the sole migration runner; no destructive rollback or evidence cleanup is supplied. Terminal evidence must outlive prunable session payloads.

func (RotationMigrationSource) Load

Load returns owned forward-only history without IO. Invalid or cancelled input fails before composition; duplicate/unmanaged tables are not adopted.

type SelectedSessionAdmissionConfig

type SelectedSessionAdmissionConfig struct {
	SingleFactor SingleFactorSessionAdmissionConfig
	MFAMagicLink *MagicLinkAdmissionConfig
	// MFAPassword selects genuine password-plus-TOTP/OTP/recovery owners independently
	// of single-factor password and magic-link profiles. No fallback is allowed.
	MFAPassword *IdentifierAdmissionConfig
	// Passkey selects the owned RP/mapping and known-empty factor authority.
	// Stored passkey provenance selects only this owner, never another method.
	Passkey *PasskeySessionAdmission
	// MFAPasskey independently selects original passkey plus confirmed TOTP.
	// It cannot fall back to the known-empty Passkey selection or password MFA.
	MFAPasskey *MFAPasskeySessionAdmission
	// OrganizationPassword retains current organization/member authority for
	// selected single-factor password sessions. Nil continues to reject them.
	OrganizationPassword *OrganizationPasswordSessionAdmission
}

SelectedSessionAdmissionConfig explicitly selects single-factor, passkey and original magic-link/TOTP owners. An MFA record requires the MFA selection; a failed factor read never falls back to a single-factor profile. All selected owners must share deployment, policy namespace and audience.

func (SelectedSessionAdmissionConfig) Format

Format redacts deployment, profile and key configuration.

func (SelectedSessionAdmissionConfig) MarshalJSON

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

MarshalJSON rejects implicit correlated configuration export.

func (SelectedSessionAdmissionConfig) MarshalText

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

MarshalText rejects implicit configuration export and map-key disclosure.

type SelectedSessionServiceConfig

type SelectedSessionServiceConfig struct {
	Repository Config
	Admission  SelectedSessionAdmissionConfig
	Validation session.ServiceConfig
}

SelectedSessionServiceConfig retains the native repository and validation budgets and ownership. Install every selected owner's migration histories. The pool is borrowed and must outlive calls; no application store is needed.

func (SelectedSessionServiceConfig) Format

Format redacts deployment, profile and key configuration.

func (SelectedSessionServiceConfig) MarshalJSON

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

MarshalJSON rejects implicit correlated configuration export.

func (SelectedSessionServiceConfig) MarshalText

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

MarshalText rejects implicit configuration export and map-key disclosure.

type SessionAuthorityKeySet

type SessionAuthorityKeySet struct{ Family, Session string }

SessionAuthorityKeySet contains version-one session-owner scope keys, not versions, active-state evidence or authentication. Keys correlate identity state and must not be logged. Family binds tenant/user/family; Session adds the session ID, so a family switch cannot retain the previous session key.

func SessionAuthorityKeys

func SessionAuthorityKeys(tenant identity.TenantID, user identity.UserID, family, id string) (SessionAuthorityKeySet, error)

SessionAuthorityKeys derives exact keys from the session owner's existing 1..128-byte visible-ASCII ID profile without normalization. Each key is its dimension plus ":v1:" and the unpadded base64url SHA-256 of "golib.identity.session.authority.v1\x00", followed by the dimension and scope components framed by big-endian uint16 byte lengths. Family's dimension is "session_family"; Session's is "session". Framing prevents delimiter aliases. Historical custom keys are not silently migrated. Invalid inputs return redacted InvalidInput and zero output. No IO, lease or callback occurs; callers must keep inputs immutable during this concurrency-safe operation.

Example
package main

import (
	"fmt"

	"github.com/faustbrian/go-identity/session/postgres"
)

func main() {
	keys, err := postgres.SessionAuthorityKeys("tenant-a", "user-a", "family-a", "session-a")
	if err != nil {
		panic(err)
	}
	// Do not log the correlation keys. Derivation alone proves no authority.
	fmt.Println(keys.Family != keys.Session)
}
Output:
true

func (SessionAuthorityKeySet) Format

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

Format redacts internal correlation keys.

func (SessionAuthorityKeySet) MarshalJSON

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

MarshalJSON rejects implicit correlation-key export.

func (SessionAuthorityKeySet) MarshalText

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

MarshalText rejects implicit correlation-key export.

type SessionQueryer

type SessionQueryer[R SessionRows] interface {
	Query(context.Context, string, ...any) (R, error)
}

SessionQueryer preserves the native owner's narrower row type without raw connection escape. Protected operations require the original primary transaction, never a replica or autocommit pool. The owning participant must fence its scope/lifetime and poison or abort on every returned error.

type SessionRows

type SessionRows interface {
	Next() bool
	Scan(...any) error
	Err() error
	Close()
}

SessionRows is the synchronous borrowed cursor contract implemented by pgx Rows and identity's generation-bound WorkRows. Close releases only this result; it must not terminalize the original transaction.

type SessionServiceConfig

type SessionServiceConfig struct {
	Repository Config
	Profile    IdentifierAdmissionConfig
	Validation session.ServiceConfig
}

SessionServiceConfig selects an explicit single-factor stateful profile. Repository borrows a migrated PRIMARY pool; its read budget must not exceed Validation.MaximumDuration. Profile's audience must equal Validation's. Directory, user/status, identifier, credential, authorization and session migrations are required. Validation retains core clock/key/profile semantics. No application-written domain store, transaction or policy callback is used.

func (SessionServiceConfig) Format

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

Format redacts profile and key configuration.

func (SessionServiceConfig) MarshalJSON

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

MarshalJSON denies implicit configuration export.

type SetRevocationServiceConfig

type SetRevocationServiceConfig struct {
	Execution       IssueExecutorConfig
	Validation      session.ServiceConfig
	MaximumSessions uint32
	MaximumDuration time.Duration
}

SetRevocationServiceConfig selects one owned primary/execution profile and whole-call all-or-nothing bound. Validation.Clock must be nil: Execution.Clock owns authentication and execution. Earlier admission/freshness always wins. Dependencies are immutable and borrowed until calls finish. Zero is invalid.

func (SetRevocationServiceConfig) Format

Format redacts authority, policy and key configuration.

func (SetRevocationServiceConfig) MarshalJSON

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

MarshalJSON denies implicit configuration export.

type SignOutServiceConfig

type SignOutServiceConfig struct {
	Execution       IssueExecutorConfig
	Validation      session.ServiceConfig
	Cookie          session.CookiePolicy
	MaximumDuration time.Duration
}

SignOutServiceConfig selects owned primary authentication and transactional revocation. Execution owns the sole schema, authority profile, trusted clock, policy and audit/outbox composition. Validation.Clock must be nil: the factory supplies Execution.Clock to both authentication and execution, preventing contradictory time sources. Validation retains its key, audience, storage, read-budget and uncertainty rules. MaximumDuration bounds the whole logout call to 1ms..30s; earlier caller and authority deadlines always win. Zero is invalid. Configuration and dependencies must not be mutated during calls.

func (SignOutServiceConfig) Format

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

Format redacts key, policy and authority configuration.

func (SignOutServiceConfig) MarshalJSON

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

MarshalJSON denies implicit configuration export.

type SingleFactorSessionAdmissionConfig

type SingleFactorSessionAdmissionConfig struct {
	Verified  *IdentifierAdmissionConfig
	OTP       *OTPAdmissionConfig
	MagicLink *MagicLinkAdmissionConfig
}

SingleFactorSessionAdmissionConfig explicitly selects owned authentication profiles. At least one is required; deployment, policy namespace and audience must agree. No selection implies authority for another method. Organization, MFA and passkey dimensions remain denied until their owners are composed.

func (SingleFactorSessionAdmissionConfig) Format

Format redacts correlated native owner configuration.

func (SingleFactorSessionAdmissionConfig) MarshalJSON

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

MarshalJSON rejects implicit configuration export.

type SingleFactorSessionServiceConfig

type SingleFactorSessionServiceConfig struct {
	Repository Config
	Admission  SingleFactorSessionAdmissionConfig
	Validation session.ServiceConfig
}

SingleFactorSessionServiceConfig selects one bounded primary lookup followed by dispatch on the stored authentication kind. Repository and Validation retain their existing ownership, cancellation and lifetime contracts. Install every selected method's native migration histories before calls. No fallback reader, caller-owned domain store, transaction or policy callback is accepted.

func (SingleFactorSessionServiceConfig) Format

Format redacts key and deployment configuration.

func (SingleFactorSessionServiceConfig) MarshalJSON

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

MarshalJSON rejects implicit configuration export.

type StoredSession

type StoredSession struct {
	Session                session.Session
	Revoked, FamilyRevoked bool
	CurrentFamilyVersion   uint64
}

StoredSession is a structural primary projection, NOT proof of authentication or current authority. Session retains its original authority snapshot; CurrentFamilyVersion and tombstones are separately read current family facts. Callers must deny revoked families/records and perform every online authority, scope, expiry and bounded-validity check before accepting a credential. No method here mints a bearer, renews evidence, or changes the stored vector.

type UpdateExecutor

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

UpdateExecutor owns native atomic self-session label CAS and historical outcome recovery. It accepts no application store, journal or transaction, starts no goroutines and is safe concurrently. Borrowed dependencies/pool must outlive calls. Zero is invalid; construction performs no IO.

func NewUpdateExecutor

func NewUpdateExecutor(pool *database.Pool, c UpdateExecutorConfig) (*UpdateExecutor, error)

NewUpdateExecutor validates explicit native composition without granting permission or beginning a transaction. Sessions must prepare every request.

func (*UpdateExecutor) ExecuteUpdate

func (e *UpdateExecutor) ExecuteUpdate(ctx context.Context, request session.UpdateCommandRequest) (out session.UpdateExecution, err error)

ExecuteUpdate checks original opaque admission and current exact policy, then executes label/session CAS, audit, lifecycle and receipt in the sole Work. Original absolute validity bounds the transaction and final commit. Exact replays observe history, never reapply. Post-entry ambiguity/panics never prove rollback; known commitment survives ancillary metadata errors.

func (UpdateExecutor) Format

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

Format redacts borrowed dependencies and runtime policy/key configuration.

func (UpdateExecutor) MarshalJSON

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

MarshalJSON denies implicit executor export.

func (*UpdateExecutor) RecoverUpdate

RecoverUpdate observes/reconciles exact historical outcome under current result-access policy, even after source expiry. Original same-reader custody is historical only; no authentication renewal, mutation or label is returned.

func (*UpdateExecutor) RecoverUpdateCommand

RecoverUpdateCommand supports restart-safe outcome observation using exact original safe scope and trusted current caller context. It never accepts a structural session as authentication, renews a lease or reserves missing IDs. Current configured access policy governs disclosure; no device/label payload is returned. Cancellation and earlier caller deadlines bound the operation.

type UpdateExecutorConfig

type UpdateExecutorConfig struct {
	Execution IssueExecutorConfig
	Sessions  *session.SessionService
}

UpdateExecutorConfig borrows the exact authenticating reader and existing native policy/kernel/audit/outbox composition. Final-signin admission is not required for display labels. Install UpdateMigrationSource before use.

func (UpdateExecutorConfig) Format

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

Format redacts borrowed dependencies and configuration for every verb.

func (UpdateExecutorConfig) MarshalJSON

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

MarshalJSON denies implicit runtime configuration export.

type UpdateMigrationSource

type UpdateMigrationSource struct {
	Schema  string
	Version migrations.Version
}

UpdateMigrationSource installs non-authoritative labels and retained update participant evidence after the existing session/kernel history. Version is a permanent 1..MaxInt64 slot. It rewrites no existing row or checksum and does not change positional old-binary session writes or the closed codec. Current labels cascade with payload deletion; historical evidence stores only their digest, not plaintext. No destructive rollback/cleanup is supplied.

func (UpdateMigrationSource) Load

Load validates allocation/cancellation and returns independently owned, forward-only transactional SQL without IO. Use the sole migration Runner.

type UsernameSigninMigrationSource

type UsernameSigninMigrationSource struct {
	Schema      string
	Version     migrations.Version
	Predecessor UsernameSigninPredecessor
	// MFASignin records the MFA-before-verification variant of the installed
	// v7 constraint. It is valid only with UsernameSigninAfterVerification.
	// The verification-first v8 predecessor already includes MFA unambiguously.
	MFASignin bool
}

UsernameSigninMigrationSource adds the exact username-signin purpose while preserving every installed predecessor purpose. Schema and Version are permanent explicit composition; the caller's migration runner owns locks and transactions.

func (UsernameSigninMigrationSource) Load

Load builds one forward-only suffix. It changes no existing issuance or bytes.

type UsernameSigninPredecessor

type UsernameSigninPredecessor uint8

UsernameSigninPredecessor identifies the already-installed purpose constraint, not an authentication policy. Installing older suffixes afterward is invalid.

const (
	// UsernameSigninAfterPassword follows PasswordSigninMigrationSource.
	UsernameSigninAfterPassword UsernameSigninPredecessor = 3
	// UsernameSigninAfterSignup retains PasswordSignupMigrationSource purposes.
	UsernameSigninAfterSignup UsernameSigninPredecessor = 4
	// UsernameSigninAfterMagicLink retains MagicLinkSigninMigrationSource purposes.
	UsernameSigninAfterMagicLink UsernameSigninPredecessor = 5
	// UsernameSigninAfterMFA retains the factor-completion purpose profile.
	UsernameSigninAfterMFA UsernameSigninPredecessor = 6
	// UsernameSigninAfterVerification retains verification-only signin purposes.
	UsernameSigninAfterVerification UsernameSigninPredecessor = 7
	// UsernameSigninAfterVerificationMFA retains verification plus MFA purposes.
	UsernameSigninAfterVerificationMFA UsernameSigninPredecessor = 8
)

Source Files

Jump to

Keyboard shortcuts

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