legal

package
v0.25.1 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package legal is the framework's legal-compliance core (the legal-compliance framework plan, LC-1/LC-2/LC-3 + the LC-6 /config block): a compile-time document metadata registry, the legal_* settings key group, and click-through acceptance evidence that rides the existing identity hooks. It is a top-level composition package — NOT inside identity — for the same lateral-import reason as provisioning (ADR 0016): acceptance evidence composes identity hooks with the settings store and the audit recorder, and no single business domain may own that composition.

Design anchors (plan §5 / audit L3-L6):

  • Document text is DATA that ships with product code; the framework stores only metadata (version, effective date, billing model, placeholder list) — there is deliberately no legal_documents table (audit L4: a DB copy of the version would be a second truth).
  • Legal identity (entity name, jurisdiction, contact) lives in the settings registry: Wire registers the whole legal_* key group, so the generic admin settings card and env fallback come for free (audit L5).
  • Acceptance evidence rides AfterRegister/AfterLogin — the identity hooks that already fire on every registration/login path — instead of new endpoints or an identity signature change (audit L3).
  • Live values beat snapshots: the payment-processor name is a callback (ProcessorName func() string), never a billing import — this package must not depend on billing, so switching payment channels never leaves stale copy in legal text.

Index

Constants

View Source
const (
	MethodSignup        = "signup"
	MethodLoginImplicit = "login_implicit"
	MethodReaccept      = "reaccept"
)

Acceptance methods (LC-3): how an (user, doc, version) triple came to be recorded. signup = the account itself (every registration path via AfterRegister); login_implicit = "signing in means agreeing" backfill via AfterLogin; reaccept = an explicit POST /api/legal/acceptances.

View Source
const (
	CheckOK     = "ok"
	CheckWarn   = "warn"
	CheckManual = "manual"
)

ComplianceCheck statuses: ok (framework verified), warn (action needed), manual (promise the framework cannot verify — ops or a later batch).

View Source
const (
	BillingV1Subscription = "v1_subscription"
	BillingV2Credits      = "v2_credits"
	BillingV3Hybrid       = "v3_hybrid"
)

Billing-model enum — the Waffo template's mandatory three-way choice (subscription / credits / hybrid). Every registered Doc declares one, and Wire fails fast when the legal_billing_model setting disagrees with any Doc: the template's billing section and the live site must never diverge.

View Source
const (
	KeyEntityName    = "legal_entity_name"
	KeyEntityAddress = "legal_entity_address"
	KeyJurisdiction  = "legal_jurisdiction"
	KeyContactEmail  = "legal_contact_email"
	KeyBillingModel  = "legal_billing_model"
	KeyMinAge        = "legal_min_age"
)

Variables

This section is empty.

Functions

func KeySpecs

func KeySpecs() []settings.KeySpec

KeySpecs returns the whole legal_* key group in display order. Wire registers them; the descriptions double as the admin card's field help. Empty values are valid everywhere in this group: an unfilled legal key is a first-class state the compliance card red-lights, not a validation error.

func RegisterDocs

func RegisterDocs(docs ...Doc) error

RegisterDocs adds document metadata to the process-wide registry. It runs at boot and fails fast — returning an error, not panicking — on: a bad key/version shape, a zero EffectiveFrom, a BillingModel outside the three-way enum, a placeholder outside the known set, or a duplicate key (within the batch or against already-registered docs). The batch is validated before anything is appended, so a rejected call leaves the registry untouched.

Ordering with Wire: call RegisterDocs BEFORE legal.Wire — Wire reconciles every registered doc against the legal_billing_model setting and fails the boot on mismatch, which is only possible when the docs are already registered.

Types

type Acceptance

type Acceptance struct {
	UserID         string    `json:"user_id"`
	DocKey         string    `json:"doc_key"`
	DocVersion     string    `json:"doc_version"`
	Method         string    `json:"method"`
	IP             string    `json:"ip"`
	ClientPlatform string    `json:"client_platform"`
	ClientVersion  string    `json:"client_version"`
	ClientOS       string    `json:"client_os"`
	AcceptedAt     time.Time `json:"accepted_at"`
}

