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

identitycapability

package module
v0.0.0-...-f510d49 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 27 Imported by: 7

README

Identity capability PostgreSQL participant

issuer.PrepareAccountLinkConsumption(ctx, command, proof, originalReplayVersion) reauthenticates an already-issued canonical explicit self-link proof before counter enrichment. The root command constructor binds the full provider, target, actor, session, policy and mutation intent; preparation accepts only its exact original envelope under the configured issuer, audience, revocation and time policy. Implicit, administrative and enriched commands deny. Retained replay-key custody and signed expiry remain unchanged, including after rotation.

Preparation performs no SQL, signing, custody transfer or consumption. Compose the existing Participant with the native AccountLinkUnitOfWork and actual provider/session/policy/risk owners for atomic one-use consumption, mutation, audit, lifecycle and conservative recovery. A plan is not provider authority or a commit receipt. This seam does not implement OAuth state reservation before exchange or attachment of a grant minted after exchange; those require their separate coordinator-owned preparation and capability-issued custody.

RetireEmailVerificationGrants is callable only by the exact original native email-removal Apply after the kernel locks/prepares its full directory partition. It uses the same Work, not a new transaction or authority. Revoke only unused issued/reserved grants with that retained signed identifier target; preserve consumed/other-target history and all reservation/origin metadata. Live unclassified legacy grants deny removal, never guess targets or bulk-retire a subject. Propagate every error to roll back the complete protected mutation.

Optional Go 1.27 module implementing capability-owned reservation and recovery through the sole identity PostgreSQL Coordinator. This is a storage adapter, not a workflow, signing service or independently committable store.

The module path is github.com/faustbrian/go-capability/postgres/identity. Supply the trusted deployment issuer in IssuerConfig.Crypto.Issuer and in verifier-key ownership; issuance and verification must not select that trust from a parsed token. Existing cap1 wire bytes and this adapter's separate coordinator ledger stay unchanged. The root capability store's explicit legacy-issuer migration applies only to its own consumption tables, never this adapter's identity tables.

Quick start and API

PrepareAnonymousUpgradeConsumption reauthenticates the original signed proof for identity.anonymous.upgrade / identity.anonymous.upgrade.native-v1 v1. The user actor and subject are the permanent target; the distinct record is the guest. Supply AnonymousUpgradeScope, original envelope and retained replay-key version from authenticated original native preparation, never HTTP assertions. Exactly five signed anonymous.* caveats bind the source version, both original session IDs, canonical merge digest and session/persistent remember selection. The signed expiry cannot exceed the original guest's positive UTC microsecond expiry. Original fingerprint, replay identity and signed expiry are preserved. This is read-only metadata preparation: no signing, SQL, consumption or renewal. It cannot substitute for current action-bound target credential proof from the native password ActionPrimarySource. Native identity/session owners must still prove current guest, target, sessions, merge and policy and use the existing capability participant atomically with all effects in the sole coordinator.

PrepareRegistration accepts the exact anonymous identity.password.signup (password-signup, v1) or identity.username.signup (username-signup, v1) origin. It preserves the original operation/schema throughout preparation and recovery. A username route cannot impersonate a password origin or vice versa. This is unsigned-workflow composition, not registration authority: the existing kernel must still prove actual identity creation and stage the grant in its single protected transaction. Ordinary Prepare has no anonymous override.

PrepareOrganizationInvitationConsumption authenticates an original invitation proof for identity.organization.invitation.accept. Supply the authenticated retained envelope, replay-key version and OrganizationInvitationScope from the original durable invitation; never use client-selected expected metadata. It binds the signed recipient, invitation resource, organization, role, versions, trusted issuer and single configured audience. It returns only preparation metadata: no consumption, membership, delivery, expiry renewal or transaction. The organization owner must still fence current verified-recipient and session authority, policy and limits and consume atomically with membership/audit effects through the sole identity coordinator. The existing native coordinator must support that closed invitation profile before this preparation can be executed.

Original identity.organization.invitation-send / organization-invitation-send v1 recovery additionally permits the existing fenced absence proof for exactly one accept-purpose grant. The sealed coordinator supplies the original command, tenant, inviter, recipient, record and frozen grant; ordinary caller metadata is not recovery authority. A missing exact row alone is insufficient: capability ID, replay identity and every issuance of the originating command must all be absent. Conflicting or retained evidence remains unknown; expiry is never proof of rollback. Each other participant still votes before the sole coordinator classifies the command. No proof is signed, renewed, consumed or redelivered, and no schema change is required. Other issuance profiles are unchanged.

IssuerConfig.RetainEmailVerificationTargets explicitly selects migration 005. It retains the exact authenticated signed identifier resource during the same original issuance transaction, including signup and unselected managed links. Enable it on every native verification issuer before selecting email removal. False preserves the prior issuance SQL and does not require the new column. The populated upgrade never guesses a target or rewrites retained origin/use history. Active original verification grants without target classification must make removal fail closed; originless grants cannot safely be assigned even to a subject. Expired or terminal history remains unchanged. Do not backfill targets from current addresses or unsigned caller annotations.

The removal storage transition revokes only unused issued/reserved verification grants with the exact tenant, subject and retained identifier. It preserves consuming-command/generation, original provenance, expiry and replay metadata. Exact reserved-but-unused revoked evidence remains negative for native recovery; unanimous noncommit reconciliation preserves revocation rather than reactivating or converting it into usable proof. The public native removal orchestration and its complete lifecycle are still unfinished; these storage prerequisites are not an independently executable removal API.

ManagedEmailScopeFromPayload projects the stable bounded family of a management-v1 identifier-verification grant. An explicitly selected fifth email.supersession caveat must match that family. Fresh commands, times, callbacks, key versions and observed authority cannot escape predecessor invalidation. This metadata is not authentication or permission to resend.

Install migration 004 after the unchanged 003 history before selected management supersession. Issuance reuses the existing family columns and one-use participant; replacement commit invalidates older unused selected grants, while rollback retains predecessor validity and original recovery custody. Selected inspection and managed consumption deny superseded rows. Consumed, unselected and other families remain untouched. The native email workflow must acquire the same family fence before identity/factor/capability locks and enforce current pending state, fresh primary/factor/risk authority and 30s..10m cooldown (reference 60s). It must commit pending-generation changes, encrypted delivery and replacement issuance together. These adapter seams do not yet supply that public resend path.

issuer.PrepareManagedVerificationConsumption(ctx, confirmationBinding, proof, originalEnvelope, originalReplayVersion) prepares the exact management-v1 email link for identity.email.verification-confirm.managed-v1. Signup links and change-confirm schemas deny. The signed purpose, subject/resource, intent caveats, expiry and retained replay identity are unchanged. This performs no SQL, signing or consumption. The native email owner still authenticates the original encrypted request and current credential/account/factor/risk authority; the existing Participant consumes proof atomically with the protected effect. This seam does not issue sessions or provide a primary-address change workflow.

issuer.PrepareMFAContinuation(ctx, consumeBinding, payload) signs one identity.mfa.complete child for the closed anonymous magic-link consumption, password-signin, username-signin or phone-password-signin profile. Each retains its exact original operation and schema; encrypted restoration never converts one into another. Supply the canonical challenge ID and exact MFA profile/scope caveats already frozen by the native owner. The child is bounded to five minutes; kernel staging additionally enforces the original primary expiry and complete scope. This method grants no factor or session authority. Original encrypted preparation binds the MFA subject and preserves signed bytes, ID and expiry across retries without renewing disclosure. Real native factor persistence and completion remain required before a public MFA login can use this profile.

issuer.PreparePasskeyMFAContinuation(ctx, binding, payload) selects the separate native UV-passkey primary profile. Its exact self-user signin-verify.native-v1 command uses its own ID as record and signed child correlation. This method does not validate an assertion or bypass an enrolled factor: the genuine native assertion owner must prove browser, user, key and factor authority before the kernel stages the child. The same encrypted preparation preserves original bytes and expiry on recovery. Existing anonymous primary APIs stay unchanged.

issuer.PrepareMFAConsumption(ctx, factorBinding, recipientUserID, continuationID, scopeDigest, configuredIssuer, proof, originalEnvelope, originalReplayVersion) verifies that same child for the closed anonymous TOTP, OTP, recovery-code or security-key completion operation. Supply original authenticated continuation and issuance metadata, never request-selected identity or current-key defaults. The exact signed child/profile/scope, tenant, recipient, issuer, audience and one-use bounds must match; signed purpose stays identity.mfa.complete, not the factor operation. It preserves original envelope, expiry and replay identity without transfer, signing or SQL.

This is not factor proof or permission to issue a session. The MFA owner still checks original browser/primary/remember scope, allowed factor, current policy, account/factor authority and shared attempts, and verifies the actual factor. The sole coordinator consumes the original child atomically with successful factor replay, continuation completion, session and audit/lifecycle effects. No public MFA authentication workflow is supplied by this capability seam.

issuer.ReadMFAMagicLinkParent(ctx, primaryPool, originalChild, originalParentID, originalParentEnvelope, originalParentExpiry) resolves the already-consumed parent from authenticated continuation custody. The parent's consumer command/fingerprint/generation must equal the child's original issuance tuple. Bindings supplies the original request and primary identities and signed times, not the parent's decoded payload or access authority. The magic-link owner reconstructs its entire original payload using existing request custody and must call parent.MatchPayload(payload) before using that metadata. The opaque retained digest rejects changed or incomplete reconstruction. No primary bearer, new intent table, signing, use or expiry renewal is involved. Current browser, account, factor, policy and child authority still need their native protected-transaction checks. Install the complete existing capability adapter history, including original issuance and magic-link supersession.

issuer.PrepareMagicLinkConsumption(ctx, consumeBinding, recipientUserID, identifierID, proof, originalEnvelope, originalReplayVersion) verifies original proof custody for anonymous identity.magic-link.consume / magic-link-consume version one. Supply the authenticated envelope and replay version from original durable issuance, not client input or current-key defaults. Signed tenant, recipient, identity.magiclink/<identifierID> resource, identifier caveat, audience and one-use limit must match; an alternate valid envelope denies. No reservation, consumption, transfer, signing or expiry renewal occurs.

The resulting plan is not login permission. The native owner must authenticate the complete original payload and encrypted intent, callback/pre-auth custody and current recipient/factor/risk authority, then enlist this module's existing Participant with all session/audit/lifecycle effects in the sole transaction. Bounded signature/revocation verification applies; failed or cancelled calls return a zero plan and redacted typed error. Retained replay keys remain usable after active-key rotation without changing the original consuming identity.

