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

magiclinkpostgres

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

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

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

README

This experimental Go 1.27 module composes the existing identity coordinator, capability issuer, encrypted delivery, risk and session owners. Public signin-only and explicitly selected signup request, consume and recovery paths are present. Selected enrolled-MFA login yields an original continuation rather than a single-factor session; native TOTP completion is composed separately. This is a backend library, not a login UI or a release-qualified identity product.

Public request and consumption

NewRequestService selects explicit RequestConfig, a primary pool and the local envelope keyring. Request binds original browser possession, callback, address policy and risk; issuance, delivery intent, audit and lifecycle effects share the existing coordinator transaction. The caller receives a neutral acknowledgement, not a bearer or selected account. A configured delivery worker sends only committed encrypted custody through the consumer's bounded sender.

Select RequestConfig.Signup and its matching Possession policy to admit SignupIfAllowed. An unused mailbox receives a signed prospective creation; request/delivery creates no user. Existing verified accounts use the normal signin path without duplicate creation. Occupied ineligible mailboxes remain enumeration-safe. Consumption alone creates the user, verified email, empty factor authority, policy authority and session in the protected transaction. Install kernel registration/acceptance and magic-link registration extensions, plus the MFA owner's magic-link signup extension, before enabling this profile. Reuse the same identifier comparison/retirement key history as other account creation methods. New prospective resends supersede previous unused links in the original mailbox/browser/policy family, not by newly allocated account IDs.

NewConsumeService composes the public explicit-consumption path. It authenticates the original proof and durable provenance, cookie/origin/callback and current account/address/factor/policy/risk authority before atomic session issuance. Inspection does not consume a link. Recovery is credential-free and cannot redeliver a token. Required but unsupported MFA denies instead of falling back to a single-factor session.

Original primary metadata for MFA

After authenticating the original child and stored continuation, use the capability owner's ReadMFAMagicLinkParent to obtain opaque consumed-parent custody. RequestService.ReadMFAMagicLinkPrimary then reads the original committed request under current history-access policy, decrypts its existing preparation, reconstructs every signed payload field and matches the complete canonical digest. It returns the original recipient and session.MagicLinkAuthentication, not a factor proof, current access authority or session credential.

Supply the original restored browser flow and the stored continuation's original primary authentication time. These are trusted native inputs, not request overrides. Before charging a factor denial or completing a session, verify the submitted cookie and use the session owner's consumed-browser guard. Repeat current recipient/account/factor/policy checks in the protected completion transaction; historical metadata alone cannot authorize it. No old risk admission is restored as new permission and no primary bearer is needed again.

Codec compatibility and adoption

New signin request outputs retain their full command inside an authenticated MLR2 origin codec. AAD binds the exact original command scope, generation and configuration, without needing unrecoverable initiating fields. The existing journal remains its only persistence owner; no new intent table is installed. Legacy signin and prospective retry contexts keep their original meaning. Changing or removing the codec marker cannot relabel ciphertext successfully.

Origin-only reconstruction deliberately refuses legacy signin records lacking the retained full command. Ordinary retries can still restore those records with their original input. Upgrade every request writer before enabling MFA challenge branching, and fail closed on missing origin custody rather than inventing metadata or asking for another reusable primary credential.

Security and ownership

Pools, immutable configuration and opaque inputs are borrowed; earlier context deadlines win over configured finite budgets. No background goroutine or separate transaction owner is created. Do not log or implicitly serialize metadata, proofs, cookies, preparation output or reveal-once results. Foreign actors/scopes, corrupt history and unavailable authority return zero projections. Consumers supply configuration and bounded policy/provider callbacks, not replacement domain stores or workflow implementations.

Native public request/delivery/signin, origin reconstruction, legacy restoration and denial/rollback/retry behavior have focused integration tests. The origin test's consumed-parent/child tuple is a labeled fixture; its native atomic production has separate capability-owner tests. Neither proves completed public MFA login. Complete MFA/reference/HTTP composition and release gates remain.

Documentation

Overview

Package magiclinkpostgres provides optional native PostgreSQL composition for magic-link workflows. The core module remains independent of SQL adapters.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ConsumeConfig

type ConsumeConfig struct {
	ConfigurationID, PolicyNamespace string
	Issuer                           session.IssuerConfig
	CSRF                             session.CSRFKey
	MFA                              *MFAChallengeConfig
}

ConsumeConfig selects the session owner's original lookup/cookie/CSRF custody and current user authorization namespace. ConfigurationID pins these semantics and must change when they change. RequestService retains the original request profile, issuer, browser, risk and envelope configuration. Neither config is client input. Authority must be nil for this grant-consuming issuance profile.

func (ConsumeConfig) Format

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

Format redacts borrowed secret and deployment configuration.

func (ConsumeConfig) MarshalJSON

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

MarshalJSON prevents implicit secret-bearing configuration export.

type ConsumeService

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

ConsumeService composes original request custody with native one-use/session effects under the existing coordinator. It owns no goroutine, connection, sender, token table or independent journal. The borrowed RequestService and primary pool outlive calls; callers close their resources. Zero denies.

func NewConsumeService

