Skip to content

Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.

20.9 KB
Raw Blame
// v0.9.3: rust-free Prisma client.
//
// The classic prisma-client-js generator ships a native Rust query
// engine binary — fine on Vercel/self-hosted Node, impossible on edge
// runtimes like Cloudflare Workers. The new `prisma-client` generator
// (GA path toward Prisma 7) emits the TypeScript/WASM client that runs
// anywhere JS runs and talks to Postgres through a real `pg` driver
// (src/lib/db.ts wires @prisma/adapter-pg). Rust-free is the default
// since 6.16 — no preview flags needed.
//
// The client is generated to src/generated/prisma (gitignored,
// regenerated by postinstall / `npm run db:generate`) — imports are
// `@/generated/prisma` in app code and relative paths in scripts.
// (prisma-client-js was tried first: even with the queryCompiler flag
// it silently generates the library-engine client — engineWasm stays
// undefined. prisma-client-es needs an extra package; `prisma-client`
// is built into the CLI, and engineType="client" flips it to the
// TypeScript/WASM query compiler.)
generator client {
  provider   = "prisma-client"
  output     = "../src/generated/prisma"
  engineType = "client"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

// ── v0.9.0: accounts ─────────────────────────────────────────
// Username/password accounts — deliberately self-contained (no email,
// no OAuth, no external provider) so self-hosting stays free forever.
// Passwords are scrypt hashes from node:crypto (see src/lib/auth/passwords.ts).
model User {
  id           String           @id @default(cuid())
  // lowercase, 3–32 chars, [a-z0-9_-] (enforced in src/lib/auth/validate.ts)
  username     String           @unique
  passwordHash String
  // v0.16 (A1): admin console access. "user" | "admin". Effective admin ALSO
  // honours the CANVIX_ADMIN_USERS env bootstrap (src/lib/admin/guard.ts) so
  // the first admin exists without CLI surgery; this column is what the
  // console manages afterwards.
  role         String           @default("user")
  createdAt    DateTime         @default(now())
  designs      Design[]         @relation("DesignOwner")
  folders      Folder[]         @relation("FolderOwner")
  sessions     Session[]
  aiProviders  UserAIProvider[]
  apiKeys      ApiKey[]
}

// ── v0.23: BYOK — per-user AI providers (profile page) ────────
// A signed-in user can save their own AI credentials and use them
// for every provider-backed feature, instead of the operator's
// instance-wide slots. Mirrors the admin multi-provider shape
// (baseUrl + apiKey + optional model per slot) but scoped to one
// user row. Keys are write-only through the API: reads return the
// same mask the admin console shows, never the stored key.
model UserAIProvider {
  id        String   @id @default(cuid())
  userId    String
  user      User     @relation(fields: [userId], references: [id], onDelete: Cascade)
  // 3–60 chars — shown in the profile list and usage accounting
  label     String
  // http(s) URL, no embedded credentials (validated like the admin table)
  baseUrl   String
  // write-only credential — masked on every read path
  apiKey    String
  // capability slots this provider answers ('text','vision','image','imageEdit','video')
  slots     String   @default("text")
  // model id per slot, JSON: {"text":"glm-4.7",…} (validated against MODEL_RE)
  models    Json     @default("{}")
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  @@index([userId])
}

// Opaque server-side sessions. The cookie carries the raw token; the row
// id is sha256(token) — a DB leak never yields usable tokens.
model Session {
  id        String   @id // sha256(token) hex
  userId    String
  user      User     @relation(fields: [userId], references: [id], onDelete: Cascade)
  createdAt DateTime @default(now())
  expiresAt DateTime

  @@index([userId])
  @@index([expiresAt])
}

// ── v0.24 (Wave 6 core): scoped API keys — the REST rail ───────
// A user-created bearer key for the /api/v1 REST surface. Storage
// mirrors Session: the row id is sha256(raw token), so a DB leak
// never yields usable keys; the raw value is shown exactly once at
// creation. Scopes are a CSV subset of API_KEY_SCOPES
// (src/lib/auth/api-key.ts); revocation is a timestamp, not a
// delete, so the 401 reason can say "revoked" and the audit trail
// (lastUsedAt) survives.
model ApiKey {
  id         String    @id // sha256(token) hex
  userId     String
  user       User      @relation(fields: [userId], references: [id], onDelete: Cascade)
  label      String
  // CSV of API_KEY_SCOPES, or 'all' (sugar for every current scope)
  scopes     String    @default("designs:read")
  createdAt  DateTime  @default(now())
  lastUsedAt DateTime?
  expiresAt  DateTime?
  revokedAt  DateTime?

  @@index([userId])
}

// A user design / project — the core artifact of Canvix.
model Design {
  id         String            @id @default(cuid())
  name       String            @default("Untitled design")
  width      Int               @default(1080)
  height     Int               @default(1080)
  // Structured document: { pages: PageData[], ... } — stored as native jsonb
  pages      Json              @default("[]")
  thumbnail  String? // small dataURL preview
  source     String            @default("blank") // blank | template:<id> | duplicate:<id> | resize:<id>
  // v0.9: owning account. null = link-accessible design (pre-accounts
  // behaviour — anonymous editing keeps working for legacy + shared links).
  ownerId    String?
  owner      User?             @relation("DesignOwner", fields: [ownerId], references: [id], onDelete: SetNull)
  // v0.9.1: anonymous attribution — sha256 of the canvix_anon cookie that
  // was set when an anonymous browser created this design. adopt-all only
  // claims rows whose anonKey matches the caller's cookie, so one account
  // can never sweep up another person's anonymous work. null = legacy
  // design created before attribution existed (claimable only via the
  // explicit per-design adopt endpoint).
  anonKey    String?
  // v0.14 (D6): dashboard organization — the folder this design is
  // filed under. null = "All designs" (the root; unchanged pre-v0.14
  // behaviour). Deleting a folder unfiles its designs (SetNull) — a
  // folder delete never destroys work.
  folderId   String?
  folder     Folder?           @relation("DesignFolder", fields: [folderId], references: [id], onDelete: SetNull)
  // soft delete (dashboard Trash) — null = live design
  deletedAt  DateTime?
  versions   DesignVersion[]
  // v0.32 (Unified Canvix AI): the brief contract an autonomous
  // generation was verified against, persisted on the applied design —
  // chat-agent refinements of the SAME design merge it into their run
  // brief so verified requirements survive refinement
  provenance DesignProvenance? @relation("DesignProvenance")
  // v0.32.4: per-design agent run ledger — compact records of what
  // each Canvix AI run did (mode, request, actions, outcome), fed
  // back into the next run's context. The canvas state stays the
  // authority; this explains how it got there.
  agentRuns  DesignAgentRun[]  @relation("DesignAgentRuns")
  createdAt  DateTime          @default(now())
  updatedAt  DateTime          @updatedAt

  @@index([ownerId])
  @@index([anonKey])
  @@index([folderId])
}

// ── v0.32 (Unified Canvix AI): design provenance ─────────────
// One row per design (unique). `brief` is the normalized DesignBrief
// JSON (src/lib/agent/brief.ts) — the exact texts/colors/features the
// autonomous run was verified against; `prompt` and `outcome` keep the
// audit trail of the run that produced it. Cascade: deleting a design
// deletes its provenance (it is meaningless without the design).
model DesignProvenance {
  id         String    @id @default(cuid())
  designId   String    @unique
  design     Design    @relation("DesignProvenance", fields: [designId], references: [id], onDelete: Cascade)
  prompt     String    @default("")
  brief      Json      @default("{}")
  outcome    String    @default("passed")
  // v0.32.1 (review P1): server-side verification state. The design
  // save re-validates the stored brief against the SAVED pages and
  // flips this flag — stored provenance carries proof, not a client's
  // claim. verifiedAt binds the proof to the document version it was
  // checked against.
  verified   Boolean   @default(false)
  verifiedAt DateTime?
  createdAt  DateTime  @default(now())
  updatedAt  DateTime  @updatedAt
}

// ── v0.14 (D6): dashboard folders ───────────────────────────
// A named group of the caller's designs. Attribution mirrors Design/
// Media exactly: signed-in → ownerId, anonymous → anonKey (the
// canvix_anon cookie hash). Folders are PRIVATE organization — the
// list endpoint only ever returns the caller's own rows — while the
// designs inside keep their own visibility (the anonymous commons
// stays shared). claim-on-login moves anon folders into the account
// (src/lib/auth/claim-folders.ts), so organization follows the user
// across devices just like uploads (D1).
model Folder {
  id        String   @id @default(cuid())
  name      String
  ownerId   String?
  owner     User?    @relation("FolderOwner", fields: [ownerId], references: [id], onDelete: Cascade)
  anonKey   String?
  designs   Design[] @relation("DesignFolder")
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  @@index([ownerId])
  @@index([anonKey])
}

// Server-side version snapshots for a design (Canva "Version history").
model DesignVersion {
  id        String   @id @default(cuid())
  designId  String
  design    Design   @relation(fields: [designId], references: [id], onDelete: Cascade)
  label     String   @default("Version")
  name      String
  width     Int
  height    Int
  pages     Json
  createdAt DateTime @default(now())

  @@index([designId, createdAt(sort: Desc)])
}

// Built-in starter templates rendered in the dashboard & editor.
model Template {
  id        String   @id @default(cuid())
  slug      String   @unique
  name      String
  category  String // social | presentation | print | logo | thumbnail
  width     Int
  height    Int
  pages     Json // structured document — same shape as Design.pages
  accent    String   @default("#00C4CC") // card decoration
  // v0.17 (Wave 2): smart-template field declarations (null = plain
  // template). [{ key, label, example }] — see lib/templates/fields.ts
  fields    Json?
  createdAt DateTime @default(now())
}

// ── v0.5.0: collaboration, comments & AI infrastructure ──────

// Append-only operation log — the replication stream for live collaboration.
// `id` is a global monotonic sequence: clients track their last seen seq and
// replay from any offset after reconnecting (SSE `?since=<seq>`).
model DesignEvent {
  id        BigInt   @id @default(autoincrement())
  designId  String
  actorId   String // participant id (client-generated)
  kind      String // op name — see research/COLLABORATION-ARCHITECTURE.md §3
  payload   Json
  // v0.10.1: the client's dedupe key for this op. Unique per design so a
  // retried flush (network drop / function timeout mid-batch) is a no-op
  // instead of a duplicate — at-least-once delivery becomes exactly-once.
  // Nullable: rows written before v0.10.1 have none (Postgres unique
  // indexes ignore NULLs, so legacy rows never conflict).
  eventId   String?
  createdAt DateTime @default(now())

  @@unique([designId, eventId])
  @@index([designId, id(sort: Desc)])
}

// Live presence per participant per design (heartbeat-based).
// v0.10.1: the primary key is (designId, id) — participant identity is
// per-BROWSER (src/lib/collab/identity.ts) and one browser can edit two
// designs at once (two tabs). The old single-column PK on id made presence
// exclusive to one design: every heartbeat for a second design failed with
// P2002 (production incident 2026-10-29).
model Presence {
  id       String // = participant id
  designId String
  name     String
  color    String
  cursor   Json? // { page: number, x: number, y: number, selection?: string[] }
  lastSeen DateTime @default(now()) @updatedAt

  @@id([designId, id])
  @@index([designId, lastSeen])
}

// Canvas-anchored comment threads (author identity is the local participant).
model Comment {
  id          String   @id @default(cuid())
  designId    String
  pageId      String
  x           Float // anchor in page coordinates (fraction of page size, 0..1)
  y           Float
  elementId   String? // optional element anchor — pin follows the element
  authorId    String
  authorName  String
  authorColor String
  body        String
  parentId    String? // reply threading
  resolved    Boolean  @default(false)
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt

  @@index([designId, createdAt])
  @@index([designId, resolved])
}

// ── v0.11: media store (audio/video uploads) ─────────────────
// A/V files are far too large for the dataURL-in-element pattern images
// use (multi-MB per autosave). They live here as bytea; elements
// reference them by id (`/api/media/<id>`). Chunks are appended with a
// raw `bytes || chunk` UPDATE (offset-guarded) because serverless body
// limits force chunked uploads. Access mirrors designs: link-accessible
// once the id is known; ownership columns exist for future GC/quota.
model Media {
  id          String    @id @default(cuid())
  mime        String
  size        Int
  bytes       Bytes
  ownerId     String?
  anonKey     String?
  // set by finalize — GET 404s until the upload is complete
  finalizedAt DateTime?
  createdAt   DateTime  @default(now())

  // v0.14 (D1): the persistent uploads library
  contentHash   String? // sha256 of the finalized bytes — same-owner dedupe
  name          String? // original filename, surfaced in the library
  keepInLibrary Boolean @default(false) // library membership; GC-protected

  @@index([ownerId])
  @@index([anonKey])
  @@index([finalizedAt, createdAt])
  @@index([contentHash])
  @@index([ownerId, keepInLibrary])
}

// Provider accounting + request telemetry for AI routes (v0.16.3 A3
// extends it into the admin Logs view). One row per AI request through
// withProvider, every outcome recorded — success, provider failure
// (with the scrubbed reason), no-provider, feature-disabled, rate-
// limited and rejected. `error` carries a short, key-scrubbed
// provider message; credentials never reach this table.
model AIUsage {
  id         String   @id @default(cuid())
  feature    String // write | image | image-edit | translate | assistant | magic-layers | search
  provider   String // multi-table label | db | env | file
  ok         Boolean  @default(true)
  model      String? // model id the slot requested (null = provider default)
  status     Int? // outcome: 200-299 ok · 403/429/503 guard exits · provider HTTP code on failure
  durationMs Int? // provider round-trip
  error      String? // scrubbed, capped failure reason
  createdAt  DateTime @default(now())

  @@index([createdAt])
}

// ── v0.13: plugin system (research/PLUGIN-SYSTEM.md §4.2) ────
// A plugin install is a per-user snapshot of a third-party plugin's
// files, pinned at install time (sha256 per file). After install the
// instance is fully offline — the runtime never fetches anything.
// Updates are explicit reinstalls; `enabled` is the user's kill switch
// and CANVIX_PLUGINS=0 the instance-wide one. Elements created by a
// plugin survive uninstall (they are plain elements in design jsonb).
model PluginInstall {
  id        String        @id @default(cuid())
  userId    String
  pluginId  String
  version   String
  manifest  Json
  enabled   Boolean       @default(true)
  assets    PluginAsset[]
  createdAt DateTime      @default(now())
  updatedAt DateTime      @updatedAt

  @@unique([userId, pluginId])
  @@index([userId])
}

model PluginAsset {
  id        String        @id @default(cuid())
  installId String
  install   PluginInstall @relation(fields: [installId], references: [id], onDelete: Cascade)
  path      String
  mime      String
  bytes     Bytes
  sha256    String

  @@unique([installId, path])
}

// ── v0.16 (A1): admin console ─────────────────────────────────────────────────

// Instance-wide configuration, written from /admin (AI provider,
// models, feature flags, app settings). Small key→JSON rows; reads go
// through the typed accessor + short-TTL cache in src/lib/admin/config.ts.
// Nothing user-scoped ever lives here — operator config only.
model AppConfig {
  key       String   @id
  value     Json
  updatedAt DateTime @updatedAt
}

// Per-day aggregate API traffic counters — the "see all the traffic"
// side of the console. Written fire-and-forget by the withLogging wrapper
// every API route already passes through (src/lib/observability.ts):
// COUNTS ONLY — never ids, never IPs, never query strings. One row per
// (UTC day, route, method, status); cardinality is bounded by the route
// table × days × status codes. Rows older than 90 days are swept lazily.
// CANVIX_TRAFFIC=0 opts an instance out entirely.
model TrafficStat {
  id     BigInt   @id @default(autoincrement())
  day    DateTime // UTC midnight
  route  String // logical route name, e.g. "GET /api/designs"
  method String
  status Int
  hits   Int      @default(0)

  @@unique([day, route, method, status])
  @@index([day])
}

// Daily active actors for the DAU chart: one row per (UTC day, actor),
// actor = userId for accounts or the already-hashed anonymous cookie key
// for anonymous browsers. First-party, admin-visible only; recorded from
// the two surfaces that mean "someone used Canvix today" (design list /
// editor open), so it adds no extra auth resolution anywhere.
model DailyActive {
  id    BigInt   @id @default(autoincrement())
  day   DateTime
  actor String

  @@unique([day, actor])
}

// ── v0.17 (Wave 2): asset & template ecosystem ───────────────

// User-saved templates ("Save as template" in the editor). Attribution
// mirrors designs: owning account OR the anon cookie that created it —
// adopt-all claims rows the same way designs do. Pages use the same
// structured-document shape as Design.pages / Template.pages.
model UserTemplate {
  id        String   @id @default(cuid())
  name      String
  category  String // social | presentation | print | logo | thumbnail | doc
  width     Int
  height    Int
  pages     Json
  accent    String   @default("#00C4CC")
  ownerId   String?
  anonKey   String?
  createdAt DateTime @default(now())

  @@index([ownerId])
  @@index([anonKey])
}

// Server-side brand kits (v0.17 Wave 2): colours, palettes, fonts and
// logos travel with the account (or anon attribution) instead of living
// only in localStorage. One row per kit; the client keeps the active
// kit id locally.
model BrandKitRecord {
  id          String   @id @default(cuid())
  name        String   @default("My brand")
  colors      Json // string[]
  palettes    Json // string[][]
  headingFont String   @default("Montserrat")
  bodyFont    String   @default("Inter")
  logos       Json // data URLs (small, ≤ 8 entries)
  ownerId     String?
  anonKey     String?
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt

  @@index([ownerId])
  @@index([anonKey])
}

// ── v0.32.4: per-design agent run ledger ──────────────────────
// One row per Canvix AI run on a design (create/edit/improve/
// review). Compact by design: mode + request + action count + the
// run's own summary (trimmed). The route reads the last few rows
// into the next run's system prompt as "YOUR RECENT RUNS IN THIS
// DESIGN" — grounded memory of what the agent itself did, distinct
// from the chat history (what the user said). findings keeps the
// disclosed audit/vision residue so a follow-up can target it.
model DesignAgentRun {
  id        String   @id @default(cuid())
  designId  String
  design    Design   @relation("DesignAgentRuns", fields: [designId], references: [id], onDelete: Cascade)
  createdAt DateTime @default(now())
  mode      String // create | edit | improve | review | plan
  request   String   @db.VarChar(240)
  summary   String   @db.VarChar(600)
  toolCalls Int      @default(0)
  findings  String?  @db.VarChar(1200)
  /// v0.32.7 · PERSISTENT EXECUTION: running | interrupted |
  /// completed | stopped — an interrupted run (429/502/network,
  /// mid-flight) is recoverable; the next message COMPLETES it.
  status String?
  /// v0.32.7 · the run's live state, persisted as it happens:
  /// intent, request, brief, plan bands, applied tool calls,
  /// pending items, verification milestones (RunStateSnapshot).
  /// Best-effort — the canvas stays the authority.
  state Json?

  @@index([designId, createdAt])
}