issuer.PrepareMagicLinkRecipient(ctx, originalRequestBinding, recipientUserID, payload) prepares one identity.magic-link.consume grant for the exact anonymous identity.magic-link.request / magic-link-request version-one profile. It uses the existing signer and opaque proof custody; it is not recipient eligibility or authentication. Before staging, the native identity/magiclink/postgres owner must call the kernel's RequireMagicLinkRecipient with the original verified email snapshot and supply its documented magiclink.* signed scope caveats. Original command scope remains anonymous. Ordinary, signup and password-reset preparation cannot borrow this selection.

For selected resend behavior, project MagicLinkScopeFromPayload from the authenticated/reconstructed original magiclink.* payload. It binds the exact issuer, audience, tenant, recipient, identifier, callback, intent and browser flow/profile; token IDs, dates and observed authority versions do not change that scope. Set signed magiclink.supersession to lowercase hex of Digest(). This is metadata, not authentication or recipient eligibility. Install migration 003 before using this selection. Historical rows without it remain unchanged.

The native request and consume feature must call LockMagicLinkSupersession in their exact Apply invocation before account, factor or browser row locks. Do not hold the fence across signing, risk/provider preparation or callbacks. Selected issuer persistence registers the new scope and invalidates earlier issued/reserved unused links in that same transaction. Consumption acquires the same fence before capability row locks and rejects superseded rows. Recovery and terminal release preserve original command, generation and use evidence. A consume already holding the fence can commit; resend then leaves its consumed evidence intact. This native contract still requires the complete workflow's scope reconstruction and HTTP composition.

issuer.ReadMagicLinkOrigin(ctx, primaryPool, proof) also returns an authenticated superseded flag from that same original-issuance read. It requires the stored scope to match the signed claim and returns zero metadata on failure. ValidateIssuedProof denies superseded links; historical origin remains readable for command retries, not reusable authority. A workflow must check browser scope before exposing distinctions publicly and repeat admission atomically: a read cannot prevent a subsequent resend or establish a committed command outcome.

Use the existing IssuancePreparationCodec for encrypted durable retry custody. Its magic-link-specific authenticated context binds the selected recipient while leaving older profiles byte-identical. Restoration preserves the original grant, replay key, expiry and ciphertext; it cannot reveal a bearer again. Issuance and encrypted delivery enlist in the sole coordinator transaction. Recovery reports absent issuance as not committed only under the original recovery fence when the grant, keyed replay identity and originating-command rows are all absent; conflicting evidence remains unknown. Neither preparation nor origin inspection implements resend/supersession, factor policy, consume or session orchestration.

issuer.PreparePhonePasswordResetConsumption(ctx, originalJointResetCommand, originalReplayVersion) authenticates only the canonical capability retained in the sealed PhonePasswordResetInputFeature/InputCustody or generated PhonePasswordResetFeature/Custody command. It requires the exact identity/phone / identity.phone.password-reset-complete / identity.phone.password-reset-complete.native-v1 version-one descriptor. The signed identity.password/<credentialID> resource, tenant, user, audience and one-use limit must match. No externally supplied replacement proof or generic/single-code conversion is accepted; original password/hash, capability, SMS, independent TOTP and browser-cookie custody remain together unchanged. The original retained replay-key version and absolute expiry are preserved.

Phone issuance uses the existing user-bound Issuer.Prepare owner with the canonical identity.phone.password-reset-complete payload. It does not borrow the email-only anonymous ResetRecipientUserID profile. The native service must resolve and fence the actual phone/password/factor/browser scope; issuance and encrypted restoration alone do not prove recovery eligibility. Consumption preparation does not sign, transfer, reserve, consume or begin a transaction. The existing Participant and sole identity coordinator must consume capability, OTP and risk atomically with canonical password replacement and required session effects. These adapter seams do not establish complete phone recovery acceptance.

issuer.PreparePasswordResetConsumption(ctx, originalResetCommand, originalReplayVersion) derives a one-use consumption plan directly from the paired opaque proof retained by identity.NewFeaturePasswordResetInputCommand or identity.NewFeaturePasswordResetCommand. Use the original input form to prepare the same plan before authoritative admission and password hashing. There is no substitute proof argument. The exact reset descriptor and signed identity.password/<credentialID> resource must match the command, along with tenant and user. The issuer rechecks configured signature, audience, time and revocation policy and uses the explicitly retained issuance key version, not the active default. Repeated preparation preserves envelope, expiry and replay identity; it performs no SQL, signing, transfer, reservation or consumption.

This plan alone cannot reset a password. The native password workflow must authenticate durable original issuance intent and its closed recovery profile, check current identifier/factor eligibility and HIBP/risk, and compose password mutation and required session effects with capability use in the sole kernel transaction. Obtain the original replay version from authenticated issuance provenance. Retain that key through recovery; expired or transferred custody cannot be renewed through preparation. Errors return a zero plan and redacted typed classification. Earlier deadlines and the issuer timeout bound work.

issuer.ReadIssuanceOrigin(ctx, primaryPool, proof, trustedPurpose) reads exact original provenance for an explicitly selected one-use purpose, including password reset. issuer.ValidateIssuedProof has the same arguments and also requires issued, unused, primary-unexpired state in that read. Both preserve original replay-key version, signed envelope and timestamps. Retain replay keys until their original credentials no longer need them; never substitute the active version on a retry. Neither method reserves or consumes a proof.

These are trusted adapter seams, not public scanner responses or reset permission. The owning workflow must validate its closed purpose-specific payload and encrypted original intent, current account/factor/risk eligibility, exact tenant/subject/callback and transactional one-use effects. Do not expose their sensitive grant/command projections publicly. Historical origin lookup can observe terminal provenance but still enforces configured signature, audience, time and revocation policy; it does not make that proof reusable. Earlier cancellation and the issuer timeout bound one indexed primary read and crypto. Failure returns zero metadata; pools and opaque proof custody are borrowed. Registration-specific methods retain their stricter closed profile.

issuer.PrepareRegistrationVerificationConsumption(ctx, binding, proof, originalEnvelope, originalReplayVersion) prepares the anonymous signup profile for the current native email confirmation action. The signed purpose remains identity.identifier.verify; the current binding identifies the actual caller, tenant, user and signed identifier, without introducing session caveats. The email owner must authorize the original mailbox/redirect/version commitment first. This rechecks configured crypto/time/revocation and preserves original envelope/expiry/replay metadata, but performs no SQL, reservation, consumption or signing. A plan is not current authority or a usable confirmation transaction; native kernel atomic confirmation composition remains in development.

issuer.ReadRegistrationOrigin(ctx, primaryPool, proof) authenticates a registration-profile signup proof and matches its exact original positive issuance, returning the grant, original command and retained replay-key version. It is bounded and read-only: repeated or concurrent reads cannot reserve, consume, issue, deliver or renew a credential. Key rotation must retain the original replay key; unavailable retained keys fail closed.

This lookup is a trusted composition seam, not public email validation or a signup receipt. The origin owner must authenticate the original encrypted signup input and email intent. Confirmation must separately check current account/identifier and capability state and consume atomically with the protected mutation. Historical provenance remains readable independently of the row's consuming state; it never grants permission to use a terminal token.

For a privacy-export command, use issuer.PreparePrivacyExportConsumption(ctx, command, proof, originalReplayVersion). It authenticates the original opaque proof under the same configured verification and retained-key derivation as identifier consumption. Even another trusted signature over identical payload metadata is distinct custody and is rejected. The returned plan alone cannot enable privacy reservation or execution: the kernel must still compose current native session/policy checks, atomic durable proof use, all 23 captured cuts, audit/lifecycle and terminal receipt recovery. Preparation does not transfer or consume bearer custody and cannot renew its lifetime. Snapshot integrity and current authority remain their owners' concerns.

Before a protected identifier transaction, call issuer.PrepareIdentifierConsumption(ctx, command, proof, originalReplayVersion) to obtain the capability plan. command is the immutable core identifier command; proof must be the exact original opaque signed envelope. Preparation rechecks the configured signature, audience, time and revocation policy; it never transfers or consumes the proof. The version comes from trusted original issuance metadata or server policy, never a bearer-selected default. Keep the original version after replay-key rotation: selecting the current key produces different metadata which cannot match the issued durable record. The native participant still owns exact durable matching and coordinator-only atomic use. This method is not current session/policy/ceremony admission or a commit receipt.

Install Migrations() through your migration backend with a separate adapter ledger. Compose the real kernel, audit and outbox before coordinator construction:

participant := identitycapability.NewParticipant()
registry, err := identitypostgres.NewContributorRegistry([]identitypostgres.Contributor{
    repository, auditContributor, lifecycleContributor, participant,
})

Only the coordinator may invoke phases using its frozen registry and sealed handles. Registration grants neither cryptographic validation nor current identity/session authority. No pool, transaction, callbacks, keys or goroutines are retained; instances are immutable and concurrent-safe across independent commands. Each handle is serial-use. Nil/zero participants and fabricated, foreign or stale authority fail before writes. Cancellation/deadlines and conflicts remain typed; SQL errors never expose diagnostics or private values.

  • NewParticipant: stateless default-schema instance, without I/O.
  • Descriptor: capability/postgres, capability.one-use, version 1.
  • ReserveCapability: existing issued to reserved, without consumption.
  • RebindCapability: CAS exact command/fingerprint/prior generation with live primary expiry. Missing, terminal or changed input cannot be reserved.
  • ApplyCapability: provisionally consume the exact reserved current generation only below the original signed maximum. Row locking precedes primary expiry evaluation, so waiting cannot carry positive validity beyond its expiry.
  • FinalizeCapability: recheck original primary expiry and mark that exact consumed reservation finalized, in the same protected transaction. Neither method closes a transaction or determines the command outcome.
  • RecoverParticipant: exact frozen primary evidence. Missing/conflicting evidence stays unknown; participant commit evidence is not a command receipt.
  • ReleaseCapability: only unanimous non-commit authority permits terminal release. It never makes a bearer reusable. Expiry alone cannot release it.
  • Migrations: additive embedded SQL independent of legacy consumption rows.

Adoption, compatibility and tradeoffs

The root go-capability/v2/postgres.ConsumptionStore remains a separate store with its own documented issuer-ownership migration. It owns separate transactions and cannot provide atomic identity mutations. This optional nested module avoids a dependency cycle: identity consumes capability, so the core must not depend on identity/postgres. There are no permanent replacements or mandatory root dependencies on this module. No legacy row is imported, reset or removed; missing records are never inserted during reserve. Mixed binaries retain the separate legacy schema. Downgrade and time-based deletion are unsupported because erasing one-time evidence permits replay. Never reinterpret legacy consumed bearers as issued.

