# iMakeFun — original platform architecture

> Updated requirements: `implementation-v2.md` supersedes conflicting API origin, plans, monorepo, authentication and release scope in this original design. The API root is now https://api.imakefun.com/v1/.

Canonical origin: **https://www.imakefun.com**. Architecture baseline: 22 September 2026.

This is the implementation blueprint, not a claim that the complete service is running. The initial repository implements the pure generation/credit domain and a foundational SQL migration. Live identity, AI providers, payment processing, storage and deployment remain integration work.

## 1. Product requirements

The product is a private creative workspace for individual creators, agencies and production teams. Its primary journey is project → inputs → editable generation specification → price estimate → asynchronous job → review → revision → licensed export. Every asset belongs to a workspace and project. A personal account gets its own workspace; team accounts use the same tenancy model.

The complete product includes the capabilities in the accompanying original brief. Acceptance is based on working end-to-end flows, not the presence of navigation labels.

| Area | Requirement | Acceptance criterion | Phase |
|---|---|---|---|
| Accounts | Email/OIDC sign-in, verified identity, recovery, MFA, session revocation, export/deletion | Revoked sessions cannot access private media; recovery cannot enumerate accounts | 1 |
| Workspace | Dashboard, projects, uploads, library, search, favorites, trash, versions | A saved project survives sign-out; cross-workspace requests are denied | 1 |
| Commerce | Plans, invoices, credit purchases, subscriptions | Replayed payment events cannot grant credits twice | 1 |
| Images | Generation, reference editing, masks, variation, upscale, restoration | User can submit, track, review and export a real result | 2 |
| Video | Text/image/video inputs, motion, duration, audio, enhancement | Unsupported provider settings are rejected before debit | 2 |
| Voice input | Consent-based recording, upload, transcription, editable prompt | No transcription automatically submits a paid generation | 2 |
| Editing | Multitrack timeline, trim/split, transforms, audio, subtitles, undo | Reload restores the timeline; export reproduces saved state | 3 |
| Film | Script, reusable characters, shots, storyboard, approval stages | Only approved shots enter a final render; failed shots can be retried alone | 4 |
| Collaboration | Invites, roles, comments, review links, public portfolios, discovery | Viewer cannot mutate; unpublishing revokes public delivery | 5 |
| Enterprise | Scoped API keys, SSO, advanced policy, custom providers | Keys can be revoked and usage attributed to a workspace | 6 |

Nonfunctional launch targets (design targets, to measure): 99.9% control-plane availability; p95 metadata reads below 300 ms under the agreed load profile; durable job acknowledgement below 1 second excluding third-party operations; WCAG 2.2 AA; recoverable database RPO ≤15 minutes and RTO ≤4 hours after restore drills. Model latency and visual consistency are provider-dependent and must not be promised as deterministic.

## 2. Stack decision and alternatives

Use a TypeScript monorepo: React/Next.js web, NestJS modular API, PostgreSQL system of record, Redis/BullMQ workers, S3-compatible private object storage, CDN, Stripe billing, and FFmpeg render workers. Add Python/FastAPI only for processing that needs Python libraries or GPU inference. Start with managed containers and managed database services; choose exact versions and pin dependencies during each integration.

| Decision | Selected approach | Tradeoff / alternative |
|---|---|---|
| Web | Next.js + React + TypeScript | SEO for creator pages plus interactive editor; plain React SPA is simpler but requires separate public rendering |
| API | NestJS modular monolith | Consistent modules and authorization; FastAPI is appropriate for Python workers, not a second competing business backend |
| Database | PostgreSQL | Transactions and relationships suit credits and tenancy; document databases complicate accounting invariants |
| Queue | BullMQ with Redis | Fits TypeScript and launch volume; managed SQS reduces Redis operations; Kafka only for demonstrated event-stream requirements |
| Storage | S3-compatible adapter; S3 initial recommendation | Lifecycle/region tooling; R2 may improve egress economics, subject to measured workload and residency |
| Search | PostgreSQL full-text + trigram initially | Introduce OpenSearch when corpus size/relevance requirements justify another system |
| Delivery | Managed containers + CDN | Kubernetes adds operational cost; adopt only for scheduling/scale needs supported by staff |
| Billing | Stripe initially; payment adapter boundary | PayPal later; wallet availability depends on merchant configuration and region |

Keep WebSockets for collaboration later; server-sent events plus polling fallback suffice for job progress. Never use the queue or browser storage as the billing ledger.

## 3. High-level system

