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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
Security: file-serving XSS, CSRF + report-only CSP, RLS authz manifest (#1737)
Sid4df5f8c9bd9c
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex 533728c2ec..61ee05d768 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -2317,6 +2317,23 @@ attacker reads it: `SET LOCAL ROLE anon; SELECT count(*) FROM "view";` must be 0**Applies to:** `packages/database/supabase/migrations/**`; enforced by the`no-view-without-invoker` conformance check and the `view-without-security-invoker` invariant.+## A local-only sync step does not deploy (authz manifest, 2026-09-27)++**Context:** RLS policies moved from migrations into `packages/database/src/authz/manifest.ts`,+applied by `authz sync` after `crbn migrate`. Production runs migrations only.++**Problem:** With policies forbidden in migrations, a new table would be correct locally and+ship to production with no policies and RLS off — open to the anon key, since Supabase grants+public tables to `anon`/`authenticated` by default. Edited rules would silently never deploy.+Separately, a test of a missing UPDATE `WITH CHECK` passed against the broken policy: a+filtered `UPDATE … WHERE` checks the new row against the SELECT policy too.++**Rule:** Anything applied outside migrations needs a CI gate that proves the deploy path+carries it (`migration.test.ts` → `authz migration`). Test a WITH CHECK with an unfiltered+UPDATE or by evaluating the policy expression directly, and prove the test red first.++**Applies to:** `packages/database/src/authz/**`, `packages/database/supabase/tests/authz-*.sql`.+## A PostgREST update that matches no row reports success**Context:** Typed item updates (`upsertPart`, `upsertTool`, `upsertConsumable`,diff --git a/.ai/plans/2026-09-27-authz-manifest.md b/.ai/plans/2026-09-27-authz-manifest.mdnew file mode 100644index 0000000000..5b28b80aab--- /dev/null+++ b/.ai/plans/2026-09-27-authz-manifest.md@@ -0,0 +1,74 @@+# Authz manifest: every policy and RLS helper from one source++This plan is the current design. Branch `feat/authz-manifest`.++The manifest (`packages/database/src/authz/`) is the only place RLS policies and the RLS /+auth helper functions are authored. `authz sync` makes a database match it in one+transaction after migrations; migrations only create tables. CI is not wired (production+connection availability unverified) — local `crbn up/migrate/restore` only. Production gets+changes through `authz migration`; `migration.test.ts` fails CI until it does. Guide:+`.claude/rules/authz-manifest.md`.++## Done++- [x] `rules.ts` builders + Kysely-compiled `render()`; per-action actors, `false` = denied+- [x] `sync.ts` one-transaction sync (scratch-schema normalization, drop-all + recreate)+- [x] `import` (bootstrap, 0 drift) and `convert` (exact custom → pattern) — done, then deleted+- [x] `journal` fixed through the manifest (standalone migration removed), red/green proven+- [x] `crbn up/migrate/restore` run sync after type regen++## Now++- [x] Add `libpg-query` (authz CLI only)+- [x] Pieces API: who (`employee`, `member`, permission, `anyOf`) and predicates+ (`inCompany`, `viaParent`, `exists`, `owner`, `portal.*`, `authenticated`, `isNull`,+ `where`, `or`, `and`); `company()` as sugar; `policies()` for everything else+- [x] Strict SQL: every rendered rule (custom included) must parse to only CREATE POLICY on+ its own table (`assertOnlyPolicies`), checked before anything runs+- [x] Helpers: `helpers/<name>.sql` (20, now 16 after the retirement below) (validated: exactly one CREATE OR REPLACE FUNCTION+ public.<name>), synced first in the same transaction, applied in a savepoint and kept+ only if different; signature change fails loudly; `import-helpers` bootstrap = 0 drift;+ proven: a hand-made VOLATILE flip is detected and healed+- [x] Retired the four deprecated helpers (has_role, has_company_permission,+ get_companies_with_permission, get_permission_companies): manifest moved (generated+ 20260927224243), storage policies + is_claims_admin moved and unused create_rfq_* RPCs ++ the helpers dropped (20260927224314). Portal accounts lose document / demand / supply+ reads; API keys scoped to resources_* gain userAttribute* (consistent with every table)+- [x] AST converter (`convert.ts`): 118 of 147 customs → pieces; each round-trips to the+ same canonical meaning; 61 rewritten in text, synced locally; all SQL tests green+ (except `integration-metadata-patch`, stale since #1725 — EXECUTE grants, not policies)+- [x] Bespoke tables: `exists` gained a condition + `sameCompany`; new `through` / `member`;+ converter learned unions of portal/legacy sets, COALESCE, array_agg, owner spellings.+ Manifest (393 tables): mostly `company`, then `policies`, 11 serviceOnly, 4 group, 3 custom+ (each with a real reason). Equivalence rules pinned in `convert.test.ts`.+- [x] Behavior tests per piece: `supabase/tests/authz-pieces.test.sql` (proven red on a broken rule)+- [x] `@carbon/checks` `no-authz-ddl-in-migrations`: new migrations may not CREATE/ALTER+ POLICY or define/alter/drop a managed helper (list read from helpers/, no dependency)++## Self-review fixes++- [x] Production shipping gate: `unshipped()` + `baseline.json` + `migration.test.ts` (CI, no+ DB). New tables, edited rules and edited helpers fail until `authz migration <name>`,+ which now ships exactly the unshipped set. Generated files are allowlist-parsed, so the+ header cannot be borrowed+- [x] `no-authz-ddl-in-migrations` only flags policies on public tables (storage buckets allowed)+- [x] Deleted `import` / `import-helpers` / `convert` (they could overwrite fixes from a stale DB)+- [x] `get_companies_with_employee_permission` STABLE; RPC guard matches any case / trailing `/`+ (both shipped in `20260927172338_authz-security-fixes.sql`, regenerated)+- [x] `maintenanceDispatchComment` behavior test; `allows()` falls back to USING like Postgres++## Later (needs approval — behavior changes)++- [x] Fixed (tests/authz-fixes.test.sql; each fix proven red against its old definition):+ invoiceSettlement EXISTS self-compare; userAttributeValue (self-write of canSelfManage+ attributes in own company); note / tableView / maintenanceDispatchComment owner UPDATE+ WITH CHECK; maintenance_* → resources; userToCompany API INSERT/UPDATE denied (audit M);+ get_company_id_from_foreign_key refused as an RPC; H3: legacy permission helpers drop the+ '0' wildcard and intersect membership, API keys scope-checked. Shipped with journal in+ the generated migration 20260927172338_authz-security-fixes.sql (`authz migration`)+- [x] App drift: the attribute upsert route checked users_update; it and the DB now both use+ resources_update, and users can clear their own self-managed values (the delete route+ offered it; the DB refused silently) — generated 20260927230425+- [ ] Any-employee writes (`trackedEntity`, `riskRegister`, …) → permission?+- [ ] Unscoped API keys reading `employee`-read tables+- [ ] Re-wire CI once every active workspace has a Postgres connectiondiff --git a/.ai/plans/2026-09-28-csp-csrf.md b/.ai/plans/2026-09-28-csp-csrf.mdnew file mode 100644index 0000000000..31ffb6a97b--- /dev/null+++ b/.ai/plans/2026-09-28-csp-csrf.md@@ -0,0 +1,125 @@+# CSP + CSRF hardening, repo-wide++Branch `feat/authz-manifest` (same branch as the file-serving XSS fixes). Inventory done+2026-09-28 (two read-only sweeps; findings summarised here, file:line in the session log).++## Where we are++- CSP: `object-src 'none'; base-uri 'self'; frame-ancestors 'self'` only, set in+ `apps/{erp,mes}/app/entry.server.tsx` for DOCUMENT responses. No `script-src`, so it does+ nothing against XSS. Resource and `.data` responses get no security headers at all.+- CSRF: nothing. The only defence is the `carbon` session cookie's `SameSite=Lax`, which+ (a) is `None` in the Test edition (and sent without `Secure`, which browsers reject), and+ (b) is scoped to the parent domain, so every `*.carbon.ms` host (docs, marketing, rest,+ learn, mes) is "same-site" to the ERP.+- GET loaders that write — CSRF-able through Lax top-level navigation: kanban QR flow+ (`api+/kanban.$id.tsx` creates jobs/POs/transfers, redirects into MES `x+/start` /+ `x+/end` which start production events, issue material, finish operations), sales- and+ purchase-invoice `new.tsx` (create invoices), `api+/settings.sequence.next.ts`+ (increments a sequence), stock-transfer `pick`/`unpick` loaders, stripe-connect+ `connect`/`dashboard`.++## Design++### 1. CSRF: one cross-origin check, no token (Go 1.25 `CrossOriginProtection` algorithm)++`securityMiddleware` (`packages/auth/src/middleware/security.server.ts`; the rules are pure+in `lib/security.ts`), added to the root `middleware` of erp, mes, academy, starter. For POST/PUT/PATCH/DELETE:++1. Path (with a trailing `.data` stripped) in the exemption list → allow. The list is only+ the endpoints browsers call cross-origin by design: `/token`, `/register`, `/api/mcp`.+2. `Sec-Fetch-Site` is `same-origin` or `none` → allow; any other value → 403. `same-site`+ is refused on purpose (parent-domain cookie).+3. No `Sec-Fetch-Site`: no `Origin` → allow (not a browser: webhooks, Inngest, the Rust+ assembler, the MES→ERP proxy, the stock-transfer self-POST, API-key clients). `Origin`+ equal to the request's host (`x-forwarded-host ?? host`, never `request.url`, which is+ the internal origin behind portless/Vercel) → allow; else 403.++Webhooks need no exemption: they send neither header. Unit-tested as a pure function of+(method, path, headers).++### 2. GET writes++A `rejectCrossSiteNavigation(request)` guard (same file) at the top of each loader listed+above: 403 when `Sec-Fetch-Site: cross-site`. `none` (QR scan, typed URL, bookmark),+`same-origin` and `same-site` (the ERP→MES kanban redirect) pass, so no UX changes.+`api+/link.ts` (company switch from notification emails) is left alone: webmail clicks are+cross-site and it only switches between the user's own companies. Stripe-connect `connect`+is left alone too: Stripe's `refresh_url` → `callback` → `connect` chain starts on+stripe.com, and the worst a forged link does is open Stripe onboarding for the user.++### 3. CSP: nonce + strict-dynamic++- A middleware makes a per-request nonce and puts it in router context; `entry.server`+ passes it to `vercelHandleRequest(…, { nonce })`. React Router's `<Links>`, `<Scripts>`+ and `<ScrollRestoration>` read it from framework context (also on error pages); the+ inline `window.env` script reads `UNSAFE_FrameworkContext`.+- The policy is built by one pure function (`buildContentSecurityPolicy`, `@carbon/auth`+ `lib/security.ts`, tested) from config:++ ```+ default-src 'self';+ script-src 'nonce-…' 'strict-dynamic' 'wasm-unsafe-eval' [erp: 'unsafe-eval'] https: 'unsafe-inline';+ style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net;+ img-src 'self' data: blob: https:;+ font-src 'self' data: https://cdn.jsdelivr.net;+ connect-src 'self' <SUPABASE https + wss> <PostHog ingest + assets> https://places.googleapis.com https://cdn.jsdelivr.net;+ frame-src 'self' blob: data: https://www.youtube.com https://www.youtube-nocookie.com https://www.loom.com https://challenges.cloudflare.com;+ worker-src 'self' blob: data:;+ media-src 'self';+ object-src 'none'; base-uri 'self'; frame-ancestors 'self'+ ```++ Why each exception: `wasm-unsafe-eval` (HEIC/jSquash upload, meshopt, CAD import),+ `unsafe-eval` (ERP configurator runs `new Function` + TypeScript from unpkg),+ `style-src 'unsafe-inline'` (sonner, Radix, tiptap, `<html style>`), `img-src https:`+ (agent markdown images, Google favicons), jsdelivr (Monaco). `form-action` is omitted+ on purpose: Chrome applies it to the redirect after the OAuth `/authorize` consent POST.+ Academy adds Google Fonts.+- Rollout: `Content-Security-Policy-Report-Only` + a same-origin `/api/csp-report` that+ logs (body capped), then flip to enforcing.++### 4. Headers on every response++`nosniff`, `X-Frame-Options`, `Referrer-Policy`, HSTS move from `entry.server` into a+middleware so resource and `.data` responses get them too (routes that set their own CSP,+like the file preview routes, keep it).++### 5. Cookies++Test edition: `Secure` whenever `SameSite=None` (session, oauth-state, console-pin).+`companyId` gets the session cookie's `SameSite`/`Secure` rules.++## Tasks++- [x] Decisions confirmed 2026-09-28: block cross-site only for GET writes; report-only first;+ keep ERP `unsafe-eval`, follow-up to remove+- [x] `middleware/security.server.ts` (pure rules in `lib/security.ts` + tests); wired into 4 roots+- [x] `rejectCrossSiteNavigation` in the GET-writing loaders+- [x] CSP builder + tests; nonce middleware; entry.server + root.tsx for 4 apps+- [x] `/api/csp-report` (all 4 apps)+- [x] security-headers middleware; trim `applySecurityHeaders`+- [x] cookie fixes+- [x] typecheck erp/mes/academy/starter/auth/utils (one at a time), tests, biome+- [x] Browser check (2026-09-28, local stack, agent-browser — it enforces CSP, verified with an+ injected handler → report → server WRN): login, 14 ERP module pages, MES login ++ operation page, PDF, image preview (XSS payload inert), thumbnail upload (wasm), same-site+ POST MES→ERP `/logout` + `/api/*` → 403 and session kept, cross-site link → kanban / MES+ start → 403 with nothing written, typed URL → kanban creates the PO, ERP→MES link starts the+ operation, real same-origin form POST passes. Found + fixed: zod's JIT `new Function` probe+ reported on every MES page → `app/zod.client.ts` (`z.config({ jitless: true })`), imported+ FIRST by each `root.tsx` (React Router's hydration script loads route modules before+ entry.client, so entry.client was too late). Not covered: MFA, OAuth consent, configurator+ (no demo data), PostHog (no key locally)+- [x] `.claude/rules/authentication-system.md` + `packages/auth/AGENTS.md`++## Follow-ups (not in this change)++- Drop `'unsafe-eval'`: bundle Monaco + TypeScript and run configurator code in a worker.+- `api+/webhook.onshape.$companyId.ts` has no signature check (capability URL only).+- Turnstile `script-src-elem` was reported twice on the ERP login page, both right after a dev+ server reload; four normal loads reported nothing. If production reports show it, pass the+ nonce to the widget (`scriptOptions.nonce`, react-turnstile supports it).+- Pre-existing, found while testing: `/file/model/$id` fetches bundled demo models+ (`_templates/…`) through the public model route, which only serves `<companyId>/models/…`+ → 404 (on main too); `$bucket` preview throws a 500 (not 404) for a malformed path.diff --git a/.claude/rules/authentication-system.md b/.claude/rules/authentication-system.mdindex b1bde130b2..5eea9b1df7 100644--- a/.claude/rules/authentication-system.md+++ b/.claude/rules/authentication-system.md@@ -207,10 +207,46 @@ querying), and every route entry point checks it too — login buttons, the(compose substitution → `GOTRUE_SAML_*`; `crbn reload` does not read root `.env` —see `.ai/lessons.md`).+## CSRF and CSP (`middleware/security.server.ts`, `lib/security.ts`)++The `carbon` cookie is `SameSite=Lax` on the PARENT domain (`carbon.ms`), so every+`*.carbon.ms` host is same-site and Lax alone is not a CSRF defence. `securityMiddleware`+(root `middleware` of erp, mes, academy, starter) refuses a POST/PUT/PATCH/DELETE when+`Sec-Fetch-Site` is anything but `same-origin`/`none`, or — without that header — when+`Origin` differs from the addressed host (`getRequestHost`, `@carbon/utils`; never+`request.url`, the internal origin behind the proxy). No `Origin` at all is a server (webhooks,+Inngest, assembler callback, API-key clients, the MES→ERP proxy) and passes, so webhooks+need no exemption; `CROSS_ORIGIN_ENDPOINTS` is only `/token`, `/register`, `/api/mcp`.+Browser submissions arrive as `…/path.data`, stripped before matching.+React Router 7.18 has its own check (`throwIfPotentialCSRFAttack`: `Origin` host vs+`request.url` host, 400) — but only on DOCUMENT and `.data` actions, and it runs before+middleware. Resource routes (every `api+` action) get no check from it; the middleware is+what refuses those (checked 2026-09-28: `handleResourceRequest` calls no origin check; a+cross-site POST to an `api+` route now gets the middleware's 403).++GET loaders that write (kanban QR `api+/kanban.$id.tsx`, MES `x+/start|end.$operationId`,+invoice `new` routes, `settings.sequence.next`, stock-transfer pick/unpick, stripe-connect+dashboard) call `rejectCrossSiteNavigation`: 403 on `Sec-Fetch-Site: cross-site`,+while a QR scan (`none`) and the ERP→MES redirect (`same-site`) pass. Deliberately unguarded:+`api+/link.ts` (company switch from email links — webmail clicks are cross-site) and+stripe-connect `connect` (Stripe's expired-link `refresh_url` lands on `callback`, which+redirects there: a chain started on stripe.com, so cross-site).++CSP: the middleware puts a per-request nonce in `nonceContext`; `entry.server` passes it+to `vercelHandleRequest(…, { nonce })`, which React Router's `<Links>`, `<Scripts>` and+`<ScrollRestoration>` read from framework context; the inline `window.env` script reads+`UNSAFE_FrameworkContext`. The enforced policy is still the old baseline (`object-src`,+`base-uri`, `frame-ancestors`); the strict nonce + `strict-dynamic` policy+(`buildContentSecurityPolicy`) ships as `Content-Security-Policy-Report-Only`, reporting+to `/api/csp-report` in each app. Why each exception exists (`wasm-unsafe-eval`, ERP+`unsafe-eval` for the configurator, `style-src 'unsafe-inline'`, `img-src https:`) and+why there is no `form-action`: `.ai/plans/2026-09-28-csp-csrf.md`.+## Sessions (`session.server.ts`)- `createCookieSessionStorage`, cookie name **`carbon`**, `httpOnly`, `sameSite: "lax"`- (`"none"` in Test edition), `secure`/`domain` from `DOMAIN` in non-test. Payload stored+ (`"none"` in Test edition, always with `Secure` — browsers drop `None` without it),+ `secure`/`domain` from `DOMAIN` in non-test. Payload storedunder key `SESSION_KEY = "auth"`; `SESSION_MAX_AGE = 7 days`.- `requireAuthSession` reads/validates; `getOrRefreshAuthSession` refreshes within`REFRESH_ACCESS_TOKEN_THRESHOLD` (10 min) of expiry via `refreshAccessToken`.@@ -312,11 +348,20 @@ Supabase's `auth.mfa_factors` — no app table.## Permissions & RLS gating (`auth.server.ts` → `requirePermissions`)-`requirePermissions(request, { view?, create?, update?, delete?, role?, bypassRls? })` is+`requirePermissions(request, { view?, create?, update?, delete?, role?, bypassRls?, allowPortalAccounts? })` isthe gate used in every loader/action. Two paths:1. **`carbon-key` header present** → API-key auth (see below).2. **Otherwise** → `requireAuthSession`, then `getUserClaims(userId, companyId)`.+ - A session whose role in the active company is `customer` or `supplier` (portal+ accounts) is refused with a 403 BEFORE the empty-requirement early exit, unless the+ route passes `allowPortalAccounts: true`. Portal accounts hold `documents_*`,+ `parts_view`, `sales_view`/`purchasing_view`, and `{}` admitted any session, so before+ this ~50 routes that read with the service role (file previews, job travelers, order+ and quote pages) served them. No route is theirs: portal pages are share links on+ the service role. Opted in: onboarding, company switch (erp/mes/starter),+ `api+/link.ts`, academy challenge — each acts on the user's own identity. A 403, not a+ redirect: the MES `/x` middleware calls `requirePermissions`, so a redirect there loops.- Claims are `{ role, permissions }`. Cached in **Redis** (`@carbon/kv`) at key`permissions:${userId}`; on miss, fetched via the `get_claims(uid, company)` RPC(`getCarbonServiceRole`) and cached. `makePermissionsFromClaims` shapes the result.diff --git a/.claude/rules/authz-manifest.md b/.claude/rules/authz-manifest.mdnew file mode 100644index 0000000000..db3baf2b15--- /dev/null+++ b/.claude/rules/authz-manifest.md@@ -0,0 +1,98 @@+---+paths:+ - "packages/database/src/authz/**"+ - "packages/database/supabase/migrations/**"+ - "packages/database/supabase/tests/authz-*.test.sql"+ - "packages/checks/src/conformance/no-authz-ddl-in-migrations.ts"+ - "packages/dev/src/services/migrations.ts"+---++# Authz manifest: RLS policies and helpers++Every RLS policy on a `public` table, and the 20 RLS/auth helper functions, are authored in+`packages/database/src/authz/` and nowhere else. Migrations create tables; they never write+`CREATE POLICY` / `ALTER POLICY` on a public table or define a managed helper+(`no-authz-ddl-in-migrations` in `@carbon/checks` fails them, from `20260927000000` on).+`storage.objects` (bucket) policies are not in the manifest and stay in migrations.++| File | What it is |+|---|---|+| `manifest.ts` | one rule per public table, typed by table name (`satisfies Manifest`) |+| `rules.ts` | the pieces and builders; `render()` compiles a rule to `CREATE POLICY` SQL with Kysely |+| `helpers/<name>.sql` | one `CREATE OR REPLACE FUNCTION public.<name>` per file (validated with Postgres's parser) |+| `sync.ts` | `authz sync` / `check`: make a database match, in one transaction |+| `migration.ts` | `authz migration`: ship changes to databases that do not sync; `unshipped()` |+| `baseline.json` | what production had when the manifest took over — written once, never regenerated |++## Writing a rule++```ts+widget: company("inventory"), // the four standard policies+widgetLine: parent("widget", "widgetId", "inventory"),+maintenanceDispatchItemTrackedEntity: company("resources", { create: "employee" }),+userToCompany: company("users", { create: false, update: false }), // no API writes+note: policies({+ select: inCompany("companyId", "employee"),+ update: { using: owner("createdBy"), check: and(owner("createdBy"), inCompany("companyId", "employee")) }+}),+```++- `company(module, overrides)` — SELECT any employee, writes `<module>_<action>`; an actor is+ `"employee"`, a permission, `anyOf(...)`, a predicate, or `false` (denied). `where` narrows a+ write (`journal` edits only Draft/Posted rows).+- `group(module)` — group-shared rows by `companyGroupId`.+- Pieces for `policies({...})`: `inCompany`, `inGroup`, `viaParent`, `exists` (optionally+ `sameCompany`), `through`, `member`, `owner`, `portal.customer/supplier`, `authenticated`,+ `isNull`/`isNotNull`, `where<"table">(eb => …)`, `or`, `and`.+- An UPDATE that can change `companyId` needs a `check` that pins the company — without it+ Postgres reuses USING, and an owner-only USING lets the author move the row to any company.+- `serviceOnly()` — RLS on, no policy: only the service role reaches it.+- `custom(reason, sql)` — last resort (3 today). The rendered SQL must parse to only+ `CREATE POLICY` on its own table.++## Shipping a change++1. Migration creates the table (no policies).+2. Add its rule to `manifest.ts` (or edit a rule / helper file).+3. `pnpm db:migrate` — `crbn migrate` (and `crbn up` / `crbn restore`) run `authz sync` last, so+ the local database gets the rule. A public table with no rule fails the sync.+4. `pnpm --filter @carbon/database authz migration <name>` — writes a generated migration with+ every rule and helper production does not have yet. Production does NOT run sync (CI is+ not wired: a Postgres connection is only guaranteed for some workspaces), so this migration+ is the only way the change deploys.++`migration.test.ts` (runs in CI, no database) fails until step 4 is done: every table's latest+generated block, or else its `baseline.json` hash, must equal what the manifest renders now —+so a new table cannot deploy without policies and an edited rule cannot silently not deploy.+It also refuses a generated file containing anything `authz migration` does not write, so the+header exemption cannot be borrowed by a hand-written file. Never edit a generated migration+or `baseline.json` by hand.++## Commands++```bash+pnpm --filter @carbon/database authz check # what sync would change (exit 3 = drift)+pnpm --filter @carbon/database authz sync # make the local database match+pnpm --filter @carbon/database authz migration <name> # ship unshipped rules/helpers+pnpm --filter @carbon/database exec vitest run src/authz+```++Behaviour tests (run against a local database, each rolls back):+`supabase/tests/authz-pieces.test.sql` (one case per piece),+`authz-fixes.test.sql`, `journal-update-tenant-check.test.sql`.++## Gotchas++- A filtered `UPDATE … WHERE` also checks the new row against the SELECT policy, so a test of+ a missing WITH CHECK passes vacuously; test with an unfiltered UPDATE or `pg_temp.allows`.+- Policy subqueries run under the caller's RLS: an `exists` over a table the caller cannot+ read is always false.+- `REVOKE EXECUTE` segfaults this image; `get_company_id_from_foreign_key` refuses a direct+ `/rpc/` call by checking `request.path` instead.+- Retiring a helper is not automated. Move every caller (manifest rules via `authz+ migration`; storage policies and function bodies in a hand-written migration), delete its+ `helpers/<name>.sql`, map it in `RETIRED_HELPERS` (`helpers.ts`) to the generated migration+ that last defined it (only that file may still define it), and `DROP FUNCTION` it in a migration AFTER the one that+ moved the callers, without CASCADE so a missed dependent fails loudly. Done this way for+ `has_role`, `has_company_permission`, `get_companies_with_permission`,+ `get_permission_companies` (`20260927224243` + `20260927224314`).diff --git a/.claude/rules/conventions-database.md b/.claude/rules/conventions-database.mdindex 74aebf6144..3baa71b736 100644--- a/.claude/rules/conventions-database.md+++ b/.claude/rules/conventions-database.md@@ -101,45 +101,20 @@ ALTER TABLE "entityName" ADD CONSTRAINT "entityName_companyId_name_key"| `JSONB` | Custom fields / structured config || `TEXT[]` | Tags / arrays of ids |-## RLS Policies (the only correct pattern)--Enable RLS and create the four policies named **exactly** `SELECT` / `INSERT` /-`UPDATE` / `DELETE`. Schema-qualify the table (`"public"."t"`) and cast the helper-result `::text[]`. From `20260609143732_document-template.sql`:--```sql-ALTER TABLE "public"."entityName" ENABLE ROW LEVEL SECURITY;--CREATE POLICY "SELECT" ON "public"."entityName"-FOR SELECT USING (- "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])-);--CREATE POLICY "INSERT" ON "public"."entityName"-FOR INSERT WITH CHECK (- "companyId" = ANY ((SELECT get_companies_with_employee_permission('module_create'))::text[])-);--CREATE POLICY "UPDATE" ON "public"."entityName"-FOR UPDATE USING (- "companyId" = ANY ((SELECT get_companies_with_employee_permission('module_update'))::text[])-);--CREATE POLICY "DELETE" ON "public"."entityName"-FOR DELETE USING (- "companyId" = ANY ((SELECT get_companies_with_employee_permission('module_delete'))::text[])-);-```--- **SELECT** → `get_companies_with_employee_role()` (any employee of the company can read).- Some tables tighten read to a view permission instead (e.g. picking lists use- `get_companies_with_employee_permission('inventory_view')`) — that's a valid variant.-- **INSERT / UPDATE / DELETE** → `get_companies_with_employee_permission('<module>_<action>')`,- `<action>` ∈ `create` / `update` / `delete` (e.g. `settings_create`, `inventory_update`).-- The old `has_role` / `has_company_permission` pattern is **deprecated** — never use it.+## RLS Policies++Policies are **not** written in migrations. Add the table's rule to+`packages/database/src/authz/manifest.ts` — usually one line, `entityName: company("<module>")`,+which renders the four standard policies (`SELECT` any employee via+`get_companies_with_employee_role()`, writes via+`get_companies_with_employee_permission('<module>_<action>')`) — then `pnpm db:migrate` syncs it+locally and `pnpm --filter @carbon/database authz migration <name>` ships it to production.+Full guide, including tables without a `companyId`: `authz-manifest.md`.++- The old `has_role` / `has_company_permission` / `get_companies_with_permission` /+ `get_permission_companies` helpers are gone — dropped in `20260927224314_retire-legacy-rls-helpers.sql` (they admitted customer and supplier portal accounts); `authz-fixes.test.sql` asserts they stay gone.- For tables **without a `companyId` column**, reach the company through the parent- via `EXISTS`, gating writes on the **write** permission (not just visibility). See- `database-migration-patterns.md` ("Tables without a companyId column").+ (`parent(...)`, `viaParent`, `exists`), gating writes on the **write** permission.## Views@@ -189,8 +164,7 @@ Validate in route actions with `validator(schema).validate(formData)` from- [ ] `companyId` present with composite PK `("id", "companyId")` + FK `ON DELETE CASCADE`- [ ] Audit columns; `*By` reference `"user"("id")` inline- [ ] Indexes on `companyId` and every FK-- [ ] RLS enabled with the four standardized policy names; SELECT via- `get_companies_with_employee_role()`, writes via- `get_companies_with_employee_permission('<module>_<action>')`+- [ ] No `CREATE POLICY` in the migration; the table's rule is in `authz/manifest.ts`+ and shipped with `pnpm --filter @carbon/database authz migration <name>`- [ ] Zod validators in `{module}.models.ts`- [ ] Applied locally with `pnpm db:migrate` (regenerates types) — never `db:build`diff --git a/.claude/rules/database-migration-patterns.md b/.claude/rules/database-migration-patterns.mdindex 15698925ae..d3bdb858cb 100644--- a/.claude/rules/database-migration-patterns.md+++ b/.claude/rules/database-migration-patterns.md@@ -72,53 +72,19 @@ ALTER TABLE "documentTemplate" ADD CONSTRAINT "documentTemplate_companyId_docume- Index `companyId` and every FK (e.g. `createdBy`).- Never add an `itemReadableId` column, and never specify decimal places in a `NUMERIC` — this applies everywhere: column definitions, `RETURNS TABLE` declarations, and `::NUMERIC` casts. Always use bare `NUMERIC`, never `NUMERIC(19,4)` or any precision form.-## RLS (the only correct pattern)+## RLS-Enable RLS and create the four standardized policies named exactly `SELECT` / `INSERT` /-`UPDATE` / `DELETE`. Schema-qualify the table (`"public"."t"`) on the `ALTER`/`CREATE POLICY`,-and cast the helper result with `::text[]`.--```sql-ALTER TABLE "public"."documentTemplate" ENABLE ROW LEVEL SECURITY;--CREATE POLICY "SELECT" ON "public"."documentTemplate"-FOR SELECT USING (- "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])-);--CREATE POLICY "INSERT" ON "public"."documentTemplate"-FOR INSERT WITH CHECK (- "companyId" = ANY ((SELECT get_companies_with_employee_permission('settings_create'))::text[])-);--- UPDATE → USING get_companies_with_employee_permission('<module>_update')--- DELETE → USING get_companies_with_employee_permission('<module>_delete')-```--- **SELECT** uses `get_companies_with_employee_role()` (any employee of the company can read).-- **INSERT/UPDATE/DELETE** use `get_companies_with_employee_permission('<module>_<action>')`- where `<action>` is `create` / `update` / `delete` (e.g. `settings_create`, `inventory_update`).-- The old `has_role` / `has_company_permission` pattern is **deprecated** — never use it.--### Tables without a `companyId` column--Reach the company through the parent via `EXISTS`, gating on the same permission.-From `20260614092317_picking-tracked-entity-rls.sql`:--```sql-CREATE POLICY "INSERT" ON "pickingListLineTrackedEntity"-FOR INSERT WITH CHECK (- EXISTS (- SELECT 1 FROM "pickingListLine" pll- WHERE pll."id" = "pickingListLineId"- AND pll."companyId" = ANY (- (SELECT get_companies_with_employee_permission('inventory_create'))::text[]- )- )-);-```+Policies are **not** written in migrations. Add the table's rule to+`packages/database/src/authz/manifest.ts` — usually one line, `entityName: company("<module>")`,+which renders the four standard policies (`SELECT` any employee via+`get_companies_with_employee_role()`, writes via+`get_companies_with_employee_permission('<module>_<action>')`) — then `pnpm db:migrate` syncs it+locally and `pnpm --filter @carbon/database authz migration <name>` ships it to production.+Full guide, including tables without a `companyId`: `authz-manifest.md`.Gate writes on the **write** permission, not just visibility — a SELECT-only predicate on-INSERT/UPDATE/DELETE is a privilege-escalation bug (the reason that migration exists).+INSERT/UPDATE/DELETE is a privilege-escalation bug (`20260614092317_picking-tracked-entity-rls.sql`+exists because of one). `parent(table, fk, module)` gets this right for child tables.## Viewsdiff --git a/.claude/rules/database-patterns.md b/.claude/rules/database-patterns.mdindex 44e2532683..8926c87544 100644--- a/.claude/rules/database-patterns.md+++ b/.claude/rules/database-patterns.md@@ -247,7 +247,8 @@ export async function action({ request, params }: ActionFunctionArgs) {- Multi-tenant: nearly every table has `companyId` (composite PK `("id", "companyId")`).- Standardized policy names `SELECT` / `INSERT` / `UPDATE` / `DELETE`, gated by SQL helpers`get_companies_with_employee_role()` (read) and `get_companies_with_employee_permission('<module>_<action>')`- (write). Verified current in the newest migrations (e.g. `20260603140000_storage-rules-inventory-rls.sql`).+ (write). Policies and those helpers are authored in `packages/database/src/authz/`, not in+ migrations — see `authz-manifest.md`.- RLS is the real authorization boundary for supabase-js clients; `requirePermissions` is the app-layer gate(and the only gate for service-role / Kysely paths). See `conventions-database.md` for the table+RLS template.diff --git a/.claude/rules/user-employee-job-relationships.md b/.claude/rules/user-employee-job-relationships.mdindex 490776ac90..684930bc0a 100644--- a/.claude/rules/user-employee-job-relationships.md+++ b/.claude/rules/user-employee-job-relationships.md@@ -52,7 +52,7 @@ is the separate `job` table from `20240909194622_jobs.sql`).`userToCompany` and `permissions` from `userPermission`, then returns`(jsonb_build_object('role', role) || permissions)`. Called through the API it answers only forthe caller's own `uid`, or for someone in a company where the caller holds `users_view` or- `users_update`; service role and direct connections are unrestricted. RLS helpers like `has_company_permission`,+ `users_update`; service role and direct connections are unrestricted. RLS helpers like`get_companies_with_employee_role()`, and `get_companies_with_employee_permission('<module>_<action>')`enforce this in policies (helpers re-defined in later migrations — read the newest).5. App layer (`packages/auth/src/services/`): `getUserClaims()` caches claims in Redis atdiff --git a/.claude/rules/workflow-database-migration.md b/.claude/rules/workflow-database-migration.mdindex 2c286fdffc..28b4740422 100644--- a/.claude/rules/workflow-database-migration.md+++ b/.claude/rules/workflow-database-migration.md@@ -70,16 +70,12 @@ newest migrations, e.g. `20260609143732_document-template.sql`):— the `*By` columns reference `"user"("id")` **inline** (no named constraints).`updatedAt` is set by the app, not a trigger.- **Indexes** on `companyId` and **every** FK (e.g. `createdBy`).-- **RLS** — enable, then create exactly four policies named `SELECT` / `INSERT` /- `UPDATE` / `DELETE`, schema-qualified (`"public"."t"`) with the helper result- cast `::text[]`:- - `SELECT` → `get_companies_with_employee_role()` (any employee reads). Some- tables tighten read to a view permission — a valid variant.- - `INSERT`/`UPDATE`/`DELETE` →- `get_companies_with_employee_permission('<module>_<action>')`- (`<action>` ∈ `create` / `update` / `delete`).- - The old `has_role` / `has_company_permission` helpers are **deprecated** —- never use them. For tables without a `companyId`, reach the company through+- **RLS** — not in the migration. Add the table's rule to+ `packages/database/src/authz/manifest.ts` (usually `entityName: company("<module>")`),+ then ship it with `pnpm --filter @carbon/database authz migration <name>`; CI's+ `migration.test.ts` fails until you do. See `authz-manifest.md`.+ - The old `has_role` / `has_company_permission` helpers no longer exist+ (dropped in `20260927224314_retire-legacy-rls-helpers.sql` (they admitted customer and supplier portal accounts); `authz-fixes.test.sql` asserts they stay gone). For tables without a `companyId`, reach the company throughthe parent via `EXISTS` (see `database-migration-patterns.md`).- **Never**: an `itemReadableId` column, or a precision spec on `NUMERIC`.- **Views** use `WITH(SECURITY_INVOKER=true)`.@@ -140,9 +136,8 @@ pre-commit hook runs it anyway. Details: `onboarding-company-templates.md`.- [ ] `companyId` + composite PK `("id", "companyId")` + FK `ON DELETE CASCADE`- [ ] Audit columns; `*By` reference `"user"("id")` inline- [ ] Indexes on `companyId` and every FK-- [ ] RLS enabled with the four standardized policy names (SELECT via- `get_companies_with_employee_role()`, writes via- `get_companies_with_employee_permission('<module>_<action>')`)+- [ ] Rule added to `packages/database/src/authz/manifest.ts` and shipped with+ `pnpm --filter @carbon/database authz migration <name>` (no `CREATE POLICY` in migrations)- [ ] Renamed/dropped a tenant-scoped table? `TABLE_RENAMES` entry added(`packages/jobs/src/backups/renames.ts`) — new name, or `null` if dropped with its feature- [ ] Zod validators updated in `{module}.models.ts`diff --git a/AGENTS.md b/AGENTS.mdindex 188a7261ec..8e04287560 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -69,6 +69,7 @@ IMPORTANT: Before any research or coding, match the task to this table. A single| Database conventions (tables, RLS, multi-tenancy) | `.claude/rules/conventions-database.md` || Database access patterns (clients, Kysely, RPCs) | `.claude/rules/database-patterns.md` || Migration SQL patterns (enums, views, triggers) | `.claude/rules/database-migration-patterns.md` |+| RLS policies and RLS helpers (authz manifest) | `.claude/rules/authz-manifest.md` || Working with the database package | `packages/database/AGENTS.md` || **Server & Services** | || Writing service functions | `.claude/rules/conventions-services.md` |diff --git a/apps/academy/app/entry.server.tsx b/apps/academy/app/entry.server.tsxindex 5c7c911225..87b319a785 100644--- a/apps/academy/app/entry.server.tsx+++ b/apps/academy/app/entry.server.tsx@@ -1,3 +1,8 @@+import { POSTHOG_API_HOST, SUPABASE_URL } from "@carbon/auth";+import {+ getNonce,+ setStrictContentSecurityPolicy+} from "@carbon/auth/middleware/security.server";import { ensureLoggingConfigured } from "@carbon/logger/config.server";import { handleRequest as vercelHandleRequest } from "@vercel/react-router/entry.server";import type { EntryContext, RouterContextProvider } from "react-router";@@ -13,12 +18,23 @@ export default function handleRequest(routerContext: EntryContext,_loadContext: RouterContextProvider // RouterContextProvider when v8_middleware is turned on) {+ const nonce = getNonce(_loadContext);+ setStrictContentSecurityPolicy(responseHeaders, nonce, {+ supabaseUrl: SUPABASE_URL,+ posthogHost: POSTHOG_API_HOST,+ // tailwind.css imports Google Fonts.+ extra: {+ "style-src": ["https://fonts.googleapis.com"],+ "font-src": ["https://fonts.gstatic.com"]+ }+ });return vercelHandleRequest(request,responseStatusCode,responseHeaders,routerContext,// @ts-expect-error- _loadContext // Vercel's handler still expecting AppLoadContext type+ _loadContext, // Vercel's handler still expecting AppLoadContext type+ { nonce });}diff --git a/apps/academy/app/root.tsx b/apps/academy/app/root.tsxindex f418591bb8..d195923541 100644--- a/apps/academy/app/root.tsx+++ b/apps/academy/app/root.tsx@@ -1,3 +1,4 @@+import "./zod.client";import { CONTROLLED_ENVIRONMENT, getBrowserEnv, getCarbon } from "@carbon/auth";import { flashClientMiddleware } from "@carbon/auth/middleware/flash.client";import {@@ -5,6 +6,7 @@ import {flashMiddleware,flashResultContext} from "@carbon/auth/middleware/flash.server";+import { securityMiddleware } from "@carbon/auth/middleware/security.server";import { getOrRefreshAuthSession } from "@carbon/auth/session.server";import { requestIdMiddleware } from "@carbon/logger/middleware.server";import {@@ -17,6 +19,7 @@ import { faviconLinks } from "@carbon/utils/favicon";import { I18nProvider } from "@react-aria/i18n";import { Analytics } from "@vercel/analytics/react";import type React from "react";+import { useContext } from "react";import type {LinksFunction,LoaderFunctionArgs,@@ -30,6 +33,7 @@ import {Outlet,Scripts,ScrollRestoration,+ UNSAFE_FrameworkContext,useLoaderData} from "react-router";import NProgress from "~/styles/nprogress.css?url";@@ -38,7 +42,11 @@ import { CourseSidebarNav } from "./components/CourseSidebar";import { SiteHeader } from "./components/SiteHeader";import { path } from "./utils/path";-export const middleware = [requestIdMiddleware, flashMiddleware];+export const middleware = [+ requestIdMiddleware,+ securityMiddleware,+ flashMiddleware+];export const clientMiddleware = [flashClientMiddleware];export const links: LinksFunction = () => [@@ -156,6 +164,7 @@ function Document({}export default function App() {+ const nonce = useContext(UNSAFE_FrameworkContext)?.nonce;const loaderData = useLoaderData<typeof loader>();const env = loaderData?.env ?? {};const prefs = loaderData?.preferences;@@ -169,6 +178,9 @@ export default function App() {<Outlet /></div><script+ // Server render only: on the client the nonce is undefined (and browsers hide it).+ nonce={nonce}+ suppressHydrationWarningdangerouslySetInnerHTML={{__html: `window.env = ${JSON.stringify(env)}`}}diff --git a/apps/academy/app/routes/_auth+/login.tsx b/apps/academy/app/routes/_auth+/login.tsxindex e61794462e..f46ae003e9 100644--- a/apps/academy/app/routes/_auth+/login.tsx+++ b/apps/academy/app/routes/_auth+/login.tsx@@ -29,6 +29,7 @@ import {useBotProtection,VStack} from "@carbon/react";+import { getClientIp } from "@carbon/utils";import { LuCircleAlert } from "react-icons/lu";import type {ActionFunctionArgs,@@ -64,7 +65,7 @@ export async function loader({ request }: LoaderFunctionArgs) {export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);- const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";+ const ip = getClientIp(request) ?? "127.0.0.1";const ratelimit = new Ratelimit({redis,limiter: Ratelimit.slidingWindow(RATE_LIMIT, "1 h"),diff --git a/apps/academy/app/routes/_auth+/mfa.tsx b/apps/academy/app/routes/_auth+/mfa.tsxindex 121b15f8d6..3da6066d35 100644--- a/apps/academy/app/routes/_auth+/mfa.tsx+++ b/apps/academy/app/routes/_auth+/mfa.tsx@@ -23,6 +23,7 @@ import {Heading,VStack} from "@carbon/react";+import { getClientIp } from "@carbon/utils";import { useEffect, useRef } from "react";import { LuCircleAlert } from "react-icons/lu";import type {@@ -71,7 +72,7 @@ export async function loader({ request }: LoaderFunctionArgs) {export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);- const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";+ const ip = getClientIp(request) ?? "127.0.0.1";const ratelimit = new Ratelimit({redis,diff --git a/apps/academy/app/routes/api+/csp-report.ts b/apps/academy/app/routes/api+/csp-report.tsnew file mode 100644index 0000000000..5e62dcec53--- /dev/null+++ b/apps/academy/app/routes/api+/csp-report.ts@@ -0,0 +1,7 @@+import { cspReportAction } from "@carbon/auth/middleware/security.server";+import type { ActionFunctionArgs } from "react-router";++// CSP_REPORT_PATH: where browsers send report-only CSP violations.+export async function action({ request }: ActionFunctionArgs) {+ return cspReportAction(request);+}diff --git a/apps/academy/app/routes/challenge+/$id.tsx b/apps/academy/app/routes/challenge+/$id.tsxindex 0dc07671b9..208701e508 100644--- a/apps/academy/app/routes/challenge+/$id.tsx+++ b/apps/academy/app/routes/challenge+/$id.tsx@@ -24,7 +24,10 @@ interface ActionData {}export async function action({ request }: ActionFunctionArgs) {- const { client, userId } = await requirePermissions(request, {});+ const { client, userId } = await requirePermissions(request, {+ // Records the learner's own progress, whatever their role in the company.+ allowPortalAccounts: true+ });const formData = await request.formData();const reset = formData.get("reset");diff --git a/apps/academy/app/zod.client.ts b/apps/academy/app/zod.client.tsnew file mode 100644index 0000000000..a37176591f--- /dev/null+++ b/apps/academy/app/zod.client.ts@@ -0,0 +1,7 @@+import { z } from "zod";++// Imported first by root.tsx — React Router's hydration script loads the route+// modules before entry.client, so this is the earliest code on the page:+// zod probes `new Function` once for its JIT, and the CSP refuses eval, so every+// page load would raise a violation report. Client only — the server keeps the JIT.+z.config({ jitless: true });diff --git a/apps/erp/app/components/Configurator/ConfigurationEditor/ConfigurationEditor.tsx b/apps/erp/app/components/Configurator/ConfigurationEditor/ConfigurationEditor.tsxindex 981a719622..035ec8dd51 100644--- a/apps/erp/app/components/Configurator/ConfigurationEditor/ConfigurationEditor.tsx+++ b/apps/erp/app/components/Configurator/ConfigurationEditor/ConfigurationEditor.tsx@@ -229,14 +229,8 @@ export default function Configurator({}}, [fetcher.data]);- const runCode = useCallback(() => {+ const runCode = useCallback(async () => {const jsCode = convertTypescriptToJavaScript(code);- if (isUnsafeCode(jsCode)) {- setOutput(- "Error: Unsupported code detected. The code you're trying to run contains disallowed patterns."- );- return;- }try {// Create parameters object from the panel@@ -257,16 +251,11 @@ export default function Configurator({{} as Record<string, any>);- // Execute the code- const fn = new Function(- "parameters",- `- ${jsCode}- return configure(parameters);- `+ // Rules run in the same QuickJS sandbox as get-method, never in this page's engine.+ const { runConfigurationRule } = await import(+ "@carbon/database/configuration-rule");-- const result = fn(parametersObj);+ const result: any = await runConfigurationRule(jsCode, parametersObj);// Verify return typeif (returnType.type === "list") {@@ -436,16 +425,3 @@ export default function Configurator({</>);}--function isUnsafeCode(code: string) {- // Check for disallowed code patterns- const disallowedPatterns = [- /\bfetch\b/, // fetch calls- /setTimeout|setInterval/, // timeouts- /\bimport\b/, // dynamic imports- /new Promise/, // promise construction- /Function\(/ // Function constructor- ];-- return disallowedPatterns.some((pattern) => pattern.test(code));-}diff --git a/apps/erp/app/entry.server.tsx b/apps/erp/app/entry.server.tsxindex 9edde6881b..542d2a3293 100644--- a/apps/erp/app/entry.server.tsx+++ b/apps/erp/app/entry.server.tsx@@ -1,3 +1,8 @@+import { POSTHOG_API_HOST, SUPABASE_URL } from "@carbon/auth";+import {+ getNonce,+ setStrictContentSecurityPolicy+} from "@carbon/auth/middleware/security.server";import { getLogger } from "@carbon/logger";import { ensureLoggingConfigured } from "@carbon/logger/config.server";import { getRequestId } from "@carbon/logger/middleware.server";@@ -46,12 +51,12 @@ if (export const streamTimeout = 60_000;-// Baseline security response headers (NIST 800-171 3.13.13 control-of-mobile-code-// + SC-7/SC-8 hardening). The CSP is a deliberately SAFE SUBSET: it omits-// default-src/script-src so it cannot break the SPA's script/style/connect-// loading, and sets only mobile-code / injection-vector controls — object-src-// 'none' (no plugins), base-uri 'self', frame-ancestors 'self' (no cross-origin-// framing/clickjacking while still allowing same-origin embeds like previews).+// The ENFORCED CSP (NIST 800-171 3.13.13 control-of-mobile-code + SC-7/SC-8+// hardening) is still this safe subset — object-src 'none' (no plugins),+// base-uri 'self', frame-ancestors 'self' (no cross-origin framing while still+// allowing same-origin embeds like previews). The strict nonce policy runs+// report-only beside it until its reports are clean+// (.ai/plans/2026-09-28-csp-csrf.md).const BASELINE_CSP_DIRECTIVES = ["object-src 'none'","base-uri 'self'",@@ -78,18 +83,19 @@ function composeContentSecurityPolicy(existing: string | null): string {: existing;}-function applySecurityHeaders(headers: Headers) {+// nosniff, X-Frame-Options, Referrer-Policy and HSTS are set on every response+// (resource routes included) by securityMiddleware in root.tsx.+function applySecurityHeaders(headers: Headers, nonce: string) {headers.set("Content-Security-Policy",composeContentSecurityPolicy(headers.get("Content-Security-Policy")));- headers.set("X-Content-Type-Options", "nosniff");- headers.set("X-Frame-Options", "SAMEORIGIN");- headers.set("Referrer-Policy", "strict-origin-when-cross-origin");- headers.set(- "Strict-Transport-Security",- "max-age=31536000; includeSubDomains"- );+ setStrictContentSecurityPolicy(headers, nonce, {+ supabaseUrl: SUPABASE_URL,+ posthogHost: POSTHOG_API_HOST,+ // The configurator runs its code with `new Function`.+ allowEval: true+ });}/**@@ -132,13 +138,15 @@ export default function handleRequest(routerContext: EntryContext,_loadContext: RouterContextProvider // RouterContextProvider when v8_middleware is turned on) {- applySecurityHeaders(responseHeaders);+ const nonce = getNonce(_loadContext);+ applySecurityHeaders(responseHeaders, nonce);return vercelHandleRequest(request,responseStatusCode,responseHeaders,routerContext,// @ts-expect-error- _loadContext // Vercel's handler still expecting AppLoadContext type+ _loadContext, // Vercel's handler still expecting AppLoadContext type+ { nonce });}diff --git a/apps/erp/app/modules/agent/kb/docs/reference/configurator.md b/apps/erp/app/modules/agent/kb/docs/reference/configurator.mdindex 129b903bff..b6a2d3b22e 100644--- a/apps/erp/app/modules/agent/kb/docs/reference/configurator.md+++ b/apps/erp/app/modules/agent/kb/docs/reference/configurator.md@@ -36,7 +36,7 @@ function configure(params: Params): number {}```-Rule code is transpiled and executed in a restricted sandbox (`packages/database/supabase/functions/lib/sandbox.ts`): no `fetch`, no `setTimeout`/`setInterval`, no dynamic `import`, no `new Promise`, no `Function` constructor. A rule that trips a banned pattern is neutered to `return null`, and any rule that throws falls back to the field's default. Rules are for deriving a value from the inputs, not for side effects.+Rule code runs in an isolated JavaScript sandbox (QuickJS, `packages/database/supabase/functions/shared/configuration-rule.ts`), both when a method is created and when you test a rule in the editor. The parameters are the only input and the returned value is the only output: a rule has no network, timers, or access to the page or server it runs in, and each run is limited in time and memory. A rule that fails to compile, throws, or exceeds a limit is ignored: a field keeps its default, and a bill of materials or process keeps all of its lines. Rules are for deriving a value from the inputs, not for side effects.Rules can also **filter** the method wholesale: a `billOfMaterial` or `billOfProcess` rule returns the list of component or operation names to keep, so a boolean parameter can drop a whole subassembly or an outside-processing step from the recipe.diff --git a/apps/erp/app/root.tsx b/apps/erp/app/root.tsxindex bead39a6f4..42b32431d8 100644--- a/apps/erp/app/root.tsx+++ b/apps/erp/app/root.tsx@@ -1,3 +1,4 @@+import "./zod.client";import { CONTROLLED_ENVIRONMENT, error, getBrowserEnv } from "@carbon/auth";import { flashClientMiddleware } from "@carbon/auth/middleware/flash.client";import {@@ -5,6 +6,7 @@ import {flashMiddleware,flashResultContext} from "@carbon/auth/middleware/flash.server";+import { securityMiddleware } from "@carbon/auth/middleware/security.server";import { validator } from "@carbon/form";import { LocaleProvider, resolveLanguage } from "@carbon/locale";import {@@ -30,7 +32,7 @@ import { I18nProvider } from "@react-aria/i18n";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { Analytics } from "@vercel/analytics/react";import type React from "react";-import { useState } from "react";+import { useContext, useState } from "react";import type {ActionFunctionArgs,LinksFunction,@@ -45,6 +47,7 @@ import {Outlet,Scripts,ScrollRestoration,+ UNSAFE_FrameworkContext,useLoaderData} from "react-router";import SonnerStyle from "sonner/dist/styles.css?url";@@ -61,6 +64,7 @@ export const middleware = [// First: publishes the request context so server code can reach it via ALS.requestContextMiddleware,requestIdMiddleware,+ securityMiddleware,flashMiddleware];export const clientMiddleware = [flashClientMiddleware];@@ -198,6 +202,7 @@ export function Document({theme?: string;env?: Record<string, unknown>;}) {+ const nonce = useContext(UNSAFE_FrameworkContext)?.nonce;const selectedTheme = themes.find((t) => t.name === theme) as| Theme| undefined;@@ -249,6 +254,9 @@ export function Document({window.env at module load and otherwise crashes hydration. */}{env ? (<script+ // Server render only: on the client the nonce is undefined (and browsers hide it).+ nonce={nonce}+ suppressHydrationWarningdangerouslySetInnerHTML={{__html: `window.env = ${JSON.stringify(env)};`}}diff --git a/apps/erp/app/routes/[.]well-known.mcp[.]json.ts b/apps/erp/app/routes/[.]well-known.mcp[.]json.tsindex d9d31ac01c..a2bbf6631e 100644--- a/apps/erp/app/routes/[.]well-known.mcp[.]json.ts+++ b/apps/erp/app/routes/[.]well-known.mcp[.]json.ts@@ -1,4 +1,5 @@import { getAppUrl } from "@carbon/env";+import { getRequestOrigin } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { buildMcpManifest } from "./api+/mcp+/lib/manifest";@@ -11,8 +12,8 @@ import { buildMcpManifest } from "./api+/mcp+/lib/manifest";* the agent as "no manifest exists".*/export async function loader({ request }: LoaderFunctionArgs) {- const url = new URL(request.url);- const origin = getAppUrl() || url.origin;+ const origin =+ getAppUrl() || getRequestOrigin(request) || new URL(request.url).origin;return new Response(JSON.stringify(buildMcpManifest(origin), null, 2), {status: 200,diff --git a/apps/erp/app/routes/[.]well-known.oauth-authorization-server.ts b/apps/erp/app/routes/[.]well-known.oauth-authorization-server.tsindex ccac19c426..06a6eb17d3 100644--- a/apps/erp/app/routes/[.]well-known.oauth-authorization-server.ts+++ b/apps/erp/app/routes/[.]well-known.oauth-authorization-server.ts@@ -1,9 +1,10 @@import { getAppUrl } from "@carbon/env";+import { getRequestOrigin } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";export async function loader({ request }: LoaderFunctionArgs) {- const url = new URL(request.url);- const issuer = getAppUrl() || url.origin;+ const issuer =+ getAppUrl() || getRequestOrigin(request) || new URL(request.url).origin;const metadata = {issuer,diff --git a/apps/erp/app/routes/[.]well-known.oauth-protected-resource.ts b/apps/erp/app/routes/[.]well-known.oauth-protected-resource.tsindex 09a5d51948..6eb35bd3ef 100644--- a/apps/erp/app/routes/[.]well-known.oauth-protected-resource.ts+++ b/apps/erp/app/routes/[.]well-known.oauth-protected-resource.ts@@ -1,9 +1,10 @@import { getAppUrl } from "@carbon/env";+import { getRequestOrigin } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";export async function loader({ request }: LoaderFunctionArgs) {- const url = new URL(request.url);- const origin = getAppUrl() || url.origin;+ const origin =+ getAppUrl() || getRequestOrigin(request) || new URL(request.url).origin;return new Response(JSON.stringify({diff --git a/apps/erp/app/routes/_public+/invite.$code.tsx b/apps/erp/app/routes/_public+/invite.$code.tsxindex b3b497b7d4..836e30ec04 100644--- a/apps/erp/app/routes/_public+/invite.$code.tsx+++ b/apps/erp/app/routes/_public+/invite.$code.tsx@@ -20,7 +20,7 @@ import { sendEmail } from "@carbon/lib/email.server";import { getLogger } from "@carbon/logger";import { Button as _Button, Heading as _Heading, VStack } from "@carbon/react";import { updateSubscriptionQuantityForCompany } from "@carbon/stripe/stripe.server";-import { datetime, Edition } from "@carbon/utils";+import { datetime, Edition, getClientIp } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import { render } from "@react-email/components";import { AnimatePresence, motion } from "framer-motion";@@ -109,9 +109,7 @@ export async function action({ request, params }: ActionFunctionArgs) {actorId: null,diff: { acceptedAt: { old: null, new: accept.data.acceptedAt } },metadata: {- ipAddress:- request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ??- undefined,+ ipAddress: getClientIp(request) ?? undefined,userAgent: request.headers.get("user-agent") ?? undefined}}@@ -172,9 +170,7 @@ async function requestNewInvite(code: string,serviceRole: ReturnType<typeof getCarbonServiceRole>) {- const ip =- request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ??- "127.0.0.1";+ const ip = getClientIp(request) ?? "127.0.0.1";const location = request.headers.get("x-vercel-ip-city") ?? "Unknown";const invite = await serviceRolediff --git a/apps/erp/app/routes/_public+/login.tsx b/apps/erp/app/routes/_public+/login.tsxindex 5c82082b9e..5b717d4d27 100644--- a/apps/erp/app/routes/_public+/login.tsx+++ b/apps/erp/app/routes/_public+/login.tsx@@ -48,7 +48,7 @@ import {useMount,VStack} from "@carbon/react";-import { Edition } from "@carbon/utils";+import { Edition, getClientIp } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import {browserSupportsWebAuthn,@@ -110,7 +110,7 @@ export async function loader({ request }: LoaderFunctionArgs) {export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);- const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";+ const ip = getClientIp(request) ?? "127.0.0.1";const ratelimit = new Ratelimit({redis,limiter: Ratelimit.slidingWindow(RATE_LIMIT, "1 h"),diff --git a/apps/erp/app/routes/_public+/mfa.tsx b/apps/erp/app/routes/_public+/mfa.tsxindex c6e428112c..983aabbbb4 100644--- a/apps/erp/app/routes/_public+/mfa.tsx+++ b/apps/erp/app/routes/_public+/mfa.tsx@@ -25,6 +25,7 @@ import {Heading,VStack} from "@carbon/react";+import { getClientIp } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import { useEffect, useRef } from "react";import { LuCircleAlert } from "react-icons/lu";@@ -76,7 +77,7 @@ export async function loader({ request }: LoaderFunctionArgs) {export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);- const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";+ const ip = getClientIp(request) ?? "127.0.0.1";const ratelimit = new Ratelimit({redis,diff --git a/apps/erp/app/routes/_public+/unlock.tsx b/apps/erp/app/routes/_public+/unlock.tsxindex 5eccd306fa..d3b05bf350 100644--- a/apps/erp/app/routes/_public+/unlock.tsx+++ b/apps/erp/app/routes/_public+/unlock.tsx@@ -35,6 +35,7 @@ import {toast,VStack} from "@carbon/react";+import { getClientIp } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import type { WebAuthnCredential } from "@simplewebauthn/browser";import {@@ -265,7 +266,7 @@ async function unlockWithPasskey(request: Request) {export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);- const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";+ const ip = getClientIp(request) ?? "127.0.0.1";const ratelimit = new Ratelimit({redis,diff --git a/apps/erp/app/routes/_public+/verify.tsx b/apps/erp/app/routes/_public+/verify.tsxindex a07e7c300c..182f481e09 100644--- a/apps/erp/app/routes/_public+/verify.tsx+++ b/apps/erp/app/routes/_public+/verify.tsx@@ -26,6 +26,7 @@ import {Heading,VStack} from "@carbon/react";+import { getClientIp } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import { LuCircleAlert } from "react-icons/lu";import type {@@ -66,7 +67,7 @@ export async function loader({ request }: LoaderFunctionArgs) {export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);- const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";+ const ip = getClientIp(request) ?? "127.0.0.1";const ratelimit = new Ratelimit({redis,diff --git a/apps/erp/app/routes/agent-setup.prompt[.]md.tsx b/apps/erp/app/routes/agent-setup.prompt[.]md.tsxindex 1de5c2e3c6..5541a6b036 100644--- a/apps/erp/app/routes/agent-setup.prompt[.]md.tsx+++ b/apps/erp/app/routes/agent-setup.prompt[.]md.tsx@@ -1,4 +1,5 @@import { getAppUrl } from "@carbon/env";+import { getRequestOrigin } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { buildAgentSetupPrompt } from "./api+/mcp+/lib/agent-setup-prompt";@@ -14,8 +15,8 @@ import { buildAgentSetupPrompt } from "./api+/mcp+/lib/agent-setup-prompt";* reads to the agent as "no document exists".*/export async function loader({ request }: LoaderFunctionArgs) {- const url = new URL(request.url);- const origin = getAppUrl() || url.origin;+ const origin =+ getAppUrl() || getRequestOrigin(request) || new URL(request.url).origin;return new Response(buildAgentSetupPrompt(origin), {status: 200,diff --git a/apps/erp/app/routes/api+/csp-report.ts b/apps/erp/app/routes/api+/csp-report.tsnew file mode 100644index 0000000000..5e62dcec53--- /dev/null+++ b/apps/erp/app/routes/api+/csp-report.ts@@ -0,0 +1,7 @@+import { cspReportAction } from "@carbon/auth/middleware/security.server";+import type { ActionFunctionArgs } from "react-router";++// CSP_REPORT_PATH: where browsers send report-only CSP violations.+export async function action({ request }: ActionFunctionArgs) {+ return cspReportAction(request);+}diff --git a/apps/erp/app/routes/api+/docs.ts b/apps/erp/app/routes/api+/docs.tsindex a89254a5c2..18dc7784c9 100644--- a/apps/erp/app/routes/api+/docs.ts+++ b/apps/erp/app/routes/api+/docs.ts@@ -1,5 +1,6 @@import swaggerDocsSchema from "@carbon/database/swagger-docs-schema";import { Ratelimit, redis } from "@carbon/kv";+import { getClientIp } from "@carbon/utils";import {type ClientLoaderFunctionArgs,data,@@ -8,7 +9,7 @@ import {import { docsQuery } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {- const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";+ const ip = getClientIp(request) ?? "127.0.0.1";const ratelimit = new Ratelimit({redis,limiter: Ratelimit.slidingWindow(20, "1 h"),diff --git a/apps/erp/app/routes/api+/integrations.stripe-connect.connect.ts b/apps/erp/app/routes/api+/integrations.stripe-connect.connect.tsindex db58ea7594..53ad16bd2a 100644--- a/apps/erp/app/routes/api+/integrations.stripe-connect.connect.ts+++ b/apps/erp/app/routes/api+/integrations.stripe-connect.connect.ts@@ -7,6 +7,7 @@ import {getOrCreateConnectAccount,isStaleConnectAccountError} from "@carbon/stripe/connect.server";+import { getRequestOrigin } from "@carbon/utils";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { redirect } from "react-router";import { path } from "~/utils/path";@@ -19,8 +20,10 @@ async function handle({ request }: { request: Request }) {});const url = new URL(request.url);- const returnUrl = `${url.origin}/api/integrations/stripe-connect/callback?status=success`;- const refreshUrl = `${url.origin}/api/integrations/stripe-connect/callback?status=refresh`;+ // Stripe sends the browser back here: the public origin, not request.url's.+ const origin = getRequestOrigin(request) ?? url.origin;+ const returnUrl = `${origin}/api/integrations/stripe-connect/callback?status=success`;+ const refreshUrl = `${origin}/api/integrations/stripe-connect/callback?status=refresh`;try {let stripeAccountId = await getOrCreateConnectAccount(diff --git a/apps/erp/app/routes/api+/integrations.stripe-connect.dashboard.ts b/apps/erp/app/routes/api+/integrations.stripe-connect.dashboard.tsindex d933af8dba..03691440df 100644--- a/apps/erp/app/routes/api+/integrations.stripe-connect.dashboard.ts+++ b/apps/erp/app/routes/api+/integrations.stripe-connect.dashboard.ts@@ -1,5 +1,6 @@import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";+import { rejectCrossSiteNavigation } from "@carbon/auth/middleware/security.server";import { flash } from "@carbon/auth/session.server";import { getLogger } from "@carbon/logger";import { createExpressDashboardLoginLink } from "@carbon/stripe/connect.server";@@ -77,6 +78,8 @@ async function handle({ request }: { request: Request }) {}export async function loader({ request }: LoaderFunctionArgs) {+ // Writes on GET: a link on another site must not trigger it.+ rejectCrossSiteNavigation(request);return handle({ request });}diff --git a/apps/erp/app/routes/api+/kanban.$id.tsx b/apps/erp/app/routes/api+/kanban.$id.tsxindex 5e92248e4e..a80e2b33b2 100644--- a/apps/erp/app/routes/api+/kanban.$id.tsx+++ b/apps/erp/app/routes/api+/kanban.$id.tsx@@ -1,6 +1,7 @@import { notFound } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { rejectCrossSiteNavigation } from "@carbon/auth/middleware/security.server";import type { Database } from "@carbon/database";import { trigger } from "@carbon/jobs";import { trackWorkEvent } from "@carbon/lib/telemetry";@@ -429,6 +430,8 @@ async function handleKanban({}export async function loader({ request, params }: LoaderFunctionArgs) {+ // Writes on GET: a link on another site must not trigger it.+ rejectCrossSiteNavigation(request);const { client, companyId, companyGroupId, userId } =await requirePermissions(request, {role: "employee"diff --git a/apps/erp/app/routes/api+/link.ts b/apps/erp/app/routes/api+/link.tsindex a372f255e8..9a58099a91 100644--- a/apps/erp/app/routes/api+/link.ts+++ b/apps/erp/app/routes/api+/link.ts@@ -113,7 +113,11 @@ export async function loader({ request }: LoaderFunctionArgs) {client,companyId: sessionCompanyId,userId- } = await requirePermissions(request, {});+ } = await requirePermissions(request, {+ // Notification links switch to the linked company, which must work from a+ // portal company session too.+ allowPortalAccounts: true+ });const url = new URL(request.url);const event = url.searchParams.get("event") as NotificationEvent | null;diff --git a/apps/erp/app/routes/api+/mcp+/_index.ts b/apps/erp/app/routes/api+/mcp+/_index.tsindex c092b26ea2..29118b931e 100644--- a/apps/erp/app/routes/api+/mcp+/_index.ts+++ b/apps/erp/app/routes/api+/mcp+/_index.ts@@ -10,7 +10,7 @@ import { createMcpServer } from "@carbon/ee/mcp.server";import { getAppUrl } from "@carbon/env";import { Ratelimit, redis } from "@carbon/kv";import { withLogContext } from "@carbon/logger/middleware.server";-import { datetime } from "@carbon/utils";+import { datetime, getRequestOrigin } from "@carbon/utils";import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";import type { ActionFunctionArgs } from "react-router";import { getCompanyTimeZone } from "~/modules/shared/timezone.server";@@ -117,7 +117,8 @@ function makeMcpDisabledResponse(): Response {}function make401Response(request: Request): Response {- const origin = getAppUrl() || new URL(request.url).origin;+ const origin =+ getAppUrl() || getRequestOrigin(request) || new URL(request.url).origin;return new Response(null, {status: 401,headers: {diff --git a/apps/erp/app/routes/api+/mfa.unenroll.ts b/apps/erp/app/routes/api+/mfa.unenroll.tsindex fc90b5c938..ff849866c9 100644--- a/apps/erp/app/routes/api+/mfa.unenroll.ts+++ b/apps/erp/app/routes/api+/mfa.unenroll.ts@@ -6,6 +6,7 @@ import {setAuthSession} from "@carbon/auth/session.server";import { Ratelimit, redis } from "@carbon/kv";+import { getClientIp } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";@@ -14,7 +15,7 @@ export async function action({ request }: ActionFunctionArgs) {await requirePermissions(request, {});const authSession = await requireAuthSession(request);- const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";+ const ip = getClientIp(request) ?? "127.0.0.1";const ratelimit = new Ratelimit({redis,limiter: Ratelimit.slidingWindow(RATE_LIMIT, "1 h"),diff --git a/apps/erp/app/routes/api+/mfa.verify.ts b/apps/erp/app/routes/api+/mfa.verify.tsindex dc8672479a..08dd92322b 100644--- a/apps/erp/app/routes/api+/mfa.verify.ts+++ b/apps/erp/app/routes/api+/mfa.verify.ts@@ -7,6 +7,7 @@ import {setAuthSession} from "@carbon/auth/session.server";import { Ratelimit, redis } from "@carbon/kv";+import { getClientIp } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { sendMfaEnabledEmail } from "~/services/mfa-email.server";@@ -16,7 +17,7 @@ export async function action({ request }: ActionFunctionArgs) {await requirePermissions(request, {});const authSession = await requireAuthSession(request);- const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";+ const ip = getClientIp(request) ?? "127.0.0.1";const ratelimit = new Ratelimit({redis,limiter: Ratelimit.slidingWindow(RATE_LIMIT, "1 h"),diff --git a/apps/erp/app/routes/api+/settings.bypass.ts b/apps/erp/app/routes/api+/settings.bypass.tsdeleted file mode 100644index 982acc5b40..0000000000--- a/apps/erp/app/routes/api+/settings.bypass.ts+++ /dev/null@@ -1,11 +0,0 @@-import { STRIPE_BYPASS_COMPANY_IDS } from "@carbon/auth";--export async function loader() {- if (STRIPE_BYPASS_COMPANY_IDS) {- const bypassList = STRIPE_BYPASS_COMPANY_IDS.split(",").map((id: string) =>- id.trim()- );- return { bypassList };- }- return { bypassList: [] };-}diff --git a/apps/erp/app/routes/api+/settings.sequence.next.ts b/apps/erp/app/routes/api+/settings.sequence.next.tsindex c402647183..8d0c1e8363 100644--- a/apps/erp/app/routes/api+/settings.sequence.next.ts+++ b/apps/erp/app/routes/api+/settings.sequence.next.ts@@ -1,11 +1,14 @@import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";+import { rejectCrossSiteNavigation } from "@carbon/auth/middleware/security.server";import { flash } from "@carbon/auth/session.server";import type { LoaderFunctionArgs } from "react-router";import { data } from "react-router";import { getNextSequence } from "~/modules/settings";export async function loader({ request }: LoaderFunctionArgs) {+ // Writes on GET: a link on another site must not trigger it.+ rejectCrossSiteNavigation(request);const { client, companyId } = await requirePermissions(request, {});const url = new URL(request.url);diff --git a/apps/erp/app/routes/api+/sso.check.ts b/apps/erp/app/routes/api+/sso.check.tsindex 535917f891..8a13a4e0b3 100644--- a/apps/erp/app/routes/api+/sso.check.ts+++ b/apps/erp/app/routes/api+/sso.check.ts@@ -2,6 +2,7 @@ import { assertIsPost } from "@carbon/auth";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { getSsoConnectionByDomain, isSsoEnabled } from "@carbon/ee/sso.server";import { Ratelimit, redis } from "@carbon/kv";+import { getClientIp } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";@@ -15,7 +16,7 @@ export async function action({ request }: ActionFunctionArgs) {return data({ enabled: false, required: false });}- const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";+ const ip = getClientIp(request) ?? "127.0.0.1";const ratelimit = new Ratelimit({redis,limiter: Ratelimit.slidingWindow(20, "1 h"),diff --git a/apps/erp/app/routes/api+/stock-transfer.$id.$lineId.pick.tsx b/apps/erp/app/routes/api+/stock-transfer.$id.$lineId.pick.tsxindex b444e214a0..2d2fe5a10f 100644--- a/apps/erp/app/routes/api+/stock-transfer.$id.$lineId.pick.tsx+++ b/apps/erp/app/routes/api+/stock-transfer.$id.$lineId.pick.tsx@@ -1,11 +1,14 @@import { error, notFound, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";+import { rejectCrossSiteNavigation } from "@carbon/auth/middleware/security.server";import { flash } from "@carbon/auth/session.server";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";import { path } from "~/utils/path";export async function loader({ request, params }: ActionFunctionArgs) {+ // Writes on GET: a link on another site must not trigger it.+ rejectCrossSiteNavigation(request);const { client } = await requirePermissions(request, {update: "inventory"});diff --git a/apps/erp/app/routes/api+/stock-transfer.$id.$lineId.unpick.tsx b/apps/erp/app/routes/api+/stock-transfer.$id.$lineId.unpick.tsxindex 4faad7334a..0157de2d75 100644--- a/apps/erp/app/routes/api+/stock-transfer.$id.$lineId.unpick.tsx+++ b/apps/erp/app/routes/api+/stock-transfer.$id.$lineId.unpick.tsx@@ -1,11 +1,14 @@import { error, notFound, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";+import { rejectCrossSiteNavigation } from "@carbon/auth/middleware/security.server";import { flash } from "@carbon/auth/session.server";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";import { path } from "~/utils/path";export async function loader({ request, params }: ActionFunctionArgs) {+ // Writes on GET: a link on another site must not trigger it.+ rejectCrossSiteNavigation(request);const { client } = await requirePermissions(request, {update: "inventory"});diff --git a/apps/erp/app/routes/file+/kanban+/$id.$action[.]png.tsx b/apps/erp/app/routes/file+/kanban+/$id.$action[.]png.tsxindex d040aa9321..a53e6755ff 100644--- a/apps/erp/app/routes/file+/kanban+/$id.$action[.]png.tsx+++ b/apps/erp/app/routes/file+/kanban+/$id.$action[.]png.tsx@@ -1,5 +1,6 @@import { requirePermissions } from "@carbon/auth/auth.server";import { generateQRCodeBuffer } from "@carbon/documents/qr";+import { getRequestOrigin } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { data } from "react-router";import { getKanban } from "~/modules/inventory/inventory.service";@@ -23,10 +24,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {return data({ error: "Unauthorized" }, { status: 401 });}- const url = new URL(request.url);let kanbanUrl = "";let qrColor = "000000";- const baseUrl = `${url.protocol}//${url.host}`;+ // The origin the user is on, not request.url's (internal, http) — it is+ // printed into the QR code.+ const baseUrl = getRequestOrigin(request) ?? new URL(request.url).origin;if (action === "order") {kanbanUrl = `${baseUrl}${path.to.api.kanban(id)}`;qrColor = "000000"; // blackdiff --git a/apps/erp/app/routes/file+/kanban+/labels.$action[.]pdf.tsx b/apps/erp/app/routes/file+/kanban+/labels.$action[.]pdf.tsxindex fdb55d989b..b61f46fde3 100644--- a/apps/erp/app/routes/file+/kanban+/labels.$action[.]pdf.tsx+++ b/apps/erp/app/routes/file+/kanban+/labels.$action[.]pdf.tsx@@ -1,6 +1,7 @@import { requirePermissions } from "@carbon/auth/auth.server";import { KanbanLabelPDF } from "@carbon/documents/pdf";import { getLogger } from "@carbon/logger";+import { getRequestOrigin } from "@carbon/utils";import { renderToStream } from "@react-pdf/renderer";import type { LoaderFunctionArgs } from "react-router";import { getCompany } from "~/modules/settings";@@ -27,7 +28,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const url = new URL(request.url);const idsParam = url.searchParams.get("ids");- const baseUrl = url.origin;+ const baseUrl = getRequestOrigin(request) ?? url.origin;if (!idsParam) {return new Response("No kanban IDs provided", { status: 400 });diff --git a/apps/erp/app/routes/file+/model+/public.$.tsx b/apps/erp/app/routes/file+/model+/public.$.tsxindex 6876f460ad..afc359d311 100644--- a/apps/erp/app/routes/file+/model+/public.$.tsx+++ b/apps/erp/app/routes/file+/model+/public.$.tsx@@ -1,12 +1,11 @@import { notFound } from "@carbon/auth";import { getCarbonServiceRole } from "@carbon/auth/client.server";import {+ fileResponseHeaders,getContentType,isUnsafeStoragePath,- MEDIA_CONTENT_TYPES,storage} from "@carbon/files";-import { supportedModelTypes } from "@carbon/files/cad";import { getLogger } from "@carbon/logger";import type { LoaderFunctionArgs } from "react-router";@@ -27,15 +26,13 @@ export async function loader({ params }: LoaderFunctionArgs) {throw notFound("Invalid path");}- const fileType = path.split(".").pop()?.toLowerCase();-- if (- !fileType ||- (!(fileType in MEDIA_CONTENT_TYPES) &&- !supportedModelTypes.includes(fileType))- )- throw new Error(`File type ${fileType} not supported`);- const contentType = getContentType(fileType);+ // Only the GLB the model viewer draws (`/file/model/$id`, rendered headless+ // for thumbnails). Any other type here is a tenant-uploaded file served with+ // no session — an SVG under models/ ran script on our origin.+ if (path.split(".").pop()?.toLowerCase() !== "glb") {+ logger.error("Refused a public model file type", { path });+ throw notFound("Invalid path");+ }// No auth session on this public route — the object path's first segment is// the companyId, which selects the per-company bucket (with legacy fallback).@@ -60,12 +57,12 @@ export async function loader({ params }: LoaderFunctionArgs) {}}- const headers = new Headers({- "Content-Type": contentType,- "Cache-Control": "public, max-age=31536000, immutable",- "Access-Control-Allow-Origin": "*", // Allow cross-origin requests- "Access-Control-Allow-Methods": "GET", // Only allow GET requests- "Access-Control-Allow-Headers": "Content-Type" // Allow Content-Type header- });+ const headers = fileResponseHeaders(+ getContentType("glb"),+ "public, max-age=31536000, immutable"+ );+ headers.set("Access-Control-Allow-Origin", "*");+ headers.set("Access-Control-Allow-Methods", "GET");+ headers.set("Access-Control-Allow-Headers", "Content-Type");return new Response(fileData, { status: 200, headers });}diff --git a/apps/erp/app/routes/file+/preview+/$bucket.$.tsx b/apps/erp/app/routes/file+/preview+/$bucket.$.tsxindex 37ea5e4087..723f67a5b3 100644--- a/apps/erp/app/routes/file+/preview+/$bucket.$.tsx+++ b/apps/erp/app/routes/file+/preview+/$bucket.$.tsx@@ -3,6 +3,7 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";import type { CompanyBucket } from "@carbon/files";import {effectiveExtension,+ fileResponseHeaders,getCompanyPrivateBucket,getContentType,isUnsafeStoragePath,@@ -16,7 +17,10 @@ import type { LoaderFunctionArgs } from "react-router";const logger = getLogger("erp", "bucket");export let loader = async ({ request, params }: LoaderFunctionArgs) => {- const { companyId } = await requirePermissions(request, {});+ // Employees only: the read below uses the service role, so this is the whole+ // gate. A customer or supplier portal account is also a session in the company+ // and would otherwise read every private file it has.+ const { companyId } = await requirePermissions(request, { role: "employee" });const { bucket } = params;let path = params["*"];@@ -50,7 +54,7 @@ export let loader = async ({ request, params }: LoaderFunctionArgs) => {// that bypass the app (API uploads): browsers outside Safari can't render// HEIC, so ask storage for the imgproxy JPEG rendition instead.const isHeicFile = effectiveType === "heic" || effectiveType === "heif";- let contentType = effectiveType ? getContentType(effectiveType) : undefined;+ let contentType = getContentType(effectiveType);// Authorize against the companyId as a full path segment (prefix or// slash-bounded), not a loose substring — `.includes(companyId)` lets@@ -123,13 +127,10 @@ export let loader = async ({ request, params }: LoaderFunctionArgs) => {}}- const headers = new Headers({- "Cache-Control": "private, max-age=31536000, immutable"- });-- if (contentType) {- headers.set("Content-Type", contentType);- }+ const headers = fileResponseHeaders(+ contentType,+ "private, max-age=31536000, immutable"+ );if (isZst) {// Stream the storage object through a zstd decompress transform (Nodediff --git a/apps/erp/app/routes/file+/preview+/image.tsx b/apps/erp/app/routes/file+/preview+/image.tsxindex 57cfb57913..f53dfebf16 100644--- a/apps/erp/app/routes/file+/preview+/image.tsx+++ b/apps/erp/app/routes/file+/preview+/image.tsx@@ -3,6 +3,9 @@ import type { LoaderFunctionArgs } from "react-router";import { path } from "~/utils/path";// this route exists so we can apply some styles to the preview iframe+const escapeAttribute = (value: string) =>+ value.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);+export let loader = async ({ request }: LoaderFunctionArgs) => {await requirePermissions(request, {view: "documents"@@ -31,9 +34,16 @@ export let loader = async ({ request }: LoaderFunctionArgs) => {</style></head><body>- <img src="${path.to.file.previewFile(file)}" />+ <img src="${escapeAttribute(path.to.file.previewFile(file))}" /></body></html>`;- const headers = new Headers({ "Content-Type": "text/html" });+ // `file` is attacker-controlled (it comes from the link): escaped above, and+ // this page runs no script at all even if escaping is ever lost.+ const headers = new Headers({+ "Content-Type": "text/html",+ "Content-Security-Policy":+ "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'",+ "X-Content-Type-Options": "nosniff"+ });return new Response(body, { status: 200, headers });};diff --git a/apps/erp/app/routes/onboarding+/industry.tsx b/apps/erp/app/routes/onboarding+/industry.tsxindex 754f7be418..7f79f16494 100644--- a/apps/erp/app/routes/onboarding+/industry.tsx+++ b/apps/erp/app/routes/onboarding+/industry.tsx@@ -92,7 +92,11 @@ function appendDraftCompany(}export async function loader({ request }: ActionFunctionArgs) {- const { client, companyId, email } = await requirePermissions(request, {});+ const { client, companyId, email } = await requirePermissions(request, {+ // Onboarding acts on the user's own account: a portal-only user may still+ // create a company of their own.+ allowPortalAccounts: true+ });// Restoring from a backup stays internal-only; the demo template and a clean// start are open to every signup.@@ -116,7 +120,11 @@ export async function loader({ request }: ActionFunctionArgs) {export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);- const { client, userId, email } = await requirePermissions(request, {});+ const { client, userId, email } = await requirePermissions(request, {+ // Onboarding acts on the user's own account: a portal-only user may still+ // create a company of their own.+ allowPortalAccounts: true+ });// Get draft data from previous step (company)const draft = await getOnboardingDraft(request);diff --git a/apps/erp/app/routes/onboarding+/user.tsx b/apps/erp/app/routes/onboarding+/user.tsxindex 6e6b87a3ae..886d0591fb 100644--- a/apps/erp/app/routes/onboarding+/user.tsx+++ b/apps/erp/app/routes/onboarding+/user.tsx@@ -34,7 +34,11 @@ import { path } from "~/utils/path";const logger = getLogger("erp", "user");export async function loader({ request }: ActionFunctionArgs) {- const { userId } = await requirePermissions(request, {});+ const { userId } = await requirePermissions(request, {+ // Onboarding acts on the user's own account: a portal-only user may still+ // create a company of their own.+ allowPortalAccounts: true+ });const user = await getUser(getCarbonServiceRole(), userId);if (user.error || !user.data) {@@ -46,7 +50,11 @@ export async function loader({ request }: ActionFunctionArgs) {export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);- const { userId } = await requirePermissions(request, {});+ const { userId } = await requirePermissions(request, {+ // Onboarding acts on the user's own account: a portal-only user may still+ // create a company of their own.+ allowPortalAccounts: true+ });const validation = await validator(onboardingUserValidator).validate(await request.formData()diff --git a/apps/erp/app/routes/share+/customer.$id.$.tsx b/apps/erp/app/routes/share+/customer.$id.$.tsxindex 5f2bb23788..98c33f2ae8 100644--- a/apps/erp/app/routes/share+/customer.$id.$.tsx+++ b/apps/erp/app/routes/share+/customer.$id.$.tsx@@ -1,6 +1,7 @@import { getCarbonServiceRole } from "@carbon/auth/client.server";import { companyHasFeature } from "@carbon/ee/plan.server";import {+ fileResponseHeaders,getContentType,hasCompanyPrivateObjectPathPrefix,isUnsafeStoragePath,@@ -10,6 +11,7 @@ import {import { supportedModelTypes } from "@carbon/files/cad";import { Ratelimit, redis } from "@carbon/kv";import { getLogger } from "@carbon/logger";+import { getClientIp } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { getJobByOperationId } from "~/modules/production";import { getCustomerPortal } from "~/modules/shared/shared.service";@@ -23,7 +25,7 @@ export let loader = async ({ params, request }: LoaderFunctionArgs) => {throw new Error("Customer ID is required");}- const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";+ const ip = getClientIp(request) ?? "127.0.0.1";const ratelimit = new Ratelimit({redis,limiter: Ratelimit.slidingWindow(10, "1 m"), // 10 downloads per minute@@ -132,9 +134,9 @@ export let loader = async ({ params, request }: LoaderFunctionArgs) => {}}- const headers = new Headers({- "Content-Type": contentType,- "Cache-Control": "private, max-age=31536000, immutable"- });+ const headers = fileResponseHeaders(+ contentType,+ "private, max-age=31536000, immutable"+ );return new Response(fileData, { status: 200, headers });};diff --git a/apps/erp/app/routes/x+/account+/$userId.attribute.tsx b/apps/erp/app/routes/x+/account+/$userId.attribute.tsxindex 6d21852ede..7047dd2def 100644--- a/apps/erp/app/routes/x+/account+/$userId.attribute.tsx+++ b/apps/erp/app/routes/x+/account+/$userId.attribute.tsx@@ -36,7 +36,7 @@ export async function action({ request, params }: ActionFunctionArgs) {const clientClaims = await getUserClaims(userId, companyId);const canUpdateAnyUser =// biome-ignore lint/complexity/useLiteralKeys: suppressed due to migration- clientClaims.permissions["users"]?.update?.includes(companyId);+ clientClaims.permissions["resources"]?.update?.includes(companyId);if (!canUpdateAnyUser && userId !== targetUserId) {return data(diff --git a/apps/erp/app/routes/x+/acknowledge.tsx b/apps/erp/app/routes/x+/acknowledge.tsxindex a4d7c85a75..4d3ffdf5a4 100644--- a/apps/erp/app/routes/x+/acknowledge.tsx+++ b/apps/erp/app/routes/x+/acknowledge.tsx@@ -7,7 +7,11 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { insertAuditLogEntries } from "@carbon/ee/audit.server";import { getLogger } from "@carbon/logger";-import { datetime, requiresItarEntityCertification } from "@carbon/utils";+import {+ datetime,+ getClientIp,+ requiresItarEntityCertification+} from "@carbon/utils";import { parseAbsolute } from "@internationalized/date";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";@@ -21,11 +25,7 @@ const logger = getLogger("erp", "acknowledge");/** Best-effort request metadata for the compliance record. */function getRequestMeta(request: Request) {- const forwardedFor = request.headers.get("x-forwarded-for");- const ipAddress =- forwardedFor?.split(",")[0]?.trim() ||- request.headers.get("x-real-ip") ||- null;+ const ipAddress = getClientIp(request);const userAgent = request.headers.get("user-agent") ?? null;return { ipAddress, userAgent };}diff --git a/apps/erp/app/routes/x+/items+/methods+/versions.activate.$id.tsx b/apps/erp/app/routes/x+/items+/methods+/versions.activate.$id.tsxindex 844442b321..e908ff34a8 100644--- a/apps/erp/app/routes/x+/items+/methods+/versions.activate.$id.tsx+++ b/apps/erp/app/routes/x+/items+/methods+/versions.activate.$id.tsx@@ -3,6 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";import { getLogger } from "@carbon/logger";+import { getRequestOrigin } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";import { checkRevisionLock } from "~/modules/items/items.server";@@ -42,17 +43,14 @@ export async function action({ request, params }: ActionFunctionArgs) {const redirectPath = requestReferrer(request)?.replace(methodToReplace, id);if (!redirectPath) {- // requestReferrer returns null when the Referer is missing or its origin- // differs from request.url's — behind a proxy the server can see an- // internal scheme/host, which rejects every same-site referrer.+ // requestReferrer returns null when the Referer is missing or points at+ // another origin.logger.warning("Method version activation could not resolve a redirect", {methodVersionId: id,methodToReplace,referer: request.headers.get("referer"),requestUrl: request.url,- host: request.headers.get("host"),- forwardedHost: request.headers.get("x-forwarded-host"),- forwardedProto: request.headers.get("x-forwarded-proto")+ origin: getRequestOrigin(request)});return {success: false,diff --git a/apps/erp/app/routes/x+/purchase-invoice+/new.tsx b/apps/erp/app/routes/x+/purchase-invoice+/new.tsxindex 48e12fabf3..2348632ba9 100644--- a/apps/erp/app/routes/x+/purchase-invoice+/new.tsx+++ b/apps/erp/app/routes/x+/purchase-invoice+/new.tsx@@ -1,6 +1,7 @@import { assertIsPost, error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { rejectCrossSiteNavigation } from "@carbon/auth/middleware/security.server";import { flash } from "@carbon/auth/session.server";import { storage } from "@carbon/files";import { validationError, validator } from "@carbon/form";@@ -33,6 +34,8 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {+ // Writes on GET: a link on another site must not trigger it.+ rejectCrossSiteNavigation(request);// we don't use the client here -- if they have this permission, we'll upgrade to a service role if neededconst { companyId, userId } = await requirePermissions(request, {create: "invoicing"diff --git a/apps/erp/app/routes/x+/sales-invoice+/new.tsx b/apps/erp/app/routes/x+/sales-invoice+/new.tsxindex aa7a13e936..b03f06ee39 100644--- a/apps/erp/app/routes/x+/sales-invoice+/new.tsx+++ b/apps/erp/app/routes/x+/sales-invoice+/new.tsx@@ -1,6 +1,7 @@import { assertIsPost, error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { rejectCrossSiteNavigation } from "@carbon/auth/middleware/security.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { msg } from "@lingui/core/macro";@@ -27,6 +28,8 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {+ // Writes on GET: a link on another site must not trigger it.+ rejectCrossSiteNavigation(request);// we don't use the client here -- if they have this permission, we'll upgrade to a service role if neededconst { companyId, userId } = await requirePermissions(request, {create: "invoicing"diff --git a/apps/erp/app/routes/x+/settings+/company.switch.$companyId.tsx b/apps/erp/app/routes/x+/settings+/company.switch.$companyId.tsxindex cec8ade48c..0266b46f27 100644--- a/apps/erp/app/routes/x+/settings+/company.switch.$companyId.tsx+++ b/apps/erp/app/routes/x+/settings+/company.switch.$companyId.tsx@@ -16,7 +16,11 @@ export async function loader() {}export async function action({ request, params }: ActionFunctionArgs) {- const { client, userId } = await requirePermissions(request, {});+ const { client, userId } = await requirePermissions(request, {+ // Switching away from a portal company must work: a user can be an+ // employee of one company and a customer or supplier of another.+ allowPortalAccounts: true+ });const formData = await request.formData();const redirectTo = formData.get("redirectTo");diff --git a/apps/erp/app/routes/x+/users+/bulk-edit-permissions.tsx b/apps/erp/app/routes/x+/users+/bulk-edit-permissions.tsxindex f2ea26604b..1b5e7875cf 100644--- a/apps/erp/app/routes/x+/users+/bulk-edit-permissions.tsx+++ b/apps/erp/app/routes/x+/users+/bulk-edit-permissions.tsx@@ -6,6 +6,7 @@ import { requireFeature } from "@carbon/ee/plan.server";import { validationError, validator } from "@carbon/form";import { batchTrigger } from "@carbon/jobs";import { getLogger } from "@carbon/logger";+import { getClientIp } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";import {@@ -81,7 +82,7 @@ export async function action({ request }: ActionFunctionArgs) {);}- const ip = request.headers.get("x-forwarded-for") ?? undefined;+ const ip = getClientIp(request) ?? undefined;const batchPayload = userIds.map((id) => ({payload: {diff --git a/apps/erp/app/routes/x+/users+/customers.new.tsx b/apps/erp/app/routes/x+/users+/customers.new.tsxindex 5eb53881a9..2302092f74 100644--- a/apps/erp/app/routes/x+/users+/customers.new.tsx+++ b/apps/erp/app/routes/x+/users+/customers.new.tsx@@ -12,6 +12,7 @@ import { getSsoAwareInviteLink } from "@carbon/ee/sso.server";import { validationError, validator } from "@carbon/form";import { sendEmail } from "@carbon/lib/email.server";import { getLogger } from "@carbon/logger";+import { getClientIp } from "@carbon/utils";import { render } from "@react-email/components";import { nanoid } from "nanoid";import type {@@ -67,7 +68,7 @@ export async function action({ request }: ActionFunctionArgs) {}const location = request.headers.get("x-vercel-ip-city") ?? "Unknown";- const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";+ const ip = getClientIp(request) ?? "127.0.0.1";const [company, user, invitee] = await Promise.all([client.from("company").select("name").eq("id", companyId).single(),client.from("user").select("email, fullName").eq("id", userId).single(),diff --git a/apps/erp/app/routes/x+/users+/deactivate.tsx b/apps/erp/app/routes/x+/users+/deactivate.tsxindex 07954646c5..e6fe59db9f 100644--- a/apps/erp/app/routes/x+/users+/deactivate.tsx+++ b/apps/erp/app/routes/x+/users+/deactivate.tsx@@ -4,6 +4,7 @@ import { flash } from "@carbon/auth/session.server";import { deactivateUser } from "@carbon/auth/users.server";import { validationError, validator } from "@carbon/form";import { batchTrigger } from "@carbon/jobs";+import { getClientIp } from "@carbon/utils";import type {ActionFunctionArgs,ClientActionFunctionArgs@@ -27,7 +28,7 @@ export async function action({ request }: ActionFunctionArgs) {const { users, redirectTo } = validation.data;- const ip = request.headers.get("x-forwarded-for") ?? undefined;+ const ip = getClientIp(request) ?? undefined;if (users.includes(userId)) {throw redirect(diff --git a/apps/erp/app/routes/x+/users+/employees.$employeeId.tsx b/apps/erp/app/routes/x+/users+/employees.$employeeId.tsxindex 7d6144a4f4..97ef52056f 100644--- a/apps/erp/app/routes/x+/users+/employees.$employeeId.tsx+++ b/apps/erp/app/routes/x+/users+/employees.$employeeId.tsx@@ -19,6 +19,7 @@ import {ModalTitle,VStack} from "@carbon/react";+import { getClientIp } from "@carbon/utils";import { Trans } from "@lingui/react/macro";import { LuShield } from "react-icons/lu";import type {@@ -190,7 +191,7 @@ export async function action({ request }: ActionFunctionArgs) {);}- const ip = request.headers.get("x-forwarded-for") ?? undefined;+ const ip = getClientIp(request) ?? undefined;const result = await updateEmployee(client, {id,diff --git a/apps/erp/app/routes/x+/users+/employees.new.tsx b/apps/erp/app/routes/x+/users+/employees.new.tsxindex 3b95ee7190..6f075db35c 100644--- a/apps/erp/app/routes/x+/users+/employees.new.tsx+++ b/apps/erp/app/routes/x+/users+/employees.new.tsx@@ -13,7 +13,7 @@ import { getSsoAwareInviteLink } from "@carbon/ee/sso.server";import { validationError, validator } from "@carbon/form";import { sendEmail } from "@carbon/lib/email.server";import { getLogger } from "@carbon/logger";-import { datetime } from "@carbon/utils";+import { datetime, getClientIp } from "@carbon/utils";import { render } from "@react-email/components";import { nanoid } from "nanoid";import type {@@ -148,7 +148,7 @@ export async function action({ request }: ActionFunctionArgs) {}const location = request.headers.get("x-vercel-ip-city") ?? "Unknown";- const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";+ const ip = getClientIp(request) ?? "127.0.0.1";const [company, user] = await Promise.all([client.from("company").select("name").eq("id", companyId).single(),client.from("user").select("email, fullName").eq("id", userId).single()diff --git a/apps/erp/app/routes/x+/users+/resend-invite.tsx b/apps/erp/app/routes/x+/users+/resend-invite.tsxindex fa11e4c719..f0f89e40a5 100644--- a/apps/erp/app/routes/x+/users+/resend-invite.tsx+++ b/apps/erp/app/routes/x+/users+/resend-invite.tsx@@ -7,7 +7,7 @@ import { getSsoAwareInviteLink } from "@carbon/ee/sso.server";import { validationError, validator } from "@carbon/form";import { batchTrigger } from "@carbon/jobs";import { sendEmail } from "@carbon/lib/email.server";-import { datetime } from "@carbon/utils";+import { datetime, getClientIp } from "@carbon/utils";import { render } from "@react-email/components";import { nanoid } from "nanoid";import type { ActionFunctionArgs } from "react-router";@@ -33,7 +33,7 @@ export async function action({ request }: ActionFunctionArgs) {if (users.length === 1) {const [userId] = users;const location = request.headers.get("x-vercel-ip-city") ?? "Unknown";- const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";+ const ip = getClientIp(request) ?? "127.0.0.1";const [company, user] = await Promise.all([serviceRole.from("company").select("name").eq("id", companyId).single(),serviceRole@@ -127,7 +127,7 @@ export async function action({ request }: ActionFunctionArgs) {);} else {const location = request.headers.get("x-vercel-ip-city") ?? "Unknown";- const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";+ const ip = getClientIp(request) ?? "127.0.0.1";try {await batchTrigger("user-admin",diff --git a/apps/erp/app/routes/x+/users+/revoke-invite.tsx b/apps/erp/app/routes/x+/users+/revoke-invite.tsxindex 0489a6ff85..5fc9b1b5ff 100644--- a/apps/erp/app/routes/x+/users+/revoke-invite.tsx+++ b/apps/erp/app/routes/x+/users+/revoke-invite.tsx@@ -8,7 +8,7 @@ import { validationError, validator } from "@carbon/form";import { batchTrigger } from "@carbon/jobs";import { getLogger } from "@carbon/logger";import { updateSubscriptionQuantityForCompany } from "@carbon/stripe/stripe.server";-import { datetime, Edition } from "@carbon/utils";+import { datetime, Edition, getClientIp } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { revokeInviteValidator } from "~/modules/users";@@ -30,7 +30,7 @@ export async function action({ request }: ActionFunctionArgs) {const { users } = validation.data;- const ip = request.headers.get("x-forwarded-for") ?? undefined;+ const ip = getClientIp(request) ?? undefined;const serviceRole = getCarbonServiceRole();@@ -119,9 +119,7 @@ export async function action({ request }: ActionFunctionArgs) {actorId: userId,diff: { revokedAt: { old: null, new: revokedAt } },metadata: {- ipAddress:- request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ??- undefined,+ ipAddress: getClientIp(request) ?? undefined,userAgent: request.headers.get("user-agent") ?? undefined}}))diff --git a/apps/erp/app/routes/x+/users+/suppliers.new.tsx b/apps/erp/app/routes/x+/users+/suppliers.new.tsxindex 9d7e082ea3..fc36e5b866 100644--- a/apps/erp/app/routes/x+/users+/suppliers.new.tsx+++ b/apps/erp/app/routes/x+/users+/suppliers.new.tsx@@ -12,6 +12,7 @@ import { getSsoAwareInviteLink } from "@carbon/ee/sso.server";import { validationError, validator } from "@carbon/form";import { sendEmail } from "@carbon/lib/email.server";import { getLogger } from "@carbon/logger";+import { getClientIp } from "@carbon/utils";import { render } from "@react-email/components";import { nanoid } from "nanoid";import type {@@ -67,7 +68,7 @@ export async function action({ request }: ActionFunctionArgs) {}const location = request.headers.get("x-vercel-ip-city") ?? "Unknown";- const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";+ const ip = getClientIp(request) ?? "127.0.0.1";const [company, user, invitee] = await Promise.all([client.from("company").select("name").eq("id", companyId).single(),client.from("user").select("email, fullName").eq("id", userId).single(),diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 64a0be5446..ae49f9baa8 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -4,6 +4,7 @@ import {getMESUrl,SUPABASE_URL} from "@carbon/auth";+import { getRequestOrigin } from "@carbon/utils";import { generatePath } from "react-router";const x = "/x"; // from ~/routes/x+ folder@@ -2398,26 +2399,17 @@ export const getStoragePath = (bucket: string, path: string) => {* cross-origin or unparsable referer yields null and callers fall back to* their fixed route.*- * Behind a TLS-terminating load balancer `request.url` is `http://` (the- * server does not trust proxy headers) while the browser's Referer is- * `https://`, so the scheme comes from `X-Forwarded-Proto` when it names one.- * Only the scheme is taken from it; the host still has to match.+ * Compared with the origin the client addressed (`getRequestOrigin`), not+ * `request.url`'s: behind the proxy that is the internal scheme and host, which+ * never matches a real Referer.*/export const requestReferrer = (request: Request, withParams = true) => {const referer = request.headers.get("referer");if (!referer) return null;try {- const requestUrl = new URL(request.url);- const forwardedProto = request.headers- .get("x-forwarded-proto")- ?.split(",")[0]- ?.trim()- .toLowerCase();- if (forwardedProto === "http" || forwardedProto === "https") {- requestUrl.protocol = `${forwardedProto}:`;- }- const url = new URL(referer, requestUrl.origin);- if (url.origin !== requestUrl.origin) return null;+ const origin = getRequestOrigin(request) ?? new URL(request.url).origin;+ const url = new URL(referer, origin);+ if (url.origin !== origin) return null;return url.pathname + url.search + url.hash;} catch {return null;diff --git a/apps/erp/app/zod.client.ts b/apps/erp/app/zod.client.tsnew file mode 100644index 0000000000..a37176591f--- /dev/null+++ b/apps/erp/app/zod.client.ts@@ -0,0 +1,7 @@+import { z } from "zod";++// Imported first by root.tsx — React Router's hydration script loads the route+// modules before entry.client, so this is the earliest code on the page:+// zod probes `new Function` once for its JIT, and the CSP refuses eval, so every+// page load would raise a violation report. Client only — the server keeps the JIT.+z.config({ jitless: true });diff --git a/apps/mes/app/entry.server.tsx b/apps/mes/app/entry.server.tsxindex 8500f2502a..074c2406f7 100644--- a/apps/mes/app/entry.server.tsx+++ b/apps/mes/app/entry.server.tsx@@ -1,3 +1,8 @@+import { POSTHOG_API_HOST, SUPABASE_URL } from "@carbon/auth";+import {+ getNonce,+ setStrictContentSecurityPolicy+} from "@carbon/auth/middleware/security.server";import { getLogger } from "@carbon/logger";import { ensureLoggingConfigured } from "@carbon/logger/config.server";import { getRequestId } from "@carbon/logger/middleware.server";@@ -44,12 +49,12 @@ if (export const streamTimeout = 60_000;-// Baseline security response headers (NIST 800-171 3.13.13 control-of-mobile-code-// + SC-7/SC-8 hardening). The CSP is a deliberately SAFE SUBSET: it omits-// default-src/script-src so it cannot break the SPA's script/style/connect-// loading, and sets only mobile-code / injection-vector controls — object-src-// 'none' (no plugins), base-uri 'self', frame-ancestors 'self' (no cross-origin-// framing/clickjacking while still allowing same-origin embeds like previews).+// The ENFORCED CSP (NIST 800-171 3.13.13 control-of-mobile-code + SC-7/SC-8+// hardening) is still this safe subset — object-src 'none' (no plugins),+// base-uri 'self', frame-ancestors 'self' (no cross-origin framing while still+// allowing same-origin embeds like previews). The strict nonce policy runs+// report-only beside it until its reports are clean+// (.ai/plans/2026-09-28-csp-csrf.md).const BASELINE_CSP_DIRECTIVES = ["object-src 'none'","base-uri 'self'",@@ -76,18 +81,17 @@ function composeContentSecurityPolicy(existing: string | null): string {: existing;}-function applySecurityHeaders(headers: Headers) {+// nosniff, X-Frame-Options, Referrer-Policy and HSTS are set on every response+// (resource routes included) by securityMiddleware in root.tsx.+function applySecurityHeaders(headers: Headers, nonce: string) {headers.set("Content-Security-Policy",composeContentSecurityPolicy(headers.get("Content-Security-Policy")));- headers.set("X-Content-Type-Options", "nosniff");- headers.set("X-Frame-Options", "SAMEORIGIN");- headers.set("Referrer-Policy", "strict-origin-when-cross-origin");- headers.set(- "Strict-Transport-Security",- "max-age=31536000; includeSubDomains"- );+ setStrictContentSecurityPolicy(headers, nonce, {+ supabaseUrl: SUPABASE_URL,+ posthogHost: POSTHOG_API_HOST+ });}/**@@ -130,13 +134,15 @@ export default function handleRequest(routerContext: EntryContext,_loadContext: RouterContextProvider // RouterContextProvider when v8_middleware is turned on) {- applySecurityHeaders(responseHeaders);+ const nonce = getNonce(_loadContext);+ applySecurityHeaders(responseHeaders, nonce);return vercelHandleRequest(request,responseStatusCode,responseHeaders,routerContext,// @ts-expect-error- _loadContext // Vercel's handler still expecting AppLoadContext type+ _loadContext, // Vercel's handler still expecting AppLoadContext type+ { nonce });}diff --git a/apps/mes/app/root.tsx b/apps/mes/app/root.tsxindex 3a627a312e..35cfb3697f 100644--- a/apps/mes/app/root.tsx+++ b/apps/mes/app/root.tsx@@ -1,3 +1,4 @@+import "./zod.client";import { CONTROLLED_ENVIRONMENT, error, getBrowserEnv } from "@carbon/auth";import { flashClientMiddleware } from "@carbon/auth/middleware/flash.client";import {@@ -5,6 +6,7 @@ import {flashMiddleware,flashResultContext} from "@carbon/auth/middleware/flash.server";+import { securityMiddleware } from "@carbon/auth/middleware/security.server";import { validator } from "@carbon/form";import { LocaleProvider, resolveLanguage } from "@carbon/locale";import {@@ -30,7 +32,7 @@ import { I18nProvider } from "@react-aria/i18n";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { Analytics } from "@vercel/analytics/react";import type React from "react";-import { useState } from "react";+import { useContext, useState } from "react";import type {ActionFunctionArgs,LoaderFunctionArgs,@@ -44,6 +46,7 @@ import {Outlet,Scripts,ScrollRestoration,+ UNSAFE_FrameworkContext,useLoaderData} from "react-router";import SonnerStyle from "sonner/dist/styles.css?url";@@ -60,6 +63,7 @@ export const middleware = [// First: publishes the request context so server code can reach it via ALS.requestContextMiddleware,requestIdMiddleware,+ securityMiddleware,flashMiddleware];export const clientMiddleware = [flashClientMiddleware];@@ -181,6 +185,7 @@ function Document({theme?: string;env?: Record<string, unknown>;}) {+ const nonce = useContext(UNSAFE_FrameworkContext)?.nonce;const selectedTheme = themes.find((t) => t.name === theme) as| Theme| undefined;@@ -233,6 +238,9 @@ function Document({window.env at module load and otherwise crashes hydration. */}{env ? (<script+ // Server render only: on the client the nonce is undefined (and browsers hide it).+ nonce={nonce}+ suppressHydrationWarningdangerouslySetInnerHTML={{__html: `window.env = ${JSON.stringify(env)};`}}diff --git a/apps/mes/app/routes/_public+/login.tsx b/apps/mes/app/routes/_public+/login.tsxindex 152fbe0824..d035bc8343 100644--- a/apps/mes/app/routes/_public+/login.tsx+++ b/apps/mes/app/routes/_public+/login.tsx@@ -42,7 +42,7 @@ import {useMount,VStack} from "@carbon/react";-import { Edition } from "@carbon/utils";+import { Edition, getClientIp } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import {browserSupportsWebAuthn,@@ -104,7 +104,7 @@ export async function loader({ request }: LoaderFunctionArgs) {export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);- const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";+ const ip = getClientIp(request) ?? "127.0.0.1";const ratelimit = new Ratelimit({redis,limiter: Ratelimit.slidingWindow(RATE_LIMIT, "1 h"),diff --git a/apps/mes/app/routes/_public+/mfa.tsx b/apps/mes/app/routes/_public+/mfa.tsxindex 4218c5bcf1..955e38f84a 100644--- a/apps/mes/app/routes/_public+/mfa.tsx+++ b/apps/mes/app/routes/_public+/mfa.tsx@@ -24,6 +24,7 @@ import {Heading,VStack} from "@carbon/react";+import { getClientIp } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import { useEffect, useRef } from "react";import { LuCircleAlert } from "react-icons/lu";@@ -73,7 +74,7 @@ export async function loader({ request }: LoaderFunctionArgs) {export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);- const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";+ const ip = getClientIp(request) ?? "127.0.0.1";const ratelimit = new Ratelimit({redis,diff --git a/apps/mes/app/routes/_public+/unlock.tsx b/apps/mes/app/routes/_public+/unlock.tsxindex 0c93c40af3..1172ae3bf4 100644--- a/apps/mes/app/routes/_public+/unlock.tsx+++ b/apps/mes/app/routes/_public+/unlock.tsx@@ -36,6 +36,7 @@ import {toast,VStack} from "@carbon/react";+import { getClientIp } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import {browserSupportsWebAuthn,@@ -267,7 +268,7 @@ async function unlockWithPasskey(request: Request) {export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);- const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";+ const ip = getClientIp(request) ?? "127.0.0.1";const ratelimit = new Ratelimit({redis,diff --git a/apps/mes/app/routes/api+/csp-report.ts b/apps/mes/app/routes/api+/csp-report.tsnew file mode 100644index 0000000000..5e62dcec53--- /dev/null+++ b/apps/mes/app/routes/api+/csp-report.ts@@ -0,0 +1,7 @@+import { cspReportAction } from "@carbon/auth/middleware/security.server";+import type { ActionFunctionArgs } from "react-router";++// CSP_REPORT_PATH: where browsers send report-only CSP violations.+export async function action({ request }: ActionFunctionArgs) {+ return cspReportAction(request);+}diff --git a/apps/mes/app/routes/api+/sso.check.ts b/apps/mes/app/routes/api+/sso.check.tsindex 535917f891..8a13a4e0b3 100644--- a/apps/mes/app/routes/api+/sso.check.ts+++ b/apps/mes/app/routes/api+/sso.check.ts@@ -2,6 +2,7 @@ import { assertIsPost } from "@carbon/auth";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { getSsoConnectionByDomain, isSsoEnabled } from "@carbon/ee/sso.server";import { Ratelimit, redis } from "@carbon/kv";+import { getClientIp } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";@@ -15,7 +16,7 @@ export async function action({ request }: ActionFunctionArgs) {return data({ enabled: false, required: false });}- const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";+ const ip = getClientIp(request) ?? "127.0.0.1";const ratelimit = new Ratelimit({redis,limiter: Ratelimit.slidingWindow(20, "1 h"),diff --git a/apps/mes/app/routes/file+/preview+/$bucket.$.tsx b/apps/mes/app/routes/file+/preview+/$bucket.$.tsxindex 83c431638f..75a89ad0a7 100644--- a/apps/mes/app/routes/file+/preview+/$bucket.$.tsx+++ b/apps/mes/app/routes/file+/preview+/$bucket.$.tsx@@ -3,6 +3,7 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";import type { CompanyBucket } from "@carbon/files";import {effectiveExtension,+ fileResponseHeaders,getCompanyPrivateBucket,getContentType,isUnsafeStoragePath,@@ -16,7 +17,10 @@ import type { LoaderFunctionArgs } from "react-router";const log = getLogger("mes");export let loader = async ({ request, params }: LoaderFunctionArgs) => {- const { companyId } = await requirePermissions(request, {});+ // Employees only: the read below uses the service role, so this is the whole+ // gate. A customer or supplier portal account is also a session in the company+ // and would otherwise read every private file it has.+ const { companyId } = await requirePermissions(request, { role: "employee" });const { bucket } = params;let path = params["*"];@@ -41,7 +45,7 @@ export let loader = async ({ request, params }: LoaderFunctionArgs) => {// that bypass the app (API uploads): browsers outside Safari can't render// HEIC, so ask storage for the imgproxy JPEG rendition instead.const isHeicFile = effectiveType === "heic" || effectiveType === "heif";- let contentType = effectiveType ? getContentType(effectiveType) : undefined;+ let contentType = getContentType(effectiveType);// Authorize against the companyId as a full path segment (prefix or// slash-bounded), not a loose substring — `.includes(companyId)` lets@@ -131,13 +135,10 @@ export let loader = async ({ request, params }: LoaderFunctionArgs) => {}}- const headers = new Headers({- "Cache-Control": "private, max-age=31536000, immutable"- });-- if (contentType) {- headers.set("Content-Type", contentType);- }+ const headers = fileResponseHeaders(+ contentType,+ "private, max-age=31536000, immutable"+ );if (isZst) {// Stream the storage object through a zstd decompress transform (Nodediff --git a/apps/mes/app/routes/file+/preview+/image.tsx b/apps/mes/app/routes/file+/preview+/image.tsxindex 85c38a74f4..8ba481bacb 100644--- a/apps/mes/app/routes/file+/preview+/image.tsx+++ b/apps/mes/app/routes/file+/preview+/image.tsx@@ -3,6 +3,9 @@ import type { LoaderFunctionArgs } from "react-router";import { path } from "~/utils/path";// this route exists so we can apply some styles to the preview iframe+const escapeAttribute = (value: string) =>+ value.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);+export let loader = async ({ request }: LoaderFunctionArgs) => {await requirePermissions(request, {view: "documents"@@ -31,9 +34,16 @@ export let loader = async ({ request }: LoaderFunctionArgs) => {</style></head><body>- <img src="${path.to.file.previewFile(file)}" />+ <img src="${escapeAttribute(path.to.file.previewFile(file))}" /></body></html>`;- const headers = new Headers({ "Content-Type": "text/html" });+ // `file` is attacker-controlled (it comes from the link): escaped above, and+ // this page runs no script at all even if escaping is ever lost.+ const headers = new Headers({+ "Content-Type": "text/html",+ "Content-Security-Policy":+ "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'",+ "X-Content-Type-Options": "nosniff"+ });return new Response(body, { status: 200, headers });};diff --git a/apps/mes/app/routes/x+/company.switch.$companyId.tsx b/apps/mes/app/routes/x+/company.switch.$companyId.tsxindex 95c8031b50..db7d1fb43a 100644--- a/apps/mes/app/routes/x+/company.switch.$companyId.tsx+++ b/apps/mes/app/routes/x+/company.switch.$companyId.tsx@@ -12,7 +12,11 @@ import { getLocation, setLocation } from "~/services/location.server";import { path, requestReferrer } from "~/utils/path";export async function action({ request, params }: ActionFunctionArgs) {- const { client, userId } = await requirePermissions(request, {});+ const { client, userId } = await requirePermissions(request, {+ // Switching away from a portal company must work: a user can be an+ // employee of one company and a customer or supplier of another.+ allowPortalAccounts: true+ });const companies = await getCompanies(client, userId);if (companies.error) {diff --git a/apps/mes/app/routes/x+/console.pin-in.tsx b/apps/mes/app/routes/x+/console.pin-in.tsxindex a8fc8278eb..584c1fe170 100644--- a/apps/mes/app/routes/x+/console.pin-in.tsx+++ b/apps/mes/app/routes/x+/console.pin-in.tsx@@ -4,6 +4,7 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";import { setConsolePinIn } from "@carbon/auth/console-pin.server";import { verifyEmployeePin } from "@carbon/ee/console.server";import { AccountLockout, Ratelimit, redis } from "@carbon/kv";+import { getClientIp } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { userContext } from "~/context";@@ -61,7 +62,7 @@ export async function action({ request, context }: ActionFunctionArgs) {return data({ error: "userId is required" }, { status: 400 });}- const ip = request.headers.get("x-forwarded-for") ?? undefined;+ const ip = getClientIp(request) ?? undefined;const lockoutKey = `${companyId}:${userId}`;const terminalKey = `${companyId}:${sessionUserId}`;diff --git a/apps/mes/app/routes/x+/end.$operationId.tsx b/apps/mes/app/routes/x+/end.$operationId.tsxindex 7649617951..6a2f62049f 100644--- a/apps/mes/app/routes/x+/end.$operationId.tsx+++ b/apps/mes/app/routes/x+/end.$operationId.tsx@@ -1,6 +1,7 @@import { error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { rejectCrossSiteNavigation } from "@carbon/auth/middleware/security.server";import { flash } from "@carbon/auth/session.server";import { evaluateLinesForSurface, isBlocked } from "@carbon/ee/rules.server";import { getLogger } from "@carbon/logger";@@ -18,6 +19,8 @@ import { path } from "~/utils/path";const logger = getLogger("mes", "end-operation");export async function loader({ request, params }: LoaderFunctionArgs) {+ // Writes on GET: a link on another site must not trigger it.+ rejectCrossSiteNavigation(request);const { userId, companyId } = await requirePermissions(request, {});const { operationId } = params;diff --git a/apps/mes/app/routes/x+/start.$operationId.tsx b/apps/mes/app/routes/x+/start.$operationId.tsxindex 2e7302ffdd..c287d63f1f 100644--- a/apps/mes/app/routes/x+/start.$operationId.tsx+++ b/apps/mes/app/routes/x+/start.$operationId.tsx@@ -1,6 +1,7 @@import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { rejectCrossSiteNavigation } from "@carbon/auth/middleware/security.server";import { flash } from "@carbon/auth/session.server";import { activeJobStatuses } from "@carbon/database";import { evaluateLinesForSurface, isBlocked } from "@carbon/ee/rules.server";@@ -20,6 +21,8 @@ import { path } from "~/utils/path";const logger = getLogger("mes", "start-operation");export async function loader({ request, params }: LoaderFunctionArgs) {+ // Writes on GET: a link on another site must not trigger it.+ rejectCrossSiteNavigation(request);const { userId, companyId } = await requirePermissions(request, {});const { operationId } = params;if (!operationId) throw new Error("Operation ID is required");diff --git a/apps/mes/app/services/itar.service.ts b/apps/mes/app/services/itar.service.tsindex 9aa3743d5a..1d4663f328 100644--- a/apps/mes/app/services/itar.service.ts+++ b/apps/mes/app/services/itar.service.ts@@ -6,7 +6,7 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";import type { Database } from "@carbon/database";import { insertAuditLogEntries } from "@carbon/ee/audit.server";import { getLogger } from "@carbon/logger";-import { datetime } from "@carbon/utils";+import { datetime, getClientIp } from "@carbon/utils";import { parseAbsolute } from "@internationalized/date";import type { SupabaseClient } from "@supabase/supabase-js";import { z } from "zod";@@ -81,11 +81,7 @@ export async function getItarCertificationStatus(}export function getRequestMeta(request: Request) {- const forwardedFor = request.headers.get("x-forwarded-for");- const ipAddress =- forwardedFor?.split(",")[0]?.trim() ||- request.headers.get("x-real-ip") ||- null;+ const ipAddress = getClientIp(request);const userAgent = request.headers.get("user-agent") ?? null;return { ipAddress, userAgent };}diff --git a/apps/mes/app/zod.client.ts b/apps/mes/app/zod.client.tsnew file mode 100644index 0000000000..a37176591f--- /dev/null+++ b/apps/mes/app/zod.client.ts@@ -0,0 +1,7 @@+import { z } from "zod";++// Imported first by root.tsx — React Router's hydration script loads the route+// modules before entry.client, so this is the earliest code on the page:+// zod probes `new Function` once for its JIT, and the CSP refuses eval, so every+// page load would raise a violation report. Client only — the server keeps the JIT.+z.config({ jitless: true });diff --git a/apps/starter/app/entry.server.tsx b/apps/starter/app/entry.server.tsxindex 5c7c911225..eabcc16bd1 100644--- a/apps/starter/app/entry.server.tsx+++ b/apps/starter/app/entry.server.tsx@@ -1,3 +1,8 @@+import { POSTHOG_API_HOST, SUPABASE_URL } from "@carbon/auth";+import {+ getNonce,+ setStrictContentSecurityPolicy+} from "@carbon/auth/middleware/security.server";import { ensureLoggingConfigured } from "@carbon/logger/config.server";import { handleRequest as vercelHandleRequest } from "@vercel/react-router/entry.server";import type { EntryContext, RouterContextProvider } from "react-router";@@ -13,12 +18,18 @@ export default function handleRequest(routerContext: EntryContext,_loadContext: RouterContextProvider // RouterContextProvider when v8_middleware is turned on) {+ const nonce = getNonce(_loadContext);+ setStrictContentSecurityPolicy(responseHeaders, nonce, {+ supabaseUrl: SUPABASE_URL,+ posthogHost: POSTHOG_API_HOST+ });return vercelHandleRequest(request,responseStatusCode,responseHeaders,routerContext,// @ts-expect-error- _loadContext // Vercel's handler still expecting AppLoadContext type+ _loadContext, // Vercel's handler still expecting AppLoadContext type+ { nonce });}diff --git a/apps/starter/app/root.tsx b/apps/starter/app/root.tsxindex 6da75d9be1..5acea41a7c 100644--- a/apps/starter/app/root.tsx+++ b/apps/starter/app/root.tsx@@ -1,3 +1,4 @@+import "./zod.client";import { CONTROLLED_ENVIRONMENT, error, getBrowserEnv } from "@carbon/auth";import { flashClientMiddleware } from "@carbon/auth/middleware/flash.client";import {@@ -5,6 +6,7 @@ import {flashMiddleware,flashResultContext} from "@carbon/auth/middleware/flash.server";+import { securityMiddleware } from "@carbon/auth/middleware/security.server";import { validator } from "@carbon/form";import { requestIdMiddleware } from "@carbon/logger/middleware.server";import { Button, Heading, Toaster, useMode } from "@carbon/react";@@ -13,6 +15,7 @@ import { modeValidator, themes } from "@carbon/utils";import { faviconLinks } from "@carbon/utils/favicon";import { Analytics } from "@vercel/analytics/react";import type React from "react";+import { useContext } from "react";import type {ActionFunctionArgs,LinksFunction,@@ -27,6 +30,7 @@ import {Outlet,Scripts,ScrollRestoration,+ UNSAFE_FrameworkContext,useLoaderData} from "react-router";import { getMode, setMode } from "~/services/mode.server";@@ -35,7 +39,11 @@ import NProgress from "~/styles/nprogress.css?url";import Tailwind from "~/styles/tailwind.css?url";import { getTheme } from "./services/theme.server";-export const middleware = [requestIdMiddleware, flashMiddleware];+export const middleware = [+ requestIdMiddleware,+ securityMiddleware,+ flashMiddleware+];export const clientMiddleware = [flashClientMiddleware];export const links: LinksFunction = () => [@@ -176,6 +184,7 @@ function Document({}export default function App() {+ const nonce = useContext(UNSAFE_FrameworkContext)?.nonce;const loaderData = useLoaderData<typeof loader>();const env = loaderData?.env ?? {};const theme = loaderData?.theme ?? "zinc";@@ -187,6 +196,9 @@ export default function App() {<Document mode={mode} theme={theme}><Outlet /><script+ // Server render only: on the client the nonce is undefined (and browsers hide it).+ nonce={nonce}+ suppressHydrationWarningdangerouslySetInnerHTML={{__html: `window.env = ${JSON.stringify(env)}`}}diff --git a/apps/starter/app/routes/_public+/login.tsx b/apps/starter/app/routes/_public+/login.tsxindex 2fd0512db8..523908dd10 100644--- a/apps/starter/app/routes/_public+/login.tsx+++ b/apps/starter/app/routes/_public+/login.tsx@@ -29,6 +29,7 @@ import {useBotProtection,VStack} from "@carbon/react";+import { getClientIp } from "@carbon/utils";import { LuCircleAlert } from "react-icons/lu";import type {ActionFunctionArgs,@@ -64,7 +65,7 @@ export async function loader({ request }: LoaderFunctionArgs) {export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);- const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";+ const ip = getClientIp(request) ?? "127.0.0.1";const ratelimit = new Ratelimit({redis,limiter: Ratelimit.slidingWindow(RATE_LIMIT, "1 h"),diff --git a/apps/starter/app/routes/_public+/mfa.tsx b/apps/starter/app/routes/_public+/mfa.tsxindex 612605c84d..7c08b01831 100644--- a/apps/starter/app/routes/_public+/mfa.tsx+++ b/apps/starter/app/routes/_public+/mfa.tsx@@ -23,6 +23,7 @@ import {Heading,VStack} from "@carbon/react";+import { getClientIp } from "@carbon/utils";import { useEffect, useRef } from "react";import { LuCircleAlert } from "react-icons/lu";import type {@@ -71,7 +72,7 @@ export async function loader({ request }: LoaderFunctionArgs) {export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);- const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";+ const ip = getClientIp(request) ?? "127.0.0.1";const ratelimit = new Ratelimit({redis,diff --git a/apps/starter/app/routes/api+/csp-report.ts b/apps/starter/app/routes/api+/csp-report.tsnew file mode 100644index 0000000000..5e62dcec53--- /dev/null+++ b/apps/starter/app/routes/api+/csp-report.ts@@ -0,0 +1,7 @@+import { cspReportAction } from "@carbon/auth/middleware/security.server";+import type { ActionFunctionArgs } from "react-router";++// CSP_REPORT_PATH: where browsers send report-only CSP violations.+export async function action({ request }: ActionFunctionArgs) {+ return cspReportAction(request);+}diff --git a/apps/starter/app/routes/x+/company.switch.$companyId.tsx b/apps/starter/app/routes/x+/company.switch.$companyId.tsxindex 0e893c877c..40adf404b3 100644--- a/apps/starter/app/routes/x+/company.switch.$companyId.tsx+++ b/apps/starter/app/routes/x+/company.switch.$companyId.tsx@@ -12,7 +12,11 @@ import { redirect } from "react-router";import { path, requestReferrer } from "~/utils/path";export async function action({ request, params }: ActionFunctionArgs) {- const { client, userId } = await requirePermissions(request, {});+ const { client, userId } = await requirePermissions(request, {+ // Switching away from a portal company must work: a user can be an+ // employee of one company and a customer or supplier of another.+ allowPortalAccounts: true+ });const companies = await getCompanies(client, userId);if (companies.error) {diff --git a/apps/starter/app/zod.client.ts b/apps/starter/app/zod.client.tsnew file mode 100644index 0000000000..a37176591f--- /dev/null+++ b/apps/starter/app/zod.client.ts@@ -0,0 +1,7 @@+import { z } from "zod";++// Imported first by root.tsx — React Router's hydration script loads the route+// modules before entry.client, so this is the earliest code on the page:+// zod probes `new Function` once for its JIT, and the CSP refuses eval, so every+// page load would raise a violation report. Client only — the server keeps the JIT.+z.config({ jitless: true });diff --git a/docs/content/docs/reference/configurator.mdx b/docs/content/docs/reference/configurator.mdxindex 6e2a75e9f7..e345a4e8f7 100644--- a/docs/content/docs/reference/configurator.mdx+++ b/docs/content/docs/reference/configurator.mdx@@ -40,7 +40,7 @@ function configure(params: Params): number {```<Callout type="note" title="Rules run in a sandbox — keep them pure">-Rule code is transpiled and executed in a restricted sandbox (`packages/database/supabase/functions/lib/sandbox.ts`): no `fetch`, no `setTimeout`/`setInterval`, no dynamic `import`, no `new Promise`, no `Function` constructor. A rule that trips a banned pattern is neutered to `return null`, and any rule that throws falls back to the field's default. Rules are for deriving a value from the inputs, not for side effects.+Rule code runs in an isolated JavaScript sandbox (QuickJS, `packages/database/supabase/functions/shared/configuration-rule.ts`), both when a method is created and when you test a rule in the editor. The parameters are the only input and the returned value is the only output: a rule has no network, timers, or access to the page or server it runs in, and each run is limited in time and memory. A rule that fails to compile, throws, or exceeds a limit is ignored: a field keeps its default, and a bill of materials or process keeps all of its lines. Rules are for deriving a value from the inputs, not for side effects.</Callout>Rules can also **filter** the method wholesale: a `billOfMaterial` or `billOfProcess` rule returns the list of component or operation names to keep, so a boolean parameter can drop a whole subassembly or an outside-processing step from the recipe.diff --git a/packages/auth/AGENTS.md b/packages/auth/AGENTS.mdindex 17a724f946..5292ccb744 100644--- a/packages/auth/AGENTS.md+++ b/packages/auth/AGENTS.md@@ -5,10 +5,13 @@ Authentication, RBAC, session management, Supabase client factories, API key aut## Always- Gate loaders/actions with `requirePermissions(request, { view?, create?, update?, delete? })` — never construct Supabase clients directly in routes.+- `requirePermissions` refuses customer and supplier portal sessions with a 403 (API keys are unaffected). `{}` used to admit them everywhere, and ~50 routes that then read with the service role were reachable by a portal account. Pass `allowPortalAccounts: true` ONLY on a route that acts on the user's own identity (onboarding, company switch, notification links, academy progress) — never on one that returns company data.- Use the factory from `@carbon/auth/client.server`: `getCarbon(accessToken)` for user-scoped (RLS), `getCarbonServiceRole()` for privileged server ops only.- Invalidate Redis permission cache (`redis.del(getPermissionCacheKey(userId))`) when changing user permissions — stale cache is the #1 cause of "Access Denied" bugs.- API key `scopes: {}` **denies all** — never treat empty scopes as full access.- Import env constants from `@carbon/auth` (re-exports `@carbon/env`) — not `process.env` directly.+- Keep `securityMiddleware` in every app's root `middleware`. It refuses cross-origin POST/PUT/PATCH/DELETE (CSRF), issues the CSP nonce and sets `nosniff`/`X-Frame-Options`/`Referrer-Policy`/HSTS on every response. A route that browsers must reach from another origin goes in `CROSS_ORIGIN_ENDPOINTS` (`lib/security.ts`) — webhooks and API-key callers do not need it (servers send neither `Sec-Fetch-Site` nor `Origin`).+- A loader that writes on GET calls `rejectCrossSiteNavigation(request)` first: the `SameSite=Lax` session cookie still rides a top-level link from another site.- Re-issue the session cookie after any `supabase.auth.mfa.challengeAndVerify` — it rotates the refresh token, and the old one dies after GoTrue's reuse interval.## Ask First@@ -44,6 +47,7 @@ pnpm --filter @carbon/auth test| `./console-pin.server` | MES console pin-in cookie (signed, bound to company + terminal session user): `setConsolePinIn`, `clearConsolePinIn`, `resolveConsolePinIn` (re-validated against the DB, memoized per read), `ConsolePinIn`; `requirePermissions` uses it to derive `userId` in console mode || `./self-signup.server` | Cloud self-signup blocklist: `isSelfSignupBlockedForEmail`, `SELF_SIGNUP_BLOCKED_MESSAGE` (free/disposable email domains; used by ERP login/verify/callback + MES callback) || `./middleware/flash.server` | Flash message middleware |+| `./middleware/security.server` | `securityMiddleware` (CSRF check + CSP nonce + baseline headers), `rejectCrossSiteNavigation`, `getNonce`, `setStrictContentSecurityPolicy` (report-only for now; `entry.server` calls it), `cspReportAction` + `CSP_REPORT_PATH`. The decisions are pure and tested in `lib/security.ts` |SAML SSO lives in `@carbon/ee/sso.server` (Enterprise-gated), NOT here — authonly carries `AuthSession.ssoProviderId` and its preservation across refresh.diff --git a/packages/auth/package.json b/packages/auth/package.jsonindex 0ca74a00cf..073bdc6dbc 100644--- a/packages/auth/package.json+++ b/packages/auth/package.json@@ -26,6 +26,7 @@"./passkey.server": "./src/services/passkey.server.ts","./verification.server": "./src/services/verification.server.ts","./middleware/flash.server": "./src/middleware/flash.server.ts",+ "./middleware/security.server": "./src/middleware/security.server.ts","./middleware/flash.client": "./src/middleware/flash.client.ts"},"main": "./src/index.ts",diff --git a/packages/auth/src/lib/oauth-state.server.ts b/packages/auth/src/lib/oauth-state.server.tsindex 9d0d2358f4..23e1338b64 100644--- a/packages/auth/src/lib/oauth-state.server.ts+++ b/packages/auth/src/lib/oauth-state.server.ts@@ -42,7 +42,7 @@ const oauthStateStorage = createCookieSessionStorage({path: "/",sameSite: isTestEdition ? "none" : "lax",secrets: [SESSION_SECRET!],- secure: !!cookieDomain,+ secure: isTestEdition || !!cookieDomain,domain: cookieDomain,maxAge: OAUTH_STATE_MAX_AGE_SECONDS}diff --git a/packages/auth/src/lib/security.test.ts b/packages/auth/src/lib/security.test.tsnew file mode 100644index 0000000000..a797d13f2b--- /dev/null+++ b/packages/auth/src/lib/security.test.ts@@ -0,0 +1,156 @@+import { describe, expect, it } from "vitest";+import {+ buildContentSecurityPolicy,+ isCrossOriginRequestAllowed,+ isCrossSiteNavigation+} from "./security";++const h = (headers: Record<string, string>) => new Headers(headers);+const erp = { host: "app.carbon.ms" };++describe("isCrossOriginRequestAllowed", () => {+ it("never checks safe methods", () => {+ for (const method of ["GET", "HEAD", "OPTIONS"]) {+ expect(+ isCrossOriginRequestAllowed(+ method,+ "/x",+ h({ ...erp, "sec-fetch-site": "cross-site" })+ )+ ).toBe(true);+ }+ });++ it("refuses a cross-site or same-site browser POST", () => {+ for (const site of ["cross-site", "same-site"]) {+ expect(+ isCrossOriginRequestAllowed(+ "POST",+ "/x/sales-order/1.data",+ h({ ...erp, "sec-fetch-site": site })+ )+ ).toBe(false);+ }+ });++ it("allows a same-origin or user-initiated POST", () => {+ for (const site of ["same-origin", "none"]) {+ expect(+ isCrossOriginRequestAllowed(+ "POST",+ "/x",+ h({ ...erp, "sec-fetch-site": site })+ )+ ).toBe(true);+ }+ });++ it("falls back to Origin against the addressed host, not the internal URL", () => {+ expect(+ isCrossOriginRequestAllowed(+ "POST",+ "/x",+ h({+ host: "127.0.0.1:3000",+ "x-forwarded-host": "app.carbon.ms",+ origin: "https://app.carbon.ms"+ })+ )+ ).toBe(true);+ expect(+ isCrossOriginRequestAllowed(+ "POST",+ "/x",+ h({ ...erp, origin: "https://docs.carbon.ms" })+ )+ ).toBe(false);+ expect(+ isCrossOriginRequestAllowed("POST", "/x", h({ ...erp, origin: "null" }))+ ).toBe(false);+ });++ it("allows server-to-server calls, which send neither header", () => {+ expect(+ isCrossOriginRequestAllowed("POST", "/api/webhook/stripe", h(erp))+ ).toBe(true);+ });++ it("lets browsers reach the MCP endpoints from anywhere", () => {+ for (const path of ["/token", "/register", "/api/mcp", "/api/mcp/"]) {+ expect(+ isCrossOriginRequestAllowed(+ "POST",+ path,+ h({ ...erp, "sec-fetch-site": "cross-site" })+ )+ ).toBe(true);+ }+ expect(+ isCrossOriginRequestAllowed(+ "POST",+ "/authorize",+ h({ ...erp, "sec-fetch-site": "cross-site" })+ )+ ).toBe(false);+ });+});++describe("isCrossSiteNavigation", () => {+ it("only flags cross-site", () => {+ expect(isCrossSiteNavigation(h({ "sec-fetch-site": "cross-site" }))).toBe(+ true+ );+ for (const site of ["none", "same-origin", "same-site"]) {+ expect(isCrossSiteNavigation(h({ "sec-fetch-site": site }))).toBe(false);+ }+ expect(isCrossSiteNavigation(h({}))).toBe(false);+ });+});++describe("buildContentSecurityPolicy", () => {+ const policy = (options = {}) =>+ Object.fromEntries(+ buildContentSecurityPolicy({+ nonce: "abc",+ supabaseUrl: "https://api.carbon.ms",+ posthogHost: "https://us.posthog.com",+ ...options+ })+ .split("; ")+ .map((d) => [d.split(" ")[0], d.split(" ").slice(1)])+ );++ it("runs only nonced scripts, with no eval unless asked", () => {+ const p = policy();+ expect(p["script-src"]).toContain("'nonce-abc'");+ expect(p["script-src"]).toContain("'strict-dynamic'");+ expect(p["script-src"]).not.toContain("'unsafe-eval'");+ expect(policy({ allowEval: true })["script-src"]).toContain(+ "'unsafe-eval'"+ );+ });++ it("connects to Supabase over https and websockets", () => {+ expect(policy()["connect-src"]).toEqual(+ expect.arrayContaining([+ "https://api.carbon.ms",+ "wss://api.carbon.ms",+ "https://*.posthog.com"+ ])+ );+ expect(+ policy({ supabaseUrl: "http://localhost:54321" })["connect-src"]+ ).toContain("ws://localhost:54321");+ });++ it("keeps the baseline directives and adds extras", () => {+ const p = policy({+ extra: { "font-src": ["https://fonts.gstatic.com"] },+ reportUri: "/api/csp-report"+ });+ expect(p["object-src"]).toEqual(["'none'"]);+ expect(p["frame-ancestors"]).toEqual(["'self'"]);+ expect(p["font-src"]).toContain("https://fonts.gstatic.com");+ expect(p["report-uri"]).toEqual(["/api/csp-report"]);+ });+});diff --git a/packages/auth/src/lib/security.ts b/packages/auth/src/lib/security.tsnew file mode 100644index 0000000000..6e42dd855c--- /dev/null+++ b/packages/auth/src/lib/security.ts@@ -0,0 +1,172 @@+// Pure request-security decisions shared by every app. No env or I/O here, so the+// rules are unit-tested as plain functions; the middleware in+// ../middleware/security.server.ts wires them to requests.++import { getRequestHost } from "@carbon/utils";++type HeaderReader = Pick<Headers, "get">;++const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);++/**+ * Endpoints browsers call from other origins by design: MCP clients register,+ * exchange tokens and talk to the MCP transport from wherever they run. None of+ * them reads the session cookie.+ */+const CROSS_ORIGIN_ENDPOINTS = ["/token", "/register", "/api/mcp"];++/**+ * CSRF check for a state-changing request (the algorithm of Go's+ * `http.CrossOriginProtection`). Browsers always send `Sec-Fetch-Site` or+ * `Origin` on a cross-origin POST; servers (webhooks, Inngest, the assembler,+ * API-key clients) send neither and are not relying on our cookies.+ *+ * `same-site` is refused on purpose: the session cookie is set on the parent+ * domain, so every `*.carbon.ms` host is same-site to the ERP.+ */+export function isCrossOriginRequestAllowed(+ method: string,+ pathname: string,+ headers: HeaderReader+): boolean {+ if (SAFE_METHODS.has(method.toUpperCase())) return true;++ // Browser submissions arrive as React Router single-fetch `…/path.data`.+ const path = pathname.replace(/\.data$/, "").replace(/(.)\/$/, "$1");+ if (CROSS_ORIGIN_ENDPOINTS.includes(path)) return true;++ const site = headers.get("sec-fetch-site");+ if (site) return site === "same-origin" || site === "none";++ const origin = headers.get("origin");+ if (!origin) return true;++ // The host the browser addressed, never `request.url`'s (the internal origin+ // behind the proxy).+ const host = getRequestHost({ headers });+ if (!host) return false;+ try {+ return new URL(origin).host === host;+ } catch {+ // `Origin: null` (sandboxed documents, privacy redirects).+ return false;+ }+}++/**+ * A top-level navigation started on another site. A loader that writes on GET+ * (the kanban QR flow, MES start/end) refuses these: a scanned QR code or typed+ * URL is `none`, and the ERP→MES redirect is `same-site`.+ */+export function isCrossSiteNavigation(headers: HeaderReader): boolean {+ return headers.get("sec-fetch-site") === "cross-site";+}++export function createNonce(): string {+ return btoa(+ String.fromCharCode(...crypto.getRandomValues(new Uint8Array(16)))+ );+}++type Directive =+ | "default-src"+ | "script-src"+ | "style-src"+ | "img-src"+ | "font-src"+ | "connect-src"+ | "frame-src"+ | "worker-src"+ | "media-src"+ | "object-src"+ | "base-uri"+ | "frame-ancestors";++export type ContentSecurityPolicyOptions = {+ nonce: string;+ /** Browser Supabase URL: REST, storage and realtime (ws/wss). */+ supabaseUrl?: string;+ posthogHost?: string;+ /** `new Function` in the ERP configurator; remove with that follow-up. */+ allowEval?: boolean;+ /** Extra sources per directive (e.g. Google Fonts for academy). */+ extra?: Partial<Record<Directive, string[]>>;+ reportUri?: string;+};++const originOf = (url: string | undefined) => {+ if (!url) return null;+ try {+ return new URL(url).origin;+ } catch {+ return null;+ }+};++/**+ * The strict app policy: scripts run only when they carry this response's nonce+ * or are loaded by one that does ('strict-dynamic'), so injected markup cannot+ * run script. Why each exception exists is in .ai/plans/2026-09-28-csp-csrf.md.+ */+export function buildContentSecurityPolicy({+ nonce,+ supabaseUrl,+ posthogHost,+ allowEval = false,+ extra = {},+ reportUri+}: ContentSecurityPolicyOptions): string {+ const supabase = originOf(supabaseUrl);+ const posthog = originOf(posthogHost);++ const directives: Record<Directive, string[]> = {+ "default-src": ["'self'"],+ "script-src": [+ `'nonce-${nonce}'`,+ "'strict-dynamic'",+ "'wasm-unsafe-eval'",+ ...(allowEval ? ["'unsafe-eval'"] : []),+ // Ignored by CSP3 browsers (nonce + strict-dynamic win); the fallback for+ // older ones.+ "https:",+ "'unsafe-inline'"+ ],+ "style-src": ["'self'", "'unsafe-inline'", "https://cdn.jsdelivr.net"],+ "img-src": ["'self'", "data:", "blob:", "https:"],+ "font-src": ["'self'", "data:", "https://cdn.jsdelivr.net"],+ "connect-src": [+ "'self'",+ ...(supabase ? [supabase, supabase.replace(/^http/, "ws")] : []),+ ...(posthog+ ? new URL(posthog).hostname.endsWith("posthog.com")+ ? ["https://*.posthog.com"]+ : [posthog]+ : []),+ "https://places.googleapis.com",+ "https://cdn.jsdelivr.net"+ ],+ "frame-src": [+ "'self'",+ "blob:",+ "data:",+ "https://www.youtube.com",+ "https://www.youtube-nocookie.com",+ "https://www.loom.com",+ "https://challenges.cloudflare.com"+ ],+ "worker-src": ["'self'", "blob:", "data:"],+ "media-src": ["'self'"],+ "object-src": ["'none'"],+ "base-uri": ["'self'"],+ "frame-ancestors": ["'self'"]+ };+ for (const [name, sources] of Object.entries(extra)) {+ directives[name as Directive].push(...(sources ?? []));+ }++ const policy = Object.entries(directives).map(+ ([name, sources]) => `${name} ${[...new Set(sources)].join(" ")}`+ );+ if (reportUri) policy.push(`report-uri ${reportUri}`);+ return policy.join("; ");+}diff --git a/packages/auth/src/middleware/security.server.ts b/packages/auth/src/middleware/security.server.tsnew file mode 100644index 0000000000..8abed1639e--- /dev/null+++ b/packages/auth/src/middleware/security.server.ts@@ -0,0 +1,126 @@+import { getLogger } from "@carbon/logger";+import {+ createContext,+ type MiddlewareFunction,+ type RouterContextProvider+} from "react-router";+import {+ buildContentSecurityPolicy,+ type ContentSecurityPolicyOptions,+ createNonce,+ isCrossOriginRequestAllowed,+ isCrossSiteNavigation+} from "../lib/security";++/** Where every app receives CSP violation reports (`api+/csp-report.ts`). */+export const CSP_REPORT_PATH = "/api/csp-report";++/**+ * The strict policy on a document response. Report-only until production+ * reports are clean; enforcing it is renaming the header here.+ */+export function setStrictContentSecurityPolicy(+ headers: Headers,+ nonce: string,+ options: Omit<ContentSecurityPolicyOptions, "nonce" | "reportUri">+): void {+ if (!nonce) return;+ headers.set(+ "Content-Security-Policy-Report-Only",+ buildContentSecurityPolicy({+ ...options,+ nonce,+ reportUri: CSP_REPORT_PATH+ })+ );+}++const log = getLogger("auth", "security");++/** This request's CSP nonce; `entry.server` hands it to React Router. */+const nonceContext = createContext<string>("");++export const getNonce = (context: Readonly<RouterContextProvider>) =>+ context.get(nonceContext);++// On every response, resource and `.data` routes included: `entry.server` only+// runs for documents.+const RESPONSE_HEADERS: Record<string, string> = {+ "X-Content-Type-Options": "nosniff",+ "X-Frame-Options": "SAMEORIGIN",+ "Referrer-Policy": "strict-origin-when-cross-origin",+ "Strict-Transport-Security": "max-age=31536000; includeSubDomains"+};++function withSecurityHeaders(response: Response): Response {+ const missing = Object.entries(RESPONSE_HEADERS).filter(+ ([name]) => !response.headers.has(name)+ );+ if (missing.length === 0) return response;+ try {+ for (const [name, value] of missing) response.headers.set(name, value);+ return response;+ } catch {+ // Immutable headers (a proxied `fetch` response): copy, then set.+ const copy = new Response(response.body, response);+ for (const [name, value] of missing) copy.headers.set(name, value);+ return copy;+ }+}++/**+ * Root middleware for every app: refuses cross-origin state-changing requests+ * (CSRF), issues the CSP nonce, and adds the baseline security headers.+ */+export const securityMiddleware: MiddlewareFunction<Response> = async (+ { request, context },+ next+) => {+ const { pathname } = new URL(request.url);+ if (!isCrossOriginRequestAllowed(request.method, pathname, request.headers)) {+ log.warn("Refused a cross-origin {method} {pathname}", {+ method: request.method,+ pathname,+ origin: request.headers.get("origin"),+ secFetchSite: request.headers.get("sec-fetch-site")+ });+ return withSecurityHeaders(+ new Response("Cross-origin request refused", { status: 403 })+ );+ }+ context.set(nonceContext, createNonce());+ return withSecurityHeaders(await next());+};++/**+ * For loaders that write on GET (QR scan flows): a link on another site must not+ * be able to trigger them through the SameSite=Lax session cookie.+ */+export function rejectCrossSiteNavigation(request: Request): void {+ if (!isCrossSiteNavigation(request.headers)) return;+ const { pathname } = new URL(request.url);+ log.warn("Refused a cross-site navigation to {pathname}", { pathname });+ throw new Response("Cross-site request refused", { status: 403 });+}++/**+ * `report-uri` target for the report-only CSP. Logs a trimmed violation and+ * never fails: the reporter is the browser and nothing reads the reply.+ */+export async function cspReportAction(request: Request): Promise<Response> {+ const body = (await request.text()).slice(0, 16_384);+ try {+ const report = JSON.parse(body)["csp-report"];+ if (!report || typeof report !== "object") throw new Error("not a report");+ log.warn("CSP violation: {directive} {blocked}", {+ directive: report["effective-directive"] ?? report["violated-directive"],+ blocked: report["blocked-uri"],+ document: report["document-uri"],+ source: report["source-file"],+ line: report["line-number"]+ });+ } catch {+ log.warn("Unreadable CSP report", { body: body.slice(0, 512) });+ }+ return new Response(null, { status: 204 });+}diff --git a/packages/auth/src/services/auth.server.ts b/packages/auth/src/services/auth.server.tsindex 42af007ece..4eeac22c68 100644--- a/packages/auth/src/services/auth.server.ts+++ b/packages/auth/src/services/auth.server.ts@@ -6,7 +6,7 @@ import {import { redis } from "@carbon/kv";import { getLogger } from "@carbon/logger";import { oncePerRequest } from "@carbon/logger/middleware.server";-import { Edition, Plan } from "@carbon/utils";+import { Edition, getClientIp, Plan } from "@carbon/utils";import type {AuthSession as SupabaseAuthSession,SupabaseClient@@ -191,6 +191,12 @@ export async function requirePermissions(delete?: string | string[];role?: string;bypassRls?: boolean;+ /**+ * Also admit customer and supplier portal accounts. Only for routes that+ * act on the signed-in user's own identity (onboarding); everything else+ * holds company data they must not reach.+ */+ allowPortalAccounts?: boolean;}): Promise<{client: SupabaseClient<Database>;@@ -264,7 +270,12 @@ export async function requirePermissions(const scopes = apiKeyData.scopes ?? {};const scopeCheckPassed = Object.entries(requiredPermissions).every(([action, permission]) => {- if (action === "bypassRls" || action === "role") return true;+ if (+ action === "bypassRls" ||+ action === "role" ||+ action === "allowPortalAccounts"+ )+ return true;if (typeof permission === "string") {const scopeKey = `${permission}_${action}`;return scopeKey in scopes && scopes[scopeKey]?.includes(companyId);@@ -335,6 +346,27 @@ export async function requirePermissions(const myClaims = await getUserClaims(userId, companyId);+ // A customer or supplier portal account is a member of the company too, and+ // holds a few permissions (documents, parts, sales/purchasing view), but no+ // route in the apps is theirs — portal pages are share links served with the+ // service role. Before this check, `{}` and those permissions admitted them to+ // every route that then reads with the service role (file previews, job+ // travelers, order and quote pages). A 403, not a redirect: the MES shell calls+ // requirePermissions itself, so a redirect to it would loop.+ if (+ (myClaims.role === "customer" || myClaims.role === "supplier") &&+ !requiredPermissions.allowPortalAccounts+ ) {+ logAuthEvent("permission_denied", {+ userId,+ actor: email,+ companyId,+ ip: getClientIp(request) ?? undefined,+ reason: `${myClaims.role} portal account`+ });+ throw new Response("Forbidden", { status: 403 });+ }+// early exit if no requiredPermissions are requiredif (Object.keys(requiredPermissions).length === 0) {return {@@ -353,7 +385,8 @@ export async function requirePermissions(const hasRequiredPermissions = Object.entries(requiredPermissions).every(([action, permission]) => {- if (action === "bypassRls") return true;+ if (action === "bypassRls" || action === "allowPortalAccounts")+ return true;if (typeof permission === "string") {if (action === "role") {return myClaims.role === permission;@@ -383,7 +416,7 @@ export async function requirePermissions(userId,actor: email,companyId,- ip: request.headers.get("x-forwarded-for") ?? undefined,+ ip: getClientIp(request) ?? undefined,reason: JSON.stringify(requiredPermissions)});if (myClaims.role === null) {diff --git a/packages/auth/src/services/bot-protection.server.ts b/packages/auth/src/services/bot-protection.server.tsindex 20f356b00c..56776fda62 100644--- a/packages/auth/src/services/bot-protection.server.ts+++ b/packages/auth/src/services/bot-protection.server.ts@@ -115,8 +115,7 @@ async function verifyTurnstileToken(body: new URLSearchParams({secret: CLOUDFLARE_TURNSTILE_SECRET_KEY ?? "",response: token,- // the client address, not the full x-forwarded-for proxy chain- remoteip: remoteip.split(",")[0]?.trim() ?? ""+ remoteip})});diff --git a/packages/auth/src/services/company.server.ts b/packages/auth/src/services/company.server.tsindex 82eaea8893..37b76d8166 100644--- a/packages/auth/src/services/company.server.ts+++ b/packages/auth/src/services/company.server.ts@@ -7,6 +7,12 @@ import { getCookieDomain } from "../utils/cookie";const cookieName = "companyId";const isTestEdition = CarbonEdition === Edition.Test;const cookieDomain = isTestEdition ? undefined : getCookieDomain(DOMAIN);+// The same SameSite/Secure rules as the session cookie.+const attributes = {+ domain: cookieDomain,+ sameSite: isTestEdition ? ("none" as const) : ("lax" as const),+ secure: isTestEdition || !!cookieDomain+};export function getCompanyId(request: Request): string | null {const cookieHeader = request.headers.get("Cookie");@@ -19,14 +25,14 @@ export function setCompanyId(companyId: string | null) {return cookie.serialize(cookieName, "", {path: "/",expires: new Date(0),- domain: cookieDomain+ ...attributes});}return cookie.serialize(cookieName, companyId, {path: "/",maxAge: 31536000, // 1 year- domain: cookieDomain+ ...attributes});}diff --git a/packages/auth/src/services/console-pin.server.ts b/packages/auth/src/services/console-pin.server.tsindex a0d8494a1f..e7f35ae7a8 100644--- a/packages/auth/src/services/console-pin.server.ts+++ b/packages/auth/src/services/console-pin.server.ts@@ -54,7 +54,7 @@ interface StoredConsolePinIn extends ConsolePinIn {}const isTestEdition = CarbonEdition === Edition.Test;-const secure = !!getCookieDomain(DOMAIN);+const secure = isTestEdition || !!getCookieDomain(DOMAIN);const cookies = new Map<string, Cookie>();diff --git a/packages/auth/src/services/session.server.ts b/packages/auth/src/services/session.server.tsindex c4a6e574ed..d13ba45b3a 100644--- a/packages/auth/src/services/session.server.ts+++ b/packages/auth/src/services/session.server.ts@@ -58,7 +58,7 @@ const sessionStorage = createCookieSessionStorage({path: "/",sameSite: isTestEdition ? "none" : "lax",secrets: [SESSION_SECRET!],- secure: !!cookieDomain,+ secure: isTestEdition || !!cookieDomain,domain: cookieDomain}});diff --git a/packages/checks/AGENTS.md b/packages/checks/AGENTS.mdindex 1b96e65bd0..2b6e23af8d 100644--- a/packages/checks/AGENTS.md+++ b/packages/checks/AGENTS.md@@ -32,6 +32,8 @@ pnpm --filter @carbon/checks baseline # regenerate baseline (careful!)## Key Patterns- **Conformance checks**: `noNumericPrecision`, `noLegacyRls`, `noDerivedPercentColumn`, `noRequiredColumnWithoutDefault`, `noViewWithoutInvoker` — scan SQL migrations for anti-patterns (`noDerivedPercentColumn` flags a `*Percent`/`*Rate` column `GENERATED ALWAYS AS` an expression that divides — a percentage is an entered fact, never a lossy echo of a rounded amount; `noViewWithoutInvoker` fails a `CREATE [OR REPLACE] VIEW` that does not state `security_invoker` — `CREATE OR REPLACE` replaces a view's options, so omitting the clause turns it into an owner-rights view that bypasses RLS for every PostgREST caller, and `openJobMaterialLines` leaked every company's rows that way. `security_invoker = false` passes, so an owner-rights view is a visible decision; materialized views are not matched. It reads one file's text, so an `EXECUTE format(...)` view or a later `ALTER VIEW … RESET` escapes it — the invariant below is the backstop); `noLocalTimezone` (in `SERVER_CHECKS`) scans server TS (`sources/server-files.ts`) for `getLocalTimeZone()`, UTC day-slicing, local date-parts of now (`new Date().getDay()` etc.), and `setHours(0,0,0,0)` midnights. Scanned files: MES services, `packages/jobs`, edge functions, ERP module `.service.ts`/`.server.ts`, **plus both apps' route trees** — route modules are server AND client in one file, so `maskClientCode` blanks the browser half (default export, `clientLoader`/`clientAction`, PascalCase/`use*` declarations) while keeping loaders, actions, and the module-level helpers they call+- **Authz ownership** (`CONFORMANCE_CHECKS` via `collectFindings`): `noAuthzDdlInMigrations(helpers)` fails a migration newer than `20260927000000` that runs `CREATE`/`ALTER POLICY` on a public table (storage bucket policies stay allowed), or defines, alters or drops a managed RLS helper — policies live in `packages/database/src/authz/manifest.ts`, helpers in `packages/database/src/authz/helpers/<name>.sql`, and `authz sync` applies both after migrations. The helper list is read from that directory (`loadAuthzHelperNames`), so it cannot drift from the files. `DROP POLICY` is allowed (dropping a column a policy uses). Files starting with the `authz migration` header are exempt; `@carbon/database`'s `migration.test.ts` verifies their contents. Older migrations are history, so there are no baseline entries+- **Forwarded headers** (own source, `REQUEST_HANDLING_ROOTS`: every app + auth, ee, jobs, lib, utils, edge functions): `noRawForwardedHeaders` fails a raw read of `X-Forwarded-For/-Host/-Proto` or `X-Real-IP` outside `packages/utils/src/headers.ts` — use `getClientIp` / `getRequestProtocol` / `getRequestHost` / `getRequestOrigin`. Hand-rolled reads keyed login rate limits and ITAR audit records on the forgeable first `X-Forwarded-For` entry. No baseline entries- **Numeric-precision checks** (in `TS_CHECKS`, over `sources/typescript.ts`): `noRawRounding` flags `Math.round/ceil/floor` and `.toFixed` on value-bearing numbers (use `round`/`scrapAllowance`/`applyRate`/`deriveRate` from `@carbon/utils`); `noInlineFractionDigits` flags `minimum`/`maximumFractionDigits` at a call site (pick a named kind from `@carbon/utils` `format.ts`, and `INPUT_FORMAT.*` for anything editable); `noUnroundedTrackedQuantity` flags inline unrounded arithmetic inside a `.updateTable("trackedEntity")` statement's `quantity:` set, and a raw `===`/`!==`/`<` compare against a `*[Ee]ntity*.quantity` read (use `round`/`settleQuantity` at the write, `isFullDraw` at a split gate — see `.claude/rules/traceability-model.md`). It is scoped to what one file can prove: a `quantity:` set from an already-rounded variable is unflaggable either way, and a compare of two locals is presumed rounded where they were defined. It has **no baseline entries** — the whole tree was fixed in the pass that added it, so any finding is new. `sources/typescript.ts` walks `apps/erp/app/{components,hooks,modules,routes}`, `apps/mes/app`, `packages/database/supabase/functions`, `packages/{ee,jobs}/src`, `packages/documents/src/{pdf,utils}` and the shared packages `packages/{utils,form,react,printing,workflows}/src` — tests and the image/logo resizers excluded. The shared packages matter: `@carbon/utils` is where the standard's own helpers live, and `form`/`react` own the number inputs whose `formatOptions` are part of the storage round-trip. See `.claude/rules/numeric-precision.md`- **Tenant-scoped Kysely writes** (in `TS_CHECKS`): `noUnscopedKyselyWrite` fails any `.updateTable(`/`.deleteFrom(` under `apps/erp/app/{modules,routes}`, `apps/mes/app` or `packages/jobs/src` whose statement (up to `.execute…(`/`.compile(`/`;`/`,` at depth 0, comments blanked) has no `.where("companyId", …)` / `.where("alias.companyId", …)`. Kysely is the superuser connection, and the public API hands a service's `db` param that same client, so the statement's own predicate is the only tenant boundary — ten drag-sort services (`updateQuoteLineOrder` and friends) were a reported cross-tenant write because they keyed on `id` alone. `company` is exempt (its `id` is the tenant); a `companyId` in `.set()` does not count; a link table with no `companyId` column passes by scoping through its parent in a subquery. Edge functions and `packages/ee` are out of scope (see the file header). No baseline entries — every hit was fixed when it was added- **Edge-function auth** (`EDGE_FUNCTION_CHECKS`): `edgeFunctionAuthorizesCaller` fails any function under `packages/database/supabase/functions/` that never calls `requirePermissions` / `requireCaller` / `requireServiceRole` / `getSupabaseServiceRole`, because `verify_jwt` accepts the published anon key. `ALLOWED` in the check holds the functions that are correct without one, each with its reason (`logo-resizer`, `transcription`). `embed`, `event-wake` and `trigger` are baselined, not allowed: Postgres calls them over pg_net with the anon key from `config`, so gating them needs a migration that makes Postgres send a server credential firstdiff --git a/packages/checks/src/conformance/no-authz-ddl-in-migrations.test.ts b/packages/checks/src/conformance/no-authz-ddl-in-migrations.test.tsnew file mode 100644index 0000000000..4ba8e2f02a--- /dev/null+++ b/packages/checks/src/conformance/no-authz-ddl-in-migrations.test.ts@@ -0,0 +1,79 @@+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import { repoRoot } from "../sources/migrations";+import {+ GENERATED_AUTHZ_MIGRATION,+ noAuthzDdlInMigrations+} from "./no-authz-ddl-in-migrations";++const check = noAuthzDdlInMigrations(["get_companies_with_employee_role"]);+const NEW = "20260928120000_widget.sql";++describe("noAuthzDdlInMigrations", () => {+ it("flags CREATE POLICY and ALTER POLICY in a new migration", () => {+ const sql = `CREATE POLICY "SELECT" ON "public"."widget" FOR SELECT USING (true);+ALTER POLICY "SELECT" ON "public"."widget" USING (false);`;+ expect(check.scan(NEW, sql).map((v) => v.line)).toEqual([1, 2]);+ });++ it("flags a policy whose target is on the next line, at the CREATE line", () => {+ const sql = `SELECT 1;\nCREATE POLICY "SELECT"\n ON widget FOR SELECT USING (true);`;+ expect(check.scan(NEW, sql).map((v) => v.line)).toEqual([2]);+ });++ it("allows policies outside public (storage buckets are not in the manifest)", () => {+ const sql = `CREATE POLICY "Bucket read" ON storage.objects FOR SELECT USING (true);+CREATE POLICY "x" ON "storage"."objects" FOR INSERT WITH CHECK (true);`;+ expect(check.scan(NEW, sql)).toEqual([]);+ });++ it("allows DROP POLICY (needed before dropping a column a policy uses)", () => {+ expect(+ check.scan(NEW, `DROP POLICY "SELECT" ON "public"."widget";`)+ ).toEqual([]);+ });++ it("flags defining, altering or dropping a managed helper, however it is spelled", () => {+ const sql = `CREATE OR REPLACE FUNCTION public.get_companies_with_employee_role() RETURNS text[] AS $$ $$;+ALTER FUNCTION "public"."get_companies_with_employee_role"() VOLATILE;+DROP FUNCTION IF EXISTS get_companies_with_employee_role();`;+ expect(check.scan(NEW, sql)).toHaveLength(3);+ });++ it("allows any other function", () => {+ expect(+ check.scan(+ NEW,+ "CREATE OR REPLACE FUNCTION public.get_part_details() RETURNS void AS $$ $$;"+ )+ ).toEqual([]);+ });++ it("exempts only the exact header `authz migration` writes", () => {+ const source = readFileSync(+ join(repoRoot(), "packages/database/src/authz/migration.ts"),+ "utf8"+ );+ expect(source).toContain(JSON.stringify(GENERATED_AUTHZ_MIGRATION));+ const edited = GENERATED_AUTHZ_MIGRATION.replace("Do not edit.", "Edited.");+ expect(+ check.scan(+ NEW,+ `${edited}\nCREATE POLICY "SELECT" ON public.widget FOR SELECT USING (true);`+ )+ ).toHaveLength(1);+ });++ it("allows a migration rendered by `authz migration`", () => {+ const sql = `-- Generated by \`pnpm --filter @carbon/database authz migration\` from packages/database/src/authz. Do not edit.+CREATE POLICY "SELECT" ON public.widget FOR SELECT USING (true);`;+ expect(check.scan(NEW, sql)).toEqual([]);+ });++ it("ignores migrations from before the manifest took over, and comments", () => {+ const sql = `CREATE POLICY "SELECT" ON t FOR SELECT USING (true);`;+ expect(check.scan("20260926141957_employee-pin.sql", sql)).toEqual([]);+ expect(check.scan(NEW, `-- CREATE POLICY "x" ON t`)).toEqual([]);+ });+});diff --git a/packages/checks/src/conformance/no-authz-ddl-in-migrations.ts b/packages/checks/src/conformance/no-authz-ddl-in-migrations.tsnew file mode 100644index 0000000000..cbc994fba8--- /dev/null+++ b/packages/checks/src/conformance/no-authz-ddl-in-migrations.ts@@ -0,0 +1,89 @@+import type { ConformanceCheck, Violation } from "../check";++/**+ * RLS policies and the RLS/auth helper functions are authored only in+ * packages/database/src/authz (manifest + helpers/<name>.sql), and `authz sync` applies+ * them after migrations. A migration that creates or alters a policy, or defines, alters+ * or drops a managed helper, would be silently overwritten at the next sync — or, for a+ * helper, reintroduce exactly the drift the manifest exists to stop (a redefinition once+ * turned get_companies_with_employee_permission from STABLE back to VOLATILE).+ *+ * `DROP POLICY` stays allowed: dropping a column a policy uses needs the policy gone+ * first, and the next sync recreates the table's policies from the manifest.+ *+ * Only migrations after the manifest took over are checked; older ones are history.+ */+const SINCE = "20260927000000";++/**+ * The first line of a migration rendered from the manifest by `authz migration` — the WHOLE+ * line, equal to GENERATED_HEADER in packages/database/src/authz/migration.ts (pinned by this+ * check's test). Those files carry policy and helper DDL on purpose, and @carbon/database's+ * migration.test.ts verifies the contents of exactly the files that start with that full line.+ * Matching only a prefix here let a hand-written file with an edited suffix skip both.+ */+export const GENERATED_AUTHZ_MIGRATION =+ "-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.";++const NAME = String.raw`(?:(?:"?public"?)\s*\.\s*)?"?(\w+)"?`;+// The target may be on a later line; group 2 is its schema, when it names one. The manifest+// owns public tables only, so storage.objects (bucket) policies stay in migrations.+const POLICY_DDL =+ /\b(?:CREATE|ALTER)\s+POLICY\s+(?:"[^"]*"|\S+)\s+ON\s+(?:"?(\w+)"?\s*\.\s*)?"?\w+"?/gi;+const FUNCTION_DDL = new RegExp(+ String.raw`\b(CREATE\s+(?:OR\s+REPLACE\s+)?FUNCTION|ALTER\s+FUNCTION|DROP\s+FUNCTION(?:\s+IF\s+EXISTS)?)\s+${NAME}`,+ "gi"+);++/** Blank out comments, keeping newlines so line numbers stay right. */+const stripComments = (sql: string) =>+ sql+ .replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, " "))+ .replace(/--[^\n]*/g, (m) => " ".repeat(m.length));++export const noAuthzDdlInMigrations = (+ helpers: string[]+): ConformanceCheck => ({+ id: "no-authz-ddl-in-migrations",+ description:+ "Policies and RLS helpers are authored in packages/database/src/authz, not migrations.",+ provenance: {+ deprecates: "CREATE/ALTER POLICY and managed helper DDL in migrations",+ replacedBy: "packages/database/src/authz (manifest.ts + helpers/*.sql)",+ since: SINCE+ },+ scan(file, contents) {+ const timestamp = /^(\d{14})_/.exec(file)?.[1];+ if (+ !timestamp ||+ timestamp < SINCE ||+ contents.startsWith(GENERATED_AUTHZ_MIGRATION)+ )+ return [];++ const managed = new Set(helpers.map((h) => h.toLowerCase()));+ const sql = stripComments(contents);+ const line = (index: number) => sql.slice(0, index).split("\n").length;+ const violations: Violation[] = [];+ for (const m of sql.matchAll(POLICY_DDL)) {+ if ((m[1] ?? "public").toLowerCase() !== "public") continue;+ violations.push({+ file,+ line: line(m.index),+ snippet: m[0].split("\n")[0] ?? m[0],+ message:+ "Author policies in packages/database/src/authz/manifest.ts, then run `pnpm --filter @carbon/database authz migration <name>`."+ });+ }+ for (const m of sql.matchAll(FUNCTION_DDL)) {+ if (!managed.has((m[2] ?? "").toLowerCase())) continue;+ violations.push({+ file,+ line: line(m.index),+ snippet: m[0],+ message: `${m[2]} is a managed helper; edit packages/database/src/authz/helpers/${m[2]}.sql, then run \`pnpm --filter @carbon/database authz migration <name>\`.`+ });+ }+ return violations;+ }+});diff --git a/packages/checks/src/conformance/no-legacy-rls.ts b/packages/checks/src/conformance/no-legacy-rls.tsindex 6b825c53d0..4d67b9b288 100644--- a/packages/checks/src/conformance/no-legacy-rls.ts+++ b/packages/checks/src/conformance/no-legacy-rls.ts@@ -1,4 +1,5 @@import type { ConformanceCheck, Violation } from "../check";+import { GENERATED_AUTHZ_MIGRATION } from "./no-authz-ddl-in-migrations";const LEGACY_RLS = /has_company_permission\s*\(/gi;@@ -12,6 +13,9 @@ export const noLegacyRls: ConformanceCheck = {since: "20250201181148_rls-refactor.sql"},scan(file, contents) {+ // Rendered from packages/database/src/authz, which owns the deprecated helpers' own+ // definitions until they can be dropped.+ if (contents.startsWith(GENERATED_AUTHZ_MIGRATION)) return [];const violations: Violation[] = [];contents.split("\n").forEach((text, i) => {for (const m of text.matchAll(LEGACY_RLS)) {diff --git a/packages/checks/src/conformance/no-raw-forwarded-headers.test.ts b/packages/checks/src/conformance/no-raw-forwarded-headers.test.tsnew file mode 100644index 0000000000..1a55ad4cf7--- /dev/null+++ b/packages/checks/src/conformance/no-raw-forwarded-headers.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from "vitest";+import { noRawForwardedHeaders } from "./no-raw-forwarded-headers";++const scan = (contents: string, file = "apps/erp/app/routes/x.tsx") =>+ noRawForwardedHeaders.scan(file, contents);++describe("noRawForwardedHeaders", () => {+ it("flags a raw read of any forwarding header", () => {+ expect(+ scan(`const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";+const host = headers.get('X-Forwarded-Host');+const proto = req.headers["x-forwarded-proto"];+const real = request.headers.has(\`x-real-ip\`);`).map((v) => v.line)+ ).toEqual([1, 2, 3, 4]);+ });++ it("ignores mentions that are not reads, and the helpers themselves", () => {+ expect(scan("// the ALB rewrites `X-Forwarded-Host` here")).toEqual([]);+ expect(+ scan('headers.get("x-forwarded-for")', "packages/utils/src/headers.ts")+ ).toEqual([]);+ });+});diff --git a/packages/checks/src/conformance/no-raw-forwarded-headers.ts b/packages/checks/src/conformance/no-raw-forwarded-headers.tsnew file mode 100644index 0000000000..fc5bcfb7f2--- /dev/null+++ b/packages/checks/src/conformance/no-raw-forwarded-headers.ts@@ -0,0 +1,40 @@+import type { ConformanceCheck, Violation } from "../check";++// The client IP, protocol, host and origin come from the proxy in front of the+// app, and each proxy we run behind writes those headers differently: the ALB+// APPENDS to a caller's X-Forwarded-For, so its first entry is forgeable. Reading+// them by hand is how login rate limits and ITAR audit records ended up keyed on+// an address the caller chose. getClientIp / getRequestProtocol / getRequestHost /+// getRequestOrigin in @carbon/utils are the one reading.+const RAW_READ =+ /(?:\.(?:get|has)\(\s*|\[\s*)["'`](?:x-forwarded-(?:for|host|proto)|x-real-ip)["'`]/i;++const HELPERS = "packages/utils/src/headers.ts";++export const noRawForwardedHeaders: ConformanceCheck = {+ id: "no-raw-forwarded-headers",+ description:+ "Read the client IP / protocol / host / origin with the @carbon/utils request helpers",+ provenance: {+ deprecates:+ "reading X-Forwarded-For / -Host / -Proto or X-Real-IP at call sites",+ replacedBy:+ "getClientIp, getRequestProtocol, getRequestHost, getRequestOrigin (@carbon/utils)",+ since: "2026-09-28"+ },+ scan(file: string, contents: string): Violation[] {+ if (file === HELPERS) return [];+ const violations: Violation[] = [];+ contents.split("\n").forEach((text, i) => {+ if (!RAW_READ.test(text)) return;+ violations.push({+ file,+ line: i + 1,+ snippet: text.trim(),+ message:+ "Use getClientIp / getRequestProtocol / getRequestHost / getRequestOrigin from @carbon/utils"+ });+ });+ return violations;+ }+};diff --git a/packages/checks/src/index.ts b/packages/checks/src/index.tsindex 563b5943a8..a7471be5ba 100644--- a/packages/checks/src/index.ts+++ b/packages/checks/src/index.ts@@ -15,6 +15,7 @@ export { noInlineFractionDigits } from "./conformance/no-inline-fraction-digits"export { noLegacyRls } from "./conformance/no-legacy-rls";export { noLocalTimezone } from "./conformance/no-local-timezone";export { noNumericPrecision } from "./conformance/no-numeric-precision";+export { noRawForwardedHeaders } from "./conformance/no-raw-forwarded-headers";export { noRawRounding } from "./conformance/no-raw-rounding";export { noRequiredColumnWithoutDefault } from "./conformance/no-required-column-without-default";export { noZeroConcurrency } from "./conformance/no-zero-concurrency";diff --git a/packages/checks/src/run.ts b/packages/checks/src/run.tsindex c7d84c5b58..5a6ddfc3b9 100644--- a/packages/checks/src/run.ts+++ b/packages/checks/src/run.ts@@ -1,3 +1,5 @@+import { readdirSync } from "node:fs";+import { join } from "node:path";import { keyOf, loadBaseline } from "./baseline";import type {ConformanceCheck,@@ -8,6 +10,7 @@ import type {} from "./check";import { edgeFunctionAuthorizesCaller } from "./conformance/edge-function-authorizes-caller";import { moduleShape } from "./conformance/module-shape";+import { noAuthzDdlInMigrations } from "./conformance/no-authz-ddl-in-migrations";import { noDbClientInService } from "./conformance/no-db-client-in-service";import { noDefaultOnEffects } from "./conformance/no-default-on-effects";import { noDerivedPercentColumn } from "./conformance/no-derived-percent-column";@@ -15,6 +18,7 @@ import { noInlineFractionDigits } from "./conformance/no-inline-fraction-digits"import { noLegacyRls } from "./conformance/no-legacy-rls";import { noLocalTimezone } from "./conformance/no-local-timezone";import { noNumericPrecision } from "./conformance/no-numeric-precision";+import { noRawForwardedHeaders } from "./conformance/no-raw-forwarded-headers";import { noRawRounding } from "./conformance/no-raw-rounding";import { noRequiredColumnWithoutDefault } from "./conformance/no-required-column-without-default";import { noUnroundedTrackedQuantity } from "./conformance/no-unrounded-tracked-quantity";@@ -25,7 +29,10 @@ import { loadEdgeFunctions } from "./sources/edge-functions";import { loadSqlFiles, migrationsDir, repoRoot } from "./sources/migrations";import { loadModules, modulesDir } from "./sources/modules";import { loadServerFiles } from "./sources/server-files";-import { loadTypescriptFiles } from "./sources/typescript";+import {+ loadTypescriptFiles,+ REQUEST_HANDLING_ROOTS+} from "./sources/typescript";export const CONFORMANCE_CHECKS: ConformanceCheck[] = [noNumericPrecision,@@ -90,13 +97,26 @@ export function scanModules(return out;}+/** The managed RLS helpers: one packages/database/src/authz/helpers/<name>.sql each. */+export function loadAuthzHelperNames(root: string): string[] {+ return readdirSync(join(root, "packages/database/src/authz/helpers"))+ .filter((file) => file.endsWith(".sql"))+ .map((file) => file.replace(/\.sql$/, ""));+}+/** Every finding across the real migrations (text) + modules (structure) + server TS + app TS + edge functions under `root`. */export function collectFindings(root: string = repoRoot()): Finding[] {return [- ...scanAll(loadSqlFiles(migrationsDir(root))),+ ...scanAll(loadSqlFiles(migrationsDir(root)), [+ ...CONFORMANCE_CHECKS,+ noAuthzDdlInMigrations(loadAuthzHelperNames(root))+ ]),...scanModules(loadModules(modulesDir(root))),...scanAll(loadServerFiles(root), SERVER_CHECKS),...scanAll(loadTypescriptFiles(root), TS_CHECKS),+ ...scanAll(loadTypescriptFiles(root, REQUEST_HANDLING_ROOTS), [+ noRawForwardedHeaders+ ]),...scanAll(loadEdgeFunctions(root), EDGE_FUNCTION_CHECKS)];}diff --git a/packages/checks/src/sources/typescript.ts b/packages/checks/src/sources/typescript.tsindex fbbe02cb13..0802a81e12 100644--- a/packages/checks/src/sources/typescript.ts+++ b/packages/checks/src/sources/typescript.ts@@ -56,9 +56,27 @@ function walk(dir: string, out: SourceFile[], repoRootDir: string) {}}-export function loadTypescriptFiles(root: string): SourceFile[] {+// Every app and every package that handles a request: no-raw-forwarded-headers+// covers auth and the smaller apps, which the numeric checks do not.+export const REQUEST_HANDLING_ROOTS = [+ "apps/erp/app",+ "apps/mes/app",+ "apps/academy/app",+ "apps/starter/app",+ "packages/auth/src",+ "packages/database/supabase/functions",+ "packages/ee/src",+ "packages/jobs/src",+ "packages/lib/src",+ "packages/utils/src"+];++export function loadTypescriptFiles(+ root: string,+ roots: string[] = TYPESCRIPT_ROOTS+): SourceFile[] {const out: SourceFile[] = [];- for (const dir of TYPESCRIPT_ROOTS) {+ for (const dir of roots) {walk(join(root, dir), out, root);}return out;diff --git a/packages/database/AGENTS.md b/packages/database/AGENTS.mdindex b46f7711f1..44e46b5683 100644--- a/packages/database/AGENTS.md+++ b/packages/database/AGENTS.md@@ -6,7 +6,7 @@ DB types, Supabase/Kysely clients, audit config, event system types, rate limiti- Use `pnpm db:migrate:new <name>` to create migrations; `pnpm db:migrate` to apply (regenerates types). There is **no** `db:build`.- Tables: composite PK `("id", "companyId")`, `id` default `id()` or `id('prefix')` — never raw UUID. Audit columns (`createdBy`/`createdAt`/`updatedBy`/`updatedAt`) with inline `REFERENCES "user"("id")`.-- RLS: four policies named exactly `SELECT`/`INSERT`/`UPDATE`/`DELETE`. SELECT uses `get_companies_with_employee_role()`, writes use `get_companies_with_employee_permission('<module>_<action>')`. Schema-qualify tables, cast `::text[]`.+- RLS: every public table's policies are a rule in `src/authz/manifest.ts` (usually `company("<module>")` — the four standard policies) and the RLS helpers are `src/authz/helpers/<name>.sql`. `pnpm db:migrate` syncs them locally; `pnpm --filter @carbon/database authz migration <name>` ships them to production (`migration.test.ts` fails until it does). See `.claude/rules/authz-manifest.md`.- Import `Database` type from `@carbon/database`; `KyselyDatabase` / `Kysely` from `@carbon/database/client`. Never hand-edit `src/types.ts` — it's generated.- `scriptRun` is a deliberate exception to the table conventions above: no `companyId`, nocomposite PK, SELECT-only RLS. It is the per-database ledger of one-off scripts that@@ -31,7 +31,8 @@ DB types, Supabase/Kysely clients, audit config, event system types, rate limiti- Specify decimal places in `NUMERIC` columns (use bare `NUMERIC`).- Use `000000` for the HHMMSS portion of migration timestamps (causes cross-branch collisions).-- Use the deprecated `has_role` / `has_company_permission` RLS helpers.+- Recreate or call the retired RLS helpers `has_role`, `has_company_permission`, `get_companies_with_permission`, `get_permission_companies` — dropped in `20260927224314_retire-legacy-rls-helpers.sql` (they admitted customer and supplier portal accounts); `authz-fixes.test.sql` asserts they stay gone.+- Write `CREATE`/`ALTER POLICY` on a public table, or define a managed RLS helper, in a migration — and never hand-edit a generated authz migration or `src/authz/baseline.json`.- Write a `SECURITY DEFINER` function that trusts a company id from its caller without `PERFORM assert_company_access(company_id)` first — every `public` function is an API endpoint (see `.claude/rules/database-migration-patterns.md`).- `REVOKE EXECUTE` on a `public` function: on this Postgres image calling it then segfaults the backend. Guard inside the function, or make it `SECURITY INVOKER`.@@ -43,6 +44,8 @@ pnpm db:types # Regenerate types onlypnpm db:check:datasets # Validate + dry-run every demo dataset against the schema (writes nothing)pnpm --filter @carbon/database typecheckpnpm --filter @carbon/database test+pnpm --filter @carbon/database authz check # local DB vs manifest (exit 3 = drift)+pnpm --filter @carbon/database authz migration <name> # ship unshipped rules/helpers```## Key Exports@@ -55,6 +58,7 @@ pnpm --filter @carbon/database test| `./methods` | Node re-export of `supabase/functions/lib/methods.ts` — shared make-method helpers || `./logging` | Node re-export of `supabase/functions/lib/logging.ts` (`getFunctionLogger`) || `./mrp-engine` | Node re-export of `supabase/functions/lib/mrp-engine.ts` (`explodeBom`, `makeKey`, `makeLocationItemKey`, `makeActualKey`, …) — the pure MRP compute engine consumed by `@carbon/planning`'s `runMrp` (the engine STAYS in the edge-lib; still used by the Deno `recalculate` function) |+| `./configuration-rule` | Node/browser re-export of `supabase/functions/shared/configuration-rule.ts` (`runConfigurationRule`) — runs configurator rule code in QuickJS (WebAssembly) with no host access and time/memory limits; used by get-method's `lib/sandbox.ts` and the ERP rule editor. Its npm deps (`quickjs-emscripten-core`, `@jitl/quickjs-singlefile-browser-release-sync`) are pinned in BOTH this package.json and `functions/deno.json` — keep the versions identical. Never run rule code with `new Function`/`eval`/`import()` || `./fetch-all` | Node re-export of `supabase/functions/lib/fetch-all.ts` (`fetchAll` — paginated PostgREST reads) || `./supersession-pick` | Node re-export of `supabase/functions/lib/supersession-pick.ts` (`buildSupersessionRedirectMap`, `buildConsumeFirstHops`, `settleConsumeFirstLine`, `resolveMadeLinePull`, `consumableInWholeAssemblies`, …) || `./picked-consumption` | Node re-export of `supabase/functions/lib/picked-consumption.ts` (`linesideCredit`, `getPickedBudgets`, `allocateAcrossBudgets`, …) — the one definition of usable lineside stock shared by the pick-list generator and the `issue` backflush |@@ -118,6 +122,7 @@ Full feature context: `.claude/rules/onboarding-company-templates.md`.- `.claude/rules/conventions-database.md` — table template, column types, migration checklist- `.claude/rules/database-patterns.md` — client factories, services, Kysely transactions+- `.claude/rules/authz-manifest.md` — RLS policies and helpers: manifest, sync, shipping- `.claude/rules/database-migration-patterns.md` — SQL conventions, enums, triggers, RLS for tables without `companyId`- `.claude/rules/event-system.md` — trigger dispatch, PGMQ queue, handler types- `packages/auth/` — Supabase client factories (`getCarbon`, `getCarbonServiceRole`)diff --git a/packages/database/package.json b/packages/database/package.jsonindex e716a3394b..33391497b0 100644--- a/packages/database/package.json+++ b/packages/database/package.json@@ -7,6 +7,7 @@"@types/pg": "8.15.6","@types/uuid": "8.3.4","dotenv": "16.3.1",+ "libpg-query": "18.1.5","npm-run-all": "catalog:","rimraf": "catalog:","supabase": "catalog:",@@ -19,6 +20,7 @@"exports": {".": "./src/index.ts","./client": "./src/client.ts",+ "./configuration-rule": "./src/configuration-rule.ts","./datetime": "./src/datetime.ts","./fetch-all": "./src/fetch-all.ts","./logging": "./src/logging.ts",@@ -42,6 +44,7 @@"private": true,"scripts": {"clean": "rimraf .turbo node_modules dist",+ "authz": "tsx src/authz/cli.ts","db:check:datasets": "tsx src/check-datasets.ts","db:function:new": "supabase functions new","db:init": "supabase init",@@ -58,6 +61,7 @@"version": "0.0.0","dependencies": {"@internationalized/date": "catalog:",+ "@jitl/quickjs-singlefile-browser-release-sync": "0.32.0","@jsquash/jpeg": "1.6.0","@jsquash/png": "3.1.1","@jsquash/resize": "2.1.1",@@ -72,6 +76,7 @@"libheif-js": "1.23.2","nanoid": "catalog:","pg": "8.20.0",+ "quickjs-emscripten-core": "0.32.0","react-pdf": "catalog:","sst": "catalog:","zod": "catalog:"diff --git a/packages/database/src/authz/baseline.json b/packages/database/src/authz/baseline.jsonnew file mode 100644index 0000000000..d68a03ad08--- /dev/null+++ b/packages/database/src/authz/baseline.json@@ -0,0 +1,407 @@+{+ "note": "What production had when the manifest took over (packages/database/src/authz/migration.ts). Written once; never regenerate it — ship changes with `authz migration`.",+ "tables": {+ "ability": "4f6fb47cb95debe8",+ "account": "42374d4e3f6212fe",+ "accountDefault": "e216c16431d02246",+ "accountingPeriod": "ad9cc0b8f681037d",+ "accountingPeriodBalance": "0b4e6177514006d8",+ "accountingSyncOperation": "d848b0f782a5abfa",+ "accountingSyncTieOut": "75ac867e18f4a3b1",+ "address": "f0b4e579fe733774",+ "agentMessage": "210ddaec39ad5a32",+ "agentMessagePart": "4f941ddb0366cf80",+ "agentThread": "651187e0b9d82436",+ "apiKey": "850f86fe3c0892c5",+ "apiKeyRateLimit": "14ca3cf4f7702019",+ "approvalRequest": "e3b0c44298fc1c14",+ "approvalRule": "06e0ea92155b1c51",+ "assemblyComponentMapping": "c0b91090383dba50",+ "assemblyInstruction": "f1946a3b9802f03c",+ "assemblyInstructionStep": "8ad3fa00b20f7f38",+ "assemblyInstructionStepMaterial": "c419de1f6594e40a",+ "assemblyInstructionStepSlide": "10548735cd312ca2",+ "assemblyInstructionStepTool": "b76f58b26ea5ab05",+ "assemblyPlanJob": "ac68d1acfed277db",+ "assemblyUnit": "afbcbf46cad9462e",+ "attributeDataType": "7be96959c8df50ce",+ "auditLogArchive": "e3b0c44298fc1c14",+ "balloon": "070fe91940a3dc9b",+ "batchProperty": "3dc6b697d5e50f78",+ "capacityReservation": "4b85a33faa45b445",+ "cardTransaction": "01d54f50091b5ebe",+ "cardTransactionLine": "3491a62f0c2b3399",+ "challengeAttempt": "bcdb093567c667f2",+ "changeOrder": "7e3c66ed9a14c105",+ "changeOrderActionTask": "2f0d1d583ef11745",+ "changeOrderAffectedItem": "de4dd111053c4d16",+ "changeOrderRequiredAction": "7906b3eeca26eea7",+ "changeOrderSupersession": "d2e7bdfdafd46626",+ "changeOrderType": "bc4ac9728546261c",+ "company": "b251d3166ed3a3b5",+ "companyAccountsPayableBillingAddress": "9451c448dfc02127",+ "companyAccountsReceivableBillingAddress": "dd3b88878b09796c",+ "companyGroup": "d0a98ce27990c0bf",+ "companyIntegration": "a6db5a13ad05d44d",+ "companyPlan": "b6863717517b9897",+ "companySettings": "33a8d94d3c27c35b",+ "companyUsage": "a5716d0d8ee0b71a",+ "config": "72b906efb5164f78",+ "configurationParameter": "628db33875b00cd4",+ "configurationParameterGroup": "8adb186fbee7ed57",+ "configurationRule": "b38847146df62041",+ "consumable": "8863459ce8469c29",+ "contact": "1f53f844bbc0e016",+ "contractor": "3b5be0b677e588fc",+ "contractorAbility": "fbe96f237f72405d",+ "costCenter": "800525f7c3990edf",+ "costLedger": "d4a3fd5bd5c3d06d",+ "country": "1e6253c747911350",+ "currency": "baea48b0bd1d5280",+ "currencyCode": "7c49cb0b087556fd",+ "customer": "4f8a1f558bab240f",+ "customerAccount": "570eb7640627ee9c",+ "customerBankAccount": "1a0d03a80430081f",+ "customerContact": "f334796962971477",+ "customerItemPriceOverride": "cb35c9e9c497bc84",+ "customerItemPriceOverrideBreak": "060e1b76501567f1",+ "customerLocation": "196cdcab7324a282",+ "customerPartToItem": "8375c6e5916ad7b3",+ "customerPayment": "db1a940982fb6c9b",+ "customerShipping": "ac549a86b08c97ca",+ "customerStatus": "ebdd0278d84ff896",+ "customerTax": "5aff40af14f05886",+ "customerType": "58bba3707f417bdf",+ "customField": "09f92a9717a57902",+ "customFieldTable": "19a25471fb3247ea",+ "demandActual": "fca32867375fd87f",+ "demandForecast": "c955a3e62ee05921",+ "demandForecastSource": "2fb9b729d00966c2",+ "demandProjection": "81d01b12b9553283",+ "department": "995ecb72155ecd92",+ "depreciationRun": "a6eafb5c5b3c60f4",+ "depreciationRunLine": "241c9703c2394d82",+ "dimension": "7bf89fb6f43dab14",+ "dimensionValue": "0191517b51a72bb9",+ "document": "ce905b492815a4c4",+ "documentExtraction": "8b2d3340553bf727",+ "documentFavorite": "24af0da8d4b769dc",+ "documentLabel": "a5c5745cbd2218a8",+ "documentSection": "2fe0b32a8ee9e6b3",+ "documentTemplate": "7eccb0d52e5706b0",+ "documentTransaction": "9fbdc9db305d9720",+ "employee": "26a6fb3496d20db6",+ "employeeAbility": "70fb5663e0191498",+ "employeeJob": "1219535b1cbda279",+ "employeePin": "e3b0c44298fc1c14",+ "employeeShift": "07339dfc0a0fcf66",+ "employeeType": "91704f93c6c80dd0",+ "employeeTypePermission": "e596f3a64ee29ec1",+ "enforcementRule": "a2a1dadfca025936",+ "enforcementRuleAcknowledgment": "c59687154a6dfde3",+ "enforcementRuleItemAssignment": "023fd7d26620be41",+ "enforcementRuleWorkCenterAssignment": "54c2acf0a7f4febc",+ "eventSystemSubscription": "4419e3a12b678aa0",+ "exchangeRate": "85336450aac16ca4",+ "exchangeRateOverride": "4920c2b47c3d1924",+ "externalIntegrationMapping": "74dc0273b2641a49",+ "externalLink": "a4894dd1f9943a9c",+ "feedback": "e3b0c44298fc1c14",+ "fiscalYearSettings": "d6eed7aacbec643c",+ "fixedAsset": "26ab8bcc10f7cc21",+ "fixedAssetClass": "5613f0f8af6a2412",+ "fixedAssetDisposal": "9bd21b7bef127029",+ "fixedAssetUsageLog": "22bc96174d53e94b",+ "fixture": "e3b0c44298fc1c14",+ "fulfillment": "e47b1926a0d26190",+ "gauge": "98b5827aff1383a8",+ "gaugeCalibrationRecord": "f03ab2a8e71420da",+ "gaugeType": "a83b7c4a671c5b85",+ "group": "4af67bcaff391b80",+ "holiday": "07b3cd0a9b0687c9",+ "implementationCheckState": "7ec47143801cb567",+ "implementationFieldValue": "8f4368d3dd3b6cf2",+ "implementationHub": "f47bfd18b9864396",+ "implementationRow": "13f83a22c0207927",+ "industry": "00dca9b1e39fefe8",+ "inspection": "e2ae9ad8276a87fb",+ "inspectionDocument": "10185cc9bb746cab",+ "inspectionFeature": "50480302d4057b1f",+ "inspectionHistory": "39d2ffeb6c5710c1",+ "inspectionMeasurement": "9a6a9a3dab2c32fc",+ "inspectionSample": "0d6c7269b2b16b18",+ "inspectionSamplingPlan": "3cb01b540014be31",+ "integration": "9e4dd950aec02a96",+ "intercompanyEliminationLine": "8f4ae3f10fe0e8cd",+ "intercompanyTransaction": "513744776a424e4c",+ "inventoryCount": "6f6d30a92b778046",+ "inventoryCountLine": "ab037a54c426a7c5",+ "invite": "e3b0c44298fc1c14",+ "itarCertification": "385753690c8a626d",+ "item": "1dcfb63d794d2215",+ "itemCost": "896d8ed0eaf4f429",+ "itemInspectionDocumentAssignment": "50f11584abdde75d",+ "itemLedger": "ce3293848aa9a8d6",+ "itemPlanning": "33b936bd58912724",+ "itemPostingGroup": "7e22268f4e8fa080",+ "itemReplenishment": "a2771c90928f22a5",+ "itemSerialSequence": "89b0714496250e82",+ "itemShelfLife": "812536a7ce2b35c3",+ "itemStockQuantities": "1911550d86a26f7d",+ "itemSupersession": "eedf8996b3cce990",+ "itemUnitSalePrice": "0d7f6ef8b42ddc83",+ "job": "5ead8edc325dc038",+ "jobFavorite": "67a54a06dac95ac1",+ "jobMakeMethod": "d5bd732f1cb25365",+ "jobMaterial": "6fd7308485f3c2b4",+ "jobMaterialStep": "bb68b97784083a6b",+ "jobOperation": "0b787f8fd16a3731",+ "jobOperationBatch": "65fba12702a163ad",+ "jobOperationDependency": "f3dd0f7ff603dd23",+ "jobOperationNote": "ad70760a34b16e38",+ "jobOperationParameter": "a16cf5e3ac6d242d",+ "jobOperationStep": "74e20f087454da68",+ "jobOperationStepRecord": "01a3201754aa95bd",+ "jobOperationStepSlide": "f1889b5f18dc1484",+ "jobOperationTool": "3ec07fe3ecd5ae63",+ "jobOperationToolStep": "a9b76bcd9d8caa75",+ "journalLine": "075694ec50663404",+ "journalLineDimension": "0c8aa668ba7d09c4",+ "kanban": "3ef63498f568d51b",+ "lessonCompletion": "2bc6ec5f537cdb4b",+ "location": "eb0b256b13735f27",+ "maintenanceDispatch": "599928bfd0212c3c",+ "maintenanceDispatchEvent": "5969e8434c866cf5",+ "maintenanceDispatchItem": "ca4b3ca0b62da9e7",+ "maintenanceDispatchWorkCenter": "46e590645ba85530",+ "maintenanceFailureMode": "760d812706e7ee36",+ "maintenanceSchedule": "3bd8a6831bc8810d",+ "maintenanceScheduleItem": "f7886a023166610d",+ "makeMethod": "c2357a0c64cb5979",+ "material": "b32ec7dc22499833",+ "materialDimension": "56dd759dfcc5fd9f",+ "materialFinish": "1dd1f49d7d656c17",+ "materialForm": "a7643d1e0972fc0a",+ "materialGrade": "ec461c3f420fa8cc",+ "materialSubstance": "b72280cb5b4c4abb",+ "materialType": "6a11576099d9e0ff",+ "membership": "0d5e83e4f8af19cd",+ "memo": "f43b17bb7f0e5abe",+ "methodMaterial": "9d06f2e8ce5512f5",+ "methodMaterialStep": "0c475c774ccfe1f1",+ "methodOperation": "52793c07c997eafe",+ "methodOperationParameter": "cb9b8ffa291f9611",+ "methodOperationStep": "0809dcba72b6765d",+ "methodOperationStepSlide": "7f2770808897129d",+ "methodOperationTool": "473a9b20c5aa20a6",+ "methodOperationToolStep": "0afcd3005d903a97",+ "modelUpload": "fba4eb011c274a51",+ "nonConformance": "b2f2dfde9be2b9e1",+ "nonConformanceActionProcess": "5de630011fffe852",+ "nonConformanceActionTask": "b8a5752efbd4dc39",+ "nonConformanceApprovalTask": "330c8dd7e5037dab",+ "nonConformanceCustomer": "2eff83467ca6bc1f",+ "nonConformanceInspection": "f40a89f429371791",+ "nonConformanceItem": "a726bfe68212ed0f",+ "nonConformanceItemTrackedEntity": "1afc22d6c98a1605",+ "nonConformanceJobOperation": "78039e79370dd772",+ "nonConformancePurchaseOrderLine": "46a9ae597be51ace",+ "nonConformancePurchaseReturnOrderLine": "e1a99ada9585cb8f",+ "nonConformanceReceiptLine": "a6bade86f06a0298",+ "nonConformanceRequiredAction": "8eab7afc185f7128",+ "nonConformanceReviewer": "036548dd4c5f35e4",+ "nonConformanceSalesOrderLine": "8881761e1648da97",+ "nonConformanceSalesReturnOrderLine": "b2340162c2aec00a",+ "nonConformanceShipmentLine": "500793a31539162e",+ "nonConformanceSupplier": "cb4bcf4efe0263c3",+ "nonConformanceTrackedEntity": "87e6d4756f10f58d",+ "nonConformanceType": "19a24ea8e1e7b392",+ "nonConformanceWorkflow": "26c0f46cab00adc2",+ "noQuoteReason": "60b21d7a198a049e",+ "notification": "5936cb727f33636f",+ "notificationDelivery": "31fd49277d1a0e34",+ "notificationPreference": "23cf7bfc43213eb2",+ "oauthClient": "e3b0c44298fc1c14",+ "oauthCode": "e3b0c44298fc1c14",+ "oauthToken": "e3b0c44298fc1c14",+ "opportunity": "bf85b940a7324f6f",+ "part": "2e1e978f8b22222a",+ "partner": "c5b5cc4ea851397b",+ "passkeyCredential": "e4c5a30e31733e16",+ "payment": "81e99561af45916e",+ "paymentTerm": "f0f0b7ba25f98a2f",+ "peopleAbsence": "35fa2a2aa1be9404",+ "peopleAssignment": "4c22aab500a594d3",+ "period": "ae430309a4fb4b3d",+ "periodCloseTask": "3bf95de35dc19849",+ "periodCloseTaskDefinition": "f81719bdb1b30132",+ "pickingList": "d76fd7ad0c81be41",+ "pickingListLine": "47d60df1e8bbc782",+ "pickingListLineTrackedEntity": "494e59a04cf7cb86",+ "pickMethod": "8483ad95143c6f19",+ "plan": "d59f7949853c4752",+ "pricingRule": "da0e632913db712c",+ "printerRoute": "c6f30933fcacb421",+ "printJob": "31b791cbef9e77ad",+ "procedure": "b409e3acd0801722",+ "procedureParameter": "f7d5ee5b0e17f80f",+ "procedureStep": "a14a68a74b1364ac",+ "process": "da808661c75d9485",+ "productionEvent": "8a85fc9144532d31",+ "productionQuantity": "8ed4f964d37c811b",+ "project": "ef2259114456e50f",+ "purchaseInvoice": "77106adef18dcf54",+ "purchaseInvoiceDelivery": "2af8e14795a868c8",+ "purchaseInvoiceLine": "b4a4e4df12f9bb45",+ "purchaseInvoicePriceChange": "b05f09912c8fccf1",+ "purchaseInvoiceStatusHistory": "abc6c425c61358c9",+ "purchaseOrder": "86d49cc32beaf56d",+ "purchaseOrderDelivery": "151b8a6679ba9eda",+ "purchaseOrderFavorite": "cf862c15e6191c6d",+ "purchaseOrderLine": "7c8e22f517ee3e75",+ "purchaseOrderPayment": "93f48f422ed086fa",+ "purchaseOrderStatusHistory": "573ffb2dd36f9fe1",+ "purchaseOrderTransaction": "04b13c5395528d2a",+ "purchaseReturnOrder": "342386102f5b27c7",+ "purchaseReturnOrderCreditLine": "d6bccae1fa483ff0",+ "purchaseReturnOrderLine": "bce55d5dfab590f7",+ "purchaseReturnOrderLineTrackedEntity": "879631d504425107",+ "purchasingRfq": "8d84a4903ffccafd",+ "purchasingRfqFavorite": "3dee2925bcffdaeb",+ "purchasingRfqLine": "cc43f6f1580084cb",+ "purchasingRfqSupplier": "73951ff940dddf77",+ "purchasingRfqToPurchaseOrder": "c45dc8652bd68669",+ "purchasingRfqToSupplierQuote": "4349324317e38290",+ "qualityDocument": "6fc0878aecafa393",+ "qualityDocumentStep": "e2906d5b6d3b9b61",+ "quote": "7c45a09f452d3c36",+ "quoteFavorite": "6b81da8100a95ea6",+ "quoteLine": "c81815d272964795",+ "quoteLinePrice": "687b2941a590926a",+ "quoteMakeMethod": "93fd58c2d66034ee",+ "quoteMaterial": "7f60dae9102f2461",+ "quoteMaterialStep": "480daf89dca43729",+ "quoteOperation": "57685a9383db7f16",+ "quoteOperationParameter": "9a6b183f944e0019",+ "quoteOperationStep": "e13aa90a47f998d2",+ "quoteOperationStepSlide": "58bc32d1b234b185",+ "quoteOperationTool": "a5fe865dbcda8758",+ "quoteOperationToolStep": "23b7a3942cfad9b3",+ "quotePayment": "3bb286cdc7746758",+ "quoteShipment": "538d3e7606e23204",+ "receipt": "bae9b945d88036a6",+ "receiptFixedAssetLine": "1a108b1f2f6888ae",+ "receiptLine": "c8900935c26b0918",+ "reportPin": "8520a3db8aa5c535",+ "reportView": "d97608026296b139",+ "returnReason": "9bc2eac0e9fe05e0",+ "rework": "5485259190b32f03",+ "riskRegister": "654dc6fe68279178",+ "salesInvoice": "43e43bfc96f4186d",+ "salesInvoiceLine": "dc4d159e7fa67cd3",+ "salesInvoiceShipment": "e593b56b1e3a8e86",+ "salesOrder": "79a6ff733705d8d2",+ "salesOrderFavorite": "d3761a6bd1597298",+ "salesOrderLine": "879cfa0b62306dfd",+ "salesOrderPayment": "90538383713d12e4",+ "salesOrderShipment": "948487e9cae146f9",+ "salesOrderStatusHistory": "efc5b6ae0b57de59",+ "salesOrderTransaction": "6353b15b4dadc127",+ "salesReturnOrder": "e58d2602f8b813b1",+ "salesReturnOrderCreditLine": "3332fd8886e6efb2",+ "salesReturnOrderLine": "a98f140f83c0c519",+ "salesReturnOrderLineTrackedEntity": "a520f6fb502607af",+ "salesRfq": "966cba460f2da359",+ "salesRfqFavorite": "1a27f001ae542065",+ "salesRfqLine": "4214de14d44560da",+ "scrapReason": "1674c88223e5f774",+ "scriptRun": "495ec82b0e3e3608",+ "searchIndexRegistry": "e3b0c44298fc1c14",+ "sequence": "95711ab9b82b1c9d",+ "service": "4a67e2f0d7334685",+ "shift": "1100e5953c34cf08",+ "shipment": "d4a76513d0b3a641",+ "shipmentFixedAssetLine": "3b387b394c3ab49a",+ "shipmentLine": "b2bb5ca0b84779c2",+ "shippingMethod": "f4f28696563013d5",+ "shippingTerm": "316d378015f71299",+ "slackDocumentThread": "e3b0c44298fc1c14",+ "ssoConnection": "58c6924889355c39",+ "ssoDomain": "abb6d0d39937138e",+ "ssoReservedDomain": "46a5baa3bceff727",+ "stockTransfer": "63c21ae01adaed83",+ "stockTransferLine": "c02c315334f2f844",+ "storageType": "8fafcb83b2af6b29",+ "storageUnit": "262137b09e0501ca",+ "suggestion": "8440eedac389d4d1",+ "supplier": "5076f5651fa66be9",+ "supplierAccount": "33e36cfa44dcb55e",+ "supplierBankAccount": "01ea5b1f42c9ede4",+ "supplierContact": "3dbbbd75f0eff5ca",+ "supplierInteraction": "7bc28ce6f3e41d06",+ "supplierLedger": "ca5a1365f3e14951",+ "supplierLocation": "04abf7c47421e7e9",+ "supplierPart": "832f6a17007a56cb",+ "supplierPartPrice": "600a10bb56a2d11a",+ "supplierPayment": "dd8373c63e398d5e",+ "supplierProcess": "a802c7ffb86b836c",+ "supplierQuote": "a3196fa189a82e00",+ "supplierQuoteFavorite": "c0073d9fd534be69",+ "supplierQuoteLine": "5d2e86752b2bc393",+ "supplierQuoteLinePrice": "229a5854210db00f",+ "supplierShipping": "f3362baf0a28e295",+ "supplierTax": "5d1e83cb74957ade",+ "supplierType": "1e22b84e0498038b",+ "supplyActual": "cc31c1579f2e5aad",+ "supplyForecast": "4191e5e0bcd4de60",+ "tag": "5eac19d8bea403c8",+ "terms": "574dd21aac1119af",+ "timeCardEntry": "2f6bd05bddf20a0b",+ "tool": "eac7c089d5d73f98",+ "trackedActivity": "dc49889722b53853",+ "trackedActivityInput": "e9adba6e4b18d845",+ "trackedActivityOutput": "0137f24f1ddd69da",+ "trackedEntity": "ccbe80eb97112320",+ "training": "b3721ee1f10cbcbe",+ "trainingAssignment": "aec3fa77b6991ffe",+ "trainingCompletion": "e9363db1dafd0870",+ "trainingQuestion": "7dcfc6e5cc2351b4",+ "unitOfMeasure": "8f7af4fef95acb98",+ "user": "f68d08e5d040793f",+ "userAttribute": "7f91be04546763f2",+ "userAttributeCategory": "07d9482b456f27b6",+ "userModulePreference": "92afef335378d89b",+ "userPermission": "065f4faee448aeee",+ "warehouse": "8f0e7564bf2830e3",+ "warehouseTransfer": "628ad43d63150b4b",+ "warehouseTransferLine": "2b6f5ca242a3d439",+ "webhook": "77407a20a30b6b4c",+ "webhookTable": "0af151c702e50f24",+ "workCenter": "a877dcc82a451a40",+ "workCenterProcess": "9c6eba8e1ec58c91",+ "workCenterReplacementPart": "32756e1ff2b8a4b8",+ "workCenterShift": "d92377aa411f91a0",+ "workflow": "124a73dd43557283",+ "workflowRun": "7183a2f929562044",+ "workflowStepRun": "3fb10646663c197a",+ "workflowTriggerEvent": "9a5b39ca421b71ab",+ "workflowVersion": "59b50d6d1b6ef681"+ },+ "helpers": {+ "assert_company_access": "1a2fe4ee08158bd7",+ "get_api_key_scopes": "43b940066bdfb1ba",+ "get_claims": "c345ac67cc3e492d",+ "get_companies_with_any_role": "807ddffb0e5fe9d8",+ "get_companies_with_employee_role": "7d1d803eda853d43",+ "get_company_groups_for_employee": "c8c24adfbae463c5",+ "get_company_groups_for_root_permission": "748135ede6ea850a",+ "get_company_id_from_api_key": "f0bcd5228d34df67",+ "get_customer_ids_with_customer_permission": "b10e6c0e6f20b87c",+ "get_supplier_ids_with_supplier_permission": "c7fefb2bbb6f5798",+ "groups_for_user": "3a289b1d4e3652fa",+ "has_any_company_permission": "4f56a8118e58686c",+ "has_role": "91fefeb97930dec8",+ "has_valid_api_key_for_company": "a437e5e6be2ae242",+ "jsonb_to_text_array": "a68615f56ddbe5c9"+ }+}diff --git a/packages/database/src/authz/cli.ts b/packages/database/src/authz/cli.tsnew file mode 100644index 0000000000..4035f7a796--- /dev/null+++ b/packages/database/src/authz/cli.ts@@ -0,0 +1,110 @@+import { execFileSync } from "node:child_process";+import { writeFileSync } from "node:fs";+import path from "node:path";+import process from "node:process";+import { fileURLToPath } from "node:url";+import { Client } from "pg";+import { loadEnv } from "../datasets/cli";+import { loadHelpers } from "./helpers";+import { renderMigration, unshipped } from "./migration";+import { syncAuthz } from "./sync";++// pnpm --filter @carbon/database authz <check|sync|migration <name>>+// check report what sync would change (reads only)+// sync make the database match manifest.ts and helpers/+// migration <name> write a migration shipping every rule and helper production does+// not have yet (see migration.ts; migration.test.ts fails until it does)+async function main() {+ const command = process.argv[2];+ if (command === "migration") {+ const name = process.argv[3];+ if (!name) {+ console.error("usage: authz migration <name>");+ process.exit(2);+ }+ const { manifest } = await import("./manifest");+ const helpers = await loadHelpers();+ const todo = await unshipped(manifest, helpers);+ if (todo.problems.length)+ throw new Error(+ `authz migration: fix these first:\n${todo.problems.join("\n")}`+ );+ if (!todo.tables.length && !todo.helpers.length) {+ console.log("authz: production already has every rule and helper");+ return;+ }+ const sql = await renderMigration(+ manifest,+ helpers.filter((h) => todo.helpers.includes(h.name)),+ todo.tables+ );+ const root = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ "..",+ ".."+ );+ const created = execFileSync(+ "pnpm",+ ["exec", "supabase", "migration", "new", name],+ { cwd: root, encoding: "utf8" }+ );+ const file = /supabase\/migrations\/\S+\.sql/.exec(created)?.[0];+ if (!file)+ throw new Error(+ `authz migration: could not find the new file in: ${created}`+ );+ writeFileSync(path.join(root, file), sql);+ console.log(+ `authz: wrote ${file} (${[...todo.helpers, ...todo.tables].join(", ")})`+ );+ return;+ }++ if (!["check", "sync"].includes(command ?? "")) {+ console.error("usage: authz <check|sync|migration <name>>");+ process.exit(2);+ }++ loadEnv();+ const url = process.env.SUPABASE_DB_URL ?? process.env.DATABASE_URL;+ if (!url) {+ console.error("Set SUPABASE_DB_URL (or DATABASE_URL).");+ process.exit(2);+ }++ const db = new Client({ connectionString: url });+ await db.connect();+ try {+ const { manifest } = await import("./manifest");+ const result = await syncAuthz(db, manifest, {+ dryRun: command === "check"+ });+ const verb = command === "check" ? "would change" : "changed";+ console.log(`authz: ${verb} ${result.helpers.length} helper(s)`);+ for (const name of result.helpers) console.log(` ${name}`);+ console.log(`authz: ${verb} ${result.changed.length} table(s)`);+ for (const table of result.changed) console.log(` ${table}`);+ if (result.unmanaged.length) {+ console.error(+ `authz: tables with no rule in manifest.ts (left as they are):\n${result.unmanaged+ .map((t) => ` ${t}`)+ .join("\n")}`+ );+ process.exit(1);+ }+ // 3, not 1: CI tells "the database differs from the manifest" apart from a failure.+ if (+ command === "check" &&+ (result.changed.length || result.helpers.length)+ ) {+ process.exit(3);+ }+ } finally {+ await db.end();+ }+}++main().catch((error) => {+ console.error(error instanceof Error ? error.message : error);+ process.exit(1);+});diff --git a/packages/database/src/authz/helpers.test.ts b/packages/database/src/authz/helpers.test.tsnew file mode 100644index 0000000000..0f999bfaa7--- /dev/null+++ b/packages/database/src/authz/helpers.test.ts@@ -0,0 +1,77 @@+import { Client } from "pg";+import { afterAll, beforeAll, describe, expect, test } from "vitest";+import { loadHelpers, validateHelper } from "./helpers";+import { syncAuthz } from "./sync";++const fn = (name: string, body = "SELECT 1") =>+ `CREATE OR REPLACE FUNCTION public.${name}() RETURNS integer LANGUAGE sql AS $$ ${body} $$;`;++describe("validateHelper: a helper file is one function, and the right one", () => {+ test("accepts exactly one CREATE OR REPLACE FUNCTION public.<name>", async () => {+ await expect(+ validateHelper({ name: "h", sql: fn("h") })+ ).resolves.toBeUndefined();+ });++ test("rejects a second statement smuggled in", async () => {+ await expect(+ validateHelper({ name: "h", sql: `${fn("h")} DROP TABLE item;` })+ ).rejects.toThrow();+ });++ test("rejects a function the file is not named for", async () => {+ await expect(+ validateHelper({ name: "h", sql: fn("other") })+ ).rejects.toThrow();+ });++ test("rejects CREATE without OR REPLACE", async () => {+ await expect(+ validateHelper({ name: "h", sql: fn("h").replace("OR REPLACE ", "") })+ ).rejects.toThrow();+ });++ test("every committed helper file passes", async () => {+ expect((await loadHelpers()).length).toBeGreaterThan(0);+ });+});++// Runs against the local database: SUPABASE_DB_URL=… pnpm vitest run src/authz+const url = process.env.SUPABASE_DB_URL;++describe.skipIf(!url)("syncHelpers against a migrated database", () => {+ const db = new Client({ connectionString: url });+ const name = `authz_helper_test_${process.pid}`;++ beforeAll(async () => {+ await db.connect();+ await db.query(fn(name));+ });++ afterAll(async () => {+ await db.query(`DROP FUNCTION IF EXISTS public.${name}()`);+ await db.query(`DROP FUNCTION IF EXISTS public.${name}(integer)`);+ await db.end();+ });++ test("replaces only a helper that differs, and a second run changes nothing", async () => {+ const helpers = [{ name, sql: fn(name, "SELECT 2") }];+ expect((await syncAuthz(db, {}, { helpers })).helpers).toEqual([name]);+ expect((await syncAuthz(db, {}, { helpers })).helpers).toEqual([]);+ });++ test("a signature change fails loudly and changes nothing", async () => {+ const helpers = [+ {+ name,+ sql: `CREATE OR REPLACE FUNCTION public.${name}(x integer) RETURNS integer LANGUAGE sql AS $$ SELECT x $$;`+ }+ ];+ await expect(syncAuthz(db, {}, { helpers })).rejects.toThrow(/signature/);+ const { rows } = await db.query(+ "SELECT count(*)::int AS n FROM pg_proc WHERE proname = $1",+ [name]+ );+ expect(rows[0].n).toBe(1);+ });+});diff --git a/packages/database/src/authz/helpers.ts b/packages/database/src/authz/helpers.tsnew file mode 100644index 0000000000..ad08962266--- /dev/null+++ b/packages/database/src/authz/helpers.ts@@ -0,0 +1,118 @@+import { readdirSync, readFileSync } from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { parse } from "libpg-query";+import type { Client } from "pg";++/**+ * The RLS and auth helper functions. `helpers/<name>.sql` is the only place each is+ * defined; migrations must not create or redefine them. Sync applies a file only when the+ * function it produces differs from the live one.+ */++export const HELPERS_DIR = path.join(+ path.dirname(fileURLToPath(import.meta.url)),+ "helpers"+);++export type Helper = { name: string; sql: string };++/**+ * Helpers that were managed here and have been dropped from the database (by a later+ * migration), each with the one generated migration that shipped its last definition.+ * `unshipped()` accepts a retired definition in that file only; in any other generated+ * migration it is reported, so no later file can bring the helper back. (`has_role` was+ * retired too, but no generated migration ever defined it.)+ */+const SECURITY_FIXES = "20260927172338_authz-security-fixes.sql";+export const RETIRED_HELPERS: Readonly<Record<string, string>> = {+ get_companies_with_permission: SECURITY_FIXES,+ get_permission_companies: SECURITY_FIXES,+ has_company_permission: SECURITY_FIXES+};++// biome-ignore lint/suspicious/noExplicitAny: libpg-query's AST is untyped JSON+type Ast = any;++/**+ * A helper file must be exactly one `CREATE OR REPLACE FUNCTION public.<name>(…)` — so a+ * file can never smuggle in a second statement, or define a function it is not named for.+ */+export async function validateHelper({ name, sql }: Helper): Promise<void> {+ const tree: Ast = await parse(sql);+ const statements = tree.stmts ?? [];+ const fn = statements[0]?.stmt?.CreateFunctionStmt;+ const qualified = (fn?.funcname ?? []).map((n: Ast) => n.String?.sval);+ if (+ statements.length !== 1 ||+ !fn ||+ !fn.replace ||+ fn.is_procedure ||+ qualified.join(".") !== `public.${name}`+ ) {+ throw new Error(+ `helpers/${name}.sql must be exactly one CREATE OR REPLACE FUNCTION public.${name}(…)`+ );+ }+}++export async function loadHelpers(dir = HELPERS_DIR): Promise<Helper[]> {+ const helpers = readdirSync(dir)+ .filter((file) => file.endsWith(".sql"))+ .sort()+ .map((file) => ({+ name: file.replace(/\.sql$/, ""),+ sql: readFileSync(path.join(dir, file), "utf8")+ }));+ for (const helper of helpers) await validateHelper(helper);+ return helpers;+}++const definitions = async (db: Client, name: string) =>+ (+ await db.query<{ def: string }>(+ `SELECT pg_get_functiondef(p.oid) AS def FROM pg_proc p+ WHERE p.pronamespace = 'public'::regnamespace AND p.proname = $1+ ORDER BY p.oid`,+ [name]+ )+ ).rows.map((r) => r.def);++/**+ * Make every helper match its file. Must run inside the authz transaction. Each file is+ * applied in a savepoint and kept only if the function it produces differs from the live+ * one; a file that would add a second overload fails, since changing a signature (and+ * everything that depends on it) needs a reviewed migration.+ */+export async function syncHelpers(+ db: Client,+ helpers: Helper[],+ { dryRun }: { dryRun: boolean }+): Promise<string[]> {+ const changed: string[] = [];+ for (const { name, sql } of helpers) {+ const before = await definitions(db, name);+ if (before.length > 1) {+ throw new Error(+ `helper ${name} has ${before.length} overloads; expected one`+ );+ }+ await db.query("SAVEPOINT authz_helper");+ await db.query(sql);+ const after = await definitions(db, name);+ if (after.length !== 1) {+ await db.query("ROLLBACK TO SAVEPOINT authz_helper");+ throw new Error(+ `helpers/${name}.sql changes the signature of ${name}; that needs a migration`+ );+ }+ const differs = after[0] !== before[0];+ if (differs) changed.push(name);+ await db.query(+ differs && !dryRun+ ? "RELEASE SAVEPOINT authz_helper"+ : "ROLLBACK TO SAVEPOINT authz_helper"+ );+ }+ return changed;+}diff --git a/packages/database/src/authz/helpers/assert_company_access.sql b/packages/database/src/authz/helpers/assert_company_access.sqlnew file mode 100644index 0000000000..4e71f49a57--- /dev/null+++ b/packages/database/src/authz/helpers/assert_company_access.sql@@ -0,0 +1,25 @@+CREATE OR REPLACE FUNCTION public.assert_company_access(p_company_id text, p_permission text DEFAULT NULL::text)+ RETURNS void+ LANGUAGE plpgsql+ STABLE SECURITY DEFINER+ SET search_path TO 'public'+AS $function$+BEGIN+ -- service_role, and direct connections (jobs, Kysely, edge functions) are already trusted.+ IF current_setting('role', true) NOT IN ('anon', 'authenticated') THEN+ RETURN;+ END IF;++ IF p_company_id = ANY (+ CASE WHEN p_permission IS NULL+ THEN get_companies_with_employee_role()+ ELSE get_companies_with_employee_permission(p_permission)+ END+ ) THEN+ RETURN;+ END IF;++ RAISE EXCEPTION 'Not authorized for this company'+ USING ERRCODE = 'insufficient_privilege';+END;+$function$;diff --git a/packages/database/src/authz/helpers/get_api_key_scopes.sql b/packages/database/src/authz/helpers/get_api_key_scopes.sqlnew file mode 100644index 0000000000..d827e271ec--- /dev/null+++ b/packages/database/src/authz/helpers/get_api_key_scopes.sql@@ -0,0 +1,23 @@+CREATE OR REPLACE FUNCTION public.get_api_key_scopes()+ RETURNS jsonb+ LANGUAGE plpgsql+ SECURITY DEFINER+ SET search_path TO 'public', 'extensions'+AS $function$+ DECLARE+ scopes JSONB;+ raw_key TEXT;+ BEGIN+ raw_key := (current_setting('request.headers'::text, true))::json ->> 'carbon-key';+ IF raw_key IS NULL THEN+ RETURN NULL;+ END IF;++ SELECT "apiKey"."scopes" INTO scopes+ FROM "apiKey"+ WHERE "keyHash" = encode(digest(raw_key::bytea, 'sha256'::text), 'hex')+ AND ("expiresAt" IS NULL OR "expiresAt" > NOW());++ RETURN scopes;+ END;+$function$;diff --git a/packages/database/src/authz/helpers/get_claims.sql b/packages/database/src/authz/helpers/get_claims.sqlnew file mode 100644index 0000000000..0574c9a399--- /dev/null+++ b/packages/database/src/authz/helpers/get_claims.sql@@ -0,0 +1,34 @@+CREATE OR REPLACE FUNCTION public.get_claims(uid text, company text)+ RETURNS jsonb+ LANGUAGE plpgsql+ STABLE SECURITY DEFINER+ SET search_path TO 'public'+AS $function$+ DECLARE company_role text;+ DECLARE role_object jsonb;+ DECLARE perms jsonb;+ BEGIN+ -- Your own claims, or those of someone in a company where you may view or+ -- update users (the permission editor reads them with users_update alone).+ IF current_setting('role', true) IN ('anon', 'authenticated')+ AND uid IS DISTINCT FROM auth.uid()::text+ AND NOT EXISTS (+ SELECT 1 FROM "userToCompany" utc+ WHERE utc."userId" = uid+ AND utc."companyId" = ANY (+ get_companies_with_employee_permission('users_view')+ || get_companies_with_employee_permission('users_update')+ )+ ) THEN+ RAISE EXCEPTION 'Not authorized to read claims for this user'+ USING ERRCODE = 'insufficient_privilege';+ END IF;++ select role from "userToCompany" into company_role where "userId" = uid AND "companyId" = company;+ select permissions from "userPermission" into perms where id = uid;+ role_object := jsonb_build_object('role', company_role);+++ return (role_object || perms)::jsonb;+ END;+$function$;diff --git a/packages/database/src/authz/helpers/get_companies_with_any_role.sql b/packages/database/src/authz/helpers/get_companies_with_any_role.sqlnew file mode 100644index 0000000000..a0de5f1b4a--- /dev/null+++ b/packages/database/src/authz/helpers/get_companies_with_any_role.sql@@ -0,0 +1,24 @@+CREATE OR REPLACE FUNCTION public.get_companies_with_any_role()+ RETURNS text[]+ LANGUAGE plpgsql+ SECURITY DEFINER+ SET search_path TO 'public'+AS $function$+DECLARE+ user_companies text[];+ api_key_company text;+BEGIN+ api_key_company := get_company_id_from_api_key();++ IF api_key_company IS NOT NULL THEN+ RETURN ARRAY[api_key_company];+ END IF;++ SELECT array_agg("companyId"::text)+ INTO user_companies+ FROM "userToCompany"+ WHERE "userId" = auth.uid()::text;++ RETURN COALESCE(user_companies, '{}');+END;+$function$;diff --git a/packages/database/src/authz/helpers/get_companies_with_employee_permission.sql b/packages/database/src/authz/helpers/get_companies_with_employee_permission.sqlnew file mode 100644index 0000000000..ae950516cc--- /dev/null+++ b/packages/database/src/authz/helpers/get_companies_with_employee_permission.sql@@ -0,0 +1,49 @@+CREATE OR REPLACE FUNCTION public.get_companies_with_employee_permission(permission text)+ RETURNS text[]+ LANGUAGE plpgsql+ STABLE SECURITY DEFINER+ SET search_path TO 'public'+AS $function$+DECLARE+ permission_companies text[];+ api_key_company text;+ employee_companies text[];+ api_key_scopes JSONB;+BEGIN+ api_key_company := get_company_id_from_api_key();++ IF api_key_company IS NOT NULL THEN+ api_key_scopes := get_api_key_scopes();+ IF api_key_scopes IS NULL OR api_key_scopes = '{}'::jsonb THEN+ RETURN '{}';+ END IF;+ IF (api_key_scopes ? permission)+ AND api_key_company = ANY(jsonb_to_text_array(api_key_scopes->permission)) THEN+ RETURN ARRAY[api_key_company];+ ELSE+ RETURN '{}';+ END IF;+ END IF;++ SELECT array_agg("companyId"::text)+ INTO employee_companies+ FROM "userToCompany"+ WHERE "userId" = auth.uid()::text AND "role" = 'employee';++ SELECT jsonb_to_text_array(COALESCE(permissions->permission, '[]'))+ INTO permission_companies+ FROM public."userPermission"+ WHERE id::text = auth.uid()::text;++ IF permission_companies IS NOT NULL AND employee_companies IS NOT NULL THEN+ SELECT array_agg(company)+ INTO permission_companies+ FROM unnest(permission_companies) company+ WHERE company = ANY(employee_companies);+ ELSE+ permission_companies := '{}';+ END IF;++ RETURN COALESCE(permission_companies, '{}');+END;+$function$;diff --git a/packages/database/src/authz/helpers/get_companies_with_employee_role.sql b/packages/database/src/authz/helpers/get_companies_with_employee_role.sqlnew file mode 100644index 0000000000..8fe6cbd66c--- /dev/null+++ b/packages/database/src/authz/helpers/get_companies_with_employee_role.sql@@ -0,0 +1,24 @@+CREATE OR REPLACE FUNCTION public.get_companies_with_employee_role()+ RETURNS text[]+ LANGUAGE plpgsql+ STABLE SECURITY DEFINER+ SET search_path TO 'public'+AS $function$+DECLARE+ user_companies text[];+ api_key_company text;+BEGIN+ api_key_company := get_company_id_from_api_key();++ IF api_key_company IS NOT NULL THEN+ RETURN ARRAY[api_key_company];+ END IF;++ SELECT array_agg("companyId"::text)+ INTO user_companies+ FROM "userToCompany"+ WHERE "userId" = auth.uid()::text AND "role" = 'employee';++ RETURN COALESCE(user_companies, '{}');+END;+$function$;diff --git a/packages/database/src/authz/helpers/get_company_groups_for_employee.sql b/packages/database/src/authz/helpers/get_company_groups_for_employee.sqlnew file mode 100644index 0000000000..4af1285a17--- /dev/null+++ b/packages/database/src/authz/helpers/get_company_groups_for_employee.sql@@ -0,0 +1,40 @@+CREATE OR REPLACE FUNCTION public.get_company_groups_for_employee()+ RETURNS text[]+ LANGUAGE plpgsql+ SECURITY DEFINER+ SET search_path TO 'public'+AS $function$+DECLARE+ employee_companies text[];+ group_ids text[];+ api_key_company text;+BEGIN+ api_key_company := get_company_id_from_api_key();++ IF api_key_company IS NOT NULL THEN+ SELECT ARRAY["companyGroupId"::text]+ INTO group_ids+ FROM "company"+ WHERE "id" = api_key_company+ AND "companyGroupId" IS NOT NULL;+ RETURN COALESCE(group_ids, '{}');+ END IF;++ SELECT array_agg("companyId"::text)+ INTO employee_companies+ FROM "userToCompany"+ WHERE "userId" = auth.uid()::text AND "role" = 'employee';++ IF employee_companies IS NULL THEN+ RETURN '{}';+ END IF;++ SELECT array_agg(DISTINCT "companyGroupId"::text)+ INTO group_ids+ FROM "company"+ WHERE "id" = ANY(employee_companies)+ AND "companyGroupId" IS NOT NULL;++ RETURN COALESCE(group_ids, '{}');+END;+$function$;diff --git a/packages/database/src/authz/helpers/get_company_groups_for_root_permission.sql b/packages/database/src/authz/helpers/get_company_groups_for_root_permission.sqlnew file mode 100644index 0000000000..98fcb6a7aa--- /dev/null+++ b/packages/database/src/authz/helpers/get_company_groups_for_root_permission.sql@@ -0,0 +1,27 @@+CREATE OR REPLACE FUNCTION public.get_company_groups_for_root_permission(permission text)+ RETURNS text[]+ LANGUAGE plpgsql+ SECURITY DEFINER+ SET search_path TO 'public'+AS $function$+DECLARE+ permitted_companies text[];+ group_ids text[];+BEGIN+ permitted_companies := get_companies_with_employee_permission(permission);++ IF permitted_companies IS NULL OR array_length(permitted_companies, 1) IS NULL THEN+ RETURN '{}';+ END IF;++ -- Only consider root companies (no parent)+ SELECT array_agg(DISTINCT "companyGroupId"::text)+ INTO group_ids+ FROM "company"+ WHERE "id" = ANY(permitted_companies)+ AND "parentCompanyId" IS NULL+ AND "companyGroupId" IS NOT NULL;++ RETURN COALESCE(group_ids, '{}');+END;+$function$;diff --git a/packages/database/src/authz/helpers/get_company_id_from_api_key.sql b/packages/database/src/authz/helpers/get_company_id_from_api_key.sqlnew file mode 100644index 0000000000..16e1425d31--- /dev/null+++ b/packages/database/src/authz/helpers/get_company_id_from_api_key.sql@@ -0,0 +1,23 @@+CREATE OR REPLACE FUNCTION public.get_company_id_from_api_key()+ RETURNS text+ LANGUAGE plpgsql+ SECURITY DEFINER+ SET search_path TO 'public', 'extensions'+AS $function$+ DECLARE+ company_id TEXT;+ raw_key TEXT;+ BEGIN+ raw_key := (current_setting('request.headers'::text, true))::json ->> 'carbon-key';+ IF raw_key IS NULL THEN+ RETURN NULL;+ END IF;++ SELECT "companyId" INTO company_id+ FROM "apiKey"+ WHERE "keyHash" = encode(digest(raw_key::bytea, 'sha256'::text), 'hex')+ AND ("expiresAt" IS NULL OR "expiresAt" > NOW());++ RETURN company_id;+ END;+$function$;diff --git a/packages/database/src/authz/helpers/get_company_id_from_foreign_key.sql b/packages/database/src/authz/helpers/get_company_id_from_foreign_key.sqlnew file mode 100644index 0000000000..891efa8783--- /dev/null+++ b/packages/database/src/authz/helpers/get_company_id_from_foreign_key.sql@@ -0,0 +1,20 @@+CREATE OR REPLACE FUNCTION public.get_company_id_from_foreign_key(foreign_key text, tbl text)+ RETURNS text+ LANGUAGE plpgsql+ STABLE SECURITY DEFINER+ SET search_path TO 'public'+AS $function$+ DECLARE+ company_id text;+ BEGIN+ -- Policies call this inside a query. Called as the API endpoint itself it would tell+ -- anyone holding the anon key which company owns any row id, so refuse that. PostgREST+ -- sets request.path to /rpc/<function> only for a direct call (any case, any trailing /).+ IF current_setting('request.path', true) ~* '/rpc/get_company_id_from_foreign_key/*$' THEN+ RAISE EXCEPTION 'get_company_id_from_foreign_key cannot be called through the API'+ USING ERRCODE = 'insufficient_privilege';+ END IF;+ EXECUTE format('SELECT "companyId" FROM %I WHERE id = $1', tbl) INTO company_id USING foreign_key;+ RETURN company_id;+ END;+$function$;diff --git a/packages/database/src/authz/helpers/get_customer_ids_with_customer_permission.sql b/packages/database/src/authz/helpers/get_customer_ids_with_customer_permission.sqlnew file mode 100644index 0000000000..1a00b91e5c--- /dev/null+++ b/packages/database/src/authz/helpers/get_customer_ids_with_customer_permission.sql@@ -0,0 +1,48 @@+CREATE OR REPLACE FUNCTION public.get_customer_ids_with_customer_permission(permission text)+ RETURNS text[]+ LANGUAGE plpgsql+ SECURITY DEFINER+ SET search_path TO 'public'+AS $function$+DECLARE+ permission_companies text[];+ customer_company_ids text[];+ customer_ids text[];+BEGIN+ -- Get companies where user is a customer+ SELECT array_agg("companyId"::text)+ INTO customer_company_ids+ FROM "userToCompany"+ WHERE "userId" = auth.uid()::text AND "role" = 'customer';++ -- Get companies from user permissions+ SELECT jsonb_to_text_array(COALESCE(permissions->permission, '[]'))+ INTO permission_companies+ FROM public."userPermission" up+ WHERE up.id::text = auth.uid()::text;++ -- Filter permission_companies to only include companies where user is customer+ IF permission_companies IS NOT NULL AND customer_company_ids IS NOT NULL THEN+ SELECT array_agg(company)+ INTO permission_companies+ FROM unnest(permission_companies) company+ WHERE company = ANY(customer_company_ids);+ ELSE+ permission_companies := '{}';+ END IF;++ -- Get customer IDs where company matches filtered permissions+ SELECT array_agg(c.id::text)+ INTO customer_ids+ FROM "customer" c+ WHERE c."companyId" = ANY(permission_companies);++ -- Get customer IDs from customer accounts+ SELECT array_agg(ca."customerId"::text)+ INTO customer_ids+ FROM "customerAccount" ca+ WHERE ca.id::uuid = auth.uid() AND ca."companyId" = ANY(customer_company_ids);++ RETURN customer_ids;+END;+$function$;diff --git a/packages/database/src/authz/helpers/get_supplier_ids_with_supplier_permission.sql b/packages/database/src/authz/helpers/get_supplier_ids_with_supplier_permission.sqlnew file mode 100644index 0000000000..3945992c09--- /dev/null+++ b/packages/database/src/authz/helpers/get_supplier_ids_with_supplier_permission.sql@@ -0,0 +1,48 @@+CREATE OR REPLACE FUNCTION public.get_supplier_ids_with_supplier_permission(permission text)+ RETURNS text[]+ LANGUAGE plpgsql+ SECURITY DEFINER+ SET search_path TO 'public'+AS $function$+DECLARE+ permission_companies text[];+ supplier_company_ids text[];+ supplier_ids text[];+BEGIN+ -- Get companies where user is a supplier+ SELECT array_agg("companyId"::text)+ INTO supplier_company_ids+ FROM "userToCompany"+ WHERE "userId" = auth.uid()::text AND "role" = 'supplier';++ -- Get companies from user permissions+ SELECT jsonb_to_text_array(COALESCE(permissions->permission, '[]'))+ INTO permission_companies+ FROM public."userPermission" up+ WHERE up.id::text = auth.uid()::text;++ -- Filter permission_companies to only include companies where user is supplier+ IF permission_companies IS NOT NULL AND supplier_company_ids IS NOT NULL THEN+ SELECT array_agg(company)+ INTO permission_companies+ FROM unnest(permission_companies) company+ WHERE company = ANY(supplier_company_ids);+ ELSE+ permission_companies := '{}';+ END IF;++ -- Get supplier IDs where company matches filtered permissions+ SELECT array_agg(c.id::text)+ INTO supplier_ids+ FROM "supplier" c+ WHERE c."companyId" = ANY(permission_companies);++ -- Get supplier IDs from supplier accounts+ SELECT array_agg(ca."supplierId"::text)+ INTO supplier_ids+ FROM "supplierAccount" ca+ WHERE ca.id::uuid = auth.uid() AND ca."companyId" = ANY(supplier_company_ids);++ RETURN supplier_ids;+END;+$function$;diff --git a/packages/database/src/authz/helpers/groups_for_user.sql b/packages/database/src/authz/helpers/groups_for_user.sqlnew file mode 100644index 0000000000..cb77576d37--- /dev/null+++ b/packages/database/src/authz/helpers/groups_for_user.sql@@ -0,0 +1,28 @@+CREATE OR REPLACE FUNCTION public.groups_for_user(uid text)+ RETURNS text[]+ LANGUAGE plpgsql+ SECURITY DEFINER+ SET search_path TO 'public'+AS $function$+ DECLARE retval TEXT[];+ BEGIN+ WITH RECURSIVE "groupsForUser" AS (+ SELECT "groupId", "memberGroupId", "memberUserId" FROM "membership"+ WHERE "memberUserId" = uid::text+ UNION+ SELECT g1."groupId", g1."memberGroupId", g1."memberUserId" FROM "membership" g1+ INNER JOIN "groupsForUser" g2 ON g2."groupId" = g1."memberGroupId"+ ) SELECT COALESCE(array_agg("groupId"), '{}') INTO retval FROM "groupsForUser";++ -- Someone else's groups: only those in a company the caller belongs to.+ IF current_setting('role', true) IN ('anon', 'authenticated')+ AND uid IS DISTINCT FROM auth.uid()::text THEN+ SELECT COALESCE(array_agg(g.id), '{}') INTO retval+ FROM "group" g+ WHERE g.id = ANY (retval)+ AND g."companyId" = ANY (get_companies_with_employee_role());+ END IF;++ RETURN retval;+ END;+$function$;diff --git a/packages/database/src/authz/helpers/has_any_company_permission.sql b/packages/database/src/authz/helpers/has_any_company_permission.sqlnew file mode 100644index 0000000000..4bb382ce9c--- /dev/null+++ b/packages/database/src/authz/helpers/has_any_company_permission.sql@@ -0,0 +1,20 @@+CREATE OR REPLACE FUNCTION public.has_any_company_permission(claim text)+ RETURNS boolean+ LANGUAGE plpgsql+ STABLE SECURITY DEFINER+ SET search_path TO 'public'+AS $function$+ DECLARE+ permission_value text[];+ BEGIN++ SELECT jsonb_to_text_array(coalesce(permissions->claim, '[]')) INTO permission_value FROM public."userPermission" WHERE id = auth.uid()::text;+ IF permission_value IS NULL THEN+ return false;+ ELSIF array_length(permission_value, 1) > 0 THEN+ return true;+ ELSE+ return false;+ END IF;+ END;+$function$;diff --git a/packages/database/src/authz/helpers/has_valid_api_key_for_company.sql b/packages/database/src/authz/helpers/has_valid_api_key_for_company.sqlnew file mode 100644index 0000000000..c5e7875e03--- /dev/null+++ b/packages/database/src/authz/helpers/has_valid_api_key_for_company.sql@@ -0,0 +1,25 @@+CREATE OR REPLACE FUNCTION public.has_valid_api_key_for_company(company text)+ RETURNS boolean+ LANGUAGE plpgsql+ SECURITY DEFINER+ SET search_path TO 'public', 'extensions'+AS $function$+ DECLARE+ has_valid_key boolean;+ raw_key TEXT;+ BEGIN+ raw_key := (current_setting('request.headers'::text, true))::json ->> 'carbon-key';+ IF raw_key IS NULL THEN+ RETURN FALSE;+ END IF;++ SELECT EXISTS(+ SELECT 1 FROM "apiKey"+ WHERE "keyHash" = encode(digest(raw_key::bytea, 'sha256'::text), 'hex')+ AND "companyId" = company+ AND ("expiresAt" IS NULL OR "expiresAt" > NOW())+ ) INTO has_valid_key;++ RETURN has_valid_key;+ END;+$function$;diff --git a/packages/database/src/authz/helpers/jsonb_to_text_array.sql b/packages/database/src/authz/helpers/jsonb_to_text_array.sqlnew file mode 100644index 0000000000..84b60ce9c3--- /dev/null+++ b/packages/database/src/authz/helpers/jsonb_to_text_array.sql@@ -0,0 +1,7 @@+CREATE OR REPLACE FUNCTION public.jsonb_to_text_array(jsonb)+ RETURNS text[]+ LANGUAGE sql+ IMMUTABLE+AS $function$+ SELECT array_agg(value::text) FROM jsonb_array_elements_text($1) AS t(value);+$function$;diff --git a/packages/database/src/authz/manifest.ts b/packages/database/src/authz/manifest.tsnew file mode 100644index 0000000000..6c6e9495b3--- /dev/null+++ b/packages/database/src/authz/manifest.ts@@ -0,0 +1,1554 @@+// The authorization rules for every public table. `authz sync` makes a database match this+// file; `authz migration` ships a change to databases that do not sync yet (see migration.ts).+import {+ always,+ and,+ anyOf,+ authenticated,+ company,+ custom,+ exists,+ group,+ inCompany,+ inGroup,+ isNotNull,+ isNull,+ type Manifest,+ member,+ or,+ owner,+ policies,+ portal,+ serviceOnly,+ through,+ viaParent,+ where+} from "./rules";++/** The payment and memo a settlement applies are both still Draft (or absent). */+const draftSettlement = and(+ or(+ isNull("paymentId"),+ exists(+ "payment",+ "paymentId",+ where<"payment">((eb) => eb("status", "=", "Draft")),+ {+ sameCompany: true+ }+ )+ ),+ or(+ isNull("memoId"),+ exists(+ "memo",+ "memoId",+ where<"memo">((eb) => eb("status", "=", "Draft")),+ {+ sameCompany: true+ }+ )+ )+);++/**+ * The value's attribute is one users manage for themselves (canSelfManage), in a category of+ * one of the caller's companies. The account route checks canSelfManage too; this makes the+ * database agree instead of trusting the route.+ */+const ownAttribute = through(+ "userAttributeId",+ "userAttribute",+ "id",+ and(+ where<"userAttribute">((eb) => eb("canSelfManage", "=", true)),+ through(+ "userAttributeCategoryId",+ "userAttributeCategory",+ "id",+ inCompany("companyId", "employee")+ )+ )+);++/** The value's attribute belongs to a category the caller manages (resources_update). */+const managedAttribute = through(+ "userAttributeId",+ "userAttribute",+ "id",+ through(+ "userAttributeCategoryId",+ "userAttributeCategory",+ "id",+ inCompany("companyId", "resources_update")+ )+);++export const manifest = {+ ability: company("resources", {+ read: anyOf("resources_view", "production_view")+ }),+ account: group("accounting"),+ accountDefault: company("accounting", {+ read: "accounting_view",+ create: false,+ delete: false+ }),+ accountingPeriod: company("accounting", { read: "accounting_view" }),+ accountingPeriodBalance: company("accounting", {+ read: "accounting_view",+ delete: "accounting_update"+ }),+ accountingSyncOperation: company("settings", {+ create: false,+ delete: false+ }),+ accountingSyncTieOut: company("accounting", {+ read: "accounting_view",+ create: false,+ update: false,+ delete: false+ }),+ address: policies({+ select: inCompany("companyId", anyOf("sales_view", "purchasing_view")),+ insert: inCompany("companyId", anyOf("sales_create", "purchasing_create")),+ update: inCompany("companyId", anyOf("sales_update", "purchasing_update")),+ delete: inCompany("companyId", anyOf("sales_delete", "purchasing_delete"))+ }),+ agentMessage: policies({+ select: and(+ inCompany("companyId", "employee"),+ exists("agentThread", "threadId", owner("userId"), { sameCompany: true })+ ),+ insert: and(+ inCompany("companyId", "employee"),+ exists("agentThread", "threadId", owner("userId"), { sameCompany: true })+ ),+ update: and(+ inCompany("companyId", "employee"),+ exists("agentThread", "threadId", owner("userId"), { sameCompany: true })+ )+ }),+ agentMessagePart: custom(+ "EXISTS over a join of agentMessage and agentThread (the caller owns the thread); no shared piece expresses a join",+ (t) => `+ CREATE POLICY "INSERT" ON ${t} AS PERMISSIVE FOR INSERT TO public WITH CHECK ((("companyId" = ANY (( SELECT get_companies_with_employee_role() AS get_companies_with_employee_role)::text[])) AND (EXISTS ( SELECT 1+ FROM ("agentMessage" m+ JOIN "agentThread" t ON (((t.id = m."threadId") AND (t."companyId" = m."companyId"))))+ WHERE ((m.id = "agentMessagePart"."messageId") AND (m."companyId" = "agentMessagePart"."companyId") AND (t."userId" = (auth.uid())::text))))));+ CREATE POLICY "SELECT" ON ${t} AS PERMISSIVE FOR SELECT TO public USING ((("companyId" = ANY (( SELECT get_companies_with_employee_role() AS get_companies_with_employee_role)::text[])) AND (EXISTS ( SELECT 1+ FROM ("agentMessage" m+ JOIN "agentThread" t ON (((t.id = m."threadId") AND (t."companyId" = m."companyId"))))+ WHERE ((m.id = "agentMessagePart"."messageId") AND (m."companyId" = "agentMessagePart"."companyId") AND (t."userId" = (auth.uid())::text))))));+ CREATE POLICY "UPDATE" ON ${t} AS PERMISSIVE FOR UPDATE TO public USING ((("companyId" = ANY (( SELECT get_companies_with_employee_role() AS get_companies_with_employee_role)::text[])) AND (EXISTS ( SELECT 1+ FROM ("agentMessage" m+ JOIN "agentThread" t ON (((t.id = m."threadId") AND (t."companyId" = m."companyId"))))+ WHERE ((m.id = "agentMessagePart"."messageId") AND (m."companyId" = "agentMessagePart"."companyId") AND (t."userId" = (auth.uid())::text))))));+ `+ ),+ agentThread: policies({+ all: and(owner("userId"), inCompany("companyId", "employee"))+ }),+ apiKey: company("settings", { read: "settings_view" }),+ apiKeyRateLimit: policies({+ select: exists("apiKey", "apiKeyId", "settings_view")+ }),+ approvalRequest: serviceOnly(),+ approvalRule: company("settings", { read: "settings_view" }),+ assemblyComponentMapping: company("production"),+ assemblyInstruction: company("production"),+ assemblyInstructionStep: company("production"),+ assemblyInstructionStepMaterial: company("production"),+ assemblyInstructionStepSlide: company("production", {+ read: "production_view"+ }),+ assemblyInstructionStepTool: company("production", {+ read: "production_view"+ }),+ assemblyPlanJob: company("production"),+ assemblyUnit: company("production"),+ attributeDataType: policies({ select: authenticated }),+ auditLogArchive: serviceOnly(),+ balloon: company("quality"),+ batchProperty: policies({+ select: inCompany("companyId", anyOf("parts_view", "inventory_view")),+ insert: inCompany("companyId", anyOf("parts_create", "inventory_create")),+ update: inCompany("companyId", anyOf("parts_update", "inventory_update")),+ delete: inCompany("companyId", anyOf("parts_delete", "inventory_delete"))+ }),+ capacityReservation: company("production"),+ cardTransaction: policies({+ select: inCompany("companyId", "employee"),+ insert: and(+ where<"cardTransaction">((eb) => eb("status", "=", "Draft")),+ inCompany("companyId", "invoicing_create")+ ),+ update: and(+ where<"cardTransaction">((eb) => eb("status", "=", "Draft")),+ inCompany("companyId", "invoicing_update")+ ),+ delete: and(+ where<"cardTransaction">((eb) => eb("status", "=", "Draft")),+ inCompany("companyId", "invoicing_delete")+ )+ }),+ cardTransactionLine: policies({+ select: inCompany("companyId", "employee"),+ insert: and(+ exists(+ "cardTransaction",+ "cardTransactionId",+ where<"cardTransaction">((eb) => eb("status", "=", "Draft")),+ { sameCompany: true }+ ),+ inCompany("companyId", "invoicing_create")+ ),+ update: and(+ exists(+ "cardTransaction",+ "cardTransactionId",+ where<"cardTransaction">((eb) => eb("status", "=", "Draft")),+ { sameCompany: true }+ ),+ inCompany("companyId", "invoicing_update")+ ),+ delete: and(+ exists(+ "cardTransaction",+ "cardTransactionId",+ where<"cardTransaction">((eb) => eb("status", "=", "Draft")),+ { sameCompany: true }+ ),+ inCompany("companyId", "invoicing_delete")+ )+ }),+ challengeAttempt: policies({+ select: owner("userId"),+ insert: owner("userId")+ }),+ changeOrder: company("parts", { read: "parts_view" }),+ changeOrderActionTask: company("parts", { read: "parts_view" }),+ changeOrderAffectedItem: company("parts", { read: "parts_view" }),+ changeOrderRequiredAction: company("parts"),+ changeOrderSupersession: company("parts", { read: "parts_view" }),+ changeOrderType: company("parts"),+ company: policies({+ select: and(+ isNotNull("companyGroupId"),+ inGroup("companyGroupId", "employee")+ ),+ update: inCompany("id", "settings_update")+ }),+ companyAccountsPayableBillingAddress: company("settings", { column: "id" }),+ companyAccountsReceivableBillingAddress: company("settings", {+ column: "id"+ }),+ companyGroup: policies({+ select: through("id", "company", "companyGroupId", member("id"))+ }),+ companyIntegration: company("settings", { read: "settings_view" }),+ companyPlan: policies({ select: and(authenticated, member("id")) }),+ companySettings: company("settings", {+ create: false,+ delete: false,+ column: "id"+ }),+ companyUsage: policies({ select: and(authenticated, member("id")) }),+ config: policies({ select: authenticated }),+ configurationParameter: company("parts", { read: "member" }),+ configurationParameterGroup: company("parts", { read: "member" }),+ configurationRule: company("parts", { read: "parts_view" }),+ consumable: company("parts"),+ contact: policies({+ select: inCompany("companyId", anyOf("sales_view", "purchasing_view")),+ insert: inCompany("companyId", anyOf("sales_create", "purchasing_create")),+ update: inCompany("companyId", anyOf("sales_update", "purchasing_update")),+ delete: inCompany("companyId", anyOf("sales_delete", "purchasing_delete"))+ }),+ contractor: company("resources", { read: "resources_view" }),+ contractorAbility: policies({+ select: viaParent("contractorId", "contractor", "resources_view"),+ insert: viaParent("contractorId", "contractor", "resources_create"),+ update: viaParent("contractorId", "contractor", "resources_update"),+ delete: viaParent("contractorId", "contractor", "resources_delete")+ }),+ costCenter: company("accounting"),+ costLedger: policies({+ select: inCompany("companyId", anyOf("accounting_view", "parts_view"))+ }),+ country: policies({ select: authenticated }),+ currency: group("accounting"),+ currencyCode: policies({ select: authenticated }),+ customer: policies({+ select: or(+ inCompany("companyId", "sales_view"),+ portal.customer("id", "sales_view")+ ),+ insert: inCompany("companyId", "sales_create"),+ update: inCompany("companyId", "sales_update"),+ delete: inCompany("companyId", "sales_delete")+ }),+ customerAccount: policies({+ select: or(+ inCompany("companyId", "sales_view"),+ portal.customer("customerId", "sales_view")+ ),+ insert: inCompany("companyId", "sales_create"),+ update: inCompany("companyId", "sales_update"),+ delete: inCompany("companyId", "sales_delete")+ }),+ customerBankAccount: company("accounting", { read: "accounting_view" }),+ customerContact: policies({+ select: or(+ viaParent("customerId", "customer", "sales_view"),+ portal.customer("customerId", "sales_view")+ ),+ insert: or(+ viaParent("customerId", "customer", "sales_create"),+ portal.customer("customerId", "sales_create")+ ),+ update: or(+ viaParent("customerId", "customer", "sales_update"),+ portal.customer("customerId", "sales_update")+ ),+ delete: or(+ viaParent("customerId", "customer", "sales_delete"),+ portal.customer("customerId", "sales_delete")+ )+ }),+ customerItemPriceOverride: company("sales"),+ customerItemPriceOverrideBreak: company("sales"),+ customerLocation: policies({+ select: or(+ viaParent("customerId", "customer", "sales_view"),+ portal.customer("customerId", "sales_view")+ ),+ insert: or(+ viaParent("customerId", "customer", "sales_create"),+ portal.customer("customerId", "sales_create")+ ),+ update: or(+ viaParent("customerId", "customer", "sales_update"),+ portal.customer("customerId", "sales_update")+ ),+ delete: or(+ viaParent("customerId", "customer", "sales_delete"),+ portal.customer("customerId", "sales_delete")+ )+ }),+ customerPartToItem: policies({+ select: or(+ or(+ inCompany("companyId", "sales_view"),+ inCompany("companyId", "parts_view")+ ),+ or(+ portal.customer("customerId", "sales_view"),+ portal.customer("customerId", "parts_view")+ )+ ),+ insert: or(+ or(+ inCompany("companyId", "sales_create"),+ inCompany("companyId", "parts_create")+ ),+ or(+ portal.customer("customerId", "sales_create"),+ portal.customer("customerId", "parts_create")+ )+ ),+ update: or(+ or(+ inCompany("companyId", "sales_update"),+ inCompany("companyId", "parts_update")+ ),+ or(+ portal.customer("customerId", "sales_update"),+ portal.customer("customerId", "parts_update")+ )+ ),+ delete: or(+ or(+ inCompany("companyId", "sales_delete"),+ inCompany("companyId", "parts_delete")+ ),+ or(+ portal.customer("customerId", "sales_delete"),+ portal.customer("customerId", "parts_delete")+ )+ )+ }),+ customerPayment: company("sales", {+ read: "sales_view",+ create: false,+ delete: false+ }),+ customerShipping: company("sales", {+ read: "sales_view",+ create: false,+ delete: false+ }),+ customerStatus: company("sales", { read: "member" }),+ customerTax: company("sales", {+ read: "sales_view",+ create: false,+ delete: false+ }),+ customerType: company("sales", { read: "member" }),+ customField: company("settings", { read: "member" }),+ customFieldTable: policies({ select: authenticated }),+ demandActual: policies({+ select: or(+ inCompany("companyId", "parts_view"),+ inCompany("companyId", "inventory_view")+ ),+ insert: inCompany("companyId", "inventory_create"),+ update: inCompany("companyId", "inventory_update"),+ delete: inCompany("companyId", "inventory_delete")+ }),+ demandForecast: company("inventory", {+ read: "inventory_view"+ }),+ demandForecastSource: company("inventory", {+ read: "inventory_view"+ }),+ demandProjection: company("inventory", {+ read: "inventory_view"+ }),+ department: company("people"),+ depreciationRun: company("accounting", { read: "accounting_view" }),+ depreciationRunLine: company("accounting", { read: "accounting_view" }),+ dimension: group("accounting"),+ dimensionValue: group("accounting"),+ document: custom(+ "bespoke: readGroups/writeGroups arrays via groups_for_user, plus has_valid_api_key_for_company",+ (t) => `+ CREATE POLICY "DELETE" ON ${t} AS PERMISSIVE FOR DELETE TO public USING ((("companyId" = ANY (( SELECT get_companies_with_employee_permission('documents_delete'::text) AS get_companies_with_employee_permission)::text[])) AND (has_valid_api_key_for_company("companyId") OR ((groups_for_user((( SELECT auth.uid() AS uid))::text) && "writeGroups") = true))));+ CREATE POLICY "INSERT" ON ${t} AS PERMISSIVE FOR INSERT TO public WITH CHECK ((("companyId" = ANY (( SELECT get_companies_with_employee_permission('documents_create'::text) AS get_companies_with_employee_permission)::text[])) AND (has_valid_api_key_for_company("companyId") OR ((groups_for_user((( SELECT auth.uid() AS uid))::text) && "writeGroups") = true))));+ CREATE POLICY "SELECT" ON ${t} AS PERMISSIVE FOR SELECT TO public USING ((("companyId" = ANY (( SELECT get_companies_with_employee_permission('documents_view'::text) AS get_companies_with_employee_permission)::text[])) AND (has_valid_api_key_for_company("companyId") OR ((groups_for_user((( SELECT auth.uid() AS uid))::text) && "readGroups") = true))));+ CREATE POLICY "UPDATE" ON ${t} AS PERMISSIVE FOR UPDATE TO public USING ((("companyId" = ANY (( SELECT get_companies_with_employee_permission('documents_update'::text) AS get_companies_with_employee_permission)::text[])) AND (has_valid_api_key_for_company("companyId") OR ((groups_for_user((( SELECT auth.uid() AS uid))::text) && "writeGroups") = true))));+ `+ ),+ documentExtraction: policies({ all: inCompany("companyId", "employee") }),+ documentFavorite: policies({+ select: owner("userId"),+ insert: owner("userId"),+ delete: owner("userId")+ }),+ documentLabel: policies({+ select: owner("userId"),+ insert: owner("userId"),+ delete: owner("userId")+ }),+ documentSection: company("settings"),+ documentTemplate: company("settings"),+ documentTransaction: policies({+ select: owner("userId"),+ insert: owner("userId")+ }),+ employee: company("users", { create: "users_update" }),+ employeeAbility: company("resources", { read: "resources_view" }),+ employeeJob: company("people"),+ employeePin: serviceOnly(),+ employeeShift: company("people", { read: "people_view" }),+ employeeType: company("users", {+ read: "users_update",+ create: "users_update",+ delete: "users_update"+ }),+ employeeTypePermission: policies({+ all: viaParent("employeeTypeId", "employeeType", "users_update")+ }),+ enforcementRule: policies({+ select: inCompany("companyId", "employee"),+ insert: or(+ and(+ where<"enforcementRule">((eb) => eb("family", "=", "storage")),+ inCompany("companyId", "inventory_create")+ ),+ and(+ where<"enforcementRule">((eb) => eb("family", "=", "sales")),+ inCompany("companyId", "sales_create")+ )+ ),+ update: or(+ and(+ where<"enforcementRule">((eb) => eb("family", "=", "storage")),+ inCompany("companyId", "inventory_update")+ ),+ and(+ where<"enforcementRule">((eb) => eb("family", "=", "sales")),+ inCompany("companyId", "sales_update")+ )+ ),+ delete: or(+ and(+ where<"enforcementRule">((eb) => eb("family", "=", "storage")),+ inCompany("companyId", "inventory_delete")+ ),+ and(+ where<"enforcementRule">((eb) => eb("family", "=", "sales")),+ inCompany("companyId", "sales_delete")+ )+ )+ }),+ enforcementRuleAcknowledgment: company("sales", {+ update: false,+ delete: false+ }),+ enforcementRuleItemAssignment: policies({+ select: inCompany("companyId", "employee"),+ insert: exists(+ "enforcementRule",+ "ruleId",+ or(+ and(+ where<"enforcementRule">((eb) => eb("family", "=", "storage")),+ inCompany("companyId", "parts_create")+ ),+ and(+ where<"enforcementRule">((eb) => eb("family", "=", "sales")),+ inCompany("companyId", "sales_create")+ )+ ),+ { sameCompany: true }+ ),+ update: exists(+ "enforcementRule",+ "ruleId",+ or(+ and(+ where<"enforcementRule">((eb) => eb("family", "=", "storage")),+ inCompany("companyId", "parts_update")+ ),+ and(+ where<"enforcementRule">((eb) => eb("family", "=", "sales")),+ inCompany("companyId", "sales_update")+ )+ ),+ { sameCompany: true }+ ),+ delete: exists(+ "enforcementRule",+ "ruleId",+ or(+ and(+ where<"enforcementRule">((eb) => eb("family", "=", "storage")),+ inCompany("companyId", "parts_delete")+ ),+ and(+ where<"enforcementRule">((eb) => eb("family", "=", "sales")),+ inCompany("companyId", "sales_delete")+ )+ ),+ { sameCompany: true }+ )+ }),+ enforcementRuleWorkCenterAssignment: policies({+ select: inCompany("companyId", "employee"),+ insert: exists(+ "enforcementRule",+ "ruleId",+ and(+ where<"enforcementRule">((eb) => eb("family", "=", "storage")),+ where<"enforcementRule">((eb) => eb("targetType", "=", "workCenter")),+ inCompany("companyId", "resources_create")+ ),+ { sameCompany: true }+ ),+ update: exists(+ "enforcementRule",+ "ruleId",+ and(+ where<"enforcementRule">((eb) => eb("family", "=", "storage")),+ where<"enforcementRule">((eb) => eb("targetType", "=", "workCenter")),+ inCompany("companyId", "resources_update")+ ),+ { sameCompany: true }+ ),+ delete: inCompany("companyId", "resources_delete")+ }),+ eventSystemSubscription: company("settings"),+ exchangeRate: policies({ select: always, to: "authenticated" }),+ exchangeRateOverride: company("accounting", {+ create: "accounting_update",+ delete: "accounting_update"+ }),+ externalIntegrationMapping: policies({+ select: inCompany("companyId", "employee"),+ insert: inCompany("companyId", "employee")+ }),+ externalLink: policies({+ select: inCompany("companyId", "employee"),+ insert: inCompany(+ "companyId",+ anyOf("sales_create", "purchasing_create", "quality_create")+ ),+ update: inCompany(+ "companyId",+ anyOf("sales_update", "purchasing_update", "quality_update")+ ),+ delete: inCompany(+ "companyId",+ anyOf("sales_delete", "purchasing_delete", "quality_delete")+ )+ }),+ feedback: serviceOnly(),+ fiscalYearSettings: company("settings", { read: "settings_view" }),+ fixedAsset: company("accounting", { read: "accounting_view" }),+ fixedAssetClass: company("accounting", { read: "accounting_view" }),+ fixedAssetDisposal: company("accounting", {+ read: "accounting_view",+ update: false,+ delete: false+ }),+ fixedAssetUsageLog: company("accounting", { read: "accounting_view" }),+ fixture: serviceOnly(),+ fulfillment: company("sales", {+ read: anyOf("inventory_view", "sales_view"),+ create: anyOf("inventory_create", "sales_create")+ }),+ gauge: company("quality"),+ gaugeCalibrationRecord: company("quality", { read: "quality_view" }),+ gaugeType: company("quality"),+ group: company("users"),+ holiday: company("people"),+ implementationCheckState: company("settings", {+ create: "employee",+ update: "employee"+ }),+ implementationFieldValue: company("settings", {+ create: "employee",+ update: "employee"+ }),+ implementationHub: company("settings", { update: "employee", column: "id" }),+ implementationRow: policies({ all: inCompany("companyId", "employee") }),+ industry: policies({ select: authenticated }),+ inspection: company("quality", { read: "quality_view" }),+ inspectionDocument: company("quality"),+ inspectionFeature: company("quality"),+ inspectionHistory: company("quality", {+ read: "quality_view",+ update: false,+ delete: false+ }),+ inspectionMeasurement: company("quality", { read: "quality_view" }),+ inspectionSample: company("quality", { read: "quality_view" }),+ inspectionSamplingPlan: company("quality", { read: "quality_view" }),+ integration: policies({ select: authenticated }),+ intercompanyEliminationLine: company("accounting"),+ intercompanyTransaction: policies({+ select: or(+ inCompany("sourceCompanyId", "accounting_create"),+ inCompany("targetCompanyId", "accounting_create")+ ),+ insert: or(+ inCompany("sourceCompanyId", "accounting_create"),+ inCompany("targetCompanyId", "accounting_create")+ ),+ update: or(+ inCompany("sourceCompanyId", "accounting_update"),+ inCompany("targetCompanyId", "accounting_update")+ ),+ delete: or(+ inCompany("sourceCompanyId", "accounting_delete"),+ inCompany("targetCompanyId", "accounting_delete")+ )+ }),+ inventoryCount: company("inventory", { read: "inventory_view" }),+ inventoryCountLine: company("inventory", { read: "inventory_view" }),+ invite: serviceOnly(),+ // Settlements change only while the payment and memo they apply are still Draft, in the+ // settlement's own company. (The imported policy compared each parent to itself —+ // p.id = p."paymentId" — so writes only passed when both ids were null.)+ invoiceSettlement: policies({+ select: inCompany("companyId", "employee"),+ insert: and(draftSettlement, inCompany("companyId", "invoicing_create")),+ update: and(draftSettlement, inCompany("companyId", "invoicing_update")),+ delete: and(draftSettlement, inCompany("companyId", "invoicing_delete"))+ }),+ itarCertification: policies({ select: inCompany("companyId", "employee") }),+ item: policies({+ select: or(+ inCompany("companyId", "employee"),+ through(+ "id",+ "supplierPart",+ "itemId",+ and(portal.supplier("supplierId", "parts_view"), isNotNull("itemId"))+ ),+ through(+ "id",+ "customerPartToItem",+ "itemId",+ and(portal.customer("customerId", "parts_view"), isNotNull("itemId"))+ )+ ),+ insert: inCompany("companyId", "parts_create"),+ update: or(+ inCompany("companyId", "parts_update"),+ through(+ "id",+ "supplierPart",+ "itemId",+ portal.supplier("supplierId", "parts_update")+ ),+ through(+ "id",+ "customerPartToItem",+ "itemId",+ portal.customer("customerId", "parts_update")+ )+ ),+ delete: or(+ inCompany("companyId", "parts_delete"),+ through(+ "id",+ "supplierPart",+ "itemId",+ portal.supplier("supplierId", "parts_delete")+ ),+ through(+ "id",+ "customerPartToItem",+ "itemId",+ portal.customer("customerId", "parts_delete")+ )+ )+ }),+ itemCost: policies({+ select: or(+ or(+ inCompany("companyId", "parts_view"),+ inCompany("companyId", "sales_view")+ ),+ through(+ "itemId",+ "supplierPart",+ "itemId",+ portal.supplier("supplierId", "parts_view")+ )+ ),+ insert: inCompany("companyId", "parts_create"),+ update: or(+ inCompany("companyId", "parts_update"),+ through(+ "itemId",+ "supplierPart",+ "itemId",+ portal.supplier("supplierId", "parts_update")+ ),+ through(+ "itemId",+ "customerPartToItem",+ "itemId",+ portal.customer("customerId", "parts_update")+ )+ )+ }),+ itemInspectionDocumentAssignment: company("quality", {+ read: "quality_view"+ }),+ itemLedger: policies({+ select: inCompany("companyId", anyOf("inventory_view", "accounting_view")),+ insert: inCompany(+ "companyId",+ anyOf("inventory_create", "accounting_create")+ )+ }),+ itemPlanning: company("parts", { read: "parts_view", delete: false }),+ itemPostingGroup: company("accounting", { read: "accounting_view" }),+ itemReplenishment: company("parts", { read: "parts_view" }),+ itemSerialSequence: company("settings"),+ itemShelfLife: company("parts", { read: "parts_view" }),+ itemStockQuantities: policies({ select: inCompany("companyId", "employee") }),+ itemSupersession: company("parts"),+ itemUnitSalePrice: company("parts", {+ read: anyOf("parts_view", "sales_view")+ }),+ job: company("production"),+ jobFavorite: policies({+ select: owner("userId"),+ insert: owner("userId"),+ delete: owner("userId")+ }),+ jobMakeMethod: company("production"),+ jobMaterial: company("production"),+ jobMaterialStep: policies({+ select: exists("jobMaterial", "jobMaterialId", "employee"),+ insert: exists("jobMaterial", "jobMaterialId", "production_create"),+ update: exists("jobMaterial", "jobMaterialId", "production_update"),+ delete: exists("jobMaterial", "jobMaterialId", "production_delete")+ }),+ jobOperation: company("production"),+ jobOperationBatch: company("production"),+ jobOperationDependency: policies({+ select: inCompany("companyId", "employee")+ }),+ jobOperationNote: company("production", { create: "employee" }),+ jobOperationParameter: company("production"),+ jobOperationStep: company("production"),+ jobOperationStepRecord: company("production", { create: "employee" }),+ jobOperationStepSlide: company("production"),+ jobOperationTool: company("production"),+ jobOperationToolStep: policies({+ select: exists("jobOperationTool", "jobOperationToolId", "employee"),+ insert: exists(+ "jobOperationTool",+ "jobOperationToolId",+ "production_create"+ ),+ update: exists(+ "jobOperationTool",+ "jobOperationToolId",+ "production_update"+ ),+ delete: exists(+ "jobOperationTool",+ "jobOperationToolId",+ "production_delete"+ )+ }),+ journal: company("accounting", {+ read: "accounting_view",+ where: {+ // Posted stays updatable only for the Posted -> Reversed transition, which the+ // journal_posted_immutable trigger enforces. The new row is always checked+ // against the company scope alone, so a journal can never move company.+ update: (eb) => eb("status", "in", ["Draft", "Posted"]),+ delete: (eb) => eb("status", "=", "Draft")+ }+ }),+ journalLine: policies({+ select: inCompany("companyId", "accounting_view"),+ insert: inCompany("companyId", "accounting_create"),+ update: and(+ inCompany("companyId", "accounting_update"),+ exists(+ "journal",+ "journalId",+ where<"journal">((eb) => eb("status", "=", "Draft"))+ )+ ),+ delete: and(+ inCompany("companyId", "accounting_delete"),+ exists(+ "journal",+ "journalId",+ where<"journal">((eb) => eb("status", "=", "Draft"))+ )+ )+ }),+ journalLineDimension: company("accounting", {+ read: "accounting_view",+ update: false+ }),+ kanban: company("inventory"),+ lessonCompletion: policies({+ select: owner("userId"),+ insert: owner("userId")+ }),+ location: company("resources"),+ maintenanceDispatch: company("resources", {+ create: "employee",+ update: "employee"+ }),+ maintenanceDispatchComment: policies({+ select: inCompany("companyId", "employee"),+ insert: inCompany("companyId", "employee"),+ update: {+ using: owner("createdBy"),+ check: and(owner("createdBy"), inCompany("companyId", "employee"))+ },+ delete: owner("createdBy")+ }),+ maintenanceDispatchEvent: company("resources", {+ create: "employee",+ update: "employee"+ }),+ maintenanceDispatchItem: company("resources", { create: "employee" }),+ // Same rule as its sibling maintenanceDispatchItem. (The imported policy named+ // maintenance_update / maintenance_delete, which no one can hold.)+ maintenanceDispatchItemTrackedEntity: company("resources", {+ create: "employee"+ }),+ maintenanceDispatchWorkCenter: company("resources", { create: "employee" }),+ maintenanceFailureMode: company("resources"),+ maintenanceSchedule: company("resources", { read: "resources_view" }),+ maintenanceScheduleItem: company("resources", { create: "employee" }),+ makeMethod: company("parts", { read: "parts_view" }),+ material: company("parts"),+ materialDimension: policies({+ select: or(isNull("companyId"), inCompany("companyId", "parts_view")),+ insert: inCompany("companyId", "parts_create"),+ update: inCompany("companyId", "parts_update"),+ delete: inCompany("companyId", "parts_delete")+ }),+ materialFinish: policies({+ select: or(isNull("companyId"), inCompany("companyId", "parts_view")),+ insert: inCompany("companyId", "parts_create"),+ update: inCompany("companyId", "parts_update"),+ delete: inCompany("companyId", "parts_delete")+ }),+ materialForm: policies({+ select: or(isNull("companyId"), inCompany("companyId", "parts_view")),+ insert: inCompany("companyId", "parts_create"),+ update: inCompany("companyId", "parts_update"),+ delete: inCompany("companyId", "parts_delete")+ }),+ materialGrade: policies({+ select: or(isNull("companyId"), inCompany("companyId", "parts_view")),+ insert: inCompany("companyId", "parts_create"),+ update: inCompany("companyId", "parts_update"),+ delete: inCompany("companyId", "parts_delete")+ }),+ materialSubstance: policies({+ select: or(isNull("companyId"), inCompany("companyId", "parts_view")),+ insert: inCompany("companyId", "parts_create"),+ update: inCompany("companyId", "parts_update"),+ delete: inCompany("companyId", "parts_delete")+ }),+ materialType: policies({+ select: or(isNull("companyId"), inCompany("companyId", "parts_view")),+ insert: inCompany("companyId", "parts_create"),+ update: inCompany("companyId", "parts_update"),+ delete: inCompany("companyId", "parts_delete")+ }),+ membership: policies({+ select: viaParent("groupId", "group", "employee"),+ insert: viaParent("groupId", "group", "users_update"),+ update: viaParent("groupId", "group", "users_update"),+ delete: viaParent("groupId", "group", "users_update")+ }),+ memo: policies({+ select: inCompany("companyId", "employee"),+ insert: inCompany("companyId", "invoicing_create"),+ update: inCompany("companyId", "invoicing_update"),+ delete: and(+ where<"memo">((eb) => eb("status", "=", "Draft")),+ inCompany("companyId", "invoicing_delete")+ )+ }),+ methodMaterial: company("parts", { read: "parts_view" }),+ methodMaterialStep: policies({+ select: exists("methodMaterial", "methodMaterialId", "employee"),+ insert: exists("methodMaterial", "methodMaterialId", "parts_create"),+ update: exists("methodMaterial", "methodMaterialId", "parts_update"),+ delete: exists("methodMaterial", "methodMaterialId", "parts_delete")+ }),+ methodOperation: company("parts", { read: "parts_view" }),+ methodOperationParameter: company("parts"),+ methodOperationStep: company("production"),+ methodOperationStepSlide: company("production"),+ methodOperationTool: company("parts", { read: "parts_view" }),+ methodOperationToolStep: policies({+ select: exists("methodOperationTool", "methodOperationToolId", "employee"),+ insert: exists(+ "methodOperationTool",+ "methodOperationToolId",+ "parts_create"+ ),+ update: exists(+ "methodOperationTool",+ "methodOperationToolId",+ "parts_update"+ ),+ delete: exists(+ "methodOperationTool",+ "methodOperationToolId",+ "parts_delete"+ )+ }),+ modelUpload: company("parts"),+ nonConformance: company("quality", { read: "quality_view" }),+ nonConformanceActionProcess: company("quality", { read: "quality_view" }),+ nonConformanceActionTask: company("quality", { read: "quality_view" }),+ nonConformanceApprovalTask: company("quality", { read: "quality_view" }),+ nonConformanceCustomer: company("quality", { read: "quality_view" }),+ nonConformanceInspection: company("quality", { read: "quality_view" }),+ nonConformanceItem: company("quality", { read: "quality_view" }),+ nonConformanceItemTrackedEntity: company("quality", { read: "quality_view" }),+ nonConformanceJobOperation: company("quality", { read: "quality_view" }),+ nonConformancePurchaseOrderLine: company("quality", { read: "quality_view" }),+ nonConformancePurchaseReturnOrderLine: company("quality", {+ read: "quality_view"+ }),+ nonConformanceReceiptLine: company("quality", { read: "quality_view" }),+ nonConformanceRequiredAction: company("quality", { read: "quality_view" }),+ nonConformanceReviewer: company("quality", { read: "quality_view" }),+ nonConformanceSalesOrderLine: company("quality", { read: "quality_view" }),+ nonConformanceSalesReturnOrderLine: company("quality", {+ read: "quality_view"+ }),+ nonConformanceShipmentLine: company("quality", { read: "quality_view" }),+ nonConformanceSupplier: company("quality", { read: "quality_view" }),+ nonConformanceTrackedEntity: company("quality", { read: "quality_view" }),+ nonConformanceType: company("quality"),+ nonConformanceWorkflow: company("quality", { read: "quality_view" }),+ noQuoteReason: company("sales", { read: "sales_view" }),+ // Only the author edits or deletes a note, and never moves it into another company.+ note: policies({+ select: inCompany("companyId", "employee"),+ insert: inCompany("companyId", "employee"),+ update: {+ using: owner("createdBy"),+ check: and(owner("createdBy"), inCompany("companyId", "employee"))+ },+ delete: owner("createdBy")+ }),+ notification: policies({ select: owner("userId"), update: owner("userId") }),+ notificationDelivery: policies({ select: owner("userId") }),+ notificationPreference: policies({+ select: and(owner("userId"), member("companyId")),+ insert: and(owner("userId"), member("companyId")),+ update: {+ using: owner("userId"),+ check: and(owner("userId"), member("companyId"))+ },+ delete: and(owner("userId"), member("companyId"))+ }),+ oauthClient: serviceOnly(),+ oauthCode: serviceOnly(),+ oauthToken: serviceOnly(),+ opportunity: company("sales", { read: "sales_view", delete: false }),+ part: company("parts"),+ partner: company("resources"),+ passkeyCredential: policies({ all: owner("userId") }),+ payment: policies({+ select: inCompany("companyId", "employee"),+ insert: inCompany("companyId", "invoicing_create"),+ update: inCompany("companyId", "invoicing_update"),+ delete: and(+ where<"payment">((eb) => eb("status", "=", "Draft")),+ inCompany("companyId", "invoicing_delete")+ )+ }),+ paymentTerm: company("accounting", {+ read: anyOf("accounting_view", "sales_view", "purchasing_view")+ }),+ peopleAbsence: company("production"),+ peopleAssignment: company("production"),+ period: policies({ select: authenticated }),+ periodCloseTask: company("accounting"),+ periodCloseTaskDefinition: company("accounting"),+ pickingList: company("inventory", { read: "inventory_view" }),+ pickingListLine: company("inventory", { read: "inventory_view" }),+ pickingListLineTrackedEntity: policies({+ select: exists("pickingListLine", "pickingListLineId", "inventory_view"),+ insert: exists("pickingListLine", "pickingListLineId", "inventory_create"),+ update: exists("pickingListLine", "pickingListLineId", "inventory_update"),+ delete: exists("pickingListLine", "pickingListLineId", "inventory_delete")+ }),+ pickMethod: company("parts", { read: "parts_view", delete: false }),+ plan: policies({ select: authenticated }),+ pricingRule: company("sales"),+ printerRoute: company("printing", { read: "printing_view" }),+ printJob: company("printing", { read: "printing_view" }),+ procedure: company("production"),+ procedureParameter: company("production"),+ procedureStep: company("production"),+ process: company("resources"),+ productionEvent: company("production", { read: "production_view" }),+ productionQuantity: company("production"),+ project: company("accounting"),+ purchaseInvoice: company("invoicing", { read: "invoicing_view" }),+ purchaseInvoiceDelivery: company("invoicing", { read: "invoicing_view" }),+ purchaseInvoiceLine: company("invoicing", { read: "invoicing_view" }),+ purchaseInvoicePriceChange: policies({+ select: viaParent("invoiceId", "purchaseInvoice", "invoicing_view")+ }),+ purchaseInvoiceStatusHistory: policies({+ select: viaParent("invoiceId", "purchaseInvoice", "invoicing_view")+ }),+ purchaseOrder: company("purchasing", {+ read: anyOf("purchasing_view", "inventory_view", "invoicing_view")+ }),+ purchaseOrderDelivery: company("purchasing", { read: "purchasing_view" }),+ purchaseOrderFavorite: policies({+ select: owner("userId"),+ insert: owner("userId"),+ delete: owner("userId")+ }),+ purchaseOrderLine: company("purchasing", { read: "purchasing_view" }),+ purchaseOrderPayment: company("purchasing", { read: "purchasing_view" }),+ purchaseOrderStatusHistory: policies({+ select: viaParent("purchaseOrderId", "purchaseOrder", "purchasing_view")+ }),+ purchaseOrderTransaction: policies({+ select: viaParent("purchaseOrderId", "purchaseOrder", "purchasing_view"),+ insert: viaParent("purchaseOrderId", "purchaseOrder", "purchasing_update")+ }),+ purchaseReturnOrder: company("purchasing"),+ purchaseReturnOrderCreditLine: company("invoicing"),+ purchaseReturnOrderLine: company("purchasing"),+ purchaseReturnOrderLineTrackedEntity: company("purchasing"),+ purchasingRfq: company("purchasing", { read: "purchasing_view" }),+ purchasingRfqFavorite: policies({+ select: owner("userId"),+ insert: owner("userId"),+ delete: owner("userId")+ }),+ purchasingRfqLine: company("purchasing", { read: "purchasing_view" }),+ purchasingRfqSupplier: company("purchasing", { read: "purchasing_view" }),+ purchasingRfqToPurchaseOrder: company("purchasing", {+ read: "purchasing_view",+ update: false,+ delete: false+ }),+ purchasingRfqToSupplierQuote: company("purchasing", {+ read: "purchasing_view",+ update: false,+ delete: false+ }),+ qualityDocument: company("quality"),+ qualityDocumentStep: company("production"),+ quote: company("sales", { read: "sales_view" }),+ quoteFavorite: policies({+ select: owner("userId"),+ insert: owner("userId"),+ delete: owner("userId")+ }),+ quoteLine: company("sales", { read: "sales_view" }),+ quoteLinePrice: policies({+ select: viaParent("quoteLineId", "quoteLine", "sales_view"),+ insert: viaParent("quoteLineId", "quoteLine", "sales_create"),+ update: viaParent("quoteLineId", "quoteLine", "sales_update"),+ delete: viaParent("quoteLineId", "quoteLine", "sales_delete")+ }),+ quoteMakeMethod: company("sales", { read: "sales_view" }),+ quoteMaterial: company("sales", { read: "sales_view" }),+ quoteMaterialStep: policies({+ select: exists("quoteMaterial", "quoteMaterialId", "employee"),+ insert: exists("quoteMaterial", "quoteMaterialId", "sales_create"),+ update: exists("quoteMaterial", "quoteMaterialId", "sales_update"),+ delete: exists("quoteMaterial", "quoteMaterialId", "sales_delete")+ }),+ quoteOperation: company("sales", { read: "sales_view" }),+ quoteOperationParameter: company("parts"),+ quoteOperationStep: company("production"),+ quoteOperationStepSlide: company("production"),+ quoteOperationTool: company("sales"),+ quoteOperationToolStep: policies({+ select: exists("quoteOperationTool", "quoteOperationToolId", "employee"),+ insert: exists(+ "quoteOperationTool",+ "quoteOperationToolId",+ "sales_create"+ ),+ update: exists(+ "quoteOperationTool",+ "quoteOperationToolId",+ "sales_update"+ ),+ delete: exists("quoteOperationTool", "quoteOperationToolId", "sales_delete")+ }),+ quotePayment: policies({+ select: or(+ inCompany("companyId", "sales_view"),+ exists("quote", "id", portal.customer("customerId", "sales_view"))+ ),+ insert: or(+ inCompany("companyId", "sales_create"),+ exists("quote", "id", portal.customer("customerId", "sales_create"))+ ),+ update: or(+ inCompany("companyId", "sales_update"),+ exists("quote", "id", portal.customer("customerId", "sales_update"))+ ),+ delete: or(+ inCompany("companyId", "sales_delete"),+ exists("quote", "id", portal.customer("customerId", "sales_delete"))+ )+ }),+ quoteShipment: policies({+ select: or(+ inCompany("companyId", "sales_view"),+ exists("quote", "id", portal.customer("customerId", "sales_view"))+ ),+ insert: or(+ inCompany("companyId", "sales_create"),+ exists("quote", "id", portal.customer("customerId", "sales_create"))+ ),+ update: or(+ inCompany("companyId", "sales_update"),+ exists("quote", "id", portal.customer("customerId", "sales_update"))+ ),+ delete: or(+ inCompany("companyId", "sales_delete"),+ exists("quote", "id", portal.customer("customerId", "sales_delete"))+ )+ }),+ receipt: company("inventory", { read: "inventory_view" }),+ receiptFixedAssetLine: company("inventory", { read: "inventory_view" }),+ receiptLine: company("inventory", { read: "inventory_view" }),+ reportPin: policies({+ all: and(owner("userId"), inCompany("companyId", "employee"))+ }),+ reportView: policies({+ select: and(+ inCompany("companyId", "employee"),+ or(+ where<"reportView">((eb) => eb("visibility", "=", "Company")),+ owner("createdBy")+ )+ ),+ insert: and(inCompany("companyId", "employee"), owner("createdBy")),+ update: and(inCompany("companyId", "employee"), owner("createdBy")),+ delete: and(inCompany("companyId", "employee"), owner("createdBy"))+ }),+ returnReason: company("sales"),+ rework: company("production", { read: "production_view" }),+ riskRegister: company("quality", { create: "employee" }),+ salesInvoice: company("invoicing", { read: "invoicing_view" }),+ salesInvoiceLine: company("invoicing", { read: "invoicing_view" }),+ salesInvoiceShipment: company("invoicing", { read: "invoicing_view" }),+ salesOrder: company("sales", {+ read: anyOf("sales_view", "inventory_view", "invoicing_view")+ }),+ salesOrderFavorite: policies({+ select: owner("userId"),+ insert: owner("userId"),+ delete: owner("userId")+ }),+ salesOrderLine: company("sales", { read: "sales_view" }),+ salesOrderPayment: policies({+ select: or(+ inCompany("companyId", "sales_view"),+ exists("salesOrder", "id", portal.customer("customerId", "sales_view"))+ ),+ insert: or(+ inCompany("companyId", "sales_create"),+ exists("salesOrder", "id", portal.customer("customerId", "sales_create"))+ ),+ update: or(+ inCompany("companyId", "sales_update"),+ exists("salesOrder", "id", portal.customer("customerId", "sales_update"))+ ),+ delete: or(+ inCompany("companyId", "sales_delete"),+ exists("salesOrder", "id", portal.customer("customerId", "sales_delete"))+ )+ }),+ salesOrderShipment: policies({+ select: or(+ inCompany("companyId", "sales_view"),+ exists("salesOrder", "id", portal.customer("customerId", "sales_view"))+ ),+ insert: or(+ inCompany("companyId", "sales_create"),+ exists("salesOrder", "id", portal.customer("customerId", "sales_create"))+ ),+ update: or(+ inCompany("companyId", "sales_update"),+ exists("salesOrder", "id", portal.customer("customerId", "sales_update"))+ ),+ delete: or(+ inCompany("companyId", "sales_delete"),+ exists("salesOrder", "id", portal.customer("customerId", "sales_delete"))+ )+ }),+ salesOrderStatusHistory: policies({+ select: viaParent("salesOrderId", "salesOrder", "sales_view")+ }),+ salesOrderTransaction: policies({+ select: viaParent("salesOrderId", "salesOrder", "sales_view"),+ insert: viaParent("salesOrderId", "salesOrder", "sales_update")+ }),+ salesReturnOrder: company("sales"),+ salesReturnOrderCreditLine: company("invoicing"),+ salesReturnOrderLine: company("sales"),+ salesReturnOrderLineTrackedEntity: company("sales"),+ salesRfq: company("sales", { read: "sales_view" }),+ salesRfqFavorite: policies({+ select: owner("userId"),+ insert: owner("userId"),+ delete: owner("userId")+ }),+ salesRfqLine: company("sales", { read: "sales_view" }),+ scrapReason: company("production"),+ scriptRun: policies({ select: authenticated }),+ searchIndexRegistry: serviceOnly(),+ sequence: company("settings", { read: "settings_view" }),+ service: company("parts"),+ shift: company("people"),+ shipment: company("inventory", {+ read: anyOf("inventory_view", "sales_view"),+ create: anyOf("inventory_create", "sales_create")+ }),+ shipmentFixedAssetLine: company("inventory", { read: "inventory_view" }),+ shipmentLine: company("sales", {+ read: anyOf("inventory_view", "sales_view"),+ create: anyOf("inventory_create", "sales_create")+ }),+ shippingMethod: company("inventory"),+ shippingTerm: company("inventory"),+ slackDocumentThread: serviceOnly(),+ ssoConnection: company("settings", {+ create: "settings_update",+ delete: "settings_update"+ }),+ ssoDomain: company("settings", {+ create: "settings_update",+ delete: "settings_update"+ }),+ ssoReservedDomain: policies({ select: authenticated }),+ stockTransfer: company("inventory"),+ stockTransferLine: company("inventory"),+ storageType: company("parts"),+ storageUnit: company("parts"),+ suggestion: company("resources", {+ read: "resources_view",+ create: "employee"+ }),+ supplier: company("purchasing", { read: "purchasing_view" }),+ supplierAccount: company("purchasing", { read: "purchasing_view" }),+ supplierBankAccount: company("accounting", { read: "accounting_view" }),+ supplierContact: policies({+ select: viaParent("supplierId", "supplier", "purchasing_view"),+ insert: viaParent("supplierId", "supplier", "purchasing_create"),+ update: viaParent("supplierId", "supplier", "purchasing_update"),+ delete: viaParent("supplierId", "supplier", "purchasing_delete")+ }),+ supplierInteraction: company("purchasing", { read: "purchasing_view" }),+ supplierLedger: company("accounting", {+ read: "accounting_view",+ create: false,+ update: false,+ delete: false+ }),+ supplierLocation: policies({+ select: viaParent("supplierId", "supplier", "purchasing_view"),+ insert: viaParent("supplierId", "supplier", "purchasing_create"),+ update: viaParent("supplierId", "supplier", "purchasing_update"),+ delete: viaParent("supplierId", "supplier", "purchasing_delete")+ }),+ supplierPart: company("parts", {+ read: anyOf("parts_view", "purchasing_view")+ }),+ supplierPartPrice: company("parts", {+ read: anyOf("parts_view", "purchasing_view")+ }),+ supplierPayment: company("purchasing", {+ read: "purchasing_view",+ create: false,+ delete: false+ }),+ supplierProcess: company("resources", {+ read: anyOf("purchasing_view", "resources_view", "sales_view"),+ create: anyOf("purchasing_update", "resources_update"),+ delete: anyOf("purchasing_delete", "resources_delete")+ }),+ supplierQuote: company("purchasing", { read: "purchasing_view" }),+ supplierQuoteFavorite: policies({+ select: owner("userId"),+ insert: owner("userId"),+ delete: owner("userId")+ }),+ supplierQuoteLine: company("purchasing", { read: "purchasing_view" }),+ supplierQuoteLinePrice: policies({+ select: viaParent("supplierQuoteId", "supplierQuote", "purchasing_view"),+ insert: viaParent("supplierQuoteId", "supplierQuote", "purchasing_create"),+ update: viaParent("supplierQuoteId", "supplierQuote", "purchasing_update"),+ delete: viaParent("supplierQuoteId", "supplierQuote", "purchasing_delete")+ }),+ supplierShipping: company("purchasing", {+ read: "purchasing_view",+ create: false,+ delete: false+ }),+ supplierTax: company("purchasing", {+ read: "purchasing_view",+ create: false,+ delete: false+ }),+ supplierType: company("purchasing", { read: "member" }),+ supplyActual: policies({+ select: or(+ inCompany("companyId", "parts_view"),+ inCompany("companyId", "inventory_view")+ ),+ insert: inCompany("companyId", "inventory_create"),+ update: inCompany("companyId", "inventory_update"),+ delete: inCompany("companyId", "inventory_delete")+ }),+ supplyForecast: company("inventory", {+ read: "inventory_view"+ }),+ tableView: policies({+ select: or(+ owner("createdBy"),+ and(+ where<"tableView">((eb) => eb("type", "=", "Public")),+ inCompany("companyId", "member")+ )+ ),+ insert: and(owner("createdBy"), inCompany("companyId", "member")),+ update: {+ using: owner("createdBy"),+ check: and(owner("createdBy"), inCompany("companyId", "member"))+ },+ delete: owner("createdBy")+ }),+ tag: company("settings", {+ create: "employee",+ update: false,+ delete: "settings_update"+ }),+ terms: company("settings", {+ read: anyOf("purchasing_view", "sales_view", "settings_view"),+ create: false,+ delete: false,+ column: "id"+ }),+ timeCardEntry: policies({+ select: or(+ and(owner("employeeId"), inCompany("companyId", "employee")),+ inCompany("companyId", "people_view")+ ),+ insert: or(+ and(owner("employeeId"), inCompany("companyId", "employee")),+ inCompany("companyId", "people_create")+ ),+ update: or(+ and(owner("employeeId"), inCompany("companyId", "employee")),+ inCompany("companyId", "people_update")+ ),+ delete: inCompany("companyId", "people_delete")+ }),+ tool: company("parts"),+ trackedActivity: company("inventory", { create: "employee" }),+ trackedActivityInput: company("inventory", { create: "employee" }),+ trackedActivityOutput: company("inventory", { create: "employee" }),+ trackedEntity: company("inventory", { create: "employee" }),+ training: company("resources"),+ trainingAssignment: company("people", { read: "people_view" }),+ trainingCompletion: policies({+ select: inCompany("companyId", "resources_view"),+ insert: or(+ inCompany("companyId", "people_create"),+ and(owner("employeeId"), inCompany("companyId", "employee"))+ ),+ update: inCompany("companyId", "resources_update"),+ delete: inCompany("companyId", "resources_delete")+ }),+ trainingQuestion: company("people"),+ unitOfMeasure: company("parts", { read: "member" }),+ user: custom(+ "bespoke: five overlapping policies — self, shared company membership, employee/customer/supplier accounts, users_update, and an API-key EXISTS on userToCompany",+ (t) => `+ CREATE POLICY "Employees can view users with an account in their company" ON ${t} AS PERMISSIVE FOR SELECT TO public USING (((id IN ( SELECT employee.id+ FROM employee+ WHERE (employee."companyId" = ANY (( SELECT get_companies_with_employee_role() AS get_companies_with_employee_role)::text[])))) OR (id IN ( SELECT "customerAccount".id+ FROM "customerAccount"+ WHERE ("customerAccount"."companyId" = ANY (( SELECT get_companies_with_employee_role() AS get_companies_with_employee_role)::text[])))) OR (id IN ( SELECT "supplierAccount".id+ FROM "supplierAccount"+ WHERE ("supplierAccount"."companyId" = ANY (( SELECT get_companies_with_employee_role() AS get_companies_with_employee_role)::text[]))))));+ CREATE POLICY "Employees with users_update can update users in their company" ON ${t} AS PERMISSIVE FOR UPDATE TO public USING ((id IN ( SELECT "userToCompany"."userId"+ FROM "userToCompany"+ WHERE ("userToCompany"."companyId" = ANY (( SELECT get_companies_with_employee_permission('users_update'::text) AS get_companies_with_employee_permission)::text[]))))) WITH CHECK ((id IN ( SELECT "userToCompany"."userId"+ FROM "userToCompany"+ WHERE ("userToCompany"."companyId" = ANY (( SELECT get_companies_with_employee_permission('users_update'::text) AS get_companies_with_employee_permission)::text[])))));+ CREATE POLICY "Requests with an API key can select users from their company" ON ${t} AS PERMISSIVE FOR SELECT TO public USING ((EXISTS ( SELECT 1+ FROM "userToCompany"+ WHERE (("userToCompany"."userId" = "user".id) AND ("userToCompany"."companyId" = get_company_id_from_api_key())))));+ CREATE POLICY "Users can modify themselves" ON ${t} AS PERMISSIVE FOR UPDATE TO public USING (((( SELECT auth.uid() AS uid))::text = id)) WITH CHECK (((( SELECT auth.uid() AS uid))::text = id));+ CREATE POLICY "Users can view other users from their same company" ON ${t} AS PERMISSIVE FOR SELECT TO public USING (((id = (( SELECT auth.uid() AS uid))::text) OR (id IN ( SELECT "userToCompany"."userId"+ FROM "userToCompany"+ WHERE ("userToCompany"."companyId" IN ( SELECT "userToCompany_1"."companyId"+ FROM "userToCompany" "userToCompany_1"+ WHERE ("userToCompany_1"."userId" = (( SELECT auth.uid() AS uid))::text)))))));+ `+ ),+ // Employees read the attributes they manage for themselves, so the self-service path of+ // userAttributeValue (which reads these rows under the caller's RLS) works without+ // resources_view; every other attribute still needs it.+ userAttribute: policies({+ select: or(+ through(+ "userAttributeCategoryId",+ "userAttributeCategory",+ "id",+ inCompany("companyId", "resources_view")+ ),+ and(+ where<"userAttribute">((eb) => eb("canSelfManage", "=", true)),+ through(+ "userAttributeCategoryId",+ "userAttributeCategory",+ "id",+ inCompany("companyId", "employee")+ )+ )+ ),+ insert: through(+ "userAttributeCategoryId",+ "userAttributeCategory",+ "id",+ inCompany("companyId", "resources_create")+ ),+ update: through(+ "userAttributeCategoryId",+ "userAttributeCategory",+ "id",+ inCompany("companyId", "resources_update")+ ),+ delete: through(+ "userAttributeCategoryId",+ "userAttributeCategory",+ "id",+ inCompany("companyId", "resources_delete")+ )+ }),+ // Any employee reads the categories (names only): userAttribute's self-service read goes+ // through them, and they cannot look back at userAttribute without a policy cycle.+ userAttributeCategory: policies({+ select: inCompany("companyId", "employee"),+ insert: inCompany("companyId", "resources_create"),+ update: inCompany("companyId", "resources_update"),+ delete: inCompany("companyId", "resources_delete")+ }),+ // A user reads, writes and clears their own values of self-managed attributes, in a+ // company they belong to; resources_update manages everyone's. (The imported "insert"+ // policy was FOR UPDATE with no USING, so the account page could not save a value without+ // resources_update.)+ userAttributeValue: policies({+ all: or(and(owner("userId"), ownAttribute), managedAttribute)+ }),+ userModulePreference: policies({ all: owner("userId") }),+ userPermission: policies({+ select: through("id", "userToCompany", "userId", member("companyId"))+ }),+ // Memberships are written only by the server (invites, SSO, onboarding) through the+ // service role. Through the API an admin could otherwise attach any user to their company+ // and then read that user's profile and permissions.+ userToCompany: company("users", { create: false, update: false }),+ warehouse: company("parts"),+ warehouseTransfer: company("inventory", { read: "inventory_view" }),+ warehouseTransferLine: company("inventory", { read: "inventory_view" }),+ webhook: company("settings", { read: "settings_view" }),+ webhookTable: policies({ select: authenticated }),+ workCenter: company("resources"),+ workCenterProcess: company("resources"),+ workCenterReplacementPart: company("resources", { read: "resources_view" }),+ workCenterShift: company("resources"),+ workflow: company("workflows", { read: "workflows_view" }),+ workflowRun: company("workflows", {+ read: "workflows_view",+ create: false,+ update: false,+ delete: false+ }),+ workflowStepRun: company("workflows", {+ read: "workflows_view",+ create: false,+ update: false,+ delete: false+ }),+ workflowTriggerEvent: company("workflows", {+ read: "workflows_view",+ create: "workflows_update",+ update: false,+ delete: "workflows_update"+ }),+ workflowVersion: company("workflows", { read: "workflows_view" })+} satisfies Manifest;diff --git a/packages/database/src/authz/migration.test.ts b/packages/database/src/authz/migration.test.tsnew file mode 100644index 0000000000..05d1858d87--- /dev/null+++ b/packages/database/src/authz/migration.test.ts@@ -0,0 +1,119 @@+import { mkdtempSync, readdirSync, readFileSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";+import { describe, expect, test } from "vitest";+import { loadHelpers } from "./helpers";+import { manifest } from "./manifest";+import {+ GENERATED_HEADER,+ MIGRATIONS_DIR,+ renderMigration,+ unshipped+} from "./migration";+import { company, type Manifest, serviceOnly } from "./rules";++// A migrations directory holding only the given generated files.+const migrations = (files: Record<string, string>) => {+ const dir = mkdtempSync(path.join(tmpdir(), "authz-migrations-"));+ for (const [name, sql] of Object.entries(files))+ writeFileSync(path.join(dir, name), sql);+ return dir;+};++describe("unshipped: production gets every rule and helper through a migration", () => {+ test("the repository ships everything the manifest and helpers say", async () => {+ expect(+ await unshipped(manifest, await loadHelpers()),+ "Production would not get these. Run: pnpm --filter @carbon/database authz migration <name>"+ ).toEqual({+ tables: [],+ helpers: [],+ problems: []+ });+ });++ test("an edited rule, a new table and an edited helper are unshipped", async () => {+ const helpers = await loadHelpers();+ const edited = helpers.map((h) =>+ h.name === "get_companies_with_employee_role"+ ? { ...h, sql: h.sql.replace("STABLE", "VOLATILE") }+ : h+ );+ const result = await unshipped(+ {+ ...manifest,+ note: company("parts"),+ brandNewTable: company("parts")+ } as Manifest,+ edited,+ migrations({})+ );+ expect(result.tables).toEqual(+ expect.arrayContaining(["note", "brandNewTable"])+ );+ expect(result.helpers).toContain("get_companies_with_employee_role");+ });++ test("a generated migration ships its tables and helpers", async () => {+ const helpers = (await loadHelpers()).map((h) =>+ h.name === "get_companies_with_employee_role"+ ? { ...h, sql: h.sql.replace("STABLE", "VOLATILE") }+ : h+ );+ const edited = {+ ...manifest,+ note: company("parts"),+ tableView: serviceOnly()+ } as Manifest;+ const sql = await renderMigration(+ edited,+ helpers.filter((h) => h.name === "get_companies_with_employee_role"),+ ["note", "tableView"]+ );+ // Every real generated migration (20260927172338 ships tableView as a company rule+ // first), then the edit: the later file must win.+ const generated = Object.fromEntries(+ readdirSync(MIGRATIONS_DIR)+ .filter((f) => f.endsWith(".sql"))+ .map(+ (f) =>+ [f, readFileSync(path.join(MIGRATIONS_DIR, f), "utf8")] as const+ )+ .filter(([, sql]) => sql.startsWith(GENERATED_HEADER))+ );+ const dir = migrations({ ...generated, "20270101000001_ship.sql": sql });+ const result = await unshipped(edited, helpers, dir);+ expect(result).toEqual({ tables: [], helpers: [], problems: [] });+ });++ test("the header cannot carry anything `authz migration` does not write", async () => {+ const note = await renderMigration(manifest, [], ["note"]);+ const dir = migrations({+ "20270101000001_spoof.sql": `${note}\nGRANT ALL ON public.note TO anon;\n`,+ "20270101000002_spoof.sql": `${GENERATED_HEADER}\n${note+ .split("\n")+ .slice(1)+ .join("\n")+ .replace(/USING \(/, "USING (true OR ")}`+ });+ const result = await unshipped(manifest, await loadHelpers(), dir);+ expect(result.problems.join("\n")).toContain("GRANT ALL");+ expect(result.tables).toContain("note");+ });++ test("a retired helper is accepted only in the migration that last shipped it", async () => {+ const securityFixes = "20260927172338_authz-security-fixes.sql";+ const dir = migrations({+ [securityFixes]: readFileSync(+ path.join(MIGRATIONS_DIR, securityFixes),+ "utf8"+ ),+ "20270101000001_revive.sql": `${GENERATED_HEADER}\nCREATE OR REPLACE FUNCTION public.has_company_permission(p text) RETURNS boolean LANGUAGE sql AS $$ SELECT true $$;\n`+ });+ const { problems } = await unshipped(manifest, await loadHelpers(), dir);+ expect(problems).toHaveLength(1);+ expect(problems[0]).toMatch(+ /^20270101000001_revive\.sql: .*has_company_permission/+ );+ });+});diff --git a/packages/database/src/authz/migration.ts b/packages/database/src/authz/migration.tsnew file mode 100644index 0000000000..b120d9cc21--- /dev/null+++ b/packages/database/src/authz/migration.ts@@ -0,0 +1,227 @@+import { createHash } from "node:crypto";+import { readdirSync, readFileSync } from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { parse } from "libpg-query";+import { type Helper, RETIRED_HELPERS } from "./helpers";+import { type AnyRule, type Manifest, render } from "./rules";+import { assertOnlyPolicies } from "./sync";++/**+ * Production does not run `authz sync` yet, so a manifest or helper change reaches it only+ * through a migration rendered by `authz migration`. `unshipped()` (pinned by+ * migration.test.ts, which runs in CI with no database) fails any rule or helper that+ * no generated migration ships:+ *+ * - a table or helper in a generated migration must equal what the manifest renders now,+ * as of the LATEST generated migration that names it;+ * - anything never shipped that way must hash to baseline.json — what production had when+ * the manifest took over (text may differ; the meaning was proven equal). The baseline is+ * written once and never regenerated: a change goes into a generated migration instead.+ *+ * A new table appears in neither, so it cannot reach production without its policies.+ */++const HERE = path.dirname(fileURLToPath(import.meta.url));+export const MIGRATIONS_DIR = path.resolve(HERE, "../../supabase/migrations");+const BASELINE = path.join(HERE, "baseline.json");++/**+ * The first line of every generated authz migration. `@carbon/checks`+ * (no-authz-ddl-in-migrations) exempts the files that start with it; `unshipped()` checks+ * their contents, so the header cannot be borrowed by a hand-written file.+ */+export const GENERATED_HEADER =+ "-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.";++const literal = (s: string) => `'${s.replaceAll("'", "''")}'`;+const ident = (s: string) => `"${s.replaceAll('"', '""')}"`;+export const hash = (sql: string) =>+ createHash("sha256").update(sql).digest("hex").slice(0, 16);++const dropAllPolicies = (table: string) =>+ [+ "DO $authz$",+ "DECLARE p record;",+ "BEGIN",+ ` FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = ${literal(table)} LOOP`,+ ` EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, ${literal(table)});`,+ " END LOOP;",+ "END",+ "$authz$;"+ ].join("\n");++/**+ * Chosen helpers and tables rendered from the manifest as one migration. Each table's+ * policies are dropped whatever their names (legacy names included) and recreated from its+ * rule, so the migration lands the manifest's exact rule; `authz sync` after it changes+ * nothing.+ */+export async function renderMigration(+ manifest: Manifest,+ helpers: Helper[],+ tables: string[]+): Promise<string> {+ const parts = [+ GENERATED_HEADER,+ "-- Ships these rules to databases where `authz sync` does not run after migrations yet."+ ];++ for (const helper of helpers) parts.push(helper.sql.trim());++ for (const table of tables) {+ const rule = (manifest as Record<string, AnyRule>)[table];+ if (!rule)+ throw new Error(`authz migration: no rule for "${table}" in manifest.ts`);+ const sql = render(rule, table);+ if (sql) await assertOnlyPolicies(sql, "public", table);+ parts.push(+ [+ `-- ${table}`,+ dropAllPolicies(table),+ `ALTER TABLE public.${ident(table)} ENABLE ROW LEVEL SECURITY;`,+ sql+ ]+ .filter(Boolean)+ .join("\n")+ );+ }++ return `${parts.join("\n\n")}\n`;+}++// biome-ignore lint/suspicious/noExplicitAny: libpg-query's AST is untyped JSON+type Ast = any;++/** Each statement's AST and its own text (comments before it and the `;` excluded). */+async function statements(sql: string): Promise<{ node: Ast; text: string }[]> {+ const tree: Ast = await parse(sql);+ const bytes = Buffer.from(sql);+ return (tree.stmts ?? []).map((s: Ast) => {+ const start = s.stmt_location ?? 0;+ const end = s.stmt_len ? start + s.stmt_len : bytes.length;+ const text = bytes+ .subarray(start, end)+ .toString()+ .replace(/^(\s*--[^\n]*\n)+/, "")+ .trim();+ return { node: s.stmt, text };+ });+}++type Shipped = {+ tables: Map<string, { file: string; policies: string[] }>;+ helpers: Map<string, { file: string; text: string }>;+ problems: string[];+};++/**+ * What the generated migrations ship, latest file winning. A generated file may contain+ * only managed helpers and, per table, the drop-all block, ENABLE ROW LEVEL SECURITY and+ * policies on that table — anything else is reported.+ */+async function readShipped(dir: string, managed: Set<string>) {+ const shipped: Shipped = {+ tables: new Map(),+ helpers: new Map(),+ problems: []+ };+ const files = readdirSync(dir)+ .filter((f) => f.endsWith(".sql"))+ .sort();+ for (const file of files) {+ const sql = readFileSync(path.join(dir, file), "utf8");+ if (!sql.startsWith(GENERATED_HEADER)) continue;+ let table: string | undefined;+ for (const { node, text } of await statements(sql)) {+ const fn = node.CreateFunctionStmt;+ const alter = node.AlterTableStmt;+ const policy = node.CreatePolicyStmt?.table;+ if (fn) {+ const [schema, name] = fn.funcname.map((n: Ast) => n.String?.sval);+ if (schema === "public" && managed.has(name)) {+ shipped.helpers.set(name, { file, text });+ continue;+ }+ if (schema === "public" && RETIRED_HELPERS[name] === file) continue;+ } else if (node.DoStmt) {+ table = /tablename = '((?:[^']|'')+)'/+ .exec(text)?.[1]+ ?.replaceAll("''", "'");+ if (+ table &&+ text === (await statements(dropAllPolicies(table)))[0]?.text+ )+ continue;+ } else if (alter) {+ const cmds = alter.cmds ?? [];+ if (+ table &&+ alter.relation?.schemaname === "public" &&+ alter.relation?.relname === table &&+ cmds.length === 1 &&+ cmds[0].AlterTableCmd?.subtype === "AT_EnableRowSecurity"+ ) {+ shipped.tables.set(table, { file, policies: [] });+ continue;+ }+ } else if (+ table &&+ policy?.schemaname === "public" &&+ policy?.relname === table &&+ shipped.tables.get(table)?.file === file+ ) {+ shipped.tables.get(table)?.policies.push(text);+ continue;+ }+ shipped.problems.push(+ `${file}: not something \`authz migration\` writes: ${text.slice(0, 80)}`+ );+ }+ }+ return shipped;+}++export type Unshipped = {+ tables: string[];+ helpers: string[];+ problems: string[];+};++/** Every rule and helper production does not have yet, and any tampered generated file. */+export async function unshipped(+ manifest: Manifest,+ helpers: Helper[],+ dir = MIGRATIONS_DIR+): Promise<Unshipped> {+ const baseline: {+ tables: Record<string, string>;+ helpers: Record<string, string>;+ } = JSON.parse(readFileSync(BASELINE, "utf8"));+ const shipped = await readShipped(dir, new Set(helpers.map((h) => h.name)));+ const result: Unshipped = {+ tables: [],+ helpers: [],+ problems: shipped.problems+ };++ for (const [table, rule] of Object.entries(manifest) as [string, AnyRule][]) {+ const sql = render(rule, table);+ const got = shipped.tables.get(table);+ const same = got+ ? JSON.stringify(got.policies) ===+ JSON.stringify(sql ? (await statements(sql)).map((s) => s.text) : [])+ : baseline.tables[table] === hash(sql);+ if (!same) result.tables.push(table);+ }++ for (const helper of helpers) {+ const got = shipped.helpers.get(helper.name);+ const same = got+ ? got.text === (await statements(helper.sql))[0]?.text+ : baseline.helpers[helper.name] === hash(helper.sql);+ if (!same) result.helpers.push(helper.name);+ }++ return result;+}diff --git a/packages/database/src/authz/rules.test.ts b/packages/database/src/authz/rules.test.tsnew file mode 100644index 0000000000..f61b80160a--- /dev/null+++ b/packages/database/src/authz/rules.test.ts@@ -0,0 +1,157 @@+import { describe, expect, test } from "vitest";+import {+ company,+ custom,+ group,+ type Manifest,+ parent,+ render,+ serviceOnly+} from "./rules";++describe("render", () => {+ test("company: the canonical four", () => {+ expect(render(company("parts"), "item")).toBe(+ [+ `CREATE POLICY "SELECT" ON "public"."item" FOR SELECT USING ("companyId" = ANY ((SELECT get_companies_with_employee_role())::text[]));`,+ `CREATE POLICY "INSERT" ON "public"."item" FOR INSERT WITH CHECK ("companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_create'))::text[]));`,+ `CREATE POLICY "UPDATE" ON "public"."item" FOR UPDATE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_update'))::text[]));`,+ `CREATE POLICY "DELETE" ON "public"."item" FOR DELETE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_delete'))::text[]));`+ ].join("\n")+ );+ });++ test("company: an update row predicate keeps the new row in the company", () => {+ const sql = render(+ company<"journal">("accounting", {+ where: { update: (eb) => eb("status", "=", "Draft") }+ }),+ "journal"+ );+ expect(sql).toContain(+ `FOR UPDATE USING (("status" = 'Draft' AND "companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_update'))::text[]))) WITH CHECK ("companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_update'))::text[]));`+ );+ });++ test("company: a read permission replaces the employee read", () => {+ expect(+ render(company("inventory", { read: "inventory_view" }), "pickingList")+ ).toContain(+ `FOR SELECT USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('inventory_view'))::text[]));`+ );+ });++ test("group: scoped by companyGroupId through the group helpers", () => {+ const sql = render(group("accounting"), "dimension");+ expect(sql).toContain(+ `FOR SELECT USING ("companyGroupId" = ANY ((SELECT get_company_groups_for_employee())::text[]));`+ );+ expect(sql).toContain(+ `FOR DELETE USING ("companyGroupId" = ANY ((SELECT get_company_groups_for_root_permission('accounting_delete'))::text[]));`+ );+ });++ test("parent: reached through the FK, writes gated on the write permission", () => {+ const sql = render(+ parent("pickingListLine", "pickingListLineId", "inventory", {+ read: "inventory_view"+ }),+ "pickingListLineTrackedEntity"+ );+ expect(sql).toContain(+ `CREATE POLICY "INSERT" ON "public"."pickingListLineTrackedEntity" FOR INSERT WITH CHECK (EXISTS (SELECT 1 FROM "public"."pickingListLine" p WHERE "p"."id" = "pickingListLineTrackedEntity"."pickingListLineId" AND "p"."companyId" = ANY ((SELECT get_companies_with_employee_permission('inventory_create'))::text[])));`+ );+ expect(sql).toContain(+ `get_companies_with_employee_permission('inventory_view')`+ );+ });++ test("serviceOnly renders no policies", () => {+ expect(render(serviceOnly(), "apiKey")).toBe("");+ });++ test("custom renders against the target it is given", () => {+ const rule = custom(+ "reads its own rows only",+ (t) =>+ `CREATE POLICY "SELECT" ON ${t} FOR SELECT USING ("userId" = (SELECT auth.uid())::text);`+ );+ expect(render(rule, "userToCompany", "scratch")).toBe(+ `CREATE POLICY "SELECT" ON "scratch"."userToCompany" FOR SELECT USING ("userId" = (SELECT auth.uid())::text);`+ );+ });++ test("the schema parameter only moves the target, never the parent", () => {+ const sql = render(+ parent("item", "itemId", "parts"),+ "itemCost",+ "scratch"+ );+ expect(sql).toContain(`ON "scratch"."itemCost"`);+ expect(sql).toContain(`FROM "public"."item" p`);+ expect(sql).not.toContain(`"public"."itemCost"`);+ });++ test("identifiers are quoted", () => {+ expect(render(company("parts"), 'we"ird')).toContain(+ `ON "public"."we""ird"`+ );+ });++ test("predicate values are inlined as literals, never bind parameters", () => {+ const sql = render(+ company<"journal">("accounting", {+ where: {+ update: (eb) => eb("status", "in", ["Draft", "O'Brien"] as never)+ }+ }),+ "journal"+ );+ expect(sql).toContain(`"status" in ('Draft', 'O''Brien')`);+ expect(sql).not.toMatch(/\$\d/);+ });++ test("deterministic", () => {+ const rule = company<"journal">("accounting", {+ read: "accounting_view",+ where: {+ update: (eb) => eb("status", "in", ["Draft", "Posted"]),+ delete: (eb) => eb("status", "=", "Draft")+ }+ });+ expect(render(rule, "journal")).toBe(render(rule, "journal"));+ });+});++// Type-level: these must not compile.+// @ts-expect-error not a module+company("partz");+// @ts-expect-error not a permission+company("parts", { read: "parts_edit" });+// @ts-expect-error not a table+parent("itm", "itemId", "parts");+// Typed from the manifest key alone — no table named twice.+const typed: Manifest = {+ itemCost: parent("item", "itemId", "parts"),+ journal: company("accounting", {+ where: { update: (eb) => eb("status", "in", ["Draft", "Posted"]) }+ })+};+const untyped: Manifest = {+ // @ts-expect-error not a column of itemCost+ itemCost: parent("item", "itmId", "parts"),+ journal: company("accounting", {+ // @ts-expect-error not a column of journal+ where: { update: (eb) => eb("staus", "=", "Draft") }+ })+};+void typed;+void untyped;+company<"journal">("accounting", {+ // @ts-expect-error not a column of journal+ where: { update: (eb) => eb("staus", "=", "Draft") }+});+company<"journal">("accounting", {+ // @ts-expect-error not a journalEntryStatus value+ where: { update: (eb) => eb("status", "=", "Drafted") }+});diff --git a/packages/database/src/authz/rules.ts b/packages/database/src/authz/rules.tsnew file mode 100644index 0000000000..d983c961c2--- /dev/null+++ b/packages/database/src/authz/rules.ts@@ -0,0 +1,404 @@+import {+ DummyDriver,+ type Expression,+ type ExpressionBuilder,+ expressionBuilder,+ Kysely,+ PostgresAdapter,+ PostgresIntrospector,+ PostgresQueryCompiler,+ type RawBuilder,+ type SqlBool,+ sql+} from "kysely";+import type { KyselyDatabase } from "../client";+import type { Database } from "../types";++type Public = Database["public"];++export type Table = keyof Public["Tables"] & keyof KyselyDatabase;+type Column<T extends Table> = keyof Public["Tables"][T]["Row"] & string;+export type Module = Lowercase<Public["Enums"]["module"]>;+export type Permission = `${Module}_${"view" | "create" | "update" | "delete"}`;++// ─── Who: the companies a caller belongs to ──────────────────────────────────++/**+ * - `"employee"`: get_companies_with_employee_role() — any employee of the company, and+ * any API key of it regardless of the key's scopes.+ * - `"member"`: get_companies_with_any_role() — employees, customers and suppliers.+ * - a Permission: get_companies_with_employee_permission() — scope-checked for API keys.+ * - `anyOf(...)`: holds at least one of the permissions.+ */+export type Who = "employee" | "member" | Permission | { anyOf: Permission[] };++export const anyOf = (...permissions: Permission[]): Who => ({+ anyOf: permissions+});++// ─── Predicates ──────────────────────────────────────────────────────────────++/** A policy expression, compiled against the table it guards. */+export type Pred = { readonly sql: (table: string) => RawBuilder<unknown> };++const pred = (build: (table: string) => RawBuilder<unknown>): Pred => ({+ sql: build+});++const isPred = (value: unknown): value is Pred =>+ typeof value === "object" && value !== null && "sql" in value;++const companySet = (who: Exclude<Who, { anyOf: Permission[] }>) => {+ if (who === "employee") return sql`get_companies_with_employee_role()`;+ if (who === "member") return sql`get_companies_with_any_role()`;+ return sql`get_companies_with_employee_permission(${sql.lit(who)})`;+};++/** `subject` is one of the caller's companies (or, for anyOf, satisfies any of them). */+const belongsTo = (+ subject: RawBuilder<unknown>,+ who: Who+): RawBuilder<unknown> =>+ typeof who === "object" && "anyOf" in who+ ? sql`(${sql.join(+ who.anyOf.map((p) => belongsTo(subject, p)),+ sql` OR `+ )})`+ : sql`${subject} = ANY ((SELECT ${companySet(who)})::text[])`;++/** The row's own company column is one of the caller's companies. */+export const inCompany = (column: string, who: Who): Pred =>+ pred(() => belongsTo(sql.ref(column), who));++/** The row's company group is one the caller belongs to (group-shared tables). */+export const inGroup = (column: string, who: "employee" | Permission): Pred =>+ pred(+ () =>+ sql`${sql.ref(column)} = ANY ((SELECT ${+ who === "employee"+ ? sql`get_company_groups_for_employee()`+ : sql`get_company_groups_for_root_permission(${sql.lit(who)})`+ })::text[])`+ );++/** The company of the parent row `fk` points at, resolved by get_company_id_from_foreign_key. */+export const viaParent = (fk: string, parentTable: Table, who: Who): Pred =>+ pred(() =>+ belongsTo(+ sql`get_company_id_from_foreign_key(${sql.ref(fk)}, ${sql.lit(parentTable)})`,+ who+ )+ );++/**+ * The parent row `fk` points at exists and satisfies `condition`: a Who (the parent's+ * company is one of the caller's) or any predicate, whose bare columns are the parent's.+ * `sameCompany` also requires the parent to be in the row's own company.+ */+export const exists = (+ parentTable: Table,+ fk: string,+ condition: Who | Pred,+ { sameCompany = false }: { sameCompany?: boolean } = {}+): Pred =>+ pred((table) => {+ const parts = [sql`${sql.ref("p.id")} = ${sql.ref(`${table}.${fk}`)}`];+ if (sameCompany) {+ parts.push(+ sql`${sql.ref("p.companyId")} = ${sql.ref(`${table}.companyId`)}`+ );+ }+ parts.push(+ isPred(condition)+ ? condition.sql(parentTable)+ : belongsTo(sql.ref("p.companyId"), condition)+ );+ return sql`EXISTS (SELECT 1 FROM ${sql.id("public", parentTable)} p WHERE ${sql.join(parts, sql` AND `)})`;+ });++/**+ * `local` is reachable through a link table: it is one of `linkTable.linkColumn` over the+ * link rows satisfying `condition`, whose bare columns are the link table's.+ */+export const through = (+ local: string,+ linkTable: Table,+ linkColumn: string,+ condition: Pred+): Pred =>+ pred(+ () =>+ sql`${sql.ref(local)} IN (SELECT ${sql.ref(`${linkTable}.${linkColumn}`)} FROM ${sql.id("public", linkTable)} WHERE ${condition.sql(linkTable)})`+ );++/**+ * The caller has any membership in the company `column` names (userToCompany). Unlike+ * the `"member"` Who, an API key never passes: it has no auth.uid().+ */+export const member = (column: string): Pred =>+ through(column, "userToCompany", "companyId", owner("userId"));++/** The row belongs to the calling user. */+export const owner = (column: string): Pred =>+ pred(() => sql`${sql.ref(column)} = ((SELECT auth.uid()))::text`);++/** The row belongs to a customer or supplier the portal user acts for. */+export const portal = {+ customer: (column: string, permission: Permission): Pred =>+ pred(+ () =>+ sql`${sql.ref(column)} = ANY ((SELECT get_customer_ids_with_customer_permission(${sql.lit(permission)}))::text[])`+ ),+ supplier: (column: string, permission: Permission): Pred =>+ pred(+ () =>+ sql`${sql.ref(column)} = ANY ((SELECT get_supplier_ids_with_supplier_permission(${sql.lit(permission)}))::text[])`+ )+};++/** Any signed-in user (reference data readable by everyone). */+export const authenticated: Pred = pred(+ () => sql`(SELECT auth.role()) = 'authenticated'`+);++export const always: Pred = pred(() => sql`true`);++export const isNull = (column: string): Pred =>+ pred(() => sql`${sql.ref(column)} IS NULL`);++export const isNotNull = (column: string): Pred =>+ pred(() => sql`${sql.ref(column)} IS NOT NULL`);++const combine = (operator: RawBuilder<unknown>, preds: Pred[]): Pred =>+ preds.length === 1 && preds[0]+ ? preds[0]+ : pred(+ (table) =>+ sql`(${sql.join(+ preds.map((p) => p.sql(table)),+ operator+ )})`+ );++export const or = (...preds: Pred[]): Pred => combine(sql` OR `, preds);+export const and = (...preds: Pred[]): Pred => combine(sql` AND `, preds);++/** A row predicate on table T, typed against the generated schema. */+export type Predicate<T extends Table> = (+ eb: ExpressionBuilder<KyselyDatabase, T>+) => Expression<SqlBool>;++const eb = expressionBuilder<KyselyDatabase, Table>();++/** Any other condition, written with Kysely against table T's real columns. */+export const where = <T extends Table>(predicate: Predicate<T>): Pred =>+ pred(() => sql`${(predicate as Predicate<Table>)(eb)}`);++// ─── Rules ───────────────────────────────────────────────────────────────────++/** One predicate per command. A missing command has no policy, so it is denied. */+export type Commands = {+ select?: Pred;+ insert?: Pred;+ update?: Pred | { using: Pred; check: Pred };+ delete?: Pred;+};++export type Rule<T extends Table = Table> =+ | ({+ kind: "policies";+ /** Policies apply to this role only (default: every role). */+ to?: "authenticated";+ /** Set by `parent()`, so the manifest entry checks it is a column of T. */+ fk?: Column<T>;+ /** Never set. Carries T so a manifest entry types its builder's callbacks. */+ readonly __table?: T;+ } & Commands)+ | { kind: "serviceOnly" }+ | { kind: "custom"; reason: string; sql: (target: string) => string };++// biome-ignore lint/suspicious/noExplicitAny: a rule for some table, read generically+export type AnyRule = Rule<any>;++/** Every public table's rule. Each entry's type is bound to its own table. */+export type Manifest = { [T in Table]?: Rule<T> };++/** Any shape: one predicate per command, or `all` for every command at once. */+export const policies = <T extends Table>({+ all,+ to,+ ...commands+}: Commands & { all?: Pred; to?: "authenticated" }): Rule<T> => ({+ kind: "policies",+ to,+ select: commands.select ?? all,+ insert: commands.insert ?? all,+ update: commands.update ?? all,+ delete: commands.delete ?? all+});++/** Who may do one action: a set of companies, any predicate, or `false` for denied. */+export type Actor = Who | Pred | false;++type Actors = { read: Actor; create: Actor; update: Actor; delete: Actor };++/** Extra row predicates, ANDed into the write policy's USING clause. */+export type Where<T extends Table> = Partial<+ Record<"insert" | "update" | "delete", Predicate<T>>+>;++const actors = (module: Module, overrides: Partial<Actors>): Actors => ({+ read: "employee",+ create: `${module}_create`,+ update: `${module}_update`,+ delete: `${module}_delete`,+ ...overrides+});++/**+ * Rows owned by a company: any employee reads, each write needs `<module>_<action>`.+ * Override any action with a Who, a predicate, or `false`.+ */+export const company = <T extends Table>(+ module: Module,+ {+ where: extra = {},+ column = "companyId",+ ...overrides+ }: Partial<Actors> & { where?: Where<T>; column?: string } = {}+): Rule<T> => {+ const all = actors(module, overrides);+ const scope = (actor: Actor) =>+ actor === false+ ? undefined+ : isPred(actor)+ ? actor+ : inCompany(column, actor);+ const guarded = (actor: Actor, predicate?: Predicate<T>) => {+ const s = scope(actor);+ return s && predicate ? and(where(predicate), s) : s;+ };+ const update = scope(all.update);+ return {+ kind: "policies",+ select: scope(all.read),+ insert: guarded(all.create, extra.insert),+ // Without a row predicate Postgres checks the new row against USING, which is+ // already the company scope. With one, the new row is checked against the scope+ // alone: it can never move company, and a status transition still passes.+ update:+ update && extra.update+ ? { using: and(where(extra.update), update), check: update }+ : update,+ delete: guarded(all.delete, extra.delete)+ };+};++/** Rows shared by a company group (chart of accounts, currencies, dimensions). */+export const group = <T extends Table>(+ module: Module,+ overrides: Partial<Record<keyof Actors, "employee" | Permission | false>> = {}+): Rule<T> => {+ const all = actors(module, overrides) as Record<+ keyof Actors,+ "employee" | Permission | false+ >;+ const scope = (who: "employee" | Permission | false) =>+ who === false ? undefined : inGroup("companyGroupId", who);+ return {+ kind: "policies",+ select: scope(all.read),+ insert: scope(all.create),+ update: scope(all.update),+ delete: scope(all.delete)+ };+};++// The FK stays a literal type so assigning the rule to its table's manifest entry is+// what checks it: a column that table lacks does not compile, with no table repeated.+export const parent = <const F extends string>(+ table: Table,+ fk: F,+ module: Module,+ options: { read?: Who } = {}+): Extract<AnyRule, { kind: "policies" }> & { fk: F } => ({+ kind: "policies",+ fk,+ select: exists(table, fk, options.read ?? "employee"),+ insert: exists(table, fk, `${module}_create`),+ update: exists(table, fk, `${module}_update`),+ delete: exists(table, fk, `${module}_delete`)+});++export const serviceOnly = <T extends Table>(): Rule<T> => ({+ kind: "serviceOnly"+});++/** `sql` receives the qualified table to target, so it can be rendered anywhere. */+export const custom = <T extends Table>(+ reason: string,+ sql: (target: string) => string+): Rule<T> => ({ kind: "custom", reason, sql });++// ─── Rendering ───────────────────────────────────────────────────────────────++/** Policies cannot take bind parameters, so every value is written inline as a literal. */+class InlineValueCompiler extends PostgresQueryCompiler {+ protected override appendValue(value: unknown): void {+ this.appendImmediateValue(value);+ }+}++// Compiles SQL only; it never connects.+const compiler = new Kysely<KyselyDatabase>({+ dialect: {+ createAdapter: () => new PostgresAdapter(),+ createDriver: () => new DummyDriver(),+ createIntrospector: (db) => new PostgresIntrospector(db),+ createQueryCompiler: () => new InlineValueCompiler()+ }+});++const toSql = (node: RawBuilder<unknown>) => node.compile(compiler).sql;++/**+ * The policies for one table, as SQL. `schema` is where to create them: "public"+ * to apply, a scratch schema to let Postgres normalize them for comparison.+ */+export function render(+ rule: AnyRule,+ table: string,+ schema = "public"+): string {+ const target = sql.id(schema, table);+ switch (rule.kind) {+ case "serviceOnly":+ return "";++ case "custom":+ return rule.sql(toSql(sql`${target}`));++ case "policies": {+ const to = rule.to ? sql` TO ${sql.raw(rule.to)}` : sql``;+ const policy = (command: string, clause: RawBuilder<unknown>) =>+ `${toSql(sql`CREATE POLICY ${sql.id(command)} ON ${target} FOR ${sql.raw(command)}${to} ${clause}`)};`;+ const using = (p: Pred) => sql`USING (${p.sql(table)})`;+ const check = (p: Pred) => sql`WITH CHECK (${p.sql(table)})`;+ const { select, insert, update, delete: remove } = rule;+ return [+ select && policy("SELECT", using(select)),+ insert && policy("INSERT", check(insert)),+ update &&+ policy(+ "UPDATE",+ isPred(update)+ ? using(update)+ : sql`${using(update.using)} ${check(update.check)}`+ ),+ remove && policy("DELETE", using(remove))+ ]+ .filter(Boolean)+ .join("\n");+ }+ }+}diff --git a/packages/database/src/authz/sync.test.ts b/packages/database/src/authz/sync.test.tsnew file mode 100644index 0000000000..c330cfae4a--- /dev/null+++ b/packages/database/src/authz/sync.test.ts@@ -0,0 +1,97 @@+import { Client } from "pg";+import { afterAll, beforeAll, describe, expect, test } from "vitest";+import { company, custom, group, type Manifest } from "./rules";+import { assertOnlyPolicies, syncAuthz } from "./sync";++// Runs against the local database: SUPABASE_DB_URL=… pnpm vitest run src/authz+const url = process.env.SUPABASE_DB_URL;++describe.skipIf(!url)("syncAuthz against a migrated database", () => {+ const db = new Client({ connectionString: url });+ const scratch = `authz_sync_test_${process.pid}`;++ beforeAll(async () => {+ await db.connect();+ await db.query(+ `CREATE TABLE public.${scratch} ("id" TEXT PRIMARY KEY, "companyId" TEXT NOT NULL)`+ );+ });++ afterAll(async () => {+ await db.query(`DROP TABLE IF EXISTS public.${scratch}`);+ await db.end();+ });++ test("canonical tables already match their rule exactly", async () => {+ const manifest: Manifest = {+ documentTemplate: company("settings"),+ dimension: group("accounting")+ };+ const { changed } = await syncAuthz(db, manifest, { dryRun: true });+ expect(changed).toEqual([]);+ });++ test("applies, is idempotent, and heals a hand-added policy", async () => {+ const manifest = { [scratch]: company("parts") } as Manifest;++ expect((await syncAuthz(db, manifest)).changed).toEqual([scratch]);+ expect((await syncAuthz(db, manifest)).changed).toEqual([]);++ await db.query(+ `CREATE POLICY "backdoor" ON public.${scratch} FOR SELECT USING (true)`+ );+ expect((await syncAuthz(db, manifest)).changed).toEqual([scratch]);++ const { rows } = await db.query(+ `SELECT policyname FROM pg_policies WHERE tablename = $1 ORDER BY 1`,+ [scratch]+ );+ expect(rows.map((r) => r.policyname)).toEqual([+ "DELETE",+ "INSERT",+ "SELECT",+ "UPDATE"+ ]);+ });+});++describe("assertOnlyPolicies: rendered SQL can only create policies on its own table", () => {+ const policy = (t: string) =>+ `CREATE POLICY "SELECT" ON ${t} FOR SELECT USING (true);`;++ test("accepts policies on the target", async () => {+ await expect(+ assertOnlyPolicies(policy(`"public"."note"`), "public", "note")+ ).resolves.toBeUndefined();+ });++ test("rejects a smuggled statement", async () => {+ await expect(+ assertOnlyPolicies(+ `${policy(`"public"."note"`)} DROP TABLE item;`,+ "public",+ "note"+ )+ ).rejects.toThrow();+ });++ test("rejects a policy on another table", async () => {+ await expect(+ assertOnlyPolicies(policy(`"public"."item"`), "public", "note")+ ).rejects.toThrow();+ });++ test("a custom rule that tries it fails the whole sync, changing nothing", async () => {+ const evil = custom(+ "test",+ (t) => `${policy(t)} ALTER TABLE item DISABLE ROW LEVEL SECURITY;`+ );+ await expect(+ assertOnlyPolicies(+ evil.kind === "custom" ? evil.sql(`"public"."note"`) : "",+ "public",+ "note"+ )+ ).rejects.toThrow();+ });+});diff --git a/packages/database/src/authz/sync.ts b/packages/database/src/authz/sync.tsnew file mode 100644index 0000000000..50a0486a8c--- /dev/null+++ b/packages/database/src/authz/sync.ts@@ -0,0 +1,214 @@+import { parse } from "libpg-query";+import type { Client } from "pg";+import { type Helper, loadHelpers, syncHelpers } from "./helpers";+import { type AnyRule, type Manifest, render } from "./rules";++export type Policy = {+ policyname: string;+ permissive: string;+ roles: string;+ cmd: string;+ qual: string | null;+ with_check: string | null;+};++/**+ * Per-company tables created at runtime (`searchIndex_<companyId>`, `auditLog_<companyId>`).+ * The function that creates each one also creates its policies; sync leaves them alone.+ */+export const DYNAMIC_TABLE_PREFIXES = ["searchIndex_", "auditLog_"];++// Never committed: it only exists inside a savepoint that is always rolled back.+const SCRATCH = "authz_scratch";+const SYNC_LOCK = "carbon.authz.sync";++const rulesOf = (manifest: Manifest) =>+ Object.entries(manifest) as [string, AnyRule][];++const ident = (name: string) => `"${name.replaceAll('"', '""')}"`;++export const readPolicies = async (db: Client, schema: string, table: string) =>+ (+ await db.query<Policy>(+ `SELECT policyname, permissive, roles::text AS roles, cmd, qual, with_check+ FROM pg_policies+ WHERE schemaname = $1 AND tablename = $2+ ORDER BY policyname`,+ [schema, table]+ )+ ).rows;++const rlsEnabled = async (db: Client, table: string) =>+ (+ await db.query<{ enabled: boolean }>(+ `SELECT relrowsecurity AS enabled FROM pg_class+ WHERE oid = to_regclass(format('public.%I', $1::text))`,+ [table]+ )+ ).rows[0]?.enabled ?? false;++/**+ * Rendered policy SQL may only create policies on the table it is rendered for. Checked+ * with Postgres's own parser before anything runs, so a `custom` entry (or a rendering+ * bug) cannot drop a table, grant a role, or touch another table's policies.+ */+export async function assertOnlyPolicies(+ sql: string,+ schema: string,+ table: string+): Promise<void> {+ // biome-ignore lint/suspicious/noExplicitAny: libpg-query's AST is untyped JSON+ const tree: any = await parse(sql);+ for (const { stmt } of tree.stmts ?? []) {+ const target = stmt?.CreatePolicyStmt?.table;+ if (target?.schemaname !== schema || target?.relname !== table) {+ throw new Error(+ `authz: the rule for "${table}" may only CREATE POLICY on ${schema}.${table}`+ );+ }+ }+}++/**+ * The policies each rule produces, as Postgres stores and prints them: rendered into a+ * scratch copy of every table inside a savepoint that is always rolled back. Must run+ * inside a transaction whose search_path is `public`, so both sides print identically.+ */+export async function desiredPolicies(db: Client, manifest: Manifest) {+ // An Error when the rule cannot apply to the table (e.g. `company` on a table with no+ // companyId): a savepoint per table keeps one bad rule from hiding the rest.+ const desired = new Map<string, Policy[] | Error>();+ await db.query("SAVEPOINT authz_scratch");+ try {+ await db.query(`CREATE SCHEMA ${ident(SCRATCH)}`);+ for (const [table, rule] of rulesOf(manifest)) {+ await db.query("SAVEPOINT authz_rule");+ try {+ await db.query(+ `CREATE TABLE ${ident(SCRATCH)}.${ident(table)} (LIKE public.${ident(table)})`+ );+ const sql = render(rule, table, SCRATCH);+ if (sql) {+ await assertOnlyPolicies(sql, SCRATCH, table);+ await db.query(sql);+ }+ desired.set(table, await readPolicies(db, SCRATCH, table));+ await db.query("RELEASE SAVEPOINT authz_rule");+ } catch (error) {+ await db.query("ROLLBACK TO SAVEPOINT authz_rule");+ desired.set(+ table,+ error instanceof Error ? error : new Error(String(error))+ );+ }+ }+ } finally {+ await db.query("ROLLBACK TO SAVEPOINT authz_scratch");+ }+ return desired;+}++/**+ * Run `work` in one transaction set up for authz: serialized against other syncs, public+ * search_path, short lock timeout. Everything is transaction-scoped, so it behaves the+ * same through a transaction-mode connection pooler.+ */+export async function inAuthzTransaction<T>(+ db: Client,+ work: () => Promise<T>,+ { commit }: { commit: boolean }+): Promise<T> {+ await db.query("BEGIN");+ try {+ await db.query("SELECT pg_advisory_xact_lock(hashtext($1))", [SYNC_LOCK]);+ await db.query("SET LOCAL search_path = public");+ await db.query("SET LOCAL lock_timeout = '5s'");+ const result = await work();+ await db.query(commit ? "COMMIT" : "ROLLBACK");+ return result;+ } catch (error) {+ await db.query("ROLLBACK");+ throw error;+ }+}++export type SyncResult = {+ /** Helper functions whose live definition differed from helpers/<name>.sql. */+ helpers: string[];+ /** Tables whose live policies differed from the manifest (rewritten unless dryRun). */+ changed: string[];+ /** Public tables the manifest does not cover. */+ unmanaged: string[];+};++/**+ * Make every manifest table's policies exactly what the manifest renders, in one+ * transaction: every change lands or none does. A table that differs has every existing+ * policy dropped (whatever its name), RLS enabled, and the rendered policies created.+ */+export async function syncAuthz(+ db: Client,+ manifest: Manifest,+ { dryRun = false, helpers }: { dryRun?: boolean; helpers?: Helper[] } = {}+): Promise<SyncResult> {+ const managedHelpers = helpers ?? (await loadHelpers());+ return inAuthzTransaction(+ db,+ async () => {+ // Helpers first: the policies below call them.+ const changedHelpers = await syncHelpers(db, managedHelpers, { dryRun });+ const desired = await desiredPolicies(db, manifest);+ const invalid = [...desired].filter(([, want]) => want instanceof Error);+ if (invalid.length) {+ throw new Error(+ `authz rules that do not apply (nothing was changed):\n${invalid+ .map(([table, error]) => ` ${table}: ${(error as Error).message}`)+ .join("\n")}`+ );+ }++ const changed: string[] = [];+ for (const [table, rule] of rulesOf(manifest)) {+ const live = await readPolicies(db, "public", table);+ const same =+ JSON.stringify(live) === JSON.stringify(desired.get(table)) &&+ (await rlsEnabled(db, table));+ if (same) continue;++ changed.push(table);+ if (dryRun) continue;++ for (const policy of live) {+ await db.query(+ `DROP POLICY ${ident(policy.policyname)} ON public.${ident(table)}`+ );+ }+ await db.query(+ `ALTER TABLE public.${ident(table)} ENABLE ROW LEVEL SECURITY`+ );+ const sql = render(rule, table);+ if (sql) {+ await assertOnlyPolicies(sql, "public", table);+ await db.query(sql);+ }+ }++ const unmanaged = (+ await db.query<{ table: string }>(+ `SELECT relname AS table FROM pg_class+ WHERE relnamespace = 'public'::regnamespace AND relkind IN ('r', 'p')+ AND NOT (relname = ANY ($1::text[]))+ AND NOT (relname LIKE ANY ($2::text[]))+ ORDER BY 1`,+ [+ Object.keys(manifest),+ DYNAMIC_TABLE_PREFIXES.map((p) => `${p.replaceAll("_", "\\_")}%`)+ ]+ )+ ).rows.map((r) => r.table);++ return { helpers: changedHelpers, changed, unmanaged };+ },+ { commit: !dryRun }+ );+}diff --git a/packages/database/src/configuration-rule.ts b/packages/database/src/configuration-rule.tsnew file mode 100644index 0000000000..0125ceb9ea--- /dev/null+++ b/packages/database/src/configuration-rule.ts@@ -0,0 +1,4 @@+// Node/browser re-export of the configuration-rule runner the edge runtime uses, so the rule+// editor and get-method run rules in the same QuickJS sandbox. Its npm dependencies are pinned+// in both this package.json and supabase/functions/deno.json — keep the versions identical.+export * from "../supabase/functions/shared/configuration-rule.ts";diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex f7c5044953..9bdbb3bbac 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -91722,9 +91722,6 @@ export default {{$ref: "#/parameters/rowFilter.companySettings.returnPickedMaterialTiming"},- {- $ref: "#/parameters/rowFilter.companySettings.salesRuleNotificationGroup"- },{$ref: "#/parameters/rowFilter.companySettings.showCurrencyTrailingZeros"},@@ -91734,6 +91731,9 @@ export default {{$ref: "#/parameters/rowFilter.companySettings.allowLowercaseItemIds"},+ {+ $ref: "#/parameters/rowFilter.companySettings.salesRuleNotificationGroup"+ },{$ref: "#/parameters/rowFilter.companySettings.includeOperationsOnTraveler"},@@ -91931,9 +91931,6 @@ export default {{$ref: "#/parameters/rowFilter.companySettings.returnPickedMaterialTiming"},- {- $ref: "#/parameters/rowFilter.companySettings.salesRuleNotificationGroup"- },{$ref: "#/parameters/rowFilter.companySettings.showCurrencyTrailingZeros"},@@ -91943,6 +91940,9 @@ export default {{$ref: "#/parameters/rowFilter.companySettings.allowLowercaseItemIds"},+ {+ $ref: "#/parameters/rowFilter.companySettings.salesRuleNotificationGroup"+ },{$ref: "#/parameters/rowFilter.companySettings.includeOperationsOnTraveler"},@@ -92094,9 +92094,6 @@ export default {{$ref: "#/parameters/rowFilter.companySettings.returnPickedMaterialTiming"},- {- $ref: "#/parameters/rowFilter.companySettings.salesRuleNotificationGroup"- },{$ref: "#/parameters/rowFilter.companySettings.showCurrencyTrailingZeros"},@@ -92106,6 +92103,9 @@ export default {{$ref: "#/parameters/rowFilter.companySettings.allowLowercaseItemIds"},+ {+ $ref: "#/parameters/rowFilter.companySettings.salesRuleNotificationGroup"+ },{$ref: "#/parameters/rowFilter.companySettings.includeOperationsOnTraveler"},@@ -93756,45 +93756,6 @@ export default {tags: ["(rpc) get_current_training_period"]}},- "/rpc/has_company_permission": {- post: {- parameters: [- {- in: "body",- name: "args",- required: true,- schema: {- properties: {- claim: {- format: "text",- type: "string"- },- company: {- format: "text",- type: "string"- }- },- required: ["claim", "company"],- type: "object"- }- },- {- $ref: "#/parameters/preferParams"- }- ],- produces: [- "application/json",- "application/vnd.pgrst.object+json;nulls=stripped",- "application/vnd.pgrst.object+json"- ],- responses: {- "200": {- description: "OK"- }- },- tags: ["(rpc) has_company_permission"]- }- },"/rpc/create_audit_log_table": {post: {parameters: [@@ -93904,59 +93865,6 @@ export default {tags: ["(rpc) set_shelf_life_for_operation"]}},- "/rpc/create_rfq_from_models_v2": {- post: {- parameters: [- {- in: "body",- name: "args",- required: true,- schema: {- properties: {- company_id: {- format: "text",- type: "string"- },- email: {- format: "text",- type: "string"- },- model_data: {- format: "json[]",- items: {},- type: "array"- },- sequence_number: {- format: "text",- type: "string"- }- },- required: [- "company_id",- "email",- "sequence_number",- "model_data"- ],- type: "object"- }- },- {- $ref: "#/parameters/preferParams"- }- ],- produces: [- "application/json",- "application/vnd.pgrst.object+json;nulls=stripped",- "application/vnd.pgrst.object+json"- ],- responses: {- "200": {- description: "OK"- }- },- tags: ["(rpc) create_rfq_from_models_v2"]- }- },"/rpc/save_inspection_document_atomic": {post: {parameters: [@@ -94403,6 +94311,28 @@ export default {}},"/rpc/get_companies_with_employee_permission": {+ get: {+ parameters: [+ {+ format: "text",+ in: "query",+ name: "permission",+ required: true,+ type: "string"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) get_companies_with_employee_permission"]+ },post: {parameters: [{@@ -94789,63 +94719,6 @@ export default {tags: ["(rpc) get_direct_ancestors_of_tracked_entity"]}},- "/rpc/get_permission_companies": {- get: {- parameters: [- {- format: "text",- in: "query",- name: "claim",- required: true,- type: "string"- }- ],- produces: [- "application/json",- "application/vnd.pgrst.object+json;nulls=stripped",- "application/vnd.pgrst.object+json"- ],- responses: {- "200": {- description: "OK"- }- },- tags: ["(rpc) get_permission_companies"]- },- post: {- parameters: [- {- in: "body",- name: "args",- required: true,- schema: {- properties: {- claim: {- format: "text",- type: "string"- }- },- required: ["claim"],- type: "object"- }- },- {- $ref: "#/parameters/preferParams"- }- ],- produces: [- "application/json",- "application/vnd.pgrst.object+json;nulls=stripped",- "application/vnd.pgrst.object+json"- ],- responses: {- "200": {- description: "OK"- }- },- tags: ["(rpc) get_permission_companies"]- }- },"/rpc/get_tool_details": {post: {parameters: [@@ -95134,59 +95007,6 @@ export default {tags: ["(rpc) insert_audit_log_batch"]}},- "/rpc/create_rfq_from_models_v1": {- post: {- parameters: [- {- in: "body",- name: "args",- required: true,- schema: {- properties: {- company_id: {- format: "text",- type: "string"- },- email: {- format: "text",- type: "string"- },- model_data: {- format: "json[]",- items: {},- type: "array"- },- sequence_number: {- format: "text",- type: "string"- }- },- required: [- "company_id",- "email",- "sequence_number",- "model_data"- ],- type: "object"- }- },- {- $ref: "#/parameters/preferParams"- }- ],- produces: [- "application/json",- "application/vnd.pgrst.object+json;nulls=stripped",- "application/vnd.pgrst.object+json"- ],- responses: {- "200": {- description: "OK"- }- },- tags: ["(rpc) create_rfq_from_models_v1"]- }- },"/rpc/sync_edit_document_transaction": {post: {parameters: [@@ -95560,41 +95380,6 @@ export default {tags: ["(rpc) get_period_end_date"]}},- "/rpc/get_companies_with_permission": {- post: {- parameters: [- {- in: "body",- name: "args",- required: true,- schema: {- properties: {- permission: {- format: "text",- type: "string"- }- },- required: ["permission"],- type: "object"- }- },- {- $ref: "#/parameters/preferParams"- }- ],- produces: [- "application/json",- "application/vnd.pgrst.object+json;nulls=stripped",- "application/vnd.pgrst.object+json"- ],- responses: {- "200": {- description: "OK"- }- },- tags: ["(rpc) get_companies_with_permission"]- }- },"/rpc/attach_audit_log_append_only": {post: {parameters: [@@ -99914,71 +99699,6 @@ export default {tags: ["(rpc) show_trgm"]}},- "/rpc/create_rfq_from_model_v1": {- post: {- parameters: [- {- in: "body",- name: "args",- required: true,- schema: {- properties: {- company_id: {- format: "text",- type: "string"- },- customer_part_id: {- format: "text",- type: "string"- },- email: {- format: "text",- type: "string"- },- model_id: {- format: "text",- type: "string"- },- notes: {- format: "json"- },- sequence_number: {- format: "text",- type: "string"- },- unit_of_measure: {- format: "text",- type: "string"- }- },- required: [- "company_id",- "customer_part_id",- "email",- "model_id",- "sequence_number",- "unit_of_measure"- ],- type: "object"- }- },- {- $ref: "#/parameters/preferParams"- }- ],- produces: [- "application/json",- "application/vnd.pgrst.object+json;nulls=stripped",- "application/vnd.pgrst.object+json"- ],- responses: {- "200": {- description: "OK"- }- },- tags: ["(rpc) create_rfq_from_model_v1"]- }- },"/rpc/increment_notification_delivery": {post: {parameters: [@@ -103495,74 +103215,6 @@ export default {tags: ["(rpc) nanoid"]}},- "/rpc/has_role": {- get: {- parameters: [- {- format: "text",- in: "query",- name: "required_role",- required: true,- type: "string"- },- {- format: "text",- in: "query",- name: "company",- required: true,- type: "string"- }- ],- produces: [- "application/json",- "application/vnd.pgrst.object+json;nulls=stripped",- "application/vnd.pgrst.object+json"- ],- responses: {- "200": {- description: "OK"- }- },- tags: ["(rpc) has_role"]- },- post: {- parameters: [- {- in: "body",- name: "args",- required: true,- schema: {- properties: {- company: {- format: "text",- type: "string"- },- required_role: {- format: "text",- type: "string"- }- },- required: ["required_role", "company"],- type: "object"- }- },- {- $ref: "#/parameters/preferParams"- }- ],- produces: [- "application/json",- "application/vnd.pgrst.object+json;nulls=stripped",- "application/vnd.pgrst.object+json"- ],- responses: {- "200": {- description: "OK"- }- },- tags: ["(rpc) has_role"]- }- },"/rpc/snapshotAccountingPeriodBalances": {post: {parameters: [@@ -149674,10 +149326,10 @@ export default {"incompletePickingListPolicy","includeMaterialsOnTraveler","returnPickedMaterialTiming",- "salesRuleNotificationGroup","showCurrencyTrailingZeros","requireMfa","allowLowercaseItemIds",+ "salesRuleNotificationGroup","includeOperationsOnTraveler"],properties: {@@ -149925,13 +149577,6 @@ export default {format: "text",type: "string"},- salesRuleNotificationGroup: {- format: "text[]",- items: {- type: "string"- },- type: "array"- },showCurrencyTrailingZeros: {default: true,format: "boolean",@@ -149947,6 +149592,13 @@ export default {format: "boolean",type: "boolean"},+ salesRuleNotificationGroup: {+ format: "text[]",+ items: {+ type: "string"+ },+ type: "array"+ },includeOperationsOnTraveler: {default: true,format: "boolean",@@ -199379,12 +199031,6 @@ export default {in: "query",type: "string"},- "rowFilter.companySettings.salesRuleNotificationGroup": {- name: "salesRuleNotificationGroup",- required: false,- in: "query",- type: "string"- },"rowFilter.companySettings.showCurrencyTrailingZeros": {name: "showCurrencyTrailingZeros",required: false,@@ -199403,6 +199049,12 @@ export default {in: "query",type: "string"},+ "rowFilter.companySettings.salesRuleNotificationGroup": {+ name: "salesRuleNotificationGroup",+ required: false,+ in: "query",+ type: "string"+ },"rowFilter.companySettings.includeOperationsOnTraveler": {name: "includeOperationsOnTraveler",required: false,diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 65c0f4f7ed..eae718dae7 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -82188,48 +82188,6 @@ export type Database = {table: string}[]}- create_rfq_from_model_v1: {- Args: {- company_id: string- customer_part_id: string- email: string- model_id: string- notes?: Json- sequence_number: string- unit_of_measure: string- }- Returns: {- rfq_id: string- rfq_line_id: string- rfq_readable_id: string- }[]- }- create_rfq_from_models_v1: {- Args: {- company_id: string- email: string- model_data: Json[]- sequence_number: string- }- Returns: {- rfq_id: string- rfq_line_ids: string[]- rfq_readable_id: string- }[]- }- create_rfq_from_models_v2: {- Args: {- company_id: string- email: string- model_data: Json[]- sequence_number: string- }- Returns: {- rfq_id: string- rfq_line_ids: string[]- rfq_readable_id: string- }[]- }create_search_subscriptions_for_company: {Args: { p_company_id: string }Returns: undefined@@ -82618,10 +82576,6 @@ export type Database = {Returns: string[]}get_companies_with_employee_role: { Args: never; Returns: string[] }- get_companies_with_permission: {- Args: { permission: string }- Returns: string[]- }get_company_groups_for_employee: { Args: never; Returns: string[] }get_company_groups_for_root_permission: {Args: { permission: string }@@ -83425,7 +83379,6 @@ export type Database = {}get_period_end_date: { Args: { period: string }; Returns: string }get_period_start_date: { Args: { period: string }; Returns: string }- get_permission_companies: { Args: { claim: string }; Returns: string[] }get_picking_list_availability: {Args: { p_picking_list_id: string }Returns: {@@ -84214,14 +84167,6 @@ export type Database = {}[]}has_any_company_permission: { Args: { claim: string }; Returns: boolean }- has_company_permission: {- Args: { claim: string; company: string }- Returns: boolean- }- has_role: {- Args: { company: string; required_role: string }- Returns: boolean- }has_valid_api_key_for_company: {Args: { company: string }Returns: booleandiff --git a/packages/database/supabase/functions/deno.json b/packages/database/supabase/functions/deno.jsonindex f9e313b7e2..e2b3d0baad 100644--- a/packages/database/supabase/functions/deno.json+++ b/packages/database/supabase/functions/deno.json@@ -18,6 +18,8 @@"@jsquash/png/decode.js": "npm:@jsquash/[email protected]/decode.js","@jsquash/png/encode.js": "npm:@jsquash/[email protected]/encode.js","@jsquash/webp/decode.js": "npm:@jsquash/[email protected]/decode.js",- "@jsquash/resize": "npm:@jsquash/[email protected]"+ "@jsquash/resize": "npm:@jsquash/[email protected]",+ "quickjs-emscripten-core": "npm:[email protected]",+ "@jitl/quickjs-singlefile-browser-release-sync": "npm:@jitl/[email protected]"}}diff --git a/packages/database/supabase/functions/lib/sandbox.ts b/packages/database/supabase/functions/lib/sandbox.tsindex bd37fdbf6e..34b4ffe363 100644--- a/packages/database/supabase/functions/lib/sandbox.ts+++ b/packages/database/supabase/functions/lib/sandbox.ts@@ -1,66 +1,41 @@import { transpile } from "https://deno.land/x/[email protected]/mod.ts";+import { runConfigurationRule } from "../shared/configuration-rule.ts";+import { getFunctionLogger } from "./logging.ts";-// Check for disallowed code patterns-const disallowedPatterns = [- /\bfetch\b/, // fetch calls- /setTimeout|setInterval/, // timeouts- /\bimport\b/, // dynamic imports- /new Promise/, // promise construction- /Function\(/, // Function constructor-];+const logger = getFunctionLogger("configuration-rule");/**- * Sandbox for executing user-provided TypeScript code safely+ * A stored configuration rule is the TypeScript body of `configure(params)`. It is+ * transpiled here and run in QuickJS (shared/configuration-rule.ts), never in this+ * function's own engine.*- * Usage:- * ```ts- * // Example code to execute- * const code = `- * // Your configuration logic here- * if (parameters.value > 10) {- * return "high";- * }- * return "low";- * `;- *- * // Parameters to pass to the code- * const parameters = {- * value: 15- * };- *- * // Import and execute the code- * const mod = await importTypeScript(code);- * const result = await mod.configure(parameters);- * // result = "high"- * ```- *- * The code will be executed in a sandboxed environment with the following restrictions:- * - No loops (for, while, do)- * - No fetch calls- * - No timeouts or intervals- * - No dynamic imports- * - No promise construction- * - No eval or Function constructor- *- * The code must export a `configure` function that takes a parameters object- * and returns a value. The parameters object will be passed to the function- * when executed.+ * A rule that does not compile, throws, or exceeds a sandbox limit yields null, so one+ * broken rule never fails the whole method: a field keeps its default, and a bill of+ * materials or process keeps all of its lines.*/--export async function importTypeScript(code: string) {+export async function importTypeScript(code: string): Promise<{+ configure: <T>(params: unknown) => Promise<T | null>;+}> {+ let javascript: string | null = null;try {- // Transpile TypeScript to JavaScript- const jsCode = await transpile(- `export function configure(params: Params) {${- disallowedPatterns.some((pattern) => pattern.test(code))- ? `return null`- : code- }}`+ javascript = await transpile(+ `function configure(params: Params) {\n${code}\n}`);-- return await import(`data:application/typescript;base64,${btoa(jsCode)}`);- } catch (err) {- console.error("Transpilation error:", err);- throw new Error(`Failed to transpile TypeScript: ${err.message}`);+ } catch (error) {+ logger.error("configuration rule does not compile", {+ error: String(error)+ });}++ return {+ configure: async <T>(params: unknown) => {+ if (javascript === null) return null;+ try {+ return (await runConfigurationRule(javascript, params)) as T | null;+ } catch (error) {+ logger.error("configuration rule failed", { error: String(error) });+ return null;+ }+ }+ };}diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 65c0f4f7ed..eae718dae7 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -82188,48 +82188,6 @@ export type Database = {table: string}[]}- create_rfq_from_model_v1: {- Args: {- company_id: string- customer_part_id: string- email: string- model_id: string- notes?: Json- sequence_number: string- unit_of_measure: string- }- Returns: {- rfq_id: string- rfq_line_id: string- rfq_readable_id: string- }[]- }- create_rfq_from_models_v1: {- Args: {- company_id: string- email: string- model_data: Json[]- sequence_number: string- }- Returns: {- rfq_id: string- rfq_line_ids: string[]- rfq_readable_id: string- }[]- }- create_rfq_from_models_v2: {- Args: {- company_id: string- email: string- model_data: Json[]- sequence_number: string- }- Returns: {- rfq_id: string- rfq_line_ids: string[]- rfq_readable_id: string- }[]- }create_search_subscriptions_for_company: {Args: { p_company_id: string }Returns: undefined@@ -82618,10 +82576,6 @@ export type Database = {Returns: string[]}get_companies_with_employee_role: { Args: never; Returns: string[] }- get_companies_with_permission: {- Args: { permission: string }- Returns: string[]- }get_company_groups_for_employee: { Args: never; Returns: string[] }get_company_groups_for_root_permission: {Args: { permission: string }@@ -83425,7 +83379,6 @@ export type Database = {}get_period_end_date: { Args: { period: string }; Returns: string }get_period_start_date: { Args: { period: string }; Returns: string }- get_permission_companies: { Args: { claim: string }; Returns: string[] }get_picking_list_availability: {Args: { p_picking_list_id: string }Returns: {@@ -84214,14 +84167,6 @@ export type Database = {}[]}has_any_company_permission: { Args: { claim: string }; Returns: boolean }- has_company_permission: {- Args: { claim: string; company: string }- Returns: boolean- }- has_role: {- Args: { company: string; required_role: string }- Returns: boolean- }has_valid_api_key_for_company: {Args: { company: string }Returns: booleandiff --git a/packages/database/supabase/functions/shared/configuration-rule.test.ts b/packages/database/supabase/functions/shared/configuration-rule.test.tsnew file mode 100644index 0000000000..f5f789319d--- /dev/null+++ b/packages/database/supabase/functions/shared/configuration-rule.test.ts@@ -0,0 +1,80 @@+import {+ assertEquals,+ assertRejects+} from "https://deno.land/[email protected]/testing/asserts.ts";+import { runConfigurationRule } from "./configuration-rule.ts";++const rule = (body: string) => `function configure(params) {\n${body}\n}`;++Deno.test("returns what configure returns, from the params it is given", async () => {+ assertEquals(+ await runConfigurationRule(+ rule(`return params.width > 10 ? ["A", params.name] : ["B"];`),+ { width: 12, name: "wide" }+ ),+ ["A", "wide"]+ );+ assertEquals(await runConfigurationRule(rule("return params.material.gradeId;"), {+ material: { gradeId: "steel-a36" }+ }), "steel-a36");+});++Deno.test("no return, or undefined, is null", async () => {+ assertEquals(await runConfigurationRule(rule(""), {}), null);+ assertEquals(await runConfigurationRule(rule("return undefined;"), {}), null);+});++Deno.test("the rule sees none of the host: no Deno, network, timers, process or module loading", async () => {+ const seen = await runConfigurationRule(+ rule(`return [+ typeof Deno, typeof fetch, typeof setTimeout, typeof process, typeof require,+ typeof XMLHttpRequest, typeof WebSocket, typeof window, typeof __params+ ];`),+ {}+ );+ assertEquals(seen, [+ "undefined", "undefined", "undefined", "undefined", "undefined",+ "undefined", "undefined", "undefined", "string"+ ]);+ // The Function constructor exists, but only builds more QuickJS code.+ await assertRejects(+ () =>+ runConfigurationRule(+ rule(`return (0, globalThis.constructor.constructor)("return Deno")();`),+ {}+ ),+ Error,+ "'Deno' is not defined"+ );+ // Promise jobs never run, so nothing asynchronous (a dynamic import included) completes.+ assertEquals(+ await runConfigurationRule(+ rule(`let state = "sync";+ import("https://example.com/x.js").then(() => { state = "loaded"; }, () => { state = "failed"; });+ Promise.resolve().then(() => { state = "async"; });+ return state;`),+ {}+ ),+ "sync"+ );+});++Deno.test("a runaway rule is stopped by the time, memory and stack limits", async () => {+ await assertRejects(() => runConfigurationRule(rule("while (true) {}"), {}));+ await assertRejects(() =>+ runConfigurationRule(rule(`const a = []; while (true) a.push("x".repeat(1e5));`), {})+ );+ await assertRejects(() =>+ runConfigurationRule(rule("const f = () => f(); return f();"), {})+ );+});++Deno.test("a throwing rule rejects, and does not break the next run", async () => {+ await assertRejects(() => runConfigurationRule(rule(`throw new Error("bad");`), {}));+ assertEquals(await runConfigurationRule(rule("return 1 + 1;"), {}), 2);+});++Deno.test("one run cannot leave state for the next", async () => {+ await runConfigurationRule(rule("globalThis.leak = 42; return null;"), {});+ assertEquals(await runConfigurationRule(rule("return typeof leak;"), {}), "undefined");+});diff --git a/packages/database/supabase/functions/shared/configuration-rule.ts b/packages/database/supabase/functions/shared/configuration-rule.tsnew file mode 100644index 0000000000..41ffd2ae73--- /dev/null+++ b/packages/database/supabase/functions/shared/configuration-rule.ts@@ -0,0 +1,55 @@+import variant from "@jitl/quickjs-singlefile-browser-release-sync";+import {+ newQuickJSWASMModuleFromVariant,+ type QuickJSWASMModule+} from "quickjs-emscripten-core";++/**+ * Configuration rules are code a company writes, so they never run in the host JavaScript+ * engine (the edge function or the browser). They run in QuickJS, a separate engine+ * compiled to WebAssembly: its globals are the language built-ins only — no network, no+ * environment, no timers, no host objects — and each run gets its own memory, stack and+ * time limits. The only way in is `params` as JSON, and the only way out is the JSON+ * value `configure` returns. Used by get-method (Deno) and the rule editor (browser).+ */++const MEMORY_LIMIT_BYTES = 16 * 1024 * 1024;+const STACK_LIMIT_BYTES = 512 * 1024;+const TIME_LIMIT_MS = 500;++let engine: Promise<QuickJSWASMModule> | undefined;++/**+ * Run JavaScript that defines `function configure(params)` and return its result. Throws+ * when the code fails, exceeds a limit, or returns something JSON cannot carry.+ */+export async function runConfigurationRule(+ javascript: string,+ params: unknown+): Promise<unknown> {+ engine ??= newQuickJSWASMModuleFromVariant(variant);+ const runtime = (await engine).newRuntime();+ runtime.setMemoryLimit(MEMORY_LIMIT_BYTES);+ runtime.setMaxStackSize(STACK_LIMIT_BYTES);+ const deadline = performance.now() + TIME_LIMIT_MS;+ runtime.setInterruptHandler(() => performance.now() > deadline);++ const context = runtime.newContext();+ try {+ const input = context.newString(JSON.stringify(params ?? null));+ context.setProp(context.global, "__params", input);+ input.dispose();++ const output = context.unwrapResult(+ context.evalCode(+ `${javascript}\n;JSON.stringify(configure(JSON.parse(__params)) ?? null) ?? "null";`+ )+ );+ const json = context.typeof(output) === "string" ? context.getString(output) : "null";+ output.dispose();+ return JSON.parse(json);+ } finally {+ context.dispose();+ runtime.dispose();+ }+}diff --git a/packages/database/supabase/migrations/20260927172338_authz-security-fixes.sql b/packages/database/supabase/migrations/20260927172338_authz-security-fixes.sqlnew file mode 100644index 0000000000..c7d27ce624--- /dev/null+++ b/packages/database/supabase/migrations/20260927172338_authz-security-fixes.sql@@ -0,0 +1,278 @@+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.++-- Ships these rules to databases where `authz sync` does not run after migrations yet.++CREATE OR REPLACE FUNCTION public.get_companies_with_employee_permission(permission text)+ RETURNS text[]+ LANGUAGE plpgsql+ STABLE SECURITY DEFINER+ SET search_path TO 'public'+AS $function$+DECLARE+ permission_companies text[];+ api_key_company text;+ employee_companies text[];+ api_key_scopes JSONB;+BEGIN+ api_key_company := get_company_id_from_api_key();++ IF api_key_company IS NOT NULL THEN+ api_key_scopes := get_api_key_scopes();+ IF api_key_scopes IS NULL OR api_key_scopes = '{}'::jsonb THEN+ RETURN '{}';+ END IF;+ IF (api_key_scopes ? permission)+ AND api_key_company = ANY(jsonb_to_text_array(api_key_scopes->permission)) THEN+ RETURN ARRAY[api_key_company];+ ELSE+ RETURN '{}';+ END IF;+ END IF;++ SELECT array_agg("companyId"::text)+ INTO employee_companies+ FROM "userToCompany"+ WHERE "userId" = auth.uid()::text AND "role" = 'employee';++ SELECT jsonb_to_text_array(COALESCE(permissions->permission, '[]'))+ INTO permission_companies+ FROM public."userPermission"+ WHERE id::text = auth.uid()::text;++ IF permission_companies IS NOT NULL AND employee_companies IS NOT NULL THEN+ SELECT array_agg(company)+ INTO permission_companies+ FROM unnest(permission_companies) company+ WHERE company = ANY(employee_companies);+ ELSE+ permission_companies := '{}';+ END IF;++ RETURN COALESCE(permission_companies, '{}');+END;+$function$;++CREATE OR REPLACE FUNCTION public.get_companies_with_permission(permission text)+ RETURNS text[]+ LANGUAGE plpgsql+ SECURITY DEFINER+ SET search_path TO 'public'+AS $function$+DECLARE+ permission_companies text[];+ api_key_company text;+ api_key_scopes jsonb;+BEGIN+ -- Deprecated: prefer get_companies_with_employee_permission. Unlike it, this also admits+ -- customer and supplier (portal) members, which the portal's document access relies on.++ -- An API key holds only the permissions its scopes grant, in its own company.+ api_key_company := get_company_id_from_api_key();+ IF api_key_company IS NOT NULL THEN+ api_key_scopes := get_api_key_scopes();+ IF api_key_scopes ? permission+ AND api_key_company = ANY(jsonb_to_text_array(api_key_scopes->permission)) THEN+ RETURN ARRAY[api_key_company];+ END IF;+ RETURN '{}';+ END IF;++ -- A user holds a permission only in companies they belong to. There is no '0' wildcard:+ -- it used to expand to every company on the instance.+ SELECT array_agg(company)+ INTO permission_companies+ FROM public."userPermission" up,+ unnest(jsonb_to_text_array(COALESCE(up.permissions->permission, '[]'))) company+ WHERE up.id = auth.uid()::text+ AND EXISTS (+ SELECT 1 FROM "userToCompany" utc+ WHERE utc."userId" = auth.uid()::text AND utc."companyId" = company+ );++ RETURN COALESCE(permission_companies, '{}');+END;+$function$;++CREATE OR REPLACE FUNCTION public.get_company_id_from_foreign_key(foreign_key text, tbl text)+ RETURNS text+ LANGUAGE plpgsql+ STABLE SECURITY DEFINER+ SET search_path TO 'public'+AS $function$+ DECLARE+ company_id text;+ BEGIN+ -- Policies call this inside a query. Called as the API endpoint itself it would tell+ -- anyone holding the anon key which company owns any row id, so refuse that. PostgREST+ -- sets request.path to /rpc/<function> only for a direct call (any case, any trailing /).+ IF current_setting('request.path', true) ~* '/rpc/get_company_id_from_foreign_key/*$' THEN+ RAISE EXCEPTION 'get_company_id_from_foreign_key cannot be called through the API'+ USING ERRCODE = 'insufficient_privilege';+ END IF;+ EXECUTE format('SELECT "companyId" FROM %I WHERE id = $1', tbl) INTO company_id USING foreign_key;+ RETURN company_id;+ END;+$function$;++CREATE OR REPLACE FUNCTION public.get_permission_companies(claim text)+ RETURNS text[]+ LANGUAGE plpgsql+ STABLE SECURITY DEFINER+ SET search_path TO 'public'+AS $function$+ DECLARE+ retval text[];+ BEGIN+ -- Deprecated: prefer get_companies_with_employee_permission. A permission counts only in+ -- a company the caller belongs to; no API key path (keys get nothing, as before).+ SELECT array_agg(company)+ INTO retval+ FROM public."userPermission" up,+ unnest(jsonb_to_text_array(COALESCE(up.permissions->claim, '[]'))) company+ WHERE up.id = auth.uid()::text+ AND EXISTS (+ SELECT 1 FROM "userToCompany" utc+ WHERE utc."userId" = auth.uid()::text AND utc."companyId" = company+ );+ RETURN retval;+ END;+$function$;++CREATE OR REPLACE FUNCTION public.has_company_permission(claim text, company text)+ RETURNS boolean+ LANGUAGE plpgsql+ SECURITY DEFINER+ SET search_path TO 'public'+AS $function$+ BEGIN+ -- Deprecated (still used by storage policies). True only when the caller holds the+ -- permission in that company AND belongs to it.+ RETURN EXISTS (+ SELECT 1+ FROM public."userPermission" up+ WHERE up.id = (SELECT auth.uid()::text)+ AND company = ANY(jsonb_to_text_array(COALESCE(up.permissions->claim, '[]')))+ ) AND EXISTS (+ SELECT 1 FROM "userToCompany" utc+ WHERE utc."userId" = (SELECT auth.uid()::text) AND utc."companyId" = company+ );+ END;+$function$;++-- journal+DO $authz$+DECLARE p record;+BEGIN+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'journal' LOOP+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'journal');+ END LOOP;+END+$authz$;+ALTER TABLE public."journal" ENABLE ROW LEVEL SECURITY;+CREATE POLICY "SELECT" ON "public"."journal" FOR SELECT USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_view'))::text[]));+CREATE POLICY "INSERT" ON "public"."journal" FOR INSERT WITH CHECK ("companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_create'))::text[]));+CREATE POLICY "UPDATE" ON "public"."journal" FOR UPDATE USING (("status" in ('Draft', 'Posted') AND "companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_update'))::text[]))) WITH CHECK ("companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_update'))::text[]));+CREATE POLICY "DELETE" ON "public"."journal" FOR DELETE USING (("status" = 'Draft' AND "companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_delete'))::text[])));++-- invoiceSettlement+DO $authz$+DECLARE p record;+BEGIN+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'invoiceSettlement' LOOP+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'invoiceSettlement');+ END LOOP;+END+$authz$;+ALTER TABLE public."invoiceSettlement" ENABLE ROW LEVEL SECURITY;+CREATE POLICY "SELECT" ON "public"."invoiceSettlement" FOR SELECT USING ("companyId" = ANY ((SELECT get_companies_with_employee_role())::text[]));+CREATE POLICY "INSERT" ON "public"."invoiceSettlement" FOR INSERT WITH CHECK (((("paymentId" IS NULL OR EXISTS (SELECT 1 FROM "public"."payment" p WHERE "p"."id" = "invoiceSettlement"."paymentId" AND "p"."companyId" = "invoiceSettlement"."companyId" AND "status" = 'Draft')) AND ("memoId" IS NULL OR EXISTS (SELECT 1 FROM "public"."memo" p WHERE "p"."id" = "invoiceSettlement"."memoId" AND "p"."companyId" = "invoiceSettlement"."companyId" AND "status" = 'Draft'))) AND "companyId" = ANY ((SELECT get_companies_with_employee_permission('invoicing_create'))::text[])));+CREATE POLICY "UPDATE" ON "public"."invoiceSettlement" FOR UPDATE USING (((("paymentId" IS NULL OR EXISTS (SELECT 1 FROM "public"."payment" p WHERE "p"."id" = "invoiceSettlement"."paymentId" AND "p"."companyId" = "invoiceSettlement"."companyId" AND "status" = 'Draft')) AND ("memoId" IS NULL OR EXISTS (SELECT 1 FROM "public"."memo" p WHERE "p"."id" = "invoiceSettlement"."memoId" AND "p"."companyId" = "invoiceSettlement"."companyId" AND "status" = 'Draft'))) AND "companyId" = ANY ((SELECT get_companies_with_employee_permission('invoicing_update'))::text[])));+CREATE POLICY "DELETE" ON "public"."invoiceSettlement" FOR DELETE USING (((("paymentId" IS NULL OR EXISTS (SELECT 1 FROM "public"."payment" p WHERE "p"."id" = "invoiceSettlement"."paymentId" AND "p"."companyId" = "invoiceSettlement"."companyId" AND "status" = 'Draft')) AND ("memoId" IS NULL OR EXISTS (SELECT 1 FROM "public"."memo" p WHERE "p"."id" = "invoiceSettlement"."memoId" AND "p"."companyId" = "invoiceSettlement"."companyId" AND "status" = 'Draft'))) AND "companyId" = ANY ((SELECT get_companies_with_employee_permission('invoicing_delete'))::text[])));++-- userAttributeValue+DO $authz$+DECLARE p record;+BEGIN+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'userAttributeValue' LOOP+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'userAttributeValue');+ END LOOP;+END+$authz$;+ALTER TABLE public."userAttributeValue" ENABLE ROW LEVEL SECURITY;+CREATE POLICY "SELECT" ON "public"."userAttributeValue" FOR SELECT USING ((("userId" = ((SELECT auth.uid()))::text AND "userAttributeId" IN (SELECT "userAttribute"."id" FROM "public"."userAttribute" WHERE ("canSelfManage" = true AND "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" IN (SELECT "userToCompany"."companyId" FROM "public"."userToCompany" WHERE "userId" = ((SELECT auth.uid()))::text))))) OR "userAttributeId" IN (SELECT "userAttribute"."id" FROM "public"."userAttribute" WHERE "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" = ANY ((SELECT get_permission_companies('resources_update'))::text[])))));+CREATE POLICY "INSERT" ON "public"."userAttributeValue" FOR INSERT WITH CHECK ((("userId" = ((SELECT auth.uid()))::text AND "userAttributeId" IN (SELECT "userAttribute"."id" FROM "public"."userAttribute" WHERE ("canSelfManage" = true AND "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" IN (SELECT "userToCompany"."companyId" FROM "public"."userToCompany" WHERE "userId" = ((SELECT auth.uid()))::text))))) OR "userAttributeId" IN (SELECT "userAttribute"."id" FROM "public"."userAttribute" WHERE "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" = ANY ((SELECT get_permission_companies('resources_update'))::text[])))));+CREATE POLICY "UPDATE" ON "public"."userAttributeValue" FOR UPDATE USING ((("userId" = ((SELECT auth.uid()))::text AND "userAttributeId" IN (SELECT "userAttribute"."id" FROM "public"."userAttribute" WHERE ("canSelfManage" = true AND "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" IN (SELECT "userToCompany"."companyId" FROM "public"."userToCompany" WHERE "userId" = ((SELECT auth.uid()))::text))))) OR "userAttributeId" IN (SELECT "userAttribute"."id" FROM "public"."userAttribute" WHERE "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" = ANY ((SELECT get_permission_companies('resources_update'))::text[])))));+CREATE POLICY "DELETE" ON "public"."userAttributeValue" FOR DELETE USING ("userAttributeId" IN (SELECT "userAttribute"."id" FROM "public"."userAttribute" WHERE "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" = ANY ((SELECT get_permission_companies('resources_update'))::text[]))));++-- note+DO $authz$+DECLARE p record;+BEGIN+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'note' LOOP+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'note');+ END LOOP;+END+$authz$;+ALTER TABLE public."note" ENABLE ROW LEVEL SECURITY;+CREATE POLICY "SELECT" ON "public"."note" FOR SELECT USING ("companyId" = ANY ((SELECT get_companies_with_employee_role())::text[]));+CREATE POLICY "INSERT" ON "public"."note" FOR INSERT WITH CHECK ("companyId" = ANY ((SELECT get_companies_with_employee_role())::text[]));+CREATE POLICY "UPDATE" ON "public"."note" FOR UPDATE USING ("createdBy" = ((SELECT auth.uid()))::text) WITH CHECK (("createdBy" = ((SELECT auth.uid()))::text AND "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])));+CREATE POLICY "DELETE" ON "public"."note" FOR DELETE USING ("createdBy" = ((SELECT auth.uid()))::text);++-- tableView+DO $authz$+DECLARE p record;+BEGIN+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'tableView' LOOP+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'tableView');+ END LOOP;+END+$authz$;+ALTER TABLE public."tableView" ENABLE ROW LEVEL SECURITY;+CREATE POLICY "SELECT" ON "public"."tableView" FOR SELECT USING (("createdBy" = ((SELECT auth.uid()))::text OR ("type" = 'Public' AND "companyId" = ANY ((SELECT get_companies_with_any_role())::text[]))));+CREATE POLICY "INSERT" ON "public"."tableView" FOR INSERT WITH CHECK (("createdBy" = ((SELECT auth.uid()))::text AND "companyId" = ANY ((SELECT get_companies_with_any_role())::text[])));+CREATE POLICY "UPDATE" ON "public"."tableView" FOR UPDATE USING ("createdBy" = ((SELECT auth.uid()))::text) WITH CHECK (("createdBy" = ((SELECT auth.uid()))::text AND "companyId" = ANY ((SELECT get_companies_with_any_role())::text[])));+CREATE POLICY "DELETE" ON "public"."tableView" FOR DELETE USING ("createdBy" = ((SELECT auth.uid()))::text);++-- maintenanceDispatchComment+DO $authz$+DECLARE p record;+BEGIN+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'maintenanceDispatchComment' LOOP+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'maintenanceDispatchComment');+ END LOOP;+END+$authz$;+ALTER TABLE public."maintenanceDispatchComment" ENABLE ROW LEVEL SECURITY;+CREATE POLICY "SELECT" ON "public"."maintenanceDispatchComment" FOR SELECT USING ("companyId" = ANY ((SELECT get_companies_with_employee_role())::text[]));+CREATE POLICY "INSERT" ON "public"."maintenanceDispatchComment" FOR INSERT WITH CHECK ("companyId" = ANY ((SELECT get_companies_with_employee_role())::text[]));+CREATE POLICY "UPDATE" ON "public"."maintenanceDispatchComment" FOR UPDATE USING ("createdBy" = ((SELECT auth.uid()))::text) WITH CHECK (("createdBy" = ((SELECT auth.uid()))::text AND "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])));+CREATE POLICY "DELETE" ON "public"."maintenanceDispatchComment" FOR DELETE USING ("createdBy" = ((SELECT auth.uid()))::text);++-- maintenanceDispatchItemTrackedEntity+DO $authz$+DECLARE p record;+BEGIN+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'maintenanceDispatchItemTrackedEntity' LOOP+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'maintenanceDispatchItemTrackedEntity');+ END LOOP;+END+$authz$;+ALTER TABLE public."maintenanceDispatchItemTrackedEntity" ENABLE ROW LEVEL SECURITY;+CREATE POLICY "SELECT" ON "public"."maintenanceDispatchItemTrackedEntity" FOR SELECT USING ("companyId" = ANY ((SELECT get_companies_with_employee_role())::text[]));+CREATE POLICY "INSERT" ON "public"."maintenanceDispatchItemTrackedEntity" FOR INSERT WITH CHECK ("companyId" = ANY ((SELECT get_companies_with_employee_role())::text[]));+CREATE POLICY "UPDATE" ON "public"."maintenanceDispatchItemTrackedEntity" FOR UPDATE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_update'))::text[]));+CREATE POLICY "DELETE" ON "public"."maintenanceDispatchItemTrackedEntity" FOR DELETE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_delete'))::text[]));++-- userToCompany+DO $authz$+DECLARE p record;+BEGIN+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'userToCompany' LOOP+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'userToCompany');+ END LOOP;+END+$authz$;+ALTER TABLE public."userToCompany" ENABLE ROW LEVEL SECURITY;+CREATE POLICY "SELECT" ON "public"."userToCompany" FOR SELECT USING ("companyId" = ANY ((SELECT get_companies_with_employee_role())::text[]));+CREATE POLICY "DELETE" ON "public"."userToCompany" FOR DELETE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('users_delete'))::text[]));diff --git a/packages/database/supabase/migrations/20260927224243_retire-legacy-rls-helpers-policies.sql b/packages/database/supabase/migrations/20260927224243_retire-legacy-rls-helpers-policies.sqlnew file mode 100644index 0000000000..6ae66aac39--- /dev/null+++ b/packages/database/supabase/migrations/20260927224243_retire-legacy-rls-helpers-policies.sql@@ -0,0 +1,155 @@+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.++-- Ships these rules to databases where `authz sync` does not run after migrations yet.++-- demandActual+DO $authz$+DECLARE p record;+BEGIN+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'demandActual' LOOP+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'demandActual');+ END LOOP;+END+$authz$;+ALTER TABLE public."demandActual" ENABLE ROW LEVEL SECURITY;+CREATE POLICY "SELECT" ON "public"."demandActual" FOR SELECT USING (("companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_view'))::text[]) OR "companyId" = ANY ((SELECT get_companies_with_employee_permission('inventory_view'))::text[])));+CREATE POLICY "INSERT" ON "public"."demandActual" FOR INSERT WITH CHECK ("companyId" = ANY ((SELECT get_companies_with_employee_permission('inventory_create'))::text[]));+CREATE POLICY "UPDATE" ON "public"."demandActual" FOR UPDATE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('inventory_update'))::text[]));+CREATE POLICY "DELETE" ON "public"."demandActual" FOR DELETE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('inventory_delete'))::text[]));++-- demandForecast+DO $authz$+DECLARE p record;+BEGIN+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'demandForecast' LOOP+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'demandForecast');+ END LOOP;+END+$authz$;+ALTER TABLE public."demandForecast" ENABLE ROW LEVEL SECURITY;+CREATE POLICY "SELECT" ON "public"."demandForecast" FOR SELECT USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('inventory_view'))::text[]));+CREATE POLICY "INSERT" ON "public"."demandForecast" FOR INSERT WITH CHECK ("companyId" = ANY ((SELECT get_companies_with_employee_permission('inventory_create'))::text[]));+CREATE POLICY "UPDATE" ON "public"."demandForecast" FOR UPDATE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('inventory_update'))::text[]));+CREATE POLICY "DELETE" ON "public"."demandForecast" FOR DELETE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('inventory_delete'))::text[]));++-- demandForecastSource+DO $authz$+DECLARE p record;+BEGIN+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'demandForecastSource' LOOP+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'demandForecastSource');+ END LOOP;+END+$authz$;+ALTER TABLE public."demandForecastSource" ENABLE ROW LEVEL SECURITY;+CREATE POLICY "SELECT" ON "public"."demandForecastSource" FOR SELECT USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('inventory_view'))::text[]));+CREATE POLICY "INSERT" ON "public"."demandForecastSource" FOR INSERT WITH CHECK ("companyId" = ANY ((SELECT get_companies_with_employee_permission('inventory_create'))::text[]));+CREATE POLICY "UPDATE" ON "public"."demandForecastSource" FOR UPDATE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('inventory_update'))::text[]));+CREATE POLICY "DELETE" ON "public"."demandForecastSource" FOR DELETE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('inventory_delete'))::text[]));++-- demandProjection+DO $authz$+DECLARE p record;+BEGIN+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'demandProjection' LOOP+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'demandProjection');+ END LOOP;+END+$authz$;+ALTER TABLE public."demandProjection" ENABLE ROW LEVEL SECURITY;+CREATE POLICY "SELECT" ON "public"."demandProjection" FOR SELECT USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('inventory_view'))::text[]));+CREATE POLICY "INSERT" ON "public"."demandProjection" FOR INSERT WITH CHECK ("companyId" = ANY ((SELECT get_companies_with_employee_permission('inventory_create'))::text[]));+CREATE POLICY "UPDATE" ON "public"."demandProjection" FOR UPDATE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('inventory_update'))::text[]));+CREATE POLICY "DELETE" ON "public"."demandProjection" FOR DELETE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('inventory_delete'))::text[]));++-- document+DO $authz$+DECLARE p record;+BEGIN+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'document' LOOP+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'document');+ END LOOP;+END+$authz$;+ALTER TABLE public."document" ENABLE ROW LEVEL SECURITY;++ CREATE POLICY "DELETE" ON "public"."document" AS PERMISSIVE FOR DELETE TO public USING ((("companyId" = ANY (( SELECT get_companies_with_employee_permission('documents_delete'::text) AS get_companies_with_employee_permission)::text[])) AND (has_valid_api_key_for_company("companyId") OR ((groups_for_user((( SELECT auth.uid() AS uid))::text) && "writeGroups") = true))));+ CREATE POLICY "INSERT" ON "public"."document" AS PERMISSIVE FOR INSERT TO public WITH CHECK ((("companyId" = ANY (( SELECT get_companies_with_employee_permission('documents_create'::text) AS get_companies_with_employee_permission)::text[])) AND (has_valid_api_key_for_company("companyId") OR ((groups_for_user((( SELECT auth.uid() AS uid))::text) && "writeGroups") = true))));+ CREATE POLICY "SELECT" ON "public"."document" AS PERMISSIVE FOR SELECT TO public USING ((("companyId" = ANY (( SELECT get_companies_with_employee_permission('documents_view'::text) AS get_companies_with_employee_permission)::text[])) AND (has_valid_api_key_for_company("companyId") OR ((groups_for_user((( SELECT auth.uid() AS uid))::text) && "readGroups") = true))));+ CREATE POLICY "UPDATE" ON "public"."document" AS PERMISSIVE FOR UPDATE TO public USING ((("companyId" = ANY (( SELECT get_companies_with_employee_permission('documents_update'::text) AS get_companies_with_employee_permission)::text[])) AND (has_valid_api_key_for_company("companyId") OR ((groups_for_user((( SELECT auth.uid() AS uid))::text) && "writeGroups") = true))));+++-- supplyActual+DO $authz$+DECLARE p record;+BEGIN+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'supplyActual' LOOP+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'supplyActual');+ END LOOP;+END+$authz$;+ALTER TABLE public."supplyActual" ENABLE ROW LEVEL SECURITY;+CREATE POLICY "SELECT" ON "public"."supplyActual" FOR SELECT USING (("companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_view'))::text[]) OR "companyId" = ANY ((SELECT get_companies_with_employee_permission('inventory_view'))::text[])));+CREATE POLICY "INSERT" ON "public"."supplyActual" FOR INSERT WITH CHECK ("companyId" = ANY ((SELECT get_companies_with_employee_permission('inventory_create'))::text[]));+CREATE POLICY "UPDATE" ON "public"."supplyActual" FOR UPDATE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('inventory_update'))::text[]));+CREATE POLICY "DELETE" ON "public"."supplyActual" FOR DELETE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('inventory_delete'))::text[]));++-- supplyForecast+DO $authz$+DECLARE p record;+BEGIN+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'supplyForecast' LOOP+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'supplyForecast');+ END LOOP;+END+$authz$;+ALTER TABLE public."supplyForecast" ENABLE ROW LEVEL SECURITY;+CREATE POLICY "SELECT" ON "public"."supplyForecast" FOR SELECT USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('inventory_view'))::text[]));+CREATE POLICY "INSERT" ON "public"."supplyForecast" FOR INSERT WITH CHECK ("companyId" = ANY ((SELECT get_companies_with_employee_permission('inventory_create'))::text[]));+CREATE POLICY "UPDATE" ON "public"."supplyForecast" FOR UPDATE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('inventory_update'))::text[]));+CREATE POLICY "DELETE" ON "public"."supplyForecast" FOR DELETE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('inventory_delete'))::text[]));++-- userAttribute+DO $authz$+DECLARE p record;+BEGIN+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'userAttribute' LOOP+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'userAttribute');+ END LOOP;+END+$authz$;+ALTER TABLE public."userAttribute" ENABLE ROW LEVEL SECURITY;+CREATE POLICY "SELECT" ON "public"."userAttribute" FOR SELECT USING ("userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_view'))::text[])));+CREATE POLICY "INSERT" ON "public"."userAttribute" FOR INSERT WITH CHECK ("userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_create'))::text[])));+CREATE POLICY "UPDATE" ON "public"."userAttribute" FOR UPDATE USING ("userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_update'))::text[])));+CREATE POLICY "DELETE" ON "public"."userAttribute" FOR DELETE USING ("userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_delete'))::text[])));++-- userAttributeCategory+DO $authz$+DECLARE p record;+BEGIN+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'userAttributeCategory' LOOP+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'userAttributeCategory');+ END LOOP;+END+$authz$;+ALTER TABLE public."userAttributeCategory" ENABLE ROW LEVEL SECURITY;+CREATE POLICY "SELECT" ON "public"."userAttributeCategory" FOR SELECT USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_view'))::text[]));+CREATE POLICY "INSERT" ON "public"."userAttributeCategory" FOR INSERT WITH CHECK ("companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_create'))::text[]));+CREATE POLICY "UPDATE" ON "public"."userAttributeCategory" FOR UPDATE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_update'))::text[]));+CREATE POLICY "DELETE" ON "public"."userAttributeCategory" FOR DELETE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_delete'))::text[]));++-- userAttributeValue+DO $authz$+DECLARE p record;+BEGIN+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'userAttributeValue' LOOP+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'userAttributeValue');+ END LOOP;+END+$authz$;+ALTER TABLE public."userAttributeValue" ENABLE ROW LEVEL SECURITY;+CREATE POLICY "SELECT" ON "public"."userAttributeValue" FOR SELECT USING ((("userId" = ((SELECT auth.uid()))::text AND "userAttributeId" IN (SELECT "userAttribute"."id" FROM "public"."userAttribute" WHERE ("canSelfManage" = true AND "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" IN (SELECT "userToCompany"."companyId" FROM "public"."userToCompany" WHERE "userId" = ((SELECT auth.uid()))::text))))) OR "userAttributeId" IN (SELECT "userAttribute"."id" FROM "public"."userAttribute" WHERE "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_update'))::text[])))));+CREATE POLICY "INSERT" ON "public"."userAttributeValue" FOR INSERT WITH CHECK ((("userId" = ((SELECT auth.uid()))::text AND "userAttributeId" IN (SELECT "userAttribute"."id" FROM "public"."userAttribute" WHERE ("canSelfManage" = true AND "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" IN (SELECT "userToCompany"."companyId" FROM "public"."userToCompany" WHERE "userId" = ((SELECT auth.uid()))::text))))) OR "userAttributeId" IN (SELECT "userAttribute"."id" FROM "public"."userAttribute" WHERE "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_update'))::text[])))));+CREATE POLICY "UPDATE" ON "public"."userAttributeValue" FOR UPDATE USING ((("userId" = ((SELECT auth.uid()))::text AND "userAttributeId" IN (SELECT "userAttribute"."id" FROM "public"."userAttribute" WHERE ("canSelfManage" = true AND "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" IN (SELECT "userToCompany"."companyId" FROM "public"."userToCompany" WHERE "userId" = ((SELECT auth.uid()))::text))))) OR "userAttributeId" IN (SELECT "userAttribute"."id" FROM "public"."userAttribute" WHERE "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_update'))::text[])))));+CREATE POLICY "DELETE" ON "public"."userAttributeValue" FOR DELETE USING ("userAttributeId" IN (SELECT "userAttribute"."id" FROM "public"."userAttribute" WHERE "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_update'))::text[]))));diff --git a/packages/database/supabase/migrations/20260927224314_retire-legacy-rls-helpers.sql b/packages/database/supabase/migrations/20260927224314_retire-legacy-rls-helpers.sqlnew file mode 100644index 0000000000..5cd0f24130--- /dev/null+++ b/packages/database/supabase/migrations/20260927224314_retire-legacy-rls-helpers.sql@@ -0,0 +1,66 @@+-- Retire the four deprecated RLS helpers: has_role, has_company_permission,+-- get_companies_with_permission, get_permission_companies. Unlike the helpers that replace+-- them, they admitted customer and supplier portal accounts holding a permission (and+-- get_permission_companies had no API-key path at all).+--+-- The public tables that used them moved to the standard helpers in+-- 20260927224243_retire-legacy-rls-helpers-policies.sql (generated from the authz+-- manifest). This migration moves their last users and then drops them; nothing may+-- depend on them by then, so each DROP fails loudly if something still does.++-- Tax-certificate and purchasing-RFQ policies on the legacy `private` bucket. "Shared+-- Private Bucket" (FOR ALL, any employee of the folder's company) already grants a+-- superset of each, so they add nothing; no code uses the purchasing-rfq folder.+DROP POLICY "Employees can view tax certificates" ON storage.objects;+DROP POLICY "Employees with sales_create can upload tax certificates" ON storage.objects;+DROP POLICY "Employees with sales_delete or purchasing_delete can delete tax" ON storage.objects;+DROP POLICY "Purchasing RFQ documents view requires purchasing_view" ON storage.objects;+DROP POLICY "Purchasing RFQ documents insert requires purchasing_create" ON storage.objects;+DROP POLICY "Purchasing RFQ documents update requires purchasing_update" ON storage.objects;+DROP POLICY "Purchasing RFQ documents delete requires purchasing_delete" ON storage.objects;++-- Company logos in the public bucket: employees holding the settings permission.+ALTER POLICY "Anyone with settings_create can insert into the public bucket" ON storage.objects+ WITH CHECK (+ bucket_id = 'public'+ AND (storage.foldername(name))[1] = ANY ((SELECT get_companies_with_employee_permission('settings_create'))::text[])+ );+ALTER POLICY "Anyone with settings_update can update the public bucket" ON storage.objects+ USING (+ bucket_id = 'public'+ AND (storage.foldername(name))[1] = ANY ((SELECT get_companies_with_employee_permission('settings_update'))::text[])+ );+ALTER POLICY "Anyone with settings_delete can delete from public bucket" ON storage.objects+ USING (+ bucket_id = 'public'+ AND (storage.foldername(name))[1] = ANY ((SELECT get_companies_with_employee_permission('settings_delete'))::text[])+ );++-- Called by updatePermissions (@carbon/ee permissions.server) with the caller's client.+CREATE OR REPLACE FUNCTION public.is_claims_admin(company text)+RETURNS boolean+LANGUAGE plpgsql+AS $function$+ BEGIN+ IF session_user = 'authenticator' THEN+ IF extract(epoch from now()) > coalesce((current_setting('request.jwt.claims', true)::jsonb)->>'exp', '0')::numeric THEN+ return false; -- jwt expired+ END IF;+ RETURN company = ANY (coalesce(get_companies_with_employee_permission('users_update'), '{}'));+ ELSE -- not a user session (trigger etc.)+ return true;+ END IF;+ END;+$function$;++-- Unused RPCs (no caller in the apps, jobs or edge functions) whose only guard was has_role.+DROP FUNCTION public.create_rfq_from_model_v1(text, text, text, text, text, text, json);+DROP FUNCTION public.create_rfq_from_models_v1(text, text, text, json[]);+DROP FUNCTION public.create_rfq_from_models_v2(text, text, text, json[]);++-- The helpers themselves. Named without an argument list (each has one overload) so the+-- text does not read as a call to them.+DROP FUNCTION public.has_role;+DROP FUNCTION public.has_company_permission;+DROP FUNCTION public.get_companies_with_permission;+DROP FUNCTION public.get_permission_companies;diff --git a/packages/database/supabase/migrations/20260927225837_is-claims-admin-service-role.sql b/packages/database/supabase/migrations/20260927225837_is-claims-admin-service-role.sqlnew file mode 100644index 0000000000..2f46c386dd--- /dev/null+++ b/packages/database/supabase/migrations/20260927225837_is-claims-admin-service-role.sql@@ -0,0 +1,23 @@+-- is_claims_admin answered false to the service role: a service-role request has no user,+-- so the users_update check (keyed on auth.uid()) never matched. Bulk permission edits run+-- as an Inngest job with the service role (update-permissions.ts), after the route checked+-- users_update, so every one failed with "You do not have permission to update+-- permissions". The service role already bypasses every policy; trust it here too.+CREATE OR REPLACE FUNCTION public.is_claims_admin(company text)+RETURNS boolean+LANGUAGE plpgsql+AS $function$+ BEGIN+ IF session_user = 'authenticator' THEN+ IF extract(epoch from now()) > coalesce((current_setting('request.jwt.claims', true)::jsonb)->>'exp', '0')::numeric THEN+ return false; -- jwt expired+ END IF;+ IF (current_setting('request.jwt.claims', true)::jsonb)->>'role' = 'service_role' THEN+ return true;+ END IF;+ RETURN company = ANY (coalesce(get_companies_with_employee_permission('users_update'), '{}'));+ ELSE -- not a user session (trigger etc.)+ return true;+ END IF;+ END;+$function$;diff --git a/packages/database/supabase/migrations/20260927230425_user-attribute-value-self-clear.sql b/packages/database/supabase/migrations/20260927230425_user-attribute-value-self-clear.sqlnew file mode 100644index 0000000000..4d5d1e4812--- /dev/null+++ b/packages/database/supabase/migrations/20260927230425_user-attribute-value-self-clear.sql@@ -0,0 +1,18 @@+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.++-- Ships these rules to databases where `authz sync` does not run after migrations yet.++-- userAttributeValue+DO $authz$+DECLARE p record;+BEGIN+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'userAttributeValue' LOOP+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'userAttributeValue');+ END LOOP;+END+$authz$;+ALTER TABLE public."userAttributeValue" ENABLE ROW LEVEL SECURITY;+CREATE POLICY "SELECT" ON "public"."userAttributeValue" FOR SELECT USING ((("userId" = ((SELECT auth.uid()))::text AND "userAttributeId" IN (SELECT "userAttribute"."id" FROM "public"."userAttribute" WHERE ("canSelfManage" = true AND "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" IN (SELECT "userToCompany"."companyId" FROM "public"."userToCompany" WHERE "userId" = ((SELECT auth.uid()))::text))))) OR "userAttributeId" IN (SELECT "userAttribute"."id" FROM "public"."userAttribute" WHERE "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_update'))::text[])))));+CREATE POLICY "INSERT" ON "public"."userAttributeValue" FOR INSERT WITH CHECK ((("userId" = ((SELECT auth.uid()))::text AND "userAttributeId" IN (SELECT "userAttribute"."id" FROM "public"."userAttribute" WHERE ("canSelfManage" = true AND "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" IN (SELECT "userToCompany"."companyId" FROM "public"."userToCompany" WHERE "userId" = ((SELECT auth.uid()))::text))))) OR "userAttributeId" IN (SELECT "userAttribute"."id" FROM "public"."userAttribute" WHERE "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_update'))::text[])))));+CREATE POLICY "UPDATE" ON "public"."userAttributeValue" FOR UPDATE USING ((("userId" = ((SELECT auth.uid()))::text AND "userAttributeId" IN (SELECT "userAttribute"."id" FROM "public"."userAttribute" WHERE ("canSelfManage" = true AND "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" IN (SELECT "userToCompany"."companyId" FROM "public"."userToCompany" WHERE "userId" = ((SELECT auth.uid()))::text))))) OR "userAttributeId" IN (SELECT "userAttribute"."id" FROM "public"."userAttribute" WHERE "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_update'))::text[])))));+CREATE POLICY "DELETE" ON "public"."userAttributeValue" FOR DELETE USING ((("userId" = ((SELECT auth.uid()))::text AND "userAttributeId" IN (SELECT "userAttribute"."id" FROM "public"."userAttribute" WHERE ("canSelfManage" = true AND "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" IN (SELECT "userToCompany"."companyId" FROM "public"."userToCompany" WHERE "userId" = ((SELECT auth.uid()))::text))))) OR "userAttributeId" IN (SELECT "userAttribute"."id" FROM "public"."userAttribute" WHERE "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_update'))::text[])))));diff --git a/packages/database/supabase/migrations/20260927234425_user-attribute-self-service.sql b/packages/database/supabase/migrations/20260927234425_user-attribute-self-service.sqlnew file mode 100644index 0000000000..0857af3b70--- /dev/null+++ b/packages/database/supabase/migrations/20260927234425_user-attribute-self-service.sql@@ -0,0 +1,48 @@+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.++-- Ships these rules to databases where `authz sync` does not run after migrations yet.++-- userAttribute+DO $authz$+DECLARE p record;+BEGIN+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'userAttribute' LOOP+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'userAttribute');+ END LOOP;+END+$authz$;+ALTER TABLE public."userAttribute" ENABLE ROW LEVEL SECURITY;+CREATE POLICY "SELECT" ON "public"."userAttribute" FOR SELECT USING (("userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_view'))::text[])) OR ("canSelfManage" = true AND "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])))));+CREATE POLICY "INSERT" ON "public"."userAttribute" FOR INSERT WITH CHECK ("userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_create'))::text[])));+CREATE POLICY "UPDATE" ON "public"."userAttribute" FOR UPDATE USING ("userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_update'))::text[])));+CREATE POLICY "DELETE" ON "public"."userAttribute" FOR DELETE USING ("userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_delete'))::text[])));++-- userAttributeCategory+DO $authz$+DECLARE p record;+BEGIN+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'userAttributeCategory' LOOP+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'userAttributeCategory');+ END LOOP;+END+$authz$;+ALTER TABLE public."userAttributeCategory" ENABLE ROW LEVEL SECURITY;+CREATE POLICY "SELECT" ON "public"."userAttributeCategory" FOR SELECT USING ("companyId" = ANY ((SELECT get_companies_with_employee_role())::text[]));+CREATE POLICY "INSERT" ON "public"."userAttributeCategory" FOR INSERT WITH CHECK ("companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_create'))::text[]));+CREATE POLICY "UPDATE" ON "public"."userAttributeCategory" FOR UPDATE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_update'))::text[]));+CREATE POLICY "DELETE" ON "public"."userAttributeCategory" FOR DELETE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_delete'))::text[]));++-- userAttributeValue+DO $authz$+DECLARE p record;+BEGIN+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'userAttributeValue' LOOP+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'userAttributeValue');+ END LOOP;+END+$authz$;+ALTER TABLE public."userAttributeValue" ENABLE ROW LEVEL SECURITY;+CREATE POLICY "SELECT" ON "public"."userAttributeValue" FOR SELECT USING ((("userId" = ((SELECT auth.uid()))::text AND "userAttributeId" IN (SELECT "userAttribute"."id" FROM "public"."userAttribute" WHERE ("canSelfManage" = true AND "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[]))))) OR "userAttributeId" IN (SELECT "userAttribute"."id" FROM "public"."userAttribute" WHERE "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_update'))::text[])))));+CREATE POLICY "INSERT" ON "public"."userAttributeValue" FOR INSERT WITH CHECK ((("userId" = ((SELECT auth.uid()))::text AND "userAttributeId" IN (SELECT "userAttribute"."id" FROM "public"."userAttribute" WHERE ("canSelfManage" = true AND "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[]))))) OR "userAttributeId" IN (SELECT "userAttribute"."id" FROM "public"."userAttribute" WHERE "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_update'))::text[])))));+CREATE POLICY "UPDATE" ON "public"."userAttributeValue" FOR UPDATE USING ((("userId" = ((SELECT auth.uid()))::text AND "userAttributeId" IN (SELECT "userAttribute"."id" FROM "public"."userAttribute" WHERE ("canSelfManage" = true AND "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[]))))) OR "userAttributeId" IN (SELECT "userAttribute"."id" FROM "public"."userAttribute" WHERE "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_update'))::text[])))));+CREATE POLICY "DELETE" ON "public"."userAttributeValue" FOR DELETE USING ((("userId" = ((SELECT auth.uid()))::text AND "userAttributeId" IN (SELECT "userAttribute"."id" FROM "public"."userAttribute" WHERE ("canSelfManage" = true AND "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[]))))) OR "userAttributeId" IN (SELECT "userAttribute"."id" FROM "public"."userAttribute" WHERE "userAttributeCategoryId" IN (SELECT "userAttributeCategory"."id" FROM "public"."userAttributeCategory" WHERE "companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_update'))::text[])))));diff --git a/packages/database/supabase/tests/authz-fixes.test.sql b/packages/database/supabase/tests/authz-fixes.test.sqlnew file mode 100644index 0000000000..a8607eebf2--- /dev/null+++ b/packages/database/supabase/tests/authz-fixes.test.sql@@ -0,0 +1,228 @@+-- Regression tests for the RLS and helper fixes made through packages/database/src/authz.+-- Run from the repository root against an existing local database:+-- pnpm exec tsx scripts/run-local-accounting-check.ts psql -X -v ON_ERROR_STOP=1 -f packages/database/supabase/tests/authz-fixes.test.sql+-- All fixtures and role changes are confined to the rolled-back transaction.+\set ON_ERROR_STOP on+BEGIN;+SET LOCAL "app.sync_in_progress" = 'true';+SET LOCAL statement_timeout = '30s';++-- Evaluates the live policy expression (USING, or WITH CHECK — which an UPDATE without one+-- takes from USING) of one command against a synthetic row, as the current role. Tests a+-- policy without building its whole fixture chain.+CREATE FUNCTION pg_temp.allows(tbl text, command text, clause text, rec jsonb)+RETURNS boolean LANGUAGE plpgsql AS $fn$+DECLARE expr text; ok boolean;+BEGIN+ SELECT CASE clause WHEN 'check' THEN coalesce(with_check, qual) ELSE qual END INTO expr+ FROM pg_policies WHERE schemaname = 'public' AND tablename = tbl AND cmd = command;+ IF expr IS NULL THEN RETURN false; END IF;+ EXECUTE format('SELECT (%s) FROM jsonb_populate_record(NULL::public.%I, $1) AS %I', expr, tbl, tbl)+ INTO ok USING rec;+ RETURN coalesce(ok, false);+END;+$fn$;++CREATE FUNCTION pg_temp.act_as(user_id text) RETURNS void LANGUAGE plpgsql AS $fn$+BEGIN+ PERFORM set_config('request.jwt.claims', jsonb_build_object('sub', user_id, 'role', 'authenticated')::text, true);+ PERFORM set_config('request.path', '/test', true);+END;+$fn$;++DO $proof$+DECLARE+ group_a text; group_b text; company_a text; company_b text;+ u text := gen_random_uuid()::text; -- employee of A, several permissions, some naming B+ w text := gen_random_uuid()::text; -- plain employee of A, no permissions at all+ c text := gen_random_uuid()::text; -- customer-portal account of A+ v text := gen_random_uuid()::text; -- employee of B only+ bank text; customer_a text; draft_payment text; posted_payment text;+ note_id text; view_id text; category_a text; category_b text;+ attribute_a text; attribute_b text; attribute_locked text;+ companies text[]; n int;+BEGIN+ INSERT INTO "companyGroup" (name, "createdBy") VALUES ('Authz A ' || id(), 'system') RETURNING id INTO group_a;+ INSERT INTO "companyGroup" (name, "createdBy") VALUES ('Authz B ' || id(), 'system') RETURNING id INTO group_b;+ INSERT INTO company (name, "companyGroupId", "baseCurrencyCode", timezone)+ VALUES ('Authz A', group_a, 'USD', 'America/New_York') RETURNING id INTO company_a;+ INSERT INTO company (name, "companyGroupId", "baseCurrencyCode", timezone)+ VALUES ('Authz B', group_b, 'USD', 'America/New_York') RETURNING id INTO company_b;++ INSERT INTO "user" (id, email) VALUES+ (u, u || '@authz.invalid'), (w, w || '@authz.invalid'), (v, v || '@authz.invalid'),+ (c, c || '@authz.invalid');+ INSERT INTO "userToCompany" ("userId", "companyId", role) VALUES+ (u, company_a, 'employee'), (w, company_a, 'employee'), (v, company_b, 'employee'),+ (c, company_a, 'customer');+ INSERT INTO "userPermission" (id, permissions) VALUES+ (u, jsonb_build_object(+ 'users_create', jsonb_build_array(company_a),+ 'resources_update', jsonb_build_array(company_a),+ 'invoicing_update', jsonb_build_array(company_a),+ 'documents_view', jsonb_build_array(company_a, company_b), -- names a company u is not in+ 'inventory_view', jsonb_build_array('0') -- the old global wildcard+ )),+ (w, '{}'::jsonb), (v, '{}'::jsonb), (c, '{}'::jsonb);++ INSERT INTO account (name, class, "incomeBalance", "isGroup", "companyGroupId", "createdBy")+ VALUES ('Authz bank', 'Asset', 'Balance Sheet', false, group_a, 'system') RETURNING id INTO bank;+ INSERT INTO customer (name, "companyId", "createdBy") VALUES ('Authz customer', company_a, 'system')+ RETURNING id INTO customer_a;+ INSERT INTO payment ("paymentId", "paymentType", "customerId", "paymentDate", "currencyCode", "totalAmount", "bankAccount", "companyId", "createdBy", status)+ VALUES ('AUTHZ-D-' || id(), 'Receipt', customer_a, '2026-09-01', 'USD', 10, bank, company_a, 'system', 'Draft')+ RETURNING id INTO draft_payment;+ INSERT INTO payment ("paymentId", "paymentType", "customerId", "paymentDate", "currencyCode", "totalAmount", "bankAccount", "companyId", "createdBy", status)+ VALUES ('AUTHZ-P-' || id(), 'Receipt', customer_a, '2026-09-01', 'USD', 10, bank, company_a, 'system', 'Posted')+ RETURNING id INTO posted_payment;++ INSERT INTO note ("documentId", note, "companyId", "createdBy") VALUES ('doc', 'hello', company_a, u)+ RETURNING id INTO note_id;+ INSERT INTO "tableView" (name, "table", "companyId", "createdBy") VALUES ('mine', 'item', company_a, u)+ RETURNING id INTO view_id;+ INSERT INTO "userAttributeCategory" (name, "companyId", "createdBy") VALUES ('Skills', company_a, 'system')+ RETURNING id INTO category_a;+ INSERT INTO "userAttributeCategory" (name, "companyId", "createdBy") VALUES ('Skills', company_b, 'system')+ RETURNING id INTO category_b;+ INSERT INTO "userAttribute" (name, "userAttributeCategoryId", "attributeDataTypeId", "canSelfManage", "createdBy")+ VALUES ('Welding', category_a, 1, true, 'system') RETURNING id INTO attribute_a;+ INSERT INTO "userAttribute" (name, "userAttributeCategoryId", "attributeDataTypeId", "canSelfManage", "createdBy")+ VALUES ('Clearance', category_a, 1, false, 'system') RETURNING id INTO attribute_locked;+ INSERT INTO "userAttribute" (name, "userAttributeCategoryId", "attributeDataTypeId", "canSelfManage", "createdBy")+ VALUES ('Welding', category_b, 1, true, 'system') RETURNING id INTO attribute_b;++ -- ── The deprecated permission helpers stay dropped (audit H3, then retired) ──+ -- They admitted customer and supplier portal accounts; nothing may bring them back.+ ASSERT NOT EXISTS (+ SELECT 1 FROM pg_proc+ WHERE pronamespace = 'public'::regnamespace+ AND proname IN ('has_role', 'has_company_permission', 'get_companies_with_permission', 'get_permission_companies')+ ), 'a deprecated RLS helper exists again';+ RAISE NOTICE 'PASS deprecated permission helpers are gone';+ PERFORM pg_temp.act_as(u);+ SET LOCAL ROLE authenticated;++ -- ── userToCompany: an admin cannot attach another user to their company ──+ BEGIN+ INSERT INTO "userToCompany" ("userId", "companyId", role) VALUES (v, company_a, 'employee');+ RAISE EXCEPTION 'an admin attached another user to their company through the API';+ EXCEPTION WHEN insufficient_privilege THEN NULL;+ END;+ RAISE NOTICE 'PASS memberships cannot be written through the API';++ -- ── Owner-only rows: the author edits, but cannot move the row into another company ──+ UPDATE note SET note = 'edited' WHERE id = note_id;+ GET DIAGNOSTICS n = ROW_COUNT;+ ASSERT n = 1, 'the author can still edit their note';+ BEGIN+ -- No WHERE: a filtered UPDATE also checks the new row against the SELECT policy, which+ -- already refuses company B. The unfiltered form meets only the UPDATE policy.+ UPDATE note SET "companyId" = company_b;+ RAISE EXCEPTION 'a note was moved into another company';+ EXCEPTION WHEN insufficient_privilege THEN NULL;+ END;+ BEGIN+ UPDATE "tableView" SET "companyId" = company_b WHERE id = view_id;+ RAISE EXCEPTION 'a table view was moved into another company';+ EXCEPTION WHEN insufficient_privilege THEN NULL;+ END;+ ASSERT pg_temp.allows('maintenanceDispatchComment', 'UPDATE', 'check',+ jsonb_build_object('createdBy', u, 'companyId', company_a)),+ 'the author can still edit their dispatch comment';+ ASSERT NOT pg_temp.allows('maintenanceDispatchComment', 'UPDATE', 'check',+ jsonb_build_object('createdBy', u, 'companyId', company_b)),+ 'a dispatch comment cannot be moved into another company';+ ASSERT NOT pg_temp.allows('maintenanceDispatchComment', 'UPDATE', 'using',+ jsonb_build_object('createdBy', w, 'companyId', company_a)),+ 'only the author edits a dispatch comment';+ RAISE NOTICE 'PASS owner-only rows stay in their company';++ -- ── invoiceSettlement: writable while its payment is Draft, not once Posted ──+ ASSERT pg_temp.allows('invoiceSettlement', 'UPDATE', 'using',+ jsonb_build_object('paymentId', draft_payment, 'companyId', company_a)),+ 'a settlement of a Draft payment is editable';+ ASSERT NOT pg_temp.allows('invoiceSettlement', 'UPDATE', 'using',+ jsonb_build_object('paymentId', posted_payment, 'companyId', company_a)),+ 'a settlement of a Posted payment is not editable';+ RAISE NOTICE 'PASS settlements follow their payment''s status';++ -- ── maintenanceDispatchItemTrackedEntity: resources_update can update ──+ ASSERT pg_temp.allows('maintenanceDispatchItemTrackedEntity', 'UPDATE', 'using',+ jsonb_build_object('companyId', company_a)),+ 'resources_update can update a dispatch item''s tracked entity';+ RAISE NOTICE 'PASS maintenance dispatch tracked entities use the resources permission';+ RESET ROLE;++ -- ── userAttributeValue: an employee with no resources permission at all saves their own+ -- value for a self-managed attribute of their own company, and nothing else ──+ PERFORM pg_temp.act_as(w);+ SET LOCAL ROLE authenticated;+ ASSERT (SELECT count(*) FROM "userAttribute" WHERE id = attribute_a) = 1,+ 'an employee sees the attributes they manage themselves';+ ASSERT (SELECT count(*) FROM "userAttribute" WHERE id IN (attribute_locked, attribute_b)) = 0,+ 'but not other attributes, nor another company''s';+ INSERT INTO "userAttributeValue" ("userAttributeId", "userId", "valueBoolean", "createdBy")+ VALUES (attribute_a, w, true, w);+ BEGIN+ INSERT INTO "userAttributeValue" ("userAttributeId", "userId", "valueBoolean", "createdBy")+ VALUES (attribute_b, w, true, w);+ RAISE EXCEPTION 'a value was attached to another company''s attribute';+ EXCEPTION WHEN insufficient_privilege THEN NULL;+ END;+ BEGIN+ INSERT INTO "userAttributeValue" ("userAttributeId", "userId", "valueBoolean", "createdBy")+ VALUES (attribute_locked, w, true, w);+ RAISE EXCEPTION 'a user set their own value for an attribute that is not self-managed';+ EXCEPTION WHEN insufficient_privilege THEN NULL;+ END;+ BEGIN+ INSERT INTO "userAttributeValue" ("userAttributeId", "userId", "valueBoolean", "createdBy")+ VALUES (attribute_a, v, true, w);+ RAISE EXCEPTION 'a plain employee set another user''s value';+ EXCEPTION WHEN insufficient_privilege THEN NULL;+ END;+ ASSERT pg_temp.allows('userAttributeValue', 'DELETE', 'using',+ jsonb_build_object('userAttributeId', attribute_a, 'userId', w)),+ 'a user can clear their own self-managed value';+ ASSERT NOT pg_temp.allows('userAttributeValue', 'DELETE', 'using',+ jsonb_build_object('userAttributeId', attribute_a, 'userId', v)),+ 'a plain employee cleared another user''s value';+ ASSERT NOT pg_temp.allows('userAttributeValue', 'DELETE', 'using',+ jsonb_build_object('userAttributeId', attribute_locked, 'userId', w)),+ 'a user cleared their own value of an attribute that is not self-managed';+ RESET ROLE;+ PERFORM pg_temp.act_as(c);+ SET LOCAL ROLE authenticated;+ BEGIN+ INSERT INTO "userAttributeValue" ("userAttributeId", "userId", "valueBoolean", "createdBy")+ VALUES (attribute_a, c, true, c);+ RAISE EXCEPTION 'a customer-portal account set a self-managed employee attribute';+ EXCEPTION WHEN insufficient_privilege THEN NULL;+ END;+ RAISE NOTICE 'PASS users save and clear their own attribute values, only in their own company';+ RESET ROLE;++ -- ── get_company_id_from_foreign_key: refused as an API endpoint, fine inside a query ──+ PERFORM set_config('request.jwt.claims', jsonb_build_object('role', 'anon')::text, true);+ PERFORM set_config('request.path', '/rpc/get_company_id_from_foreign_key', true);+ SET LOCAL ROLE anon;+ BEGIN+ PERFORM get_company_id_from_foreign_key(note_id, 'note');+ RAISE EXCEPTION 'get_company_id_from_foreign_key answered a direct API call';+ EXCEPTION WHEN insufficient_privilege THEN NULL;+ END;+ PERFORM set_config('request.path', '/rpc/Get_Company_Id_From_Foreign_Key/', true);+ BEGIN+ PERFORM get_company_id_from_foreign_key(note_id, 'note');+ RAISE EXCEPTION 'get_company_id_from_foreign_key answered a direct API call spelled differently';+ EXCEPTION WHEN insufficient_privilege THEN NULL;+ END;+ RESET ROLE;+ PERFORM set_config('request.path', '/test', true);+ ASSERT get_company_id_from_foreign_key(note_id, 'note') = company_a,+ 'inside an ordinary request the helper still resolves the company';+ RAISE NOTICE 'PASS get_company_id_from_foreign_key is not an API endpoint';+END+$proof$;++ROLLBACK;diff --git a/packages/database/supabase/tests/authz-pieces.test.sql b/packages/database/supabase/tests/authz-pieces.test.sqlnew file mode 100644index 0000000000..6dc3100f76--- /dev/null+++ b/packages/database/supabase/tests/authz-pieces.test.sql@@ -0,0 +1,159 @@+-- One behaviour check per rule piece in packages/database/src/authz/rules.ts, on a real table+-- that uses it: who is let in, who is kept out. The converter proved rewritten policies mean+-- the same as the ones they replaced; this proves what that meaning is.+-- Run from the repository root against an existing local database:+-- pnpm exec tsx scripts/run-local-accounting-check.ts psql -X -v ON_ERROR_STOP=1 -f packages/database/supabase/tests/authz-pieces.test.sql+-- All fixtures and role changes are confined to the rolled-back transaction.+\set ON_ERROR_STOP on+BEGIN;+SET LOCAL "app.sync_in_progress" = 'true';+SET LOCAL statement_timeout = '30s';++-- The live policy (USING, or WITH CHECK — which an UPDATE without one takes from USING) of+-- one command, evaluated against a synthetic row as the current role.+CREATE FUNCTION pg_temp.allows(tbl text, command text, clause text, rec jsonb)+RETURNS boolean LANGUAGE plpgsql AS $fn$+DECLARE expr text; ok boolean;+BEGIN+ SELECT CASE clause WHEN 'check' THEN coalesce(with_check, qual) ELSE qual END INTO expr+ FROM pg_policies WHERE schemaname = 'public' AND tablename = tbl AND cmd = command;+ IF expr IS NULL THEN RETURN false; END IF;+ EXECUTE format('SELECT (%s) FROM jsonb_populate_record(NULL::public.%I, $1) AS %I', expr, tbl, tbl)+ INTO ok USING rec;+ RETURN coalesce(ok, false);+END;+$fn$;++CREATE FUNCTION pg_temp.act_as(user_id text) RETURNS void LANGUAGE plpgsql AS $fn$+BEGIN+ RESET ROLE;+ PERFORM set_config('request.jwt.claims', jsonb_build_object('sub', user_id, 'role', 'authenticated')::text, true);+ PERFORM set_config('request.path', '/test', true);+ SET LOCAL ROLE authenticated;+END;+$fn$;++DO $proof$+DECLARE+ group_a text; group_b text; company_a text; company_b text;+ u text := gen_random_uuid()::text; -- employee of A with permissions (some naming B)+ w text := gen_random_uuid()::text; -- employee of A, no permissions+ v text := gen_random_uuid()::text; -- employee of B only+ c text := gen_random_uuid()::text; -- customer-portal user of A, bound to customer_a+ customer_a text; customer_other text; customer_b text;+ a jsonb; b jsonb;+BEGIN+ INSERT INTO "companyGroup" (name, "createdBy") VALUES ('Pieces A ' || id(), 'system') RETURNING id INTO group_a;+ INSERT INTO "companyGroup" (name, "createdBy") VALUES ('Pieces B ' || id(), 'system') RETURNING id INTO group_b;+ INSERT INTO company (name, "companyGroupId", "baseCurrencyCode", timezone)+ VALUES ('Pieces A', group_a, 'USD', 'America/New_York') RETURNING id INTO company_a;+ INSERT INTO company (name, "companyGroupId", "baseCurrencyCode", timezone)+ VALUES ('Pieces B', group_b, 'USD', 'America/New_York') RETURNING id INTO company_b;++ INSERT INTO "user" (id, email) VALUES+ (u, u || '@authz.invalid'), (w, w || '@authz.invalid'),+ (v, v || '@authz.invalid'), (c, c || '@authz.invalid');+ INSERT INTO "userToCompany" ("userId", "companyId", role) VALUES+ (u, company_a, 'employee'), (w, company_a, 'employee'),+ (v, company_b, 'employee'), (c, company_a, 'customer');+ INSERT INTO "userPermission" (id, permissions) VALUES+ (u, jsonb_build_object(+ 'accounting_update', jsonb_build_array(company_a, company_b), -- B: not a member there+ 'parts_view', jsonb_build_array(company_a),+ 'sales_update', jsonb_build_array(company_a)+ )),+ (w, '{}'::jsonb), (v, '{}'::jsonb), (c, '{}'::jsonb);++ INSERT INTO customer (name, "readableId", "companyId", "createdBy") VALUES ('Pieces customer', 'customer_a', company_a, 'system')+ RETURNING id INTO customer_a;+ INSERT INTO customer (name, "readableId", "companyId", "createdBy") VALUES ('Pieces other', 'customer_other', company_a, 'system')+ RETURNING id INTO customer_other;+ INSERT INTO customer (name, "readableId", "companyId", "createdBy") VALUES ('Pieces customer B', 'customer_b', company_b, 'system')+ RETURNING id INTO customer_b;+ INSERT INTO "customerAccount" (id, "customerId", "companyId", active) VALUES (c, customer_a, company_a, true);++ a := jsonb_build_object('companyId', company_a, 'companyGroupId', group_a);+ b := jsonb_build_object('companyId', company_b, 'companyGroupId', group_b);++ -- inCompany(employee): any employee reads their own company's rows (costCenter)+ PERFORM pg_temp.act_as(u);+ ASSERT pg_temp.allows('costCenter', 'SELECT', 'using', a), 'employee reads own company';+ ASSERT NOT pg_temp.allows('costCenter', 'SELECT', 'using', b), 'employee does not read another company';+ PERFORM pg_temp.act_as(c);+ ASSERT NOT pg_temp.allows('costCenter', 'SELECT', 'using', a), 'a customer-portal user is not an employee';+ RAISE NOTICE 'PASS inCompany(employee)';++ -- inCompany(permission): the permission, in a company the caller belongs to (costCenter)+ PERFORM pg_temp.act_as(u);+ ASSERT pg_temp.allows('costCenter', 'UPDATE', 'using', a), 'permission holder updates';+ ASSERT pg_temp.allows('costCenter', 'UPDATE', 'check', a), 'the updated row may stay in the company';+ ASSERT NOT pg_temp.allows('costCenter', 'UPDATE', 'check', b), 'a permission naming a company the user is not in grants nothing';+ PERFORM pg_temp.act_as(w);+ ASSERT NOT pg_temp.allows('costCenter', 'UPDATE', 'using', a), 'an employee without the permission cannot update';+ RAISE NOTICE 'PASS inCompany(permission)';++ -- anyOf: any one of the permissions (costLedger: accounting_view or parts_view)+ PERFORM pg_temp.act_as(u);+ ASSERT pg_temp.allows('costLedger', 'SELECT', 'using', a), 'one of the permissions is enough';+ PERFORM pg_temp.act_as(w);+ ASSERT NOT pg_temp.allows('costLedger', 'SELECT', 'using', a), 'none of the permissions is not';+ RAISE NOTICE 'PASS anyOf';++ -- inGroup: group-shared rows by the caller's company group (currency)+ PERFORM pg_temp.act_as(u);+ ASSERT pg_temp.allows('currency', 'SELECT', 'using', a), 'employee reads own group';+ ASSERT NOT pg_temp.allows('currency', 'SELECT', 'using', b), 'employee does not read another group';+ RAISE NOTICE 'PASS inGroup';++ -- through + member: a row reached through a link table (companyGroup via company, member)+ ASSERT pg_temp.allows('companyGroup', 'SELECT', 'using', jsonb_build_object('id', group_a)), 'member reads own group';+ ASSERT NOT pg_temp.allows('companyGroup', 'SELECT', 'using', jsonb_build_object('id', group_b)), 'not another group';+ RAISE NOTICE 'PASS through / member';++ -- viaParent: the parent row's company decides (customerContact → customer)+ ASSERT pg_temp.allows('customerContact', 'UPDATE', 'using', jsonb_build_object('customerId', customer_a)),+ 'permission holder updates a child of their company''s parent';+ ASSERT NOT pg_temp.allows('customerContact', 'UPDATE', 'using', jsonb_build_object('customerId', customer_b)),+ 'not a child of another company''s parent';+ PERFORM pg_temp.act_as(w);+ ASSERT NOT pg_temp.allows('customerContact', 'UPDATE', 'using', jsonb_build_object('customerId', customer_a)),+ 'an employee without the permission cannot';+ RAISE NOTICE 'PASS viaParent';++ -- portal.customer: a portal user sees their own customer only (customer, customerContact)+ PERFORM pg_temp.act_as(c);+ ASSERT pg_temp.allows('customer', 'SELECT', 'using', jsonb_build_object('id', customer_a, 'companyId', company_a)),+ 'portal user reads their customer';+ ASSERT NOT pg_temp.allows('customer', 'SELECT', 'using', jsonb_build_object('id', customer_other, 'companyId', company_a)),+ 'not another customer of the same company';+ ASSERT pg_temp.allows('customerContact', 'UPDATE', 'using', jsonb_build_object('customerId', customer_a)),+ 'portal user updates their customer''s contacts';+ RAISE NOTICE 'PASS portal.customer';++ -- owner: the author only (note)+ PERFORM pg_temp.act_as(u);+ ASSERT pg_temp.allows('note', 'UPDATE', 'using', jsonb_build_object('createdBy', u, 'companyId', company_a)), 'author edits';+ PERFORM pg_temp.act_as(w);+ ASSERT NOT pg_temp.allows('note', 'UPDATE', 'using', jsonb_build_object('createdBy', u, 'companyId', company_a)),+ 'a colleague does not';+ RAISE NOTICE 'PASS owner';++ -- authenticated: any signed-in user reads reference data (country); anon does not+ ASSERT pg_temp.allows('country', 'SELECT', 'using', '{}'::jsonb), 'signed-in user reads';+ RESET ROLE;+ PERFORM set_config('request.jwt.claims', jsonb_build_object('role', 'anon')::text, true);+ SET LOCAL ROLE anon;+ ASSERT NOT pg_temp.allows('country', 'SELECT', 'using', '{}'::jsonb), 'anon does not';+ RAISE NOTICE 'PASS authenticated';++ -- serviceOnly: no policy, so nobody through the API (approvalRequest)+ PERFORM pg_temp.act_as(u);+ ASSERT NOT pg_temp.allows('approvalRequest', 'SELECT', 'using', a), 'no API access';+ ASSERT (SELECT relrowsecurity FROM pg_class WHERE oid = 'public."approvalRequest"'::regclass),+ 'RLS is on, so no policy means no rows';+ RAISE NOTICE 'PASS serviceOnly';+ RESET ROLE;+END+$proof$;++ROLLBACK;diff --git a/packages/database/supabase/tests/journal-update-tenant-check.test.sql b/packages/database/supabase/tests/journal-update-tenant-check.test.sqlnew file mode 100644index 0000000000..9caf78119e--- /dev/null+++ b/packages/database/supabase/tests/journal-update-tenant-check.test.sql@@ -0,0 +1,86 @@+-- Run from the repository root against an existing local database:+-- pnpm exec tsx scripts/run-local-accounting-check.ts psql -X -v ON_ERROR_STOP=1 -f packages/database/supabase/tests/journal-update-tenant-check.test.sql+-- All fixtures and role changes are confined to the rolled-back transaction.+\set ON_ERROR_STOP on+BEGIN;+SET LOCAL "app.sync_in_progress" = 'true';+SET LOCAL statement_timeout = '30s';++DO $proof$+DECLARE+ group_a text; group_b text; company_a text; company_b text;+ user_id text := gen_random_uuid()::text;+ cash_id text; sales_id text; draft_id text; posted_id text; moved int;+BEGIN+ INSERT INTO "companyGroup" (name,"createdBy") VALUES ('Journal tenant A '||id(),'system') RETURNING id INTO group_a;+ INSERT INTO "companyGroup" (name,"createdBy") VALUES ('Journal tenant B '||id(),'system') RETURNING id INTO group_b;+ INSERT INTO company (name,"companyGroupId","baseCurrencyCode",timezone)+ VALUES ('Journal tenant A',group_a,'USD','America/New_York') RETURNING id INTO company_a;+ INSERT INTO company (name,"companyGroupId","baseCurrencyCode",timezone)+ VALUES ('Journal tenant B',group_b,'USD','America/New_York') RETURNING id INTO company_b;+ INSERT INTO account (name,class,"incomeBalance","isGroup","companyGroupId","createdBy")+ VALUES ('Cash','Asset','Balance Sheet',false,group_a,'system') RETURNING id INTO cash_id;+ INSERT INTO account (name,class,"incomeBalance","isGroup","companyGroupId","createdBy")+ VALUES ('Sales','Revenue','Income Statement',false,group_a,'system') RETURNING id INTO sales_id;+ INSERT INTO "accountingPeriod" ("startDate","endDate",status,"companyId","createdBy","fiscalYear","periodNumber")+ VALUES ('2026-07-01','2026-07-31','Active',company_a,'system',2026,7);++ INSERT INTO "user" (id,email) VALUES (user_id, user_id||'@journal-tenant.invalid');+ -- Employee of both companies: may view B's journals but update only A's. Postgres+ -- checks an UPDATE's new row against the SELECT policy too, so a user who cannot+ -- see B was never able to move a journal there; this user can see B.+ INSERT INTO "userToCompany" ("userId","companyId",role)+ VALUES (user_id,company_a,'employee'),(user_id,company_b,'employee');+ INSERT INTO "userPermission" (id,permissions)+ VALUES (user_id,jsonb_build_object(+ 'accounting_view',jsonb_build_array(company_a,company_b),+ 'accounting_update',jsonb_build_array(company_a)));++ INSERT INTO journal ("journalEntryId","companyId","postingDate",status,"sourceType","createdBy")+ VALUES ('TENANT-DRAFT-'||id(),company_a,'2026-07-15','Draft','Manual','system') RETURNING id INTO draft_id;+ PERFORM set_config('request.jwt.claims',jsonb_build_object('sub',user_id,'role','authenticated')::text,true);+ SET LOCAL ROLE authenticated;++ UPDATE journal SET description='edited' WHERE id=draft_id;+ GET DIAGNOSTICS moved = ROW_COUNT;+ ASSERT moved = 1, 'A Draft journal in the caller''s company stays editable';++ BEGIN+ UPDATE journal SET "companyId"=company_b WHERE id=draft_id;+ RAISE EXCEPTION 'A Draft journal was moved into another company';+ EXCEPTION WHEN insufficient_privilege THEN NULL;+ END;+ -- No WHERE: the statement reads no columns, so the SELECT policy is not applied+ -- to the new rows and only the UPDATE policy's WITH CHECK stands in the way.+ BEGIN+ UPDATE journal SET "companyId"=company_b;+ RAISE EXCEPTION 'Journals were moved into another company by an unfiltered update';+ EXCEPTION WHEN insufficient_privilege THEN NULL;+ END;+ RAISE NOTICE 'PASS a Draft journal cannot be moved into another company';+ RESET ROLE;++ -- Posted only now: the unfiltered update above must meet Draft rows alone, since the+ -- immutability trigger fires before the policy check.+ INSERT INTO journal ("journalEntryId","companyId","postingDate",status,"sourceType","createdBy")+ VALUES ('TENANT-POSTED-'||id(),company_a,'2026-07-15','Draft','Manual','system') RETURNING id INTO posted_id;+ INSERT INTO "journalLine" ("journalId","accountId",amount,"journalLineReference","companyId")+ VALUES (posted_id,cash_id,10,id(),company_a),(posted_id,sales_id,10,id(),company_a);+ UPDATE journal SET status='Posted' WHERE id=posted_id AND "companyId"=company_a;+ SET LOCAL ROLE authenticated;++ BEGIN+ UPDATE journal SET status='Reversed', "companyId"=company_b WHERE id=posted_id;+ RAISE EXCEPTION 'A reversed journal was moved into another company';+ EXCEPTION WHEN insufficient_privilege THEN NULL;+ END;++ UPDATE journal SET status='Reversed' WHERE id=posted_id;+ GET DIAGNOSTICS moved = ROW_COUNT;+ ASSERT moved = 1, 'Posted -> Reversed still passes the policy';+ RAISE NOTICE 'PASS Posted -> Reversed works in-company and cannot cross companies';+ RESET ROLE;+END+$proof$;++ROLLBACK;diff --git a/packages/database/supabase/tests/rpc-privileges.test.sql b/packages/database/supabase/tests/rpc-privileges.test.sqlindex caf6cbeac4..e15ad6ecb8 100644--- a/packages/database/supabase/tests/rpc-privileges.test.sql+++ b/packages/database/supabase/tests/rpc-privileges.test.sql@@ -68,8 +68,7 @@ BEGINRAISE EXCEPTION 'FAIL: event interceptors callable through the API as the owner: %', definer_interceptors;END IF;- IF (SELECT prosecdef FROM pg_proc WHERE oid = 'create_rfq_from_model_v1(text,text,text,text,text,text,json)'::regprocedure)- OR (SELECT prosecdef FROM pg_proc WHERE oid = 'backflush_job_materials(text,numeric,text,text)'::regprocedure)+ IF (SELECT prosecdef FROM pg_proc WHERE oid = 'backflush_job_materials(text,numeric,text,text)'::regprocedure)OR NOT (SELECT prosecdef FROM pg_proc WHERE oid = 'dispatch_event_interceptors()'::regprocedure)OR NOT (SELECT prosecdef FROM pg_proc WHERE oid = 'dispatch_event_after_interceptors()'::regprocedure) THENRAISE EXCEPTION 'FAIL: internal functions or dispatchers have the wrong security mode';diff --git a/packages/dev/src/commands/migrate.ts b/packages/dev/src/commands/migrate.tsindex 9816e0b46b..5f01bbcdac 100644--- a/packages/dev/src/commands/migrate.ts+++ b/packages/dev/src/commands/migrate.ts@@ -14,6 +14,7 @@ import {import {applyMigrations,ensureConfigRow,+ syncAuthz,waitForPostgres} from "../services/migrations.js";import { branchToPrefix } from "../services/portless.js";@@ -109,7 +110,11 @@ async function migrateAgainstRunningDb(}}]- : [])+ : []),+ {+ title: "Sync RLS policies with the authz manifest",+ task: () => syncAuthz(root, portDb)+ }]);outro("done");}@@ -190,7 +195,11 @@ async function migrateStandalone(}}]- : [])+ : []),+ {+ title: "Sync RLS policies with the authz manifest",+ task: () => syncAuthz(root, portDb)+ }]);if (shouldRegen) {diff --git a/packages/dev/src/commands/restore.ts b/packages/dev/src/commands/restore.tsindex cba4f7bfe2..4e2fb24450 100644--- a/packages/dev/src/commands/restore.ts+++ b/packages/dev/src/commands/restore.ts@@ -7,7 +7,8 @@ import { requireNumberEnv, tryConnect } from "../helpers.js";import { confirmRestore } from "../prompts.js";import {applyMigrations,- serviceSchemasReady+ serviceSchemasReady,+ syncAuthz} from "../services/migrations.js";import { getWorktreeRoot } from "../worktree.js";@@ -169,6 +170,16 @@ async function runRestore(}}]+ : []),+ ...(shouldMigrate+ ? [+ {+ // The snapshot carries the source environment's policies; the+ // manifest is what this branch expects.+ title: "Sync RLS policies with the authz manifest",+ task: () => syncAuthz(root, portDb)+ }+ ]: [])]);diff --git a/packages/dev/src/commands/up.ts b/packages/dev/src/commands/up.tsindex e14a69daf3..a521e93205 100644--- a/packages/dev/src/commands/up.ts+++ b/packages/dev/src/commands/up.ts@@ -38,6 +38,7 @@ import {applyMigrations,ensureConfigRow,ensureSmokeTestUser,+ syncAuthz,waitForPostgres,waitForStorageReady,waitForTcp@@ -610,6 +611,14 @@ async function runDatabaseMigrations(}}]+ : []),+ ...(cfg.shouldMigrate+ ? [+ {+ title: "Sync RLS policies with the authz manifest",+ task: () => syncAuthz(ctx.root, ctx.ports.PORT_DB)+ }+ ]: [])]);}diff --git a/packages/dev/src/services/migrations.ts b/packages/dev/src/services/migrations.tsindex 804f1d7439..2a4bf03ad8 100644--- a/packages/dev/src/services/migrations.ts+++ b/packages/dev/src/services/migrations.ts@@ -182,6 +182,34 @@ export async function applyMigrations(return { applied: didApplyMigrations(r) };}+// Make every table's RLS policies match packages/database/src/authz/manifest.ts — the+// one place policies are authored; migrations only create tables. Callers run it after+// migrations (which create the tables) and after type regen, so a manifest problem+// fails loudly without leaving the generated types stale.+export async function syncAuthz(root: string, dbPort: number): Promise<string> {+ const r = await execa(+ "pnpm",+ ["--silent", "--filter", "@carbon/database", "run", "authz", "sync"],+ {+ cwd: root,+ reject: false,+ env: {+ ...process.env,+ SUPABASE_DB_URL: `postgresql://supabase_admin:postgres@localhost:${dbPort}/postgres`+ }+ }+ );+ if (r.exitCode !== 0) {+ process.stderr.write(r.stderr?.toString() ?? "");+ process.stdout.write(r.stdout?.toString() ?? "");+ throw new Error(+ "authz sync failed: fix packages/database/src/authz/manifest.ts, then migrate again"+ );+ }+ const counts = (r.stdout ?? "").match(/changed \d+ (helper|table)\(s\)/g);+ return counts?.join(", ") ?? "policies in sync";+}+// supabase prints "Applying migration <ts>_<name>.sql..." per applied// migration — on STDERR (stdout says "Local database is up to date." even// while applying), so both streams must be checked.diff --git a/packages/files/AGENTS.md b/packages/files/AGENTS.mdindex 5876e88a08..587ec89d0c 100644--- a/packages/files/AGENTS.md+++ b/packages/files/AGENTS.md@@ -66,7 +66,11 @@ export to `package.json`, and add a row above. Don't pre-create empty slots —run picked files through `MediaUploader.prepareForUpload` first — never upload apicked `File` raw.- Serve files with `getContentType(effectiveExtension(path))` — never a local- MIME map.+ MIME map — and build the response headers with `fileResponseHeaders(type,+ cacheControl)`. Stored bytes are served from the app origin under a name the+ uploader chose: without it an uploaded SVG ran script as whoever opened the+ link (it adds `nosniff`, and for SVG/+xml/HTML `attachment` + a sandbox CSP).+ The public `file/model/public` route serves `.glb` only — it has no session.- Read PDFs through `./pdf` only. Never import `pdfjs-dist` or `pdfjs` from`react-pdf` at a call site — `react-pdf`'s `<Document>`/`<Page>` are the onlythings app code takes from that package.diff --git a/packages/files/src/index.ts b/packages/files/src/index.tsindex 715d4be435..e74fc41551 100644--- a/packages/files/src/index.ts+++ b/packages/files/src/index.ts@@ -4,6 +4,7 @@ export type { DocumentType, PreviewableDocumentType } from "./media/media";export {documentTypes,effectiveExtension,+ fileResponseHeaders,getContentType,getDocumentType,getFileExtension,diff --git a/packages/files/src/media/media.test.ts b/packages/files/src/media/media.test.tsindex e357152c71..3b604d4564 100644--- a/packages/files/src/media/media.test.ts+++ b/packages/files/src/media/media.test.ts@@ -1,6 +1,30 @@import { describe, expect, it } from "vitest";import { findDuplicateFileName } from "./image";-import { effectiveExtension, getDocumentType, isHeic } from "./media";+import {+ effectiveExtension,+ fileResponseHeaders,+ getContentType,+ getDocumentType,+ isHeic+} from "./media";++describe("fileResponseHeaders", () => {+ it("never renders a scriptable type as a page", () => {+ for (const type of [getContentType("svg"), getContentType("dae")]) {+ const headers = fileResponseHeaders(type, "private");+ expect(headers.get("Content-Disposition")).toBe("attachment");+ expect(headers.get("Content-Security-Policy")).toContain("sandbox");+ expect(headers.get("X-Content-Type-Options")).toBe("nosniff");+ }+ });+ it("leaves inert types inline, but never sniffed", () => {+ for (const ext of ["pdf", "png", "glb", "mp4"]) {+ const headers = fileResponseHeaders(getContentType(ext), "private");+ expect(headers.get("Content-Disposition")).toBeNull();+ expect(headers.get("X-Content-Type-Options")).toBe("nosniff");+ }+ });+});describe("effectiveExtension", () => {it("unwraps the .zst compaction suffix to the underlying format", () => {diff --git a/packages/files/src/media/media.ts b/packages/files/src/media/media.tsindex 488de80615..73765bfefa 100644--- a/packages/files/src/media/media.ts+++ b/packages/files/src/media/media.ts@@ -90,6 +90,35 @@ export function getContentType(extension: string): string {);}+// A type the browser renders as a document that can run script: SVG and every+// other +xml, HTML, JS.+const ACTIVE_CONTENT = /html|xml|script/i;++/**+ * Headers for stored bytes served from the app origin. The type comes from a+ * file name the uploader chose, so it is never sniffed, and a type that can run+ * script (an uploaded SVG) is a download and a sandbox, never a page on our+ * origin. `<img src>` still renders an SVG: it ignores both headers.+ */+export function fileResponseHeaders(+ contentType: string,+ cacheControl: string+): Headers {+ const headers = new Headers({+ "Content-Type": contentType,+ "Cache-Control": cacheControl,+ "X-Content-Type-Options": "nosniff"+ });+ if (ACTIVE_CONTENT.test(contentType)) {+ headers.set("Content-Disposition", "attachment");+ headers.set(+ "Content-Security-Policy",+ "default-src 'none'; style-src 'unsafe-inline'; sandbox"+ );+ }+ return headers;+}+export function isHeic(fileName: string, mimeType?: string | null): boolean {const extension = getFileExtension(fileName);return (diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.jsonindex e3ffcb643b..23c237359d 100644--- a/packages/jobs/manifests/schema.json+++ b/packages/jobs/manifests/schema.json@@ -1,11 +1,11 @@{"kind": "carbon-company-backup","version": 1,- "schemaVersion": "20260926141957",+ "schemaVersion": "20260927230425","sourceCompanyId": "schema-baseline","sourceCompanyGroupId": null,"sourceCompanyName": null,- "exportedAt": "2026-09-26T15:44:17.303Z",+ "exportedAt": "2026-09-27T23:05:53.317Z","exportedBy": "schema-baseline","label": "schema baseline","includeStorage": "none",@@ -14,23 +14,23 @@"name": "account","rows": 0,"columns": [+ "class","incomeBalance",- "updatedAt",- "createdBy",- "number","consolidatedRate",- "id","active",- "isSystem",- "name","createdAt",- "companyGroupId",- "tags",- "updatedBy",- "isGroup",+ "updatedAt","customFields",+ "isGroup","accountType",- "class",+ "isSystem",+ "id",+ "number",+ "name",+ "createdBy",+ "updatedBy",+ "tags",+ "companyGroupId","parentId"]},@@ -38,83 +38,83 @@"name": "accountDefault","rows": 0,"columns": [- "bankForeignCurrencyAccount",- "materialVarianceAccount",- "realizedExchangeGainAccount",- "accumulatedDepreciationOnDisposalAccount",- "purchaseVarianceAccount",- "realizedExchangeLossAccount",- "overheadVarianceAccount",- "salesShippingRevenueAccount",+ "companyId","salesAccount",- "prepaymentAccount",- "retainedEarningsAccount",+ "salesDiscountAccount",+ "costOfGoodsSoldAccount",+ "purchaseVarianceAccount",+ "inventoryAdjustmentVarianceAccount",+ "materialVarianceAccount",+ "laborAndMachineVarianceAccount",+ "indirectCostAccount","maintenanceAccount",- "supplierWriteOffAccount",- "goodsReceivedNotInvoicedAccount",+ "assetDepreciationExpenseAccount","serviceChargeAccount",- "laborAbsorptionAccount",- "updatedBy",+ "interestAccount",+ "supplierPaymentDiscountAccount",+ "customerPaymentDiscountAccount",+ "roundingAccount",+ "assetAquisitionCostAccount",+ "assetAquisitionCostOnDisposalAccount",+ "accumulatedDepreciationAccount",+ "accumulatedDepreciationOnDisposalAccount","workInProgressAccount",- "rawMaterialsAccount",- "laborAndMachineVarianceAccount",- "salesReturnsAccount",- "salesTaxPayableAccount",- "purchaseTaxPayableAccount",- "overheadAbsorptionAccount",- "deferredTaxLiabilityAccountId",- "assetLossOnDisposalAccount",- "finishedGoodsAccount",- "companyId",- "deferredTaxExpenseAccountId",- "inventoryAdjustmentVarianceAccount",- "bankLocalCurrencyAccount","receivablesAccount",- "accumulatedDepreciationAccount",- "intercompanyReceivablesAccount",+ "bankCashAccount",+ "bankLocalCurrencyAccount",+ "bankForeignCurrencyAccount",+ "prepaymentAccount","payablesAccount",+ "salesTaxPayableAccount",+ "purchaseTaxPayableAccount","reverseChargeSalesTaxPayableAccount",- "supplierPaymentDiscountAccount",+ "retainedEarningsAccount",+ "updatedBy",+ "goodsReceivedNotInvoicedAccount",+ "overheadVarianceAccount",+ "lotSizeVarianceAccount",+ "subcontractingVarianceAccount","currencyTranslationAccount",- "customerPaymentDiscountAccount",+ "laborAbsorptionAccount",+ "deferredTaxLiabilityAccountId",+ "deferredTaxExpenseAccountId","customerWriteOffAccount",- "assetGainOnDisposalAccount",- "costOfGoodsSoldAccount",- "assetDepreciationExpenseAccount",- "salesDiscountAccount",- "interestAccount",+ "supplierWriteOffAccount",+ "realizedExchangeGainAccount",+ "realizedExchangeLossAccount",+ "intercompanyReceivablesAccount",+ "overheadAbsorptionAccount","supplierPrepaymentAccount",- "assetAquisitionCostAccount",+ "rawMaterialsAccount",+ "finishedGoodsAccount",+ "assetGainOnDisposalAccount",+ "assetLossOnDisposalAccount",+ "scrapAccount","intercompanyPayablesAccount",- "lotSizeVarianceAccount",- "roundingAccount",- "bankCashAccount",- "indirectCostAccount",- "subcontractingVarianceAccount",- "assetAquisitionCostOnDisposalAccount",- "scrapAccount"+ "salesShippingRevenueAccount",+ "salesReturnsAccount"]},{"name": "accountingPeriod","rows": 0,"columns": [- "companyId",- "closeStatus",- "lockedAt",- "status",- "periodNumber",+ "startDate","endDate",- "closedBy",- "id",+ "status",+ "closedAt","createdAt","updatedAt",- "closedAt",- "lockedBy",+ "closeStatus","fiscalYear",- "startDate",+ "periodNumber",+ "lockedAt",+ "id",+ "companyId",+ "closedBy","createdBy",- "updatedBy"+ "updatedBy",+ "lockedBy"]},{@@ -122,316 +122,316 @@"rows": 0,"columns": ["endingBalance",- "createdBy",- "accountId",- "accountingPeriodId","endingBalanceDate",- "id",- "updatedBy",- "updatedAt","createdAt",- "companyId"+ "updatedAt",+ "id",+ "companyId",+ "accountingPeriodId",+ "accountId",+ "createdBy",+ "updatedBy"]},{"name": "accountingSyncOperation","rows": 0,"columns": [- "entityId",- "updatedAt",+ "status",+ "attemptCount",+ "lastAttemptAt","completedAt",- "externalId",- "createdBy",- "entityType",- "errorMessage",- "integration",- "updatedBy",+ "metadata","createdAt",- "trigger",+ "updatedAt","id",- "idempotencyKey",- "lastAttemptAt",+ "companyId",+ "integration",+ "entityType",+ "entityId","direction",- "metadata",+ "trigger",+ "idempotencyKey","errorCode",- "companyId",- "status",- "attemptCount"+ "errorMessage",+ "externalId",+ "createdBy",+ "updatedBy"]},{"name": "accountingSyncTieOut","rows": 0,"columns": [- "integration",- "externalDelta",- "accountingPeriodId",- "updatedBy",- "updatedAt",+ "carbonPostedAmount","syncedAmount",- "providerAmount",- "accountId",- "createdAt",- "computedAt",- "createdBy",- "companyId",- "internalDelta","docBackedAmount",- "pendingAmount","excludedAmount",- "id",+ "pendingAmount","blockedAmount",- "carbonPostedAmount"+ "providerAmount",+ "internalDelta",+ "externalDelta",+ "computedAt",+ "createdAt",+ "updatedAt",+ "id",+ "companyId",+ "integration",+ "accountingPeriodId",+ "accountId",+ "createdBy",+ "updatedBy"]},{"name": "address","rows": 0,"columns": [+ "id",+ "addressLine1","addressLine2","city",- "countryCode","stateProvince",- "addressLine1",- "companyId",+ "postalCode",+ "countryCode","phone","fax",- "id",- "postalCode"+ "companyId"]},{"name": "agentThread","rows": 0,"columns": [- "companyId",+ "lastContext","createdAt","updatedAt",- "updatedBy","id",- "lastContext",+ "companyId","userId","title",+ "modelId","createdBy",- "modelId"+ "updatedBy"]},{"name": "agentMessage","rows": 0,"columns": [- "role",- "companyId",- "updatedAt",- "feedbackNote",- "createdAt","context",- "threadId",- "updatedBy",- "finishReason",+ "inputTokens","outputTokens",+ "createdAt",+ "updatedAt","id",- "inputTokens",+ "threadId",+ "companyId",+ "role",+ "feedback",+ "feedbackNote",+ "finishReason","createdBy",- "feedback"+ "updatedBy"]},{"name": "agentMessagePart","rows": 0,"columns": [- "createdBy",- "updatedBy",- "type",- "toolState",- "toolName",- "updatedAt",- "errorMessage",- "companyId","orderIndex",- "textContent",- "toolOutput",- "toolCallId",- "id","toolInput",- "toolClassification",+ "toolOutput","toolDurationMs",+ "createdAt",+ "updatedAt",+ "id","messageId",- "createdAt"+ "companyId",+ "type",+ "textContent",+ "toolName",+ "toolClassification",+ "toolCallId",+ "toolState",+ "errorMessage",+ "createdBy",+ "updatedBy"]},{"name": "approvalRequest","rows": 0,"columns": [- "requestedAt",- "documentId",- "createdAt",+ "documentType","status",- "updatedBy",- "companyId","amount",+ "requestedAt","decisionAt",- "documentType",- "createdBy",+ "createdAt","updatedAt",+ "id",+ "documentId","requestedBy",- "decisionNotes","decisionBy",- "id"+ "decisionNotes",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "approvalRule","rows": 0,"columns": [+ "documentType",+ "enabled","lowerBoundAmount",- "updatedBy",- "id",- "createdBy",+ "escalationDays","createdAt",- "companyId",- "documentType",- "defaultApproverId","updatedAt",- "escalationDays",+ "id","approverGroupIds",- "enabled"+ "defaultApproverId",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "auditLogArchive","rows": 0,"columns": [+ "startDate",+ "endDate","rowCount",- "id",+ "sizeBytes","createdAt",+ "id","companyId",- "endDate",- "sizeBytes",- "archivePath",- "startDate"+ "archivePath"]},{"name": "changeOrderRequiredAction","rows": 0,"columns": [- "updatedAt",- "companyId",+ "active","createdAt",+ "updatedAt","customFields","id",- "updatedBy",+ "companyId","name",- "active",- "createdBy"+ "createdBy",+ "updatedBy"]},{"name": "changeOrderType","rows": 0,"columns": [+ "createdAt","updatedAt","id","name",+ "companyId","createdBy",- "updatedBy",- "createdAt",- "companyId"+ "updatedBy"]},{"name": "companyAccountsPayableBillingAddress","rows": 0,"columns": [- "postalCode",- "addressLine2",- "addressLine1","updatedAt",- "city",- "fax",- "countryCode",+ "id","name",- "updatedBy",+ "addressLine1",+ "addressLine2",+ "city","state",+ "postalCode",+ "countryCode",+ "phone",+ "fax","email",- "id",- "phone"+ "updatedBy"]},{"name": "companyAccountsReceivableBillingAddress","rows": 0,"columns": [- "state",- "phone",+ "updatedAt","id",- "email",- "countryCode",- "fax",- "updatedBy","name",+ "addressLine1",+ "addressLine2","city",- "updatedAt",+ "state","postalCode",- "addressLine1",- "addressLine2"+ "countryCode",+ "phone",+ "fax",+ "email",+ "updatedBy"]},{"name": "companySettings","rows": 0,"columns": [- "allowLowercaseItemIds",- "useMetric",- "accountsPayableEmail",- "showCurrencyTrailingZeros",- "enforceInspectionFourEyes",- "updateLeadTimesOnReceipt",- "autoStartOperationTimer",- "salesJobCompletedNotificationGroup",- "includeOperationsOnTraveler",- "id",- "plmReleaseControl",- "showCustomerReadableId",- "productLabelSize","digitalQuoteEnabled",- "consoleEnabled",- "gaugeCalibrationExpiredNotificationGroup",- "inventoryShelfLife",- "incompletePickingListPolicy",+ "digitalQuoteIncludesPurchaseOrders","materialGeneratedIds",- "qualityIssueTarget",- "includeMaterialsOnTraveler",+ "useMetric",+ "kanbanOutput",+ "purchasePriceUpdateTiming","accountsPayableAddress","accountsReceivableAddress",- "inventoryJobCompletedNotificationGroup",- "accountingEnabled",- "returnPickedMaterialTiming",- "kanbanOutput","quoteLineCategoryMarkups",- "operationsDispatchNotificationGroup",- "rfqReadyNotificationGroup",- "assetTaxRate",- "defaultSupplierCc",- "otherDispatchNotificationGroup",- "supplierQuoteNotificationGroup",- "requireMfa",- "assetTaxDepreciationEnabled",- "maintenanceDispatchNotificationGroup",+ "qualityIssueTarget",+ "consoleEnabled",+ "timeCardEnabled",+ "printing",+ "updateLeadTimesOnReceipt",+ "enforceInspectionFourEyes","samplingStandard",- "qualityDispatchNotificationGroup",+ "inventoryShelfLife",+ "accountingEnabled",+ "assetTaxDepreciationEnabled",+ "assetTaxRate","showSupplierReadableId",+ "showCustomerReadableId",+ "autoStartOperationTimer","autoSelectMaterialWithoutPickingList",- "purchasePriceUpdateTiming",+ "includeMaterialsOnTraveler",+ "showCurrencyTrailingZeros",+ "requireMfa",+ "allowLowercaseItemIds",+ "includeOperationsOnTraveler",+ "id","digitalQuoteNotificationGroup",- "digitalQuoteIncludesPurchaseOrders",- "accountsReceivableEmail",+ "rfqReadyNotificationGroup",+ "productLabelSize","shelfLabelSize",- "timeCardEnabled",- "printing",+ "inventoryJobCompletedNotificationGroup",+ "salesJobCompletedNotificationGroup",+ "gaugeCalibrationExpiredNotificationGroup",+ "supplierQuoteNotificationGroup",+ "maintenanceDispatchNotificationGroup",+ "qualityDispatchNotificationGroup",+ "operationsDispatchNotificationGroup",+ "otherDispatchNotificationGroup",+ "defaultSupplierCc","defaultCustomerCc",+ "accountsPayableEmail",+ "accountsReceivableEmail",+ "plmReleaseControl",+ "incompletePickingListPolicy",+ "returnPickedMaterialTiming","salesRuleNotificationGroup"]},@@ -439,30 +439,30 @@"name": "companyUsage","rows": 0,"columns": [- "companyId",- "id",- "updatedAt","users",+ "tasks",+ "aiTokens","nextResetDatetime","createdAt",- "tasks",- "aiTokens"+ "updatedAt",+ "id",+ "companyId"]},{"name": "consumable","rows": 0,"columns": [- "tags",- "customFields","approved",+ "customFields",+ "createdAt",+ "updatedAt",+ "id","approvedBy",+ "companyId","createdBy","updatedBy",- "id",- "companyId",- "createdAt",- "updatedAt"+ "tags"]},{@@ -470,150 +470,150 @@"rows": 0,"columns": ["isCustomer",- "email",- "lastName",- "companyId",- "notes",- "mobilePhone",- "workPhone","id",- "title","firstName",+ "lastName",+ "email",+ "title",+ "mobilePhone","homePhone",- "fax"+ "workPhone",+ "fax",+ "notes",+ "companyId"]},{"name": "costCenter","rows": 0,"columns": [- "updatedAt",- "ownerId",- "name","createdAt",+ "updatedAt","customFields","id",- "updatedBy",+ "name","parentCostCenterId","companyId",- "createdBy"+ "createdBy",+ "updatedBy",+ "ownerId"]},{"name": "currency","rows": 0,"columns": [- "updatedAt",- "companyGroupId",- "createdBy",+ "decimalPlaces","active","createdAt",+ "updatedAt",+ "customFields",+ "historicalExchangeRate","id",- "decimalPlaces","code",- "customFields",+ "createdBy","updatedBy",- "historicalExchangeRate",- "tags"+ "tags",+ "companyGroupId"]},{"name": "customField","rows": 0,"columns": [+ "sortOrder",+ "dataTypeId","active",+ "createdAt",+ "updatedAt","required",- "sortOrder",+ "id",+ "name","table",- "updatedBy",- "dataTypeId",+ "listOptions","companyId","createdBy",- "name",- "tags",- "listOptions",- "createdAt",- "id",- "updatedAt"+ "updatedBy",+ "tags"]},{"name": "customerStatus","rows": 0,"columns": [- "createdBy",- "updatedAt","createdAt",+ "updatedAt",+ "customFields",+ "id",+ "name","companyId",+ "createdBy","updatedBy",- "id",- "tags",- "customFields",- "name"+ "tags"]},{"name": "customerType","rows": 0,"columns": [- "companyId","protected",- "updatedBy","createdAt",- "name",- "tags","updatedAt",- "id","customFields",- "createdBy"+ "id",+ "name",+ "companyId",+ "createdBy",+ "updatedBy",+ "tags"]},{"name": "department","rows": 0,"columns": [- "createdBy",- "updatedBy",- "companyId",- "parentDepartmentId","createdAt",- "id",- "customFields",- "tags","updatedAt",- "name"+ "customFields",+ "id",+ "name",+ "parentDepartmentId",+ "companyId",+ "createdBy",+ "updatedBy",+ "tags"]},{"name": "depreciationRun","rows": 0,"columns": [+ "periodEnd",+ "postedAt",+ "createdAt","id",- "createdBy",- "postedBy","depreciationRunId",- "updatedBy",- "createdAt",- "postedAt","status",- "periodEnd",- "companyId"+ "postedBy",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "dimension","rows": 0,"columns": [- "name",+ "entityType",+ "active",+ "required","createdAt","updatedAt","id",- "updatedBy",- "required",+ "name","companyGroupId",- "entityType","createdBy",- "active"+ "updatedBy"]},{@@ -621,34 +621,34 @@"rows": 0,"columns": ["createdAt",- "id","updatedAt",+ "id","dimensionId",- "createdBy",- "updatedBy","name",- "companyGroupId"+ "companyGroupId",+ "createdBy",+ "updatedBy"]},{"name": "document","rows": 0,"columns": [+ "size",+ "type",+ "active","createdAt",- "path",+ "updatedAt","sourceDocument",- "active",- "readGroups",- "companyId","id",- "writeGroups",- "description",+ "path","name",- "updatedBy",- "type",- "size",+ "description",+ "readGroups",+ "writeGroups",+ "companyId","createdBy",- "updatedAt",+ "updatedBy","sourceDocumentId"]},@@ -656,20 +656,20 @@"name": "documentExtraction","rows": 0,"columns": [- "createdAt",- "storagePath",- "sourceDocument",- "updatedAt",- "sourceDocumentId",+ "documentType","status",+ "extractedData","filteredData",+ "createdAt",+ "updatedAt","id",- "createdBy",- "documentType","companyId",- "updatedBy",- "extractedData",- "error"+ "sourceDocument",+ "sourceDocumentId",+ "storagePath",+ "error",+ "createdBy",+ "updatedBy"]},{@@ -680,146 +680,146 @@{"name": "documentLabel","rows": 0,- "columns": ["documentId", "userId", "companyId", "label"]+ "columns": ["documentId", "userId", "label", "companyId"]},{"name": "documentSection","rows": 0,"columns": [- "name",- "placement",- "createdBy","content",- "companyId",- "updatedAt",+ "config","createdAt",- "updatedBy",+ "updatedAt","id",- "config"+ "companyId",+ "name",+ "placement",+ "createdBy",+ "updatedBy"]},{"name": "documentTemplate","rows": 0,"columns": [- "blocks",- "updatedBy","formatVersion",- "documentType",+ "blocks",+ "theme","settings",- "id",- "footerSectionId","createdAt",- "theme","updatedAt",+ "id","companyId",+ "documentType","headerSectionId",- "createdBy"+ "footerSectionId",+ "createdBy",+ "updatedBy"]},{"name": "documentTransaction","rows": 0,"columns": [- "documentId",+ "type",+ "createdAt","id",- "companyId",+ "documentId","userId",- "type",- "createdAt"+ "companyId"]},{"name": "employeeType","rows": 0,"columns": [- "createdAt",- "companyId","protected",+ "createdAt",+ "updatedAt","systemType","id",- "updatedAt",- "name"+ "name",+ "companyId"]},{"name": "employee","rows": 0,- "columns": ["id", "companyId", "active", "employeeTypeId"]+ "columns": ["active", "id", "companyId", "employeeTypeId"]},{"name": "employeeTypePermission","rows": 0,"columns": ["module",+ "createdAt","updatedAt","employeeTypeId",- "view",- "delete","create",- "createdAt",- "update"+ "delete",+ "update",+ "view"]},{"name": "enforcementRule","rows": 0,"columns": [+ "family","conditionAst",- "targetType",- "createdBy",- "filteredItemGroupIds",- "companyId",- "message","surfaces",- "id",+ "targetType","appliesToAll",- "severity","filteredItemMatchAll",- "family",- "name",- "updatedAt",- "updatedBy","active","createdAt",+ "updatedAt",+ "customFields",+ "id",+ "companyId",+ "name","description",+ "message",+ "severity","filteredItemTypes",- "customFields"+ "filteredItemGroupIds",+ "createdBy",+ "updatedBy"]},{"name": "enforcementRuleAcknowledgment","rows": 0,"columns": [- "updatedBy",+ "createdAt",+ "id",+ "companyId","ruleId","ruleName",- "documentLineId","documentType",- "createdBy",- "createdAt",- "companyId",- "outcome",+ "documentId",+ "documentLineId","itemId",- "message","severity",- "id",- "documentId"+ "outcome",+ "message",+ "createdBy",+ "updatedBy"]},{"name": "eventSystemSubscription","rows": 0,"columns": [- "id",- "createdAt","filter",- "name","config","active",- "operations",+ "createdAt",+ "id",+ "name","companyId","table",+ "operations","handlerType"]},@@ -827,100 +827,100 @@"name": "exchangeRateOverride","rows": 0,"columns": [- "companyId",+ "rate",+ "createdAt","updatedAt","id",- "createdAt",+ "companyId","currencyCode",- "rate",- "updatedBy",- "createdBy"+ "createdBy",+ "updatedBy"]},{"name": "externalIntegrationMapping","rows": 0,"columns": [- "externalId",- "createdBy",- "metadata",- "updatedBy",- "entityId",- "integration","allowDuplicateExternalId",- "remoteUpdatedAt",- "id",- "updatedAt",+ "metadata","lastSyncedAt",+ "remoteUpdatedAt","createdAt",+ "updatedAt",+ "id",+ "entityType",+ "entityId",+ "integration",+ "externalId",+ "createdBy","companyId",- "entityType"+ "updatedBy"]},{"name": "fiscalYearSettings","rows": 0,- "columns": ["updatedBy", "taxStartMonth", "companyId", "startMonth"]+ "columns": ["startMonth", "taxStartMonth", "companyId", "updatedBy"]},{"name": "fixedAssetClass","rows": 0,"columns": [- "lossOnDisposalAccountId",- "createdAt",+ "depreciationMethod","usefulLifeMonths",- "updatedAt",- "macrsConvention",+ "residualValuePercent",+ "taxDepreciationMethod",+ "taxUsefulLifeMonths","taxResidualValuePercent",- "createdBy",+ "macrsPropertyClass",+ "macrsConvention","bonusDepreciationPercent",- "companyId",+ "createdAt",+ "updatedAt",+ "customFields",+ "id",+ "name","description",- "taxUsefulLifeMonths",- "depreciationMethod","assetAccountId",- "updatedBy",- "writeDownAccountId",+ "accumulatedDepreciationAccountId","depreciationExpenseAccountId",- "id",- "gainOnDisposalAccountId",- "residualValuePercent",- "name",- "taxDepreciationMethod",- "macrsPropertyClass","writeOffAccountId",- "customFields",- "accumulatedDepreciationAccountId"+ "writeDownAccountId",+ "lossOnDisposalAccountId",+ "companyId",+ "createdBy",+ "updatedBy",+ "gainOnDisposalAccountId"]},{"name": "gaugeType","rows": 0,"columns": [- "createdBy",- "id",- "updatedBy",- "name",+ "customFields","createdAt","updatedAt",+ "id",+ "name","companyId",- "customFields"+ "createdBy",+ "updatedBy"]},{"name": "group","rows": 0,"columns": [+ "isIdentityGroup",+ "isEmployeeTypeGroup","isCustomerOrgGroup",- "updatedAt",- "id",+ "isCustomerTypeGroup",+ "isSupplierTypeGroup","isSupplierOrgGroup","createdAt",- "isSupplierTypeGroup",+ "updatedAt",+ "id","name",- "isEmployeeTypeGroup",- "isCustomerTypeGroup",- "isIdentityGroup","companyId"]},@@ -928,226 +928,226 @@"name": "holiday","rows": 0,"columns": [- "createdAt","date",- "companyId",+ "createdAt",+ "updatedAt","customFields",- "updatedBy",+ "id","name",+ "companyId","createdBy",- "tags",- "id",- "updatedAt"+ "updatedBy",+ "tags"]},{"name": "implementationCheckState","rows": 0,"columns": [- "updatedBy",- "companyId",- "createdBy",+ "kind",+ "createdAt","updatedAt","id",- "createdAt",+ "companyId","itemKey",- "kind",- "value"+ "value",+ "createdBy",+ "updatedBy"]},{"name": "implementationFieldValue","rows": 0,"columns": [+ "createdAt",+ "updatedAt",+ "id",+ "companyId","fieldKey","value",- "updatedBy","createdBy",- "companyId",- "updatedAt",- "id",- "createdAt"+ "updatedBy"]},{"name": "implementationRow","rows": 0,"columns": [- "createdBy",- "id",- "updatedAt",- "updatedBy",- "companyId",+ "payload","sortOrder","createdAt",- "payload",- "collection"+ "updatedAt",+ "id",+ "companyId",+ "collection",+ "createdBy",+ "updatedBy"]},{"name": "invite","rows": 0,"columns": [- "createdBy","permissions",- "email","role",- "attestedBy",- "revokedAt","createdAt",+ "acceptedAt",+ "revokedAt","attestedAt",+ "id","code",+ "email","companyId",+ "createdBy","updatedBy",- "id",- "acceptedAt"+ "attestedBy"]},{"name": "itarCertification","rows": 0,"columns": [- "fullLegalName",- "createdBy",- "type",- "userId",- "createdAt",- "updatedAt",- "docVersion",- "userAgent","certifiedAt",- "title","expiresAt",+ "createdAt",+ "updatedAt",+ "id","companyId",- "updatedBy",+ "type",+ "userId",+ "docVersion","docHash",- "ipAddress",+ "fullLegalName",+ "title","complianceContact",- "id"+ "ipAddress",+ "userAgent",+ "createdBy",+ "updatedBy"]},{"name": "itemPostingGroup","rows": 0,"columns": [- "companyId",- "description","active","createdAt","updatedAt",+ "customFields","id",- "tags",- "createdBy","name",+ "description",+ "companyId",+ "createdBy","updatedBy",- "customFields"+ "tags"]},{"name": "itemStockQuantities","rows": 0,- "columns": ["itemId", "companyId", "locationId", "quantityOnHand"]+ "columns": ["quantityOnHand", "itemId", "companyId", "locationId"]},{"name": "journal","rows": 0,"columns": [- "createdBy",- "reversedById",- "description",- "tags",+ "postingDate",+ "createdAt",+ "customFields","status",- "journalEntryId",- "id","sourceType",- "createdAt",- "accountingPeriodId","postedAt",- "companyId",+ "updatedAt","eliminationKind",- "updatedBy",- "customFields",- "postingDate",+ "id",+ "description",+ "accountingPeriodId",+ "companyId",+ "tags",+ "journalEntryId","reversalOfId",+ "reversedById","postedBy",- "updatedAt"+ "createdBy",+ "updatedBy"]},{"name": "journalLine","rows": 0,"columns": [- "updatedAt",- "updatedBy",- "description",- "createdAt",+ "amount",+ "quantity","documentType",- "intercompanyPartnerId","accrual",- "amount",- "accountId",+ "createdAt","customFields",- "createdBy",+ "updatedAt",+ "id","journalId",- "companyId",- "tags",- "journalLineReference",+ "description","documentId",- "documentLineReference",- "id","externalDocumentId",- "quantity"+ "journalLineReference",+ "documentLineReference",+ "companyId",+ "tags",+ "accountId",+ "updatedBy",+ "intercompanyPartnerId",+ "createdBy"]},{"name": "intercompanyTransaction","rows": 0,"columns": [- "status",- "sourceJournalLineId",- "updatedAt",+ "amount",+ "documentType","createdAt",+ "updatedAt",+ "id",+ "companyGroupId","sourceCompanyId","targetCompanyId",- "amount",- "documentId",- "description",- "id",+ "sourceJournalLineId","targetJournalLineId",- "companyGroupId",- "eliminationJournalId",- "documentType",- "currencyCode"+ "currencyCode",+ "description",+ "documentId",+ "status",+ "eliminationJournalId"]},{"name": "intercompanyEliminationLine","rows": 0,"columns": [- "id",+ "role",+ "amount","quantity","createdAt",- "accountId",- "companyId","updatedAt",+ "id",+ "companyId",+ "intercompanyTransactionId",+ "journalLineId",+ "accountId","itemId","createdBy",- "updatedBy",- "journalLineId",- "role",- "intercompanyTransactionId",- "amount"+ "updatedBy"]},{"name": "journalLineDimension","rows": 0,"columns": [- "journalLineId",- "id","createdAt",- "valueId",+ "id",+ "journalLineId","dimensionId",+ "valueId","companyId"]},@@ -1155,95 +1155,95 @@"name": "location","rows": 0,"columns": [- "updatedAt",- "name",- "createdBy",- "countryCode","latitude",- "timezone",- "id","longitude",- "stateProvince",- "addressLine1","createdAt",+ "updatedAt",+ "customFields",+ "requiresStaffing",+ "id",+ "name",+ "addressLine1","addressLine2",- "tags",- "code",+ "city",+ "stateProvince","postalCode",+ "countryCode",+ "timezone","companyId",- "requiresStaffing",- "city",- "customFields",- "updatedBy"+ "createdBy",+ "updatedBy",+ "tags",+ "code"]},{"name": "fixedAsset","rows": 0,"columns": [- "bonusDepreciationPercent",- "taxResidualValuePercent",- "fixedAssetId",- "updatedAt",+ "status","depreciationMethod",- "createdBy",- "disposalDate",- "customFields",- "residualValuePercent",- "id","usefulLifeMonths",- "companyId",+ "residualValuePercent","taxDepreciationMethod",- "serialNumber",- "disposalMethod",- "name",+ "taxUsefulLifeMonths",+ "taxResidualValuePercent","macrsPropertyClass",- "fixedAssetClassId",- "depreciationStartDate",+ "macrsConvention",+ "bonusDepreciationPercent",+ "acquisitionCost","acquisitionDate",- "locationId",- "status",- "createdAt",- "notes",- "assetLifetimeUsage",- "description",+ "depreciationStartDate","accumulatedDepreciation",- "updatedBy",- "taxUsefulLifeMonths",- "macrsConvention","accumulatedTaxDepreciation",+ "assetLifetimeUsage",+ "disposalDate",+ "disposalMethod","saleProceeds",- "acquisitionCost"- ]- },- {- "name": "depreciationRunLine",- "rows": 0,- "columns": [- "depreciationRunId",- "journalId",+ "createdAt",+ "updatedAt",+ "notes",+ "customFields","id",- "companyId","fixedAssetId",+ "fixedAssetClassId",+ "name",+ "description",+ "serialNumber",+ "locationId",+ "companyId",+ "createdBy",+ "updatedBy"+ ]+ },+ {+ "name": "depreciationRunLine",+ "rows": 0,+ "columns": ["amount",- "taxAmount"+ "taxAmount",+ "id",+ "depreciationRunId",+ "fixedAssetId",+ "journalId",+ "companyId"]},{"name": "fixedAssetDisposal","rows": 0,"columns": [+ "disposalMethod",+ "disposalDate",+ "saleProceeds",+ "netBookValueAtDisposal",+ "gainLoss",+ "createdAt",+ "id","fixedAssetId","journalId",- "createdAt","companyId",- "id","createdBy",- "netBookValueAtDisposal",- "disposalMethod",- "disposalDate",- "gainLoss",- "saleProceeds","updatedBy"]},@@ -1251,14 +1251,14 @@"name": "fixedAssetUsageLog","rows": 0,"columns": [- "createdAt",- "periodEnd","periodStart",+ "periodEnd","unitsProduced",- "createdBy",+ "createdAt",+ "id","fixedAssetId","companyId",- "id",+ "createdBy","updatedBy"]},@@ -1266,151 +1266,151 @@"name": "inventoryCount","rows": 0,"columns": [+ "status","isBlind",- "notes",- "id",- "postedAt",+ "scope","snapshotAt",- "postedBy",- "customFields",- "companyId",+ "postedAt","createdAt","updatedAt",- "createdBy",- "status",- "scope",- "updatedBy",+ "customFields",+ "id",+ "companyId","inventoryCountId",- "locationId"+ "locationId",+ "notes",+ "postedBy",+ "createdBy",+ "updatedBy"]},{"name": "maintenanceFailureMode","rows": 0,"columns": [- "name",+ "createdAt",+ "updatedAt","type","id",- "updatedBy",+ "name","companyId","createdBy",- "updatedAt",- "createdAt"+ "updatedBy"]},{"name": "materialForm","rows": 0,"columns": [- "createdBy",- "updatedBy","customFields",- "companyId","createdAt",+ "updatedAt","id",+ "name",+ "companyId",+ "createdBy",+ "updatedBy","tags",- "updatedAt",- "code",- "name"+ "code"]},{"name": "materialDimension","rows": 0,- "columns": ["id", "materialFormId", "companyId", "isMetric", "name"]+ "columns": ["isMetric", "id", "materialFormId", "name", "companyId"]},{"name": "materialSubstance","rows": 0,"columns": [- "name",- "code",+ "customFields",+ "createdAt","updatedAt","id",- "tags",- "createdAt",- "customFields",+ "name","companyId",+ "createdBy","updatedBy",- "createdBy"+ "tags",+ "code"]},{"name": "materialFinish","rows": 0,- "columns": ["name", "id", "materialSubstanceId", "companyId"]+ "columns": ["id", "name", "materialSubstanceId", "companyId"]},{"name": "materialGrade","rows": 0,- "columns": ["companyId", "name", "materialSubstanceId", "id"]+ "columns": ["id", "materialSubstanceId", "name", "companyId"]},{"name": "materialType","rows": 0,"columns": [- "name","id",- "companyId",+ "name","code","materialSubstanceId",- "materialFormId"+ "materialFormId",+ "companyId"]},{"name": "material","rows": 0,"columns": [+ "approved",+ "customFields",+ "createdAt","updatedAt",- "materialTypeId",- "tags",- "createdBy",- "gradeId",- "updatedBy",+ "id","materialFormId","materialSubstanceId",- "finishId",- "dimensionId","approvedBy",- "id","companyId",- "approved",- "customFields",- "createdAt"+ "createdBy",+ "updatedBy",+ "tags",+ "dimensionId",+ "finishId",+ "gradeId",+ "materialTypeId"]},{"name": "membership","rows": 0,- "columns": ["groupId", "id", "memberUserId", "memberGroupId"]+ "columns": ["id", "groupId", "memberGroupId", "memberUserId"]},{"name": "modelUpload","rows": 0,"columns": [- "glbPath",- "thumbnailPath",- "name",+ "size","createdAt",- "optimizedSize","updatedAt",- "createdBy",- "id",- "updatedBy",- "originalSize",- "size","processingStatus",- "modelPath",- "processedAt","componentCount",- "companyId",+ "processedAt",+ "optimizeStatus","optimizedAt",- "optimizeError",+ "optimizedSize",+ "originalSize",+ "id",+ "name",+ "modelPath","autodeskUrn",- "optimizedModelPath",+ "companyId",+ "createdBy",+ "updatedBy",+ "thumbnailPath","processingError",- "optimizeStatus",+ "glbPath","graphPath",+ "optimizedModelPath",+ "optimizeError","originalPath"]},@@ -1418,239 +1418,239 @@"name": "assemblyPlanJob","rows": 0,"columns": [+ "status",+ "stats",+ "createdAt","updatedAt","id",- "createdBy",- "stats","modelUploadId",- "createdAt",- "companyId",- "planPath",- "status","kind",- "error"+ "planPath",+ "error",+ "companyId",+ "createdBy"]},{"name": "noQuoteReason","rows": 0,"columns": [- "updatedAt","createdAt",- "companyId",- "createdBy",+ "updatedAt","customFields",+ "id","name",- "updatedBy",- "id"+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "nonConformanceRequiredAction","rows": 0,"columns": [- "createdBy",+ "active",+ "createdAt",+ "updatedAt","systemType","id",- "updatedBy","companyId",- "createdAt",- "updatedAt","name",- "active"+ "createdBy",+ "updatedBy"]},{"name": "nonConformanceType","rows": 0,"columns": [+ "createdAt","updatedAt",- "id","customFields",+ "id","name",- "createdBy",- "updatedBy","companyId",- "createdAt"+ "createdBy",+ "updatedBy"]},{"name": "nonConformanceWorkflow","rows": 0,"columns": [- "createdBy",- "description","content",- "requiredActionIds",- "updatedAt","priority",- "companyId",- "active",- "updatedBy",- "createdAt",- "name","source","approvalRequirements",+ "active",+ "createdAt",+ "updatedAt","id",- "tags"+ "name",+ "description",+ "tags",+ "companyId",+ "createdBy",+ "updatedBy",+ "requiredActionIds"]},{"name": "nonConformance","rows": 0,"columns": [- "description",- "nonConformanceTypeId",- "name",- "quantity",- "companyId",+ "source",+ "status","priority",- "tags",- "assignee",+ "approvalRequirements","content",- "source",- "updatedAt",- "closeDate","openDate",- "customFields","dueDate",- "nonConformanceId",- "locationId",- "requiredActionIds",- "approvalRequirements",+ "closeDate",+ "quantity",+ "customFields","createdAt",+ "updatedAt","id",- "updatedBy",+ "nonConformanceId",+ "name",+ "description","nonConformanceWorkflowId",- "status",- "createdBy"+ "locationId",+ "nonConformanceTypeId",+ "assignee",+ "tags",+ "companyId",+ "createdBy",+ "updatedBy",+ "requiredActionIds"]},{"name": "changeOrder","rows": 0,"columns": [- "assignee",- "sourceType",- "createdAt",- "dueDate",- "companyId",+ "reasonForChange","description",- "createdBy",+ "type","status",- "updatedAt",- "customFields",- "tags",- "approvalRequirements",- "name",- "reasonForChange",- "type",+ "priority","openDate",- "changeOrderTypeId",+ "dueDate",+ "customFields",+ "createdAt",+ "updatedAt","id",- "nonConformanceId",- "updatedBy",- "priority","changeOrderId",+ "name",+ "changeOrderTypeId",+ "nonConformanceId","requiredActionIds",- "sourceId"+ "approvalRequirements",+ "sourceType",+ "sourceId",+ "assignee",+ "tags",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "changeOrderActionTask","rows": 0,"columns": [- "assignee","status",- "name",- "updatedAt",- "updatedBy",- "createdAt","dueDate",- "tags",+ "completedDate","notes",+ "sortOrder",+ "createdAt",+ "updatedAt",+ "id","changeOrderId",- "createdBy",- "actionTypeId",- "completedDate",+ "name",+ "assignee",+ "tags","companyId",- "id",- "sortOrder"+ "createdBy",+ "updatedBy",+ "actionTypeId"]},{"name": "nonConformanceApprovalTask","rows": 0,"columns": [- "assignee",- "status",- "updatedAt","approvalType",- "updatedBy",- "createdAt",+ "status","dueDate",- "tags",+ "completedDate","notes",+ "sortOrder",+ "createdAt",+ "updatedAt",+ "id","nonConformanceId",- "createdBy",- "completedDate",+ "assignee",+ "tags","companyId",- "id",- "sortOrder"+ "createdBy",+ "updatedBy"]},{"name": "nonConformanceReviewer","rows": 0,"columns": [- "updatedAt",+ "status",+ "notes","createdAt",+ "updatedAt",+ "completedDate",+ "id","title",+ "nonConformanceId","assignee",- "updatedBy",- "id",- "createdBy","companyId",- "nonConformanceId",- "status",- "notes",- "completedDate"+ "createdBy",+ "updatedBy"]},{"name": "note","rows": 0,"columns": [- "documentId",- "updatedBy",- "createdBy",+ "noteRichText",+ "active",+ "createdAt","updatedAt","id",- "companyId",+ "documentId","note",- "noteRichText",- "createdAt",- "active"+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "notification","rows": 0,"columns": [- "title",- "id",- "documentType","payload",- "from",- "documentId",- "userId",+ "readAt","seenAt","createdAt",- "readAt",+ "id",+ "userId",+ "companyId",+ "topic","event",+ "title","description",- "topic",- "companyId",+ "from",+ "documentType",+ "documentId","digestedInto"]},@@ -1658,14 +1658,14 @@"name": "notificationDelivery","rows": 0,"columns": [- "id",- "createdAt","successCount",- "companyId","lastDeliveredAt",- "documentId",- "event",+ "createdAt",+ "id",+ "companyId","userId",+ "event",+ "documentId","lastDeliveryId"]},@@ -1673,243 +1673,243 @@"name": "notificationPreference","rows": 0,"columns": [- "id","enabled",+ "updatedAt",+ "id","userId",- "topic",- "channel","companyId",- "updatedAt"+ "channel",+ "topic"]},{"name": "oauthCode","rows": 0,"columns": [- "redirectUri",- "scope",- "id",- "codeChallenge",- "codeChallengeMethod",+ "createdAt","expiresAt",+ "id","code",- "companyId",- "createdAt",+ "clientId","userId",- "clientId"+ "companyId",+ "redirectUri",+ "codeChallenge",+ "codeChallengeMethod",+ "scope"]},{"name": "part","rows": 0,"columns": [- "companyId","createdAt",+ "updatedAt","customFields",+ "approved",+ "fromDate","toDate","id",+ "approvedBy",+ "companyId","createdBy","updatedBy",- "approvedBy",- "approved",- "tags",- "fromDate",- "updatedAt"+ "tags"]},{"name": "paymentTerm","rows": 0,"columns": [- "discountPercentage",- "updatedBy","daysDue",- "tags","daysDiscount",+ "discountPercentage",+ "calculationMethod","active","createdAt",- "id","updatedAt",- "calculationMethod","customFields",+ "id","name","companyId",- "createdBy"+ "createdBy",+ "updatedBy",+ "tags"]},{"name": "periodCloseTaskDefinition","rows": 0,"columns": [- "name",- "updatedBy",- "taskType",+ "sortOrder","required",- "createdBy",- "autoCheckKey",+ "active",+ "isSystem",+ "createdAt","updatedAt","customFields",+ "id","companyId",- "createdAt",+ "name",+ "taskType",+ "autoCheckKey","severity",- "isSystem",- "active",- "id","defaultAssigneeId",- "sortOrder"+ "createdBy",+ "updatedBy"]},{"name": "periodCloseTask","rows": 0,"columns": [- "evidenceJournalId",- "companyId",- "completedBy","sortOrder",- "severity","required",- "id",- "status",- "taskType","completedAt",+ "createdAt",+ "updatedAt",+ "id",+ "companyId","accountingPeriodId","definitionId",- "createdBy",- "createdAt",+ "name",+ "taskType","autoCheckKey",+ "severity",+ "status","assigneeId",- "updatedBy",- "name",+ "completedBy",+ "skippedReason",+ "evidenceJournalId","notes",- "updatedAt",- "skippedReason"+ "createdBy",+ "updatedBy"]},{"name": "pickingList","rows": 0,"columns": [- "companyId",+ "status",+ "dueDate",+ "notes","createdAt",+ "updatedAt","customFields",- "pickingListId",- "dueDate","id",- "createdBy",- "updatedBy",- "notes",+ "pickingListId","locationId",- "status","assignee",- "updatedAt"+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "pricingRule","rows": 0,"columns": [- "validFrom",- "name",- "maxQuantity",- "customerTypeIds",- "customerIds",- "id",- "itemIds",- "priority",- "validTo","ruleType","amountType",- "createdBy",- "companyId",+ "amount",+ "priority","minQuantity",+ "maxQuantity",+ "validFrom",+ "validTo",+ "active",+ "createdAt","updatedAt",- "amount",+ "id",+ "name",+ "customerIds",+ "customerTypeIds",+ "itemIds","itemPostingGroupId",- "createdAt",- "updatedBy",- "active"+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "printJob","rows": 0,"columns": [- "error",- "content",- "updatedBy",+ "attempts","createdAt",- "contentType",- "createdBy",- "status",+ "updatedAt","completedAt",- "sourceDocument","id",- "sourceDocumentReadableId",- "origin",- "printerUrl",- "updatedAt","companyId",- "attempts",+ "status",+ "contentType",+ "content",+ "printerUrl",+ "sourceDocument","sourceDocumentId",- "description"+ "sourceDocumentReadableId",+ "description",+ "origin",+ "error",+ "createdBy",+ "updatedBy"]},{"name": "printerRoute","rows": 0,"columns": [- "printerUrl",- "name",- "locationId",- "format",+ "createdAt","updatedAt",- "apiKey",+ "id","companyId",+ "locationId",+ "name",+ "format","mediaSizeId",- "templateId",- "id",- "createdAt"+ "printerUrl",+ "apiKey",+ "templateId"]},{"name": "process","rows": 0,"columns": [- "batchType",- "name",- "active",- "updatedBy",- "processType",- "updatedAt",- "id",- "tags",- "createdBy","defaultStandardFactor",- "requiresAbility",- "companyId",+ "customFields","createdAt",+ "updatedAt",+ "processType","completeAllOnScan",- "customFields",+ "active",+ "requiresAbility",+ "batchable",+ "batchType","batchRules",- "batchable"+ "id",+ "name",+ "companyId",+ "createdBy",+ "updatedBy",+ "tags"]},{"name": "ability","rows": 0,"columns": [- "active",- "recertifyEveryDays",- "createdAt","curve","shadowWeeks",- "companyId",+ "active",+ "createdAt","updatedAt",+ "recertifyEveryDays","id",- "processId",+ "companyId","createdBy",- "updatedBy"+ "updatedBy",+ "processId"]},{@@ -1917,46 +1917,46 @@"rows": 0,"columns": ["lastTrainingDate",- "abilityId",- "id","expiresAt",- "companyId",- "employeeId"+ "id",+ "employeeId",+ "abilityId",+ "companyId"]},{"name": "procedure","rows": 0,"columns": [- "processId",- "tags",- "description",- "content","version",+ "status",+ "content",+ "createdAt","updatedAt",- "updatedBy",+ "id","name",+ "processId",+ "description","assignee",- "createdAt","companyId",- "id","createdBy",- "status"+ "updatedBy",+ "tags"]},{"name": "procedureParameter","rows": 0,"columns": [- "createdBy",+ "createdAt",+ "updatedAt",+ "id",+ "procedureId","key","value","companyId",- "updatedAt",- "procedureId",- "createdAt",- "updatedBy",- "id"+ "createdBy",+ "updatedBy"]},{@@ -1965,36 +1965,36 @@"columns": ["active","createdAt",+ "updatedAt",+ "id",+ "companyId","name","description","createdBy",- "updatedAt",- "id",- "updatedBy",- "companyId"+ "updatedBy"]},{"name": "purchasingRfq","rows": 0,"columns": [- "createdBy",- "updatedBy",- "employeeId",- "companyId",- "expirationDate",- "status","revisionId",- "createdAt",+ "status","rfqDate",- "assignee",- "id",- "notes",- "locationId",+ "expirationDate","internalNotes",+ "notes","customFields",+ "createdAt",+ "updatedAt",+ "id","rfqId",- "updatedAt"+ "employeeId",+ "locationId",+ "assignee",+ "companyId",+ "createdBy",+ "updatedBy"]},{@@ -2006,117 +2006,117 @@"name": "qualityDocument","rows": 0,"columns": [- "assignee",- "description","version",- "updatedBy","status",- "companyId",- "createdBy",- "name",- "tags","content","createdAt",+ "updatedAt","id",- "updatedAt"+ "name",+ "description",+ "assignee",+ "companyId",+ "createdBy",+ "updatedBy",+ "tags"]},{"name": "reportPin","rows": 0,"columns": [- "userId",+ "pinned",+ "createdAt","updatedAt","reportKey",- "createdAt",- "pinned",+ "userId","companyId",- "updatedBy",- "createdBy"+ "createdBy",+ "updatedBy"]},{"name": "reportView","rows": 0,"columns": [- "updatedBy",- "id",+ "config","visibility",- "companyId","createdAt","updatedAt",- "config",+ "id",+ "companyId","reportKey","name",- "createdBy"+ "createdBy",+ "updatedBy"]},{"name": "returnReason","rows": 0,"columns": [- "createdBy","inventoryValueZero",- "companyId",- "updatedBy",+ "createdAt",+ "updatedAt","customFields","id",- "createdAt","name",- "updatedAt"+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "scrapReason","rows": 0,"columns": [- "createdBy",- "companyId","createdAt","updatedAt",+ "customFields","id",- "updatedBy","name",- "customFields"+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "searchIndexRegistry","rows": 0,- "columns": ["companyId", "createdAt", "lastRebuiltAt"]+ "columns": ["createdAt", "lastRebuiltAt", "companyId"]},{"name": "sequence","rows": 0,"columns": [- "prefix",- "name",+ "next","size",- "suffix",- "table","step","updatedAt",+ "table",+ "name",+ "prefix",+ "suffix","companyId",- "updatedBy",- "next"+ "updatedBy"]},{"name": "service","rows": 0,"columns": [- "updatedBy",- "companyId",- "createdBy",- "customFields",- "id",- "fromDate","serviceType",- "updatedAt","approved",+ "fromDate","toDate",- "approvedBy",+ "customFields","createdAt",+ "updatedAt",+ "id",+ "approvedBy",+ "companyId",+ "createdBy",+ "updatedBy","tags"]},@@ -2124,169 +2124,169 @@"name": "shift","rows": 0,"columns": [- "id",- "wednesday",- "friday",+ "startTime",+ "endTime","sunday",- "createdAt",- "name",- "active",+ "monday","tuesday",+ "wednesday","thursday",- "tags",+ "friday","saturday",- "locationId",- "updatedBy",- "createdBy",- "endTime",- "companyId",- "startTime",+ "active",+ "createdAt","updatedAt","customFields",- "monday"+ "id",+ "name",+ "locationId",+ "companyId",+ "createdBy",+ "updatedBy",+ "tags"]},{"name": "employeeJob","rows": 0,"columns": [- "title",- "companyId",- "managerId",- "shiftId","startDate",- "departmentId",- "id",- "updatedBy",- "customFields","updatedAt",+ "customFields",+ "id","locationId",+ "shiftId",+ "managerId",+ "title",+ "companyId",+ "updatedBy",+ "departmentId","tags"]},{"name": "employeeShift","rows": 0,- "columns": ["shiftId", "companyId", "employeeId", "id"]+ "columns": ["id", "employeeId", "shiftId", "companyId"]},{"name": "peopleAbsence","rows": 0,"columns": [- "companyId",- "updatedAt",+ "date","createdAt",- "updatedBy",+ "updatedAt","id",- "note",+ "companyId","employeeId",- "date",+ "shiftId",+ "note","createdBy",- "shiftId"+ "updatedBy"]},{"name": "shippingMethod","rows": 0,"columns": [- "createdBy",- "id",- "updatedBy",+ "carrier","active",- "tags",- "name","createdAt","updatedAt",- "trackingUrl","customFields",- "carrier",+ "id",+ "name","carrierAccountId",- "companyId"+ "trackingUrl",+ "companyId",+ "createdBy",+ "updatedBy",+ "tags"]},{"name": "shippingTerm","rows": 0,"columns": [- "updatedBy",- "name",- "createdBy",- "tags",- "id",- "updatedAt","active",+ "createdAt",+ "updatedAt",+ "id",+ "name","companyId",- "createdAt"+ "createdBy",+ "updatedBy",+ "tags"]},{"name": "slackDocumentThread","rows": 0,"columns": [- "channelId","createdAt",+ "updatedAt",+ "id",+ "companyId","documentType","documentId",+ "channelId","threadTs",- "updatedAt",- "id",- "updatedBy","createdBy",- "companyId"+ "updatedBy"]},{"name": "ssoConnection","rows": 0,"columns": [+ "active",+ "requireSso",+ "createdAt",+ "updatedAt",+ "id",+ "companyId","providerId","metadataUrl",- "requireSso","metadataXml",- "companyId","createdBy",- "updatedBy",- "createdAt",- "id",- "updatedAt",- "active"+ "updatedBy"]},{"name": "ssoDomain","rows": 0,"columns": [- "companyId",- "createdBy",- "updatedBy",+ "status",+ "verifiedAt","createdAt",- "id","updatedAt",- "status",+ "id",+ "companyId","connectionId","domain",- "verifiedAt",- "verificationToken"+ "verificationToken",+ "createdBy",+ "updatedBy"]},{"name": "stockTransfer","rows": 0,"columns": [- "updatedBy",- "createdBy",- "stockTransferId",- "customFields",- "companyId",+ "status",+ "completedAt",+ "createdAt",+ "updatedAt","notes",+ "customFields","id",- "updatedAt",- "createdAt",- "status",+ "stockTransferId","locationId",- "tags",+ "companyId",+ "createdBy",+ "updatedBy","assignee",- "completedAt"+ "tags"]},{@@ -2295,63 +2295,63 @@"columns": ["createdAt","updatedAt",+ "customFields",+ "id",+ "name","companyId","createdBy",- "updatedBy",- "id",- "customFields",- "name"+ "updatedBy"]},{"name": "suggestion","rows": 0,"columns": [- "path",+ "createdAt",+ "id",+ "suggestion","emoji",- "userId",+ "path","attachmentPath",- "suggestion",- "companyId",- "id",- "createdAt",- "tags"+ "tags",+ "userId",+ "companyId"]},{"name": "supplierType","rows": 0,"columns": [+ "updatedAt",+ "customFields",+ "protected","createdAt",- "updatedBy",+ "id",+ "name","companyId",- "protected","createdBy",- "id",- "customFields",- "updatedAt",- "tags",- "name"+ "updatedBy",+ "tags"]},{"name": "tableView","rows": 0,"columns": [- "name",- "createdAt",+ "type",+ "sortOrder","columnPinning",- "filters",- "id","columnVisibility",- "sorts",- "sortOrder",- "description",+ "createdAt",+ "id",+ "name","table",- "createdBy",+ "description","columnOrder",+ "filters",+ "sorts","companyId",- "type",+ "createdBy","updatedBy"]},@@ -2359,56 +2359,56 @@"name": "tag","rows": 0,"columns": [- "table",- "updatedBy",- "name","createdAt",+ "name",+ "table","companyId",- "createdBy"+ "createdBy",+ "updatedBy"]},{"name": "terms","rows": 0,"columns": [+ "purchasingTerms","salesTerms","updatedAt",- "updatedBy",- "purchasingTerms",- "id"+ "id",+ "updatedBy"]},{"name": "timeCardEntry","rows": 0,"columns": [- "id",+ "clockIn",+ "clockOut","createdAt","updatedAt",- "note",+ "id","employeeId",- "createdBy",- "updatedBy",- "clockOut",- "clockIn","companyId",- "autoCloseShiftId"+ "note",+ "autoCloseShiftId",+ "createdBy",+ "updatedBy"]},{"name": "tool","rows": 0,"columns": [- "tags",+ "approved","customFields",- "createdBy",+ "createdAt",+ "updatedAt",+ "id","approvedBy",- "approved","companyId",- "id",+ "createdBy","updatedBy",- "createdAt",- "updatedAt"+ "tags"]},{@@ -2416,382 +2416,382 @@"rows": 0,"columns": ["attributes",- "createdBy",- "id",- "updatedBy","createdAt",+ "id","type",+ "sourceDocument",+ "sourceDocumentId","sourceDocumentReadableId","companyId",- "sourceDocument",- "sourceDocumentId"+ "createdBy",+ "updatedBy"]},{"name": "training","rows": 0,"columns": [- "estimatedDuration",- "type",- "companyId",- "name",- "updatedAt",+ "version","status",- "tags",+ "frequency",+ "type","content",+ "createdAt",+ "updatedAt","id",- "frequency",- "grantsAbilityId",+ "name","description",- "createdAt",- "version",+ "processId",+ "estimatedDuration",+ "tags",+ "assignee",+ "companyId","createdBy","updatedBy",- "processId",- "assignee"+ "grantsAbilityId"]},{"name": "trainingAssignment","rows": 0,"columns": [+ "createdAt",+ "updatedAt","id",- "createdBy","trainingId",- "updatedBy",- "createdAt",- "companyId","groupIds",- "updatedAt"+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "trainingCompletion","rows": 0,"columns": [- "trainingAssignmentId",- "updatedBy",- "createdBy",- "period",- "updatedAt","id",- "completedBy",+ "completedAt",+ "createdAt",+ "updatedAt",+ "trainingAssignmentId","employeeId","companyId",- "createdAt",- "completedAt"+ "completedBy",+ "createdBy",+ "updatedBy",+ "period"]},{"name": "trainingQuestion","rows": 0,"columns": [- "correctNumber",+ "type",+ "sortOrder",+ "required","correctBoolean",+ "matchingPairs",+ "correctNumber",+ "tolerance",+ "createdAt",+ "updatedAt","id",- "required","trainingId",- "companyId",- "updatedAt",- "matchingPairs",+ "question",+ "options","correctAnswers",- "tolerance",- "sortOrder",- "updatedBy",+ "companyId","createdBy",- "question",- "createdAt",- "type",- "options"+ "updatedBy"]},{"name": "unitOfMeasure","rows": 0,"columns": [- "code",+ "active",+ "createdAt",+ "updatedAt","customFields",- "updatedBy",- "tags","id",- "updatedAt",- "createdBy",- "active",+ "code","name",- "createdAt",- "companyId"+ "companyId",+ "createdBy",+ "updatedBy",+ "tags"]},{"name": "item","rows": 0,"columns": [- "notes",+ "type",+ "replenishmentSystem","defaultMethodType",- "changeOrderId",- "description",+ "itemTrackingType",+ "active",+ "createdAt",+ "updatedAt",+ "notes",+ "embedding",+ "sourcingType",+ "revisionStatus",+ "id",+ "readableId","name",+ "description",+ "unitOfMeasureCode",+ "companyId","createdBy",+ "updatedBy","assignee",- "createdAt",- "revision",- "updatedAt",- "thumbnailPath",- "type","modelUploadId",- "revisionStatus",- "itemTrackingType",- "mpn",- "sourcingType",+ "thumbnailPath","trackingMethod",- "active",- "updatedBy",- "companyId",- "readableId",- "replenishmentSystem",- "embedding",- "id",- "unitOfMeasureCode"+ "revision",+ "mpn",+ "changeOrderId"]},{"name": "assemblyComponentMapping","rows": 0,"columns": [- "createdBy",+ "createdAt",+ "updatedAt",+ "id",+ "modelUploadId","geometryHash","itemId","confidence",- "updatedAt",- "createdAt",- "modelUploadId","companyId",- "updatedBy",- "id"+ "createdBy",+ "updatedBy"]},{"name": "assemblyInstruction","rows": 0,"columns": [- "tags",- "assemblyPlanJobId",- "rootInstructionId",- "updatedBy",- "createdAt",- "modelUploadId",- "itemId",+ "status","version",- "customFields",+ "publishedAt","settings",+ "customFields",+ "createdAt",+ "updatedAt","id",- "status","name",- "createdBy",- "updatedAt",+ "modelUploadId",+ "itemId",+ "assemblyPlanJobId","companyId",- "publishedAt"+ "tags",+ "createdBy",+ "updatedBy",+ "rootInstructionId"]},{"name": "assemblyInstructionStep","rows": 0,"columns": [- "title",- "fastener",+ "sortOrder",+ "type",+ "description",+ "required",+ "minValue","maxValue",- "rootStepId",- "planConfidence",- "warnings","notes",- "createdAt","motion",- "explode","camera",- "sortOrder",- "parentStepId",- "fileTypes",+ "explode",+ "fastener",+ "warnings","durationSeconds",- "description",+ "createdAt","updatedAt",+ "status",+ "buildWave","updatedBy",- "minValue",+ "rootStepId","id",- "required",- "createdBy",- "type",- "listValues","assemblyInstructionId",+ "parentStepId",+ "title",+ "instructionText",+ "unitOfMeasureCode",+ "listValues",+ "fileTypes","componentNodeIds",+ "planConfidence","companyId",- "unitOfMeasureCode",- "instructionText",- "buildWave",- "status"+ "createdBy"]},{"name": "assemblyInstructionStepMaterial","rows": 0,"columns": [- "updatedAt",+ "quantity",+ "sortOrder","createdAt",+ "updatedAt",+ "id","stepId",+ "itemId","companyId",- "id",- "updatedBy","createdBy",- "quantity",- "itemId",- "sortOrder"+ "updatedBy"]},{"name": "assemblyInstructionStepSlide","rows": 0,"columns": [- "modelUploadId",- "imagePath",- "size",- "caption",- "updatedBy",- "updatedAt",- "stepId",+ "sortOrder","annotations",- "createdBy",+ "createdAt",+ "updatedAt","id",+ "stepId",+ "imagePath",+ "modelUploadId",+ "caption",+ "size","companyId",- "createdAt",- "sortOrder"+ "createdBy",+ "updatedBy"]},{"name": "assemblyInstructionStepTool","rows": 0,"columns": [- "createdBy",- "itemId","quantity","sortOrder",- "updatedAt","createdAt",+ "updatedAt",+ "id","stepId",+ "itemId","companyId",- "updatedBy",- "id"+ "createdBy",+ "updatedBy"]},{"name": "assemblyUnit","rows": 0,"columns": [+ "createdAt",+ "updatedAt",+ "id",+ "modelUploadId","name","componentNodeIds",- "createdBy","itemId",- "modelUploadId",- "createdAt",- "updatedAt",+ "companyId",+ "createdBy","updatedBy",- "id",- "sourceGroupId",- "companyId"+ "sourceGroupId"]},{"name": "batchProperty","rows": 0,"columns": [- "label","dataType",- "companyId",- "listOptions",- "itemId",+ "sortOrder","createdAt","updatedAt",- "createdBy","id",- "updatedBy",- "sortOrder"+ "itemId",+ "label",+ "listOptions",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "changeOrderSupersession","rows": 0,"columns": [- "successorItemId",- "predecessorItemId",- "successorEffectivityDate","supersessionMode",- "updatedBy",+ "discontinuationDate",+ "successorEffectivityDate",+ "createdAt",+ "updatedAt",+ "id","changeOrderId",+ "predecessorItemId",+ "successorItemId","companyId","createdBy",- "id",- "createdAt",- "updatedAt",- "discontinuationDate"+ "updatedBy"]},{"name": "configurationParameterGroup","rows": 0,"columns": [- "itemId",- "companyId",+ "sortOrder",+ "isUngrouped","id",+ "itemId","name",- "sortOrder",- "isUngrouped"+ "companyId"]},{"name": "configurationParameter","rows": 0,"columns": [- "materialFormFilterId",- "label",- "key",- "configurationParameterGroupId","dataType",+ "sortOrder",+ "createdAt","updatedAt",- "updatedBy",+ "id","itemId",- "createdAt",- "sortOrder",- "createdBy",+ "label",+ "key",+ "listOptions",+ "configurationParameterGroupId","companyId",- "id",- "listOptions"+ "createdBy",+ "updatedBy",+ "materialFormFilterId"]},{"name": "configurationRule","rows": 0,"columns": [- "code",- "companyId","updatedAt",+ "itemId","field",- "updatedBy",- "itemId"+ "code",+ "companyId",+ "updatedBy"]},{"name": "demandForecast","rows": 0,"columns": [- "createdAt",- "companyId",- "locationId",+ "forecastQuantity","confidence",+ "createdAt","updatedAt",- "createdBy","itemId",- "notes",+ "locationId","periodId",- "forecastQuantity","forecastMethod",+ "notes",+ "companyId",+ "createdBy","updatedBy"]},@@ -2799,19 +2799,19 @@"name": "demandProjection","rows": 0,"columns": [- "forecastMethod",- "updatedBy",- "notes",- "periodId","forecastQuantity","confidence",- "createdBy",- "itemId",+ "createdAt","updatedAt",+ "itemId",+ "locationId",+ "periodId",+ "forecastMethod",+ "notes","companyId",- "createdAt",- "id",- "locationId"+ "createdBy",+ "updatedBy",+ "id"]},{@@ -2819,11 +2819,11 @@"rows": 0,"columns": ["createdAt",- "createdBy",- "companyId",- "updatedBy","itemId",- "ruleId"+ "ruleId",+ "companyId",+ "createdBy",+ "updatedBy"]},{@@ -2831,117 +2831,117 @@"rows": 0,"columns": ["version",- "samplingInspectionLevel",- "createdBy",+ "pageCount",+ "defaultPageWidth",+ "defaultPageHeight",+ "createdAt","updatedAt",- "samplingSeverity",+ "samplingPlanType","samplingSampleSize",- "drawingNumber",- "partId",- "updatedBy",- "samplingAql","samplingPercentage",- "fileName",+ "samplingAql",+ "samplingInspectionLevel",+ "samplingSeverity","id",- "defaultPageWidth",- "uploadedBy",- "storagePath",- "samplingPlanType",- "createdAt","companyId",- "pageCount",- "defaultPageHeight"+ "partId",+ "drawingNumber",+ "storagePath",+ "fileName",+ "uploadedBy",+ "createdBy",+ "updatedBy"]},{"name": "inspectionFeature","rows": 0,"columns": [- "nominalValue",- "samplingAql",- "samplingPercentage",- "companyId",- "updatedAt","pageNumber",+ "createdAt",+ "updatedAt","type",- "samplingSeverity",+ "samplingPlanType","samplingSampleSize",- "label",- "createdAt",+ "samplingPercentage",+ "samplingAql","samplingInspectionLevel",- "unit",- "tolerancePlus",- "updatedBy",+ "samplingSeverity",+ "id","inspectionDocumentId",- "samplingPlanType",+ "companyId",+ "label","description",- "createdBy",+ "nominalValue",+ "tolerancePlus","toleranceMinus",- "id"+ "unit",+ "createdBy",+ "updatedBy"]},{"name": "balloon","rows": 0,"columns": [- "companyId",- "updatedBy",- "inspectionFeatureId",- "regionY","pageNumber",- "createdBy",- "updatedAt",- "createdAt",- "inspectionDocumentId",+ "regionX",+ "regionY","regionWidth",- "xCoordinate","regionHeight",- "id",+ "xCoordinate","yCoordinate",- "regionX"+ "createdAt",+ "updatedAt",+ "id",+ "inspectionDocumentId",+ "companyId",+ "inspectionFeatureId",+ "createdBy",+ "updatedBy"]},{"name": "inventoryCountLine","rows": 0,"columns": [- "countedBy",- "locationId",- "updatedBy",- "createdBy",- "itemId",- "postedItemLedgerId",- "inventoryCountId",+ "systemQuantity",+ "countedQuantity",+ "countedAt",+ "createdAt","updatedAt","customFields",- "trackedEntityId","id",- "systemQuantity",- "storageUnitId",- "createdAt","companyId",- "countedAt",+ "inventoryCountId",+ "itemId",+ "locationId",+ "storageUnitId",+ "trackedEntityId","readableId",- "countedQuantity"+ "countedBy",+ "postedItemLedgerId",+ "createdBy",+ "updatedBy"]},{"name": "itemCost","rows": 0,"columns": [+ "costingMethod",+ "standardCost",+ "unitCost","costIsAdjusted",+ "createdAt","updatedAt",+ "customFields","itemId",- "createdAt",- "updatedBy",- "createdBy","itemPostingGroupId",- "tags",- "customFields",- "unitCost","companyId",- "standardCost",- "costingMethod"+ "createdBy",+ "updatedBy",+ "tags"]},{@@ -2949,282 +2949,282 @@"rows": 0,"columns": ["usage",+ "createdAt","updatedAt","itemId",- "createdAt",- "companyId","inspectionDocumentId",- "updatedBy",- "createdBy"+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "itemPlanning","rows": 0,"columns": [- "demandAccumulationPeriod",- "maximumInventoryQuantity",- "updatedBy",- "createdAt",- "maximumOrderQuantity","reorderingPolicy","critical",- "customFields",+ "demandAccumulationPeriod",+ "demandAccumulationIncludesInventory",+ "reorderPoint",+ "reorderQuantity",+ "minimumOrderQuantity",+ "maximumOrderQuantity","orderMultiple",- "createdBy",+ "createdAt","updatedAt",- "tags",+ "customFields",+ "maximumInventoryQuantity","demandAccumulationSafetyStock",- "reorderPoint",- "minimumOrderQuantity",+ "minimumReserveQuantity",+ "itemId","locationId","companyId",- "minimumReserveQuantity",- "reorderQuantity",- "demandAccumulationIncludesInventory",- "itemId"+ "createdBy",+ "updatedBy",+ "tags"]},{"name": "itemSerialSequence","rows": 0,"columns": [- "prefix",- "itemId",+ "next","size",- "updatedAt",- "suffix",- "companyId",- "createdAt","step",- "updatedBy",+ "createdAt",+ "updatedAt","id",+ "companyId",+ "itemId",+ "prefix",+ "suffix","createdBy",- "next"+ "updatedBy"]},{"name": "itemShelfLife","rows": 0,"columns": [- "updatedBy",- "itemId",- "customFields",- "companyId","mode",+ "days",+ "triggerTiming","createdAt","updatedAt",- "triggerTiming",+ "customFields","calculateFromBom",- "days",+ "itemId","triggerProcessId",- "createdBy"+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "itemSupersession","rows": 0,"columns": [- "discontinuationDate","supersessionMode",- "successorItemId",+ "discontinuationDate",+ "successorEffectivityDate","conversionFactor",- "updatedAt","createdAt",+ "updatedAt","itemId",- "successorEffectivityDate","companyId",- "updatedBy",- "createdBy"+ "successorItemId",+ "createdBy",+ "updatedBy"]},{"name": "itemUnitSalePrice","rows": 0,"columns": [- "customFields","unitSalePrice",- "companyId",+ "salesBlocked",+ "priceIncludesTax",+ "allowInvoiceDiscount","createdAt",+ "updatedAt",+ "customFields","itemId",+ "currencyCode",+ "salesUnitOfMeasureCode",+ "companyId","createdBy","updatedBy",- "priceIncludesTax",- "salesUnitOfMeasureCode",- "currencyCode",- "tags",- "allowInvoiceDiscount",- "salesBlocked",- "updatedAt"+ "tags"]},{"name": "makeMethod","rows": 0,"columns": [- "version",- "customFields",- "itemId",+ "createdAt","updatedAt",+ "customFields",+ "version","status",- "tags","id",- "updatedBy",+ "itemId","companyId",- "createdAt",- "changeOrderId",- "createdBy"+ "createdBy",+ "updatedBy",+ "tags",+ "changeOrderId"]},{"name": "changeOrderAffectedItem","rows": 0,"columns": [- "itemId",- "createdAt","sortOrder",- "baseMakeMethodId","changeType",- "changeSummary",- "createdBy",- "updatedBy",- "updatedAt",- "companyId",- "changeOrderId","supersessionMode",- "successorEffectivityDate","discontinuationDate",+ "successorEffectivityDate",+ "changeSummary",+ "createdAt",+ "updatedAt","id",+ "changeOrderId",+ "itemId",+ "draftMakeMethodId",+ "baseMakeMethodId","newItemId",- "draftMakeMethodId"+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "nonConformanceItem","rows": 0,"columns": [- "id",+ "createdAt",+ "updatedAt","disposition",- "createdBy",- "nonConformanceId",- "updatedBy","quantity",- "createdAt",- "companyId",+ "id",+ "nonConformanceId","itemId",- "updatedAt"+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "procedureStep","rows": 0,"columns": [+ "required",+ "sortOrder",+ "type",+ "minValue",+ "maxValue",+ "createdAt","updatedAt",+ "description",+ "id","procedureId",- "companyId",+ "name","unitOfMeasureCode",- "maxValue",- "minValue",- "id","listValues",- "sortOrder",- "name",- "createdAt",- "description",- "type","fileTypes",- "required",- "updatedBy",- "createdBy"+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "purchasingRfqLine","rows": 0,"columns": [- "createdBy",- "updatedBy","quantity",- "companyId",- "inventoryUnitOfMeasureCode",- "description",- "createdAt",- "itemId",- "purchaseUnitOfMeasureCode",- "id",- "order",- "externalNotes","conversionFactor",+ "order","internalNotes",- "updatedAt",+ "externalNotes","customFields",- "purchasingRfqId"+ "createdAt",+ "updatedAt",+ "id",+ "purchasingRfqId",+ "itemId",+ "description",+ "purchaseUnitOfMeasureCode",+ "inventoryUnitOfMeasureCode",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "qualityDocumentStep","rows": 0,"columns": [- "description",- "name",- "createdAt",- "type",- "fileTypes","required",- "updatedBy",- "createdBy",+ "sortOrder",+ "type",+ "minValue",+ "maxValue",+ "createdAt","updatedAt",+ "id","qualityDocumentId",- "companyId",+ "name",+ "description","unitOfMeasureCode",- "maxValue",- "id",- "minValue","listValues",- "sortOrder"+ "fileTypes",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "riskRegister","rows": 0,"columns": [- "createdBy",+ "id","source",- "updatedBy",- "notes",+ "severity",+ "likelihood",+ "status",+ "createdAt","updatedAt",+ "notes",+ "type",+ "companyId","title","description",- "severity",- "assignee",- "itemId",- "id","sourceId",- "companyId",- "createdAt",- "type",- "status",- "likelihood"+ "itemId",+ "assignee",+ "createdBy",+ "updatedBy"]},{"name": "trackedEntity","rows": 0,"columns": [- "expirationDate","quantity",- "companyId",- "createdBy",- "id",- "createdAt",- "readableId",- "sourceDocumentReadableId",- "sourceDocument","status",- "updatedBy","attributes",+ "createdAt",+ "expirationDate",+ "id",+ "sourceDocument","sourceDocumentId",- "itemId"+ "sourceDocumentReadableId",+ "companyId",+ "createdBy",+ "readableId",+ "itemId",+ "updatedBy"]},{@@ -3233,146 +3233,146 @@"columns": ["quantity","createdAt",+ "updatedAt",+ "id",+ "nonConformanceItemId","nonConformanceId","trackedEntityId","companyId",- "updatedAt",- "id","createdBy",- "updatedBy",- "nonConformanceItemId"+ "updatedBy"]},{"name": "nonConformanceTrackedEntity","rows": 0,"columns": [- "updatedBy",- "nonConformanceId",- "createdBy",- "id",+ "createdAt","updatedAt",+ "id",+ "nonConformanceId","trackedEntityId","companyId",- "createdAt"+ "createdBy",+ "updatedBy"]},{"name": "trackedActivityInput","rows": 0,"columns": [- "companyId",- "createdBy","quantity","createdAt","trackedActivityId",- "updatedBy",- "trackedEntityId"+ "trackedEntityId",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "trackedActivityOutput","rows": 0,"columns": [- "trackedEntityId",- "trackedActivityId",- "createdBy","quantity",+ "createdAt",+ "trackedActivityId",+ "trackedEntityId","companyId",- "updatedBy",- "createdAt"+ "createdBy",+ "updatedBy"]},{"name": "userAttributeCategory","rows": 0,"columns": [- "companyId","public","protected",+ "active","createdAt","updatedAt","id",- "emoji",- "active","name",+ "companyId","createdBy",- "updatedBy"+ "updatedBy",+ "emoji"]},{"name": "userAttribute","rows": 0,"columns": [- "updatedBy",+ "sortOrder","attributeDataTypeId","canSelfManage",- "sortOrder",- "userAttributeCategoryId",- "listOptions",- "updatedAt",+ "active","createdAt",+ "updatedAt","id",+ "name",+ "userAttributeCategoryId",+ "listOptions","createdBy",- "active",- "name"+ "updatedBy"]},{"name": "userAttributeValue","rows": 0,"columns": [+ "updatedAt","valueBoolean",- "userId",- "valueText","valueDate",- "updatedBy",- "valueFile",+ "valueNumeric",+ "createdAt",+ "id","userAttributeId",+ "userId",+ "valueText","valueUser","createdBy",- "id",- "createdAt",- "updatedAt",- "valueNumeric"+ "valueFile",+ "updatedBy"]},{"name": "userModulePreference","rows": 0,"columns": [- "userId",+ "position","hidden",- "id","updatedAt",+ "id",+ "userId","companyId",- "module",- "position"+ "module"]},{"name": "userToCompany","rows": 0,- "columns": ["userId", "companyId", "role"]+ "columns": ["role", "userId", "companyId"]},{"name": "warehouse","rows": 0,"columns": [- "requiresShipment",- "companyId",- "updatedBy",- "name",+ "requiresPick",+ "requiresPutAway","requiresBin",- "id",- "active",- "createdBy","requiresReceive",- "requiresPick",+ "requiresShipment",+ "active",+ "createdAt","updatedAt",+ "id",+ "name","locationId",- "requiresPutAway",- "createdAt"+ "companyId",+ "createdBy",+ "updatedBy"]},{@@ -3380,48 +3380,48 @@"rows": 0,"columns": ["status",+ "transferDate",+ "expectedReceiptDate","createdAt",+ "updatedAt","customFields",+ "id",+ "transferId","fromLocationId",- "updatedAt","toLocationId",- "expectedReceiptDate",+ "notes","reference",- "id",+ "companyId","createdBy",- "transferDate",- "tags","updatedBy",- "transferId",- "notes",- "companyId"+ "tags"]},{"name": "workCenter","rows": 0,"columns": [- "tags",- "overheadRate",- "description",- "createdAt",- "minimumBatchQuantity",- "defaultStandardFactor","laborRate",- "departmentId",+ "defaultStandardFactor",+ "active","customFields",- "batchCapacity",- "updatedBy",- "alwaysOn",+ "createdAt",+ "updatedAt","machineRate",- "createdBy",+ "overheadRate",+ "alwaysOn",+ "batchCapacity",+ "minimumBatchQuantity",+ "id","name",- "updatedAt",- "active",+ "description","locationId",+ "requiredAbilityId","companyId",- "id",- "requiredAbilityId"+ "createdBy",+ "updatedBy",+ "tags",+ "departmentId"]},{@@ -3429,161 +3429,161 @@"rows": 0,"columns": ["createdAt",+ "workCenterId",+ "ruleId","companyId","createdBy",- "updatedBy",- "workCenterId",- "ruleId"+ "updatedBy"]},{"name": "jobOperationBatch","rows": 0,"columns": [- "outputLotNumber",- "updatedBy",- "workCenterId","status",- "processId",- "companyId",- "mergeOutput",- "locationId",- "id","customFields","createdAt",+ "updatedAt",+ "mergeOutput",+ "id",+ "readableId",+ "companyId",+ "processId",+ "workCenterId",+ "locationId","notes","createdBy",- "readableId",- "updatedAt"+ "updatedBy",+ "outputLotNumber"]},{"name": "maintenanceSchedule","rows": 0,"columns": [+ "frequency",+ "priority","estimatedDuration",- "skipHolidays",- "thursday",- "wednesday",- "description",- "updatedBy",- "workCenterId",- "saturday",+ "active",+ "lastGeneratedAt",+ "nextDueAt",+ "createdAt","updatedAt",+ "monday","tuesday",- "takesWorkCenterOffline",- "frequency",- "createdBy",+ "wednesday",+ "thursday","friday",+ "saturday","sunday",- "locationId",- "nextDueAt",- "active",- "createdAt",+ "skipHolidays",+ "takesWorkCenterOffline",+ "id","name",- "monday",- "procedureId",- "priority",+ "description",+ "workCenterId","companyId",- "lastGeneratedAt",- "id"+ "createdBy",+ "updatedBy",+ "locationId",+ "procedureId"]},{"name": "maintenanceDispatch","rows": 0,"columns": [- "actualStartTime","content","status",- "completedAt",- "assignee",- "locationId",- "updatedBy",- "createdAt",- "plannedStartTime",- "companyId","priority",- "nonConformanceId",- "actualEndTime",- "createdBy",- "maintenanceDispatchId",+ "source",+ "plannedStartTime","plannedEndTime",- "procedureId",+ "actualStartTime",+ "actualEndTime",+ "completedAt",+ "createdAt",+ "updatedAt",+ "oeeImpact",+ "severity","takesWorkCenterOffline",+ "id",+ "maintenanceDispatchId","workCenterId",- "suspectedFailureModeId",- "updatedAt","maintenanceScheduleId",- "id",+ "suspectedFailureModeId","actualFailureModeId",- "severity",- "source",- "oeeImpact"+ "nonConformanceId",+ "assignee",+ "companyId",+ "createdBy",+ "updatedBy",+ "locationId",+ "procedureId"]},{"name": "maintenanceDispatchComment","rows": 0,"columns": [- "createdBy",- "updatedBy",- "comment",- "companyId","createdAt",- "id","updatedAt",- "maintenanceDispatchId"+ "id",+ "maintenanceDispatchId",+ "comment",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "maintenanceDispatchEvent","rows": 0,"columns": [- "createdBy",- "maintenanceDispatchId",- "updatedAt",+ "startTime","endTime",- "companyId",- "id","createdAt",- "notes",+ "updatedAt",+ "id",+ "maintenanceDispatchId","employeeId","workCenterId",- "updatedBy",- "startTime"+ "notes",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "maintenanceDispatchItem","rows": 0,"columns": [- "unitOfMeasureCode",- "updatedAt",- "itemId","quantity",- "updatedBy",- "createdBy",- "id","unitCost",- "maintenanceDispatchId","createdAt",- "companyId"+ "updatedAt",+ "id",+ "maintenanceDispatchId",+ "itemId",+ "unitOfMeasureCode",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "maintenanceDispatchItemTrackedEntity","rows": 0,"columns": [- "createdAt","quantity",+ "createdAt",+ "updatedAt",+ "id",+ "maintenanceDispatchItemId","trackedEntityId","companyId",- "updatedBy",- "maintenanceDispatchItemId","createdBy",- "id",- "updatedAt"+ "updatedBy"]},{@@ -3591,49 +3591,49 @@"rows": 0,"columns": ["createdAt",- "id","updatedAt",+ "id","maintenanceDispatchId",- "createdBy",- "updatedBy",+ "workCenterId","companyId",- "workCenterId"+ "createdBy",+ "updatedBy"]},{"name": "maintenanceScheduleItem","rows": 0,"columns": [- "companyId",- "updatedBy",- "id",- "updatedAt",+ "quantity","createdAt",+ "updatedAt",+ "id","maintenanceScheduleId",+ "itemId","unitOfMeasureCode",+ "companyId","createdBy",- "itemId",- "quantity"+ "updatedBy"]},{"name": "peopleAssignment","rows": 0,"columns": [- "overtimeHours",- "companyId",+ "date","createdAt",- "note",- "updatedBy",+ "updatedAt",+ "overtimeHours",+ "hours","id",- "createdBy",- "date",- "workCenterId",+ "companyId","locationId",- "hours",- "shiftId",+ "workCenterId","employeeId",- "updatedAt"+ "shiftId",+ "note",+ "createdBy",+ "updatedBy"]},{@@ -3641,64 +3641,64 @@"rows": 0,"columns": ["active",- "storageTypeIds",- "warehouseId","createdAt",- "companyId",- "tags",- "workCenterId",- "parentId",- "locationId",- "isWorkCenterDefault",+ "updatedAt","customFields",+ "isWorkCenterDefault",+ "id",+ "locationId",+ "warehouseId",+ "companyId",+ "createdBy","updatedBy","name",- "id",- "updatedAt",- "createdBy"+ "tags",+ "parentId",+ "storageTypeIds",+ "workCenterId"]},{"name": "itemLedger","rows": 0,"columns": [+ "entryNumber",+ "postingDate",+ "entryType","documentType",- "comment","quantity",- "updatedBy",- "trackedEntityStatus",- "createdBy",- "trackedEntityId",- "entryType",- "postingDate","createdAt",- "correctionOfItemLedgerId",- "externalDocumentId",- "storageUnitId",+ "trackedEntityStatus","id","documentId",+ "externalDocumentId",+ "itemId",+ "locationId",+ "storageUnitId","companyId",- "entryNumber",+ "createdBy","documentLineId",- "scrapReasonId",- "locationId",- "itemId"+ "trackedEntityId",+ "comment",+ "updatedBy",+ "correctionOfItemLedgerId",+ "scrapReasonId"]},{"name": "pickMethod","rows": 0,"columns": [+ "createdAt","updatedAt",+ "customFields","sortMethod",- "locationId",- "createdAt","itemId",- "customFields",- "updatedBy",- "companyId",+ "locationId","defaultStorageUnitId",- "createdBy"+ "companyId",+ "createdBy",+ "updatedBy"]},{@@ -3706,100 +3706,100 @@"rows": 0,"columns": ["quantity",- "itemId",- "createdBy",- "customFields",- "fromLocationId",- "notes","shippedQuantity",- "updatedAt",+ "receivedQuantity","createdAt",- "updatedBy",+ "updatedAt",+ "customFields",+ "id","transferId",- "companyId",- "fromStorageUnitId",- "toStorageUnitId",- "id",+ "itemId",+ "fromLocationId",+ "fromStorageUnitId","toLocationId",+ "toStorageUnitId","unitOfMeasureCode",- "receivedQuantity"+ "notes",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "workCenterProcess","rows": 0,"columns": [+ "createdAt",+ "updatedAt","workCenterId",- "updatedBy","processId",- "createdAt","companyId","createdBy",- "updatedAt"+ "updatedBy"]},{"name": "workCenterReplacementPart","rows": 0,"columns": [- "unitOfMeasureCode",- "createdBy",- "itemId","quantity",- "companyId",- "updatedBy",- "id",- "updatedAt","createdAt",- "workCenterId"+ "updatedAt",+ "id",+ "workCenterId",+ "itemId",+ "unitOfMeasureCode",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "workCenterShift","rows": 0,"columns": [- "updatedBy",+ "createdAt",+ "updatedAt",+ "id",+ "companyId","workCenterId","shiftId","createdBy",- "updatedAt",- "companyId",- "createdAt",- "id"+ "updatedBy"]},{"name": "cardTransaction","rows": 0,"columns": [- "integration",+ "type",+ "status",+ "transactionDate",+ "postingDate",+ "exchangeRate",+ "amount",+ "postedAt",+ "voidedAt","createdAt",- "supplierId",- "id",- "cardHolderName","updatedAt",+ "customFields",+ "id",+ "companyId",+ "cardTransactionId",+ "integration",+ "cardAccountId","offsetAccountId",+ "supplierId","merchantName",- "createdBy",- "currencyCode",- "companyId",+ "cardHolderName",+ "cardLast4","memo",- "exchangeRate",- "updatedBy",- "postingDate",+ "currencyCode",+ "journalId","postedBy",- "voidedAt",- "cardLast4",- "postedAt",- "status",- "customFields",- "cardAccountId","voidedBy",- "transactionDate",- "cardTransactionId",- "type",- "amount",- "journalId"+ "createdBy",+ "updatedBy"]},{@@ -3807,132 +3807,132 @@"rows": 0,"columns": ["amount",- "projectId",+ "sequence",+ "createdAt",+ "updatedAt",+ "customFields",+ "id",+ "companyId","cardTransactionId","accountId",- "updatedAt","costCenterId",- "createdAt",- "sequence",- "companyId",- "customFields","description",- "updatedBy","createdBy",- "id"+ "updatedBy",+ "projectId"]},{"name": "contractor","rows": 0,"columns": [- "customFields",- "id",- "createdAt","hoursPerWeek",- "updatedAt",- "tags",- "createdBy","active",+ "createdAt",+ "updatedAt",+ "customFields",+ "id","companyId",- "updatedBy"+ "createdBy",+ "updatedBy",+ "tags"]},{"name": "contractorAbility","rows": 0,"columns": [- "companyId",- "createdBy","createdAt","contractorId",- "updatedBy",- "abilityId"+ "abilityId",+ "createdBy",+ "companyId",+ "updatedBy"]},{"name": "costLedger","rows": 0,"columns": [- "quantity",- "costLedgerType",- "supplierId",- "companyId",- "remainingQuantity",- "appliesToCostLedgerId",- "nominalCost",+ "entryNumber","postingDate","itemLedgerType",- "documentType",- "externalDocumentId",- "id",+ "costLedgerType","adjustment",- "entryNumber",+ "documentType",+ "quantity","cost",+ "nominalCost","createdAt",+ "remainingQuantity",+ "id",+ "documentId",+ "externalDocumentId","itemId",- "documentId"+ "companyId",+ "supplierId",+ "appliesToCostLedgerId"]},{"name": "customer","rows": 0,"columns": [- "updatedBy",- "name",- "phone","createdAt",- "assignee",- "readableId",- "intercompanyCompanyId",- "createdBy",- "id",- "companyId",- "defaultCc",- "accountManagerId",- "website",- "customerStatusId",+ "updatedAt","customFields",- "customerTypeId",- "salesContactId",- "logo","taxPercent",- "updatedAt","embedding",+ "id",+ "name",+ "customerTypeId",+ "customerStatusId",+ "accountManagerId",+ "logo",+ "assignee",+ "companyId",+ "createdBy",+ "updatedBy","currencyCode",+ "phone",+ "fax",+ "website","tags",- "fax"+ "salesContactId",+ "defaultCc",+ "intercompanyCompanyId",+ "readableId"]},{"name": "customerAccount","rows": 0,- "columns": ["active", "companyId", "customerId", "id"]+ "columns": ["active", "id", "customerId", "companyId"]},{"name": "customerBankAccount","rows": 0,"columns": [- "createdBy",- "companyId","isPrimary",- "countryCode",- "accountNumber",- "currencyCode",- "id",- "bankCode",- "bankName","active",+ "createdAt",+ "updatedAt",+ "customFields",+ "id",+ "companyId","customerId","name",- "updatedBy",- "updatedAt",+ "accountHolderName",+ "bankName","bankAddress",+ "countryCode",+ "currencyCode",+ "accountNumber",+ "bankCode","swiftBic",- "customFields",- "accountHolderName",- "createdAt","notes",+ "createdBy",+ "updatedBy","tags"]},@@ -3940,48 +3940,48 @@"name": "customerItemPriceOverride","rows": 0,"columns": [- "notes",- "createdAt",+ "validFrom","validTo",+ "active",+ "applyRulesOnTop",+ "createdAt","updatedAt",+ "id",+ "customerId","customerTypeId","itemId",- "validFrom",- "createdBy",- "applyRulesOnTop",- "id",+ "notes","companyId",- "active",- "updatedBy",- "customerId"+ "createdBy",+ "updatedBy"]},{"name": "customerItemPriceOverrideBreak","rows": 0,"columns": [- "active",- "overridePrice","quantity",- "createdBy",+ "overridePrice",+ "active",+ "createdAt",+ "updatedAt","id",- "updatedBy",- "companyId","customerItemPriceOverrideId",- "updatedAt",- "createdAt"+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "customerLocation","rows": 0,"columns": [- "name",- "addressId","customFields","id",- "tags","customerId",+ "addressId",+ "name",+ "tags","companyId"]},@@ -3989,13 +3989,13 @@"name": "customerContact","rows": 0,"columns": [- "userId",- "customerLocationId",- "contactId",- "tags",- "id","customFields",+ "id","customerId",+ "contactId",+ "customerLocationId",+ "userId",+ "tags","companyId"]},@@ -4003,138 +4003,138 @@"name": "customerPartToItem","rows": 0,"columns": [- "companyId",- "itemId",- "customerPartRevision","customerId",- "id",- "customerPartId"+ "customerPartId",+ "customerPartRevision",+ "itemId",+ "companyId",+ "id"]},{"name": "customerPayment","rows": 0,"columns": [- "paymentTermId",- "invoiceCustomerLocationId",- "invoiceCustomerContactId",- "companyId",- "updatedBy",+ "updatedAt","customerId","invoiceCustomerId",- "updatedAt"+ "invoiceCustomerLocationId",+ "invoiceCustomerContactId",+ "paymentTermId",+ "companyId",+ "updatedBy"]},{"name": "customerShipping","rows": 0,"columns": [- "shippingCustomerId",- "incoterm","updatedAt",- "incotermLocation",- "updatedBy",+ "incoterm","customerId",- "shippingMethodId",+ "shippingCustomerId","shippingCustomerLocationId","shippingCustomerContactId",+ "shippingTermId",+ "shippingMethodId","companyId",- "shippingTermId"+ "updatedBy",+ "incotermLocation"]},{"name": "customerTax","rows": 0,"columns": [+ "taxExempt","taxExemptionReason",- "companyId",- "customerId",- "updatedBy",- "taxExemptionCertificatePath","updatedAt",+ "customerId","taxId",- "taxExempt",- "taxExemptionCertificateNumber","vatNumber",- "eori"+ "eori",+ "taxExemptionCertificateNumber",+ "taxExemptionCertificatePath",+ "companyId",+ "updatedBy"]},{"name": "fixture","rows": 0,"columns": [+ "approved","customFields",+ "createdAt","updatedAt","id",- "createdAt",- "updatedBy",- "createdBy",- "tags","itemId",+ "customerId","approvedBy","companyId",- "approved",- "customerId"+ "createdBy",+ "updatedBy",+ "tags"]},{"name": "nonConformanceCustomer","rows": 0,"columns": [- "createdBy",- "id",- "updatedBy",- "nonConformanceId","createdAt","updatedAt",+ "id",+ "nonConformanceId","customerId",- "companyId"+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "opportunity","rows": 0,"columns": [- "customerId","id",- "purchaseOrderDocumentPath","companyId",- "requestForQuoteDocumentPath"+ "purchaseOrderDocumentPath",+ "requestForQuoteDocumentPath",+ "customerId"]},{"name": "salesOrder","rows": 0,"columns": [- "opportunityId",- "exchangeRateUpdatedAt",- "currencyCode",- "createdBy",- "updatedAt",+ "revisionId","status",+ "orderDate","closedAt",- "revisionId",- "salesPersonId",+ "customFields","createdAt",- "locationId",- "closedBy",- "updatedBy",- "assignee",- "orderDate",+ "updatedAt","exchangeRate",- "customerContactId",+ "exchangeRateUpdatedAt","externalNotes",- "customerEngineeringContactId",- "customerId",- "completedDate",- "salesOrderId",- "companyId",- "customFields","internalNotes","sentCompleteDate",- "customerReference",+ "completedDate","id",- "customerLocationId"+ "salesOrderId",+ "currencyCode",+ "customerId",+ "customerLocationId",+ "customerContactId",+ "customerReference",+ "assignee",+ "companyId",+ "closedBy",+ "createdBy",+ "updatedBy",+ "locationId",+ "salesPersonId",+ "opportunityId",+ "customerEngineeringContactId"]},{@@ -4146,605 +4146,605 @@"name": "salesOrderLine","rows": 0,"columns": [- "exchangeRate",- "sentDate",- "createdBy",- "modelUploadId",- "promisedDate",- "description",- "accountId",- "salesOrderId",- "externalNotes",+ "salesOrderLineType",+ "saleQuantity",+ "quantitySent","quantityInvoiced",- "locationId",+ "unitPrice",+ "setupPrice",+ "sentComplete",+ "invoicedComplete",+ "createdAt","updatedAt",- "priceTrace",- "quantitySent","customFields",- "taxPercent",- "saleQuantity",- "sortOrder",- "id",- "methodType","status",- "assetId",- "createdAt",+ "promisedDate",+ "addOnCost",+ "methodType",+ "exchangeRate","shippingCost",- "nonTaxableAddOnCost",+ "taxPercent","internalNotes",- "setupPrice",- "sentComplete",- "unitPrice",- "salesOrderLineType",+ "externalNotes",+ "sentDate",+ "nonTaxableAddOnCost",+ "priceTrace",+ "sortOrder",+ "id",+ "salesOrderId","itemId",+ "assetId",+ "description",+ "unitOfMeasureCode",+ "locationId","storageUnitId",+ "companyId",+ "createdBy","updatedBy",- "pricingRuleId",- "unitOfMeasureCode",- "addOnCost",- "invoicedComplete",- "companyId"+ "modelUploadId",+ "accountId",+ "pricingRuleId"]},{"name": "nonConformanceSalesOrderLine","rows": 0,"columns": [- "id",+ "createdAt","updatedAt",- "companyId",+ "id","nonConformanceId",- "updatedBy",- "createdBy",- "salesOrderReadableId",- "salesOrderId","salesOrderLineId",- "createdAt"+ "salesOrderId",+ "salesOrderReadableId",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "salesOrderPayment","rows": 0,"columns": [- "id",+ "paymentComplete","updatedAt","customFields",- "paymentComplete",+ "id","invoiceCustomerId",- "companyId",- "updatedBy",- "paymentTermId",+ "invoiceCustomerLocationId","invoiceCustomerContactId",- "invoiceCustomerLocationId"+ "paymentTermId",+ "companyId",+ "updatedBy"]},{"name": "salesOrderShipment","rows": 0,"columns": [- "incoterm",- "companyId",- "updatedAt","receiptRequestedDate",- "customerLocationId",- "shippingCost",- "incotermLocation",+ "receiptPromisedDate","deliveryDate",- "assignee",+ "dropShipment",+ "updatedAt","customFields",- "supplierLocationId",+ "shippingCost",+ "incoterm",+ "id",+ "locationId","shippingMethodId","shippingTermId",- "receiptPromisedDate",- "customerId",- "trackingNumber",- "id",- "dropShipment","notes",+ "trackingNumber",+ "customerId",+ "customerLocationId","supplierId",- "locationId",- "updatedBy"+ "supplierLocationId",+ "companyId",+ "updatedBy",+ "assignee",+ "incotermLocation"]},{"name": "salesOrderStatusHistory","rows": 0,"columns": [- "updatedBy","status","createdAt",- "createdBy",+ "id","salesOrderId",+ "createdBy","companyId",- "id"+ "updatedBy"]},{"name": "salesOrderTransaction","rows": 0,"columns": [- "salesOrderId",- "companyId",- "id","type",+ "createdAt",+ "id",+ "salesOrderId","userId",- "createdAt"+ "companyId"]},{"name": "salesReturnOrder","rows": 0,"columns": [- "updatedAt",+ "status","exchangeRate",- "createdAt",- "customerLocationId",- "assignee",- "updatedBy",- "internalNotes",+ "orderDate","expirationDate",- "status",- "customerId",- "companyId",- "createdBy",- "customerReference",+ "internalNotes",+ "externalNotes",+ "createdAt",+ "updatedAt","customFields",- "salesOrderId","id",- "currencyCode",- "customerContactId",- "externalNotes","salesReturnOrderId",- "orderDate",+ "customerId",+ "customerLocationId",+ "customerContactId",+ "customerReference","locationId",- "replacementSalesOrderId"+ "salesOrderId",+ "replacementSalesOrderId",+ "currencyCode",+ "assignee",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "salesRfq","rows": 0,"columns": [- "salesPersonId",- "customerId",- "noQuoteReasonId",- "id",+ "revisionId",+ "status","rfqDate","expirationDate",- "internalNotes",- "customerEngineeringContactId",- "customerReference",+ "customFields",+ "createdAt",+ "updatedAt",+ "externalNotes",+ "internalNotes","completedDate",+ "id","rfqId",+ "employeeId",+ "customerId",+ "customerContactId",+ "customerReference","locationId",- "customFields",- "tags",- "createdAt",+ "assignee","companyId",- "customerLocationId",+ "createdBy","updatedBy",- "employeeId",+ "customerLocationId",+ "salesPersonId",+ "tags",+ "noQuoteReasonId","opportunityId",- "externalNotes",- "customerContactId",- "createdBy",- "updatedAt",- "status",- "assignee",- "revisionId"+ "customerEngineeringContactId"]},{"name": "salesRfqFavorite","rows": 0,- "columns": ["userId", "rfqId"]+ "columns": ["rfqId", "userId"]},{"name": "salesRfqLine","rows": 0,"columns": [+ "quantity",+ "order","internalNotes",- "unitOfMeasureCode",- "salesRfqId",+ "externalNotes","customFields",+ "createdAt","updatedAt",- "description",- "externalNotes","id",- "order",- "quantity",+ "salesRfqId",+ "itemId",+ "description",+ "unitOfMeasureCode",+ "companyId",+ "createdBy",+ "updatedBy","modelUploadId","customerPartId",- "createdAt",- "updatedBy",- "createdBy",- "tags","customerPartRevision",- "companyId",- "itemId"+ "tags"]},{"name": "externalLink","rows": 0,"columns": [- "documentType",- "supplierId","id",+ "documentType",+ "createdAt","expiresAt",- "customerId","documentId",+ "customerId","companyId",- "createdAt"+ "supplierId"]},{"name": "quote","rows": 0,"columns": [+ "revisionId",+ "dueDate","expirationDate",- "currencyCode",- "salesPersonId",- "id",- "customerId",- "exchangeRateUpdatedAt",- "digitalQuoteAcceptedBy",- "digitalQuoteAcceptedByEmail",+ "status",+ "customFields",+ "createdAt",+ "updatedAt",+ "externalNotes","internalNotes",- "digitalQuoteRejectedByEmail",+ "exchangeRate",+ "exchangeRateUpdatedAt",+ "externalLinkId",+ "completedDate",+ "id",+ "quoteId",+ "salesPersonId","estimatorId",- "assignee",+ "customerId",+ "customerLocationId","customerContactId",- "quoteId",- "opportunityId",+ "customerReference","locationId",- "updatedAt",- "customFields",- "exchangeRate",+ "assignee",+ "companyId",+ "createdBy","updatedBy",- "dueDate",+ "currencyCode",+ "digitalQuoteAcceptedBy",+ "digitalQuoteAcceptedByEmail","tags",- "customerLocationId",- "createdBy",- "completedDate",- "status",- "customerEngineeringContactId",- "externalNotes",- "externalLinkId","digitalQuoteRejectedBy",- "customerReference",- "revisionId",- "createdAt",- "companyId"+ "digitalQuoteRejectedByEmail",+ "opportunityId",+ "customerEngineeringContactId"]},{"name": "job","rows": 0,"columns": [- "notes",+ "quantity",+ "scrapQuantity",+ "quantityComplete",+ "quantityShipped","quantityReceivedToInventory",- "salesOrderLineId",- "createdBy",- "customerId",+ "notes",+ "customFields",+ "createdAt",+ "updatedAt",+ "configuration","releasedDate",- "modelUploadId",- "assignee","completedDate",- "status",- "customFields",+ "estimatedTime",+ "actualTime","startDate",- "updatedBy",- "quoteLineId",- "quoteId",+ "priority","projectedCompletionAt",- "itemId",- "quantityShipped",- "unitOfMeasureCode",- "createdAt",- "locationId","scheduleOutdatedAt",- "priority",- "storageUnitId",- "scrapQuantity",- "updatedAt",+ "status",+ "dueDate","deadlineType","id",+ "jobId",+ "itemId",+ "unitOfMeasureCode",+ "customerId",+ "locationId",+ "salesOrderId",+ "salesOrderLineId",+ "quoteId",+ "quoteLineId",+ "modelUploadId",+ "assignee","companyId",- "quantity",- "estimatedTime",+ "createdBy",+ "updatedBy","tags",- "dueDate",- "configuration",- "quantityComplete",- "scheduleOutdatedReason",- "actualTime",- "jobId",- "salesOrderId"+ "storageUnitId",+ "scheduleOutdatedReason"]},{"name": "fulfillment","rows": 0,"columns": [- "createdBy",- "salesOrderLineId",- "companyId",- "updatedBy",- "id",- "createdAt","type","quantity",- "jobId"+ "createdAt",+ "id",+ "salesOrderLineId",+ "jobId",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "jobFavorite","rows": 0,- "columns": ["userId", "jobId"]+ "columns": ["jobId", "userId"]},{"name": "quoteFavorite","rows": 0,- "columns": ["userId", "quoteId"]+ "columns": ["quoteId", "userId"]},{"name": "quoteLine","rows": 0,"columns": [- "customerPartId",- "noQuoteReason",- "configuration",- "pricingRuleId",- "itemType",- "quoteId",- "unitOfMeasureCode",- "createdBy",- "taxPercent",- "itemId",- "customerPartRevision",- "unitPricePrecision",- "description",- "id",- "sortOrder",- "externalNotes",- "locationId",- "updatedBy",- "customFields",- "internalNotes","quoteRevisionId","status",+ "methodType",+ "internalNotes","updatedAt",- "tags",- "companyId",+ "customFields","quantity",+ "additionalCharges",+ "taxPercent",+ "unitPricePrecision",+ "externalNotes",+ "configuration","priceTrace",- "methodType",- "modelUploadId",+ "sortOrder",+ "id",+ "quoteId","estimatorId",- "additionalCharges"+ "itemId",+ "itemType",+ "description",+ "customerPartId",+ "customerPartRevision",+ "unitOfMeasureCode",+ "companyId",+ "createdBy",+ "updatedBy",+ "modelUploadId",+ "locationId",+ "noQuoteReason",+ "tags",+ "pricingRuleId"]},{"name": "quoteLinePrice","rows": 0,"columns": [- "companyId",- "updatedBy",- "quoteId",- "priceSource",- "createdAt",- "createdBy",- "categoryMarkups",- "leadTime","quantity",- "unitPrice",- "quoteLineId",+ "leadTime","discountPercent",+ "createdAt","updatedAt",+ "unitPrice",+ "exchangeRate","shippingCost",- "exchangeRate"+ "categoryMarkups",+ "quoteId",+ "quoteLineId",+ "createdBy",+ "updatedBy",+ "companyId",+ "priceSource"]},{"name": "quotePayment","rows": 0,"columns": [- "companyId",+ "updatedAt",+ "customFields",+ "id",+ "invoiceCustomerId","invoiceCustomerLocationId","invoiceCustomerContactId","paymentTermId",- "customFields",- "updatedAt",- "invoiceCustomerId",- "updatedBy",- "id"+ "companyId",+ "updatedBy"]},{"name": "quoteShipment","rows": 0,"columns": [- "shippingMethodId",- "shippingTermId",- "updatedBy",- "incotermLocation","receiptRequestedDate",- "locationId","updatedAt",- "incoterm","shippingCost",+ "incoterm","id",- "companyId"+ "locationId",+ "shippingMethodId",+ "shippingTermId",+ "companyId",+ "updatedBy",+ "incotermLocation"]},{"name": "capacityReservation","rows": 0,"columns": [- "jobId",- "createdAt",- "id",- "scenarioId",- "createdBy",+ "resourceKind",+ "startAt","endAt",- "companyId",+ "createdAt","updatedAt",+ "earliestStartAt","workHours","isPlaceholder",- "scheduleNote",- "updatedBy",- "operationId",- "startAt",- "jobOperationBatchId",+ "id",+ "companyId","resourceId",- "earliestStartAt",- "resourceKind"+ "operationId",+ "jobId",+ "scenarioId",+ "createdBy",+ "updatedBy",+ "scheduleNote",+ "jobOperationBatchId"]},{"name": "gauge","rows": 0,"columns": [- "createdBy",+ "dateAcquired",+ "gaugeCalibrationStatus",+ "gaugeStatus",+ "gaugeRole","calibrationIntervalInMonths",- "serialNumber",- "updatedBy",- "companyId",- "locationId",- "updatedAt",+ "lastCalibrationDate",+ "nextCalibrationDate","customFields","createdAt",- "modelNumber",- "supplierId",- "nextCalibrationDate",+ "updatedAt","lastCalibrationStatus",- "dateAcquired",- "gaugeRole","id",- "gaugeCalibrationStatus",- "description","gaugeId",- "lastCalibrationDate",+ "supplierId",+ "modelNumber",+ "serialNumber",+ "description",+ "gaugeTypeId",+ "locationId","storageUnitId",- "gaugeStatus",- "gaugeTypeId"+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "gaugeCalibrationRecord","rows": 0,"columns": [+ "dateCalibrated",+ "inspectionStatus",+ "requiresAction",+ "requiresAdjustment",+ "requiresRepair",+ "notes","customFields",- "id","createdAt",- "requiresAdjustment",- "temperature","updatedAt",+ "temperature",+ "humidity",+ "calibrationAttempts",+ "id","gaugeId",- "notes","companyId",- "requiresAction","createdBy",- "calibrationAttempts",- "supplierId",- "humidity","updatedBy",- "dateCalibrated",- "inspectionStatus",- "measurementStandard",+ "supplierId","approvedBy",- "requiresRepair"+ "measurementStandard"]},{"name": "inspection","rows": 0,"columns": [- "status",- "notes",+ "lotSize",+ "samplingStandard",+ "samplingPlanType",+ "sampleSize",+ "acceptanceNumber",+ "rejectionNumber","aql",- "sourceDocument",+ "inspectionLevel",+ "severity",+ "status",+ "dispositionedAt","createdAt",+ "updatedAt",+ "sourceDocument",+ "id",+ "inspectionId",+ "itemId",+ "itemReadableId","supplierId",+ "codeLetter",+ "notes","dispositionedBy",- "acceptanceNumber",- "sourceDocumentReadableId",- "itemId","companyId",- "updatedBy",- "codeLetter",- "dispositionedAt",- "inspectionLevel",- "inspectionId",- "rejectionNumber",- "severity",- "samplingPlanType","createdBy",- "lotSize",- "sourceDocumentLineId",- "sourceDocumentId",+ "updatedBy","inspectionDocumentId",- "sampleSize",- "id",- "samplingStandard",- "updatedAt",- "itemReadableId"+ "sourceDocumentId",+ "sourceDocumentLineId",+ "sourceDocumentReadableId"]},{"name": "inspectionSample","rows": 0,"columns": [+ "status","inspectedAt",+ "createdAt",+ "updatedAt",+ "id",+ "inspectionId","trackedEntityId",- "status","notes",- "updatedBy",+ "inspectedBy","companyId","createdBy",- "inspectionId",- "inspectedBy",- "createdAt",- "id",- "updatedAt"+ "updatedBy"]},{"name": "inspectionMeasurement","rows": 0,"columns": [- "inspectionSampleId",- "updatedAt",- "inspectionFeatureId",- "notes","value",+ "status",+ "inspectedAt","createdAt",- "updatedBy",+ "updatedAt",+ "id","inspectionId",+ "inspectionSampleId",+ "inspectionFeatureId",+ "notes","inspectedBy","companyId",- "inspectedAt",- "id","createdBy",- "status"+ "updatedBy"]},{"name": "inspectionSamplingPlan","rows": 0,"columns": [- "updatedAt",- "acceptanceNumber",- "codeLetter","sampleSize",- "inspectionFeatureId",+ "acceptanceNumber","rejectionNumber",+ "createdAt",+ "updatedAt","id",- "createdBy",- "updatedBy",+ "inspectionId",+ "inspectionFeatureId",+ "codeLetter","companyId",- "createdAt",- "inspectionId"+ "createdBy",+ "updatedBy"]},{@@ -4752,198 +4752,198 @@"rows": 0,"columns": ["createdAt",- "companyId",- "inspectionId",- "updatedBy","id",+ "nonConformanceId",+ "inspectionId",+ "companyId","createdBy",- "nonConformanceId"+ "updatedBy"]},{"name": "inspectionHistory","rows": 0,"columns": [- "outcome","samplingStandard",- "createdBy",- "supplierId",- "createdAt",- "itemId",+ "severity","inspectionLevel",- "id",+ "aql","lotSize",+ "sampleSize","defectsFound",- "severity",- "updatedBy",+ "createdAt",+ "id","inspectionId",+ "itemId",+ "supplierId",+ "outcome","companyId",- "aql",- "sampleSize"+ "createdBy",+ "updatedBy"]},{"name": "itemReplenishment","rows": 0,"columns": [- "createdBy","conversionFactor",- "scrapPercentage",+ "purchasingBlocked",+ "manufacturingBlocked",+ "requiresConfiguration",+ "lotSize",+ "createdAt","updatedAt",- "updatedBy",- "purchasingUnitOfMeasureCode",- "tags",+ "customFields",+ "scrapPercentage","leadTime",- "requiresConfiguration","itemId",- "companyId",- "purchasingBlocked",- "customFields","preferredSupplierId",- "createdAt",- "manufacturingBlocked",- "lotSize"+ "purchasingUnitOfMeasureCode",+ "companyId",+ "createdBy",+ "updatedBy",+ "tags"]},{"name": "jobMakeMethod","rows": 0,"columns": [- "id",+ "quantityPerParent",+ "createdAt","updatedAt","customFields",- "companyId",+ "requiresSerialTracking",+ "requiresBatchTracking",+ "version","itemScrapPercentage",+ "id","jobId",- "requiresSerialTracking",+ "parentMaterialId",+ "itemId",+ "companyId","createdBy","updatedBy",- "trackedEntityId",- "quantityPerParent",- "version",- "itemId",- "requiresBatchTracking",- "parentMaterialId",- "createdAt"+ "trackedEntityId"]},{"name": "jobMaterial","rows": 0,"columns": [- "updatedAt",+ "methodType",+ "order",+ "quantity",+ "scrapQuantity",+ "unitCost","createdAt",- "jobOperationId",+ "updatedAt",+ "customFields","estimatedQuantity",- "itemScrapPercentage",- "unitOfMeasureCode",- "jobMakeMethodId",- "itemType",- "requiresSerialTracking",- "order","defaultStorageUnit",- "substitutedFromItemId",- "companyId",- "itemId",- "updatedBy",- "customFields",- "methodType","quantityIssued",- "quantity",- "id",+ "requiresSerialTracking","requiresBatchTracking","kit",- "description",+ "itemScrapPercentage","substitutionFactor",- "scrapQuantity",- "storageUnitId",- "createdBy",+ "id","jobId",- "unitCost"+ "itemId",+ "itemType",+ "description",+ "unitOfMeasureCode",+ "companyId",+ "createdBy",+ "updatedBy",+ "jobMakeMethodId",+ "jobOperationId",+ "storageUnitId",+ "substitutedFromItemId"]},{"name": "stockTransferLine","rows": 0,"columns": [- "fromStorageUnitId",- "trackedEntityId",- "id",- "pickedQuantity","quantity",+ "pickedQuantity",+ "requiresBatchTracking","requiresSerialTracking",- "stockTransferId",- "createdBy","createdAt","updatedAt",+ "id",+ "stockTransferId",+ "jobId",+ "jobMaterialId","itemId",- "requiresBatchTracking",+ "fromStorageUnitId","toStorageUnitId",- "updatedBy",- "jobMaterialId",+ "trackedEntityId","companyId",- "jobId"+ "createdBy",+ "updatedBy"]},{"name": "jobMaterialStep","rows": 0,- "columns": ["jobOperationStepId", "jobMaterialId", "quantity"]+ "columns": ["quantity", "jobMaterialId", "jobOperationStepId"]},{"name": "jobOperation","rows": 0,"columns": [- "conflictReason",- "overheadRate",- "jobId",- "status",- "dueDate",- "machineUnit",- "customFields",- "operationQuantity",+ "order","setupTime",- "targetQuantity",- "quantityReworked",- "laborTime",- "companyId",- "inspectionDocumentId","setupUnit",- "projectedCompletionAt",- "id",+ "laborTime","laborUnit",- "updatedAt",- "tags",- "procedureId",- "workCenterId",- "hasConflict",- "createdAt",- "readyAt",- "jobOperationBatchId",+ "machineTime",+ "machineUnit","operationOrder",- "jobMakeMethodId",- "order",- "startDate",+ "laborRate",+ "overheadRate",+ "machineRate","operationType","operationMinimumCost",- "assemblyInstructionId",- "updatedBy",- "priority",- "description",+ "operationLeadTime",+ "operationUnitCost","workInstruction",- "assignee",- "quantityScrapped",- "reworkId",- "operationSupplierProcessId",+ "createdAt",+ "updatedAt",+ "customFields",+ "operationQuantity","quantityComplete",- "machineTime",- "operationLeadTime",- "processId",+ "quantityScrapped",+ "quantityReworked",+ "status",+ "priority",+ "startDate",+ "dueDate",+ "hasConflict",+ "targetQuantity","manuallyScheduled",- "machineRate",+ "readyAt",+ "projectedCompletionAt",+ "id",+ "jobId",+ "jobMakeMethodId",+ "processId",+ "workCenterId",+ "description",+ "operationSupplierProcessId",+ "companyId","createdBy",- "laborRate",- "operationUnitCost"+ "updatedBy",+ "assignee",+ "tags",+ "procedureId",+ "conflictReason",+ "reworkId",+ "assemblyInstructionId",+ "inspectionDocumentId",+ "jobOperationBatchId"]},{@@ -4951,134 +4951,134 @@"rows": 0,"columns": ["createdAt",- "companyId",- "jobId","operationId",- "dependsOnId"+ "dependsOnId",+ "jobId",+ "companyId"]},{"name": "jobOperationParameter","rows": 0,"columns": [- "id",- "updatedBy","createdAt",- "key","updatedAt",- "companyId",- "operationId",+ "id",+ "key","value",- "createdBy"+ "operationId",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "jobOperationTool","rows": 0,"columns": [+ "quantity","createdAt",- "id",- "updatedBy","updatedAt",+ "id","operationId",+ "toolId","companyId","createdBy",- "quantity",- "toolId"+ "updatedBy"]},{"name": "nonConformanceJobOperation","rows": 0,"columns": [- "jobReadableId",- "jobOperationId",- "jobId","createdAt","updatedAt","id",- "companyId","nonConformanceId",- "updatedBy",- "createdBy"+ "jobOperationId",+ "jobId",+ "jobReadableId",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "pickingListLine","rows": 0,"columns": [+ "quantityToPick",+ "quantityPicked","status",- "jobOperationId",- "updatedAt","createdAt",+ "updatedAt","customFields","quantityReturned",- "jobMaterialId",- "jobId",- "createdBy",- "quantityToPick",- "toStorageUnitId","id",- "itemId","pickingListId",- "companyId",- "updatedBy",+ "jobId",+ "jobMaterialId",+ "jobOperationId",+ "itemId","storageUnitId",- "quantityPicked"+ "toStorageUnitId",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "pickingListLineTrackedEntity","rows": 0,"columns": [+ "quantity",+ "quantityPicked","pickingListLineId","trackedEntityId",- "companyId",- "quantityPicked",- "quantity"+ "companyId"]},{"name": "productionEvent","rows": 0,"columns": [- "createdBy",- "companyId",- "id",+ "type",+ "startTime",+ "endTime","createdAt",+ "updatedAt",+ "postedToGL",+ "id",+ "jobOperationId",+ "employeeId","workCenterId",+ "companyId",+ "createdBy","updatedBy",- "jobOperationId",- "postedToGL","notes",- "jobOperationBatchId",- "endTime",- "updatedAt",- "employeeId",- "type",- "startTime"+ "jobOperationBatchId"]},{"name": "productionQuantity","rows": 0,"columns": [- "laborProductionEventId",- "createdBy",- "companyId",- "id",+ "type",+ "quantity","createdAt",- "notes",- "jobOperationId",- "updatedBy",- "inspectionSampleId",- "inspectionId","updatedAt",+ "id",+ "jobOperationId","setupProductionEventId",+ "laborProductionEventId","machineProductionEventId",- "type",+ "notes",+ "companyId",+ "createdBy",+ "updatedBy","scrapReasonId",- "quantity"+ "inspectionId",+ "inspectionSampleId"]},{@@ -5086,74 +5086,74 @@"rows": 0,"columns": ["createdAt",- "updatedBy",+ "updatedAt",+ "id",+ "jobOperationId","note","companyId","createdBy",- "productionQuantityId",- "id",- "updatedAt",- "jobOperationId"+ "updatedBy",+ "productionQuantityId"]},{"name": "rework","rows": 0,"columns": [- "jobId",- "companyId",- "requestedById",- "createdAt",+ "quantity","completedAt",+ "createdAt",+ "updatedAt","id",- "quantity",+ "jobId","triggeredAtJobOperationId","targetJobOperationId",- "updatedAt",- "reason"+ "reason",+ "requestedById",+ "companyId"]},{"name": "jobOperationStep","rows": 0,"columns": [+ "required",+ "sortOrder","type",- "fileTypes",+ "minValue","maxValue",+ "createdAt",+ "updatedAt",+ "description","id",- "listValues",- "minValue","name",+ "unitOfMeasureCode",+ "listValues",+ "fileTypes",+ "operationId","companyId",- "updatedAt",- "updatedBy","createdBy",- "assemblyInstructionStepId",- "operationId",- "nonConformanceInvestigationId",- "sortOrder",- "unitOfMeasureCode",- "description",+ "updatedBy","nonConformanceActionId",- "createdAt",- "required"+ "nonConformanceInvestigationId",+ "assemblyInstructionStepId"]},{"name": "jobOperationStepRecord","rows": 0,"columns": [- "createdAt",- "booleanValue","numericValue",- "userValue",+ "booleanValue",+ "createdAt",+ "updatedAt","index",- "createdBy",- "updatedBy",+ "jobOperationStepId","value",+ "userValue","companyId",- "jobOperationStepId",- "updatedAt",+ "createdBy",+ "updatedBy","id"]},@@ -5161,189 +5161,189 @@"name": "jobOperationStepSlide","rows": 0,"columns": [- "annotations","sortOrder",- "caption",+ "createdAt",+ "updatedAt",+ "annotations",+ "id",+ "stepId","imagePath",+ "caption",+ "companyId","createdBy",- "id","updatedBy","size",- "companyId",- "stepId",- "modelUploadId",- "createdAt",- "updatedAt"+ "modelUploadId"]},{"name": "jobOperationToolStep","rows": 0,- "columns": ["jobOperationStepId", "jobOperationToolId"]+ "columns": ["jobOperationToolId", "jobOperationStepId"]},{"name": "kanban","rows": 0,"columns": [- "completedBarcodeOverride",- "updatedBy",- "createdAt",- "locationId",- "supplierId",- "jobId",- "fromStorageUnitId",- "quantity","replenishmentSystem",- "updatedAt",- "storageUnitId",- "companyId",- "id",+ "quantity","conversionFactor","autoRelease",- "purchaseUnitOfMeasureCode",+ "createdAt",+ "updatedAt",+ "autoStartJob",+ "id","itemId",+ "locationId",+ "storageUnitId",+ "supplierId",+ "purchaseUnitOfMeasureCode",+ "companyId","createdBy",- "autoStartJob"+ "updatedBy",+ "completedBarcodeOverride",+ "jobId",+ "fromStorageUnitId"]},{"name": "methodMaterial","rows": 0,"columns": [- "makeMethodId",- "updatedBy",- "unitOfMeasureCode",+ "methodType",+ "quantity","createdAt",- "storageUnitIds",- "companyId",- "id",- "createdBy",- "itemId",- "sourcingType",+ "updatedAt","customFields",- "methodType",- "materialMakeMethodId",- "methodOperationId",+ "order","scrapQuantity",- "quantity","kit",- "updatedAt",+ "storageUnitIds",+ "sourcingType",+ "id",+ "makeMethodId",+ "materialMakeMethodId","itemType",- "order",+ "itemId",+ "unitOfMeasureCode",+ "companyId",+ "createdBy",+ "updatedBy",+ "methodOperationId","tags"]},{"name": "methodMaterialStep","rows": 0,- "columns": ["quantity", "methodOperationStepId", "methodMaterialId"]+ "columns": ["quantity", "methodMaterialId", "methodOperationStepId"]},{"name": "methodOperation","rows": 0,"columns": [- "companyId",- "workInstruction",- "id",- "operationType",- "createdBy",- "inspectionDocumentId",- "makeMethodId",+ "order",+ "operationOrder",+ "createdAt",+ "updatedAt","customFields",+ "setupTime",+ "setupUnit",+ "laborTime",+ "laborUnit",+ "machineTime","machineUnit",- "assemblyInstructionId",- "procedureId",+ "operationType",+ "workInstruction","operationMinimumCost","operationLeadTime",- "createdAt",- "setupUnit",- "laborUnit",+ "operationUnitCost",+ "id",+ "makeMethodId",+ "description",+ "companyId",+ "createdBy","updatedBy",- "laborTime","processId",- "operationSupplierProcessId",- "setupTime","workCenterId",- "order",- "updatedAt",- "operationOrder",- "operationUnitCost",- "description",- "machineTime",- "tags"+ "operationSupplierProcessId",+ "tags",+ "procedureId",+ "assemblyInstructionId",+ "inspectionDocumentId"]},{"name": "methodOperationParameter","rows": 0,"columns": [- "id",- "updatedBy","createdAt",- "key","updatedAt",- "companyId",- "operationId",+ "id",+ "key","value",- "createdBy"+ "operationId",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "methodOperationStep","rows": 0,"columns": [- "updatedAt",- "name",- "companyId",+ "required",+ "sortOrder",+ "type","minValue",- "listValues","maxValue",- "id",- "fileTypes",- "type","createdAt",- "required",+ "updatedAt","description",- "assemblyInstructionStepId",+ "id",+ "name","unitOfMeasureCode",+ "listValues",+ "fileTypes","operationId",- "sortOrder",+ "companyId",+ "createdBy","updatedBy",- "createdBy"+ "assemblyInstructionStepId"]},{"name": "methodOperationStepSlide","rows": 0,"columns": [- "imagePath",- "caption",- "createdBy",- "annotations","sortOrder",- "stepId",- "modelUploadId","createdAt","updatedAt",- "updatedBy",+ "annotations","id",+ "stepId",+ "imagePath",+ "caption",+ "companyId",+ "createdBy",+ "updatedBy","size",- "companyId"+ "modelUploadId"]},{"name": "methodOperationTool","rows": 0,"columns": [- "updatedBy",- "id",+ "quantity","createdAt",- "operationId","updatedAt",- "companyId",+ "id",+ "operationId","toolId",- "quantity",- "createdBy"+ "companyId",+ "createdBy",+ "updatedBy"]},{@@ -5355,52 +5355,52 @@"name": "nonConformanceActionProcess","rows": 0,"columns": [- "updatedBy",- "actionTaskId",- "createdBy",- "id",+ "createdAt","updatedAt",+ "id",+ "actionTaskId","processId","companyId",- "createdAt"+ "createdBy",+ "updatedBy"]},{"name": "nonConformanceActionTask","rows": 0,"columns": [- "updatedBy",- "supplierId",- "dueDate",- "createdAt",- "assignee",- "updatedAt","status",+ "dueDate","completedDate",+ "notes","sortOrder",+ "createdAt",+ "updatedAt","id",- "companyId",- "notes",+ "nonConformanceId",+ "assignee","tags",- "actionTypeId",+ "companyId","createdBy",- "nonConformanceId"+ "updatedBy",+ "actionTypeId",+ "supplierId"]},{"name": "nonConformancePurchaseReturnOrderLine","rows": 0,"columns": [- "companyId",- "purchaseReturnOrderLineId",- "purchaseReturnOrderId",- "purchaseReturnOrderReadableId",+ "quantity","createdAt","updatedAt",+ "id","nonConformanceId",- "quantity",+ "purchaseReturnOrderLineId",+ "purchaseReturnOrderId",+ "purchaseReturnOrderReadableId",+ "companyId","createdBy",- "id","updatedBy"]},@@ -5408,127 +5408,127 @@"name": "nonConformanceSalesReturnOrderLine","rows": 0,"columns": [- "nonConformanceId",- "createdBy",- "updatedBy",+ "createdAt","updatedAt","id",- "companyId",+ "nonConformanceId","salesReturnOrderLineId","salesReturnOrderId",- "createdAt",- "salesReturnOrderReadableId"+ "salesReturnOrderReadableId",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "nonConformanceSupplier","rows": 0,"columns": [- "supplierId",- "companyId",- "updatedAt","createdAt",- "nonConformanceId",- "updatedBy",+ "updatedAt","externalLinkId","id",- "createdBy"+ "nonConformanceId",+ "supplierId",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "partner","rows": 0,"columns": [- "companyId",- "createdAt",- "abilityId",+ "hoursPerWeek","active",- "createdBy",+ "createdAt","updatedAt",- "id",- "tags",- "updatedBy","customFields",- "hoursPerWeek"- ]+ "id",+ "abilityId",+ "companyId",+ "createdBy",+ "updatedBy",+ "tags"+ ]},{"name": "payment","rows": 0,"columns": [- "supplierId",- "customFields",- "id",- "currencyCode",- "totalAmount",+ "paymentType",+ "status",+ "paymentDate","postingDate",- "updatedAt","exchangeRate",+ "totalAmount","postedAt",- "reference",- "paymentId",- "createdBy",- "journalId",- "postedBy",+ "voidedAt","createdAt",+ "updatedAt",+ "customFields",+ "id",+ "paymentId","customerId",- "companyId",+ "supplierId",+ "currencyCode","bankAccount",- "updatedBy",- "paymentDate",- "status",+ "reference","memo",- "paymentType",+ "journalId",+ "postedBy","voidedBy",- "voidedAt"+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "purchaseInvoiceDelivery","rows": 0,"columns": [- "locationId",+ "supplierShippingCost","updatedAt",- "incoterm","customFields",+ "incoterm","id",- "incotermLocation",- "companyId",+ "locationId","shippingMethodId","shippingTermId",+ "companyId","updatedBy",- "supplierShippingCost"+ "incotermLocation"]},{"name": "purchaseInvoiceStatusHistory","rows": 0,- "columns": ["invoiceId", "id", "status", "createdAt", "companyId"]+ "columns": ["createdAt", "status", "id", "invoiceId", "companyId"]},{"name": "purchaseOrderDelivery","rows": 0,"columns": ["receiptRequestedDate",- "incotermLocation",- "customerLocationId",+ "receiptPromisedDate",+ "deliveryDate",+ "dropShipment","updatedAt",- "tags",- "incoterm",+ "customFields","supplierShippingCost",- "shippingTermId",- "updatedBy",- "shippingMethodId",- "deliveryDate",- "customerId",+ "incoterm","id",+ "locationId",+ "shippingMethodId",+ "shippingTermId",+ "notes","trackingNumber",- "receiptPromisedDate",+ "customerId",+ "customerLocationId","companyId",- "locationId",- "customFields",- "dropShipment",- "notes"+ "updatedBy",+ "tags",+ "incotermLocation"]},{@@ -5540,222 +5540,222 @@"name": "purchaseOrderLine","rows": 0,"columns": [+ "purchaseOrderLineType",+ "purchaseQuantity",+ "quantityReceived",+ "quantityInvoiced",+ "supplierUnitPrice",+ "setupPrice",+ "receivedComplete",+ "invoicedComplete",+ "createdAt",+ "updatedAt",+ "customFields","conversionFactor",- "receivedDate",- "description",- "tags",+ "internalNotes","externalNotes",- "createdAt",- "purchaseUnitOfMeasureCode","exchangeRate",- "purchaseOrderId",- "jobId",- "ownerId",- "quantityInvoiced",- "modelUploadId",+ "supplierShippingCost","supplierTaxAmount",- "accountId",- "supplierPartId",+ "taxPercent",+ "quantityShipped",+ "promisedDate","requiredDate",- "createdBy",- "purchaseQuantity",- "id",- "quantityReceived",- "updatedBy",- "supplierShippingCost",+ "receivedDate","sortOrder",- "customFields",- "assetId",- "companyId",- "internalNotes",- "promisedDate",- "purchaseOrderLineType",- "supplierUnitPrice",+ "id",+ "purchaseOrderId","itemId",- "storageUnitId",- "setupPrice",- "locationId",- "updatedAt",- "quantityShipped",- "taxPercent",- "invoicedComplete",+ "assetId",+ "description","inventoryUnitOfMeasureCode",- "costCenterId",+ "purchaseUnitOfMeasureCode",+ "locationId",+ "storageUnitId",+ "companyId",+ "createdBy",+ "updatedBy",+ "tags",+ "modelUploadId",+ "jobId","jobOperationId",- "receivedComplete"+ "accountId",+ "costCenterId",+ "ownerId",+ "supplierPartId"]},{"name": "nonConformancePurchaseOrderLine","rows": 0,"columns": [- "nonConformanceId",- "createdBy",- "updatedBy",+ "createdAt","updatedAt","id",- "companyId",+ "nonConformanceId","purchaseOrderLineId","purchaseOrderId",- "createdAt",- "purchaseOrderReadableId"+ "purchaseOrderReadableId",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "purchaseOrderStatusHistory","rows": 0,"columns": [- "createdBy",- "createdAt","status",- "updatedBy",+ "createdAt","id",+ "purchaseOrderId",+ "createdBy","companyId",- "purchaseOrderId"+ "updatedBy"]},{"name": "purchaseOrderTransaction","rows": 0,"columns": [- "purchaseOrderId",- "companyId",- "id","type",+ "createdAt",+ "id",+ "purchaseOrderId","userId",- "createdAt"+ "companyId"]},{"name": "purchaseReturnOrderLineTrackedEntity","rows": 0,"columns": [- "updatedBy",- "companyId","quantity",- "createdBy",+ "createdAt","updatedAt",+ "purchaseReturnOrderLineId","trackedEntityId",- "createdAt",- "purchaseReturnOrderLineId"+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "purchasingRfqSupplier","rows": 0,"columns": [- "supplierId",- "companyId",- "updatedBy","createdAt",- "purchasingRfqId","id",- "createdBy"+ "purchasingRfqId",+ "supplierId",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "purchasingRfqToPurchaseOrder","rows": 0,- "columns": ["companyId", "purchaseOrderId", "purchasingRfqId"]+ "columns": ["purchasingRfqId", "purchaseOrderId", "companyId"]},{"name": "purchasingRfqToSupplierQuote","rows": 0,- "columns": ["companyId", "supplierQuoteId", "purchasingRfqId"]+ "columns": ["purchasingRfqId", "supplierQuoteId", "companyId"]},{"name": "quoteMakeMethod","rows": 0,"columns": [- "createdBy",- "id",- "updatedBy","quantityPerParent",- "tags",- "quoteId","createdAt","updatedAt",- "itemId","customFields",- "quoteLineId","version",+ "id",+ "quoteId",+ "quoteLineId","parentMaterialId",- "companyId"+ "itemId",+ "companyId",+ "createdBy",+ "updatedBy",+ "tags"]},{"name": "quoteMaterial","rows": 0,"columns": [- "customFields",- "quoteMakeMethodId",- "quoteLineId",- "createdAt",- "itemId",- "unitCostSource","methodType",- "tags",+ "order",+ "quantity","unitCost",- "quoteOperationId",- "updatedBy",- "storageUnitId",+ "createdAt",+ "updatedAt",+ "customFields","scrapQuantity",- "createdBy",+ "kit",+ "id","quoteId",- "companyId",- "updatedAt",- "quantity",- "order",- "unitOfMeasureCode",+ "quoteLineId",+ "itemId",+ "itemType","description",- "id",- "kit",- "itemType"+ "unitOfMeasureCode",+ "companyId",+ "createdBy",+ "updatedBy",+ "quoteMakeMethodId",+ "quoteOperationId",+ "tags",+ "storageUnitId",+ "unitCostSource"]},{"name": "quoteMaterialStep","rows": 0,- "columns": ["quoteMaterialId", "quoteOperationStepId", "quantity"]+ "columns": ["quantity", "quoteMaterialId", "quoteOperationStepId"]},{"name": "quoteOperation","rows": 0,"columns": [+ "order",+ "operationOrder",+ "laborRate",+ "overheadRate",+ "createdAt",+ "updatedAt",+ "customFields",+ "setupTime",+ "setupUnit",+ "laborTime",+ "laborUnit",+ "machineTime",+ "machineUnit",+ "machineRate",+ "operationType",+ "operationMinimumCost",+ "operationLeadTime","operationUnitCost",+ "workInstruction",+ "id","quoteId",- "inspectionDocumentId",- "companyId",- "operationLeadTime",- "setupTime",+ "quoteLineId",+ "quoteMakeMethodId","description",- "machineRate",- "machineUnit",- "laborUnit",- "tags",- "procedureId",- "id",- "setupUnit",- "assemblyInstructionId",+ "companyId","createdBy",- "updatedAt",- "quoteMakeMethodId",- "quoteLineId",- "laborRate",- "operationMinimumCost",- "machineTime",- "workInstruction",- "workCenterId",- "operationSupplierProcessId","updatedBy",- "operationType",- "operationOrder",- "order","processId",- "laborTime",- "createdAt",- "overheadRate",- "customFields"+ "workCenterId",+ "operationSupplierProcessId",+ "tags",+ "procedureId",+ "assemblyInstructionId",+ "inspectionDocumentId"]},{@@ -5763,269 +5763,269 @@"rows": 0,"columns": ["createdAt",- "id",- "updatedBy","updatedAt",+ "id","key",+ "value",+ "operationId","companyId","createdBy",- "operationId",- "value"+ "updatedBy"]},{"name": "quoteOperationStep","rows": 0,"columns": [+ "minValue",+ "maxValue","createdAt",- "required",+ "updatedAt","description",- "unitOfMeasureCode",+ "required","sortOrder",- "operationId",- "createdBy",- "updatedBy",- "updatedAt",- "companyId",+ "type",+ "id","name",- "minValue",+ "unitOfMeasureCode","listValues",- "maxValue",- "id","fileTypes",- "type"+ "operationId",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "quoteOperationStepSlide","rows": 0,"columns": [- "companyId",- "id",- "updatedBy",- "size",+ "sortOrder","createdAt","updatedAt",- "stepId",- "modelUploadId","annotations",- "sortOrder",- "createdBy",+ "id",+ "stepId",+ "imagePath","caption",- "imagePath"+ "companyId",+ "createdBy",+ "updatedBy",+ "size",+ "modelUploadId"]},{"name": "quoteOperationTool","rows": 0,"columns": [- "companyId",- "toolId","quantity",- "createdBy",- "updatedBy",- "id","createdAt",+ "updatedAt",+ "id","operationId",- "updatedAt"+ "toolId",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "quoteOperationToolStep","rows": 0,- "columns": ["quoteOperationStepId", "quoteOperationToolId"]+ "columns": ["quoteOperationToolId", "quoteOperationStepId"]},{"name": "receiptFixedAssetLine","rows": 0,"columns": [+ "received",+ "createdAt","updatedAt","id",- "companyId","receiptId",- "createdAt",- "updatedBy",- "serialNumber","purchaseOrderLineId",- "received",- "createdBy"+ "serialNumber",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "receiptLine","rows": 0,"columns": [- "requiresSerialTracking",- "conversionFactor",- "itemId",- "lineId",- "createdAt",+ "orderQuantity","outstandingQuantity",- "requiresBatchTracking",+ "receivedQuantity","unitPrice",- "createdBy",- "updatedBy",- "companyId",- "receiptId",+ "createdAt","updatedAt",- "storageUnitId",- "receivedQuantity",- "unitOfMeasure",+ "conversionFactor",+ "requiresSerialTracking",+ "requiresBatchTracking","id",+ "receiptId",+ "lineId",+ "itemId","locationId",- "orderQuantity"+ "storageUnitId",+ "unitOfMeasure",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "nonConformanceReceiptLine","rows": 0,"columns": [- "createdBy",- "updatedBy",- "nonConformanceId",- "companyId",- "id",- "updatedAt","createdAt",- "receiptId",+ "updatedAt",+ "id",+ "nonConformanceId","receiptLineId",- "receiptReadableId"+ "receiptId",+ "receiptReadableId",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "salesInvoice","rows": 0,"columns": [- "exchangeRateUpdatedAt",+ "status",+ "postingDate",+ "dateIssued","dateDue",- "createdAt",- "customerReference",+ "datePaid",+ "subtotal","totalDiscount",- "companyId",- "exchangeRate",- "currencyCode",- "locationId",- "status",- "customerId","totalAmount","totalTax",+ "exchangeRate",+ "exchangeRateUpdatedAt",+ "customFields","internalNotes",- "invoiceCustomerLocationId",- "opportunityId",- "createdBy",- "paymentTermId",+ "externalNotes",+ "createdAt",+ "updatedAt","id",- "dateIssued",- "customFields",+ "invoiceId",+ "customerId",+ "customerReference","invoiceCustomerId",+ "invoiceCustomerLocationId",+ "invoiceCustomerContactId",+ "paymentTermId",+ "locationId",+ "currencyCode",+ "opportunityId",+ "shipmentId","assignee",- "subtotal",- "invoiceId",- "updatedBy",- "datePaid",- "externalNotes",+ "companyId","tags",- "invoiceCustomerContactId",- "postingDate",- "updatedAt",- "shipmentId"+ "createdBy",+ "updatedBy"]},{"name": "salesInvoiceLine","rows": 0,"columns": [- "addOnCost",- "modelUploadId",+ "invoiceLineType",+ "methodType",+ "quantity",+ "exchangeRate","unitPrice",- "locationId",- "companyId",- "itemId",- "createdAt",- "salesOrderId",- "updatedBy",- "accountId",+ "setupPrice",+ "addOnCost","shippingCost",- "sortOrder","taxPercent",- "exchangeRate",- "invoiceLineType",- "description",+ "externalNotes","internalNotes",- "methodType",- "unitOfMeasureCode",- "opportunityId",+ "customFields",+ "createdAt",+ "updatedAt","nonTaxableAddOnCost",- "assetId",+ "sortOrder","id",- "quantity",- "createdBy",- "externalNotes",- "salesOrderLineId",- "customFields","invoiceId",- "updatedAt",+ "description",+ "itemId",+ "assetId",+ "unitOfMeasureCode",+ "locationId","storageUnitId",- "setupPrice"+ "modelUploadId",+ "opportunityId",+ "salesOrderId",+ "salesOrderLineId",+ "companyId",+ "createdBy",+ "updatedBy",+ "accountId"]},{"name": "salesInvoiceShipment","rows": 0,"columns": [+ "shippingCost","customFields",- "id",- "createdBy",- "updatedBy","createdAt","updatedAt",- "incotermLocation",- "shippingCost",- "shippingTermId","incoterm",- "companyId",+ "id",+ "locationId","shippingMethodId",- "locationId"+ "shippingTermId",+ "companyId",+ "createdBy",+ "updatedBy",+ "incotermLocation"]},{"name": "salesReturnOrderLine","rows": 0,"columns": [+ "lineNumber",+ "quantity",+ "quantityReceived",+ "unitPrice","restockFeePercent",+ "disposition",+ "closedComplete",+ "createdAt",+ "updatedAt",+ "customFields","id",- "salesOrderLineId",- "quantityReceived",- "companyId","salesReturnOrderId",- "salesInvoiceLineId",- "unitPrice",+ "itemId",+ "unitOfMeasureCode","returnReasonId",+ "salesOrderLineId","shipmentLineId",- "updatedAt",- "quantity",+ "salesInvoiceLineId",+ "companyId","createdBy",- "customFields",- "closedComplete",- "disposition",- "lineNumber",- "itemId",- "createdAt",- "updatedBy",- "unitOfMeasureCode"+ "updatedBy"]},{"name": "salesReturnOrderLineTrackedEntity","rows": 0,"columns": [- "salesReturnOrderLineId",+ "quantity","createdAt",- "trackedEntityId","updatedAt",- "createdBy",- "quantity",+ "salesReturnOrderLineId",+ "trackedEntityId","companyId",+ "createdBy","updatedBy"]},@@ -6033,58 +6033,58 @@"name": "salesReturnOrderCreditLine","rows": 0,"columns": [- "id",+ "quantity",+ "unitPrice",+ "restockFee","createdAt","updatedAt",- "restockFee",+ "id","memoId",- "createdBy",- "updatedBy",- "unitPrice",- "quantity","salesReturnOrderLineId",- "companyId"+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "shipmentFixedAssetLine","rows": 0,"columns": [- "serialNumber",- "salesOrderLineId","shipped",- "createdBy",+ "createdAt","updatedAt","id",- "companyId","shipmentId",- "updatedBy",- "createdAt"+ "salesOrderLineId",+ "serialNumber",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "shipmentLine","rows": 0,"columns": [- "updatedBy",- "updatedAt",- "itemId",- "requiresBatchTracking",- "lineId",+ "orderQuantity","outstandingQuantity",- "fulfillmentId",+ "shippedQuantity","unitPrice",- "companyId",- "createdBy","requiresSerialTracking",- "shipmentId",+ "requiresBatchTracking","createdAt",- "storageUnitId",- "shippedQuantity",- "unitOfMeasure",+ "updatedAt","id",+ "shipmentId",+ "lineId",+ "itemId","locationId",- "orderQuantity"+ "storageUnitId",+ "unitOfMeasure",+ "companyId",+ "createdBy",+ "updatedBy",+ "fulfillmentId"]},{@@ -6092,761 +6092,761 @@"rows": 0,"columns": ["createdAt",+ "updatedAt",+ "id",+ "nonConformanceId","shipmentLineId","shipmentId","shipmentReadableId",- "updatedBy",- "createdBy",- "nonConformanceId","companyId",- "updatedAt",- "id"+ "createdBy",+ "updatedBy"]},{"name": "supplier","rows": 0,"columns": [- "website",- "supplierTypeId",- "customFields",- "intercompanyCompanyId",- "purchasingContactId",- "logo",- "tags",+ "createdAt","updatedAt",- "embedding",- "fax",+ "customFields","taxPercent",- "currencyCode",- "name",- "updatedBy",- "phone",- "createdAt",- "assignee",- "readableId",+ "embedding","supplierStatus",- "createdBy","id",+ "name",+ "supplierTypeId",+ "accountManagerId",+ "logo",+ "assignee","companyId",+ "createdBy",+ "updatedBy",+ "currencyCode",+ "phone",+ "fax",+ "website",+ "tags",+ "purchasingContactId","defaultCc",- "accountManagerId"+ "intercompanyCompanyId",+ "readableId"]},{"name": "supplierAccount","rows": 0,- "columns": ["active", "companyId", "id", "supplierId"]+ "columns": ["active", "id", "supplierId", "companyId"]},{"name": "supplierBankAccount","rows": 0,"columns": [- "bankCode",- "currencyCode",+ "isPrimary",+ "active",+ "createdAt",+ "updatedAt",+ "customFields","id",- "bankName","companyId",- "isPrimary",- "createdBy",- "accountNumber",+ "supplierId",+ "name",+ "accountHolderName",+ "bankName",+ "bankAddress","countryCode",+ "currencyCode",+ "accountNumber",+ "bankCode","swiftBic",- "customFields",- "accountHolderName",- "createdAt",- "tags","notes",+ "createdBy","updatedBy",- "updatedAt",- "active",- "supplierId",- "name",- "bankAddress"+ "tags"]},{"name": "supplierInteraction","rows": 0,- "columns": ["supplierId", "id", "companyId"]+ "columns": ["id", "companyId", "supplierId"]},{"name": "receipt","rows": 0,"columns": [- "postedBy",- "sourceDocumentId",- "internalNotes",- "assignee",- "supplierInteractionId",- "createdBy",- "updatedBy","sourceDocument",- "createdAt",- "locationId",- "tags",- "customFields",- "externalDocumentId",- "id","status",+ "postingDate","invoiced",- "sourceDocumentReadableId",+ "createdAt","updatedAt",- "companyId",+ "customFields",+ "internalNotes",+ "id","receiptId",+ "locationId",+ "sourceDocumentId",+ "sourceDocumentReadableId",+ "externalDocumentId","supplierId",- "postingDate"+ "assignee",+ "companyId",+ "createdBy",+ "updatedBy",+ "tags",+ "supplierInteractionId",+ "postedBy"]},{"name": "shipment","rows": 0,"columns": [- "customFields",+ "sourceDocument","status",- "trackingNumber",+ "postingDate","invoiced",- "shipmentId",+ "internalNotes","externalNotes",- "supplierId",- "sourceDocumentReadableId",- "postingDate",- "externalDocumentId",- "customerId",- "id",- "shippingMethodId",- "tags","createdAt",- "companyId",- "assignee",- "locationId",- "sourceDocument","updatedAt",- "internalNotes",- "opportunityId",- "supplierInteractionId",+ "customFields",+ "id",+ "shipmentId",+ "locationId","sourceDocumentId",+ "sourceDocumentReadableId",+ "shippingMethodId",+ "trackingNumber",+ "customerId","postedBy",+ "assignee",+ "opportunityId",+ "companyId","createdBy",- "updatedBy"+ "updatedBy",+ "tags",+ "supplierId",+ "supplierInteractionId",+ "externalDocumentId"]},{"name": "supplierLedger","rows": 0,"columns": [- "supplierId",+ "entryNumber","postingDate","documentType",- "documentId",- "createdAt","amount",- "entryNumber",+ "createdAt",+ "id",+ "documentId","externalDocumentId",- "companyId",- "id"+ "supplierId",+ "companyId"]},{"name": "supplierLocation","rows": 0,"columns": [- "name","customFields",+ "id",+ "supplierId","addressId",+ "name","tags",- "id",- "companyId",- "supplierId"+ "companyId"]},{"name": "supplierContact","rows": 0,"columns": [- "id","customFields",+ "id","supplierId",- "companyId",- "userId",- "supplierLocationId","contactId",- "tags"+ "supplierLocationId",+ "userId",+ "tags",+ "companyId"]},{"name": "purchaseInvoice","rows": 0,"columns": [+ "exchangeRate",+ "postingDate","dateIssued",- "status",- "invoiceId",+ "dateDue",+ "datePaid","subtotal",- "createdBy",- "currencyCode",- "invoiceSupplierContactId",+ "totalDiscount",+ "totalAmount",+ "totalTax",+ "customFields",+ "createdAt",+ "updatedAt","internalNotes",- "supplierInteractionId",- "updatedAt",- "exchangeRate",+ "exchangeRateUpdatedAt",+ "status","id",- "paymentTermId",- "createdAt",- "invoiceSupplierId",- "totalTax",- "totalAmount",+ "invoiceId","supplierId",- "dateDue",- "locationId",- "customFields",- "invoiceSupplierLocationId",- "tags","supplierReference",- "postingDate",- "exchangeRateUpdatedAt",- "companyId",+ "invoiceSupplierId",+ "invoiceSupplierLocationId",+ "invoiceSupplierContactId",+ "paymentTermId",+ "currencyCode","assignee",- "datePaid",+ "companyId",+ "createdBy","updatedBy",- "totalDiscount"+ "tags",+ "supplierInteractionId",+ "locationId"]},{"name": "purchaseOrder","rows": 0,"columns": [- "purchaseOrderType",- "exchangeRateUpdatedAt",- "createdBy",- "updatedAt","revisionId",+ "status",+ "orderDate","closedAt",+ "customFields","createdAt",+ "updatedAt",+ "exchangeRate",+ "exchangeRateUpdatedAt",+ "internalNotes","externalNotes",- "currencyCode",- "closedBy",+ "purchaseOrderType",+ "id",+ "purchaseOrderId",+ "supplierId",+ "supplierLocationId",+ "supplierContactId",+ "supplierReference","assignee",+ "companyId",+ "closedBy",+ "createdBy","updatedBy",- "status",- "exchangeRate",- "supplierContactId",+ "currencyCode","tags",- "jobId",- "supplierId",- "jobReadableId",- "purchaseOrderId",- "companyId",- "customFields",- "internalNotes",- "orderDate",- "supplierReference","supplierInteractionId",- "supplierLocationId",- "id"+ "jobId",+ "jobReadableId"]},{"name": "purchaseInvoiceLine","rows": 0,"columns": [- "itemId",+ "invoiceLineType",+ "quantity",+ "supplierUnitPrice",+ "exchangeRate",+ "createdAt","updatedAt",- "locationId",- "id",+ "customFields","conversionFactor","internalNotes",- "serviceId",- "storageUnitId","supplierShippingCost",- "updatedBy",+ "supplierTaxAmount",+ "taxPercent","requiredDate",+ "sortOrder",+ "id","invoiceId",- "projectId",+ "purchaseOrderId",+ "purchaseOrderLineId",+ "itemId",+ "serviceId",+ "locationId",+ "storageUnitId",+ "assetId","description",- "jobOperationId",- "ownerId",- "customFields",- "accountId",+ "inventoryUnitOfMeasureCode",+ "purchaseUnitOfMeasureCode","companyId",- "supplierUnitPrice",- "taxPercent","createdBy",- "assetId",- "purchaseUnitOfMeasureCode",- "purchaseOrderLineId",+ "updatedBy","tags","modelUploadId",- "createdAt",- "supplierTaxAmount",+ "jobOperationId",+ "accountId","costCenterId",- "quantity",- "invoiceLineType",- "purchaseOrderId",- "sortOrder",- "exchangeRate",- "inventoryUnitOfMeasureCode"+ "ownerId",+ "projectId"]},{"name": "purchaseInvoicePriceChange","rows": 0,"columns": [- "updatedBy",- "invoiceId",+ "previousPrice",+ "newPrice","previousQuantity",- "companyId",- "id","newQuantity",+ "id",+ "invoiceId","invoiceLineId",- "previousPrice",- "newPrice"+ "updatedBy",+ "companyId"]},{"name": "purchaseOrderPayment","rows": 0,"columns": [- "paymentTermId",- "tags",- "invoiceSupplierContactId",- "invoiceSupplierLocationId",+ "paymentComplete",+ "updatedAt","customFields","id",- "updatedAt",- "paymentComplete","invoiceSupplierId",+ "invoiceSupplierLocationId",+ "invoiceSupplierContactId",+ "paymentTermId",+ "companyId","updatedBy",- "companyId"+ "tags"]},{"name": "purchaseReturnOrder","rows": 0,"columns": [- "supplierReference",- "customFields",- "expirationDate","status",- "supplierId",- "companyId",- "createdBy",- "assignee",- "updatedBy",- "internalNotes",- "updatedAt","exchangeRate",- "createdAt",- "supplierLocationId",- "locationId",- "replacementPurchaseOrderId",+ "orderDate",+ "expirationDate",+ "internalNotes","externalNotes",+ "createdAt",+ "updatedAt",+ "customFields",+ "id","purchaseReturnOrderId",- "orderDate",+ "supplierId",+ "supplierLocationId","supplierContactId",+ "supplierReference",+ "locationId","purchaseOrderId",- "id",- "currencyCode"+ "replacementPurchaseOrderId",+ "currencyCode",+ "assignee",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "memo","rows": 0,"columns": [- "createdBy",- "journalId",- "salesReturnOrderId",- "postedBy",- "customerId",- "companyId",- "reasonAccount",- "createdAt",- "updatedBy",+ "direction",+ "status","memoDate",- "voidedBy",+ "postingDate",+ "exchangeRate",+ "amount",+ "postedAt","voidedAt",- "status",- "direction",- "notes",+ "createdAt",+ "updatedAt","customFields",- "supplierId",- "purchaseReturnOrderId",- "amount","id",+ "memoId",+ "customerId",+ "supplierId","currencyCode",- "updatedAt",- "exchangeRate",- "postingDate",+ "reasonAccount","reference",- "memoId",- "postedAt"+ "notes",+ "journalId",+ "postedBy",+ "voidedBy",+ "companyId",+ "createdBy",+ "updatedBy",+ "salesReturnOrderId",+ "purchaseReturnOrderId"]},{"name": "invoiceSettlement","rows": 0,"columns": [- "appliedViaPaymentId",- "createdBy",+ "appliedAmount",+ "discountAmount",+ "writeOffAmount",+ "sourceExchangeRate",+ "targetExchangeRate","fxGainLossAmount",+ "appliedDate",+ "createdAt","sourceAmount",- "targetPurchaseInvoiceId",- "appliedAmount",- "updatedBy",- "sourcePaymentId",- "companyId",+ "id",+ "paymentId","memoId","targetSalesInvoiceId",+ "targetPurchaseInvoiceId","targetMemoId",- "targetExchangeRate",- "writeOffAmount",- "id",- "sourceExchangeRate",- "discountAmount",- "paymentId",- "appliedDate",- "createdAt"+ "companyId",+ "createdBy",+ "appliedViaPaymentId",+ "updatedBy",+ "sourcePaymentId"]},{"name": "purchaseReturnOrderLine","rows": 0,"columns": [- "createdBy",- "purchaseReturnOrderId",- "purchaseInvoiceLineId",+ "lineNumber",+ "quantity",+ "quantityShipped","unitPrice",- "returnReasonId",- "id","restockFeePercent",- "purchaseOrderLineId",- "quantityShipped",- "itemId",- "lineNumber","closedComplete",- "updatedBy",+ "createdAt","updatedAt",- "unitOfMeasureCode","customFields",+ "id",+ "purchaseReturnOrderId",+ "itemId",+ "unitOfMeasureCode",+ "returnReasonId",+ "purchaseOrderLineId","receiptLineId",- "quantity",- "createdAt",- "companyId"+ "purchaseInvoiceLineId",+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "purchaseReturnOrderCreditLine","rows": 0,"columns": [- "createdBy",- "updatedBy",- "memoId",+ "quantity",+ "unitPrice","restockFee","createdAt",- "id","updatedAt",- "companyId",+ "id",+ "memoId","purchaseReturnOrderLineId",- "quantity",- "unitPrice"+ "companyId",+ "createdBy",+ "updatedBy"]},{"name": "supplierPart","rows": 0,"columns": [+ "minimumOrderQuantity","conversionFactor",- "supplierPartId",- "customFields",- "supplierId",- "orderMultiple",- "unitPrice",- "updatedBy",- "supplierUnitOfMeasureCode",- "createdBy","active",- "itemId",- "updatedAt",- "tags",- "minimumOrderQuantity","createdAt",+ "updatedAt",+ "customFields",+ "unitPrice",+ "orderMultiple","id",- "companyId"+ "itemId",+ "supplierId",+ "supplierPartId",+ "supplierUnitOfMeasureCode",+ "companyId",+ "createdBy",+ "updatedBy",+ "tags"]},{"name": "supplierPartPrice","rows": 0,"columns": [- "sourceDocumentId",+ "quantity","unitPrice","sourceType",- "createdBy",- "updatedBy",- "supplierPartId",+ "createdAt",+ "updatedAt","leadTime",+ "supplierPartId",+ "sourceDocumentId","companyId",- "quantity",- "createdAt",- "updatedAt"+ "createdBy",+ "updatedBy"]},{"name": "supplierPayment","rows": 0,"columns": [- "paymentTermId",- "invoiceSupplierContactId",+ "updatedAt",+ "customFields",+ "supplierId",+ "invoiceSupplierId","invoiceSupplierLocationId",+ "invoiceSupplierContactId",+ "paymentTermId","companyId",- "tags",- "supplierId","updatedBy",- "invoiceSupplierId",- "customFields",- "updatedAt"+ "tags"]},{"name": "supplierProcess","rows": 0,"columns": [- "companyId",- "processId","minimumCost",- "updatedAt",+ "leadTime","customFields","createdAt",+ "updatedAt",+ "id","supplierId",- "tags",- "leadTime",+ "processId",+ "companyId","createdBy",- "id",- "updatedBy"+ "updatedBy",+ "tags"]},{"name": "supplierQuote","rows": 0,"columns": [+ "revisionId",+ "quotedDate",+ "expirationDate","status",- "supplierQuoteType",- "supplierId",- "id",- "supplierContactId",+ "internalNotes","externalNotes",- "supplierInteractionId",- "supplierLocationId",- "exchangeRateUpdatedAt",- "assignee",- "supplierQuoteId",- "createdBy","exchangeRate",- "companyId",- "externalLinkId",+ "exchangeRateUpdatedAt",+ "customFields",+ "createdAt","updatedAt",- "expirationDate",+ "supplierQuoteType",+ "externalLinkId",+ "id",+ "supplierQuoteId",+ "supplierId",+ "supplierLocationId",+ "supplierContactId","supplierReference",- "createdAt",- "internalNotes",- "updatedBy",- "revisionId",+ "assignee","currencyCode",- "quotedDate",+ "companyId","tags",- "customFields"+ "createdBy",+ "updatedBy",+ "supplierInteractionId"]},{"name": "supplierQuoteFavorite","rows": 0,- "columns": ["userId", "supplierQuoteId"]+ "columns": ["supplierQuoteId", "userId"]},{"name": "supplierQuoteLine","rows": 0,"columns": [- "externalNotes",- "itemId",- "tags",+ "supplierQuoteRevisionId",+ "quantity","conversionFactor",- "companyId",- "internalNotes",- "requiredDate","updatedAt",- "quantity",- "supplierQuoteRevisionId","customFields",- "updatedBy",- "costCenterId",- "description",+ "internalNotes",+ "externalNotes",+ "requiredDate","sortOrder","id",+ "supplierQuoteId",+ "itemId",+ "description",+ "supplierPartId","supplierPartRevision",- "ownerId",+ "inventoryUnitOfMeasureCode","purchaseUnitOfMeasureCode",- "supplierQuoteLineType",+ "companyId","createdBy",- "supplierQuoteId",- "supplierPartId",+ "updatedBy",+ "tags",+ "costCenterId","accountId",- "inventoryUnitOfMeasureCode"+ "supplierQuoteLineType",+ "ownerId"]},{"name": "supplierQuoteLinePrice","rows": 0,"columns": [- "supplierQuoteLineId",- "createdBy",- "supplierTaxAmount",- "supplierShippingCost",- "companyId",- "taxPercent",- "supplierQuoteId",- "exchangeRate","quantity",- "updatedAt","leadTime",- "createdAt","supplierUnitPrice",- "updatedBy"+ "exchangeRate",+ "supplierShippingCost",+ "createdAt",+ "updatedAt",+ "supplierTaxAmount",+ "taxPercent",+ "supplierQuoteId",+ "supplierQuoteLineId",+ "createdBy",+ "updatedBy",+ "companyId"]},{"name": "supplierShipping","rows": 0,"columns": [- "companyId",- "shippingSupplierContactId",- "shippingSupplierLocationId",- "incoterm",- "shippingTermId",- "customFields","updatedAt",+ "customFields",+ "incoterm",+ "supplierId","shippingSupplierId",- "incotermLocation",+ "shippingSupplierLocationId",+ "shippingSupplierContactId",+ "shippingTermId","shippingMethodId",+ "companyId",+ "updatedBy","tags",- "supplierId",- "updatedBy"+ "incotermLocation"]},{"name": "supplierTax","rows": 0,"columns": [- "taxId",- "taxExemptionCertificatePath",+ "taxExempt",+ "taxExemptionReason","updatedAt","supplierId",- "companyId",- "updatedBy",- "taxExemptionReason",- "eori",+ "taxId","vatNumber",+ "eori","taxExemptionCertificateNumber",- "taxExempt"+ "taxExemptionCertificatePath",+ "companyId",+ "updatedBy"]},{"name": "workflow","rows": 0,"columns": [- "updatedBy",- "ownerId",- "publishedVersionId",- "name",- "description",+ "nextRunAt","canvasState",- "id","createdAt",- "nextRunAt",- "createdBy",+ "updatedAt",+ "id","companyId",- "updatedAt"+ "name",+ "description",+ "ownerId",+ "publishedVersionId",+ "createdBy",+ "updatedBy"]},{"name": "workflowVersion","rows": 0,"columns": [- "companyId",- "updatedBy",- "createdBy",+ "versionNumber",+ "formatVersion",+ "nodes",+ "edges",+ "createdAt","updatedAt","id",- "createdAt",- "nodes",- "versionNumber",+ "companyId","workflowId",- "edges",- "formatVersion"+ "createdBy",+ "updatedBy"]},{"name": "workflowRun","rows": 0,"columns": [- "startedAt",- "depth",- "compactedAt",- "error","isTest",- "eventId",- "createdAt",- "triggerTable",+ "depth",+ "startedAt","completedAt","durationMs",- "workflowVersionId",- "causedByRunId",+ "compactedAt",+ "createdAt",+ "id",+ "companyId","workflowId",+ "workflowVersionId",+ "eventId","sourceEventId",- "statusReason",- "id",+ "triggerTable",+ "triggerRecordId","ownerId","status",- "triggerRecordId",- "companyId",+ "statusReason","rootRunId",- "path"+ "causedByRunId",+ "path",+ "error"]},{"name": "workflowStepRun","rows": 0,"columns": [- "branchTaken",- "nodeId",- "compactedAt",- "durationMs",- "runId",- "completedAt","sequence",+ "input",+ "output",+ "startedAt",+ "completedAt",+ "durationMs",+ "compactedAt","createdAt","detail",- "itemKey",- "statusReason","id",- "output",- "nodeType",- "error","companyId",- "startedAt",+ "runId",+ "nodeId",+ "nodeType",+ "itemKey","status",- "input"+ "statusReason",+ "branchTaken",+ "error"]},{"name": "workflowTriggerEvent","rows": 0,"columns": [- "companyId",+ "createdAt","id",- "origin",+ "companyId","workflowId","workflowVersionId",- "createdAt",- "eventId"+ "eventId",+ "origin"]}],diff --git a/packages/jobs/src/inngest/functions/scheduled/weekly.ts b/packages/jobs/src/inngest/functions/scheduled/weekly.tsindex c8a912b576..22ccdc42df 100644--- a/packages/jobs/src/inngest/functions/scheduled/weekly.ts+++ b/packages/jobs/src/inngest/functions/scheduled/weekly.ts@@ -1,6 +1,7 @@import { getCarbonServiceRole } from "@carbon/auth/client.server";import { fetchAllFromTable } from "@carbon/database";import { isReminderItemStatus } from "@carbon/documents/email";+import { STRIPE_BYPASS_COMPANY_IDS } from "@carbon/env";import {MAX_NOTIFICATION_DELIVERIES,NotificationEvent@@ -18,18 +19,10 @@ export const weeklyFunction = inngest.createFunction(try {if (process.env.CARBON_EDITION === Edition.Cloud) {- const bypassUrl = `${process.env.VERCEL_URL}/api/settings/bypass`;- const bypassResponse = await fetch(bypassUrl);- if (!bypassResponse.ok) {- logger.error("Failed to fetch bypass list", {- statusText: bypassResponse.statusText- });- return;- }- const bypassData = (await bypassResponse.json()) as {- bypassList?: string[];- };- const bypassList = bypassData.bypassList ?? [];+ const bypassList = (STRIPE_BYPASS_COMPANY_IDS ?? "")+ .split(",")+ .map((id) => id.trim())+ .filter(Boolean);logger.info("Bypass list", { bypassList });diff --git a/packages/utils/AGENTS.md b/packages/utils/AGENTS.mdindex ca8717679b..890b37397f 100644--- a/packages/utils/AGENTS.md+++ b/packages/utils/AGENTS.md@@ -41,6 +41,7 @@ pnpm --filter @carbon/utils typecheck| `bom` | Bill of Materials traversal and level computation || `date` | Date formatting, parsing, range helpers (uses `@internationalized/date`); `HOUR_MS`/`DAY_MS` millisecond constants for instant arithmetic || `datetime` | Server-side date derivation with mandatory explicit timezone: `timestamp()`, `today(tz)`, `now(tz)`, `businessDay(instant, tz)`, `weekBounds(tz, offset?, anchor?)` (DST-safe Monday→Sunday instant bounds), `weekNumber(date)`. DST/exotic-zone stress suite in `datetime.test.ts` (gap/overlap disambiguation, midnight-skipping zones, 167/169h weeks, ±30/45-min offsets). Mirrored for Deno at `packages/database/supabase/functions/lib/datetime.ts` — keep in sync |+| `headers` | Request facts from the proxy in front of the app: `getClientIp` (LAST `X-Forwarded-For` entry — the one a caller cannot forge; the ALB appends to a caller's header), `getRequestProtocol`, `getRequestHost`, `getRequestOrigin` (the public origin — `request.url` is the internal one behind the proxy). The host is caller-influenced behind the ALB: compare with it, never build a link someone else opens from it (use `getAppUrl()`). Raw reads are refused by `no-raw-forwarded-headers`. Also `getPreferenceHeaders` (locale, platform) || `hash` | The repo's stable content hashes — `fnv1a32`/`fnv1a64` (cache and idempotency keys) and `getBucket`. Browser-safe; never add `node:crypto` here || `math` | `clamp`/`lerp`/`inverseLerp` only — it re-exports nothing || `precision` | The whole numeric-precision API, re-exported from the edge-runtime module: `SCALE`, `EPSILON`, `RoundingMode`, `round`, `distributeRoundingResidual`, `scrapAllowance`, `applyRate`, `deriveRate`, `isBalanced`, `assertBalanced` |diff --git a/packages/utils/src/headers.test.ts b/packages/utils/src/headers.test.tsnew file mode 100644index 0000000000..12e284fc7d--- /dev/null+++ b/packages/utils/src/headers.test.ts@@ -0,0 +1,71 @@+import { describe, expect, it } from "vitest";+import {+ getClientIp,+ getRequestHost,+ getRequestOrigin,+ getRequestProtocol+} from "./headers";++const req = (+ headers: Record<string, string>,+ url = "http://127.0.0.1:3000/x"+) => new Request(url, { headers });++describe("getClientIp", () => {+ it("takes the address the proxy in front of us saw, not what the caller claimed", () => {+ // The ALB appends the real client to a caller-supplied header.+ expect(+ getClientIp(req({ "x-forwarded-for": "6.6.6.6, 203.0.113.9" }))+ ).toBe("203.0.113.9");+ expect(getClientIp(req({ "x-forwarded-for": "203.0.113.9" }))).toBe(+ "203.0.113.9"+ );+ });++ it("is null when no proxy reported one", () => {+ expect(getClientIp(req({}))).toBeNull();+ expect(getClientIp(req({ "x-forwarded-for": " , " }))).toBeNull();+ });+});++describe("getRequestProtocol", () => {+ it("prefers the proxy's scheme over request.url's", () => {+ expect(getRequestProtocol(req({ "x-forwarded-proto": "https" }))).toBe(+ "https"+ );+ expect(+ getRequestProtocol(req({ "x-forwarded-proto": "HTTPS, http" }))+ ).toBe("https");+ });++ it("ignores anything that is not http or https", () => {+ expect(getRequestProtocol(req({ "x-forwarded-proto": "ftp" }))).toBe(+ "http"+ );+ expect(getRequestProtocol(req({}, "https://app.carbon.ms/x"))).toBe(+ "https"+ );+ });+});++describe("getRequestHost / getRequestOrigin", () => {+ it("uses the forwarded host, then Host, then request.url", () => {+ expect(+ getRequestHost(+ req({ "x-forwarded-host": "erp.x.dev, internal", host: "127.0.0.1" })+ )+ ).toBe("erp.x.dev");+ expect(getRequestHost(req({ host: "app.carbon.ms" }))).toBe(+ "app.carbon.ms"+ );+ expect(getRequestHost({ headers: new Headers() })).toBeNull();+ });++ it("builds the public origin behind a TLS-terminating proxy", () => {+ expect(+ getRequestOrigin(+ req({ "x-forwarded-host": "erp.x.dev", "x-forwarded-proto": "https" })+ )+ ).toBe("https://erp.x.dev");+ });+});diff --git a/packages/utils/src/headers.ts b/packages/utils/src/headers.tsindex f18f9373ff..c41430859d 100644--- a/packages/utils/src/headers.ts+++ b/packages/utils/src/headers.ts@@ -3,6 +3,70 @@ import { parseAcceptLanguage } from "intl-parse-accept-language";type OperatingSystemPlatform = "mac" | "windows";+// ── What the proxy in front of the app tells us ─────────────────────────────+// Every deployment runs one proxy in front of the app: Vercel (Cloud), the AWS+// ALB (SST / ITAR), Caddy (self-host), portless (dev). `request.url` is the+// address the app was reached on BEHIND that proxy (an internal host, `http:`),+// so client and public-URL facts come from the forwarding headers — through+// these helpers only (`no-raw-forwarded-headers` in @carbon/checks).++/** A `Request`, or just its headers (plus its url, when there is one). */+type RequestLike = { headers: Pick<Headers, "get">; url?: string };++const headersOf = (input: RequestLike) => input.headers;+const urlOf = (input: RequestLike) => (input.url ? new URL(input.url) : null);++const listOf = (value: string | null) =>+ (value ?? "")+ .split(",")+ .map((part) => part.trim())+ .filter(Boolean);++/**+ * The client's IP address, or null when no proxy reported one.+ *+ * `X-Forwarded-For` is a chain each proxy APPENDS to, so only its LAST entry —+ * the address the proxy in front of the app saw — cannot be forged: the ALB+ * appends to whatever the caller sent, and a first-entry read there hands the+ * caller any rate-limit bucket or audit-log address it likes. Vercel and Caddy+ * write a single entry, which is the same address.+ */+export function getClientIp(input: RequestLike): string | null {+ return listOf(headersOf(input).get("x-forwarded-for")).at(-1) ?? null;+}++/** `https` or `http` as the client used it: the proxy's, else `request.url`'s. */+export function getRequestProtocol(input: RequestLike): "http" | "https" {+ const forwarded = listOf(+ headersOf(input).get("x-forwarded-proto")+ )[0]?.toLowerCase();+ if (forwarded === "http" || forwarded === "https") return forwarded;+ return urlOf(input)?.protocol === "https:" ? "https" : "http";+}++/**+ * The host the client addressed (`app.carbon.ms`, with a port if it has one).+ *+ * Fine for comparing with what the browser sent (`Origin`, `Referer`). NOT for+ * building a link someone else will open: the ALB passes a caller's own+ * `X-Forwarded-Host` through, so use `getAppUrl()` / `getMESUrl()` for those.+ */+export function getRequestHost(input: RequestLike): string | null {+ const headers = headersOf(input);+ return (+ listOf(headers.get("x-forwarded-host"))[0] ??+ headers.get("host") ??+ urlOf(input)?.host ??+ null+ );+}++/** `https://app.carbon.ms`: the origin the client addressed. Same caveat as the host. */+export function getRequestOrigin(input: RequestLike): string | null {+ const host = getRequestHost(input);+ return host ? `${getRequestProtocol(input)}://${host}` : null;+}+export const getPreferenceHeaders = (request: Request) => {const acceptLanguage = request.headers.get("accept-language");const cookieHeader = request.headers.get("cookie");diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex bf6a266e8e..f5099c9bf6 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -2080,6 +2080,9 @@ importers:'@internationalized/date':specifier: 'catalog:'version: 3.12.0+ '@jitl/quickjs-singlefile-browser-release-sync':+ specifier: 0.32.0+ version: 0.32.0'@jsquash/jpeg':specifier: 1.6.0version: 1.6.0@@ -2122,6 +2125,9 @@ importers:pg:specifier: 8.20.0version: 8.20.0+ quickjs-emscripten-core:+ specifier: 0.32.0+ version: 0.32.0react-pdf:specifier: 'catalog:'@@ -2150,6 +2156,9 @@ importers:dotenv:specifier: 16.3.1version: 16.3.1+ libpg-query:+ specifier: 18.1.5+ version: 18.1.5npm-run-all:specifier: 'catalog:'version: 4.1.5@@ -5522,6 +5531,12 @@ packages:resolution: {integrity: sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw==}engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}+ '@jitl/[email protected]':+ resolution: {integrity: sha512-v9T+GQpmk43VDJ7d72sf0Nexhk+ArvtUihW27dy7lqAl0zBObFKtSBBIm5RBjwIhE8VwsPPm9PNuvPvNqLWUEg==}++ '@jitl/[email protected]':+ resolution: {integrity: sha512-Hfdl7rh8dzxNWFRiYAYNbhn0RMF1/tO6SMH2mUW0aTibqwaAtqPRbi4WkwaIDlhNz8Z4dksJi1Zjl1R54Jsc/Q==}+'@jpwilliams/[email protected]':resolution: {integrity: sha512-0CxRhNfkvFCTLZBKGvKxY2FYtYW1yWhO2McLqBL0X5UWvYjIf9suH8anKW/DNutl369A75Ewyoh2iJMwBZ2tRg==}@@ -6759,6 +6774,9 @@ packages:resolution: {integrity: sha512-C2Xj8FZ0uHWeCXXqX5B4/gVFQmtSkiuOolzAgutjTfseNOHT3pUjljDZsTSxXFGgio54bCzVFqmEOUrIVk8RDA==}engines: {node: '>=20.0.0'}+ '@pgsql/[email protected]':+ resolution: {integrity: sha512-jtAY4JU7jdVYZ/Vv3zlZqVP+FRWZokyCLKPPCnAApiaJAElpyyiMC3HRiquBu29kSrVs+rkqZD50SUIb/zyEGw==}+'@pkgjs/[email protected]':resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==}engines: {node: '>=14'}@@ -13437,6 +13455,9 @@ packages:resolution: {integrity: sha512-qvHIXtggEsw1lCNCWBYKloL2Z36DJBm0R9ThGiH2JnhKYdeZFLPFkP30Lw4yMskxxhx0bKg1gLrBHX1D2w2pSw==}engines: {node: '>=8.0.0'}+ resolution: {integrity: sha512-xsksgH106LyVUylIp2bJz1MPFmVVIGKbB8belGWmh+J8/i38w8eM1twDIBnd97tzeNQFctH9MWKMthl22+fWcQ==}+resolution: {integrity: sha512-lsmMmGXBxXIK/VMLEj0kL6MtUs1kBGj1nTCzi6zgQoG1DEwqwt2DQyHxcLykceIxAnfE3hya7NuIh6PpC6S3fA==}@@ -14978,6 +14999,9 @@ packages:resolution: {integrity: sha512-iHZWu+q3IdFZFX36ro/lKBkSvfkztY5Y7HMiPlOUjhupPcG2JMfst2KKEpu5XndviX/3UhFbRngUPNKtgvtZiA==}+ resolution: {integrity: sha512-QFnPfjFey8EqknSrSxe1hZrf1/8z7/6s1QzGOmKo6++02r7QRRX7ZoyNaZh7JuVjWsVW87KnQrbZqnHkOAzUyg==}+resolution: {integrity: sha512-h36JMxKRqrAxVD8201FrCpyeNuUY9Y5zZwujr20fFO77tpUtGa6EZzfKw/3WaiBX95fq7+MpsuMLNdSnORAwSA==}engines: {node: '>=14.18.0'}@@ -18505,6 +18529,12 @@ snapshots:'@types/yargs': 17.0.35chalk: 4.1.2+ '@jitl/[email protected]': {}++ '@jitl/[email protected]':+ dependencies:+ '@jitl/quickjs-ffi-types': 0.32.0+'@jpwilliams/[email protected]': {}'@jridgewell/[email protected]':@@ -20123,6 +20153,8 @@ snapshots:tslib: 2.8.1tsyringe: 4.10.0+ '@pgsql/[email protected]': {}+'@pkgjs/[email protected]':optional: true@@ -28180,6 +28212,10 @@ snapshots:+ dependencies:+ '@pgsql/types': 18.0.0+@@ -29897,6 +29933,10 @@ snapshots:dependencies:inherits: 2.0.4+ dependencies:+ '@jitl/quickjs-ffi-types': 0.32.0+