func NewConsumeService(request *RequestService, c ConsumeConfig) (*ConsumeService, error)

NewConsumeService freezes the actual native owners without IO or migrations. Install magic-link session/issuance and authorization histories alongside all RequestService prerequisites. The default denies enrolled factor authority; explicit MFA selection additionally needs MFA continuation and confirmed TOTP histories. It issues only a continuation, never an enrolled account's session.

func (*ConsumeService) Consume

Consume attempts one original stable command. It authenticates durable grant origin and browser intent before native preparation, then generates one prospective session only after acknowledged journal ownership. The retained output contains tokenless session fields, never the new bearer. Protected effects and one-use finalize atomically; only the generating invocation can deliver credentials after an exact committed receipt. Ambiguity and replay never regenerate. Caller-supplied user, factor, expiry or remember overrides are absent from the input contract.

func (*ConsumeService) ConsumeRateSource

func (s *ConsumeService) ConsumeRateSource(ctx context.Context, r magiclink.ConsumeRequest) (user identity.UserID, challenge string, lifetime time.Duration, err error)

ConsumeRateSource authenticates durable original issuance, complete signed scope, current primary recipient and original browser custody before exposing sensitive subject/challenge metadata for HTTP admission. Lifetime is original signed expiry minus issuance, never remaining time or a renewed interval. Query policy must authorize the original anonymous-flow resource at its exact configured revision. An omitted resource is filled; a foreign explicit one denies. No proof transfer/use reservation, counter debit, session generation, mutation, retry or goroutine occurs. Consume independently repeats current authority and factor/risk checks in its protected transaction. Metadata grants no login permission; never log it or return it to the browser. Calls are concurrent-safe, bounded by original configuration/earlier deadlines, and every failure returns zero metadata.

func (*ConsumeService) RecoverConsume

RecoverConsume reconciles only the original proof-free command under current result-access policy. No proof/browser input, session generation, provider, sender or credential delivery is possible. Committed metadata never implies a currently valid session; live session validation remains session-owned.

type MFAChallengeConfig

type MFAChallengeConfig struct {
	Lifetime    time.Duration
	MaxAttempts uint32
}

MFAChallengeConfig enables native TOTP continuation, never a single-factor session for enrolled accounts. Lifetime is absolute and capped by original primary expiry/five minutes. Missing supported factor authority denies.

type MFAMagicLinkPrimary

type MFAMagicLinkPrimary struct {
	Recipient      kernel.RecipientRecord
	Authentication session.MagicLinkAuthentication
}

MFAMagicLinkPrimary is authenticated historical request metadata, not current account authority, a factor proof or a session. Recipient is the exact original selected address/versions; protected completion must fence it against primary authority. Authentication preserves the original primary time and exclusive parent expiry, never the time this projection was read. Copies own scalar metadata and immutable session bindings; do not mutate borrowed input.

func (MFAMagicLinkPrimary) Format

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

Format redacts historical primary identity and recipient metadata.

func (MFAMagicLinkPrimary) LogValue

func (MFAMagicLinkPrimary) LogValue() slog.Value

LogValue redacts correlated recipient and primary metadata.

func (MFAMagicLinkPrimary) MarshalJSON

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

MarshalJSON refuses implicit historical metadata export.

func (MFAMagicLinkPrimary) MarshalText

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

MarshalText refuses implicit text/map-key export.

type RequestConfig

type RequestConfig struct {
	MaximumDuration                                         time.Duration
	ConfigurationID, PolicyID, GlobalAuthorityID, IssuerURL string
	Origins, Callbacks                                      []string
	Lifetime                                                time.Duration
	Address                                                 email.AddressParser
	Coordinator                                             kernel.CoordinatorConfig
	RequestKeys                                             kernel.RequestKeyConfig
	Issuer                                                  issuerpg.IssuerConfig
	IssuanceCustody                                         issuerpg.IssuancePreparationConfig
	Risk                                                    risk.AuthenticationAdmissionCustodyConfig
	Session                                                 sessionpg.Config
	CookieKeys                                              map[uint32]session.DigestKey
	IntentKey                                               [32]byte
	ActiveEnvelopeKeyID                                     string
	Delivery                                                RequestDeliveryConfig
	// Possession is explicit email-owned prospective signup acceptance. Nil
	// disables prospective issuance; it does not alter existing signin profiles
	// or enable the unfinished public signup workflow by itself.
	Possession *email.MagicLinkPossessionPolicy
	// Signup selects prospective account creation policy. Nil leaves signup
	// disabled. Possession must select the identical mailbox-policy version.
	Signup *SignupConfig
	// MFAContinuation enables primary-link requests for known enrolled accounts.
	// False preserves single-factor-only suppression. Consumption still requires
	// its separately selected native MFA branch; this flag grants no session.
	MFAContinuation bool
}

RequestConfig selects immutable native request composition. ConfigurationID pins callback/renderer/parser semantics; change it when those semantics change. Keys are independent original-intent HMAC/cookie/issuance/envelope owners, not interchangeable credentials. Every retained cookie version must be kept while its flow is supported. This initial request path is signin-only; optional Signup remains unfinished rather than silently enabled. Resends supersede unused links for the exact original recipient/browser flow transactionally.