Security and unfinished scope

Application roles must not own tables or have DDL, TRUNCATE, DELETE or trigger-disable authority. Raw bearers and cryptographic keys are not stored; retained keyed digests, opaque IDs, proof/command fingerprints and generations are sensitive correlation metadata. Restrict them to trusted composition. Participant formatting is redacted and JSON export rejected. Status and release accept the exact original expiry even after it passes, without renewing authority.

Native consumption/apply and finalization SQL are implemented; revocation, tombstone cleanup/key retirement and complete identifier orchestration remain unfinished. Do not deploy this as a complete workflow. Tests seed issued metadata explicitly as fixtures, not a production issuer or session/risk authority. The current coordinator still rejects capability-bearing domain Begin.

Real PostgreSQL tests exercise the private SQL operation delegated to by the phase methods, including rollback, maximum-use contention, unchanged binding and expiry during a lock wait or between apply/finalize. These tests do not fabricate coordinator handles or prove successful public domain execution. Closed phase custody is tested by identity/postgres; successful native callback composition remains required when its complete authorized domain path is ready.

FAQ and examples

Can lease or token expiry release a reservation? No: every frozen participant must prove non-commit. Can released evidence be reused? No: retry needs newly issued evidence. Does status replace cryptographic verification? No: trusted composition validates the proof before preparing independently keyed metadata.

The compile-checked example demonstrates registration identity; integration tests use the real coordinator, audit, outbox and capability participants with disposable PostgreSQL. Exact coverage/mutation and release gates remain pending. See CHANGELOG.md for release notes.

Original issuance

Durable preparation custody

NewIssuancePreparationCodec(issuer, config) selects a deployment-bound local keyring and concrete HMAC/Ed25519 verification keys. It does not reuse potentially remote signing resolvers or revocation callbacks during restoration. Configure a bounded local clock; retain original envelope, signing-verification and replay keys for the command journal's recovery lifetime. Keys are copied, not borrowed.

Use codec.CheckpointPreparation(ctx, prepared, originalGeneration, encrypt) instead of calling TransferForDelivery separately. Each original proof is transferred once into encrypted journal custody and, optionally, the synchronous delivery-encryption callback. The callback must honor cancellation, must not send or reveal, and must not retain borrowed token bytes. Failure or panic destroys the whole batch. Prepared values and their aliases require serial use; independent batches and the immutable codec support concurrent calls. A same-generation retry returns the original encrypted record without invoking the callback.

Retain this record and the native delivery checkpoint in the workflow's existing preparation output, under its original generation. There is no additional journal or transaction owner. Records are bounded to 512 KiB. Do not log ciphertext or retain it beyond the workflow's secret-retention policy.

codec.RestorePreparation(ctx, binding, originalGeneration, immutablePlan, wire) authenticates the full command, deployment, audience, generation and original issuance plan, then verifies the original tokens locally. It never signs, consumes, renews expiry, invokes delivery, opens SQL or acquires fresh entropy. Missing keys, changed metadata and expired grants fail closed. Restoration returns staging-only custody: issuer.Stage still requires current native Work authority, and TransferForDelivery cannot reopen any restored bearer. Restore encrypted messages through the existing delivery contributor separately.

This adapter contract does not itself implement the password signup service or prove the complete journal-retention/restart journey.

Anonymous registration

For an existing verified recipient, use issuer.PrepareResetRecipient(ctx, originalBinding, userID, payload) under the exact anonymous identity.password.reset-request / password-reset-request profile. It prepares exactly one identity.password.reset-complete grant and freezes ResetRecipientUserID without replacing the originating command's anonymous scope. Signup selection is mutually exclusive. The issuer preparation codec authenticates this target while preserving old ordinary/signup custody. Native staging additionally requires the exact invocation's primary verified email and password-credential fence, with matching original grant scope and versions. Preparation is not recovery eligibility: current factor policy, durable request orchestration, complete reset caveats and atomic completion / session effects remain workflow responsibilities.

For this exact single-grant reset-request profile, recovery can prove issuer non-commit only when the grant identity, replay identity and every grant for the original command are absent under the coordinator's locked recovery scope. Nonmatching origin rows remain conflicting evidence, not absence. This vote does not certify delivery/audit/lifecycle owners or reconstruct success. Ordinary and signup missing-evidence recovery remains unchanged.

Use issuer.PrepareRegistration(ctx, originalBinding, newUserID, payloads) for the exact anonymous identity.password.signup / password-signup v1 profile. Every payload must target that prospective user, the original tenant and the configured audience, with purpose identity.identifier.verify. The original binding must retain its anonymous flow and have no user or record identity. This method is bounded by the same preparation timeout as Prepare; typed validation, cancellation and unavailable errors carry no secrets. Inputs are borrowed during the call, returned plans are defensive copies, and prepared proof aliases share the existing reveal-once lifetime.

RegistrationUserID is frozen into the returned plan. Enlist the native password-signup phase and issuer; the native phase must apply the exact PasswordRegistrationDomain intent before issuer.Stage in the same Work. Preparation never creates a user or authorizes registration. The kernel checks the actual newly registered active user before any grant is staged. A missing registration, foreign target or changed proof metadata aborts the entire transaction. Persistence stores the signed new-user subject but retains the original anonymous command, fingerprint and generation as issuance origin.

Encrypted delivery remains scoped to the original anonymous flow, not a forged user-bound command. Render/encrypt through TransferForDelivery before the transaction and stage native delivery alongside registration and issuance; only the post-commit worker may send. Neither preparation nor an unknown commit permits a replacement token or a second disclosure. Historical recovery reads the frozen target and never signs again. Partial evidence does not reconstruct a committed command receipt; missing/conflicting issuance stays unresolved.

The module pins identity and identity/postgres at the matching committed kernel revision. Deploy compatible readers before enabling new signup plans: earlier strict decoders fail closed on their new frozen field. Existing ordinary plan bytes, schemas and user-bound APIs remain unchanged. The integration fixture proves native registration, issuance, audit/outbox and encrypted delivery with a bounded local sender; it is not yet the complete password/HIBP/email workflow.

Existing user-bound commands

NewIssuer(IssuerConfig) constructs the separate capability.issuance v1 participant. Enlist it after the base participants and before optional delivery. Its crypto configuration uses the existing capability service, not a new token format. Provision replay keys independently of signing keys. The active replay version must be retained; keys are copied and duplicate material rejected. Retained versions are required for historical metadata and recovery.

Prepare signs and verifies fresh random IDs outside every database transaction, then freezes immutable Grants and exact full-envelope fingerprints. It accepts only one-use, subject-bound tokens for the configured audience and original command tenant/user. Callers supply future-operation payload policy, never IDs or replay digests. Replay identity is HMAC-SHA-256 over the ASCII domain golib/capability/identity-replay/v1 plus NUL, big-endian uint32-length-prefixed tenant and purpose, and the authenticated 32-byte full-envelope SHA-256 digest. This intentionally differs from the core public Reference domain. Payloads, audience/origin/authority caveats and signatures are committed by that envelope; the adapter stores an additional canonical payload digest, never raw payloads.

PreparedIssuance.Plan returns a defensive declaration; Issuer.Stage binds it to the exact original command and issuer instance. The sealed persistence phase rederives every replay binding before native absent-to-issued SQL. Schema 002 adds nullable grouped original command/fingerprint/generation, subject, signing key and signed-time metadata without changing historical rows or migration 001. Origin remains distinct from later consuming-command custody. Duplicate inserts conflict rather than update any issued, reserved or terminal record; exact original-command replay is handled by the sole coordinator, without resigning.

TransferForDelivery shares the core one-transfer lifetime and permits only trusted synchronous authenticated encryption admission, not sending or response disclosure before commit. It grants no receipt. Copies cannot disclose twice; failed callbacks cannot retry. There is no synchronous reveal or end-user flow API here yet. Retain prepared custody through the same command retry; never prepare replacement credentials after unknown commit. Recovery reads exact origin evidence and never issues or reveals replacements; absence stays unknown.

Real PostgreSQL tests compose the native issuer, identity repository, audit and outbox to prove original commit/rollback, unchanged replay, cryptographic metadata mismatch denial and multi-grant insertion. A public native delivery composition also transfers each original proof into template rendering and authenticated encryption before the transaction, commits issued state and ciphertext atomically, and denies missing effects and mismatched metadata. The native worker delivers the original signed credential after commit; the test sender verifies its signature. Terminal ciphertext is erased without a second send. These checks use a bounded local sender callback, not a live email provider. They do not yet prove recovery invocation, expiry races, populated-state migration or complete identity workflows. Release gates remain pending; this is not a deployable complete one-time workflow.

Read-only registration validation

Issuer.ValidateRegistrationProof(ctx, pool, proof) combines authenticated original issuance with an indexed primary check for issued, unused and exclusively unexpired state. Repeated validation does not reserve, consume, renew or mutate the proof. Reserved and terminal states deny without returning grant or correlation metadata. ReadRegistrationOrigin remains a historical reader, including after consumption, and must not be used as usable validation.

Both are trusted composition seams: successful grant metadata is sensitive. The email workflow must additionally bind original address/redirect and current account state, returning only bounded public scanner metadata. Validation is not an execution ticket; confirmation repeats current admission and atomically consumes the original proof with the protected address transition.

Integration fixtures

Integration tests create and remove their own PostgreSQL container by default. Select CAPABILITY_POSTGRES_VERSION from the digest-pinned testdata/postgres-images.tsv matrix (default 18). Updating an image requires reviewing its version and immutable digest, then rerunning the affected tests. An explicit IDENTITY_CAPABILITY_TEST_DSN must select identity_test and only loopback primary/fallback hosts; use a disposable cluster, never a shared one.

The test-only testdata/legacy_consumptions.sql is an unchanged copy of postgres/migrations/001_capability_consumptions.sql from capability source caab644d2fec, SHA-256 a66bda3ba57407aeb6bc68724a6623e46ac83a1459a2c3bef6043232ff4ca9b0. It retains the repository license and allows the independently downloaded module to exercise the root store's explicit legacy migration without reading outside its source archive. Refresh it only against that owning migration.

Documentation

Overview

Package identitycapability provides the optional capability-owned PostgreSQL participants for the identity Coordinator. They never own a pool, transaction or command ledger. Issuer prepares secret custody outside transactions; Participant handles consumption metadata only. Install Migrations first.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func CheckManagedEmailResendCooldown

