Hosted API
Endpoints, authentication, adapters and their environment variables, limits, errors, migrations, scheduled work and webhooks of the Parity hosted backend.
The hosted backend lives in apps/web (Next.js route handlers under src/app/api, server modules under src/server). It stores reports uploaded from CI, serves them to the workspace UI, and records review decisions. It never calls a customer's API: environments are metadata only.
All responses are JSON with Cache-Control: no-store. Errors always have the shape
{ "error": { "code": "not_found", "message": "Not found" } }with extra fields on some codes (required_plan, capability, retry_after, issues, reason).
#Platform
| Concern | Service | Local substitute |
|---|---|---|
| Identity and organisations | Clerk (Clerk Organizations), shared by all x1991 products | signed dev identities |
| Data | Supabase PostgreSQL | PGlite, in process |
| Artifacts | Cloudflare R2 (S3 API) | table parity.blobs |
| Hosting | Cloudflare Workers via @opennextjs/cloudflare | next dev / next start |
Resend through @x1991/email | local outbox | |
| Billing | Stripe | local provider |
| Analytics | PostHog | console / none |
Identity, the organisation model and billing infrastructure are shared across products; product data, permissions and entitlements are Parity's own.
A Parity workspace is a Clerk organisation. Parity stores no passwords and has no invitation flow: people are invited, removed and given their Clerk role in Clerk.
#Authentication
#Users (browser)
In clerk mode the session is Clerk's. Every /api/orgs/:org/... route requires that :org — a Clerk organisation id or its slug — is the caller's active organisation:
| Situation | Result |
|---|---|
| Not signed in | 401 unauthorized |
| Signed in, no active organisation | 409 organization_required |
:org is not the active organisation (whether or not it exists) | 404 not_found |
| Resource id belongs to another organisation | 404 not_found |
| Parity role too low | 403 forbidden |
| Plan lacks the capability | 402 plan_required with required_plan |
Non-GET requests authenticated by a cookie must carry a same-origin Origin header (or Sec-Fetch-Site: same-origin); otherwise 403 csrf_failed. PARITY_APP_URL pins the accepted origin.
#Parity roles
Roles are product-specific: admin, member, viewer.
- Default mapping from the Clerk role:
org:admin→admin, anything else →member. - An organisation admin can override one person's Parity role (for example to
viewer) without touching Clerk or any other product. Overrides live inparity.member_roles, need the Team plan to edit, and cannot be applied to yourself.
| viewer | member | admin | |
|---|---|---|---|
| Read projects, runs, scenarios, reviews, members | yes | yes | yes |
| Subscribe yourself to notifications (Team) | yes | yes | yes |
| Classify differences | no | Team plan | Pro and Team |
| Projects, tokens, run deletion, settings, billing, audit log, role overrides | no | no | yes |
#Local identity mode (development and tests only)
PARITY_AUTH=local (the default when CLERK_SECRET_KEY is not set) replaces Clerk with fake identities. It is refused when NODE_ENV=production. POST /api/dev/session sets a signed, HttpOnly cookie naming a fake user, organisation and Clerk-style role; there are no passwords. In clerk mode the /api/dev/* endpoints return 404.
curl -c jar -H 'Origin: http://localhost:3000' -H 'Content-Type: application/json' \
-d '{"user":"admin"}' http://localhost:3000/api/dev/sessionSeeded identities: admin, member, viewer (organisation org_dev_acme) and outsider (org_dev_globex). Any other fake id works too: {"user":"user_x","org":"org_y","role":"org:admin"}.
#CI (ingestion)
POST /api/v1/ingest authenticates only by a project token: Authorization: Bearer pty_…. Cookies are ignored. A token is shown once at creation, stored as a SHA-256 hash plus a display prefix, has the scope ingest, and is valid only for its own project.
#Machines
Webhooks authenticate by the provider's signature over the raw body. The internal endpoints (/api/internal/cron, /api/internal/queue) accept Authorization: Bearer $CRON_SECRET, or — on Cloudflare Workers — a random token that the Worker entry creates per isolate and that never leaves it, so the Worker's own cron ticks and queue batches need no configured secret. With neither, they answer 503.
#Endpoints
:org = active organisation id or slug. :project = project id or slug within the organisation.
#Session
| Method | Path | Auth | Purpose |
|---|---|---|---|
| GET | /api/auth/me | optional session | User (or null), auth mode, active organisation with Parity role, plan and entitlements, feature flags (billing provider, public analytics key) |
| POST | /api/dev/session | local mode | Sign in as a fake identity { user, org?, role?, email?, name?, org_slug?, org_name? } |
| DELETE | /api/dev/session | local mode | Sign out |
| GET | /api/dev/identities | local mode | Seeded identities |
| GET | /api/health | none | Liveness and database reachability |
#Organisation
| Method | Path | Role | Purpose |
|---|---|---|---|
| GET | /api/orgs/:org | viewer | Organisation, role, plan, entitlements, default policy |
| PATCH | /api/orgs/:org | admin | { default_policy } for new projects (Team; null clears) |
| GET | /api/orgs/:org/members | viewer | Known members with provider role, default and effective Parity role |
| PUT | /api/orgs/:org/members/:user/role | admin, Team | Override a person's Parity role { role } |
| DELETE | /api/orgs/:org/members/:user/role | admin, Team | Remove the override |
| GET | /api/orgs/:org/audit | admin, Team | Audit log, ?cursor=&limit= |
| GET | /api/orgs/:org/usage | viewer | Current usage against the plan's quotas (see Quotas) |
"Known members" are people who have signed in with the organisation active or arrived through a Clerk webhook. There is no endpoint to add, invite or remove a member.
#Projects, tokens, notifications
| Method | Path | Role | Purpose |
|---|---|---|---|
| GET | /api/orgs/:org/projects | viewer | Projects with run count, latest run summary and unreviewed-change count |
| POST | /api/orgs/:org/projects | admin | Create { name, slug?, repository_url?, description?, environments?, policy?, retention_days? } |
| GET | /api/orgs/:org/projects/:project | viewer | One project |
| PATCH | /api/orgs/:org/projects/:project | admin | Update |
| DELETE | /api/orgs/:org/projects/:project | admin | Delete with tokens, runs, reviews and artifacts |
| GET | /api/orgs/:org/projects/:project/tokens | admin | List tokens (no secrets) |
| POST | /api/orgs/:org/projects/:project/tokens | admin | Create { name } → { token, secret }, secret shown once |
| DELETE | /api/orgs/:org/projects/:project/tokens/:token | admin | Revoke |
| GET | /api/orgs/:org/projects/:project/runs | viewer | Runs, newest first, ?cursor=&limit=&verdict=pass|fail&pr=<n> |
| GET | /api/orgs/:org/projects/:project/audit | admin, Team | Audit log of the project |
| GET | /api/orgs/:org/projects/:project/notifications | viewer | Your own run_failed subscription |
| PUT | /api/orgs/:org/projects/:project/notifications | viewer, Team | Subscribe yourself |
| DELETE | /api/orgs/:org/projects/:project/notifications | viewer | Unsubscribe yourself |
#Runs, scenarios, review
| Method | Path | Role | Purpose |
|---|---|---|---|
| GET | /api/orgs/:org/runs/:run | viewer | Run, policy, comparison settings and every light scenario row with its review rollup (one query, no payloads) |
| DELETE | /api/orgs/:org/runs/:run | admin | Delete the run and its artifacts |
| GET | /api/orgs/:org/runs/:run/scenarios/:scenario | viewer | Full scenario result (one artifact chunk is decrypted), per-difference review state and prior hints |
| GET | /api/orgs/:org/runs/:run/reviews | viewer | Classifications that apply to this run, and the rollup |
| PUT | /api/orgs/:org/runs/:run/reviews | plan-dependent | Classify one difference { scenario_id, difference_id, classification, note? } |
| PUT | /api/orgs/:org/runs/:run/reviews/bulk | plan-dependent | { items: [...] }, up to 1,000, all or nothing |
:scenario is the hosted row id (scn_…) from the run detail; scenario_id in review bodies is the scenario id from the report.
#Billing
| Method | Path | Role | Purpose |
|---|---|---|---|
| GET | /api/orgs/:org/billing | admin | Provider, plan, seats, period, plans with entitlements |
| POST | /api/orgs/:org/billing/checkout | admin | { plan: "pro"|"team", seats?, return_path? } → { url } |
| POST | /api/orgs/:org/billing/portal | admin | { return_path? } → { url } |
| POST | /api/orgs/:org/billing/dev-plan | admin, local provider | { plan, seats? }, instant |
#Machine endpoints
| Method | Path | Auth | Purpose |
|---|---|---|---|
| POST | /api/v1/ingest | project token | Upload a parity.report/v1 document |
| POST | /api/stripe/webhook | Stripe-Signature | Subscription state |
| POST | /api/clerk/webhook | Svix signature (CLERK_WEBHOOK_SIGNING_SECRET) | Mirror of users, organisations, memberships |
| POST | /api/resend/webhook | Svix signature (RESEND_WEBHOOK_SECRET) | Email delivery status |
| POST | /api/internal/cron | isolate token or Bearer $CRON_SECRET | Send due email, purge expired data |
| POST | /api/internal/queue | isolate token or Bearer $CRON_SECRET | Queue batches forwarded by the Worker's queue handler: { queue, messages: [{ id, attempts, body }] } → { decisions: [{ id, action: "ack" | "retry", delaySeconds? }] } |
| GET, POST | /api/notifications/unsubscribe?s=&t= | signed link | GET shows a confirmation form, POST unsubscribes (RFC 8058 one-click) |
The typed client for all user endpoints is apps/web/src/lib/api-client.ts; request and response types are in apps/web/src/lib/api-types.ts.
#Ingestion
curl -X POST "$PARITY_URL/api/v1/ingest" \
-H "Authorization: Bearer $PARITY_TOKEN" -H 'Content-Type: application/json' \
--data-binary @parity-report.jsonResponse: 201 { "run": { "id", "url" }, "duplicate": false }.
- Idempotent on
(project, run.id), decided by a unique constraint. The same report again →200withduplicate: true(key order and whitespace do not matter). A different body under the same run id →409 run_conflict. Concurrent uploads of one report create one run. - Every string in a report is treated as untrusted. Sensitive headers (
authorization,proxy-authorization,cookie,set-cookie,x-api-key,x-auth-token) are redacted again on the server, and credentials in URLs are stripped. - If artifact storage is unavailable the upload fails with
503 storage_unavailableand nothing is stored; retry. - On the Free plan only the organisation's first project ingests (
402 plan_required). - Quotas are checked twice: before the body is read (an exhausted quota costs almost nothing to refuse — this also applies to a re-upload of a report that is already stored) and again, authoritatively, inside the transaction that stores the run.
The order of work is: kill switch → token → rate limit → quota pre-check → read and parse the body → validate the report head and hash the report → duplicate check → validate, sanitise, serialise, compress and encrypt the scenarios one at a time → write the chunks to the blob store → one database transaction (run, scenario rows, differences, audit entry, outbox rows, quota counters). Each scenario is serialised exactly once and there is never a second full copy of the report in memory.
#Limits
| Limit | Default | Variable | Over the limit |
|---|---|---|---|
| Request body | 8 MiB, enforced while streaming; configurable up to 20 MiB | PARITY_INGEST_MAX_BODY_BYTES | 413 payload_too_large |
| Scenarios per report | 10,000 | PARITY_INGEST_MAX_SCENARIOS | 413 |
| One scenario | 1 MiB (at most 8 MiB) | PARITY_INGEST_MAX_SCENARIO_BYTES | bodies stripped, scenario marked truncated |
| Uploads per token | 60 per minute | PARITY_INGEST_RATE_PER_MIN, or the INGEST_RATE_LIMITER binding | 429 rate_limited with Retry-After |
| Failed token attempts per address | 30 per minute | the AUTH_RATE_LIMITER binding | 429 rate_limited |
| Other JSON bodies | 256 KB | PARITY_JSON_MAX_BODY_BYTES | 413 |
| Page size | 50, at most 200 | — | 400 |
The body limit is the one large runs meet first. A report with small JSON responses is about 1 KB per scenario, so 8 MiB holds roughly 7,000 scenarios, fewer with large bodies; the 10,000-scenario cap only applies to reports that are still under the size limit. An oversized upload is refused with 413 and the CLI says so; the local report is unaffected. Uploading a large run in parts is not supported yet.
The default body limit was 20 MiB and is now 8 MiB: an 8 MiB report costs about 120 ms of CPU and about 57 MB of transient memory to ingest, a 20 MiB report about 335 ms and about 90 MB, against an isolate limit of 128 MB on Cloudflare Workers. Raise it (up to 20 MiB, the hard ceiling) only on a host with more memory, or accept that the largest reports run close to the limit.
Rate limiting has two implementations behind one function (src/server/adapters/ratelimit). On Cloudflare Workers with the rate-limit bindings declared in wrangler.jsonc, the Workers Rate Limiting API decides; its budget and window are set in that file (simple.limit, simple.period), it is shared by all isolates in a Cloudflare location, and it is approximate by design. Everywhere else an in-memory token bucket decides, per process. PARITY_INGEST_RATE_PER_MIN=0 disables the per-token limit in both. Neither is a quota.
#Quotas and spending safeguards
Hard limits are counted in PostgreSQL (parity.usage_counters, parity.org_usage — primary-key lookups only, no count(*) over runs or scenarios) and enforced on the server.
Per organisation, by plan (src/server/entitlements.ts, PLAN_QUOTAS). Every value can be overridden per deployment with PARITY_QUOTA_<PLAN>_<NAME>, for example PARITY_QUOTA_FREE_RUNS_PER_DAY=100 or PARITY_QUOTA_TEAM_STORAGE_BYTES=unlimited.
Quota (<NAME>) | Free | Pro | Team | Window |
|---|---|---|---|---|
RUNS_PER_DAY — reports accepted | 25 | 300 | 1,000 | UTC day |
RUNS_PER_MONTH — reports accepted | 300 | 5,000 | 20,000 | UTC month |
STORAGE_BYTES — encrypted artifact bytes stored | 250 MB | 5 GB | 25 GB | — |
SCENARIOS_STORED — scenario rows stored | 50,000 | 2,000,000 | 10,000,000 | — |
TOKENS_PER_PROJECT — active tokens | 2 | 10 | 25 | — |
EMAILS_PER_DAY — notification emails sent | 10 | 50 | 200 | UTC day |
Projects per organisation (Free: 1) and retention (Free: 7 days; Pro and Team: 90 by default, at most 365) are plan limits too; see Plans.
Whole deployment, last resort.
| Safeguard | Default | Variable | Effect |
|---|---|---|---|
| Kill switch | off | PARITY_INGEST_DISABLED=1 | every upload → 503 ingest_disabled, before any token or body is looked at |
| Daily ingest cap | 5,000 runs per UTC day | PARITY_GLOBAL_INGEST_PER_DAY (unlimited to remove) | 503 quota_exceeded, scope: "deployment" |
| Daily email cap | 90 emails per UTC day | PARITY_GLOBAL_EMAILS_PER_DAY | a circuit breaker: remaining rows stay queued, a log line and an audit entry are written, sending resumes when the window turns or the cap is raised |
| Analytics events per request | 5 | PARITY_ANALYTICS_MAX_EVENTS_PER_REQUEST | further events in that request are dropped (analytics is best effort) |
A refusal is always this shape. Organisation quotas are HTTP 402 (a higher plan raises them); deployment-wide caps are 503. Retry-After is set when the quota resets with time.
{ "error": { "code": "quota_exceeded", "message": "This organisation has reached the daily limit of 25 runs. It resets at 2026-11-29T00:00:00.000Z.",
"quota": "runs_per_day", "limit": 25, "used": 25, "resets_at": "2026-11-29T00:00:00.000Z",
"scope": "organization", "current_plan": "free" } }quota is one of runs_per_day, runs_per_month, storage_bytes, scenarios_stored, tokens_per_project, emails_per_day, global_ingest_per_day, global_emails_per_day. resets_at is null for quotas that do not reset with time.
- Duplicates do not count: only a run that is actually stored takes a unit. The counters are reserved in the same transaction as the run, so concurrent uploads cannot overshoot.
- Stored bytes and stored scenarios are kept exact by triggers on
parity.runs, so deleting a run or a project, the retention purge and the purge of a deleted organisation all give the space back. Scenarios are counted by the server, not taken from the report's summary. - Email quotas are applied when an email is about to be handed to the provider. A held row keeps status
queued, spends no attempt, and records why inlast_error; it is never dropped. - The first refusal of each quota per organisation per UTC day is written to the audit log (
quota.exceeded;safeguard.triggeredfor deployment-wide caps) and logged. Further refusals that day only increase a counter, so a retrying client cannot fill the audit log.
GET /api/orgs/:org/usage (any member) returns the current numbers for the UI:
{ "plan": "team", "ingest_enabled": true,
"runs_per_day": { "used": 12, "limit": 1000, "resets_at": "2026-11-29T00:00:00.000Z" },
"runs_per_month": { "used": 340, "limit": 20000, "resets_at": "2026-12-01T00:00:00.000Z" },
"storage_bytes": { "used": 48211934, "limit": 26843545600, "resets_at": null },
"scenarios_stored": { "used": 30260, "limit": 10000000, "resets_at": null },
"emails_per_day": { "used": 3, "limit": 200, "resets_at": "2026-11-29T00:00:00.000Z" },
"projects": { "used": 2, "limit": null, "resets_at": null },
"runs_stored": 340,
"limits": { "tokens_per_project": 25, "scenarios_per_run": 10000, "report_bytes": 8388608, "scenario_bytes": 1048576, "ingest_per_minute_per_token": 60 } }A limit of null means unlimited. The plan's quotas are also in entitlements.quotas of GET /api/orgs/:org and GET /api/auth/me.
#Artifacts and encryption at rest
Full scenario payloads are never stored in table rows. The scenarios of a run are packed into chunks of about 512 KB of JSON, gzipped, encrypted with AES-256-GCM (random IV per chunk; the object key is authenticated as additional data) and written to the blob store under
parity/<org id>/<project id>/<run id>/<chunk index>Scenario rows keep light columns plus (chunk_index, chunk_offset). Reading one scenario fetches and decrypts one chunk. Deleting a run or a project, the retention purge and the purge of a deleted organisation delete the objects too; deletions are queued in the same transaction (parity.blob_purge_queue) so a temporary storage failure is retried by the cron.
Where the chunks go is chosen by the blob adapter: the Worker's R2 bucket binding (PARITY_ARTIFACTS) when it exists, otherwise the S3-compatible API with R2_* credentials, otherwise the table parity.blobs. BLOB_STORE=r2 requires one of the first two; BLOB_STORE=postgres selects the table explicitly. In production the table is never chosen silently: without R2 configured and without an explicit BLOB_STORE=postgres, the server refuses to store artifacts. There is no fallback between stores at run time — if R2 fails the upload fails (503), and nothing is written to PostgreSQL instead.
PARITY_DATA_KEY (32 bytes, base64) is required in production. The id of the key (PARITY_DATA_KEY_ID, default k1) is stored in every chunk and on the run. To rotate, set a new key and id and list the old keys in PARITY_DATA_KEYS_PREVIOUS (<id>:<base64>,…); old data stays readable, new data uses the new key.
#Review
A classification (regression, intentional, nondeterministic; unreviewed clears it) is keyed by its full scope:
(project, scenario id, difference id, baseline revision, candidate revision, config fingerprint)It applies to a difference in a run only when every part matches exactly; a missing revision is the empty string. It never carries over to another difference, scenario, revision pair or comparison configuration. Classifications made under another scope are returned only as prior hints on the scenario detail, with the parts that differ. Every change is written to the audit log with before and after.
#Plans
src/server/entitlements.ts is the only place that maps a Parity plan to capabilities.
| Free | Pro ($9.99/month) | Team ($19.99/seat/month, proposed) | |
|---|---|---|---|
| Projects | 1 | unlimited | unlimited |
| Retention | 7 days | 90 days default, up to 365 | same as Pro |
| Workspace | read-only | full | full |
| Review | no | admins | admins and members |
| Role overrides, org default policy, audit log, failed-run email | no | no | yes |
Billing infrastructure is shared: one provider customer per organisation (x1991.billing_customers) and one subscription row per (organisation, product) (x1991.subscriptions, Parity's is product = 'parity').
BILLING_PROVIDER=stripe: Checkout Sessions in subscription mode (STRIPE_PRICE_PARITY_PRO,STRIPE_PRICE_PARITY_TEAM, quantity = seats for Team, metadataorg_idandproduct), Customer Portal, and the webhook. The plan changes only when the webhook says so. Keys that do not start withsk_test_orrk_test_are refused unlessPARITY_ALLOW_LIVE_BILLING=1.BILLING_PROVIDER=local(development default): checkout applies the plan immediately and returns toreturn_path?checkout=success;billing/dev-planswitches plans directly. Never active in production.BILLING_PROVIDER=none:GET billingreportsconfigured: false; checkout and portal return503 billing_not_configured.
#Adapters and environment variables
Every external dependency is an interface in apps/web/src/server/adapters/<name>/ with a factory that picks the implementation from the environment. Moving a service to another account, or replacing it, is a change of environment variables only. apps/web/.env.example lists every variable.
| Port | Selector | Production | Variables |
|---|---|---|---|
| identity | PARITY_AUTH=clerk|local | Clerk | CLERK_SECRET_KEY, NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY, CLERK_WEBHOOK_SIGNING_SECRET; local: PARITY_DEV_SESSION_SECRET |
| database | HYPERDRIVE binding on Workers, else presence of DATABASE_URL | pg → Hyperdrive → Supabase | DATABASE_URL, PARITY_DB_SSL, DATABASE_CA_CERT, PARITY_DB_POOL_MAX; local: PARITY_PGLITE_DIR |
| blob | BLOB_STORE=r2|postgres | R2 by bucket binding (PARITY_ARTIFACTS); off Workers, R2 via aws4fetch | R2_ACCOUNT_ID, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_BUCKET, R2_ENDPOINT, R2_REGION (S3 API only; the binding needs none) |
| billing | BILLING_PROVIDER=stripe|local|none | Stripe REST | STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET, STRIPE_PRICE_PARITY_PRO, STRIPE_PRICE_PARITY_TEAM, STRIPE_API_VERSION, STRIPE_API_BASE, PARITY_ALLOW_LIVE_BILLING |
| analytics | ANALYTICS_PROVIDER=posthog|console|none | PostHog capture API | POSTHOG_KEY, POSTHOG_HOST |
EMAIL_PROVIDER=resend|local | Resend via @x1991/email | RESEND_API_KEY, RESEND_WEBHOOK_SECRET, PARITY_EMAIL_FROM, EMAIL_ALLOWED_FROM_DOMAINS, EMAIL_LOCAL_DIR | |
| rate limit | rate-limit bindings on Workers | Workers Rate Limiting API (INGEST_RATE_LIMITER, AUTH_RATE_LIMITER); elsewhere an in-memory token bucket | PARITY_INGEST_RATE_PER_MIN |
| jobs | PARITY_JOBS queue binding on Workers | Cloudflare Queues; elsewhere a background task in the same process | — |
Cloudflare bindings are read in one place, src/server/adapters/cloudflare, through OpenNext's getCloudflareContext(); off Workers it returns nothing and every adapter uses its portable implementation.
Other variables: PARITY_APP_URL, PARITY_TRUSTED_PROXY_HOPS, PARITY_DATA_KEY, PARITY_DATA_KEY_ID, PARITY_DATA_KEYS_PREVIOUS, PARITY_ARTIFACT_CHUNK_BYTES, CRON_SECRET, PARITY_ORG_PURGE_GRACE_DAYS, PARITY_AUDIT_RETENTION_DAYS, PARITY_MIGRATIONS_DIR, the limits above, the quota and safeguard variables (PARITY_QUOTA_<PLAN>_<NAME>, PARITY_GLOBAL_INGEST_PER_DAY, PARITY_GLOBAL_EMAILS_PER_DAY, PARITY_INGEST_DISABLED, PARITY_ANALYTICS_MAX_EVENTS_PER_REQUEST), PARITY_INGEST_TIMING (measurements only: adds a Server-Timing header with phase durations to ingest responses) and PARITY_LOCAL_PREVIEW (the local Workers preview only).
With R2_ENDPOINT set, any S3-compatible store works in place of R2.
Analytics events (run_ingested, review_classified, project_created, checkout_started, plan_changed) carry ids and counts only — never report content, email addresses or tokens. A failing analytics provider never affects a request.
#Database
Two schemas; nothing is created in public.
x1991— shared by all products:organizations(id = Clerk organisation id, soft-deleted),usersandmemberships(a display mirror of Clerk for audit trails, member lists and seat counts),billing_customers,subscriptions,webhook_events,email_outbox.parity— product tables:projects,project_tokens,runs,scenarios,run_differences,blobs,blob_purge_queue,reviews,audit_log,member_roles,org_settings,org_purges,notification_subscriptions, and for quotasorg_usage(stored bytes, runs and scenarios per organisation, maintained by triggers onruns) andusage_counters(windowed counters per organisation and for the deployment).
Timestamps are bigint milliseconds since the Unix epoch. Row level security is enabled on every table with no policies, and schema usage is revoked from anon and authenticated: the Supabase Data API can reach nothing. The application connects with a privileged server role and enforces tenancy in code on every query path; RLS is a backstop.
The pg driver is used in a way that works through a transaction-mode pooler: no session state, unnamed statements only, explicit transactions on one client.
On Cloudflare Workers the connection goes through Hyperdrive when the HYPERDRIVE binding exists (env.HYPERDRIVE.connectionString, no TLS from the Worker: Hyperdrive encrypts the hop to the origin itself), and straight to DATABASE_URL otherwise. There is no module-global pool or client on Workers: every request, background task, queue batch and cron tick gets its own clients, opened lazily (a typical request uses one) and closed when it ends. The Hyperdrive configuration must have query caching disabled — the application reads its own writes (idempotency, quota counters, review state) and Hyperdrive's cache is not invalidated by writes.
#Migrations
Plain SQL in supabase/migrations/, in this order:
20261128170000_x1991_platform.sql20261128170100_parity_product.sql20261128180000_parity_usage_quotas.sql
Each file is idempotent and records itself (x1991.schema_migrations or parity.schema_migrations), so it can be applied and re-applied with the Supabase CLI, psql or the bundled runner:
npm run db:migrate -w @x1991/parity-web # applies what is pending
npm run db:status -w @x1991/parity-web # applied / PENDING per fileThe embedded development database migrates itself when it opens.
#Scheduled work
POST /api/internal/cron:
- sends due rows of the email outbox — the sweep for anything a queue message did not finish,
- deletes runs past their retention, bounded by the plan, with their artifacts,
- purges the product data of organisations deleted in Clerk once the grace period (
PARITY_ORG_PURGE_GRACE_DAYS, default 7) has passed, - drains the artifact deletion queue, trims old webhook ids, finished outbox rows and usage counters of past windows.
On Cloudflare Workers the Cron Trigger in wrangler.jsonc (every five minutes) calls the Worker's scheduled handler (apps/web/cloudflare/worker.ts), which calls this endpoint inside the isolate with the isolate token. Off Workers, call it from any scheduler with Authorization: Bearer $CRON_SECRET. npm run purge -w @x1991/parity-web runs steps 2–4 from a shell. Retention also runs opportunistically for a project after each upload.
When an uploaded run's verdict is fail, one email per run_failed subscriber of the project is queued in x1991.email_outbox in the same transaction as the run. The idempotency key parity:run_failed:<run id>:<user id> is unique in the table and is passed to the provider, so neither a re-upload nor a retry can send twice. The upload response never waits for email.
After the transaction commits, delivery is handed off:
- On Workers with the
PARITY_JOBSqueue bound: one small message per 25 rows,{ "type": "outbox", "ids": ["eml_…"] }— ids only, never addresses or report content. The Worker'squeuehandler forwards each batch toPOST /api/internal/queue, and every message is acknowledged or retried on its own: sent, permanently failed or nothing left to do → acknowledged; a retryable provider error → retried when the row is due again (the outbox backoff, at most 12 hours); the batch could not be processed at all → retried with backoff. After five retries a message goes to the dead-letter queue (parity-jobs-dlq); the row itself is still in the outbox and the cron sweep keeps trying it. - Everywhere else (Node, tests, a Worker without the binding, or when the queue refuses the message): a background task in the same process, as before.
Queues deliver at least once. That is safe because the outbox decides who sends: a row is claimed with FOR UPDATE SKIP LOCKED, only while it is due, and its idempotency key goes to the provider. A duplicate delivery finds nothing to claim.
The sender renders the template from light table columns, sends, and records the provider message id. Network errors, 5xx and 429 are retried with exponential backoff and jitter, honouring Retry-After, up to six attempts; other 4xx responses mark the row failed. Daily email quotas are applied just before sending; see Quotas.
Statuses: queued → sending → sent → delivered, or bounced, complained, failed. A bounce or complaint also removes the subscription.
Organisation invitations and every authentication email are sent by Clerk, not by Parity.
#Webhooks
All three verify the signature over the raw body and are idempotent through x1991.webhook_events (provider, event_id).
| Endpoint | Events | Effect |
|---|---|---|
/api/stripe/webhook | checkout.session.completed, customer.subscription.created, .updated, .deleted | Sets the Parity plan, seats and period. 5-minute timestamp tolerance, constant-time comparison. Out-of-order events and subscriptions of other products are ignored. Live-mode events are refused. |
/api/clerk/webhook | user.created, .updated, .deleted; organization.created, .updated, .deleted; organizationMembership.created, .updated, .deleted | Keeps the mirror current. Removing a membership removes the role override and that person's notification subscriptions. Deleting an organisation soft-deletes it, revokes its tokens and schedules its Parity data for purge. |
/api/resend/webhook | email.sent, .delivered, .bounced, .complained, .delivery_delayed | Updates the outbox row by provider message id; status never moves backwards. |
#Cloudflare Workers
The bindings, the local preview and the deployment checklist are described in apps/web/CLOUDFLARE.md in the repository.
npm run cf:db -w @x1991/parity-web # disposable Postgres in Docker for the preview, migrated
npm run cf:build -w @x1991/parity-web # OpenNext build → apps/web/.open-next, then strip and verify
npm run cf:preview -w @x1991/parity-web # build and run the Worker in local workerd (http://localhost:8799)
npm run cf:smoke -w @x1991/parity-web # end-to-end check against the running preview
npm run cf:size -w @x1991/parity-web # Worker size and what contributes to itapps/web/wrangler.jsonc holds no secrets, no account id and no real resource id. Secrets are Worker secrets with the names used in .env.example. In production PARITY_DATA_KEY and a database (the HYPERDRIVE binding, or DATABASE_URL) are required; the embedded database is never bundled into the Worker.
Always build with npm run cf:build, never with opennextjs-cloudflare build directly: OpenNext compiles every .env* file it finds, including .env.local, into the Worker bundle (.open-next/cloudflare/next-env.mjs). The script empties that file after the build and then scans the whole output for credential-shaped values and for assignments to secret names; a finding fails the build.
#Development
npm run seed -w @x1991/parity-web # demo data, local identities
npm run seed -w @x1991/parity-web -- --org org_123 # attach the demo project to a Clerk organisation
npm test -w @x1991/parity-web # vitest on an in-memory database