Acceptance is one click-through evidence row (migration 052). The unique constraint (user_id, doc_key, doc_version) makes every write idempotent — first evidence wins, and the client environment columns store the structured triple, never a raw User-Agent string.

type AcceptanceRepo

type AcceptanceRepo interface {
	// InsertAcceptances writes rows idempotently (INSERT … ON CONFLICT DO
	// NOTHING on the natural key). An empty slice is a no-op.
	InsertAcceptances(ctx context.Context, rows []Acceptance) error

	// UnacceptedDocs filters docs down to those whose CURRENT version has
	// no recorded acceptance for the user (any method counts — a signup
	// row covers the same version a login would). One lookup backs the
	// AfterLogin fast path.
	UnacceptedDocs(ctx context.Context, userID string, docs []Doc) ([]Doc, error)

	// AcceptancesByUser lists a user's full acceptance history, newest
	// first (admin evidence export / dispute response).
	AcceptancesByUser(ctx context.Context, userID string) ([]Acceptance, error)
}

AcceptanceRepo is the persistence port for acceptance evidence. The PG implementation is the shipped one; hermetic tests substitute a fake.

type Auditor

type Auditor interface {
	Record(ctx context.Context, workspaceID *string, p *webx.Principal, action, resourceType, resourceID string, meta map[string]any)
}

Auditor is the audit surface the legal module consumes — the exact Record signature of *audit.Recorder, as an interface so hermetic tests substitute a fake. Record is fire-and-forget by contract (it logs its own failures), so an audit write can never fail a user-facing operation.

type Compliance

type Compliance struct {
	MissingKeys []ComplianceMissingKey `json:"missing_keys"`
	LegalConfig ComplianceLegalConfig  `json:"legal_config"`
	Checks      []ComplianceCheck      `json:"checks"`
}

Compliance is the P0-lite admin reconciliation surface (LC-9): what the AdminComplianceCard renders. It aggregates three things the module already knows — unfilled legal_* settings keys (the red-light list that used to be a manual grep over copy placeholders), the resolved legal identity block, and a promise-vs-mechanism checklist. "manual" checks are promises the framework cannot verify from here (ops-level or later batches) — they are surfaced, not guessed.

type ComplianceCheck

type ComplianceCheck struct {
	ID     string `json:"id"`
	Label  string `json:"label"`
	Status string `json:"status"`
	Detail string `json:"detail,omitempty"`
}

ComplianceCheck is one promise-vs-mechanism line.

type ComplianceLegalConfig

type ComplianceLegalConfig struct {
	EntityName    string `json:"entity_name"`
	Jurisdiction  string `json:"jurisdiction"`
	ProcessorName string `json:"processor_name"`
	BillingModel  string `json:"billing_model"`
}

ComplianceLegalConfig mirrors the /config legal block's identity subset.

type ComplianceMissingKey

type ComplianceMissingKey struct {
	Key         string `json:"key"`
	Description string `json:"description"`
}

ComplianceMissingKey is one unfilled required legal_* key.

type Config

type Config struct {
	Pool  *pgxpool.Pool
	Store SettingsStore
	Log   *slog.Logger

	// Auditor optionally receives re-acceptance audit records
	// (*audit.Recorder satisfies the interface).
	Auditor Auditor

	// ProcessorName resolves the payment_processor_name placeholder live
	// (e.g. "Waffo Pancake"); nil = always empty.
	ProcessorName func() string

	// SiteURL resolves the site_url placeholder live; nil = always empty.
	SiteURL func() string
}

Config wires the legal module. Pool and Store are required; everything else is optional and silently degrades: without Auditor the re-acceptance action skips the audit trail, without ProcessorName / SiteURL the corresponding placeholders resolve to empty strings (the compliance card red-lights them). ProcessorName is a CALLBACK on purpose — this package must never import billing; the integrator passes e.g. the current merchant-of-record display name, and switching payment channels updates every legal text that references the processor without a code change.