func (RequestConfig) Format

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

Format redacts configuration and borrowed key custody.

func (RequestConfig) LogValue

func (RequestConfig) LogValue() slog.Value

LogValue redacts structured configuration diagnostics.

func (RequestConfig) MarshalJSON

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

MarshalJSON forbids implicit configuration export.

func (RequestConfig) MarshalText

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

MarshalText forbids implicit textual configuration export.

type RequestDeliveryConfig

type RequestDeliveryConfig struct {
	Owner                *deliverypg.Contributor
	Renderer             *delivery.TemplateRenderer
	Endpoint, TemplateID string
	TemplateVersion      uint32
	ProviderVersion      uint64
	Locales              []string
	ScopeKey             [32]byte
	Timeout              time.Duration
}

RequestDeliveryConfig selects actual encrypted delivery and rendering owners. Endpoint is a trusted HTTPS landing URL without query/fragment/userinfo. The bearer goes only into the emailed fragment, never the callback or a redirect. The landing consumer submits it explicitly in a no-store body. This backend supplies no UI and never invokes a sender before request commitment.

type RequestService

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

RequestService owns public request and proof-free recovery through the real kernel journal, capability issuer, risk and encrypted delivery participants. It borrows the primary pool and local keyring and starts no goroutine, retry, transaction outside the coordinator, sender or independent intent store.

func NewRequestService

func NewRequestService(pool *database.Pool, c RequestConfig, keys *keyring.Provider) (*RequestService, error)

NewRequestService freezes explicit composition without IO, migrations or callbacks. Install kernel preparation/request-key/authority, session pre-auth, MFA authority, capability issuance, delivery, audit and lifecycle histories first. Missing/inactive primary authority denies, never implies empty state.

func (*RequestService) ReadMFAMagicLinkPrimary

func (s *RequestService) ReadMFAMagicLinkPrimary(ctx context.Context, parent issuerpg.MFAMagicLinkParent, flow session.PreAuthTransaction, authenticatedAt time.Time, caller authorization.DecisionContext) (out MFAMagicLinkPrimary, err error)

ReadMFAMagicLinkPrimary reconstructs original magic-link metadata after the capability owner has authenticated its consumed parent through the original MFA child. flow must be restored original browser custody; authenticatedAt must be the authenticated stored continuation's original primary admission time, never request data or this read's clock. Caller is trusted native transport/result-access context. This seam is not a public lookup endpoint.

Current history-access policy precedes reads/decryption of the existing committed request preparation. The owner reconstructs every original signed payload field and compares its full canonical digest against opaque parent custody. It does not restore old risk admission as new permission, decrypt a bearer, generate or transfer credentials, mutate state, consume, renew or run a sender. Final completion must authenticate original cookie possession and repeat current account/recipient/factor/policy/child checks in its protected transaction; a projection is not an execution ticket.

Concurrent calls borrow the pool and immutable service configuration. One MaximumDuration and the earlier caller deadline bound policy, indexed journal reads and local decryption. Zero/foreign scope denies; missing/legacy origin ciphertext or unavailable storage fails closed without reconstructing intent from a digest. Cancellation retains its classification. Every failure returns zero metadata; errors and diagnostics expose no correlated or credential data.

func (*RequestService) RecoverRequest

RecoverRequest reconciles the original request through current result-access policy and participant custody. It takes no email/cookie/token and cannot issue, render, renew or send another message.

func (*RequestService) Request

Request preserves raw original intent in a keyed digest and issues/encrypts only in the journal's acknowledged first generation. Native final Work fences the same verified recipient, browser, MFA, directory and original risk facts, then stages issuer/message/audit/lifecycle atomically. Eligible and suppressed selections have identical acknowledgements. No bearer or selected user leaves this call; ambiguity never triggers automatic regeneration or a sender.

func (*RequestService) RequestRateSource

func (s *RequestService) RequestRateSource(ctx context.Context, input email.AddressInput) (canonical string, err error)

RequestRateSource returns the frozen request parser's canonical destination without account, factor, issuer, delivery or database access. It grants no eligibility or authentication authority. Call after trusted-IP admission, debit the shared destination budget, then pass the same raw input to Request; Request independently repeats normalization and current recipient selection. The returned address is sensitive: never log it or include it in a response. Calls are concurrent-safe, bounded by the parser's input limits and perform no IO or callbacks. Cancellation and invalid configuration return no source.

type SignupConfig

type SignupConfig struct {
	SchemaID      string
	SchemaVersion uint32
	Domain        kernel.MagicLinkRegistrationDomainConfig
}

SignupConfig freezes prospective account schema and kernel retirement policy. It is trusted server configuration, never an anonymous request field. The request allocates IDs only in acknowledged generation; no account is created until the original link is consumed under mailbox, risk and current authority. Construction copies retained keys. Do not log or export configuration.

func (SignupConfig) Format

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

Format redacts retained identifier keys and configuration.

func (SignupConfig) MarshalJSON

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

MarshalJSON prevents implicit export of key-bearing configuration.

Jump to

Keyboard shortcuts

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