func CheckManagedEmailResendCooldown(ctx context.Context, w kernel.Work, owner kernel.FeatureExecutionContributor, scope ManagedEmailSupersessionScope, interval time.Duration) error

CheckManagedEmailResendCooldown checks the authoritative last committed family issuance using database creation time, never signed proof time or caller time. The exact registered resend Apply invocation must already hold the same family fence before account/factor/domain locks. This method reacquires it defensively and performs no mutation, proof consumption or clock renewal. Interval is an explicit startup policy, between 30 seconds and 10 minutes. Missing history, unavailable history and cooldown deny; callers must propagate every error. Work and rows remain coordinator-owned and bounded by its context/lifetime.

func LockMagicLinkSupersession

LockMagicLinkSupersession acquires the original-flow transaction fence before the invoking native feature locks account, factor or browser rows. Only the exact registered request/consume Apply invocation may act. It performs no provider work and retains no handle; the coordinator owns lock release. Callers must authenticate and reconstruct scope, not accept request digests.

func Migrations

func Migrations() fs.FS

Migrations returns additive forward-only migrations rooted at filenames. Use a separate migration ledger from the legacy consumption store. No legacy row is imported, reset or removed. Downgrade is unsupported because deleting retained one-time state permits replay. Application roles must not own tables or have DDL, TRUNCATE, DELETE or trigger-disable privileges. Issuance and retirement must use owned phases, never client-controlled inserts. The native Issuer owns original inserts; retention/revocation phases remain unfinished.

func RetireEmailVerificationGrants

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

RetireEmailVerificationGrants revokes only unused issued/reserved verification grants for the exact removed identifier in the kernel-locked original Apply invocation. The native owner must propagate errors to abort the same Work. Live unclassified legacy grants deny removal; reserved origin/fingerprint/ generation metadata and consumed/other-target history are preserved. No transaction, lock protocol, credential, worker or recovery journal is created. Nil, foreign, unprepared, reconstructed and returned Work deny without SQL.

Types

type AnonymousUpgradeScope

type AnonymousUpgradeScope struct {
	// SourceVersion is the original guest identity version signed into the proof.
	SourceVersion uint64
	// SourceSessionID identifies the original authenticated guest session.
	SourceSessionID string
	// TargetSessionID identifies the original authenticated permanent-user session.
	TargetSessionID string
	// MergeDigest binds the exact original native merge selection.
	MergeDigest [32]byte
	// Remember selects the signed persistent rather than session-only profile.
	Remember bool
	// SourceExpiresAt bounds the proof by the original guest's absolute lifetime.
	SourceExpiresAt time.Time
}

AnonymousUpgradeScope contains original authenticated native preparation metadata, never HTTP assertions or current authorization. SourceVersion is positive; session IDs are exact 1..128-byte visible ASCII identifiers; MergeDigest is nonzero. SourceExpiresAt is the original guest's positive UTC expiry, at microsecond precision and within years 1..9999. Immutable copies support concurrent reads. Formatting is redacted and serialization rejects.

func (AnonymousUpgradeScope) Format

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

Format hides correlated guest, session and merge metadata.

func (AnonymousUpgradeScope) MarshalJSON

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

MarshalJSON rejects automatic export of original trusted scope custody.

func (AnonymousUpgradeScope) MarshalText

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

MarshalText rejects automatic export of original trusted scope custody.

type IssuancePreparationCodec

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

IssuancePreparationCodec owns no journal, SQL connection or remote provider. Restored custody permits staging only, never another bearer transfer.

func NewIssuancePreparationCodec

func NewIssuancePreparationCodec(i *Issuer, c IssuancePreparationConfig) (*IssuancePreparationCodec, error)

NewIssuancePreparationCodec snapshots bounded local cryptographic policy.

func (*IssuancePreparationCodec) CheckpointPreparation

func (c *IssuancePreparationCodec) CheckpointPreparation(ctx context.Context, p PreparedIssuance, generation uint64, encrypt func(context.Context, uint16, []byte) error) (wire []byte, err error)

CheckpointPreparation irreversibly transfers every original proof to local encrypted journal custody and optionally to synchronous delivery encryption. The callback borrows bytes for its call only, must honor cancellation and must not send or reveal before commit. Failure invalidates the entire batch. Call this instead of TransferForDelivery; do not checkpoint transferred proofs.

func (*IssuancePreparationCodec) Format

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

Format hides codec keys and deployment configuration.

func (*IssuancePreparationCodec) LogValue

func (*IssuancePreparationCodec) LogValue() slog.Value

LogValue redacts codec keys and deployment configuration.

func (*IssuancePreparationCodec) MarshalJSON

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

MarshalJSON rejects implicit codec export.

func (*IssuancePreparationCodec) MarshalText

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

MarshalText rejects implicit codec export.

func (*IssuancePreparationCodec) RestorePreparation

func (c *IssuancePreparationCodec) RestorePreparation(ctx context.Context, b identity.CommandBinding, generation uint64, plan identitypostgres.CapabilityIssuancePlan, wire []byte) (out PreparedIssuance, err error)

RestorePreparation authenticates the original encrypted checkpoint, binding, generation and plan using local retained keys. It performs no SQL, network, signing, entropy acquisition, delivery or consumption. Expired grants fail closed; current transaction authority remains the coordinator's concern.

type IssuancePreparationConfig

type IssuancePreparationConfig struct {
	// Deployment binds encrypted preparation to one trusted deployment identifier.
	Deployment string
	// ActiveEnvelopeKey names the retained envelope key used for new checkpoints.
	ActiveEnvelopeKey string
	// EnvelopeKeys holds 1..32 nonzero 32-byte encryption keys, copied on construction.
	// Keep referenced keys until the original journal no longer requires recovery.
	EnvelopeKeys map[string][]byte
	// VerificationKeys retains 1..32 local policies for authenticating original grants.
	VerificationKeys []PreparationVerificationKey
	// Clock provides current trusted time locally and must support concurrent calls.
	Clock func() time.Time
}

IssuancePreparationConfig selects local encrypted custody and verification. Retain referenced keys for the original journal's entire recovery lifetime.

func (IssuancePreparationConfig) Format

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

Format hides envelope and verification configuration.

func (IssuancePreparationConfig) LogValue

LogValue redacts envelope and verification configuration.

func (IssuancePreparationConfig) MarshalJSON

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

MarshalJSON rejects implicit custody-configuration export.

func (IssuancePreparationConfig) MarshalText

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

MarshalText rejects implicit custody-configuration export.

type Issuer

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

Issuer prepares original signed credentials before the transaction, then inserts immutable metadata solely through coordinator-issued phase custody. It owns no pool, transaction, command result or provider. Immutable instances support concurrent commands; each prepared batch and Work is serial-use.

func NewIssuer

func NewIssuer(c IssuerConfig) (*Issuer, error)

NewIssuer snapshots configuration without I/O. Zero keys, duplicate key material, unknown active version or invalid crypto policy fail closed.

func (*Issuer) Descriptor

Descriptor identifies the separate capability.issuance v1 original producer. It does not grant permission to invoke any coordinator phase.

func (*Issuer) Format

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

Format hides keys, bearer custody and correlation metadata.

func (*Issuer) MarshalJSON

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

MarshalJSON rejects serialization of signing and replay configuration.

func (*Issuer) PersistCapabilityIssuance

func (i *Issuer) PersistCapabilityIssuance(ctx context.Context, w identitypostgres.CapabilityIssuanceWork) error

PersistCapabilityIssuance authenticates every frozen envelope/replay binding before absent-to-issued inserts. Primary time and all origin fields are part of the coordinator transaction. Conflict never updates or resurrects a row. The method retains no handle, calls no signer/provider and closes no transaction.

func (*Issuer) Prepare

func (i *Issuer) Prepare(ctx context.Context, b identity.CommandBinding, inputs []capability.Payload) (out PreparedIssuance, err error)

Prepare creates 1..16 new random capability IDs, signs and authenticates each original envelope, and derives independent keyed replay metadata. Caller IDs, subjectless bearers, foreign subject/tenant, multiple/foreign audiences or non-one-use payloads fail. Exact purpose, resource, caveats and timestamps remain subject to core crypto policy. Whole-second UTC expiry is required. This bounded pre-transaction phase grants no authority and persists nothing. Caller input is borrowed only during the call. Failure destroys all acquired proof custody; collaborators' diagnostics/panics are redacted.

func (*Issuer) PrepareAccountLinkConsumption

func (i *Issuer) PrepareAccountLinkConsumption(ctx context.Context, command identity.Command, proof capability.Proof, replayKeyVersion uint32) (kernel.CapabilityPlan, error)

PrepareAccountLinkConsumption reauthenticates the original opaque proof for one bare canonical explicit self-link command, before native counter enrichment. The root constructor owns the complete signed provider, target, actor, session, policy and mutation intent. The supplied proof must be that exact envelope under this issuer's configured verification policy. The replay-key version comes from trusted original issuance custody, not a request or the current issuance default. Original expiry is never extended.

This bounded read-only phase does not sign, transfer, reserve or consume proof, establish provider/session authority, or attach newly minted issuance. The native AccountLinkUnitOfWork and registered Participant must still match durable issuance and consume atomically with the protected mutation and all current owner checks. OAuth state-before-exchange and post-exchange issuance require their separate native composition; this method supplies neither.

Calls borrow shared proof custody and may overlap. PreparationTimeout and the earlier caller deadline bound verification. Invalid composition returns InvalidInput; invalid, foreign or expired proof returns Forbidden; unavailable verification or panic returns Unavailable. Cancellation remains classified, errors are redacted and every failure returns a zero plan.

func (*Issuer) PrepareAnonymousUpgradeConsumption

func (i *Issuer) PrepareAnonymousUpgradeConsumption(ctx context.Context, binding identity.CommandBinding, proof capability.Proof, originalEnvelope [32]byte, replayKeyVersion uint32, expected AnonymousUpgradeScope) (out kernel.CapabilityPlan, err error)

PrepareAnonymousUpgradeConsumption reauthenticates an original signed proof for identity.anonymous.upgrade / identity.anonymous.upgrade.native-v1 v1. UserID and the user ActorID identify the permanent target; the distinct RecordID identifies the guest. Supply expected scope, originalEnvelope and replayKeyVersion from authenticated original native preparation, never HTTP assertions or current-key defaults. All five signed anonymous caveats, issuer, tenant, target, guest, purpose, audience and one-use bounds must match. Signed expiry cannot exceed the original guest expiry.