type Doc

type Doc struct {
	// Key identifies the document ("tos", "privacy"). Lowercase letters,
	// digits and underscores, starting with a letter, at most 64 chars;
	// unique across registrations.
	Key string

	// Version is the human version tag rendered into /config and stored on
	// every acceptance row ("1.0", "2026-10-25.2", …).
	Version string

	// EffectiveFrom is the date the version takes legal effect. Required —
	// an acceptance row without an effective date cannot answer "which
	// version did they agree to" disputes.
	EffectiveFrom time.Time

	// BillingModel is the billing chapter this version's text carries —
	// one of BillingV1Subscription / BillingV2Credits / BillingV3Hybrid.
	BillingModel string

	// MaterialChange marks a version that materially changes obligations
	// (audited re-acceptation / change-notice territory; informational for
	// LC-3's evidence writes, consumed by the P1/P2 change-notice tooling).
	MaterialChange bool

	// Placeholders names the template variables the text references; every
	// entry must exist in the known placeholder set (the legal_* settings
	// keys plus payment_processor_name and site_url) so an unresolved
	// placeholder is caught at boot, not as "{{legal_entity_name}}" in
	// production copy.
	Placeholders []string
}

Doc is one legal document's compile-time metadata (LC-2). The text itself lives in product i18n files; this struct is what the framework reconciles and publishes — document versions ship with product code, so a release bump IS the version bump.

func RegisteredDocs

func RegisteredDocs() []Doc

RegisteredDocs returns a copy of the registry in registration order. Callers may mutate the returned slice freely.

type LegalPublic

type LegalPublic struct {
	EntityName    string      `json:"entity_name"`
	Jurisdiction  string      `json:"jurisdiction"`
	ProcessorName string      `json:"processor_name"`
	ContactEmail  string      `json:"contact_email"`
	Docs          []PublicDoc `json:"docs"`
}

LegalPublic is the `legal` block of the public /config payload (LC-6, audit L6 — rides the existing endpoint, no new fetch surface). Unfilled keys render as empty strings on purpose: the admin compliance card red-lights exactly those gaps, and product legal pages substitute them.

type Module

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

Module is everything legal.Wire mounts. It is inert by itself — the integrator decides which pieces to attach: Hooks() onto the identity services (via identity.ChainHooks when other hooks already occupy the slots), Service() onto the re-acceptance/admin handlers, PublicConfig onto the public /config payload.

func Wire

func Wire(cfg Config) (*Module, error)

Wire is the one-line product integration (LC-1, the provisioning.PersonalWorkspace precedent): it registers the whole legal_* settings key group on the store, reconciles every registered doc against the legal_billing_model setting (fail-fast — call RegisterDocs BEFORE Wire so the reconciliation sees them), and returns the mountable pieces. A product that never calls Wire keeps today's behavior exactly.

func (*Module) Compliance

func (m *Module) Compliance(ctx context.Context) Compliance

Compliance builds the admin report. Store read failures degrade to an empty report (the card shows what it can) rather than erroring the admin endpoint — a half-empty checklist beats no checklist.

func (*Module) Hooks

func (m *Module) Hooks() identity.IdentityHooks

Hooks returns the identity hook surface for acceptance evidence (LC-3, audit L3). Compose it with the other hooks a product already wires — identity services take exactly one hook value, so use identity.ChainHooks:

sessions.WithHooks(identity.ChainHooks(
	provisioning.PersonalWorkspace(cfg), legalMod.Hooks()))

Both hooks honor the identity contract verbatim: they are idempotent (the (user_id, doc_key, doc_version) unique key + ON CONFLICT DO NOTHING — not code discipline), and they return errors instead of logging, letting the identity firing sites apply their documented semantics — AfterRegister failures become LoginResult.ProvisioningPending and re-fire on the next login; AfterLogin failures are logged at WARN and never block the login. With no registered docs both hooks are no-ops.