```mermaid
flowchart LR
  U[Creator browser] --> E[CDN / WAF / HTTPS]
  E --> W[Web and same-origin API proxy]
  W --> A[API: identity, projects, billing, generation]
  A --> P[(PostgreSQL + outbox)]
  A --> S[Private object storage]
  P --> D[Outbox dispatcher]
  D --> Q[(Redis queues)]
  Q --> G[AI gateway workers]
  Q --> R[Render / scan workers]
  G --> V[Provider APIs]
  G --> S
  R --> S
  A --> B[Payment processor]
  G --> P
  R --> P
```

The control plane owns authorization, quotes, reservations and job state. The data plane processes media asynchronously. Business modules initially share one database and deployable API; queues isolate generation, transcription, moderation, thumbnails and rendering. Extract services only when ownership or resource isolation warrants it.

## 4. Frontend architecture

`apps/web` will contain App Router routes, feature modules, a shared accessible component library and a generated API client. Server components render public pages and initial authenticated data. Client components own prompt editing, uploads and timeline interactions. Server state uses one query cache; timeline state uses a normalized document with command-based undo/redo. Avoid duplicating authoritative credit or entitlement calculations in the browser.

The editor stores integer frame/tick positions, source in/out points, independent tracks, transforms, gain envelopes and subtitle cues. Preview uses proxies; final rendering uses original assets and a pinned render specification. Autosave uses ETags/document versions and rejects conflicting writes with 409. Start with optimistic versioning and review comments; introduce a CRDT only for simultaneous editing requirements.

## 5. Backend architecture

Modules: identity, workspaces, memberships, projects, assets, generations, models, moderation, billing, credits, exports, notifications, sharing and administration. Each owns its repository and application services. Controllers validate inputs and call services; no controller writes directly to billing tables. Transaction boundaries cover generation creation + credit reservation + outbox insertion. An outbox dispatcher bridges database commits to queue delivery. Internal events contain IDs and minimal metadata, never signed URLs or raw secrets.

## 6. Provider-independent AI gateway

Expose `generateImage`, `generateVideo`, `generateVoice`, `transcribeAudio`, `generateMusic`, `enhanceImage`, `enhanceVideo` through typed operation contracts. Adapters implement capabilities, quote, submit, inspect, cancel and normalizeResult. Requests include internal idempotency key, immutable model revision, structured input asset references, output constraints, safety policy revision and license policy revision.

Capabilities declare supported inputs, aspect ratios, resolutions, durations, seeds, reference limits, cancellation and idempotency support. Model selection filters by capability, region, entitlement, safety, licensing and spend limit before scoring latency/cost. Administrators may disable a registered adapter/model or edit its configuration; a new protocol still requires code.

Persist provider request IDs and attempts. A submission timeout means **unknown outcome**, not safe failure. Reconcile with the provider before retrying; never automatically submit a different paid provider after an ambiguous timeout. Fall back only on a known pre-acceptance rejection or confirmed terminal failure within the authorized quote. Do not promise identical character output across providers; store reference packs, model revision and consistency scores for human review.

## 7. Database design

UUID primary keys, UTC timestamptz, bigint byte/credit/money units and explicit foreign keys. The foundational migration implements users, workspaces, memberships, projects, credit accounts, reservations, ledger, generations and outbox. Remaining entities below are the target schema, not yet migrations.