This bounded read-only seam borrows concurrent proof custody and returns only the existing participant plan, preserving original replay identity, envelope fingerprint and exact signed expiry. It performs no signing, SQL, reservation, consumption, transfer or renewal. It is not target-credential proof: the native password ActionPrimarySource must separately authenticate the current target for this action. Native identity/session owners still fence current guest, target, sessions, merge, policy and expiry and consume atomically with all effects through the sole coordinator and existing capability participant.

Invalid composition returns InvalidInput; foreign or expired proof returns Forbidden; verification failure or panic returns Unavailable. Earlier caller cancellation wins. Every failure returns a zero plan and redacted typed error.

func (*Issuer) PrepareIdentifierConsumption

func (i *Issuer) PrepareIdentifierConsumption(ctx context.Context, command identity.Command, proof capability.Proof, replayKeyVersion uint32) (out identitypostgres.CapabilityPlan, err error)

PrepareIdentifierConsumption authenticates the original proof with this issuer's configured verification policy and derives metadata for the exact immutable identifier command. replayKeyVersion is the trusted original issuance version, not the current issuance default or a bearer-selected value. Retain that key until its credentials and durable custody expire. The participant subsequently matches all metadata against durable issuance; this read-only preparation is neither reservation nor mutation authority. It does not consume or transfer proof custody, resign, extend expiry or open a transaction. Calls are concurrent-safe and bounded by PreparationTimeout and the caller's earlier deadline. Invalid composition returns InvalidInput; invalid/foreign/expired proof returns Forbidden; collaborator failure or panic returns Unavailable. Cancellation remains classified and redacted.

func (*Issuer) PrepareMFAConsumption

func (i *Issuer) PrepareMFAConsumption(ctx context.Context, b identity.CommandBinding, recipient identity.UserID, continuation identity.CommandID, scope [32]byte, issuer string, proof capability.Proof, originalEnvelope [32]byte, replayKeyVersion uint32) (out kernel.CapabilityPlan, err error)

PrepareMFAConsumption reauthenticates the original single-use MFA child for one closed anonymous factor-completion operation. recipient, continuation, scope, issuer, originalEnvelope and replayKeyVersion are trusted original continuation/issuance custody, not request-selected authority. The signed tenant, subject, canonical child ID, resource, closed profile, scope, issuer, audience and original envelope must match. Purpose remains identity.mfa.complete rather than being rewritten to the selected factor operation. Expiry and replay identity are unchanged, including across replay-key rotation.

This bounded read-only seam neither authenticates a factor nor issues a session. It performs no SQL, signing, reservation, consumption, custody transfer, renewal or goroutine creation. The native owner must authenticate durable origin, original browser/primary/remember scope, allowed factor, current policy/account/factor authority and shared attempts. The sole coordinator and capability participant consume with replay/continuation and session effects atomically; this scalar plan is never permission to do so.

Calls may overlap and borrow the proof's shared lifetime. PreparationTimeout and the earlier caller deadline bound verification. Invalid composition returns InvalidInput; invalid/foreign/expired proof returns Forbidden; unavailable verification or collaborator panic returns Unavailable. Context errors remain typed and redacted. Every failure returns a zero plan.

func (*Issuer) PrepareMFAContinuation

func (i *Issuer) PrepareMFAContinuation(ctx context.Context, b identity.CommandBinding, input capability.Payload) (PreparedIssuance, error)

PrepareMFAContinuation signs one original challenge under an anonymous magic-link consume, password-signin, username-signin or phone-password-signin command. The native owner allocates the canonical ID and freezes the full scope before this bounded call; this method preserves that ID, scope and expiry. It performs no SQL, consumption or authentication. Kernel staging still requires the same-Work native primary and exact frozen challenge scope. Retain original encrypted custody across retries; never sign replacements to resolve unknown commit. Restoration cannot renew disclosure.

func (*Issuer) PrepareMagicLinkConsumption

func (i *Issuer) PrepareMagicLinkConsumption(ctx context.Context, binding identity.CommandBinding, recipient identity.UserID, identifier identity.IdentifierID, proof capability.Proof, originalEnvelope [32]byte, replayKeyVersion uint32) (out kernel.CapabilityPlan, err error)

PrepareMagicLinkConsumption reauthenticates the original one-use proof for the exact anonymous identity.magic-link.consume/magic-link-consume v1 binding. recipient and identifier are trusted original issuance selections, not a customer-selected user override. originalEnvelope and replayKeyVersion must come from authenticated durable origin custody; neither an alternate valid signature nor the current replay-key default may replace them. Tenant, signed recipient, identity.magiclink identifier resource, audience and original envelope must match. The anonymous command scope remains unchanged.

This read-only adapter seam is not login permission or a public inspection response. The native owner must additionally validate all original caveats, callback/pre-auth intent, current recipient/factor/risk policy and session effects. The existing capability participant matches durable issuance and consumes atomically in the sole coordinator transaction. No SQL, signing, reservation, consumption, renewal, transfer or goroutine occurs here.

Calls may overlap and borrow the upstream shared proof lifetime. Preparation is bounded by PreparationTimeout and the earlier caller deadline. Invalid composition returns InvalidInput; invalid proof/scope returns Forbidden; unavailable verification or collaborator panic returns Unavailable. Context errors stay classified. Every failure returns a zero plan with no secrets.

func (*Issuer) PrepareMagicLinkProspectiveRecipient

func (i *Issuer) PrepareMagicLinkProspectiveRecipient(ctx context.Context, b identity.CommandBinding, user identity.UserID, input capability.Payload) (PreparedIssuance, error)

PrepareMagicLinkProspectiveRecipient signs exactly one prospective signup grant under the original anonymous request, without creating an account or proving mailbox possession. Its explicit profile binds future creation and policy; kernel staging still requires the same invocation's unused-recipient fence. Preserve returned original custody across retries and recovery. This bounded call performs no SQL or delivery and renews no stored validity.

func (*Issuer) PrepareMagicLinkRecipient

func (i *Issuer) PrepareMagicLinkRecipient(ctx context.Context, b identity.CommandBinding, user identity.UserID, input capability.Payload) (PreparedIssuance, error)

PrepareMagicLinkRecipient prepares exactly one magic-link consume grant for an existing recipient under the unchanged anonymous magic-link request. This bounded pre-transaction call signs original custody but grants no current eligibility, authentication or factor permission. The kernel requires its same-invocation primary verified-email fence and exact signed recipient scope before staging. The native workflow owns original flow, callback and factor/ risk policy. Retain original custody across retries and unknown outcomes; encrypted preparation restoration never renews bearer disclosure or expiry.

func (*Issuer) PrepareManagedChangeConsumption

func (i *Issuer) PrepareManagedChangeConsumption(ctx context.Context, binding identity.CommandBinding, proof capability.Proof, envelope [32]byte, replayKeyVersion uint32) (kernel.CapabilityPlan, error)

PrepareManagedChangeConsumption authenticates only change-confirm.managed-v1 and its original management-v1 change grant. It conserves signed identifier purpose, envelope, expiry and retained replay identity. Verification-only schemas/proofs deny. Original intent/current admission and atomic old notice, primary/session effects remain the native email/kernel transaction's duty. Ownership, bounded verification and error semantics match the verification seam; no SQL, signing, consumption, session or custody transfer occurs.

func (*Issuer) PrepareManagedVerificationConsumption

func (i *Issuer) PrepareManagedVerificationConsumption(ctx context.Context, binding identity.CommandBinding, proof capability.Proof, envelope [32]byte, replayKeyVersion uint32) (kernel.CapabilityPlan, error)

PrepareManagedVerificationConsumption reauthenticates an original management-v1 link for identity.email.verification-confirm.managed-v1 version1. Signed tenant/user/resource, exact profile/caveats, original envelope and retained replay-key version must match. Signup proofs, change-confirm and alternate schemas deny. No original session is inferred or required by this seam.

The native email owner must authenticate original encrypted mailbox intent and current caller/account/factor/risk authority. Returned metadata grants no mutation authority; the existing capability participant matches durable issuance and consumes/finalizes in the sole protected coordinator transaction. Original signed purpose, expiry and replay identity are conserved unchanged. This method performs no SQL, signing, consumption, transfer or session work, owns no goroutines and is concurrent-safe. PreparationTimeout and earlier cancellation bound verification. Errors are typed/redacted; failures return zero plans. Proof custody is borrowed and must remain immutable during calls.

func (*Issuer) PrepareOrganizationInvitationConsumption

func (i *Issuer) PrepareOrganizationInvitationConsumption(ctx context.Context, binding identity.CommandBinding, proof capability.Proof, originalEnvelope [32]byte, replayKeyVersion uint32, expected OrganizationInvitationScope) (out kernel.CapabilityPlan, err error)

PrepareOrganizationInvitationConsumption reauthenticates one original opaque invitation proof for the closed organization invitation-accept command. The authenticated recipient is both UserID and ActorID; RecordID is the invitation, not the organization or capability ID. Expected scope, original envelope and replay-key version come from authenticated retained issuance, never caller claims. Signed tenant, recipient, invitation, issuer, audience, exact purpose, role, invitation version and verified-recipient identifier version must match.

This bounded read-only preparation performs no SQL, signing, reservation, consumption, delivery or renewal. It grants neither membership nor current recipient authority. The native organization owner must fence the original verified recipient, current session, organization, policy and limits in the same coordinator Work as atomic one-use consumption, membership and audit. No proof custody is transferred; concurrent calls borrow its shared lifetime.

Invalid composition returns InvalidInput; foreign or expired proof returns Forbidden; unavailable verification or collaborator panic returns Unavailable. Earlier caller cancellation wins. Every failure returns a zero plan, and retained key rotation never replaces the original replay identity or expiry.

func (*Issuer) PreparePasskeyMFAContinuation

func (i *Issuer) PreparePasskeyMFAContinuation(ctx context.Context, b identity.CommandBinding, input capability.Payload) (PreparedIssuance, error)

PreparePasskeyMFAContinuation signs the original child of the explicit native UV-passkey primary profile. The self-user command retains its own ID as both record and signed correlation; this is not a general subject override. The native owner must prove actual assertion/browser/factor authority before the kernel stages the child in the same transaction. Preparation performs no SQL, authentication or session issuance. Restore original encrypted custody on retries rather than signing another child or extending its lifetime.

func (*Issuer) PreparePasswordResetConsumption

func (i *Issuer) PreparePasswordResetConsumption(ctx context.Context, command identity.Command, replayKeyVersion uint32) (out kernel.CapabilityPlan, err error)

