Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

refactor(db): finish the RLS helper migration, move webhooks onto the event system, add crbn restore (#1348)

Sidf25eba584c54
diff --git a/.ai/lessons.md b/.ai/lessons.md
index fe1ea3efcb..3e9fa38a96 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -683,3 +683,23 @@ Format: `Context → Problem → Rule → Applies to`
**Rule:** Benchmark the query the service actually builds — copy the projection, the `ORDER BY` from `setGenericQueryFilters`, and the `LIMIT/OFFSET`, not a simplified `SELECT * ... LIMIT n`. Run `ANALYZE` before trusting any timing on seeded data, and check `pg_stat_user_tables.last_analyze` first. When a rewrite's premise is "this touches rows it shouldn't", verify it against `pg_policies` before optimizing — RLS may already be doing it. A LATERAL is only a win when the limit can be pushed below the join, which needs an index supplying the sort; check the plan for `Seq Scan ... loops=<number of outer rows>`, which is the signature of a per-row aggregate that was meant to run per page.
**Applies to:** `packages/database/supabase/migrations/20260807011742_lateralize-order-list-views.sql`, `20260806235710_perf-list-query-indexes.sql`, `apps/erp/app/utils/query.ts` (`setGenericQueryFilters`), and any future list-view or RLS-policy performance work.
+
+## Inngest `concurrency: { limit: 0 }` is no capacity, not unlimited
+
+**Context:** Moving webhooks onto the event system. The `WEBHOOK` handler had never actually run — webhooks went through 39 pg_net triggers, so the handler was dead code. Once a subscription made it live, every delivery sat in `QUEUED` forever and nothing reached the endpoint.
+
+**Problem:** `webhook.ts` declared `concurrency: { limit: 0, key: "<table>-<recordId>" }`. `limit: 0` reads like "unlimited" and is almost certainly what the author meant, but Inngest treats it as zero capacity: runs are accepted, grouped by key, and never scheduled. The failure is silent and looks like the event never fired — the drainer completes, the queue empties, `pgmq` shows nothing pending, and only the run list reveals runs parked in `QUEUED` while sibling handlers from the same drain show `COMPLETED`. A controlled test confirmed it: three runs stuck at `limit: 0`, and changing only that value to `1` released them. Two more instances existed — `workflow.ts` (a stub, latent) and `reschedule-job.ts` (`schedule-job`, live, called from `production.server.ts` and `production.service.ts`).
+
+**Rule:** Inngest `concurrency.limit` must be `>= 1`; to mean "unlimited", omit the `concurrency` block entirely. With a `key`, `limit: 1` is the usual intent — serialize per record/company. Enforced by the `no-zero-concurrency` conformance check in `@carbon/checks`. More generally: a handler with zero subscriptions is dead code whose config is never exercised, so any bug in it surfaces only when something makes it live — when wiring an existing-but-unused handler, fire it end-to-end rather than trusting that it worked before.
+
+**Applies to:** `packages/jobs/src/inngest/**` `createFunction` options; `packages/checks/src/conformance/no-zero-concurrency.ts`.
+
+## Generated DB types must come from a migration-built database, never a restored snapshot
+
+**Context:** `crbn restore` ends with `pnpm db:types`. Those regenerated types were then swept into a commit by `git add -A`, putting 194 lines of unrelated churn into a webhooks/RLS PR.
+
+**Problem:** A production snapshot carries whatever the source environment accumulated outside the migration stream, so types generated from it describe *that* database rather than the schema the migrations define. The diff added a `v_readable_id` relation absent from `main` — not a schema object at all, but a plpgsql local (`v_readable_id TEXT;` … `SELECT … INTO v_readable_id, v_company_id`) that ran somewhere in a plain-SQL context, where `SELECT … INTO` is CREATE-TABLE-AS. An accidental artifact table exists in the snapshot, and regenerating baked it into the repo's public type surface, alongside `procedureStep`→`procedureAttribute` FK-name churn.
+
+**Rule:** Never commit `packages/database/src/types.ts` (or `supabase/functions/lib/types.ts`) generated after a `crbn restore` — regenerate against a migration-built database first. `crbn restore` now warns about this. Stage generated types explicitly rather than with `git add -A`, and diff them before committing: any relation appearing that no migration defines is drift from the source environment, not a schema change. Separately, `SELECT … INTO <name>` in a SQL (non-plpgsql) context silently creates a table — a real hazard when copying plpgsql bodies into migrations.
+
+**Applies to:** `packages/dev/src/commands/restore.ts`, `packages/database/src/types.ts`, `packages/database/supabase/functions/lib/types.ts`.
diff --git a/.claude/rules/event-system.md b/.claude/rules/event-system.md
index 27e0b450f9..1a2c1c5ac8 100644
--- a/.claude/rules/event-system.md
+++ b/.claude/rules/event-system.md
@@ -29,7 +29,7 @@ pg_cron 'event-queue-sweeper' (* * * * *, in-DB): if visible messages exist →
```
The wake path (`20260721184852_event-queue-wake.sql`) — both helpers live in the internal `util` schema (like `util.process_embeddings`), NOT `public`:
-- `util.wake_event_queue()` — SECURITY DEFINER; reads `apiUrl`/`anonKey` from the singleton `config` table (same as the webhook triggers) and `net.http_post`s to `/functions/v1/event-wake`. Error-swallowed and no-ops when `config` is unseeded — OLTP writes never fail on push failure. pg_net queues the request transactionally, so the wake fires only after commit.
+- `util.wake_event_queue()` — SECURITY DEFINER; reads `apiUrl`/`anonKey` from the singleton `config` table and `net.http_post`s to `/functions/v1/event-wake`. Error-swallowed and no-ops when `config` is unseeded — OLTP writes never fail on push failure. pg_net queues the request transactionally, so the wake fires only after commit.
- `dispatch_event_batch()` calls it at most **once per transaction** via the txn-local GUC `carbon.event_wake_sent` (`set_config(..., true)`).
- `util.sweep_event_queue()` — pg_cron job `event-queue-sweeper` re-wakes every minute while *visible* messages (`vt <= clock_timestamp()`) sit in `pgmq.q_event_system`.
- **Why `util`, not `public`:** a public function is auto-exposed as a PostgREST RPC, and a non-superuser reference to a function that transitively calls `net.http_post` segfaults the backend (pg_net 0.20 / PG15) — a remote-DoS surface a `REVOKE` can't close because the crash precedes the privilege check. anon/authenticated have no `USAGE` on `util`, so the API can't reach it. The trigger and pg_cron call it as the owner (superuser), where the pg_net path is safe.
@@ -66,7 +66,7 @@ Zod schemas + helpers. `QueueMessage` = `{ subscriptionId, triggerType: ROW|STAT
| handlerType | event name | file | purpose |
|---|---|---|---|
-| `WEBHOOK` | `carbon/event-webhook` | `webhook.ts` | `axios.post(config.url, data, { headers })` |
+| `WEBHOOK` | `carbon/event-webhook` | `webhook.ts` | `axios.post(config.url, toWebhookBody(...), { headers })` — customer-facing webhooks; see below |
| `WORKFLOW` | `carbon/event-workflow` | `workflow.ts` | dispatch by `workflowId` (<!-- UNVERIFIED: body is still a stub/no-op --> ) |
| `SYNC` | `carbon/event-sync` | `sync.ts` | accounting sync (Xero); maps table→entity, calls `@carbon/ee/accounting` |
| `SEARCH` | `carbon/event-search` | `search.ts` | upsert/delete `search_index` via RPC per entity config |
@@ -75,6 +75,14 @@ Zod schemas + helpers. `QueueMessage` = `{ subscriptionId, triggerType: ROW|STAT
All handlers (incl. `eventQueueFunction`) are exported from `events/index.ts` and registered in `packages/jobs/src/inngest/functions/index.ts`. Inngest client comes from `@carbon/lib/inngest`.
+### WEBHOOK — the customer-facing one
+
+Since `20260807234512_webhooks-via-event-system.sql`, user-configured webhooks (Settings → Webhooks) run on this handler. Before that they had their own pg_net path: 39 `webhook_*` triggers → the `webhook` edge function. Both the triggers and that edge function are **deleted** — don't resurrect them.
+
+- **Subscriptions are derived, not app-managed.** The `sync_webhook_subscription` AFTER-ROW interceptor — registered via `attach_event_trigger('webhook', ARRAY[]::TEXT[], ARRAY['sync_webhook_subscription'])`, so it follows the same convention as `sync_create_customer_entries` — maintains a subscription named `webhook-<webhook.id>` with `handlerType 'WEBHOOK'` and `config {url, webhookId}`. The `webhook` table is the single source of truth, so UI/API/MCP writers all work without lifecycle code. It deletes-then-recreates on UPDATE because `table` is editable and uniqueness is `(companyId, name, table)`.
+- **The body is a PUBLIC contract**: `{type, record, old?, companyId, table, eventId}` — documented at `docs/content/docs/building/webhooks.mdx` and pinned by `webhook.test.ts`. `toWebhookBody` maps the queue event onto it. Two traps: DELETE takes `record` from the event's `old` (its `new` is null), and `companyId` is **not** on the event — the drainer forwards it from the queue message.
+- Delivery moved from at-most-once to **at-least-once** (Inngest `retries: 3`); `increment_webhook_error` fires only on the final attempt so counters stay one-per-event. `eventId` is the pgmq `msgId` — stable across an event's retries (it is also the Inngest idempotency key), distinct per change — and is the documented de-dup key. `type` + `record.id` is NOT usable: two genuine updates to a row share both.
+
## Notes
- Latency: typically ~3–5s (sub-second wake + the multi-step drain run). Worst case ~1 min if a push is lost (dead pg_net worker, edge fn down) — the pg_cron sweeper re-wakes while messages are pending. Still async: use sync interceptors, not subscriptions, for data-integrity / real-time needs.
- The wake path depends on a seeded `config` row (`apiUrl`, `anonKey`). Dev seeds it automatically (`ensureConfigRow` in `packages/dev/src/services/migrations.ts`, apiUrl `http://kong:8000`). **Unseeded config (e.g. self-hosted) = events never process** — both the push and the sweeper wake no-op.
diff --git a/README.md b/README.md
index f4d93fa9fe..f636574407 100644
--- a/README.md
+++ b/README.md
@@ -396,31 +396,31 @@ To run a command against a single workspace, use `pnpm --filter`:
$ pnpm --filter @carbon/react test
```
-To restore a production database snapshot locally, use the `scripts/restore-database.sh` script. It handles both plain-text `.backup` and custom-format `.dump` archives, drops and rebuilds the public schema, realigns internal sequences, and resets storage metadata.
+To restore a production database snapshot locally, use `crbn restore`. It handles both plain-text `.backup` and custom-format `.dump` archives, drops and rebuilds the public schema, realigns internal sequences, resets storage metadata, then applies any migrations the backup predates and regenerates types.
1. Export a backup from your production Supabase project (`pg_dump` or Supabase Dashboard → Database → Backups).
-2. Boot the stack **without applying migrations** so they don't fight the dump's schema state:
+2. Run it from your worktree root:
```bash
- $ crbn up --no-migrate
- ```
-3. Run the restore script from your worktree root, passing the path to the backup file:
- ```bash
- $ ./scripts/restore-database.sh /path/to/db_cluster.backup
+ $ crbn restore /path/to/db_cluster.backup
# …or for .dump archives:
- $ ./scripts/restore-database.sh /path/to/postgres_YYYYMMDD.dump
+ $ crbn restore /path/to/postgres_YYYYMMDD.dump
```
- To also get local admin access, set `ADMIN_EMAIL` to your production email. The script will upgrade your account to Admin in all companies you already belong to and reset your password locally:
+ It prompts before replacing the database. The stack must already be running (`crbn up`) — a restore rewrites the `auth` and `storage` schemas, which GoTrue and Storage build through their own migrations when those containers boot, so `crbn restore` refuses rather than restore into an uninitialized stack.
+
+ To also get local admin access, pass your production email — your account is upgraded to Admin in the companies it already belongs to and the password is reset locally:
```bash
- $ [email protected] ./scripts/restore-database.sh /path/to/backup.backup
+ $ crbn restore /path/to/backup.backup --admin-email [email protected]
# Optional: set a custom local password (default: localpass)
- $ [email protected] ADMIN_PASSWORD=mypass ./scripts/restore-database.sh /path/to/backup.backup
+ $ crbn restore /path/to/backup.backup --admin-email [email protected] --admin-password mypass
```
- > **Note:** Emails are not scrubbed — real production addresses will be present in the local DB. Ensure local email sending is disabled or pointed at a sandbox (e.g. Mailpit) before triggering any email flows.
-4. Regenerate types so app code reflects the restored schema:
- ```bash
- $ pnpm db:types
- ```
+ Useful flags: `--no-scrub-emails` keeps real addresses (see the warning below), `--mode prod` restores exactly as-is without localizing config/webhooks/integrations, `--no-migrate` / `--no-regen` skip the trailing steps, `--yes` skips the prompt.
+
+ > **Emails are scrubbed by default** — every address is rewritten to `@example.test` (your `--admin-email` is preserved so you can still log in). If you pass `--no-scrub-emails`, real production addresses will be present in the local DB; ensure local email sending is disabled or pointed at a sandbox (e.g. Mailpit) before triggering any email flows.
+ >
+ > **Note:** `storage.objects` is truncated by default, so a restore does not populate local file storage — kept rows would reference files that only exist in the source environment's backend. Pass `--keep-storage-objects` to retain the metadata (and the backup's buckets) anyway; downloads will still 404, but the rows are there for work that needs realistic storage volume.
+
+The underlying script, `scripts/restore-database.sh`, can still be invoked directly — it takes the same options as environment variables (`SCRUB_EMAILS`, `ADMIN_EMAIL`, `ADMIN_PASSWORD`, `RESTORE_MODE`), but note it defaults to **not** scrubbing emails and leaves the trailing `pnpm db:migrate` / `pnpm db:types` to you.
## API
diff --git a/apps/erp/app/modules/agent/kb/docs/building/webhooks.md b/apps/erp/app/modules/agent/kb/docs/building/webhooks.md
index 5efed3dfe0..fb837d5676 100644
--- a/apps/erp/app/modules/agent/kb/docs/building/webhooks.md
+++ b/apps/erp/app/modules/agent/kb/docs/building/webhooks.md
@@ -1,6 +1,6 @@
# Webhooks
-> Get an HTTP callback the moment a Carbon record is created, changed, or deleted.
+> Get an HTTP callback when a Carbon record is created, changed, or deleted.
A **webhook** sends an HTTP `POST` to a URL you choose whenever a record in a subscribed table is inserted, updated, or deleted. It's the lightest way to react to Carbon in your own systems without polling the API.
@@ -22,19 +22,22 @@ For each webhook you choose which operations fire it (**insert**, **update**, **
## The payload
-Carbon `POST`s a JSON body to your URL. `type` is the operation, `record` is the affected row, and `old` carries the previous row on updates and deletes.
+Carbon `POST`s a JSON body to your URL. `type` is the operation, `record` is the affected row, and `old` carries the previous row on updates.
```json
{
"type": "UPDATE",
"table": "salesOrder",
"companyId": "abc123",
+ "eventId": "1042",
"record": { "id": "...", "salesOrderId": "SO000042", "status": "To Ship and Invoice" },
"old": { "id": "...", "salesOrderId": "SO000042", "status": "Draft" }
}
```
-On an insert, `old` is omitted; on a delete, `record` is the row as it last existed. The only request header is `Content-Type: application/json`.
+`old` appears only on updates. On a delete, `record` is the row as it last existed and there is no `old`. The only request header is `Content-Type: application/json`.
+
+`eventId` identifies the individual change. It stays the same across retries of that change and differs between changes — including two separate edits to the same record — which makes it the field to de-duplicate on (see below).
## Configuration
@@ -50,7 +53,14 @@ Carbon tracks a success and error count per webhook, with the timestamp of the l
## Delivery & reliability
-Delivery is **at-most-once**: Carbon fires a single `POST` per change and records the outcome. There are no automatic retries, no backoff, and no rate limiting on outbound calls. If your endpoint is down when the event fires, that delivery is missed (the success/error counters will show it). Build your consumer to tolerate the occasional gap, and reconcile against the API when it matters.
+Webhooks are queued rather than sent inline with the database write, so a `POST` normally lands a few seconds after the change. A brief delay is expected; it is not a sign your endpoint was skipped.
+
+Delivery is **at-least-once**. If your endpoint doesn't return a success status, Carbon retries the same change a few times with exponential backoff before giving up. Two consequences to design for:
+
+- **Handle duplicates.** A delivery that times out or errors after you've already processed it will arrive again. De-duplicate on `eventId`, which is stable across retries of a change. Don't key on `type` + `record.id` — every update to a given record shares those, so you would discard genuine later changes.
+- **A sustained outage still loses events.** Once retries are exhausted the change is dropped and counted as an error. Reconcile against the API when completeness matters.
+
+The success and error counters record one outcome per change, not per attempt, so a retried-then-delivered event counts once as a success.
Carbon does **not** sign webhook payloads. There is no shared secret or signature header to verify against. Treat the webhook URL itself as the secret: serve it over HTTPS and include an unguessable token in the path or query so you can reject anything that doesn't carry it.
diff --git a/apps/erp/app/modules/agent/kb/docs/reference/company-settings.md b/apps/erp/app/modules/agent/kb/docs/reference/company-settings.md
index 9ce3ef71c6..5f672455bb 100644
--- a/apps/erp/app/modules/agent/kb/docs/reference/company-settings.md
+++ b/apps/erp/app/modules/agent/kb/docs/reference/company-settings.md
@@ -32,7 +32,7 @@ company membership is per-user, so one login can hold several companies and swit
Companies can also nest. A company with a `parentCompanyId` is a **subsidiary** (`subsidiaryValidator`, `settings.models.ts:279`); an `isEliminationEntity` company exists only to net intercompany transactions out of consolidated reports.
-The **Companies** management screen is gated to internal operators (`internalOnlyRoutes` in `useSettingsSubmodules.tsx`); **Backups** is gated to internal operators on any real deployment but is open to every user on a local dev stack (`canAccessBackups`). Most tenants create and switch companies through onboarding and the company picker, not this screen.
+The **Companies** management screen and **Backups** are gated to internal operators (`internalOnlyRoutes` in `useSettingsSubmodules.tsx`). Most tenants create and switch companies through onboarding and the company picker, not this screen.
For consolidated reporting and the elimination flow, see `docs/reference/intercompany`.
@@ -102,7 +102,7 @@ Which company-wide features are available at all also depends on your plan and e
Mostly "why can't I see or change setting X" — the answers are preconditions, not error strings.
### I can't find the Companies or Backups settings page
-Companies is internal-operator-only (`internalOnlyRoutes` in `useSettingsSubmodules.tsx`). Backups is internal-operator-only on hosted and self-hosted deployments, but visible to any user running a local dev stack (`canAccessBackups`). Regular tenants don't get these screens — create and switch companies through onboarding and the company picker instead.
+Both are internal-operator-only, gated by `internalOnlyRoutes` in `useSettingsSubmodules.tsx`. Regular tenants don't get these screens — create and switch companies through onboarding and the company picker instead.
### I can't see the Billing settings page
Billing needs **company ownership** *and* a Cloud environment — it's gated on both (`useSettingsSubmodules.tsx`). Self-hosted/community editions and non-owner users won't see it.
diff --git a/apps/erp/app/modules/agent/kb/manifest.json b/apps/erp/app/modules/agent/kb/manifest.json
index df3bb972f9..efcca2e51b 100644
--- a/apps/erp/app/modules/agent/kb/manifest.json
+++ b/apps/erp/app/modules/agent/kb/manifest.json
@@ -18,7 +18,7 @@
{
"slug": "docs/building/webhooks",
"title": "Webhooks",
- "description": "Get an HTTP callback the moment a Carbon record is created, changed, or deleted.",
+ "description": "Get an HTTP callback when a Carbon record is created, changed, or deleted.",
"keywords": ["webhooks", "docs", "building"],
"headings": [
"Subscribable tables",
diff --git a/docs/content/docs/building/webhooks.mdx b/docs/content/docs/building/webhooks.mdx
index efdbb48946..c4c2776e64 100644
--- a/docs/content/docs/building/webhooks.mdx
+++ b/docs/content/docs/building/webhooks.mdx
@@ -1,7 +1,7 @@
---
title: Webhooks
plan: Business
-description: Get an HTTP callback the moment a Carbon record is created, changed, or deleted.
+description: Get an HTTP callback when a Carbon record is created, changed, or deleted.
---
A **webhook** sends an HTTP `POST` to a URL you choose whenever a record in a subscribed table is inserted, updated, or deleted. It's the lightest way to react to Carbon in your own systems without polling the API.
@@ -24,19 +24,22 @@ For each webhook you choose which operations fire it (**insert**, **update**, **
## The payload
-Carbon `POST`s a JSON body to your URL. `type` is the operation, `record` is the affected row, and `old` carries the previous row on updates and deletes.
+Carbon `POST`s a JSON body to your URL. `type` is the operation, `record` is the affected row, and `old` carries the previous row on updates.
```json
{
"type": "UPDATE",
"table": "salesOrder",
"companyId": "abc123",
+ "eventId": "1042",
"record": { "id": "...", "salesOrderId": "SO000042", "status": "To Ship and Invoice" },
"old": { "id": "...", "salesOrderId": "SO000042", "status": "Draft" }
}
```
-On an insert, `old` is omitted; on a delete, `record` is the row as it last existed. The only request header is `Content-Type: application/json`.
+`old` appears only on updates. On a delete, `record` is the row as it last existed and there is no `old`. The only request header is `Content-Type: application/json`.
+
+`eventId` identifies the individual change. It stays the same across retries of that change and differs between changes — including two separate edits to the same record — which makes it the field to de-duplicate on (see below).
## Configuration
@@ -52,7 +55,14 @@ Carbon tracks a success and error count per webhook, with the timestamp of the l
## Delivery & reliability
-Delivery is **at-most-once**: Carbon fires a single `POST` per change and records the outcome. There are no automatic retries, no backoff, and no rate limiting on outbound calls. If your endpoint is down when the event fires, that delivery is missed (the success/error counters will show it). Build your consumer to tolerate the occasional gap, and reconcile against the API when it matters.
+Webhooks are queued rather than sent inline with the database write, so a `POST` normally lands a few seconds after the change. A brief delay is expected; it is not a sign your endpoint was skipped.
+
+Delivery is **at-least-once**. If your endpoint doesn't return a success status, Carbon retries the same change a few times with exponential backoff before giving up. Two consequences to design for:
+
+- **Handle duplicates.** A delivery that times out or errors after you've already processed it will arrive again. De-duplicate on `eventId`, which is stable across retries of a change. Don't key on `type` + `record.id` — every update to a given record shares those, so you would discard genuine later changes.
+- **A sustained outage still loses events.** Once retries are exhausted the change is dropped and counted as an error. Reconcile against the API when completeness matters.
+
+The success and error counters record one outcome per change, not per attempt, so a retried-then-delivered event counts once as a success.
<Callout type="warn">
Carbon does **not** sign webhook payloads. There is no shared secret or signature header to verify against. Treat the webhook URL itself as the secret: serve it over HTTPS and include an unguessable token in the path or query so you can reject anything that doesn't carry it.
diff --git a/packages/checks/src/conformance/no-zero-concurrency.test.ts b/packages/checks/src/conformance/no-zero-concurrency.test.ts
new file mode 100644
index 0000000000..51e1685191
--- /dev/null
+++ b/packages/checks/src/conformance/no-zero-concurrency.test.ts
@@ -0,0 +1,56 @@
+import { describe, expect, it } from "vitest";
+import { noZeroConcurrency } from "./no-zero-concurrency";
+
+// This exists because `limit: 0` shipped in two handlers and silently parked
+// every webhook delivery in QUEUED — invisible until a live end-to-end run,
+// since no unit test reaches createFunction's config object.
+describe("noZeroConcurrency", () => {
+ const scan = (src: string) => noZeroConcurrency.scan("f.ts", src);
+
+ it("flags the real shape the bug shipped in", () => {
+ const v = scan(`inngest.createFunction(
+ {
+ id: "event-handler-webhook",
+ concurrency: {
+ limit: 0,
+ key: "event.data.data.table"
+ }
+ },
+);`);
+ expect(v).toHaveLength(1);
+ expect(v[0]!.line).toBe(4);
+ });
+
+ it("accepts a real limit", () => {
+ expect(scan(`concurrency: {\n limit: 1,\n key: "x"\n}`)).toHaveLength(0);
+ expect(scan(`concurrency: 1,`)).toHaveLength(0);
+ });
+
+ it("ignores an unrelated limit: 0 far from any concurrency block", () => {
+ expect(scan(`const opts = { limit: 0, offset: 0 };`)).toHaveLength(0);
+ expect(
+ scan(
+ `concurrency: { limit: 5 },\n${"// pad\n".repeat(30)}const q = { limit: 0 };`
+ )
+ ).toHaveLength(0);
+ });
+
+ it("does not match past the closing brace of the concurrency object", () => {
+ // A bounded [\s\S] span reached over the `}` and flagged this.
+ expect(scan(`concurrency: {}, const query = { limit: 0 };`)).toHaveLength(
+ 0
+ );
+ expect(
+ scan(`concurrency: { limit: 2 }, const query = { limit: 0 };`)
+ ).toHaveLength(0);
+ expect(
+ scan(`concurrency: {\n key: "x"\n},\nconst q = { limit: 0 };`)
+ ).toHaveLength(0);
+ });
+
+ it("catches every occurrence in a file with more than one handler", () => {
+ expect(
+ scan(`concurrency: {\n limit: 0\n}\n\nconcurrency: {\n limit: 0\n}`)
+ ).toHaveLength(2);
+ });
+});
diff --git a/packages/checks/src/conformance/no-zero-concurrency.ts b/packages/checks/src/conformance/no-zero-concurrency.ts
new file mode 100644
index 0000000000..60500ede7c
--- /dev/null
+++ b/packages/checks/src/conformance/no-zero-concurrency.ts
@@ -0,0 +1,37 @@
+import type { ConformanceCheck, Violation } from "../check";
+
+/**
+ * Matches `limit: 0` inside an Inngest `concurrency` block.
+ *
+ * `[^{}]*?` cannot cross a brace, so the match is confined to the concurrency
+ * object itself — an unrelated `limit: 0` after it closes (a query limit, a
+ * pagination default) is not flagged. A bounded `[\s\S]` span would reach past
+ * the `}` and match `concurrency: {}, const q = { limit: 0 }`.
+ *
+ * The concurrency object contains no nested braces in practice (`limit`, `key`,
+ * `scope` are all scalars), so excluding braces entirely is exact rather than
+ * approximate.
+ */
+const ZERO_CONCURRENCY = /concurrency\s*:\s*\{[^{}]*?\blimit\s*:\s*0\b/g;
+
+export const noZeroConcurrency: ConformanceCheck = {
+ id: "no-zero-concurrency",
+ description: "Inngest concurrency.limit must be >= 1.",
+ provenance: {
+ deprecates: "concurrency: { limit: 0 }",
+ replacedBy: "concurrency: { limit: 1 }"
+ },
+ scan(file, contents) {
+ const violations: Violation[] = [];
+ for (const m of contents.matchAll(ZERO_CONCURRENCY)) {
+ violations.push({
+ file,
+ line: contents.slice(0, m.index).split("\n").length,
+ snippet: m[0].replace(/\s+/g, " "),
+ message:
+ "concurrency.limit 0 is no capacity, not unlimited — every run parks in QUEUED forever. Use >= 1, or omit the concurrency block."
+ });
+ }
+ return violations;
+ }
+};
diff --git a/packages/checks/src/index.ts b/packages/checks/src/index.ts
index c731d18a92..713a06ca12 100644
--- a/packages/checks/src/index.ts
+++ b/packages/checks/src/index.ts
@@ -9,6 +9,7 @@ export { moduleShape } from "./conformance/module-shape";
export { noLegacyRls } from "./conformance/no-legacy-rls";
export { noLocalTimezone } from "./conformance/no-local-timezone";
export { noNumericPrecision } from "./conformance/no-numeric-precision";
+export { noZeroConcurrency } from "./conformance/no-zero-concurrency";
export {
type Invariant,
type InvariantResult,
diff --git a/packages/checks/src/run.ts b/packages/checks/src/run.ts
index c2e22a9146..900958a345 100644
--- a/packages/checks/src/run.ts
+++ b/packages/checks/src/run.ts
@@ -9,6 +9,7 @@ import { moduleShape } from "./conformance/module-shape";
import { noLegacyRls } from "./conformance/no-legacy-rls";
import { noLocalTimezone } from "./conformance/no-local-timezone";
import { noNumericPrecision } from "./conformance/no-numeric-precision";
+import { noZeroConcurrency } from "./conformance/no-zero-concurrency";
import {
loadSqlFiles,
migrationsDir,
@@ -24,7 +25,10 @@ export const CONFORMANCE_CHECKS: ConformanceCheck[] = [
];
/** Checks that run over server-side TS, not SQL migrations. */
-export const SERVER_CHECKS: ConformanceCheck[] = [noLocalTimezone];
+export const SERVER_CHECKS: ConformanceCheck[] = [
+ noLocalTimezone,
+ noZeroConcurrency
+];
export const STRUCTURE_CHECKS: StructureCheck[] = [moduleShape];
diff --git a/packages/database/supabase/functions/webhook/index.ts b/packages/database/supabase/functions/webhook/index.ts
deleted file mode 100644
index 473961eb8b..0000000000
--- a/packages/database/supabase/functions/webhook/index.ts
+++ /dev/null
@@ -1,77 +0,0 @@
-import { createClient } from "@supabase/supabase-js";
-import { serve } from "https://deno.land/[email protected]/http/server.ts";
-import { z } from "npm:zod@^3.24.1";
-import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
-import type { Database } from "../lib/types.ts";
-
-const payloadValidator = z.object({
- webhookId: z.string(),
- type: z.enum(["INSERT", "UPDATE", "DELETE"]),
- record: z.any(),
- old: z.any().optional(),
- url: z.string(),
- companyId: z.string(),
- table: z.string(),
-});
-
-serve(async (req: Request) => {
- const preflight = corsPreflight(req);
- if (preflight) return preflight;
- const payload = await req.json();
- const { type, record, old, url, companyId, table, webhookId } =
- payloadValidator.parse(payload);
-
- const serviceRole = createClient<Database>(
- Deno.env.get("SUPABASE_URL") ?? "",
- Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ?? "",
- {
- auth: {
- autoRefreshToken: false,
- persistSession: false,
- },
- }
- );
-
- try {
- console.log({
- function: "webhook",
- type,
- url,
- companyId,
- table,
- });
-
- // Send webhook request
- const response = await fetch(url, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- type,
- record,
- ...(old && { old }),
- companyId,
- table,
- }),
- });
-
- if (!response.ok) {
- throw new Error(`Webhook request failed with status ${response.status}`);
- }
-
- await serviceRole.rpc("increment_webhook_success", {
- webhook_id: webhookId,
- });
-
- return jsonResponse({ success: true });
- } catch (err) {
- console.error(err);
- if (webhookId) {
- await serviceRole.rpc("increment_webhook_error", {
- webhook_id: webhookId,
- });
- }
- return errorResponse(err, 500);
- }
-});
diff --git a/packages/database/supabase/migrations/20260807141822_purchasing-rfq-rls-uncorrelated.sql b/packages/database/supabase/migrations/20260807141822_purchasing-rfq-rls-uncorrelated.sql
new file mode 100644
index 0000000000..1181e016b8
--- /dev/null
+++ b/packages/database/supabase/migrations/20260807141822_purchasing-rfq-rls-uncorrelated.sql
@@ -0,0 +1,175 @@
+-- Convert the purchasingRfq family off the deprecated per-row RLS helpers.
+--
+-- These five tables are the last in the schema still using the deprecated pair
+-- of per-row helpers -- the permission check and the role check, each passed the
+-- row's own "companyId" and ANDed together (verified against pg_policies: 16
+-- policies, 5 tables, nothing else).
+--
+-- The permission helper is VOLATILE and SECURITY DEFINER, so Postgres must
+-- re-evaluate it for every row it considers and cannot hoist it out of the scan
+-- or use it in an index condition. The modern form passes the row's companyId to
+-- an uncorrelated `= ANY (array)` whose array is produced once by a STABLE
+-- helper in an InitPlan -- one call per query instead of one per row, and an
+-- index-able ScalarArrayOpExpr.
+--
+-- Semantics are preserved exactly, which matters in two ways here:
+--
+-- 1. SELECT keeps its PERMISSION gate. The old predicate gated on
+-- 'purchasing_view' via the deprecated helper, so this uses
+-- get_companies_with_employee_permission('purchasing_view') and NOT
+-- get_companies_with_employee_role(). The generic template in
+-- conventions-database.md would suggest the latter, but that grants read to
+-- any employee of the company and would widen access. The same choice was
+-- made for `journal` and `purchaseOrder` in 20260228000000_rls-refactor-3.
+--
+-- 2. Write access is preserved per table. purchasingRfqToPurchaseOrder and
+-- purchasingRfqToSupplierQuote permitted only SELECT + INSERT -- they are
+-- insert-only join tables that clean up via ON DELETE CASCADE. Their
+-- UPDATE/DELETE are now spelled out as USING (false) rather than left
+-- absent: RLS denies either way, but an explicit deny cannot be mistaken
+-- for a policy someone dropped, which is exactly the ambiguity that made
+-- the `rework` drift hard to read.
+--
+-- The old policies carried long descriptive names; they are recreated with the
+-- standardized SELECT/INSERT/UPDATE/DELETE names, matching the rest of the
+-- schema. Original definitions: 20260115143000_purchasing-rfq.sql lines 71-255,
+-- unaltered by any later migration.
+--
+-- NOT dropping has_company_permission/has_role: 7 storage.objects policies and 5
+-- functions (get_next_sequence, is_claims_admin, create_rfq_from_model_v1,
+-- create_rfq_from_models_v1, create_rfq_from_models_v2) still call them.
+
+-- purchasingRfq
+
+DROP POLICY IF EXISTS "Employees with purchasing_view can view purchasingRfq" ON "public"."purchasingRfq";
+DROP POLICY IF EXISTS "Employees with purchasing_create can insert purchasingRfq" ON "public"."purchasingRfq";
+DROP POLICY IF EXISTS "Employees with purchasing_update can update purchasingRfq" ON "public"."purchasingRfq";
+DROP POLICY IF EXISTS "Employees with purchasing_delete can delete purchasingRfq" ON "public"."purchasingRfq";
+
+CREATE POLICY "SELECT" ON "public"."purchasingRfq"
+FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('purchasing_view'))::text[])
+);
+
+CREATE POLICY "INSERT" ON "public"."purchasingRfq"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('purchasing_create'))::text[])
+);
+
+CREATE POLICY "UPDATE" ON "public"."purchasingRfq"
+FOR UPDATE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('purchasing_update'))::text[])
+);
+
+CREATE POLICY "DELETE" ON "public"."purchasingRfq"
+FOR DELETE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('purchasing_delete'))::text[])
+);
+
+-- purchasingRfqLine
+
+DROP POLICY IF EXISTS "Employees with purchasing_view can view purchasingRfqLine" ON "public"."purchasingRfqLine";
+DROP POLICY IF EXISTS "Employees with purchasing_create can insert purchasingRfqLine" ON "public"."purchasingRfqLine";
+DROP POLICY IF EXISTS "Employees with purchasing_update can update purchasingRfqLine" ON "public"."purchasingRfqLine";
+DROP POLICY IF EXISTS "Employees with purchasing_delete can delete purchasingRfqLine" ON "public"."purchasingRfqLine";
+
+CREATE POLICY "SELECT" ON "public"."purchasingRfqLine"
+FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('purchasing_view'))::text[])
+);
+
+CREATE POLICY "INSERT" ON "public"."purchasingRfqLine"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('purchasing_create'))::text[])
+);
+
+CREATE POLICY "UPDATE" ON "public"."purchasingRfqLine"
+FOR UPDATE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('purchasing_update'))::text[])
+);
+
+CREATE POLICY "DELETE" ON "public"."purchasingRfqLine"
+FOR DELETE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('purchasing_delete'))::text[])
+);
+
+-- purchasingRfqSupplier
+
+DROP POLICY IF EXISTS "Employees with purchasing_view can view purchasingRfqSupplier" ON "public"."purchasingRfqSupplier";
+DROP POLICY IF EXISTS "Employees with purchasing_create can insert purchasingRfqSupplier" ON "public"."purchasingRfqSupplier";
+DROP POLICY IF EXISTS "Employees with purchasing_update can update purchasingRfqSupplier" ON "public"."purchasingRfqSupplier";
+DROP POLICY IF EXISTS "Employees with purchasing_delete can delete purchasingRfqSupplier" ON "public"."purchasingRfqSupplier";
+
+CREATE POLICY "SELECT" ON "public"."purchasingRfqSupplier"
+FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('purchasing_view'))::text[])
+);
+
+CREATE POLICY "INSERT" ON "public"."purchasingRfqSupplier"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('purchasing_create'))::text[])
+);
+
+CREATE POLICY "UPDATE" ON "public"."purchasingRfqSupplier"
+FOR UPDATE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('purchasing_update'))::text[])
+);
+
+CREATE POLICY "DELETE" ON "public"."purchasingRfqSupplier"
+FOR DELETE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('purchasing_delete'))::text[])
+);
+
+-- purchasingRfqToSupplierQuote -- insert-only join table; UPDATE/DELETE denied explicitly
+
+DROP POLICY IF EXISTS "Employees with purchasing_view can view purchasingRfqToSupplierQuote" ON "public"."purchasingRfqToSupplierQuote";
+DROP POLICY IF EXISTS "Employees with purchasing_create can insert purchasingRfqToSupplierQuote" ON "public"."purchasingRfqToSupplierQuote";
+
+CREATE POLICY "SELECT" ON "public"."purchasingRfqToSupplierQuote"
+FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('purchasing_view'))::text[])
+);
+
+CREATE POLICY "INSERT" ON "public"."purchasingRfqToSupplierQuote"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('purchasing_create'))::text[])
+);
+
+-- Explicit rather than absent. RLS already denies what no policy permits, so
+-- these change nothing -- but this PR exists partly because `rework` drifted and
+-- nobody could tell a deliberate omission from a lost policy. Say it out loud.
+CREATE POLICY "UPDATE" ON "public"."purchasingRfqToSupplierQuote"
+FOR UPDATE USING (false);
+
+CREATE POLICY "DELETE" ON "public"."purchasingRfqToSupplierQuote"
+FOR DELETE USING (false);
+
+-- purchasingRfqToPurchaseOrder -- insert-only join table; UPDATE/DELETE denied explicitly
+
+DROP POLICY IF EXISTS "Employees with purchasing_view can view purchasingRfqToPurchaseOrder" ON "public"."purchasingRfqToPurchaseOrder";
+DROP POLICY IF EXISTS "Employees with purchasing_create can insert purchasingRfqToPurchaseOrder" ON "public"."purchasingRfqToPurchaseOrder";
+
+CREATE POLICY "SELECT" ON "public"."purchasingRfqToPurchaseOrder"
+FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('purchasing_view'))::text[])
+);
+
+CREATE POLICY "INSERT" ON "public"."purchasingRfqToPurchaseOrder"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('purchasing_create'))::text[])
+);
+
+CREATE POLICY "UPDATE" ON "public"."purchasingRfqToPurchaseOrder"
+FOR UPDATE USING (false);
+
+CREATE POLICY "DELETE" ON "public"."purchasingRfqToPurchaseOrder"
+FOR DELETE USING (false);
+
+-- The new predicate is an index-able `companyId = ANY (array)`. purchasingRfqLine
+-- and purchasingRfqSupplier had only parent-FK indexes; the other three tables
+-- above already carry a companyId index from 20260115143000.
+CREATE INDEX IF NOT EXISTS "purchasingRfqLine_companyId_idx"
+ ON "purchasingRfqLine" ("companyId");
+
+CREATE INDEX IF NOT EXISTS "purchasingRfqSupplier_companyId_idx"
+ ON "purchasingRfqSupplier" ("companyId");
diff --git a/packages/database/supabase/migrations/20260807224530_rework-rls-realign.sql b/packages/database/supabase/migrations/20260807224530_rework-rls-realign.sql
new file mode 100644
index 0000000000..7f0d2503f0
--- /dev/null
+++ b/packages/database/supabase/migrations/20260807224530_rework-rls-realign.sql
@@ -0,0 +1,58 @@
+-- Realign `rework` RLS with the definitions in 20260527142837_rework.sql.
+--
+-- Production's policies do not match that migration. They were changed outside
+-- the migration stream at some point, so the deployed authorization differs from
+-- what the repository says it is -- found by restoring a production snapshot and
+-- diffing pg_policies against the source.
+--
+-- verb | production (restored 2026-08-07) | 20260527142837 intends
+-- --------+------------------------------------------+------------------------
+-- SELECT | employee AND member of the company | production_view
+-- INSERT | employee AND member of the company | production_create
+-- UPDATE | employee AND production_update | production_update
+-- DELETE | (absent -- every delete denied) | production_delete
+--
+-- So production is BROADER on read/insert (any employee of the company, not just
+-- those granted production access) and NARROWER on delete (nobody can delete a
+-- rework record at all). It also still calls the deprecated per-row helpers,
+-- which is how it surfaced: after 20260807141822 converted the purchasingRfq
+-- family, `rework` was the only thing left in public still using them.
+--
+-- This restores the migration's intent. Measured impact on the restored
+-- snapshot, across the companies that actually have rework rows:
+--
+-- 19 employees in those companies
+-- 16 hold production_view -> read access unchanged
+-- 3 do NOT -> LOSE read access to rework (this is the point:
+-- the repo gates rework on production access)
+-- 16 hold production_delete -> gain delete, which no one could do before
+--
+-- Written to converge from either state: on a database that already matches the
+-- source (a fresh stack) the DROP/CREATE pairs are a no-op rewrite; on one
+-- carrying the drift they replace it. Policy names are already the standardized
+-- four in both.
+
+DROP POLICY IF EXISTS "SELECT" ON "public"."rework";
+DROP POLICY IF EXISTS "INSERT" ON "public"."rework";
+DROP POLICY IF EXISTS "UPDATE" ON "public"."rework";
+DROP POLICY IF EXISTS "DELETE" ON "public"."rework";
+
+CREATE POLICY "SELECT" ON "public"."rework"
+FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('production_view'))::text[])
+);
+
+CREATE POLICY "INSERT" ON "public"."rework"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('production_create'))::text[])
+);
+
+CREATE POLICY "UPDATE" ON "public"."rework"
+FOR UPDATE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('production_update'))::text[])
+);
+
+CREATE POLICY "DELETE" ON "public"."rework"
+FOR DELETE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('production_delete'))::text[])
+);
diff --git a/packages/database/supabase/migrations/20260807234512_webhooks-via-event-system.sql b/packages/database/supabase/migrations/20260807234512_webhooks-via-event-system.sql
new file mode 100644
index 0000000000..aef4852412
--- /dev/null
+++ b/packages/database/supabase/migrations/20260807234512_webhooks-via-event-system.sql
@@ -0,0 +1,122 @@
+-- Move webhooks off their own pg_net dispatch path (39 webhook_* triggers -> the
+-- `webhook` edge function) and onto the event system. All 13 tables already
+-- carried trg_event_async_* triggers, so every write was being observed twice.
+-- A webhook is now an eventSystemSubscription with handlerType 'WEBHOOK'.
+--
+-- Delivery moves from on-commit to queued (~3-5s) and from at-most-once to
+-- at-least-once; the customer-facing body is unchanged (see toWebhookBody).
+-- Also retires 3 of the ~7 net.http_post call sites, which pg_net blocks on RDS.
+
+-- ── 1. Derive a subscription from a webhook row ──────────────────────────────
+-- AFTER-ROW interceptor rather than a bespoke trigger: attach_event_trigger is
+-- how derived-row maintenance is wired here (cf. sync_create_customer_entries).
+-- AFTER because the subscription references the webhook row.
+
+CREATE OR REPLACE FUNCTION sync_webhook_subscription(
+ p_table TEXT,
+ p_operation TEXT,
+ p_new JSONB,
+ p_old JSONB
+)
+RETURNS VOID
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path TO 'public'
+AS $$
+DECLARE
+ v_ops TEXT[];
+ v_name TEXT;
+BEGIN
+ IF p_operation = 'DELETE' THEN
+ PERFORM delete_event_system_subscriptions_by_name(
+ p_old->>'companyId', 'webhook-' || (p_old->>'id')
+ );
+ RETURN;
+ END IF;
+
+ v_name := 'webhook-' || (p_new->>'id');
+
+ -- Clear first: `table` is editable and uniqueness is (companyId, name, table),
+ -- so an upsert would strand the old row and fire the webhook twice.
+ PERFORM delete_event_system_subscriptions_by_name(p_new->>'companyId', v_name);
+
+ v_ops := ARRAY[]::TEXT[];
+ IF (p_new->>'onInsert')::BOOLEAN THEN v_ops := array_append(v_ops, 'INSERT'); END IF;
+ IF (p_new->>'onUpdate')::BOOLEAN THEN v_ops := array_append(v_ops, 'UPDATE'); END IF;
+ IF (p_new->>'onDelete')::BOOLEAN THEN v_ops := array_append(v_ops, 'DELETE'); END IF;
+
+ IF array_length(v_ops, 1) IS NULL THEN
+ RETURN;
+ END IF;
+
+ PERFORM create_event_system_subscription(
+ v_name,
+ p_new->>'table',
+ p_new->>'companyId',
+ v_ops,
+ 'WEBHOOK',
+ jsonb_build_object('url', p_new->>'url', 'webhookId', p_new->>'id'),
+ '{}'::jsonb,
+ COALESCE((p_new->>'active')::BOOLEAN, false)
+ );
+END;
+$$;
+
+-- Also attaches the async statement triggers to `webhook`; harmless, since
+-- dispatch_event_batch() enqueues nothing unless a subscription watches it.
+SELECT attach_event_trigger(
+ 'webhook',
+ ARRAY[]::TEXT[],
+ ARRAY['sync_webhook_subscription']::TEXT[]
+);
+
+-- ── 2. Backfill subscriptions for existing webhooks ──────────────────────────
+-- A no-op update fires the interceptor, so the backfill can't drift from it.
+
+UPDATE "webhook" SET "url" = "url";
+
+-- ── 3. Retire the old dispatch path ──────────────────────────────────────────
+
+DROP TRIGGER IF EXISTS "customerInsertWebhook" ON "customer";
+DROP TRIGGER IF EXISTS "customerUpdateWebhook" ON "customer";
+DROP TRIGGER IF EXISTS "customerDeleteWebhook" ON "customer";
+DROP TRIGGER IF EXISTS "employeeInsertWebhook" ON "employee";
+DROP TRIGGER IF EXISTS "employeeUpdateWebhook" ON "employee";
+DROP TRIGGER IF EXISTS "employeeDeleteWebhook" ON "employee";
+DROP TRIGGER IF EXISTS "itemInsertWebhook" ON "item";
+DROP TRIGGER IF EXISTS "itemUpdateWebhook" ON "item";
+DROP TRIGGER IF EXISTS "itemDeleteWebhook" ON "item";
+DROP TRIGGER IF EXISTS "jobInsertWebhook" ON "job";
+DROP TRIGGER IF EXISTS "jobUpdateWebhook" ON "job";
+DROP TRIGGER IF EXISTS "jobDeleteWebhook" ON "job";
+DROP TRIGGER IF EXISTS "purchaseInvoiceInsertWebhook" ON "purchaseInvoice";
+DROP TRIGGER IF EXISTS "purchaseInvoiceUpdateWebhook" ON "purchaseInvoice";
+DROP TRIGGER IF EXISTS "purchaseInvoiceDeleteWebhook" ON "purchaseInvoice";
+DROP TRIGGER IF EXISTS "purchaseOrderInsertWebhook" ON "purchaseOrder";
+DROP TRIGGER IF EXISTS "purchaseOrderUpdateWebhook" ON "purchaseOrder";
+DROP TRIGGER IF EXISTS "purchaseOrderDeleteWebhook" ON "purchaseOrder";
+DROP TRIGGER IF EXISTS "quoteInsertWebhook" ON "quote";
+DROP TRIGGER IF EXISTS "quoteUpdateWebhook" ON "quote";
+DROP TRIGGER IF EXISTS "quoteDeleteWebhook" ON "quote";
+DROP TRIGGER IF EXISTS "receiptInsertWebhook" ON "receipt";
+DROP TRIGGER IF EXISTS "receiptUpdateWebhook" ON "receipt";
+DROP TRIGGER IF EXISTS "receiptDeleteWebhook" ON "receipt";
+DROP TRIGGER IF EXISTS "salesInvoiceInsertWebhook" ON "salesInvoice";
+DROP TRIGGER IF EXISTS "salesInvoiceUpdateWebhook" ON "salesInvoice";
+DROP TRIGGER IF EXISTS "salesInvoiceDeleteWebhook" ON "salesInvoice";
+DROP TRIGGER IF EXISTS "salesOrderInsertWebhook" ON "salesOrder";
+DROP TRIGGER IF EXISTS "salesOrderUpdateWebhook" ON "salesOrder";
+DROP TRIGGER IF EXISTS "salesOrderDeleteWebhook" ON "salesOrder";
+DROP TRIGGER IF EXISTS "salesRfqInsertWebhook" ON "salesRfq";
+DROP TRIGGER IF EXISTS "salesRfqUpdateWebhook" ON "salesRfq";
+DROP TRIGGER IF EXISTS "salesRfqDeleteWebhook" ON "salesRfq";
+DROP TRIGGER IF EXISTS "supplierInsertWebhook" ON "supplier";
+DROP TRIGGER IF EXISTS "supplierUpdateWebhook" ON "supplier";
+DROP TRIGGER IF EXISTS "supplierDeleteWebhook" ON "supplier";
+DROP TRIGGER IF EXISTS "supplierQuoteInsertWebhook" ON "supplierQuote";
+DROP TRIGGER IF EXISTS "supplierQuoteUpdateWebhook" ON "supplierQuote";
+DROP TRIGGER IF EXISTS "supplierQuoteDeleteWebhook" ON "supplierQuote";
+
+DROP FUNCTION IF EXISTS webhook_insert() CASCADE;
+DROP FUNCTION IF EXISTS webhook_update() CASCADE;
+DROP FUNCTION IF EXISTS webhook_delete() CASCADE;
diff --git a/packages/dev/AGENTS.md b/packages/dev/AGENTS.md
index 149caadb04..5f714974fa 100644
--- a/packages/dev/AGENTS.md
+++ b/packages/dev/AGENTS.md
@@ -30,7 +30,8 @@ pnpm --filter @carbon/dev typecheck # tsgo --noEmit
## Key Patterns
-- **Commands**: `up`, `down` (`--purge` releases the slot), `new`, `init`, `remove`, `list`, `status`, `reset`, `migrate`, `copy` (env sync), `reload` (`crbn reload <service...>` → `docker compose up -d --force-recreate` a subset, applying compose/`.env.local` edits without restarting the app dev servers)
+- **Commands**: `up`, `down` (`--purge` releases the slot), `new`, `init`, `remove`, `list`, `status`, `reset`, `migrate`, `restore`, `copy` (env sync), `reload` (`crbn reload <service...>` → `docker compose up -d --force-recreate` a subset, applying compose/`.env.local` edits without restarting the app dev servers)
+- **Restore** (`commands/restore.ts`): `crbn restore <file>` wraps `scripts/restore-database.sh` (the SQL is deliberately NOT ported) and adds worktree/`PORT_DB` resolution, a confirmation gate, and the trailing `applyMigrations` + `db:types`. It deliberately does NOT boot a postgres-only stack the way `crbn migrate` does — a restore rewrites `auth`/`storage`, whose schemas GoTrue and Storage build via their own migrations, so it requires a fully booted stack (`serviceSchemasReady` probes for GoTrue's `auth.users.email_confirmed_at` AND `storage.objects`/`storage.buckets` — the restore script's `to_regclass` guards mean a missing Storage schema would otherwise let the restore finish with no buckets seeded) and refuses otherwise — the backup carries the SOURCE schema, which is usually behind the branch. **`--scrub-emails` defaults ON here, inverting the script's opt-in default**, so a restore cannot drop real customer addresses into a local DB unless asked. By default the script truncates `storage.objects` (kept rows would point at files that live only in the source environment's backend, so downloads 404); pass `--keep-storage-objects` to retain them and the dump's buckets when you need realistic storage metadata, e.g. profiling storage RLS.
- **Stack boot** (`commands/up.ts`): Docker Compose → wait Postgres → migrations → regen types → spawn apps → portless aliases
- **Provision** (`commands/init.ts`): `crbn init` provisions an already-created worktree (canonical slug + env sync + skills) to match a `crbn checkout`; shared by `new`, the bash `checkout` post-create hook, and Conductor's `setup` (`.conductor/settings.toml`). It does NOT boot the stack — `crbn up` still mints ports/`.env.local`.
- **Worktree** (`worktree.ts`): `resolveSlug()`, `canonicalSlug()` (branch-derived `<repoBase>-<branch>`), `getWorktreeRoot()`, `projectName()`, `ensureSlugAvailable()`
diff --git a/packages/dev/bin/crbn b/packages/dev/bin/crbn
index 3111bc06e8..a234f7ade7 100755
--- a/packages/dev/bin/crbn
+++ b/packages/dev/bin/crbn
@@ -450,6 +450,7 @@ crbn — Carbon dev CLI
crbn reset Wipe volumes + redis, then up.
crbn status Port assignment + container health.
crbn migrate Apply DB migrations (loads .env.local).
+ crbn restore <file> Restore a prod backup, then apply migrations it predates.
crbn reload <service...> Recreate compose services (apply compose/env edits, apps untouched).
Files:
@@ -481,7 +482,7 @@ case "$cmd" in
checkout)
cmd_checkout "$@"
;;
- copy|env|up|down|reset|status|migrate|new|init|list|remove|reload|complete)
+ copy|env|up|down|reset|status|migrate|restore|new|init|list|remove|reload|complete)
delegate_ts "$cmd" "$@"
;;
*)
diff --git a/packages/dev/src/commands/restore.test.ts b/packages/dev/src/commands/restore.test.ts
new file mode 100644
index 0000000000..4c0dc268ed
--- /dev/null
+++ b/packages/dev/src/commands/restore.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from "vitest";
+import { buildRestoreEnv } from "./restore.js";
+
+// The restore itself is ~200 lines of SQL in scripts/restore-database.sh and is
+// not unit-testable. What IS testable — and what a mistake here would actually
+// cost — is the flag→env mapping: getting the scrub wrong silently loads real
+// production email addresses into a local database.
+describe("buildRestoreEnv", () => {
+ it("scrubs emails by default, inverting the script's opt-in default", () => {
+ expect(buildRestoreEnv({}).SCRUB_EMAILS).toBe("1");
+ });
+
+ it("OMITS the key when opted out — the script treats any non-empty value as true", () => {
+ const env = buildRestoreEnv({ scrubEmails: false });
+ // "0" would enable scrubbing, not disable it.
+ expect(env).not.toHaveProperty("SCRUB_EMAILS");
+ });
+
+ it("defaults to local mode so the restore cannot talk to production services", () => {
+ expect(buildRestoreEnv({}).RESTORE_MODE).toBe("local");
+ expect(buildRestoreEnv({ mode: "prod" }).RESTORE_MODE).toBe("prod");
+ });
+
+ it("passes admin credentials through only when supplied", () => {
+ expect(buildRestoreEnv({})).not.toHaveProperty("ADMIN_EMAIL");
+ expect(buildRestoreEnv({})).not.toHaveProperty("ADMIN_PASSWORD");
+
+ const env = buildRestoreEnv({
+ adminEmail: "[email protected]",
+ adminPassword: "s3cret"
+ });
+ expect(env.ADMIN_EMAIL).toBe("[email protected]");
+ expect(env.ADMIN_PASSWORD).toBe("s3cret");
+ });
+
+ it("does not leak an empty ADMIN_EMAIL that would make the script look up ''", () => {
+ expect(buildRestoreEnv({ adminEmail: "" })).not.toHaveProperty(
+ "ADMIN_EMAIL"
+ );
+ });
+
+ it("clears storage metadata unless explicitly asked to keep it", () => {
+ // Default matters: kept rows point at files that only exist in the source
+ // environment's backend, so every download 404s.
+ expect(buildRestoreEnv({})).not.toHaveProperty("KEEP_STORAGE_OBJECTS");
+ expect(buildRestoreEnv({ keepStorageObjects: false })).not.toHaveProperty(
+ "KEEP_STORAGE_OBJECTS"
+ );
+ expect(
+ buildRestoreEnv({ keepStorageObjects: true }).KEEP_STORAGE_OBJECTS
+ ).toBe("1");
+ });
+});
diff --git a/packages/dev/src/commands/restore.ts b/packages/dev/src/commands/restore.ts
new file mode 100644
index 0000000000..cba4f7bfe2
--- /dev/null
+++ b/packages/dev/src/commands/restore.ts
@@ -0,0 +1,183 @@
+import { existsSync } from "node:fs";
+import { cancel, intro, log, outro, tasks } from "@clack/prompts";
+import { config as loadDotenv } from "dotenv";
+import { execa } from "execa";
+import { isAbsolute, join, resolve } from "pathe";
+import { requireNumberEnv, tryConnect } from "../helpers.js";
+import { confirmRestore } from "../prompts.js";
+import {
+ applyMigrations,
+ serviceSchemasReady
+} from "../services/migrations.js";
+import { getWorktreeRoot } from "../worktree.js";
+
+export type RestoreMode = "local" | "prod";
+
+export type RestoreOptions = {
+ file: string;
+ scrubEmails?: boolean;
+ adminEmail?: string;
+ adminPassword?: string;
+ mode?: RestoreMode;
+ keepStorageObjects?: boolean;
+ migrate?: boolean;
+ regen?: boolean;
+ yes?: boolean;
+};
+
+const SCRIPT = "scripts/restore-database.sh";
+
+/**
+ * Build the environment the restore script reads.
+ *
+ * `SCRUB_EMAILS` is opt-IN in the script but defaults ON here: a dev CLI should
+ * not drop real customer email addresses into a local database unless asked.
+ * The script treats any non-empty value as true, so opting out means omitting
+ * the key entirely rather than setting "0".
+ */
+export function buildRestoreEnv(
+ opts: Pick<
+ RestoreOptions,
+ | "scrubEmails"
+ | "adminEmail"
+ | "adminPassword"
+ | "mode"
+ | "keepStorageObjects"
+ >
+): Record<string, string> {
+ const env: Record<string, string> = {
+ RESTORE_MODE: opts.mode ?? "local"
+ };
+ if (opts.scrubEmails !== false) env.SCRUB_EMAILS = "1";
+ if (opts.adminEmail) env.ADMIN_EMAIL = opts.adminEmail;
+ if (opts.adminPassword) env.ADMIN_PASSWORD = opts.adminPassword;
+ if (opts.keepStorageObjects) env.KEEP_STORAGE_OBJECTS = "1";
+ return env;
+}
+
+export async function restore(opts: RestoreOptions) {
+ intro("Carbon · dev restore");
+
+ const root = await getWorktreeRoot();
+
+ const backup = isAbsolute(opts.file) ? opts.file : resolve(opts.file);
+ if (!existsSync(backup)) {
+ cancel(`backup file not found: ${backup}`);
+ process.exit(1);
+ }
+ if (!existsSync(join(root, SCRIPT))) {
+ cancel(`${SCRIPT} is missing from this worktree`);
+ process.exit(1);
+ }
+
+ const envLocal = join(root, ".env.local");
+ if (existsSync(envLocal)) loadDotenv({ path: envLocal, override: true });
+ loadDotenv({ path: join(root, ".env"), override: false });
+
+ let portDb: number;
+ try {
+ portDb = requireNumberEnv("PORT_DB");
+ } catch {
+ cancel("PORT_DB not set — run `crbn up` once to provision this worktree");
+ process.exit(1);
+ }
+
+ const mode = opts.mode ?? "local";
+ // Warned unconditionally: --yes also skips the confirmation, so gating this on
+ // !yes made the most dangerous invocation the silent one.
+ if (mode === "prod") {
+ log.warn(
+ "--mode prod skips ALL localization: webhooks, integrations and printer routes stay pointed at the source environment"
+ );
+ }
+ if (opts.scrubEmails === false) {
+ log.warn(
+ "--no-scrub-emails: real email addresses from the backup will be present locally"
+ );
+ }
+
+ if (
+ !opts.yes &&
+ !(await confirmRestore({ port: portDb, file: backup, mode }))
+ ) {
+ cancel("restore aborted");
+ process.exit(0);
+ }
+
+ // Deliberately NOT booting a postgres-only stack the way `crbn migrate` does.
+ // A restore rewrites `auth`/`storage` too, and those schemas are built by
+ // GoTrue's and Storage's own migrations when THOSE containers boot. Against a
+ // postgres-only stack the dump's `CREATE TABLE auth.users` no-ops onto the
+ // image's stub, and the restore fails late — after the data has landed but
+ // before the email scrub — leaving unscrubbed production addresses on disk.
+ if (!(await tryConnect("127.0.0.1", portDb, 500))) {
+ cancel("postgres is not reachable — run `crbn up` first, then retry");
+ process.exit(1);
+ }
+ if (!(await serviceSchemasReady(portDb))) {
+ cancel(
+ "the auth/storage schemas are not initialized (postgres is up but GoTrue/Storage are not) — run `crbn up` so the full stack boots once, then retry"
+ );
+ process.exit(1);
+ }
+
+ await runRestore(root, backup, portDb, opts);
+ outro("done");
+}
+
+async function runRestore(
+ root: string,
+ backup: string,
+ portDb: number,
+ opts: RestoreOptions
+) {
+ // stdio inherit: the script streams its own progress and can run for minutes.
+ await execa("bash", [join(root, SCRIPT), backup], {
+ cwd: root,
+ stdio: "inherit",
+ env: buildRestoreEnv(opts)
+ });
+
+ const shouldMigrate = opts.migrate !== false;
+ const shouldRegen = opts.regen !== false;
+ if (!shouldMigrate && !shouldRegen) return;
+
+ await tasks([
+ ...(shouldMigrate
+ ? [
+ {
+ // The dump carries the SOURCE environment's schema, which is
+ // usually behind this branch. Without this the DB is left at prod's
+ // migration state and app code compiled from newer types breaks.
+ title: "Apply migrations the backup predates",
+ task: async () => {
+ const r = await applyMigrations(root, portDb);
+ return r.applied
+ ? "migrations applied"
+ : "schema already up to date";
+ }
+ }
+ ]
+ : []),
+ ...(shouldRegen
+ ? [
+ {
+ title: "Regenerate types",
+ task: async () => {
+ await execa("pnpm", ["db:types"], { cwd: root });
+ return "types refreshed";
+ }
+ }
+ ]
+ : [])
+ ]);
+
+ if (shouldRegen) {
+ // These types now describe the RESTORED database, which carries whatever
+ // the source environment accumulated outside the migration stream. Commit
+ // them and that drift enters the repo's type surface.
+ log.warn(
+ "types were regenerated from the restored snapshot — do NOT commit them; run `pnpm db:types` against a migration-built database before committing"
+ );
+ }
+}
diff --git a/packages/dev/src/main.ts b/packages/dev/src/main.ts
index 202529cd10..2ed60b01d1 100644
--- a/packages/dev/src/main.ts
+++ b/packages/dev/src/main.ts
@@ -8,6 +8,7 @@ import { newWorktree } from "./commands/new.js";
import { reload } from "./commands/reload.js";
import { removeWorktreeCmd } from "./commands/remove.js";
import { reset } from "./commands/reset.js";
+import { type RestoreMode, restore } from "./commands/restore.js";
import { status } from "./commands/status.js";
import { up } from "./commands/up.js";
@@ -163,6 +164,89 @@ const main = defineCommand({
run: ({ args }) =>
args.force ? reset() : migrate({ regen: args.regen !== false })
}),
+ restore: defineCommand({
+ meta: {
+ description:
+ "Restore a production backup into this worktree's database, then apply the migrations it predates (wraps scripts/restore-database.sh)"
+ },
+ args: {
+ file: {
+ type: "positional",
+ required: true,
+ description: "Path to a .backup cluster dump or .dump archive"
+ },
+ "scrub-emails": {
+ type: "boolean",
+ default: true,
+ description:
+ "Rewrite every email address to @example.test so production addresses can never be contacted locally (--no-scrub-emails to keep them)"
+ },
+ "admin-email": {
+ type: "string",
+ description:
+ "Your email in the backup — upgraded to Admin in the companies it already belongs to, with the password reset locally"
+ },
+ "admin-password": {
+ type: "string",
+ description: "Local password for --admin-email (default: localpass)"
+ },
+ mode: {
+ type: "string",
+ default: "local",
+ description:
+ "'local' points config at the local stack and deactivates webhooks/integrations/printer routes; 'prod' restores as-is"
+ },
+ "keep-storage-objects": {
+ type: "boolean",
+ default: false,
+ description:
+ "Keep the backup's storage.objects rows and buckets instead of clearing them. Downloads still 404 (the bytes are not in the DB); use when you need realistic storage metadata, e.g. profiling storage RLS"
+ },
+ migrate: {
+ type: "boolean",
+ default: true,
+ description:
+ "Apply migrations the backup predates (use --no-migrate to leave the schema at the backup's state)"
+ },
+ regen: {
+ type: "boolean",
+ default: true,
+ description: "Regenerate db types afterwards (use --no-regen to skip)"
+ },
+ yes: {
+ type: "boolean",
+ default: false,
+ description: "Skip the confirmation prompt"
+ }
+ },
+ run: ({ args }) => {
+ // Explicit rather than coercing anything non-"prod" to "local": a typo
+ // in a flag that controls whether production services stay wired up
+ // must not silently pick a mode.
+ const mode = String(args.mode ?? "local");
+ if (mode !== "local" && mode !== "prod") {
+ console.error(`--mode must be 'local' or 'prod' (got '${mode}')`);
+ process.exit(1);
+ }
+ return restore({
+ file: String(args.file),
+ scrubEmails: args["scrub-emails"] !== false,
+ adminEmail:
+ typeof args["admin-email"] === "string"
+ ? args["admin-email"]
+ : undefined,
+ adminPassword:
+ typeof args["admin-password"] === "string"
+ ? args["admin-password"]
+ : undefined,
+ mode: mode as RestoreMode,
+ keepStorageObjects: args["keep-storage-objects"] === true,
+ migrate: args.migrate !== false,
+ regen: args.regen !== false,
+ yes: args.yes === true
+ });
+ }
+ }),
new: defineCommand({
meta: {
description:
diff --git a/packages/dev/src/prompts.ts b/packages/dev/src/prompts.ts
index b230dbd38c..0408079fe3 100644
--- a/packages/dev/src/prompts.ts
+++ b/packages/dev/src/prompts.ts
@@ -202,6 +202,20 @@ export async function confirmReset(projectName: string): Promise<boolean> {
return ok as boolean;
}
+export async function confirmRestore(opts: {
+ port: number;
+ file: string;
+ mode: string;
+}): Promise<boolean> {
+ if (process.env.CARBON_DEV_YES === "1") return true;
+ const ok = await confirm({
+ message: `Replace the database on 127.0.0.1:${pc.bold(String(opts.port))} with ${pc.bold(opts.file)}? (mode: ${opts.mode} — the current data, including any seeded test data, is wiped)`,
+ initialValue: false
+ });
+ if (isCancel(ok)) return false;
+ return ok as boolean;
+}
+
export async function confirmRemove(opts: {
branchOrPath: string;
hasStack: boolean;
diff --git a/packages/dev/src/services/migrations.ts b/packages/dev/src/services/migrations.ts
index 29e34b4f11..804f1d7439 100644
--- a/packages/dev/src/services/migrations.ts
+++ b/packages/dev/src/services/migrations.ts
@@ -236,12 +236,44 @@ async function repairStaleMigrations(
// Config row (pg_net push targets)
// ---------------------------------------------------------------------------
+/**
+ * Whether the Supabase service schemas are initialized, not just present.
+ *
+ * GoTrue and Storage build `auth`/`storage` through their OWN migrations, which
+ * only run when those containers boot. A postgres-only stack leaves stubs — and
+ * restoring a dump into that state silently no-ops the dump's `CREATE TABLE
+ * auth.users` (the stub already exists), leaving a users table missing most of
+ * its columns. `email_confirmed_at` is GoTrue's, so its presence proves GoTrue
+ * migrated rather than that the table merely exists.
+ *
+ * Storage is checked separately rather than assumed from GoTrue: the restore
+ * script guards its storage TRUNCATEs with `to_regclass` so a partially booted
+ * stack can't abort the run, which means a missing `storage.objects` would let
+ * the restore finish "successfully" with no buckets seeded. Both services must
+ * have booted.
+ */
+export async function serviceSchemasReady(dbPort: number): Promise<boolean> {
+ return withClient(dbPort, async (c) => {
+ const r = await c.query(
+ `SELECT to_regclass('auth.users') IS NOT NULL
+ AND to_regclass('storage.objects') IS NOT NULL
+ AND to_regclass('storage.buckets') IS NOT NULL
+ AND EXISTS (
+ SELECT 1 FROM information_schema.columns
+ WHERE table_schema = 'auth' AND table_name = 'users'
+ AND column_name = 'email_confirmed_at'
+ ) AS ready`
+ );
+ return r.rows[0]?.ready === true;
+ });
+}
+
// The singleton "config" row is what SECURITY DEFINER functions
-// (wake_event_queue, webhook_insert/update/delete) read to POST to edge
+// (wake_event_queue and the other pg_net callers) read to POST to edge
// functions via pg_net. Without it those pushes silently no-op, so the
-// event-queue wake and local webhooks never fire in dev. `apiUrl` must be the
-// in-network Kong URL — pg_net runs inside the postgres container, which
-// can't reach host ports.
+// event-queue wake never fires in dev — and since webhooks now ride the event
+// system, they don't either. `apiUrl` must be the in-network Kong URL — pg_net
+// runs inside the postgres container, which can't reach host ports.
export async function ensureConfigRow(
dbPort: number,
anonKey: string
diff --git a/packages/jobs/AGENTS.md b/packages/jobs/AGENTS.md
index f4f1d8f8af..c44997c4f8 100644
--- a/packages/jobs/AGENTS.md
+++ b/packages/jobs/AGENTS.md
@@ -42,7 +42,7 @@ pnpm --filter @carbon/jobs dev:jobs # Start local Inngest dev server
| Handler | Event | Purpose |
|---------|-------|---------|
-| WEBHOOK | `carbon/event-webhook` | POST to configured URL |
+| WEBHOOK | `carbon/event-webhook` | POST to configured URL. Backs the user-facing Settings → Webhooks feature; its body `{type, record, old?, companyId, table}` is a public contract — change `toWebhookBody` only with the docs and `webhook.test.ts` |
| SYNC | `carbon/event-sync` | Accounting sync (Xero) |
| SEARCH | `carbon/event-search` | Upsert/delete search index |
| AUDIT | `carbon/event-audit` | Per-company audit log |
diff --git a/packages/jobs/src/inngest/functions/events/queue.ts b/packages/jobs/src/inngest/functions/events/queue.ts
index aa0a41e02f..fae79d41c1 100644
--- a/packages/jobs/src/inngest/functions/events/queue.ts
+++ b/packages/jobs/src/inngest/functions/events/queue.ts
@@ -109,6 +109,7 @@ export const eventQueueFunction = inngest.createFunction(
data: {
msgId: job.msg_id,
url: job.message.handlerConfig.url,
+ companyId: job.message.companyId,
config: job.message.handlerConfig,
data: job.message.event
}
diff --git a/packages/jobs/src/inngest/functions/events/webhook-body.test.ts b/packages/jobs/src/inngest/functions/events/webhook-body.test.ts
new file mode 100644
index 0000000000..30a3fb7344
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/events/webhook-body.test.ts
@@ -0,0 +1,149 @@
+import { describe, expect, it } from "vitest";
+import { toWebhookBody } from "./webhook-body.ts";
+
+// PUBLIC contract — these cases mirror the deleted `webhook` edge function
+// (git history: packages/database/supabase/functions/webhook/index.ts), which
+// is what customer endpoints actually received.
+describe("toWebhookBody", () => {
+ const row = { id: "c1", name: "Acme", companyId: "co1" };
+ const prev = { id: "c1", name: "Acme Inc", companyId: "co1" };
+
+ it("INSERT sends the new row as `record`, with no `old` key", () => {
+ const body = toWebhookBody(
+ { table: "customer", operation: "INSERT", new: row, old: null },
+ "co1",
+ "42"
+ );
+ expect(body).toEqual({
+ type: "INSERT",
+ record: row,
+ companyId: "co1",
+ table: "customer",
+ eventId: "42"
+ });
+ expect(body).not.toHaveProperty("old");
+ });
+
+ it("UPDATE sends both `record` (new) and `old`", () => {
+ expect(
+ toWebhookBody(
+ { table: "customer", operation: "UPDATE", new: row, old: prev },
+ "co1",
+ "42"
+ )
+ ).toEqual({
+ type: "UPDATE",
+ record: row,
+ old: prev,
+ companyId: "co1",
+ table: "customer",
+ eventId: "42"
+ });
+ });
+
+ it("DELETE takes `record` from OLD and omits `old`", () => {
+ // Getting this wrong hands consumers `record: null` on every delete.
+ const body = toWebhookBody(
+ { table: "customer", operation: "DELETE", new: null, old: row },
+ "co1",
+ "42"
+ );
+ expect(body).toEqual({
+ type: "DELETE",
+ record: row,
+ companyId: "co1",
+ table: "customer",
+ eventId: "42"
+ });
+ expect(body).not.toHaveProperty("old");
+ });
+
+ it("TRUNCATE behaves like DELETE", () => {
+ expect(
+ toWebhookBody(
+ { table: "customer", operation: "TRUNCATE", new: null, old: row },
+ "co1",
+ "42"
+ )
+ ).toEqual({
+ type: "TRUNCATE",
+ record: row,
+ companyId: "co1",
+ table: "customer",
+ eventId: "42"
+ });
+ });
+
+ it("never emits an `old` key for UPDATE when old is missing", () => {
+ const body = toWebhookBody(
+ { table: "customer", operation: "UPDATE", new: row, old: null },
+ "co1",
+ "42"
+ );
+ expect(body).toEqual({
+ type: "UPDATE",
+ record: row,
+ companyId: "co1",
+ table: "customer",
+ eventId: "42"
+ });
+ expect(body).not.toHaveProperty("old");
+ });
+
+ it("normalises a missing row to null rather than undefined", () => {
+ // undefined would drop `record` from the JSON body entirely.
+ const body = toWebhookBody(
+ { table: "customer", operation: "INSERT" },
+ "co1",
+ "42"
+ );
+ expect(body.record).toBeNull();
+ expect(Object.keys(body)).toContain("record");
+ });
+
+ it("carries the event's table, not the subscription's", () => {
+ expect(
+ toWebhookBody(
+ { table: "salesOrder", operation: "INSERT", new: row },
+ "co2",
+ "42"
+ )
+ ).toMatchObject({ table: "salesOrder", companyId: "co2" });
+ });
+
+ it("distinguishes two genuine UPDATEs to the same record", () => {
+ // The reason eventId exists. Delivery is at-least-once, so consumers must
+ // de-dup — but `type` + `record.id` is identical for every update to a row,
+ // so de-duping on those would silently drop real changes. Only eventId
+ // separates them.
+ const first = toWebhookBody(
+ { table: "customer", operation: "UPDATE", new: prev, old: row },
+ "co1",
+ "100"
+ );
+ const second = toWebhookBody(
+ { table: "customer", operation: "UPDATE", new: row, old: prev },
+ "co1",
+ "101"
+ );
+ expect(first.type).toBe(second.type);
+ expect((first.record as { id: string }).id).toBe(
+ (second.record as { id: string }).id
+ );
+ expect(first.eventId).not.toBe(second.eventId);
+ });
+
+ it("gives a retried delivery the same eventId", () => {
+ // eventId is the pgmq message id, which is also the Inngest idempotency
+ // key — retries of one change reuse it, which is what makes it usable as a
+ // de-duplication key rather than just a nonce.
+ const attempt = () =>
+ toWebhookBody(
+ { table: "customer", operation: "INSERT", new: row },
+ "co1",
+ "77"
+ );
+ expect(attempt()).toEqual(attempt());
+ expect(attempt().eventId).toBe("77");
+ });
+});
diff --git a/packages/jobs/src/inngest/functions/events/webhook-body.ts b/packages/jobs/src/inngest/functions/events/webhook-body.ts
new file mode 100644
index 0000000000..73e7ef44d6
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/events/webhook-body.ts
@@ -0,0 +1,74 @@
+import { z } from "zod";
+
+// Separate from webhook.ts so the contract below is testable — the handler
+// imports client.server, which validates the server env at module load.
+
+const eventSchema = z.object({
+ table: z.string(),
+ operation: z.enum(["INSERT", "UPDATE", "DELETE", "TRUNCATE"]),
+ recordId: z.string().optional(),
+ new: z.record(z.any()).nullable().optional(),
+ old: z.record(z.any()).nullable().optional(),
+ timestamp: z.string().optional()
+});
+
+export const webhookPayloadSchema = z.object({
+ url: z.string().url(),
+ companyId: z.string(),
+ msgId: z.union([z.number(), z.string()]),
+ data: eventSchema,
+ config: z
+ .object({
+ headers: z.record(z.string()).optional(),
+ webhookId: z.string().optional()
+ })
+ .passthrough()
+});
+
+export type WebhookPayload = z.infer<typeof webhookPayloadSchema>;
+export type WebhookEvent = z.infer<typeof eventSchema>;
+
+/**
+ * Map a queue event onto the body external consumers receive. PUBLIC contract —
+ * see docs/content/docs/building/webhooks.mdx and webhook-body.test.ts.
+ *
+ * INSERT { type, record: NEW, companyId, table, eventId }
+ * UPDATE { type, record: NEW, old: OLD, companyId, table, eventId }
+ * DELETE { type, record: OLD, companyId, table, eventId }
+ *
+ * DELETE is the trap: the queue event carries the row under `old` (its `new` is
+ * null), but consumers expect it as `record`.
+ *
+ * `eventId` is the only addition to what the pg_net path sent, and it exists
+ * because delivery is now at-least-once: consumers need something to de-dup a
+ * retried delivery on, and `type` + `record.id` cannot serve — two genuine
+ * updates to the same row share both, so de-duping on them drops real changes.
+ * It is the pgmq message id, which is stable across an event's retries (it is
+ * also the Inngest idempotency key) and distinct per change.
+ */
+export function toWebhookBody(
+ event: WebhookEvent,
+ companyId: string,
+ eventId: string
+): {
+ type: string;
+ record: Record<string, unknown> | null;
+ old?: Record<string, unknown>;
+ companyId: string;
+ table: string;
+ eventId: string;
+} {
+ const isRemoval =
+ event.operation === "DELETE" || event.operation === "TRUNCATE";
+ const record = (isRemoval ? event.old : event.new) ?? null;
+
+ // `old` must be absent, not null, for non-UPDATE operations.
+ return {
+ type: event.operation,
+ record,
+ ...(event.operation === "UPDATE" && event.old ? { old: event.old } : {}),
+ companyId,
+ table: event.table,
+ eventId
+ };
+}
diff --git a/packages/jobs/src/inngest/functions/events/webhook.ts b/packages/jobs/src/inngest/functions/events/webhook.ts
index ef66d57a80..a3e3408a34 100644
--- a/packages/jobs/src/inngest/functions/events/webhook.ts
+++ b/packages/jobs/src/inngest/functions/events/webhook.ts
@@ -1,38 +1,64 @@
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
import axios from "axios";
-import { z } from "zod";
import { inngest } from "../../client.ts";
+import { toWebhookBody, webhookPayloadSchema } from "./webhook-body.ts";
-const webhookPayloadSchema = z.object({
- url: z.string().url(),
- data: z.any(),
- config: z
- .object({
- headers: z.record(z.string()).optional()
- })
- .passthrough()
-});
-
-export type WebhookPayload = z.infer<typeof webhookPayloadSchema>;
+const RETRIES = 3;
export const webhookFunction = inngest.createFunction(
{
id: "event-handler-webhook",
- retries: 3,
+ retries: RETRIES,
idempotency: "event.data.msgId",
+ // One in-flight delivery per record, so a rapid update burst can't reorder
+ // on the wire. limit must be >= 1 -- 0 is no capacity, not unlimited, and
+ // parks every run in QUEUED forever.
concurrency: {
- limit: 0,
+ limit: 1,
key: "event.data.data.table + '-' + event.data.data.recordId"
}
},
{ event: "carbon/event-webhook" },
- async ({ event, step, logger }) => {
+ async ({ event, step, logger, attempt }) => {
const payload = webhookPayloadSchema.parse(event.data);
+ const body = toWebhookBody(
+ payload.data,
+ payload.companyId,
+ String(payload.msgId)
+ );
+ const webhookId = payload.config.webhookId;
await step.run("send-webhook", async () => {
- logger.info(`Firing webhook to ${payload.url}`);
- await axios.post(payload.url, payload.data, {
- headers: payload.config.headers
- });
+ // Never log payload.url — the docs tell customers to treat the URL itself
+ // as the secret (an unguessable token in the path or query), since Carbon
+ // does not sign webhooks. webhookId identifies it without leaking that.
+ logger.info(
+ `Firing ${body.type} webhook ${webhookId ?? "<unknown>"} for ${payload.data.table}`
+ );
+
+ try {
+ await axios.post(payload.url, body, {
+ headers: {
+ "Content-Type": "application/json",
+ ...payload.config.headers
+ }
+ });
+ } catch (err) {
+ // Count one failure per event, not per attempt — otherwise retries
+ // inflate errorCount 4x for a single undelivered event.
+ if (webhookId && attempt >= RETRIES) {
+ await getCarbonServiceRole().rpc("increment_webhook_error", {
+ webhook_id: webhookId
+ });
+ }
+ throw err;
+ }
+
+ if (webhookId) {
+ await getCarbonServiceRole().rpc("increment_webhook_success", {
+ webhook_id: webhookId
+ });
+ }
});
}
);
diff --git a/packages/jobs/src/inngest/functions/events/workflow.ts b/packages/jobs/src/inngest/functions/events/workflow.ts
index 48d7939216..cfd856959b 100644
--- a/packages/jobs/src/inngest/functions/events/workflow.ts
+++ b/packages/jobs/src/inngest/functions/events/workflow.ts
@@ -14,7 +14,7 @@ export const workflowFunction = inngest.createFunction(
retries: 3,
idempotency: "event.data.msgId",
concurrency: {
- limit: 0,
+ limit: 1,
key: "event.data.data.table + '-' + event.data.data.recordId"
}
},
diff --git a/packages/jobs/src/inngest/functions/tasks/reschedule-job.ts b/packages/jobs/src/inngest/functions/tasks/reschedule-job.ts
index f362f04cd2..a0732ea55f 100644
--- a/packages/jobs/src/inngest/functions/tasks/reschedule-job.ts
+++ b/packages/jobs/src/inngest/functions/tasks/reschedule-job.ts
@@ -10,7 +10,7 @@ export const rescheduleJobFunction = inngest.createFunction(
id: "schedule-job",
retries: 3,
concurrency: {
- limit: 0,
+ limit: 1,
key: "event.data.companyId"
}
},
diff --git a/packages/lib/src/events.ts b/packages/lib/src/events.ts
index 80cf8d4cab..1e250a73bc 100644
--- a/packages/lib/src/events.ts
+++ b/packages/lib/src/events.ts
@@ -357,6 +357,9 @@ export type Events = {
data: {
msgId: number;
url: string;
+ // Part of the outbound body, but not on the event — forwarded off the
+ // queue message by the drainer.
+ companyId: string;
config: {
headers?: Record<string, string>;
[key: string]: unknown;
diff --git a/scripts/restore-database.sh b/scripts/restore-database.sh
index 95f67301a8..edb1c8be4b 100644
--- a/scripts/restore-database.sh
+++ b/scripts/restore-database.sh
@@ -25,6 +25,13 @@
# contact, invite, companySettings, quote) to @example.test
# so no production emails can be contacted from local.
# The ADMIN_EMAIL account is preserved so you can still log in.
+# KEEP_STORAGE_OBJECTS
+# set to any non-empty value to KEEP the dump's
+# storage.objects/prefixes rows and its buckets instead of
+# clearing them. File downloads still 404 (the bytes live in
+# the source environment's backend, not the DB) — this is for
+# work that needs realistic storage metadata volume, such as
+# profiling RLS on storage listings.
# RESTORE_MODE 'local' (default) or 'prod'.
# local: after restoring, localize environment-sensitive state —
# re-seed the config row to local Kong, deactivate webhooks /
@@ -47,6 +54,7 @@ set -euo pipefail
ADMIN_EMAIL="${ADMIN_EMAIL:-}"
ADMIN_PASSWORD="${ADMIN_PASSWORD:-localpass}"
SCRUB_EMAILS="${SCRUB_EMAILS:-}"
+KEEP_STORAGE_OBJECTS="${KEEP_STORAGE_OBJECTS:-}"
RESTORE_MODE="${RESTORE_MODE:-local}"
if [[ "$RESTORE_MODE" != "local" && "$RESTORE_MODE" != "prod" ]]; then
echo "RESTORE_MODE must be 'local' or 'prod' (got '$RESTORE_MODE')" >&2
@@ -103,7 +111,19 @@ $PSQL_PG -At -c "
WHERE n.nspname='public' AND t.typcategory IN ('E','C')
UNION ALL SELECT format('DROP SEQUENCE IF EXISTS public.%I CASCADE;', sequencename) FROM pg_sequences WHERE schemaname='public'
" | $PSQL_PG -v ON_ERROR_STOP=0 >/dev/null
-$PSQL_PG -c "TRUNCATE auth.users CASCADE; TRUNCATE storage.objects CASCADE; TRUNCATE storage.buckets CASCADE;" >/dev/null
+# Guarded the same way as the storage reset in step 5: on a stack that has only
+# ever booted postgres (e.g. `crbn restore` right after a `crbn reset`), the
+# service schemas do not exist yet -- storage.objects is created by the storage
+# service's own migrations, not by the postgres image. A bare TRUNCATE there
+# aborts the whole restore under `set -e`.
+$PSQL_PG -c "
+DO \$\$
+BEGIN
+ IF to_regclass('auth.users') IS NOT NULL THEN TRUNCATE auth.users CASCADE; END IF;
+ IF to_regclass('storage.objects') IS NOT NULL THEN TRUNCATE storage.objects CASCADE; END IF;
+ IF to_regclass('storage.buckets') IS NOT NULL THEN TRUNCATE storage.buckets CASCADE; END IF;
+END \$\$;
+" >/dev/null
# ── 3. Restore ───────────────────────────────────────────────────────────────
# Supports both plain-text SQL dumps (Supabase cluster .backup files) and
# custom-format pg_dump archives (.dump, magic bytes 'PGDMP').
@@ -173,10 +193,20 @@ ON CONFLICT (queue_name) DO NOTHING;
# the actual file bytes live in prod's storage backend, not in the DB — so
# those rows would point at files that don't exist locally and downloads
# would 404. Clear the metadata, keep/create the buckets the app expects.
-echo "▶ Resetting storage metadata + ensuring buckets (fixed + per-company)"
-# Guard each TRUNCATE with to_regclass so a table that doesn't exist in this
-# Supabase version can't abort — and thereby roll back — the whole block.
-$PSQL_SA -v ON_ERROR_STOP=0 -c "
+if [[ -n "$KEEP_STORAGE_OBJECTS" ]]; then
+ # Opt-in: keep the dump's storage rows AND its buckets. Downloads still 404
+ # (the bytes are in the source environment's backend, not the DB) — this
+ # exists for work that needs realistic storage.objects volume, e.g. profiling
+ # the RLS on storage listings, which is unmeasurable against an empty table.
+ # Buckets are kept too: the objects reference buckets that the re-seed below
+ # does not recreate (`temp-staging` is neither a fixed bucket nor a company),
+ # so truncating them would strand those rows on a missing FK.
+ echo "▶ Keeping storage metadata (KEEP_STORAGE_OBJECTS) — downloads will 404 locally"
+else
+ echo "▶ Resetting storage metadata + ensuring buckets (fixed + per-company)"
+ # Guard each TRUNCATE with to_regclass so a table that doesn't exist in this
+ # Supabase version can't abort — and thereby roll back — the whole block.
+ $PSQL_SA -v ON_ERROR_STOP=0 -c "
DO \$\$
BEGIN
IF to_regclass('storage.objects') IS NOT NULL THEN TRUNCATE storage.objects CASCADE; END IF;
@@ -186,6 +216,7 @@ BEGIN
IF to_regclass('storage.buckets') IS NOT NULL THEN TRUNCATE storage.buckets CASCADE; END IF;
END \$\$;
" >/dev/null 2>&1 || true
+fi
# Re-seed buckets in a SEPARATE statement so the TRUNCATE outcome above can never
# roll it back: the fixed app buckets plus one private bucket per restored
# company (id = company id), matching the bucket-seeding migrations.