| Tables | Relationships and important fields/indexes |
|---|---|
| users, identities, sessions, mfa_factors, recovery_codes | identities unique(provider,subject); session token hash unique; user_id/expires_at index; factor secrets encrypted |
| profiles, notification_preferences, consents | profile user_id unique; case-insensitive username unique; visibility enum; consent purpose/version/evidence |
| workspaces, memberships, invitations | membership PK(workspace_id,user_id); role owner/admin/editor/viewer; hashed invite tokens unique, expiry |
| plans, plan_versions, subscriptions, entitlement_snapshots | price/benefit versions immutable; processor subscription ID unique; workspace/status index |
| payments, invoices, payment_events | processor/external_id unique; invoice currency and integer totals; raw events access-restricted with retention |
| credit_accounts, credit_reservations, credit_ledger, credit_grants | one account per workspace; append-only ledger; reservation by generation; expiring grant lots later; no floating-point accounting |
| projects, project_versions | workspace/id composite key; workspace/updated_at index; unique(project_id,version); archive/deletion timestamps |
| assets, asset_versions, asset_derivatives | project/workspace scoped FK; object key unique; media kind, checksum, scan status, size, duration, codec, dimensions |
| image_metadata, video_metadata, audio_metadata | asset_id unique; subtype properties, streams and color profile |
| films, scenes, shots, storyboards, storyboard_frames | project ownership; ordered scene and shot positions; explicit approved revision |
| characters, character_references, voices, voice_consents | workspace ownership; reference asset FK; versioned appearance/voice instructions and consent evidence |
| prompts, generations, generation_attempts, job_events | model/version, immutable request, input asset IDs, provider request ID, estimate/actual cost; workspace/status/time index |
| ai_providers, ai_models, model_versions, model_policies | unique(provider,external_model,revision); enabled state; capability and license snapshots; secrets referenced, never stored plaintext |
| timelines, timeline_versions, exports, export_licenses | project scoped; immutable render document/hash and licensing manifest; signed export reference |
| folders, collections, collection_items, favorites, tags, asset_tags | unique owner/item pairs; scoped joins prevent cross-workspace links |
| shares, publications, followers, likes, comments | hashed scoped share token; unique follower/followed; unique actor/content like; comments bind asset revision/timecode |
| templates, template_versions, marketplace_orders | owner, published version, license, price currency; marketplace settlement deferred |
| notifications, notification_deliveries | user/read_at/time index; event/channel/user deduplication key |
| api_keys, audit_logs, reports, moderation_decisions, support_tickets | hashed keys with scopes/expiry; append-only audits; report status/time index; decision policy/version |
| outbox, consumer_receipts, idempotency_keys | unique tenant/key; request hash and response; partial pending outbox index; per-consumer event receipt |
| deletion_requests, data_exports, retention_holds | user/workspace scope; deadlines and purge proof; legal hold reason with restricted access |

All tenant-to-tenant references include workspace_id in composite foreign keys. Tenant tables use RLS as defense in depth, with a non-owner runtime role and transaction-local tenant context derived from authenticated membership. Never trust a workspace header alone. Platform administration uses a separately audited service identity. Index foreign keys and actual query predicates; avoid indexing arbitrary JSON fields preemptively. Partition high-volume job events/audit records by time after measurements justify it.

## 8. Storage architecture

Private buckets for quarantine, originals, derived media and exports; separate public copies for approved publications. Keys use opaque workspace/project/asset IDs, never user-supplied paths. API issues short-lived constrained upload authorizations after quota checks; completion verifies object size, signature, checksum and ownership, then queues malware/media parsing scans. Quarantined assets cannot be viewed or sent to models. Parser workers run sandboxed with memory, CPU and duration limits.

Use multipart uploads for large files, lifecycle cleanup for abandoned parts, temporary files and expired exports, and database tombstones for deferred deletion. CDN uses signed delivery for private content. Provider outputs are downloaded by an allowlisted fetcher with SSRF protections, revalidated and stored; provider links are not durable asset URLs. Maintain restore-tested backups and object versioning per retention policy.

## 9. Job architecture

User-visible states: queued → processing → rendering → completed, with failed/cancelled terminal branches. Internally use leases, attempts, heartbeat, cancellation-requested and reconciliation-needed metadata. Progress is stage-based, not a fabricated percentage. Workers may receive messages more than once; all effects must be idempotent.

1. Authenticate, authorize project, validate approved inputs and moderate prompt.
2. Produce an expiring server quote from immutable model pricing and entitlement versions.
3. In one transaction: lock credit account, validate unexpired quote, reserve credits, insert generation and outbox event under a tenant-scoped idempotency key.
4. Dispatcher enqueues using stable job ID; failed dispatch can safely retry.
5. Worker obtains a lease, rechecks cancellation, submits/reconciles provider attempt and persists provider request ID.
6. Fetch, validate and moderate result, persist asset metadata, then atomically settle credits and complete job.
7. Release reservation on confirmed unbillable failure. Billable partial work follows the displayed cancellation policy; never exceed the reserved quote without new approval.
8. Periodic reconciliation detects stale leases, missing results, stranded reservations and delayed callbacks. Dead-letter failures expose a recovery action to operators.

A cancelled local job does not guarantee provider cancellation. Signed webhooks and polling reconciliation must converge to the same durable state. Completion/cancellation races serialize on the generation row. SSE events are tenant authorized and resumable; polling reads authoritative database state.

## 10. Dashboard structure