PreparePasswordResetConsumption authenticates the original opaque proof retained inside the exact password-reset input or generated command. The input form allows authoritative preparation admission before hashing; both forms produce the same original plan. No alternate proof or caller-built envelope is accepted. The signed tenant, subject and password resource must match the immutable binding. replayKeyVersion is trusted original issuance metadata from ReadIssuanceOrigin, not the current version or a client-selected default. Original envelope, expiry and replay identity are preserved under the issuer's configured signature/time/revocation policy.

Preparation is bounded by PreparationTimeout and the earlier caller deadline. It performs no SQL, signing, transfer, reservation, consumption or renewal; copies of the proof retain their upstream shared lifetime. Calls may overlap. Invalid composition returns InvalidInput, invalid scope/proof returns Forbidden, unavailable verification or collaborator panic returns Unavailable, and cancellation remains typed. Every failure returns a zero plan with no secrets.

A plan is not reset permission. The password owner must validate original durable issuance intent, closed recovery profile, current identifier/factors, risk/HIBP and verifier policy. The sole coordinator and capability participant must match durable provenance and atomically consume with password/session effects. Preparation cannot make a terminal proof usable or establish commit.

func (*Issuer) PreparePhonePasswordResetConsumption

func (i *Issuer) PreparePhonePasswordResetConsumption(ctx context.Context, command identity.Command, replayKeyVersion uint32) (out kernel.CapabilityPlan, err error)

PreparePhonePasswordResetConsumption authenticates only the original signed proof retained by a sealed joint phone-reset input or generated command. The exact identity/phone native-v1 descriptor, signed password resource, tenant, user, configured audience and one-use bound must match. The original password or hash, SMS code, independent TOTP and browser cookie remain in their joint command custody; no generic command conversion or alternate proof is accepted.

replayKeyVersion is trusted original issuance metadata from ReadIssuanceOrigin, not a request-selected version or the active issuance default. Retain that key through recovery. Configured signature, time and revocation policy apply. Repeated preparation preserves the original envelope, absolute expiry and replay identity; it performs no SQL, signing, transfer, reservation or use. Calls may overlap and are bounded by PreparationTimeout and earlier deadlines. Invalid composition returns InvalidInput, invalid scope/proof Forbidden, unavailable verification or collaborator panic Unavailable, and cancellation remains typed. Every failure returns a zero plan and redacted error.

This plan is not recovery permission. The native owner must authenticate the complete original durable phone reset profile and current phone/password, browser, independent-factor and completion-risk authority. The sole identity coordinator must consume capability, OTP and risk with the canonical password replacement and required session effects. Preparation cannot establish commit, renew expired custody or make terminal evidence usable.

func (*Issuer) PreparePrivacyExportConsumption

func (i *Issuer) PreparePrivacyExportConsumption(ctx context.Context, command identity.Command, proof capability.Proof, replayKeyVersion uint32) (out identitypostgres.CapabilityPlan, err error)

PreparePrivacyExportConsumption reauthenticates the exact original opaque proof for an immutable privacy request and derives the capability-owned consumption plan. replayKeyVersion is trusted retained issuance metadata, never a current default or a bearer-selected version. Configured signature, audience, time and revocation policy apply; another valid signed envelope cannot replace the command's original proof. Calls are concurrent-safe and bounded by PreparationTimeout and the caller's earlier deadline.

Preparation does not transfer, resign, renew, reserve or consume the proof, begin a transaction, or authorize a session/export. The sole coordinator must still enforce primary expiry, session/policy eligibility, exact durable issuance and atomic use with all snapshot/effect owners. Invalid composition returns InvalidInput; invalid/foreign proof returns Forbidden; verification availability failures and panics return Unavailable. Cancellation stays classified and all errors are redacted. No raw proof material is returned.

func (*Issuer) PrepareRegistration

func (i *Issuer) PrepareRegistration(ctx context.Context, b identity.CommandBinding, user identity.UserID, inputs []capability.Payload) (PreparedIssuance, error)

PrepareRegistration prepares new-user verification under the unchanged original anonymous signup command. Preparation grants no creation authority; staging still requires the kernel's same-Work registration of this exact user.

func (*Issuer) PrepareRegistrationVerificationConsumption

func (i *Issuer) PrepareRegistrationVerificationConsumption(ctx context.Context, binding identity.CommandBinding, proof capability.Proof, envelope [32]byte, replayKeyVersion uint32) (kernel.CapabilityPlan, error)

PrepareRegistrationVerificationConsumption reauthenticates the exact original anonymous signup proof for a current native email confirmation binding. The action is identity.email.verification-confirm, schema is identity.email.verification-confirm.native-v1 version 1, and RecordID is the signed identifier. Tenant and UserID must equal the signed target. The envelope must come from the authenticated original intent, not an alternate signature, and replayKeyVersion from original durable issuance, never an active-key default. No session caveats or rewritten proof are introduced.

Configured signature, audience, time and revocation policy apply. The original identity.identifier.verify purpose, expiry, envelope and replay identity are preserved. The owning email workflow must first authorize the full original mailbox/redirect/version commitment. This metadata alone is not that proof, current identity/session authority, a usable grant or a command receipt. The sole Coordinator must still match durable issuance, fence current account and identifier state and consume atomically with the protected mutation.

No SQL, reservation, signing, custody transfer, consumption or goroutine runs. Calls are concurrent-safe and bounded by PreparationTimeout and earlier deadlines. Invalid composition is InvalidInput; invalid proof/profile is Forbidden; verification failure/panic is Unavailable. Cancellation remains typed and redacted. Every failure returns a zero plan; no raw bearer escapes.

func (*Issuer) PrepareResetRecipient

func (i *Issuer) PrepareResetRecipient(ctx context.Context, b identity.CommandBinding, user identity.UserID, input capability.Payload) (PreparedIssuance, error)

PrepareResetRecipient prepares exactly one reset-complete grant for an existing user under the unchanged anonymous password-reset-request command. The bounded, pre-transaction call grants no recovery eligibility, performs no SQL and does not prove current account, credential or factor authority. The kernel requires this exact recipient's primary fence before staging; the workflow owns the complete reset profile and current recovery-factor policy. Retain the returned original custody across retries and unknown outcomes.

func (*Issuer) PrepareVerificationMFAContinuation

func (i *Issuer) PrepareVerificationMFAContinuation(ctx context.Context, b identity.CommandBinding, input capability.Payload) (PreparedIssuance, error)

PrepareVerificationMFAContinuation signs one original challenge for the explicit recipient of a separately committed registration verification. Binding retains that confirmation's command ID in RecordID, not an anonymous primary or a same-transaction consumption. Structural checks do not prove the parent or browser; the exact native owner must fence both before kernel staging. This bounded call performs no SQL, authentication or session issuance. Retain encrypted preparation across retries; restore original bytes without extending expiry or signing replacements after an unknown commit.

func (*Issuer) ReadIssuanceOrigin

func (i *Issuer) ReadIssuanceOrigin(ctx context.Context, pool *database.Pool, proof capability.Proof, purpose capability.Purpose) (capability.Grant, identity.CommandID, uint32, error)

ReadIssuanceOrigin authenticates a purpose-explicit original one-use proof and matches its complete persisted issuance provenance. Purpose is trusted composition, never a bearer-selected fallback. Historical terminal state may retain provenance but grants no usable authority; signature, audience, time and configured revocation policy still apply. Missing or mismatched origins deny. Original replay versions are returned without current-key substitution.

This is a trusted adapter seam, not public inspection or workflow permission. The owning workflow must validate its closed purpose-specific payload, original encrypted intent, current account/factor/risk state and exact scope before any public response or protected consumption. No transaction, reservation, consumption, renewal, bearer transfer, callback or goroutine is created. Pool/proof are borrowed; the issuer timeout and earlier deadline bound crypto and one indexed primary read. Instances are concurrent-safe. Errors redact; every failed/cancelled call returns zero projections. Metadata is sensitive.

func (*Issuer) ReadMFAMagicLinkParent

func (i *Issuer) ReadMFAMagicLinkParent(ctx context.Context, pool *database.Pool, child capability.Proof, parentID string, parentEnvelope [32]byte, parentExpiry time.Time) (out MFAMagicLinkParent, err error)

ReadMFAMagicLinkParent verifies the original MFA child and resolves its exact already-consumed magic-link parent without accepting a reusable primary bearer. Parent ID/envelope/expiry must come from the authenticated stored continuation, not client fields. The parent's finalized consumer tuple must match the child's original issuance command/fingerprint/generation. Original request provenance, tenant, subject, signature times and exclusive lifetimes are preserved; superseded/missing/foreign records deny.

The result owns no connection or transaction and grants no execution ticket. Signature/revocation verification and indexed primary reads share one issuer timeout and the earlier caller deadline. Pool/child custody are borrowed; immutable issuers permit concurrent calls. No callback, goroutine, signing, consumption, intent store or freshness renewal is created. Invalid composition returns InvalidInput; missing/foreign provenance returns Forbidden; unavailable storage/verification returns Unavailable. Cancellation remains typed. Every error returns zero custody and reveals no SQL, credential or correlated data.

func (*Issuer) ReadMFAVerificationParent

func (i *Issuer) ReadMFAVerificationParent(ctx context.Context, pool *database.Pool, child capability.Proof, parentID string, parentEnvelope [32]byte, parentExpiry time.Time) (MFAVerificationParent, error)

ReadMFAVerificationParent authenticates the child and its already-consumed registration grant without recovering a reusable primary bearer. Parent identity/digest/expiry must come from the authenticated durable continuation. The signed child's correlation identifies the separate confirmation command; its exact committed journal fingerprint/generation must match consumption. The native owner separately checks the challenge journal's declared parent. Earlier caller deadlines and the issuer timeout bound all primary reads. Borrowed pool/child remain caller-owned; errors return zero redacted custody. No callback, goroutine, signing, consumption or freshness renewal occurs.

func (*Issuer) ReadMagicLinkOrigin

func (i *Issuer) ReadMagicLinkOrigin(ctx context.Context, pool *database.Pool, proof capability.Proof) (capability.Grant, identity.CommandID, uint32, bool, error)

ReadMagicLinkOrigin authenticates original magic-link provenance and its exact signed supersession scope in one indexed primary read. The additional flag reports retained invalidation, not command outcome or permission to consume. Reserved/terminal provenance remains readable for retries and recovery; legacy unselected records report false. Migration 003 is required. Missing, tampered or unavailable evidence returns zero projections including the flag. Proof and pool are borrowed; bounds and cancellation match ReadIssuanceOrigin. The workflow must still reconstruct browser scope, check current authority and repeat admission/one-use in the protected transaction. No freshness renews.

func (*Issuer) ReadRegistrationOrigin