func (*Module) PublicConfig

func (m *Module) PublicConfig(ctx context.Context) LegalPublic

PublicConfig resolves the legal block live: settings values (DB row > env > default, hot-reloaded per request), the processor-name callback, and the registered docs' versions and effective dates. A settings read failure degrades honestly: the value fields stay empty, the docs list still publishes, and the error is logged — a public config endpoint must answer, and the compliance card surfaces the gap.

func (*Module) Service

func (m *Module) Service() *Service

Service exposes the principal-facing and admin operations (Reaccept, AcceptancesByUser).

func (*Module) SiteURL

func (m *Module) SiteURL() string

SiteURL resolves the site_url placeholder live ("" when unwired) — the one Config input that is not part of the public /config legal block; products resolving their own copy call this alongside PublicConfig.

type PGAcceptanceRepo

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

PGAcceptanceRepo is the AcceptanceRepo implementation over the shared pool. It never opens its own transactions: every statement is a single idempotent write or read, safe under concurrent logins.

func NewAcceptanceRepo

func NewAcceptanceRepo(pool *pgxpool.Pool) *PGAcceptanceRepo

NewAcceptanceRepo builds the PG repo; the clock is injectable for tests.

func (*PGAcceptanceRepo) AcceptancesByUser

func (r *PGAcceptanceRepo) AcceptancesByUser(ctx context.Context, userID string) ([]Acceptance, error)

func (*PGAcceptanceRepo) InsertAcceptances

func (r *PGAcceptanceRepo) InsertAcceptances(ctx context.Context, rows []Acceptance) error

func (*PGAcceptanceRepo) UnacceptedDocs

func (r *PGAcceptanceRepo) UnacceptedDocs(ctx context.Context, userID string, docs []Doc) ([]Doc, error)

type PublicDoc

type PublicDoc struct {
	Key           string `json:"key"`
	Version       string `json:"version"`
	EffectiveFrom string `json:"effective_from"`
}

PublicDoc is one document's published identity inside the legal block.

type Service

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

Service carries the user-facing legal operations: explicit re-acceptance and the admin acceptance-history query. The implicit write points live on the identity hooks (Module.Hooks); this is everything that needs a principal or an operator's eye.

func (*Service) AcceptancesByUser

func (s *Service) AcceptancesByUser(ctx context.Context, userID string) ([]Acceptance, error)

AcceptancesByUser returns a user's full acceptance history, newest first — the admin evidence export behind "which version did this user agree to" disputes and DSAR responses.

func (*Service) Reaccept

func (s *Service) Reaccept(ctx context.Context, p *webx.Principal, docKey string) error

Reaccept records an explicit, user-initiated acceptance of one document's current version (POST /api/legal/acceptances territory — the handler is a thin wrapper around this call). Idempotent: re-accepting a version the user already recorded is a silent no-op (first evidence wins), which is exactly what a re-submit double-click should do. When an Auditor is wired the action lands in the audit trail with the version, method and IP.

type SettingsStore

type SettingsStore interface {
	RegisterKeys(specs ...settings.KeySpec) error
	Effective(ctx context.Context) (map[string]string, error)
	// EffectiveKey is the single-key read the boot-time reconciliation uses:
	// unlike Effective it cannot fail because of an UNRELATED sealed key
	// (settings.Store.EffectiveKey doc — the no-SEAL_KEY amplification bug).
	EffectiveKey(ctx context.Context, key string) (string, error)
}

SettingsStore is the settings surface the legal module consumes; it is the exact method subset *settings.Store already implements, as an interface so hermetic tests substitute a fake (pass the real store unchanged).

Directories

Path Synopsis
adapters
http
Package legalhttp mounts the legal module's HTTP surface: the logged-in re-acceptance endpoint and the platform-admin acceptance-history / compliance endpoints.
Package legalhttp mounts the legal module's HTTP surface: the logged-in re-acceptance endpoint and the platform-admin acceptance-history / compliance endpoints.

Jump to

Keyboard shortcuts

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