Desktop: collapsible navigation, active workspace selector, central recent projects and Create action, compact credit/storage indicators, and a job activity drawer. Create shows modality, prompt/record/upload inputs, model-compatible controls, estimated cost and explicit submission. Advanced controls use progressive disclosure. Project detail groups media, scenes, characters, versions and exports. Empty states offer a real next action; failed jobs explain whether credits were returned.

Mobile supports browsing, prompting, reviewing and light edits. Full timeline editing prioritizes desktop, with clear device guidance rather than inaccessible squeezed controls.

## 11. Application sitemap and domain

Canonical root **https://www.imakefun.com**. Redirect `https://imakefun.com/*` to the same path/query on `https://www.imakefun.com/*` with 308 after DNS and certificates are ready. Use same-origin `/api/v1` for browser APIs to simplify cookie security. Future developer APIs can use api.imakefun.com. Media origin may use media.imakefun.com with separate signed-delivery policy; no wildcard session cookies.

```
/                              public product entry
/pricing /templates /explore    public discovery
/creator/[username]            public creator profile
/watch/[publicationId]         approved public creation
/legal/terms /legal/privacy /legal/licenses
/auth/sign-in /auth/sign-up /auth/verify /auth/recover /auth/mfa
/app                          creator home
/app/create/[mode]             image, video, film, audio, storyboard
/app/projects /app/projects/[id]
/app/projects/[id]/editor /storyboard /scenes /characters /exports /history
/app/media /images /videos /films /audio /characters
/app/templates /shared /favorites /trash
/app/settings/profile /security /sessions /notifications /privacy
/app/settings/team /billing /credits /storage /api-keys
/admin/users /billing /credits /jobs /models /storage
/admin/moderation /reports /audit /support /analytics
/api/v1/*
```

DNS values must come from the selected deployment. Domain ownership, TLS issuance, redirect behavior and email authentication (SPF/DKIM/DMARC) require verification; this repository does not change DNS.

## 12. Authentication and authorization

Prefer a mature OIDC identity service with verified email, Google/Apple/Microsoft federation, MFA/passkeys and recovery. If self-hosting identity, budget patching, email delivery and abuse controls explicitly. BFF uses opaque server sessions in Secure, HttpOnly, SameSite cookies, CSRF tokens and Origin validation for mutations. Rotate session after authentication and privilege changes. OAuth uses state, nonce, PKCE and exact redirect allowlists. Hash session and API tokens at rest.

Require workspace membership on every request and job action. Owner controls billing and membership; admin manages workspace; editor edits; viewer reads. Support staff cannot silently impersonate users. Admin and finance adjustments require MFA, justification and immutable audit events. Account deletion revokes sessions immediately and schedules asset deletion with clearly documented retention exceptions.

## 13. Subscriptions and credits

Plan names: Free, Starter, Creator, Professional, Business, Enterprise. Store versioned entitlements rather than scattered plan-name conditionals. Benefits cover quota, quality, duration, storage, concurrency, priority, watermark, seats and API access. Do not set prices until measured model costs and margin targets are available. Commercial use remains bounded by provider/asset licenses, not merely plan status.

Credits are integer units. Available = balance − reserved. Grants and charges have immutable external references. Reserve the maximum approved charge before enqueue; settle actual charge ≤ reservation and release the remainder. Refund with a compensating ledger entry. Define expiry, rollover, annual allotment cadence, failed-payment grace, cancellation and chargeback behavior before sale. Add grant-lot allocation before shipping expiring credits. Paid compute continues only while funded; per-workspace concurrency limits prevent reserve exhaustion.

## 14. Payment architecture

Use hosted checkout and customer portal to reduce card-data exposure. Map processor customer to workspace on the server. Verify webhook signature against raw body, deduplicate event IDs, durably store before acknowledging, and process asynchronously. Events can be duplicated or arrive out of order; reconcile current processor state before changing subscription entitlements. Credit grants are tied to settled invoice/payment records, not browser success redirects. Handle refunds/disputes with compensating accounting, entitlement changes and an operator queue. Tax, currencies and merchant availability are explicit launch decisions. PayPal uses a separate adapter after Stripe flows pass reconciliation testing.

## 15. Administration

Provide paginated users/workspaces, membership and session revocation, invoices, ledger with adjustment reasons, job attempts and reconciliation, provider health and disable switches, moderation queues and appeals, storage reconciliation and support tickets. Financial exports distinguish gross revenue, refunds, tax, provider costs and contribution margin. Audit privileged reads as well as mutations. No general-purpose SQL console or arbitrary provider URL field in the product UI.

## 16. Security and privacy