func (i *Issuer) ReadRegistrationOrigin(ctx context.Context, pool *database.Pool, proof capability.Proof) (capability.Grant, identity.CommandID, uint32, error)

ReadRegistrationOrigin authenticates a registration-profile proof with this issuer's configured signature, audience, time and revocation policy, then matches its exact persisted original issuance. It returns the authenticated grant, originating command ID and original replay-key version, never a raw bearer, current-key substitution or newly signed credential. Unpublished, legacy originless, foreign-envelope and mismatched evidence deny identically.

This is a trusted native composition seam, not public scanner validation, session authority, a signup receipt or permission to consume. The origin owner must authenticate its original signup input and email intent. Confirm must still recheck current identity and capability state in the sole protected transaction. Later consuming/terminal state does not erase original provenance and is deliberately not interpreted here as usable authority or rollback.

The primary pool and proof are borrowed; no transaction, custody transfer, reservation, mutation, callback or goroutine is created. Immutable issuers permit concurrent calls. PreparationTimeout and the earlier caller deadline bound crypto and the indexed primary read. Invalid composition returns InvalidInput, unavailable verification/storage returns Unavailable, and cancellation retains its typed classification. Errors never expose SQL, credentials or correlation metadata. Successful projections remain sensitive.

func (*Issuer) RecoverParticipant

RecoverParticipant reads original issuance evidence under the coordinator's frozen prior generation. Missing, partial or conflicting ordinary/signup rows remain unknown. Selected single-grant recipient and native anonymous- upgrade preparation profiles can prove non-commit only when neither original identity nor replay identity nor any grant of that originating command exists under the coordinator recovery fence. No expiry, timeout or consuming state is rewritten as rollback.

func (*Issuer) RequireVerificationMFAParent

func (i *Issuer) RequireVerificationMFAParent(ctx context.Context, w kernel.Work, owner kernel.EmailVerificationMFAChallengeContributor, grant capability.Grant, signup identity.CommandID) error

RequireVerificationMFAParent fences the genuine registration grant consumed by the separately committed confirmation. It is read-only and available only to the exact native email challenge participant during preparation, Apply or final admission. Grant must be actual verified capability custody; original signup and confirmation come from authenticated native history, never a client assertion. The row and confirmation journal must retain their exact original fingerprint/generation. This neither consumes again nor grants factor/session authority. Locks share the caller's sole Work; every error must propagate.

func (*Issuer) RequireVerificationMFATOTPParent

func (i *Issuer) RequireVerificationMFATOTPParent(ctx context.Context, w kernel.Work, owner kernel.MFACompletionContributor, command identity.Command, parent MFAVerificationParent) error

RequireVerificationMFATOTPParent repeats original parent/child custody under the exact native TOTP owner's preparation, Apply or final-check Work. Parent must come from ReadMFAVerificationParent and be matched to the owner's actual continuation before this call. This read-only fence neither authenticates a factor nor consumes the child. It locks original confirmation and challenge history and both grants until the caller's sole transaction closes; original expiry cannot be renewed. Foreign/returned handles and changed custody deny. Every error must abort the protected operation. All IO retains the earlier caller deadline and issuer timeout; rows are closed on every path.

func (*Issuer) RequireVerificationMFATOTPParentAttempt

func (i *Issuer) RequireVerificationMFATOTPParentAttempt(ctx context.Context, w kernel.MFATOTPAttemptWork, owner kernel.MFATOTPAttemptContributor, parent MFAVerificationParent) error

RequireVerificationMFATOTPParentAttempt applies the same immutable parent fence in the sealed counted-attempt callback, before code comparison or debit. The live callback's frozen child and subject must match opaque parent custody. This cannot charge an attempt, consume a factor or create a session. Copies share the caller's bounded transaction lifetime and every error must propagate.

func (*Issuer) Stage

Stage binds immutable original grants to this exact owner in the admitted original command. It neither signs, persists nor exposes bearer bytes.

func (*Issuer) ValidateCapabilityIssuance

func (i *Issuer) ValidateCapabilityIssuance(b identity.CommandBinding, p identitypostgres.CapabilityIssuancePlan) error

ValidateCapabilityIssuance checks retained-key and metadata shape without I/O. Exact cryptographic provenance is rederived from Grants in the sealed phase.

func (*Issuer) ValidateIssuedProof

func (i *Issuer) ValidateIssuedProof(ctx context.Context, pool *database.Pool, proof capability.Proof, purpose capability.Purpose) (capability.Grant, identity.CommandID, uint32, error)

ValidateIssuedProof additionally requires issued, unused state and exclusive primary expiry in the same indexed read. Repeated inspection is read-only: no reservation, consumption or execution ticket results. Reserved, terminal, expired or revoked proofs deny; the owning workflow must still recheck current eligibility and repeat admission during atomic completion. Ownership, bounds, cancellation, redaction and zero-on-error semantics match ReadIssuanceOrigin.

func (*Issuer) ValidateRegistrationProof

func (i *Issuer) ValidateRegistrationProof(ctx context.Context, pool *database.Pool, proof capability.Proof) (capability.Grant, identity.CommandID, uint32, error)

ValidateRegistrationProof authenticates original registration provenance and requires an issued, unused proof whose exclusive expiry is after primary time in that same indexed read. No reservation, consumption, expiry renewal or mutation occurs. Reserved, finalized, released, expired and revoked proofs deny identically to absence. ReadRegistrationOrigin deliberately remains the separate historical reader, including after consumption.

This trusted email composition seam returns sensitive original grant metadata, not a public scanner response, mailbox ownership or permission to execute. The email owner must bind original address/redirect and current account state before returning bounded public metadata. Confirmation must repeat admission and consume atomically; validation cannot hold authority across a later call. The borrowed pool/proof, finite budget, concurrency, redaction and zero-on-error semantics are the same as ReadRegistrationOrigin. No handles or goroutines are retained and cancelled calls return no sensitive projection.

type IssuerConfig

type IssuerConfig struct {
	// Crypto pins the trusted issuer, signing and verification policy and local clock.
	Crypto capability.ServiceConfig
	// Audience is the single exact audience admitted for every prepared grant.
	Audience string
	// CurrentReplayKeyVersion selects a nonzero retained key for new replay bindings.
	CurrentReplayKeyVersion uint32
	// RetainedReplayKeys holds 1..32 distinct nonzero keys, copied at construction.
	// Retain referenced versions for the full lifetime of original command recovery.
	RetainedReplayKeys map[uint32][32]byte
	// PreparationTimeout bounds each signing and verification phase to 1..30 seconds.
	PreparationTimeout time.Duration
	// RetainEmailVerificationTargets selects migration 005 and retains the
	// authenticated signed Resource for identifier verification. Enable before
	// issuing signup/management links when native email removal is selected.
	// False preserves the existing installation and issuance SQL contract.
	RetainEmailVerificationTargets bool
}

IssuerConfig pins signing/verification policy and a separate versioned replay key set. Replay keys must never be signing keys; deployment key custody owns that separation. Maps contain 1..32 nonzero unique keys and are copied. Keep every referenced version until bearer validation and retained authority no longer require it. Audience is one exact target, PreparationTimeout is 1..30s. Crypto collaborators must support concurrent bounded calls; Clock is local.

type MFAMagicLinkParent

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

MFAMagicLinkParent retains opaque canonical-payload custody from an exact consumed parent linked to an authenticated original child. It is immutable, copyable and safe for concurrent local comparisons; zero values deny. Inspection is not permission to complete MFA or issue a session. No raw primary credential is recovered, recreated, signed or retained.

func (MFAMagicLinkParent) Bindings

Bindings projects immutable historical routing/times, not decoded payload fields or current authority. A copied projection cannot manufacture custody.

func (MFAMagicLinkParent) Format

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

Format prevents implicit disclosure of correlated parent custody.

func (MFAMagicLinkParent) LogValue

func (MFAMagicLinkParent) LogValue() slog.Value

LogValue redacts parent provenance and canonical-payload custody.

func (MFAMagicLinkParent) MarshalJSON

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

MarshalJSON refuses implicit export of parent digest custody.

func (MFAMagicLinkParent) MarshalText

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

MarshalText refuses implicit text/map-key export of parent custody.

func (MFAMagicLinkParent) MatchPayload

func (p MFAMagicLinkParent) MatchPayload(v capability.Payload) error

MatchPayload requires byte-equivalent canonical reconstruction of the entire retained parent payload under the original bounded capability format. Extra, missing or changed caveats, subject, tenant, scope, request origin or times deny. This local comparison performs no IO, consumption, signing or renewal. Success authenticates historical metadata only; protected execution must repeat its current account/factor/browser/child authority checks.

type MFAMagicLinkParentBindings

type MFAMagicLinkParentBindings struct {
	// TenantID is the tenant authenticated by the original consumed parent.
	TenantID identity.TenantID
	// UserID identifies the original parent recipient, not a caller override.
	UserID identity.UserID
	// CapabilityID is the original consumed magic-link credential identifier.
	CapabilityID string
	// RequestCommandID identifies the original request that issued the parent.
	RequestCommandID identity.CommandID
	// PrimaryCommandID identifies the original command that consumed the parent.
	PrimaryCommandID identity.CommandID
	// ReplayKeyVersion identifies the retained key authenticating original replay.
	ReplayKeyVersion uint32
	// IssuedAt retains the parent's original signed issuance time.
	IssuedAt time.Time
	// NotBefore retains the parent's original signed earliest-use time.
	NotBefore time.Time
	// ExpiresAt retains original expiry; reconstruction cannot renew it.
	ExpiresAt time.Time
}

MFAMagicLinkParentBindings is historical original request/primary provenance. It contains no bearer, factor proof or current authorization. The owning magic-link adapter must reconstruct its entire original payload and call MatchPayload before using identifier or session metadata. The MFA workflow must still fence current authority and original browser custody atomically.

type MFAVerificationParent

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

MFAVerificationParent owns opaque original-payload custody. It cannot be used as a magic-link parent or manufactured from projected bindings. Zero denies; immutable copies support concurrent local matching and retain no bearer.

func (MFAVerificationParent) Bindings

Bindings projects exact committed-parent routing and original deadlines. Projections cannot reconstruct payload custody or authorize factor completion.

func (MFAVerificationParent) Format

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

Format redacts correlated parent custody.

func (MFAVerificationParent) LogValue

func (MFAVerificationParent) LogValue() slog.Value

LogValue redacts structured diagnostics.

func (MFAVerificationParent) MarshalJSON

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

MarshalJSON rejects implicit custody export.

func (MFAVerificationParent) MarshalText

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

MarshalText rejects implicit textual custody export.