TLS at every ingress; WAF and per-account/IP limits; request schema/size limits; parameterized SQL; restrictive CSP; sanitization for displayed user text; signed asset access; encrypted secrets manager; least-privilege identities; backup encryption; dependency scanning; secret scanning; and reviewed migration procedures. Upload file extensions and MIME headers alone are insufficient validation. Prevent SSRF on imported assets and provider callbacks. Redact prompts, identity data and tokens from default telemetry.

Privacy design supports consent versions, purpose-bound processing, subprocessor inventory, regional processing choices, retention jobs, portability exports and verified deletion. Do not train on private uploads by default. Voice cloning needs specific consent and revocation flow. Obtain jurisdiction-specific legal review of age rules, privacy notices, international transfers and billing terms before launch; architecture alone does not establish compliance.

## 17. API structure

JSON `/api/v1`, resource IDs as UUIDs, cursor pagination and RFC-style problem responses with request IDs. OpenAPI-generated clients. Auth/session APIs are routed to identity/BFF; workspace context is validated server-side. Public and private endpoints have separate rate policies.

| Resources | Operations |
|---|---|
| /me, /me/sessions, /me/export, /me/deletion | profile, security, session revocation, privacy requests |
| /workspaces, /workspaces/{id}/members | membership and invitations |
| /projects, /projects/{id}/versions | CRUD, archive/restore, optimistic versions |
| /uploads, /uploads/{id}/complete, /assets | constrained upload sessions and library |
| /models, /quotes, /generations | capabilities, estimated cost, idempotent submission |
| /generations/{id}, /generations/{id}/cancel, /events | status, cancellation, authorized progress |
| /characters, /scenes, /storyboards, /timelines | versioned creative documents |
| /exports, /exports/{id}/license | render and license manifest |
| /billing/checkout, /billing/portal, /credits/ledger | commerce, server-calculated products |
| /webhooks/stripe, /webhooks/providers/{adapter} | signed machine callbacks |
| /shares, /publications, /comments, /notifications | collaboration and publication |
| /admin/* | separate role, MFA and audited policy |

Creation endpoints use `Idempotency-Key`, scoped to workspace + operation, with canonical payload hash. Reusing a key with different payload returns 409. Return 202 and generation resource for accepted asynchronous work. Use 401/403 for authentication/authorization, 409 for version conflicts, 422 for invalid options, 429 with Retry-After for rate limits, and a stable insufficient-credit error. Never expose raw provider errors or internal storage paths.

## 18. Deployment architecture

Environments: local, isolated staging and production, each with independent keys/storage/databases. CI performs domain tests, SQL integration tests, type checks, dependency/security checks and build; staging runs real provider smoke tests within a hard spend cap. Use immutable container releases, expand/contract database migrations, smoke checks, gradual traffic shifts and rollback. Database changes must remain compatible with the previous application release.

Deploy web/API separately from CPU render and provider workers; later GPU pools are independent. Connection pooling, queue depth and provider limits bound autoscaling. Monitor request errors/latency, queue age, stale leases, reserved credit age, provider spend, webhook delay, storage growth and moderation backlog. Run database/object restore and provider-outage exercises. Domain switch follows successful staging and verified TLS; this phase does not publish an unfinished service.

## 19. Development structure

```
apps/web/                  frontend integration boundary
apps/api/                  authenticated API integration boundary
apps/worker/               queue/provider/render integration boundary
packages/core/src/         framework-independent domain implementation
packages/core/test/        domain invariant tests
packages/database/migrations/ PostgreSQL migrations
packages/contracts/        future OpenAPI client and schemas
packages/ui/               future shared accessible components
infra/                     infrastructure decisions/runbooks
 docs/                     architecture, original brief, delivery status
```

Use npm workspaces initially, one dependency lockfile when integration dependencies are introduced, strict TypeScript at application boundaries, structured error codes and explicit repository interfaces. Do not invent placeholder implementations that report successful AI generation or payments.

## 20. UI component system

Tokens: neutral workspace surfaces, high-contrast primary action, restrained accent, typography and spacing scales, semantic danger/warning/success colors. Components: app shell, sidebar, workspace picker, project grid/table, prompt composer, recording/upload control, capability picker, quote panel, job card, asset viewer, timeline tracks, storyboard shot, character reference board, review comments, credit ledger and billing summary. All controls need keyboard focus, labels, loading, disabled, empty and error states. Use accessible primitives for dialogs/menus/tabs, reduced-motion support, readable timelines and caption controls. Localize messages, dates, numbers and layout direction; do not hardcode text inside rendering algorithms.

## 21. Development phases and gates

1. Foundation: identity, tenant isolation, projects, upload quarantine, storage, billing and credit ledger. Gate: cross-tenant and webhook replay tests plus backup restore.
2. AI: one image provider and one video provider, moderated inputs/results, voice transcription, quote/reserve/queue/settle. Gate: real job lifecycle, timeout reconciliation, cancellation races and cost cap tests.
3. Editor: saved timeline, proxy preview, audio, captions and FFmpeg export. Gate: deterministic export against reference fixtures and accessibility review.
4. Film: versioned screenplay, approved scenes, character packs and shot graph. Gate: partial re-render without recharging completed shots.
5. Teams/community: review links, permissions, publication, profiles, discovery and templates. Gate: revocation and moderation/appeal workflows.
6. Enterprise: scoped APIs, SSO, residency and dedicated capacity. Gate: load/security review and operations readiness.

## 22. MVP definition

A sellable first release combines phases 1 and a bounded phase 2: authenticated private workspace; projects/media; one real image workflow; one short-video workflow; editable transcription; asynchronous progress; secure downloads; one paid plan plus free allowance; billing portal; auditable credits; moderation and basic operator controls. Include operational support and data deletion. Exclude full film automation, advanced timeline, voice cloning, social feed and marketplace from initial launch. Foundation code alone is not the MVP.

## 23. Future versions

Add masks/outpainting, object removal, relighting, restoration, video interpolation/stabilization, consented talking avatars, multilingual dubbing, music/SFX, multi-scene films, professional editing, marketplace sales and enterprise APIs incrementally. Capability availability is explicit per model; unavailable modes must not appear to work. Marketplace introduces payouts, seller verification, tax and dispute obligations and needs its own launch review.

## 24. Scalability strategy

Begin single-region with multi-zone managed database, connection pooling, private object storage and horizontally scalable stateless API/workers. Cache public discovery and model metadata, not authorization decisions indefinitely. Scale worker groups by queue age and provider quotas. Isolate large exports from short generations. Add read replicas for proven read pressure; time-partition event tables; move analytical workloads to a warehouse. At multi-region scale assign workspace home regions and retain a single authoritative billing writer per workspace; do not introduce uncontrolled multi-master credit balances.

## 25. Cost control

Measure contribution margin per operation: revenue allocated to credits minus provider, rendering, storage, egress, payment and support costs. Quote conservatively using duration × resolution × output count and model revision. Enforce per-job, workspace and platform spend ceilings; concurrency and retry budgets; provider circuit breakers; low-balance alerts; orphan reservation reconciliation; thumbnail/proxy reuse; lifecycle cleanup; and explicit user approval for expensive re-renders. Set provider account hard caps where available. Cache only within permitted privacy/license boundaries. Free tier requires verified identity, rate limits and abuse monitoring. Do not promise unlimited generation.

## 26. Commercial licensing

Persist model/provider/version, applicable terms revision, input ownership attestation, stock/music licenses, consent records, generation timestamp and transformations in an export manifest. Show restrictions before purchase/export. A subscription cannot override third-party restrictions. Rights, copyright protection and exclusivity vary by provider, asset and jurisdiction; commercial plans must not imply guaranteed copyright or risk-free likeness use. Legal review and provider agreements are launch dependencies. Watermark and provenance settings are recorded per export; provenance metadata is an integrity signal, not proof of factual truth.

## 27. Moderation and safety

Moderate prompts, uploads, outputs and public publications. Quarantine uncertain content; block generation until required checks succeed. Policies address illegal material, sexual exploitation of minors, non-consensual intimate imagery, identity misuse, unauthorized voice cloning and abusive impersonation. Store decision reasons and policy versions with restricted evidence access, appeal and human review. Reports create traceable cases; deletion/unpublishing invalidates delivery caches. Provider safety controls supplement platform checks. Emergency disable switches stop a model, operation or workspace without modifying source.

## Technical references checked

- Next.js self-hosting: https://nextjs.org/docs/app/guides/self-hosting
- PostgreSQL row security: https://www.postgresql.org/docs/17/ddl-rowsecurity.html
- BullMQ idempotent jobs: https://docs.bullmq.io/patterns/idempotent-jobs
- Stripe webhook verification/reconciliation: https://docs.stripe.com/webhooks
- S3 presigned object access: https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html

These support specific implementation decisions; cost estimates, provider licensing and legal requirements still need launch-specific verification.