func (MFAVerificationParent) MatchPayload

func (p MFAVerificationParent) MatchPayload(v capability.Payload) error

MatchPayload requires exact canonical reconstruction of the original issued registration-verification grant, including all native signup/callback caveats. It performs no signing, disclosure, IO, consumption or validity renewal. The native completion owner must repeat live account, browser and factor fences.

type MFAVerificationParentBindings

type MFAVerificationParentBindings struct {
	// TenantID is the tenant shared by the original parent and MFA child.
	TenantID identity.TenantID
	// UserID is their authenticated original recipient, not current authority.
	UserID identity.UserID
	// CapabilityID identifies the already-consumed registration grant.
	CapabilityID string
	// RequestCommandID identifies the original signup issuance.
	RequestCommandID identity.CommandID
	// VerificationCommandID identifies the separately committed parent use.
	VerificationCommandID identity.CommandID
	// ChallengeCommandID identifies the subsequent pending MFA issuance.
	ChallengeCommandID identity.CommandID
	// ReplayKeyVersion retains the parent's original replay-key identity.
	ReplayKeyVersion uint32
	// IssuedAt is the original parent grant's signed issuance time.
	IssuedAt time.Time
	// NotBefore is its original signed lower validity bound.
	NotBefore time.Time
	// ExpiresAt is its original signed deadline, never renewed by this read.
	ExpiresAt time.Time
}

MFAVerificationParentBindings is historical provenance for three distinct commands: original signup issuance, committed verification, and subsequent MFA challenge. It conveys no current authentication, factor or session authority.

type MagicLinkSupersessionScope

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

MagicLinkSupersessionScope identifies one exact original browser flow and recipient selection. It is metadata, not proof verification or authorization. Copies are immutable and safe for concurrent use; the zero value is invalid.

func MagicLinkScopeFromPayload

func MagicLinkScopeFromPayload(p capability.Payload) (MagicLinkSupersessionScope, error)

MagicLinkScopeFromPayload projects bounded, exact original scope from a magic-link payload. The caller must separately authenticate the payload and reconstruct original intent. Token/command IDs, dates and authority versions are deliberately excluded: resending cannot escape its original flow by issuing a different token or observing newer authority. No strings normalize.

func (MagicLinkSupersessionScope) Digest

func (s MagicLinkSupersessionScope) Digest() [32]byte

Digest returns the opaque scope identity for signed metadata and native transactional fencing. It cannot grant authority or select another tenant.

func (MagicLinkSupersessionScope) Format

Format redacts scope metadata, including browser and recipient bindings.

func (MagicLinkSupersessionScope) MarshalJSON

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

MarshalJSON rejects serialization of opaque scope custody.

type ManagedEmailSupersessionScope

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

ManagedEmailSupersessionScope identifies one exact issuer/audience, tenant, recipient, identifier and confirmation action. It is metadata, not proof or authority. Copies are immutable and safe for concurrent use; zero is invalid. A family deliberately excludes request IDs, times, key versions, callbacks and changing authority versions: a newly authorized resend must invalidate every older selected grant for that mailbox/action, not escape through new intent.

func ManagedEmailScopeFromPayload

func ManagedEmailScopeFromPayload(p capability.Payload) (ManagedEmailSupersessionScope, error)

ManagedEmailScopeFromPayload projects a bounded stable mailbox family. The native owner must separately authenticate/reconstruct complete original mailbox, callback, policy, fresh primary proof and pending-identifier state. This function does not sign, normalize, read a clock/store, reserve, consume or authorize anything. Existing four-caveat management payloads can be used to compute the family; an explicitly selected fifth email.supersession caveat must exactly equal it. Registration and magic-link profiles cannot borrow it. Inputs remain borrowed/immutable. Invalid input returns zero/redacted error; no resources or goroutines are created.

func (ManagedEmailSupersessionScope) Digest

func (s ManagedEmailSupersessionScope) Digest() [32]byte

Digest returns the opaque family identity for signed metadata and native transaction fencing. It grants no authority and selects no different tenant.

func (ManagedEmailSupersessionScope) Format

Format redacts correlated account and mailbox metadata.

func (ManagedEmailSupersessionScope) MarshalJSON

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

MarshalJSON denies implicit scope export.

type OrganizationInvitationScope

type OrganizationInvitationScope struct {
	// OrganizationID identifies the organization bound by original issuance.
	OrganizationID string
	// InvitationVersion is the positive version signed into the invitation.
	InvitationVersion uint64
	// Role is the exact signed role; current role admission remains external.
	Role string
	// RecipientIdentifierID identifies the originally verified recipient.
	RecipientIdentifierID identity.IdentifierID
	// RecipientIdentifierVersion binds that recipient's original version.
	RecipientIdentifierVersion uint64
}

OrganizationInvitationScope is original trusted invitation metadata, not authorization or HTTP input. Resolve it from authenticated durable invitation custody. Versions are positive; string fields are exact 1..128-byte visible ASCII identifiers. The organization owner alone decides whether that role is currently permitted. Copies are immutable and safe for concurrent reads.

func (OrganizationInvitationScope) Format

Format hides correlated invitation and recipient metadata.

func (OrganizationInvitationScope) MarshalJSON

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

MarshalJSON rejects automatic export of trusted scope custody.

func (OrganizationInvitationScope) MarshalText

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

MarshalText rejects automatic export of trusted scope custody.

type Participant

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

Participant is an immutable coordinator-only one-use storage participant. Instances may serve concurrent independent commands; handles remain serial-use. The zero value is invalid. No handles, rows or runtime resources are retained. It supports reserve, takeover, provisional consumption, finalization, evidence and terminal release. Issuance, revocation and cleanup remain unfinished; execution still requires the complete identity-owned domain composition.

func NewParticipant

func NewParticipant() *Participant

NewParticipant creates the stateless default-schema participant without I/O. Migration installation and permissions remain explicit composition concerns.

Example
package main

import (
	"fmt"
	identitycapability "github.com/faustbrian/go-capability/postgres/identity"
)

func main() {
	p := identitycapability.NewParticipant()
	d := p.Descriptor()
	fmt.Println(d.Owner, d.ContractID, d.Version)
}
Output:
capability/postgres capability.one-use 1

func (*Participant) ApplyCapability

ApplyCapability provisionally consumes the exact original reservation under current-generation invocation custody. It locks before checking exclusive primary expiry and increments only below the signed maximum. It never renews expiry, releases evidence or claims a committed command. Rollback restores the original unused reservation; only the coordinator owns transaction closure.

func (*Participant) Descriptor

Descriptor returns the immutable identity of capability.one-use v1. It grants registration identity only, never invocation or transaction authority.

func (*Participant) FinalizeCapability

FinalizeCapability CASes the same consumed current-generation reservation to finalized in the protected transaction, after rechecking exclusive primary expiry under its row lock. Missing use, repeated/terminal state or changed binding conflicts. Finalization is provisional until the coordinator commits; it neither terminalizes the command ledger nor infers an unknown outcome.

func (*Participant) Format

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

Format redacts runtime participant state.

func (*Participant) MarshalJSON

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

MarshalJSON rejects serialization of runtime composition.

func (*Participant) RebindCapability

RebindCapability CAS-transfers only the exact previous reserved generation. It preserves immutable issued input and command/fingerprint; live primary expiry is required. Failed takeover leaves no participant or journal prefix.

func (*Participant) RecoverParticipant

RecoverParticipant reads retained primary evidence for the exact frozen input and previous reserved generation. Reserved or revoked with zero uses and matching original reservation linkage is negative evidence; finalized or used is committed participant evidence, never a command receipt. Missing, mismatched or other terminal evidence remains unknown. Expiry alone changes nothing. Coordinator combines all participant evidence before release.

func (*Participant) ReleaseCapability

ReleaseCapability terminal-releases an exact unused reserved record only with coordinator-granted unanimous non-commit authority. The transition CASes previous to recovery generation with the failure audit and aborted receipt. It never makes evidence reusable; expiry does not reactivate or erase it.

func (*Participant) ReserveCapability

ReserveCapability locks an existing issued record and binds exact command, fingerprint and generation in the coordinator's reservation transaction. It never inserts missing state or consumes a use. Expired, terminal or changed input returns a redacted Conflict. Only the exact registered instance may act.

type PreparationVerificationKey

type PreparationVerificationKey struct {
	// ID identifies original signing material under the codec's trusted issuer.
	ID string
	// HMAC supplies a nonzero 32..512-byte secret key instead of Ed25519 material.
	// Construction copies it; the key must differ from replay and envelope keys.
	HMAC []byte
	// Ed25519 supplies a 32-byte public verification key instead of HMAC material.
	Ed25519 []byte
	// Disabled denies verification with this key in the constructed codec.
	Disabled bool
	// Revoked marks this retained key as revoked for original-envelope verification.
	Revoked bool
	// NotBefore optionally limits the key's earliest accepted verification time.
	NotBefore time.Time
	// NotAfter optionally limits the key's latest accepted verification time.
	NotAfter time.Time
}

PreparationVerificationKey pins local signing-verification material and key lifecycle policy. Exactly one of HMAC or Ed25519 must be populated.

func (PreparationVerificationKey) Format

Format hides verification key material and lifecycle metadata.

func (PreparationVerificationKey) LogValue

LogValue redacts verification key material and lifecycle metadata.

func (PreparationVerificationKey) MarshalJSON

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

MarshalJSON rejects implicit verification-key export.

func (PreparationVerificationKey) MarshalText

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

MarshalText rejects implicit verification-key export.

type PreparedIssuance

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

PreparedIssuance is original request-memory custody, not authorization or a commit receipt. All copies share the proofs' one-transfer lifetime. Plan snapshots are owned; no method exposes raw bearer strings or signing keys.

func (PreparedIssuance) Format

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

Format hides prepared credential custody and immutable metadata.

func (PreparedIssuance) MarshalJSON

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

MarshalJSON rejects serialization of prepared credential custody.

func (PreparedIssuance) Plan

Plan returns a defensive metadata-only declaration. Retain the same prepared batch across retries; never sign replacement credentials after unknown commit.

func (PreparedIssuance) TransferForDelivery

func (p PreparedIssuance) TransferForDelivery(ctx context.Context, index uint16, encrypt func(context.Context, []byte) error) error

TransferForDelivery irreversibly transfers one proof only to synchronous authenticated encryption admission, never to a sender or response before commit. The trusted workflow owns that destination. Aliases are invalidated before the callback and borrowed bytes cleared after all exits. It is not a synchronous reveal API, a transport receipt or permission to retry disclosure.

Jump to

Keyboard shortcuts

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