Skip to content

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

(feat): each company's files now live in its own storage bucket (#1682)

Anshul sharma03f252a3bda9
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 47afd4de63..56720977e4 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -2072,6 +2072,16 @@ full-screen ERP route.
**Applies to:** `packages/jobs/src/inngest/functions/**` — every cron with a per-company loop (`accounting-*-sweep`, `accounting-reconciliation`, `accounting-consolidation`, `scheduled/mrp.ts`); use `runIsolatedCompanyStep` (`integrations/accounting-auth-failure.ts`) for the accounting ones.
+## Sweeping storage call sites by one literal misses named-constant buckets
+
+**Context:** The company-private-bucket migration swept every `storage.from("private")` call in the repo to per-company buckets. The literal grep found ~160 call sites and missed six more: `RAW_DURABLE_BUCKET = "private"` (assembler-client), `STORAGE_BUCKET = "private"` (company-backup/export), `BUCKET = "private"` (onshape-attach), `DOCUMENTS_BUCKET = "private"` (download.$token), `archiveBucket: "private"` (audit.config), and the `["private", "temp-staging"]` probe arrays in both apps' model.artifacts/model.download routes.
+
+**Problem:** Each miss was a real defect, not noise — new CAD raws kept landing in the legacy bucket, backups silently skipped assets uploaded to company buckets, restores wrote assets back into the legacy bucket, and token downloads / audit-archive reads would 404 on new files once the legacy fallback is removed.
+
+**Rule:** When migrating a string-keyed resource (a bucket, a queue, a topic), grep for the VALUE in every syntactic position — `= "x"`, `: "x"`, `"x",`, `("x"`, and type unions — not just the one call pattern you are rewriting. Constants exist precisely to hide the literal from the call site.
+
+**Applies to:** any repo-wide sweep keyed on a string literal; storage buckets (`private`, `temp-staging`, `company-templates`), PGMQ queue names, Inngest event names.
+
## A merged-away table breaks every existing backup unless the rename map and schema manifest move with it
**Context:** The sales-rules PR (#1382) merged `storageRule` / `storageRuleItemAssignment` / `storageRuleWorkCenterAssignment` into the shared `enforcementRule*` tables and dropped the old ones. The branch shipped with no `TABLE_RENAMES` entries and a stale `packages/jobs/manifests/schema.json` still listing the dropped tables.
@@ -2111,3 +2121,90 @@ full-screen ERP route.
**Rule:** Realtime listeners must not revalidate while a fetcher on the page is submitting — use `useRealtimeRevalidator()` (`apps/mes/app/hooks/useRealtime.tsx`), never a bare `useRevalidator().revalidate()` in a realtime callback. Skipping loses nothing: the router revalidates after every action, which is why `revalidate()` already no-ops during a navigation submission. The same race also reached single-operation completion: finishing a job's last operation completes the job, the job UPDATE revalidated the operation loader mid-action, its floor gate redirected with "This operation's job has not been released to the floor", and the operator saw that error instead of "Operation finished successfully" (reproduced 2 of 10 runs before the guard, 0 of 8 after). Batch completion additionally returns `data({ completed: true })` and navigates client-side.
**Applies to:** every realtime- or interval-driven `revalidate()` on a page that submits fetchers — MES `useOperation`, `AssemblyView`, `useRealtime`.
+
+## A hardcoded list that mirrors the schema goes stale silently, and a restore still reports success
+
+**Context:** Two independent cross-company restore defects, found together while
+tracing one broken restored company. (1) #1148 (2026-07-20) added `glbPath` /
+`graphPath` to `modelUpload` and removed `modelPath` from `STORAGE_PATH_COLUMNS`
+without adding the two new columns, so restored assemblies pointed at the SOURCE
+company's storage prefix. (2) `2a19048def` (2026-08-31) correctly widened
+id-remapping to composite-PK tables, which swept in `part`/`material`/
+`consumable`/`service`/`tool` — whose `id` is a human-authored part number
+(`ADCS-001`) that the `parts` view joins against `item."readableId"`, not an
+identifier. Every Items page rendered empty against 860 intact rows.
+
+**Problem:** Both lists mirror a schema property no constraint expresses, so
+neither compiler nor DB catches drift. Worse, the restore job reports SUCCESS in
+both cases — the rows load and the files copy; only a join or a URL silently
+resolves to nothing. And both are invisible on a same-company restore, where the
+remap is a no-op, so the usual manual test passes.
+
+**Rule:** When a list in code enumerates schema facts (path columns, tables
+exempt from a transform), pin it with a test that fails when the schema outgrows
+it, and state in the list's own doc comment what must be added alongside a new
+column/table. When widening a rule that mints or rewrites ids, ask which of the
+newly-swept tables use that column as a VALUE others match on rather than as an
+identifier — `part.id` is a part number. Verify a restore by querying the view
+the UI reads (`parts`), not the table (`part`); the table was always full.
+
+**Applies to:** `packages/jobs/src/inngest/functions/tasks/company-backup.ts`
+(`STORAGE_PATH_COLUMNS`, `READABLE_ID_TABLES`), `buildIdMaps` in
+`company-backup.transforms.ts`, and any future cross-company restore work — test
+cross-company, never same-company.
+
+## A folder that implies "run this in production" arms every file dropped into it
+
+**Context:** One-off data migrations (copying the legacy `private` bucket into
+per-company buckets) needed to run automatically, once per database. The design
+made `scripts/one-off/` self-registering: `discoverOneOffScripts` reads the
+directory and every `.ts` file is executed against every production database
+after `supabase db push`, recorded in that database's own `scriptRun` table.
+
+**Problem:** Removing the hardcoded registry array killed a real duplication —
+a list that could disagree with the folder — but replaced an explicit opt-in
+with an implicit one. `endsWith(".ts")` also matches `foo.test.ts`, and
+`scripts/lib/` already colocates `*.test.ts` beside its sources. A developer
+following the repo's own established convention would have shipped a test file
+into production execution. Nothing in the type system, the linter, or a review
+diff makes a new file in a directory look dangerous.
+
+**Rule:** When a directory's *membership* is what triggers an action, gate it
+with an ALLOWLIST pattern and make non-matching files a loud failure, never a
+silent skip. A blocklist arms whatever nobody thought to exclude; a silent skip
+is worse than a crash, because a script ignored for a filename typo is
+indistinguishable from one that already ran, and the deploy reports success
+having done nothing. State the naming rule in the folder's README, and test it
+with the exact filename the surrounding conventions would produce.
+
+**Applies to:** `ci/src/one-off-scripts.ts` (`SCRIPT_FILENAME`,
+`discoverOneOffScripts`), `scripts/one-off/`, and any future
+convention-over-configuration discovery where the discovered thing is executed
+rather than merely loaded.
+
+## A wrapper that narrows a result type needs its call sites re-read, not re-cast
+
+**Context:** Replacing the free-function storage helpers
+(`listCompanyPrivateObjects` and friends) with a fluent
+`storage(client).company(id)` client in `@carbon/files`. The old helpers
+returned `{ data: StorageFileLike[]; errors: [] }` — `data` never null, entries
+structurally typed — so ~10 call sites carried `as FileObject[]` /
+`as unknown as StorageItem[]` casts to recover the real supabase fields. The
+new client returns supabase's own `{ data: FileObject[] | null; error }`.
+
+**Problem:** Every one of those casts still compiled, and now silently asserted
+away a `null` the wrapper had just introduced. `(result.data as FileObject[]).map(...)`
+typechecks and throws at runtime the first time a company bucket errors —
+exactly the case the legacy-fallback window makes likely. A cast written to
+paper over a WIDER type keeps compiling when the type gets NARROWER, and TS
+reports nothing.
+
+**Rule:** When a refactor changes a shared helper's return type, grep its call
+sites for casts on the changed field BEFORE trusting a green typecheck — a cast
+is a silenced diagnostic, so the compiler cannot tell you it is now wrong.
+Delete the cast and let the type flow; if the new type is right, the cast was
+load-bearing only for the old one.
+
+**Applies to:** `packages/files/src/storage.ts` (`CompanyBucket`), its ~60 call
+sites across `apps/erp`, `apps/mes`, `packages/{jobs,ee,lib}`, and any future
+change to a helper whose result is destructured widely.
diff --git a/.ai/plans/2026-09-17-company-private-buckets.md b/.ai/plans/2026-09-17-company-private-buckets.md
new file mode 100644
index 0000000000..ab06ae1a40
--- /dev/null
+++ b/.ai/plans/2026-09-17-company-private-buckets.md
@@ -0,0 +1,280 @@
+# Company Private Buckets — implementation plan
+
+**Spec / source:** `.ai/specs/2026-09-17-company-private-buckets.md`
+**Branch:** `feat/supabase-bucket-migration` (worktree `carbon-feat-supabase-bucket-migration`)
+
+## Progress
+- [x] Task 1: Storage contract in `@carbon/utils` (`storage.ts` + tests) — 14 tests pass
+- [x] Task 2: Bucket-provisioning migration (trigger + backfill) — file written; `pnpm db:migrate` BLOCKED locally (worktree has no provisioned stack; `storage.buckets` missing in postgres-only stack) — apply from the main checkout
+- [x] Task 3: Preview routes, `getPrivateUrl`, path helpers (ERP + MES) — gate amended to allow shared `public`/`temp-staging` buckets (behavior preservation; spec AC#4 adjusted)
+- [x] Task 4: ERP module services + MCP signed-upload wrappers — 34 sites across 10 files
+- [x] Task 5: ERP UI components sweep — 75 sites across 48 files
+- [x] Task 6: ERP routes sweep (x+, api+, file+, share+) — 20 files incl. share-route TODO resolved
+- [x] Task 7: MES app sweep — mes typecheck green
+- [x] Task 8: packages/jobs + ee + lib sweep — added `@carbon/utils` dep to `@carbon/lib`; jobs/ee/lib typecheck green
+- [x] Task 9: Edge function `import-csv` — inline fallback; deno not installed locally, CI checks
+- [x] Task 10: Copy script `scripts/migrate-private-buckets.ts` — standalone tsc green, `--dry-run` supported
+- [x] Task 11: Final verification sweep — all six typechecks green, 245 utils tests pass (14 new), lint 35/35, leftover sweep clean (only helper internals + import-csv inline fallback + copy-script source remain; scripts/model-upload.ts also migrated). `.claude/rules` mentions of the private bucket deliberately NOT updated yet — they document committed code only; sync post-commit.
+
+## Dependencies
+Task 1 first (everything imports it). Task 2 independent. Tasks 3–9 depend on 1 and are mutually independent (parallel subagents OK, but 4/5/6 touch adjacent ERP files — run 4 before 5/6 to avoid conflicts in service files imported by components). Task 10 independent of 3–9. Task 11 last.
+
+## Shared conventions for every sweep task (3–9)
+
+- Import from `@carbon/utils`: `getCompanyPrivateBucket`, `LEGACY_PRIVATE_BUCKET`, `downloadCompanyPrivateObject`, `createCompanyPrivateSignedUrl`, `listCompanyPrivateObjects`, `removeCompanyPrivateObjects`.
+- **Writes** (`upload`, `createSignedUploadUrl`, `copy`, `move`): `client.storage.from(getCompanyPrivateBucket(companyId))` — no fallback. Object paths unchanged.
+- **Reads** (`download`, `createSignedUrl`): use the fallback helpers, passing `client.storage`.
+- **Lists**: `listCompanyPrivateObjects` (unions company + legacy, de-dup by name, company wins).
+- **Removes**: `removeCompanyPrivateObjects` (both buckets, ignore missing).
+- Where no `companyId` is in scope but the object path starts with it, derive: `const companyId = objectPath.split("/")[0]` with a comment. Prefer real companyId when available.
+- Never touch: `temp-staging`, `company-templates`, `public`, `avatars`, `feedback` buckets; `getDatasetAssetUrl` branches; zstd logic in preview routes.
+- If a call site doesn't fit these patterns, STOP and report — do not improvise.
+
+---
+
+## Task 1: Storage contract in `@carbon/utils`
+
+**Depends on:** none
+**Files:**
+- Create: `packages/utils/src/storage.ts`
+- Create: `packages/utils/src/storage.test.ts`
+- Modify: `packages/utils/src/index.ts` — add `export * from "./storage";`
+
+**Steps:**
+1. Implement in `storage.ts` (no supabase-js dependency — structural typing):
+ ```ts
+ export const LEGACY_PRIVATE_BUCKET = "private";
+ export const COMPANY_BUCKET_FILE_SIZE_LIMIT = 52428800;
+
+ export const normalizeStorageSegment = (value: string) =>
+ value.trim().replace(/[\\/]+/g, "-").replace(/^[-/]+|[-/]+$/g, "");
+
+ export const getCompanyPrivateBucket = (companyId: string) =>
+ normalizeStorageSegment(companyId);
+
+ export const hasCompanyPrivateObjectPathPrefix = (companyId: string, objectPath: string) =>
+ objectPath.startsWith(`${getCompanyPrivateBucket(companyId)}/`);
+
+ export const buildCompanyPrivateStorageTarget = ({ companyId, logicalFolder, entityId, fileName }: {...})
+ // => { physicalBucket, logicalFolder, objectPath: [bucket, folder, entityId?, fileName].filter(Boolean).join("/") }
+ ```
+ Fallback helpers take a minimal `StorageClientLike` interface (`from(bucket) => { download, createSignedUrl, list, remove }` with supabase-shaped `{ data, error }` returns):
+ - `downloadCompanyPrivateObject({ storage, companyId, objectPath })` — try company bucket; on error/null data, try `LEGACY_PRIVATE_BUCKET`; return `{ data, physicalBucket, errors: { bucket, error }[] }`.
+ - `createCompanyPrivateSignedUrl({ storage, companyId, objectPath, expiresIn })` — same two-step; returns `{ signedUrl, physicalBucket, errors }`.
+ - `listCompanyPrivateObjects({ storage, companyId, prefix, options? })` — list both buckets (company first), union de-duped by `name`, company entries win; collect per-bucket errors; returns `{ data, errors }`.
+ - `removeCompanyPrivateObjects({ storage, companyId, objectPaths })` — remove from company bucket AND legacy bucket; a "not found"/empty result on either is NOT an error; return combined `{ errors }` only for real failures.
+2. Tests in `storage.test.ts` (vitest, mirror `packages/utils/src/*.test.ts` style): normalization edge cases; target path shape with/without `entityId`; download fallback order (company hit → no legacy call; company miss → legacy tried); list de-dup preference; remove tolerates missing on one bucket.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/utils test && pnpm --filter @carbon/utils typecheck
+# Expected: storage.test.ts passes, tsgo exits 0
+```
+
+**Out of scope:** `packages/utils/src/storage-rules.ts` (warehouse rules, unrelated).
+
+## Task 2: Bucket-provisioning migration
+
+**Depends on:** none
+**Files:**
+- Create: via `pnpm db:migrate:new company-bucket-provisioning` (timestamp HHMMSS must not be 000000)
+
+**Steps:**
+1. Migration SQL:
+ ```sql
+ -- Backfill buckets for companies created after 20250827181005, 50MB cap
+ INSERT INTO storage.buckets (id, name, public, file_size_limit)
+ SELECT id, id, false, 52428800 FROM company
+ ON CONFLICT (id) DO NOTHING;
+
+ -- Normalize limit on the 2025 backfill rows (created with NULL)
+ UPDATE storage.buckets SET file_size_limit = 52428800
+ WHERE id IN (SELECT id FROM company) AND file_size_limit IS NULL;
+
+ CREATE OR REPLACE FUNCTION public.create_company_private_bucket()
+ RETURNS TRIGGER AS $$
+ BEGIN
+ INSERT INTO storage.buckets (id, name, public, file_size_limit)
+ VALUES (NEW.id, NEW.id, false, 52428800)
+ ON CONFLICT (id) DO NOTHING;
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql SECURITY DEFINER SET search_path = public, storage;
+
+ CREATE TRIGGER create_company_private_bucket_trigger
+ AFTER INSERT ON "company"
+ FOR EACH ROW EXECUTE FUNCTION public.create_company_private_bucket();
+ ```
+ (Precedent for AFTER INSERT ON company: `20240908100622_terms.sql:25`. SECURITY DEFINER needed — authenticated role can't write storage.buckets.)
+2. `pnpm db:migrate` (applies + regenerates types; storage schema isn't in generated public types, so no TS diff expected).
+
+**Verify:**
+```bash
+pnpm db:migrate
+# Expected: migration applies cleanly; then `pnpm db:check:datasets` passes (company inserts still work)
+```
+
+**Out of scope:** RLS changes (20250827181005 already covers company buckets); dropping the "Shared Private Bucket" policy.
+
+## Task 3: Preview routes, `getPrivateUrl`, path helpers
+
+**Depends on:** 1
+**Files:**
+- Modify: `apps/erp/app/routes/file+/preview+/$bucket.$.tsx` — bucket gate + fallback download
+- Modify: `apps/mes/app/routes/file+/preview+/$bucket.$.tsx` — same
+- Modify: `apps/erp/app/utils/path.ts` — `getPrivateUrl` (line ~2388)
+- Modify: `apps/mes/app/utils/path.ts` — `getPrivateUrl` (line ~227)
+
+**Steps:**
+1. Preview routes: keep zstd streaming and the existing segment-bounded ownership check EXACTLY as-is. Add after `requirePermissions`: allow only `params.bucket === getCompanyPrivateBucket(companyId) || params.bucket === LEGACY_PRIVATE_BUCKET`, else 403. Replace the direct `.download(...)` with `downloadCompanyPrivateObject` when the requested bucket is company/legacy (single code path — the helper tries both).
+2. `getPrivateUrl(path, companyId?)` in both apps: keep the `getDatasetAssetUrl(path)` branch first. When a `companyId` argument is provided emit `/file/preview/${getCompanyPrivateBucket(companyId)}/${path}`; the no-arg legacy form derives the bucket from `path.split("/")[0]` (paths start with companyId) and falls back to `private` only if the first segment is empty. Update call sites of `getPrivateUrl` ONLY where the compiler forces it (signature stays backward compatible).
+
+**Verify:**
+```bash
+pnpm --filter erp typecheck && pnpm --filter mes typecheck
+# Expected: exit 0
+```
+
+**Out of scope:** `file+/model+/public.$.tsx` (Task 6); dataset-asset resolution.
+
+## Task 4: ERP module services + MCP signed-upload wrappers
+
+**Depends on:** 1 (do before 5/6)
+**Files (Modify, apply shared conventions):**
+- `apps/erp/app/modules/documents/documents.service.ts`
+- `apps/erp/app/modules/inventory/inventory.service.ts`
+- `apps/erp/app/modules/items/items.service.ts`
+- `apps/erp/app/modules/production/production.service.ts`
+- `apps/erp/app/modules/purchasing/purchasing.service.ts`
+- `apps/erp/app/modules/quality/quality.service.ts`
+- `apps/erp/app/modules/sales/sales.service.ts`
+- `apps/erp/app/modules/sales/sales.import.server.ts`
+- `apps/erp/app/modules/shared/shared.server.ts`
+- `apps/erp/app/modules/shared/shared.service.ts`
+- `apps/erp/app/modules/documents/documents.models.ts` — `buildDocumentUploadPath` gains no path change (path keeps companyId prefix) but its consumers' `createSignedUploadUrl` calls move to the company bucket
+
+**Steps:**
+1. Sweep every `from("private")` per shared conventions. Services already receive `companyId` in almost every signature; where one genuinely lacks it, derive from path first segment.
+2. `shared.server.ts` (~L191,265,342,474 generated-PDF upload/copy + signed URLs): uploads/copies to company bucket; signed URLs via `createCompanyPrivateSignedUrl`.
+3. MCP signed-upload wrappers (added in e0f8265ea4) in documents/items/production/purchasing/sales services: mint on company bucket.
+
+**Verify:**
+```bash
+pnpm --filter erp typecheck
+# Expected: exit 0
+```
+
+**Out of scope:** UI components (Task 5), routes (Task 6).
+
+## Task 5: ERP UI components sweep
+
+**Depends on:** 1, 4
+**Files (Modify, apply shared conventions — all have `useUser()`/`company.id` available; precedent for the pattern: PR #682's `CadModel`/`Documents.tsx` changes, i.e. `const bucket = getCompanyPrivateBucket(company.id)` once per component):**
+- `apps/erp/app/components/`: `AttachmentsList.tsx`, `DefaultAttachmentsPanel.tsx`, `Documents.tsx`, `Form/PdfExtractor.tsx`, `ImportCSVModal/UploadCSV.tsx`, `ItemThumnailUpload.tsx`, `Layout/Topbar/Suggestion.tsx`, `SlidesEditor.tsx`
+- `apps/erp/app/modules/**/ui/`: `account/.../UserAttributesForm.tsx`, `accounting/.../FixedAssetNotes.tsx`, `documents/.../DocumentCreateForm.tsx`, `documents/.../useDocument.ts`, `inventory/.../PickingListNotes.tsx`, `inventory/.../ReceiptLines.tsx`, `inventory/.../ShipmentNotes.tsx`, `inventory/.../StockTransferNotes.tsx`, `items/.../ChangeNoticeActions.tsx`, `items/.../ChangeNoticeContent.tsx`, `items/.../BillOfProcess.tsx`, `items/.../ItemDocuments.tsx`, `items/.../ItemNotes.tsx`, `production/.../AssemblyInstructionProperties.tsx`, `production/.../AssemblyStepSlides.tsx`, `production/.../InspectionDocumentEditor.tsx`, `production/.../JobBillOfProcess.tsx`, `production/.../JobDocuments.tsx`, `production/.../JobNotes.tsx`, `production/.../ProcedureExplorer.tsx`, `purchasing/.../SupplierTaxForm.tsx`, `purchasing/.../SupplierInteractionDocuments.tsx`, `purchasing/.../SupplierInteractionLineDocuments.tsx`, `purchasing/.../SupplierInteractionLineNotes.tsx`, `purchasing/.../SupplierInteractionNotes.tsx`, `quality/.../GaugeCalibrationRecordForm.tsx`, `quality/.../QualityDocumentEditor.tsx`, `quality/.../IssueContent.tsx`, `quality/.../IssueTask.tsx`, `quality/.../IssueWorkflowForm.tsx`, `quality/.../RiskRegisterForm.tsx`, `resources/.../MaintenanceDispatchForm.tsx`, `resources/.../MaintenanceDispatchNotes.tsx`, `sales/.../CustomerTaxForm.tsx`, `sales/.../OpportunityDocuments.tsx`, `sales/.../OpportunityLineDocuments.tsx`, `sales/.../OpportunityLineNotes.tsx`, `sales/.../OpportunityNotes.tsx`, `sales/.../QuoteBillOfProcess.tsx`
+
+**Steps:** apply shared conventions (uploads → company bucket; downloads/signed URLs → fallback helpers; lists → union helper; removes → both-bucket helper).
+
+**Verify:**
+```bash
+pnpm --filter erp typecheck
+# Expected: exit 0
+```
+
+**Out of scope:** styling/behavior changes; `getPrivateUrl` internals (done in Task 3).
+
+## Task 6: ERP routes sweep
+
+**Depends on:** 1, 4
+**Files (Modify, apply shared conventions):**
+- `apps/erp/app/routes/api+/sales.digital-quote.$id.tsx`
+- `apps/erp/app/routes/file+/model+/public.$.tsx`
+- `apps/erp/app/routes/share+/customer.$id.$.tsx` — resolve the `// TODO` at ~L82: bucket = `getCompanyPrivateBucket(customerPortal.companyId)`; require `hasCompanyPrivateObjectPathPrefix(customerPortal.companyId, decodedPath)` else 404; download via fallback helper
+- `apps/erp/app/routes/x+/`: `inspection-document+/$id.delete.tsx`, `maintenance+/$dispatchId.tsx`, `procedure+/$id.tsx`, `purchase-invoice+/new.tsx`, `purchase-order+/$orderId.finalize.tsx`, `purchase-order+/$orderId.tsx`, `purchasing-rfq+/$rfqId.finalize.tsx`, `quote+/$quoteId.drag.tsx`, `quote+/$quoteId.finalize.tsx`, `sales-invoice+/$invoiceId.post.tsx`, `sales-rfq+/$rfqId.drag.tsx`, `sales-rfq+/new.tsx`, `settings+/purchasing.tsx`, `shipment+/$shipmentId.post.tsx`, `supplier+/$supplierId.default-attachments.tsx`, `supplier-quote+/$id.send.tsx`, `training+/$id.tsx`
+
+**Steps:**
+1. Sweep per shared conventions. Finalize/send routes (`purchasing-rfq`, `purchase-order`, `quote`, `supplier-quote`, `sales-invoice`): email-attachment signed URLs via `createCompanyPrivateSignedUrl`; log the returned `errors` array before failing.
+2. `file+/model+/public.$.tsx` downloads a model by path with no session — derive companyId from the path's first segment for the fallback helper.
+
+**Verify:**
+```bash
+pnpm --filter erp typecheck
+# Expected: exit 0
+```
+
+**Out of scope:** `send-email.ts` internals (stays SMTP-only, attachments arrive as URLs — no change needed there unless the compiler disagrees; if it does, STOP and report).
+
+## Task 7: MES app sweep
+
+**Depends on:** 1
+**Files (Modify, apply shared conventions):**
+- `apps/mes/app/services/operations.service.ts` (4 lists)
+- `apps/mes/app/components/Suggestion.tsx`, `.../JobOperation/components/Step.tsx`, `.../JobOperation/components/MaintenanceDispatch.tsx` (uploads)
+
+**Verify:**
+```bash
+pnpm --filter mes typecheck
+# Expected: exit 0
+```
+
+## Task 8: packages/jobs + ee + lib sweep
+
+**Depends on:** 1
+**Files (Modify, apply shared conventions; all run server-side with serviceRole clients):**
+- `packages/jobs/src/inngest/functions/`: `extraction/extract-document.ts` (download), `scheduled/cleanup.ts` (list/info), `tasks/assembly-convert.ts` (signed upload URLs), `tasks/assembly-plan.ts`, `tasks/model-optimize.ts` (list + signed upload URL), `tasks/model-thumbnail.ts` (upload/remove), `tasks/print-job/renderers.tsx` (download)
+- `packages/ee/src/paperless-parts/lib/lib.ts` (3 uploads)
+- `packages/lib/src/slack.server.ts:118` (createSignedUrl → fallback helper)
+
+**Steps:** event payloads already carry `companyId` in most of these; where only a path exists, derive from first segment with a comment.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/jobs typecheck && pnpm --filter @carbon/ee typecheck && pnpm --filter @carbon/lib typecheck
+# Expected: exit 0 for all three
+```
+
+## Task 9: Edge function `import-csv`
+
+**Depends on:** none (can't import `@carbon/utils` — Deno)
+**Files:**
+- Modify: `packages/database/supabase/functions/import-csv/index.ts` (~L971)
+
+**Steps:** inline two-step download: try `client.storage.from(companyId).download(filePath)` (companyId is in the validated payload), on error fall back to `from("private")`. No shared-lib extraction for one call site.
+
+**Verify:**
+```bash
+cd packages/database/supabase/functions && deno check import-csv/index.ts
+# Expected: exit 0 (if deno isn't installed locally, STOP and note it in the run log; CI checks it)
+```
+
+## Task 10: Copy script
+
+**Depends on:** none
+**Files:**
+- Create: `scripts/migrate-private-buckets.ts`
+- Copy from (precedent): `scripts/model-upload.ts` (env/client setup style), PR #682's `scripts/migrate-private-buckets.ts` (shape)
+
+**Steps:**
+1. For each `company.id` (service-role client): `createBucket(companyId, { public: false, fileSizeLimit: 52428800 })` tolerating "already exists"; recursively list `private` under `companyId/` (paginate, recurse folders); `copy(key, key, { destinationBucket: companyId })`; count 409/"already exists" as skipped. Print per-company `{ copied, skipped, failed }` and a final summary. Never delete.
+2. Add a `--dry-run` flag that lists what would be copied.
+
+**Verify:**
+```bash
+pnpm exec tsx scripts/migrate-private-buckets.ts --dry-run
+# Expected: runs against local stack, prints per-company summary, exits 0
+```
+
+**Out of scope:** deleting legacy objects (follow-up per spec).
+
+## Task 11: Final verification sweep
+
+**Depends on:** all
+**Steps:**
+1. `rg 'from\("private"\)' apps packages scripts --type ts` — expected hits ONLY in: `packages/utils/src/storage.ts` (helper internals), `packages/database/supabase/functions/import-csv/index.ts` (inline fallback), `scripts/migrate-private-buckets.ts` (source bucket), contrib examples. Anything else = missed site, go fix.
+2. `rg 'LEGACY_PRIVATE_BUCKET' packages/utils/src/storage.ts` — constant exists.
+3. Typechecks: `pnpm exec turbo run typecheck --filter=@carbon/utils --filter=erp --filter=mes --filter=@carbon/jobs --filter=@carbon/ee --filter=@carbon/lib`.
+4. Tests: `pnpm --filter @carbon/utils test`.
+5. `pnpm run lint`.
+6. Update `.claude/rules/` / AGENTS.md if any documented storage claim went stale (check `rg -l 'private.*bucket' .claude/rules packages/*/AGENTS.md -i` and fix only real staleness).
+
+**Verify:** all commands above exit 0; report actual outputs.
diff --git a/.ai/plans/2026-09-18-restore-readable-ids-and-model-paths.md b/.ai/plans/2026-09-18-restore-readable-ids-and-model-paths.md
new file mode 100644
index 0000000000..05345851ec
--- /dev/null
+++ b/.ai/plans/2026-09-18-restore-readable-ids-and-model-paths.md
@@ -0,0 +1,396 @@
+# Cross-company restore fixes — implementation plan
+
+**Spec / source:** `.ai/specs/2026-09-18-restore-readable-ids-and-model-paths.md`
+**Branch:** `feat/supabase-bucket-migration` (user's explicit choice)
+**Do NOT commit** — the user must grant permission for each commit.
+
+## Progress
+- [x] Task 1: Add `READABLE_ID_TABLES` and extend `STORAGE_PATH_COLUMNS`
+- [x] Task 2: Skip readable-id tables in `buildIdMaps`
+- [x] Task 3: Add regression guards to the closure test suite
+- [x] Task 4: Update `.claude/rules/company-backup-restore.md` and `.ai/lessons.md`
+- [x] Task 5: Verify (typecheck + tests)
+
+## Dependencies
+- Task 2 needs Task 1 (imports the new constant)
+- Task 3 needs Tasks 1–2
+- Task 4 independent of 2–3 (may run in parallel with Task 3)
+- Task 5 last
+
+---
+
+## Task 1: Add `READABLE_ID_TABLES` and extend `STORAGE_PATH_COLUMNS`
+
+**Depends on:** none
+**Files:**
+- Modify: `packages/jobs/src/inngest/functions/tasks/company-backup.ts` — extend
+ `STORAGE_PATH_COLUMNS` (currently line ~65) and add `READABLE_ID_TABLES` beside it.
+
+**Steps:**
+
+1. Replace the `STORAGE_PATH_COLUMNS` declaration AND its preceding doc comment.
+ The current comment claims `modelPath` is excluded because raw models live in
+ `temp-staging` and are never backed up. That is stale: `company-export.ts`
+ (~line 246) builds the asset list by LISTING the private bucket recursively
+ under `{companyId}/`, so everything under `{companyId}/models/` is carried.
+
+ New text:
+
+```ts
+/**
+ * TEXT columns that hold a storage path (`{companyId}/…/{id}.ext`) in the
+ * company's private bucket. On reseed the companyId and the embedded ids both
+ * change, so these must be rewritten in lock-step with the files they point at
+ * (see `rewriteStoragePath`).
+ *
+ * Every `modelUpload` artifact column belongs here. A backup enumerates assets by
+ * LISTING the bucket under `{companyId}/` (`company-export.ts`), not by reading
+ * these columns — so raw CAD under `{companyId}/models/` IS carried, and a column
+ * left out of this set survives a cross-company restore still pointing at the
+ * SOURCE company's prefix. `modelPath` was dropped from this set in #1148 on the
+ * rationale that raw models had moved to the transient `temp-staging` bucket; the
+ * listing-based backup contradicts that, and the same commit added `glbPath` /
+ * `graphPath` without adding them here, which is what broke the assembly viewer
+ * on every restored company.
+ *
+ * Adding a new path column to `modelUpload` REQUIRES adding it here — the
+ * `STORAGE_PATH_COLUMNS covers every modelUpload artifact column` test fails
+ * otherwise.
+ */
+export const STORAGE_PATH_COLUMNS = new Set([
+ "thumbnailPath",
+ "modelPath",
+ "glbPath",
+ "graphPath"
+]);
+
+/**
+ * Tables whose `id` is NOT an identifier but a human-authored readable key that
+ * other rows match BY VALUE: `part.id` / `material.id` / `consumable.id` /
+ * `service.id` / `tool.id` hold the part number (`ADCS-001`) and are joined
+ * against `item."readableId"` — by the `parts` / `materials` / … views among
+ * others. There is no FK constraint expressing that, so it cannot be derived.
+ *
+ * `buildIdMaps` must NOT mint a fresh id for these: doing so orphans every row
+ * from its `item` and every list view renders empty while the rows sit there.
+ *
+ * Safe to keep verbatim because these five carry ONLY the composite PK
+ * `("id","companyId")` — no global `UNIQUE (id)`. That is what separates them
+ * from the composite-PK tables the id-remap exists for (`balloon`,
+ * `inspectionDocument`, `inspectionFeature`, `changeOrderRequiredAction`,
+ * `demandProjection`), which DO carry a global `UNIQUE (id)` and would collide
+ * with the source company's live rows if their ids were preserved. The two sets
+ * are disjoint and must stay that way — see the disjointness test.
+ *
+ * Deliberately an explicit list, not a derived rule: `composite PK + text id +
+ * no global UNIQUE(id)` matches ~65 tables (`workflow`, `kanban`,
+ * `inventoryCount`, `stockTransfer`, …) that all legitimately need remapping.
+ */
+export const READABLE_ID_TABLES = new Set([
+ "part",
+ "material",
+ "consumable",
+ "service",
+ "tool"
+]);
+```
+
+2. Do not change `STORAGE_BUCKET` or anything else in the file.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/jobs
+# Expected: "Tasks: 2 successful" (or 1 successful), no "error TS" lines
+```
+
+**Out of scope:** `rewriteStoragePath` itself (its logic is correct);
+`rewriteToTemplateAssetPath`; the asset copy/restore functions.
+
+---
+
+## Task 2: Skip readable-id tables in `buildIdMaps`
+
+**Depends on:** Task 1
+**Files:**
+- Modify: `packages/jobs/src/inngest/functions/tasks/company-backup.transforms.ts` —
+ import `READABLE_ID_TABLES` and add one guard in `buildIdMaps`.
+
+**Steps:**
+
+1. Add `READABLE_ID_TABLES` to the existing import from `./company-backup`
+ (the file already imports `newIdForTable` and others from there — extend that
+ import list, keep it alphabetical if it already is).
+
+2. In `buildIdMaps`, add the skip as the FIRST check inside the `for (const table
+ of tables)` loop, before the `idType` lookup:
+
+```ts
+ for (const table of tables) {
+ // A readable-id table's `id` is a part number other rows match by value
+ // (`item."readableId"`), not an identifier — minting a fresh one orphans
+ // every row from its item. Skipped in BOTH the restore and the reseed/import
+ // path: the restore wipes the target first so the original values are free,
+ // and on an additive reseed a genuine duplicate hits the composite PK and
+ // fails loudly rather than silently corrupting the readable key.
+ if (READABLE_ID_TABLES.has(table.name)) continue;
+ const idType = table.columns.find((c) => c.name === "id")?.udtName;
+```
+
+3. Leave the rest of the function unchanged. A table with no entry in `idMaps`
+ already keeps its `id` verbatim in `buildRowTransforms` — this is the same
+ path the int/serial-id tables (`journal`) take, pinned by the existing test
+ "does NOT crash on an int/serial-id table absent from idMaps".
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/jobs
+# Expected: no "error TS" lines
+```
+
+**Out of scope:** the `idFk` parent-sharing branch; `newIdForTable`;
+`buildRowTransforms`; `mapCollidingRows`. If `buildRowTransforms` turns out NOT to
+keep ids verbatim for tables absent from `idMaps`, STOP and report — do not
+improvise a second code path.
+
+---
+
+## Task 3: Add regression guards to the closure test suite
+
+**Depends on:** Tasks 1, 2
+**Files:**
+- Modify: `packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts`
+- Copy from (precedent): the existing `describe("buildRowTransforms", …)` block in
+ the same file — reuse its `col()`, `table()`, `ctx()` and `apply()` helpers.
+
+**Steps:**
+
+1. Extend the existing import from `./company-backup` to include
+ `READABLE_ID_TABLES` and `STORAGE_PATH_COLUMNS`.
+
+2. Append a new `describe` block at the end of the file:
+
+```ts
+// ── Cross-company restore: readable ids and storage paths ────────────────────
+// Both guards pin a hardcoded list that a future schema change can silently
+// invalidate. Each list went stale exactly once already and produced a restore
+// that looked successful and was not: the Items pages rendered empty
+// (readable ids rewritten) and assemblies would not load (path columns left
+// pointing at the source company).
+describe("cross-company restore invariants", () => {
+ // Composite-PK tables backed by a global UNIQUE (id). Their ids MUST be
+ // remapped or a cross-company restore collides with the source company's
+ // still-live rows. Verified against pg_index on 2026-09-18.
+ const GLOBAL_UNIQUE_ID_TABLES = [
+ "balloon",
+ "changeOrderRequiredAction",
+ "demandProjection",
+ "inspectionDocument",
+ "inspectionFeature"
+ ];
+
+ // Every path column on `modelUpload`, verified against the live schema on
+ // 2026-09-18. Adding one to the table means adding it here AND to
+ // STORAGE_PATH_COLUMNS.
+ const MODEL_UPLOAD_PATH_COLUMNS = [
+ "modelPath",
+ "thumbnailPath",
+ "glbPath",
+ "graphPath"
+ ];
+
+ it("keeps a readable-id table out of the id maps, but maps a normal table", () => {
+ const part = table(
+ "part",
+ [col("id"), col("companyId"), col("name")],
+ [],
+ { pkColumns: ["id", "companyId"] }
+ );
+ const workflow = table(
+ "workflow",
+ [col("id"), col("companyId")],
+ [],
+ { pkColumns: ["id", "companyId"] }
+ );
+ const idMaps = buildIdMaps(
+ [part, workflow],
+ {
+ part: [{ id: "ADCS-001", companyId: "src-co", name: "Widget" }],
+ workflow: [{ id: "wf_1", companyId: "src-co" }]
+ }
+ );
+ expect(idMaps.has("part")).toBe(false);
+ expect(idMaps.get("workflow")?.get("wf_1")).toBeTypeOf("string");
+ expect(idMaps.get("workflow")?.get("wf_1")).not.toBe("wf_1");
+ });
+
+ it("preserves a part number verbatim through a cross-company restamp", () => {
+ // The `parts` view inner-joins part.id = item."readableId"; a rewritten id
+ // matches nothing and the Parts page renders empty against a full table.
+ const part = table(
+ "part",
+ [col("id"), col("companyId"), col("name")],
+ [],
+ { pkColumns: ["id", "companyId"] }
+ );
+ const idMaps = buildIdMaps(
+ [part],
+ { part: [{ id: "ADCS-001", companyId: "src-co", name: "Widget" }] }
+ );
+ const transforms = buildRowTransforms(part, part.columns, {
+ remap: true,
+ companyId: "target-co",
+ userId: "importer",
+ targetGroupId: "target-grp",
+ sourceCompanyId: "src-co",
+ idMaps,
+ idRewrite: new Map<string, string>()
+ });
+ const row: Record<string, unknown> = {
+ id: "ADCS-001",
+ companyId: "src-co",
+ name: "Widget"
+ };
+ const out: Record<string, unknown> = {};
+ part.columns.forEach((c, i) => {
+ out[c.name] = transforms[i]!(row[c.name]);
+ });
+ expect(out).toEqual({
+ id: "ADCS-001",
+ companyId: "target-co",
+ name: "Widget"
+ });
+ });
+
+ it("never exempts a table that needs a fresh id to avoid a unique collision", () => {
+ const overlap = GLOBAL_UNIQUE_ID_TABLES.filter((t) =>
+ READABLE_ID_TABLES.has(t)
+ );
+ expect(overlap).toEqual([]);
+ });
+
+ it("covers every modelUpload artifact column in STORAGE_PATH_COLUMNS", () => {
+ const missing = MODEL_UPLOAD_PATH_COLUMNS.filter(
+ (c) => !STORAGE_PATH_COLUMNS.has(c)
+ );
+ expect(missing).toEqual([]);
+ });
+});
+```
+
+3. If `buildRowTransforms`' ctx type requires fields beyond those listed, read the
+ existing `RestampCtx` helper at the top of the `buildRowTransforms` describe
+ block and match it exactly.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/jobs test -- company-backup.closure
+# Expected: all tests pass, including the 4 new ones under
+# "cross-company restore invariants"
+```
+
+**Out of scope:** rewriting existing tests; adding DB-backed tests (the suite is
+pure by design).
+
+---
+
+## Task 4: Update the rule doc and lessons
+
+**Depends on:** Task 1
+**Files:**
+- Modify: `.claude/rules/company-backup-restore.md` — the "Id minting" bullet
+ (~line 115) and the "Storage path rewriting" bullet (~line 129).
+- Modify: `.ai/lessons.md` — append one lesson.
+
+**Steps:**
+
+1. In the "Id minting" bullet, after the sentence explaining the `UNIQUE (id)`
+ five, add:
+
+ > Five OTHER composite-PK tables are excluded by name (`READABLE_ID_TABLES`:
+ > `part`, `material`, `consumable`, `service`, `tool`) because their `id` is a
+ > human-authored part number matched by value against `item."readableId"`, not
+ > an identifier. They carry only the composite PK — no global `UNIQUE (id)` —
+ > so preserving their ids cannot collide. The two sets are disjoint by
+ > construction and a test enforces it.
+
+2. Replace the "`STORAGE_PATH_COLUMNS` = `thumbnailPath` ONLY. `modelPath` (raw
+ CAD) is deliberately excluded …" text (through the end of that sentence) with:
+
+ > `STORAGE_PATH_COLUMNS` = `thumbnailPath`, `modelPath`, `glbPath`,
+ > `graphPath` — every `modelUpload` artifact column. A backup enumerates assets
+ > by LISTING the bucket under `{companyId}/`, not by reading these columns, so
+ > raw CAD IS carried; a column missing from this set survives a cross-company
+ > restore still pointing at the SOURCE company's prefix.
+
+3. Append to `.ai/lessons.md`, matching the file's existing
+ `Context → Problem → Rule → Applies to` format:
+
+```markdown
+## A hardcoded list that mirrors the schema goes stale silently, and a restore still reports success
+
+**Context:** Two independent cross-company restore defects, found together while
+tracing one broken restored company. (1) #1148 (2026-07-20) added `glbPath` /
+`graphPath` to `modelUpload` and removed `modelPath` from `STORAGE_PATH_COLUMNS`
+without adding the two new columns, so restored assemblies pointed at the SOURCE
+company's storage prefix. (2) `2a19048def` (2026-08-31) correctly widened
+id-remapping to composite-PK tables, which swept in `part`/`material`/
+`consumable`/`service`/`tool` — whose `id` is a human-authored part number
+(`ADCS-001`) that the `parts` view joins against `item."readableId"`, not an
+identifier. Every Items page rendered empty against 860 intact rows.
+
+**Problem:** Both lists mirror a schema property no constraint expresses, so
+neither compiler nor DB catches drift. Worse, the restore job reports SUCCESS in
+both cases — the rows load and the files copy; only a join or a URL silently
+resolves to nothing. And both are invisible on a same-company restore, where the
+remap is a no-op, so the usual manual test passes.
+
+**Rule:** When a list in code enumerates schema facts (path columns, tables
+exempt from a transform), pin it with a test that fails when the schema outgrows
+it, and state in the list's own doc comment what must be added alongside a new
+column/table. When widening a rule that mints or rewrites ids, ask which of the
+newly-swept tables use that column as a VALUE others match on rather than as an
+identifier — `part.id` is a part number. Verify a restore by querying the view
+the UI reads (`parts`), not the table (`part`); the table was always full.
+
+**Applies to:** `packages/jobs/src/inngest/functions/tasks/company-backup.ts`
+(`STORAGE_PATH_COLUMNS`, `READABLE_ID_TABLES`), `buildIdMaps` in
+`company-backup.transforms.ts`, and any future cross-company restore work — test
+cross-company, never same-company.
+```
+
+**Verify:**
+```bash
+grep -c "READABLE_ID_TABLES" .claude/rules/company-backup-restore.md
+# Expected: 1 (or more)
+grep -c "goes stale silently" .ai/lessons.md
+# Expected: 1
+```
+
+**Out of scope:** restructuring either document; other lessons.
+
+---
+
+## Task 5: Verify
+
+**Depends on:** Tasks 1–4
+**Files:** none (verification only)
+
+**Steps:**
+
+1. Run the scoped typecheck and the full jobs test suite.
+2. Confirm no conflict markers or stray edits: `git status --short`.
+3. Report actual output. If anything fails, report the failure verbatim — do not
+ declare success.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/jobs
+# Expected: "Tasks: ... successful", no "error TS"
+
+pnpm --filter @carbon/jobs test
+# Expected: all test files pass; the 4 new "cross-company restore invariants"
+# tests are among them
+```
+
+**Out of scope:** committing (the user must grant permission); running the whole
+repo's build; re-restoring the user's company (that is the user's manual check).
diff --git a/.ai/research/2026-09-17-security-review-company-private-buckets.md b/.ai/research/2026-09-17-security-review-company-private-buckets.md
new file mode 100644
index 0000000000..aeb94903bf
--- /dev/null
+++ b/.ai/research/2026-09-17-security-review-company-private-buckets.md
@@ -0,0 +1,116 @@
+# Security review — company-private buckets (feat/supabase-bucket-migration)
+
+Three-track review (tenant isolation / data loss / attacker-controlled input) of the
+uncommitted branch diff, 2026-09-17. Headline: **no branch-introduced cross-tenant
+access and no scenario that deletes or orphans a customer file today.** The preview
+route's new `isPrivateBucket` gate actually *closes* a HEAD hole (any URL-supplied
+bucket id was previously accepted). Remaining findings are pre-existing exposures the
+branch preserved, plus deploy-sequencing risks — listed worst-first.
+
+## Fix before merge (small, high-value)
+
+1. **Assert the tenant prefix inside the fallback helpers** — `downloadCompanyPrivateObject`
+ and `createCompanyPrivateSignedUrl` (`packages/utils/src/storage.ts:123-129, 152-166`)
+ fall back to legacy `private` with the raw `objectPath` unchecked against `companyId`.
+ Under a service-role client the path string is the only tenant boundary. Adding
+ `hasCompanyPrivateObjectPathPrefix(companyId, objectPath)` inside both helpers closes
+ findings 2 and 3 below in one place.
+ - Caveat: audit archives write company-bucket keys as `audit-logs/${companyId}/...`
+ (`packages/jobs/src/inngest/functions/scheduled/audit-archive.ts:69`) — NOT
+ companyId-prefixed, violating the module invariant (and making the legacy fallback
+ in `packages/database/src/audit.ts:365-377` fail RLS for user clients). Either
+ re-key archives to `${companyId}/audit-logs/...` or exempt that caller explicitly.
+2. **`download.$token.tsx` cross-tenant legacy read (Medium, pre-existing)** —
+ `apps/erp/app/routes/download.$token.tsx:50-54`: `document.path` content is never
+ validated against the company prefix; a company-A user who can write a `path` of
+ `companyB/<key>` gets B's bytes via the service-role legacy fallback. Fixed by #1
+ (or a local `hasCompanyPrivateObjectPathPrefix` check like the share route already does).
+3. **`import-csv` edge fn cross-tenant legacy read (Medium, pre-existing)** —
+ `packages/database/supabase/functions/import-csv/index.ts:973-976`: `filePath` is
+ client-supplied (`z.string().min(1)` only), client is service-role; the legacy
+ fallback reads any `<otherCo>/....csv` at a known key. Add
+ `if (!filePath.startsWith(companyId + "/")) throw` before the download.
+4. **Empty-companyId bucket (Medium, net-new edge)** — `getCompanyPrivateBucket("")`
+ returns `""` (`packages/utils/src/storage.ts:16`); with `path.split("/")[0] ?? ""`
+ derivations, `.from("")` gets probed (harmless miss) but the legacy fallback still
+ runs with the raw path. Make `getCompanyPrivateBucket` throw (or callers guard) on
+ empty input.
+5. **Reserved bucket ids in the trigger (Low, defense-in-depth)** —
+ `20260917163108_company-bucket-provisioning.sql:22-34`: if a `company.id` ever equaled
+ `private`/`public`/`avatars`/`feedback`/`temp-staging`/`company-templates`, the
+ `ON CONFLICT DO NOTHING` silently no-ops while the "Company bucket access" RLS policy
+ would grant that company's employees FOR ALL on the shared bucket. Not reachable
+ today (ids are generated, no user-supplied company insert path), but exclude reserved
+ ids in the trigger + backfill.
+
+## Separate urgent ticket (NOT this branch)
+
+- **Unauthenticated cross-tenant model read (High, pre-existing)** —
+ `apps/erp/app/routes/file+/model+/public.$.tsx:33-66`: no `requirePermissions`,
+ "companyId" is derived from the attacker-supplied path itself, only gate is
+ `path.includes("models")` + extension; serves from legacy `private` (and now company
+ buckets) with `Access-Control-Allow-Origin: *` and long-lived caching. Anyone with a
+ guessable key reads any tenant's model/PDF/image under a `models` segment. Same reach
+ on HEAD — the branch didn't widen it materially — but it is the weakest point found.
+ Fix: require auth (or a signed token) + `path.startsWith(companyId + "/")`.
+
+## Deploy / operational risks (data-loss track)
+
+- **H1 — copy script coverage claim is false for non-companyId prefixes.**
+ `scripts/migrate-private-buckets.ts:101` lists only `<companyId>/` prefixes; legacy
+ audit archives at `audit-logs/<companyId>/...` (and prefixes of deleted companies)
+ are never copied. Safe today (readers fall back), but decommissioning the legacy
+ bucket on the script's "copied everything" claim would permanently destroy
+ pre-migration audit archives. Fix the docblock now; extend the script (or migrate
+ `audit-logs/` explicitly) before fallback removal.
+- **H2 — deploy order.** Companies created after 2025-08-27 have no bucket until
+ `20260917163108` applies. App code writes company-bucket-only → apply the migration
+ before (or atomically with) the app deploy, else uploads for those tenants fail
+ loudly ("Bucket not found") until it lands.
+- **M1 — 50MB cap vs older legacy files.** Legacy `private` was uncapped until
+ 2026-07-15; company buckets are capped at 52428800. Oversized legacy objects would
+ fail to copy (loud, script exits 1) and stay pinned to legacy. One-time check of
+ legacy object sizes before the prod copy run; raise/drop the cap if any exceed it.
+- **M2 — backup listing silently incomplete (pre-existing).** `listBucketFilesRecursive`
+ (`packages/jobs/src/inngest/functions/tasks/company-export.ts:472-496`) swallows list
+ errors and does no pagination (>1000 direct children in a folder are dropped) while
+ reporting success. Backup is the safety net for this exact migration — worth fixing
+ alongside.
+- **M3 — restore overwrite deletes before re-copy** (`company-backup.ts:604-614`):
+ duplicate → `remove` live object → retry copy; a failed retry leaves the live object
+ gone (backup copy survives). Narrow, user-initiated, pre-existing.
+- **M4 — `.move()` is company-bucket-only** (`x+/quote+/$quoteId.drag.tsx:309-320`,
+ `x+/sales-rfq+/$rfqId.drag.tsx:165`): a file present in both buckets moves only the
+ company copy; the stale legacy copy is resurrected forever by the list union and no
+ delete ever targets the old legacy path.
+- Low: several `removeCompanyPrivateObjects` callers ignore returned `errors`
+ (production.service.ts:6824/6891, drag routes, model-thumbnail.ts:132) — a failed
+ legacy-side delete leaves a resurrectable copy silently. Files uploaded to legacy by
+ old pods during the deploy window stay legacy-only — re-run the copy script before
+ removing fallback.
+
+## Verified safe (with evidence)
+
+- **RLS**: "Company bucket access" (`20250827181005_company-bucket-rls.sql:95-103`)
+ scopes `bucket_id = ANY(get_companies_with_employee_role())`; legacy policy prefix-
+ scopes `foldername(name)[1]`. `FOR ALL ... USING` doubles as WITH CHECK — employee of
+ A cannot touch B's bucket or B's legacy prefix via a user JWT.
+- **Trigger**: SECURITY DEFINER with pinned `search_path`, `NEW.id` used only as a
+ parameterized value (no dynamic SQL → no injection), `RETURNS TRIGGER` so not
+ directly invocable; bucket creation bounded 1:1 with company inserts.
+- **Preview routes**: bucket allowlist (own bucket / legacy / public / temp-staging) +
+ `ownsPath` + fallback reuses the same checked path; naming another company's bucket
+ → 403. URL-decoding tricks don't bypass (decode happens before matching).
+- **Share route**: companyId from the share record, prefix guard + 3 further
+ job/customer checks + 10/min rate limit.
+- **Uploads / MCP**: `companyId` injected from auth, keys always
+ `${companyId}/...`-prefixed, signed upload URLs target the caller's own bucket only.
+- **Copy script**: zero delete calls; `copy()` without upsert → existing destination
+ 409s and is counted `skipped` (idempotent, can never clobber newer data); correct
+ 1000-page offset pagination + folder recursion.
+- **No missed readers/writers**: repo-wide grep leaves exactly one `.from("private")` —
+ the import-csv read *fallback*. Every traced reader has company→legacy fallback; all
+ private deletes go through the dual-bucket helper; `cleanup.ts` never prunes a
+ referenced object without a durable copy in either private bucket.
+- **Backup/restore**: export unions both buckets (company copy wins); restore writes
+ to the company bucket, which every reader checks first.
diff --git a/.ai/research/company-private-buckets.md b/.ai/research/company-private-buckets.md
new file mode 100644
index 0000000000..b2f01698e3
--- /dev/null
+++ b/.ai/research/company-private-buckets.md
@@ -0,0 +1,99 @@
+# Research: Company Private Buckets (migration off shared `private` bucket)
+
+Worktree: `carbon-feat-supabase-bucket-migration` (branch feat/supabase-bucket-migration, at main = e0f8265ea4).
+Reference: PR crbnos/carbon#682 (branch company-private-buckets, 89 files, +2377/-550).
+
+## 1. Current state in this worktree
+
+### 1.1 Migration 20250827181005_company-bucket-rls.sql — EXISTS
+- `packages/database/supabase/migrations/20250827181005_company-bucket-rls.sql:1-6` — backfills one bucket per existing company: `INSERT INTO storage.buckets (id, name, public) SELECT id, id, false FROM company`.
+- Drops ~70 legacy per-feature storage.objects policies (lines 9-79), then creates exactly two policies:
+ - `"Shared Private Bucket"` (lines 82-91): `bucket_id = 'private' AND (storage.foldername(name))[1] = ANY(get_companies_with_employee_role())` — legacy bucket stays readable, companyId must be first folder.
+ - `"Company bucket access"` (lines 95-102): `bucket_id = ANY(get_companies_with_employee_role())` — full access to your company's bucket.
+- **No auto-creation for NEW companies.** `storage.buckets` inserts exist only in migrations (buckets, feedback-bucket, company-bucket-rls, onboarding-and-backups, temp-staging-bucket — verified by `rg 'storage\.buckets'`). The three `AFTER INSERT ON "company"` triggers (20240908100622_terms.sql:25, 20241127142822_sales-settings.sql:33, 20260109134902_search-refactor.sql:187) create terms/settings/search rows; none of those files mention buckets. No TS code calls `createBucket` (rg `createBucket` over apps/packages/scripts: zero hits). A company created after 2025-08-27 has RLS ready but **no bucket**.
+
+### 1.2 Other buckets in later migrations
+- `20260617100002_onboarding-and-backups.sql:61-62` — shared `company-templates` bucket (service-role-only backup templates; comment at lines 55-60 explicitly says a per-company bucket can't serve these).
+- `20260715150742_temp-staging-bucket.sql:28-30` — `temp-staging` bucket (2.5 GB cap) for raw CAD; line 32 caps `private` at 50 MB; policies at lines 43-64 scope `temp-staging` by `${companyId}/models/...` key layout (line 37 comment).
+
+### 1.3 Legacy `private` bucket usage inventory (`rg 'from\("private"\)' --type ts`; no single-quote variants exist)
+Files / call-site occurrences:
+- apps/erp: **76 files / 142 occurrences**
+- apps/mes: **4 files / 7 occurrences**
+- packages/jobs: **7 files / 12 occurrences**
+- packages/ee: 1 file / 3 (paperless-parts/lib/lib.ts:843,932,2006 — uploads)
+- packages/lib: 1 file / 1 (slack.server.ts:118 — createSignedUrl)
+- packages/database edge functions: 1 file / 1 (functions/import-csv/index.ts:971 — download)
+- contrib/building: 2, scripts/model-upload.ts: 1 (examples/tooling)
+
+Operation mix in apps/erp (same-line + next-line method match): upload ~71, list ~20, remove ~18, download ~12, createSignedUrl ~10, copy 2, move 2.
+apps/mes: list x4 (services/operations.service.ts), upload x3 (components/Suggestion.tsx, JobOperation/components/Step.tsx, JobOperation/components/MaintenanceDispatch.tsx).
+packages/jobs: model-thumbnail.ts:96,129 (upload/remove), model-optimize.ts:192,209 (list/createSignedUploadUrl), assembly-plan.ts:236,260,294, assembly-convert.ts:176,179 (createSignedUploadUrl), print-job/renderers.tsx:205 (download), extraction/extract-document.ts:67 (download), scheduled/cleanup.ts:425 (list/info).
+packages/documents has NO direct storage calls (rg: zero hits) — attachments are resolved by callers (finalize routes / jobs) before emailing.
+
+### 1.4 Preview/download routes
+- `apps/erp/app/routes/file+/preview+/$bucket.$.tsx` and `apps/mes/app/routes/file+/preview+/$bucket.$.tsx` are near-identical: `requirePermissions` → ownership check → service-role download from `params.bucket`.
+- Ownership check is already hardened (erp $bucket.$.tsx:81-87): `decodedPath.startsWith(`${companyId}/`) || decodedPath.includes(`/${companyId}/`)` — segment-bounded, not `.includes(companyId)`. Same in MES.
+- Both routes have newer zstd handling the PR base lacks (erp $bucket.$.tsx:64-77, 123-137 — `.zst` decompress streaming).
+- Path helpers: `path.to.file.previewFile(path)` → `/file/preview/${path}` (erp path.ts:1035, mes path.ts:105); `path.to.file.preview(bucket, path)` (erp path.ts:1033-1034).
+- `getPrivateUrl(path)` → `getDatasetAssetUrl(path) ?? \`/file/preview/private/${path}\`` in BOTH apps (erp app/utils/path.ts:2365-2369, mes app/utils/path.ts:227-231) — hardcodes bucket `private`; also has demo-template dataset-asset branch the PR base lacked.
+- Share route `apps/erp/app/routes/share+/customer.$id.$.tsx:82`: `let bucket = "private"; // TODO: refactor to use companyId when we separate the storage buckets`.
+
+### 1.5 Signed URL / email attachment flows
+- Finalize/send routes mint 3600s signed URLs on `private` and pass them as email attachment `path`: e.g. purchasing-rfq $rfqId.finalize.tsx:244-245, 265-266; also shared.server.ts:191,265,342,474 (generated PDF upload/copy flows), purchase-order finalize, quote finalize, supplier-quote send, sales-invoice post (all in the 76-file list).
+- `packages/jobs/src/inngest/functions/notifications/send-email.ts` was REWRITTEN on main (commit 9fe6981ea8 "Send app email over SMTP; drop Resend"): now imports `sendEmail` from `@carbon/lib/email.server` and just forwards `payload.attachments` (send-email.ts:1-4, 40-49). No Resend, no per-company integration lookup.
+
+### 1.6 Edge functions
+- Only `packages/database/supabase/functions/import-csv/index.ts:971` touches `private` (`client.storage.from("private").download(filePath)`).
+
+### 1.7 @carbon/utils
+- No file-storage helpers exist. `packages/utils/src/storage-rules.ts` is warehouse storage-rule evaluation, unrelated. None of the PR's helper names (`getCompanyPrivateBucket` etc.) exist anywhere in this worktree (rg: zero hits).
+
+## 2. PR #682 design summary
+
+89 changed files, +2377/-550. Feature commits eab8f4197→5a7c54d8c, then "clean break" refactor 8c0ad2d81 ("remove storage fallback and implement clean break"), migration-script rework 0b9f933a1, signed-URL fix 925a2040c, plus many main merges.
+
+### 2.1 Shared contracts — new `packages/utils/src/storage.ts` (+ storage.test.ts)
+- `normalizeStorageSegment(value)` — trim, collapse `\`/`/` runs to `-`, strip leading/trailing `-`/`/`.
+- `getCompanyPrivateBucket(companyId)` = `normalizeStorageSegment(companyId)` — bucket id IS the companyId.
+- `buildCompanyPrivateStorageTarget({companyId, logicalFolder, fileName, entityId?})` → `{physicalBucket, logicalFolder, objectPath}` where `objectPath = [physicalBucket, logicalFolder, entityId?, fileName].join("/")` — **companyId stays the FIRST path segment inside the company bucket** (paths unchanged vs legacy, only the bucket differs; that's what makes copy-with-same-key migration work).
+- `hasCompanyPrivateObjectPathPrefix(companyId, objectPath)` — `objectPath.startsWith(`${bucket}/`)`.
+- `downloadCompanyPrivateObject` / `listCompanyPrivateObjects` / `createCompanyPrivateSignedUrl` — dependency-injected callbacks (`downloadObject(physicalBucket, objectPath)` etc.), returning `{data, errors: PrivateBucketAttemptError[], physicalBucket}`.
+
+### 2.2 Legacy fallback: REMOVED in final state
+- Final `downloadCompanyPrivateObject` tries ONLY the company bucket — one attempt, errors collected, no retry on `private` (`requestedBucket` param is accepted but unused). The PR description still advertises fallback, but commit 8c0ad2d81 switched to a clean break; correctness then depends entirely on running the copy script first.
+
+### 2.3 Preview/share route hardening
+- ERP/MES `$bucket.$.tsx`: adds `if (bucket !== getCompanyPrivateBucket(companyId)) return 403` AND `hasCompanyPrivateObjectPathPrefix(companyId, decodedPath)` (replacing the old loose `decodedPath.includes(companyId)` of ITS base — this worktree already has a stronger segment check).
+- `share+/customer.$id.$.tsx`: removes the `bucket = "private"` TODO; parses `[pathCompanyId, logicalFolder, operationId, fileName]` from the path, requires `pathCompanyId === customerPortal.companyId` + prefix check, downloads via `downloadCompanyPrivateObject` with `getCompanyPrivateBucket(customerPortal.companyId)`.
+- `path.to.file.previewFile` gains an overloaded `(bucket, path)` form; `getPrivateUrl` becomes overloaded — `(bucket, objectPath)` preferred, single-arg legacy form derives the bucket from the path's first segment (`getRequestedPrivateBucketFromPath`), marked `@deprecated`.
+
+### 2.4 Signed-URL fix (925a2040c)
+- Touches purchasing-rfq finalize, supplier-quote send, send-email.ts, storage.test.ts, mcp tool-metadata.json. Replaces bare `serviceRole.storage.from("private").createSignedUrl(path, 3600)` with `createCompanyPrivateSignedUrl({...})`, logging each `PrivateBucketAttemptError` and passing `signedUrlResult.signedUrl` to attachments; send-email normalizes attachments to `{filename, path}` (URL) vs `{filename, content, encoding: "base64"}` and adds a per-company Resend/SMTP provider switch (now moot — see 2.7).
+
+### 2.5 Migration script `scripts/migrate-private-buckets.ts` (new, 106 lines)
+- For each `company.id`: `supabase.storage.createBucket(companyId, {public:false, fileSizeLimit: 52428800})` tolerating "already exists"; then recursively `list` legacy `private` under prefix `companyId` and `copy(itemPath, itemPath, {destinationBucket: companyId})` — same key, new bucket. Idempotent: 409/"already exists" copy errors counted as skipped. Copy-only (two-pass design per commit 0b9f933a1) — legacy objects are NOT deleted.
+
+### 2.6 SQL / bucket creation in the PR
+- The PR contains **zero SQL migration changes** (grep 'supabase/migrations' over the diff: 0). RLS relies on 20250827181005 already being on main.
+- Bucket creation exists ONLY in the migration script (diff line: `supabase.storage.createBucket(companyId, ...)`); **no code path creates a bucket when a new company is created** — same gap as this worktree.
+
+### 2.7 Merge-conflict risk vs this worktree's main — HIGH
+- `e0f8265ea4` (2026-09-16, MCP file-upload tools): adds new `from("private")` sites the PR never saw — `createSignedUploadUrl` wrappers in documents/items/production/purchasing/sales service files + `buildDocumentUploadPath` (documents.models.ts:54, path shape `${companyId}/${folder}/${entityId}/${sanitizedName}` in `private`). PR touches 4 of those same service files.
+- `9fe6981ea8` rewrote send-email.ts to SMTP-only via `@carbon/lib/email.server` — PR's send-email rewrite (Resend/SMTP provider switch, company integration lookup) conflicts wholesale and is partly obsolete.
+- Preview routes: worktree added zstd streaming + the segment-bounded ownsPath check; PR rewrites the same lines from an older base.
+- `getPrivateUrl` in both apps now has the dataset-asset branch (erp path.ts:2365) the PR's rewrite drops.
+- temp-staging bucket (20260715150742) and its `private` 50 MB cap post-date the PR's design.
+- PR also carries unrelated scope from its long life: setup.sh/dev-CLI commit f1c3ac240, swagger-schema pruning, "delete rolloute AI Agent" (729932af9).
+
+## 3. Open design questions
+
+- Bucket provisioning for NEW companies: DB trigger on `company` insert (SQL can insert into storage.buckets, as 20250827181005 proves) vs app-level `createBucket` in the company-create flow vs lazy-create-on-first-write? Nothing exists today in either the worktree or the PR.
+- Clean break vs read fallback: PR ended with no legacy fallback, so cutover requires the copy script to complete first; do we want a fallback window (read company bucket then `private`) to deploy code before/without downtime?
+- Keep companyId as the first object-path segment inside the company bucket (PR choice, enables same-key copy + reuses `${companyId}/...` RLS/path checks) — or strip it now that the bucket itself scopes tenancy (would break same-key migration and every `buildDocumentUploadPath`-style helper)?
+- Legacy `private` bucket end-of-life: script copies but never deletes; who deletes, when, and does the `"Shared Private Bucket"` RLS policy get dropped?
+- temp-staging + `company-templates` interplay: temp-staging RLS keys on `${companyId}/models/...` inside a shared bucket — migrate CAD staging to company buckets too (2.5 GB cap is per-bucket!) or leave it shared? Per-company buckets inherit which file_size_limit (script hardcodes 50 MB)?
+- New MCP `createSignedUploadUrl` flows (e0f8265ea4) mint upload URLs on `private` via authenticated client relying on the `"Shared Private Bucket"` RLS — porting them to company buckets needs the `"Company bucket access"` policy to cover signed-upload mints and the wrappers rewritten.
+- Non-app consumers: packages/jobs (7 files), edge function import-csv, packages/ee paperless-parts, packages/lib slack — several receive only a path, not a companyId; is companyId always recoverable (first path segment) or must event payloads change?
+- `getCompanyPrivateBucket` = raw companyId: any risk of collision with reserved bucket ids (`private`, `public`, `avatars`, `models`, `temp-staging`, `company-templates`, `feedback`) or Supabase bucket-name constraints for existing companyIds?
+- Backups/exports (20260617100002 onboarding-and-backups): do company backup/restore flows enumerate buckets, and does per-company bucketing change restore targets?
diff --git a/.ai/specs/2026-09-17-company-private-buckets.md b/.ai/specs/2026-09-17-company-private-buckets.md
new file mode 100644
index 0000000000..1292228e0b
--- /dev/null
+++ b/.ai/specs/2026-09-17-company-private-buckets.md
@@ -0,0 +1,125 @@
+# Company-Specific Private Storage Buckets
+
+**Status:** Draft — awaiting approval
+**Date:** 2026-09-17
+**Research:** [.ai/research/company-private-buckets.md](../research/company-private-buckets.md)
+**Prior art:** PR crbnos/carbon#682 (reference implementation; NOT merged — this is a clean re-implementation on current main)
+
+## Problem
+
+All private files (documents, CAD models, generated PDFs, MES attachments) live in one shared `private` bucket, with tenancy enforced only by a `companyId/` path-prefix RLS check. One sloppy policy leaks every tenant's files; per-company export/deletion means filtering a giant shared bucket; per-bucket controls (size limits) can't differ per tenant.
+
+Per-company buckets already exist in the schema — `20250827181005_company-bucket-rls.sql` backfilled one bucket per company (bucket id = companyId) with RLS (`"Company bucket access"`) — but **no application code uses them**, and **companies created after that migration get no bucket at all**.
+
+## Goals
+
+1. Every private-file read/write in ERP, MES, `@carbon/jobs`, `@carbon/ee`, `@carbon/lib`, and edge functions targets the company bucket (`storage.from(companyId)`), not `storage.from("private")`.
+2. Legacy files still in `private` keep working during a fallback window (reads/lists/signed URLs fall back).
+3. New companies automatically get a bucket (DB trigger).
+4. A one-off, idempotent copy script migrates legacy objects into company buckets.
+5. Preview/share routes are hardened: requested bucket must equal the caller's company bucket.
+
+## Non-Goals
+
+- Deleting legacy objects or dropping the `"Shared Private Bucket"` RLS policy — **follow-up ~1 week after prod verification** (user decision).
+- Removing the fallback code — same follow-up.
+- `temp-staging` (CAD staging) and `company-templates` (backups) buckets — separate designs, untouched.
+- `public`, `avatars`, `feedback` buckets — untouched.
+- Re-keying object paths (paths keep the `companyId/` first segment — see decisions).
+
+## Design
+
+### 1. Shared storage contract — new `packages/utils/src/storage.ts`
+
+Adopt PR #682's contract (it's sound; re-implement, don't cherry-pick, since the PR conflicts heavily with current main):
+
+- `normalizeStorageSegment(value)` — trim, collapse `\`/`/` runs to `-`, strip leading/trailing separators.
+- `getCompanyPrivateBucket(companyId)` → normalized companyId. The bucket id IS the companyId.
+- `buildCompanyPrivateStorageTarget({companyId, logicalFolder, entityId?, fileName})` → `{physicalBucket, objectPath}` where `objectPath = companyId/logicalFolder[/entityId]/fileName` — **identical to today's legacy paths**, only the bucket differs.
+- `hasCompanyPrivateObjectPathPrefix(companyId, objectPath)`.
+- Fallback-aware, dependency-injected read helpers (unlike PR #682's final clean-break versions, ours DO fall back):
+ - `downloadCompanyPrivateObject` — try company bucket, then `private`; return `{data, physicalBucket, errors[]}`.
+ - `createCompanyPrivateSignedUrl` — same two-step.
+ - `listCompanyPrivateObjects` — list BOTH buckets, union de-duplicated by name, company bucket wins.
+- `LEGACY_PRIVATE_BUCKET = "private"` named constant; fallback lives ONLY in these helpers so the follow-up removal is one file.
+
+Unit tests in `packages/utils/src/storage.test.ts` (path shapes, normalization, fallback order, list de-dup).
+
+### 2. Bucket provisioning for new companies — new migration
+
+`pnpm db:migrate:new company-bucket-provisioning`:
+
+- `AFTER INSERT ON "company"` trigger (same pattern as the existing terms/settings/search company-insert triggers) inserting `(id, id, false, 52428800)` into `storage.buckets` with `ON CONFLICT (id) DO NOTHING`.
+- Backfill in the same migration for any company created since 2025-08-27 that lacks a bucket (`INSERT ... SELECT ... ON CONFLICT DO NOTHING`), with the same 50 MB `file_size_limit` (matching the cap `20260715150742` put on `private`); also `UPDATE storage.buckets SET file_size_limit = 52428800 WHERE id IN (SELECT id FROM company)` to normalize the 2025 backfill rows that got NULL.
+- No RLS changes — `"Company bucket access"` from `20250827181005` already covers company buckets (including signed-upload mints, which run as the authenticated user against `storage.objects` INSERT).
+
+### 3. Call-site migration (the bulk)
+
+Every `storage.from("private")` call site (76 files ERP, 4 MES, 7 jobs, 1 ee, 1 lib, 1 edge function — see research §1.3) changes as follows:
+
+| Operation | New behavior |
+|---|---|
+| upload / `createSignedUploadUrl` / copy / move (writes) | company bucket only, via `getCompanyPrivateBucket(companyId)`; no fallback |
+| download / `createSignedUrl` (reads) | via fallback helpers |
+| list | via union helper |
+| remove | attempt on BOTH buckets, ignore not-found (a file can be in either during the window) |
+
+Where a consumer has only a path and no companyId in scope (some jobs/edge-function payloads), derive it from the path's first segment — valid because paths keep the `companyId/` prefix. Prefer passing companyId explicitly where the payload already carries it.
+
+Specific flows called out:
+
+- **Preview routes** (`apps/erp/app/routes/file+/preview+/$bucket.$.tsx`, MES twin): keep current zstd streaming + segment-bounded ownership check; add `bucket === getCompanyPrivateBucket(companyId) || bucket === "private"` gate (403 otherwise) and route downloads through the fallback helper. Legacy `/file/preview/private/...` URLs keep working.
+- **`getPrivateUrl`** (both apps): keep the dataset-asset branch; emit `/file/preview/{companyBucket}/{path}` for new URLs.
+- **Share route** `share+/customer.$id.$.tsx`: resolve the TODO — bucket from `customerPortal.companyId`, require path companyId match, download via fallback helper.
+- **Generated documents / email attachments** (finalize/send routes, `shared.server.ts`, `send-email.ts`): signed URLs via `createCompanyPrivateSignedUrl`; keep the current SMTP-only `send-email.ts` (do NOT port PR #682's obsolete Resend/provider switch).
+- **MCP file-upload tools** (`e0f8265ea4`: `buildDocumentUploadPath` + `createSignedUploadUrl` wrappers in documents/items/production/purchasing/sales services): mint upload URLs on the company bucket.
+- **Edge function** `import-csv/index.ts:971`: download via fallback (inline two-step; edge runtime can't import `@carbon/utils` — mirror the helper in `functions/lib/` if cleaner).
+
+### 4. Copy script — `scripts/migrate-private-buckets.ts`
+
+Same shape as PR #682's final script: per company, `createBucket` (tolerate exists), recursively list `private` under the `companyId/` prefix, `copy(key, key, {destinationBucket: companyId})`, count 409s as skipped. Copy-only — never deletes. Idempotent, safe to re-run. Run against prod after deploy; legacy cleanup happens ~a week later as a separate task.
+
+### 5. Rollout sequence
+
+1. Merge + deploy (migration adds trigger/backfill; code writes new files to company buckets, reads fall back to `private`). Zero downtime, no ordering constraint.
+2. Run the copy script.
+3. ~1 week verification, then follow-up PR: remove fallback branches, delete legacy objects, drop `"Shared Private Bucket"` policy.
+
+## Design Decisions
+
+| # | Decision | Choice | Rationale |
+|---|---|---|---|
+| 1 | New-company bucket provisioning | DB `AFTER INSERT` trigger + backfill migration | **User-decided.** Covers all creation paths atomically; matches existing company-insert triggers |
+| 2 | Legacy compatibility | Read-fallback + copy script; cleanup deferred | **User-decided.** Zero-downtime; PR #682's clean break requires script-before-deploy sequencing |
+| 3 | Object path shape | Keep `companyId/` as first segment inside company bucket | **User-decided.** Stored DB paths stay valid; copy is same-key; consumers without companyId can derive it from the path |
+| 4 | Legacy EOL | Out of scope; ~1 week post-verification follow-up | **User-decided** ("clean it up after a week or so when we have verified all works good") |
+| 5 | List during fallback window | Union of both buckets, de-dup by name, company bucket wins | Documents UI must show legacy files until the copy script runs |
+| 6 | Remove during fallback window | Delete from both buckets, ignore missing | A file exists in exactly one (or both post-copy); partial delete would resurrect files |
+| 7 | Bucket `file_size_limit` | 52428800 (50 MB), same as `private` | Behavior-preserving; per-company overrides possible later |
+| 8 | `temp-staging` / `company-templates` | Untouched | Separate designs (2.5 GB CAD staging; service-role backup templates that a comment in `20260617100002` explicitly says can't be per-company) |
+| 9 | send-email | Keep current SMTP-only implementation | PR #682's Resend/provider switch predates `9fe6981ea8`; porting it would regress main |
+| 10 | Fallback location | Only inside the `packages/utils/src/storage.ts` helpers | Follow-up removal is a one-file change, not another 90-file sweep |
+| 11 | Bucket id collisions | None possible in practice; trigger uses `ON CONFLICT DO NOTHING` | companyIds are generated ids; reserved bucket names (`private`, `public`, `avatars`, `models`, `feedback`, `temp-staging`, `company-templates`) don't collide with id-space |
+
+## Acceptance Criteria
+
+1. Upload a document on a fresh dev company → object lands in bucket `<companyId>` at path `<companyId>/...`; no new objects appear in `private`.
+2. A file seeded into `private` (legacy) still previews, downloads, and appears in the Documents list; its email-attachment signed URL resolves.
+3. Creating a new company (onboarding or `pnpm db:seed:dev`) produces a `storage.buckets` row for it; the first upload succeeds without any manual step.
+4. Preview route returns 403 for a bucket that is neither the caller's company bucket, `private`, nor a shared bucket it already legitimately serves (`public`, `temp-staging` — discovered during execution: model raw downloads and DocumentPreview flow through this route); returns 403 for a path outside the caller's company prefix.
+5. Customer share route serves files from the portal company's bucket with legacy fallback.
+6. MCP file-upload tool mints a signed upload URL targeting the company bucket, and the uploaded file previews.
+7. `scripts/migrate-private-buckets.ts` run twice reports the second run as all-skipped (idempotent).
+8. `rg 'from\("private"\)'` over `apps/`, `packages/` returns only the `LEGACY_PRIVATE_BUCKET` constant definition/fallback helper internals (and contrib/examples).
+9. `pnpm exec turbo run typecheck --filter=@carbon/utils --filter=erp --filter=mes --filter=@carbon/jobs` passes; `packages/utils/src/storage.test.ts` passes.
+
+## Open Questions (resolved — audit trail)
+
+- [x] How do new companies get a bucket? — **Answer:** DB trigger on company insert (user chose recommended option).
+- [x] Fallback vs clean break? — **Answer:** Fallback + copy script; fallback removed in a follow-up after verification (user chose recommended option).
+- [x] Keep `companyId/` path prefix inside company buckets? — **Answer:** Keep it (user chose recommended option).
+- [x] Legacy bucket EOL? — **Answer:** Cleanup deferred ~1 week after prod verification (user: "we will clean it up after a week or so when we have verified all works good now").
+
+## Changelog
+
+- 2026-09-17 — Spec written after interview; 4 user decisions + 7 codebase-settled decisions recorded.
diff --git a/.ai/specs/2026-09-18-restore-readable-ids-and-model-paths.md b/.ai/specs/2026-09-18-restore-readable-ids-and-model-paths.md
new file mode 100644
index 0000000000..25a66b7cf9
--- /dev/null
+++ b/.ai/specs/2026-09-18-restore-readable-ids-and-model-paths.md
@@ -0,0 +1,182 @@
+# Cross-company restore: preserve readable ids, rewrite model artifact paths
+
+**Status:** Approved (design)
+**Date:** 2026-09-18
+**Branch:** `feat/supabase-bucket-migration` (user's explicit choice)
+
+## Summary / Problem
+
+A cross-company restore into a fresh company silently produces a broken company.
+Verified on the local stack: company `D9NBZmY2FhSSeFCxWkdahi` ("alone"), restored
+from source company `cvnu9ldl6de9mjn9edvg`.
+
+Two independent defects, both invisible on a same-company restore (where `remap`
+is a no-op) and both only reachable cross-company — which is why prior manual
+testing passed.
+
+1. **Items pages are empty.** 1096 `item` rows and 860 `part` rows restored fine,
+ but the `parts` view returns 0. The view inner-joins `part.id =
+ item."readableId"`; restore had replaced every `part.id` with a 21-char nanoid.
+2. **Assemblies will not load.** `modelUpload` path columns still point at the
+ SOURCE company (`cvnu9ldl6de9mjn9edvg/models/...`). The files were copied to the
+ target company's prefix correctly; only the DB columns are stale.
+
+## Goals
+
+- A cross-company restore preserves human-authored readable ids on item-child tables.
+- A cross-company restore rewrites every `modelUpload` storage-path column.
+- A future table or path column that needs this treatment fails a test rather than
+ silently producing a broken restore.
+
+## Non-goals
+
+- Repairing already-restored companies (no data-migration script). The user can
+ re-restore after the fix.
+- Changing the additive reseed/import path's collision handling (see Decision 3).
+- Revisiting the August composite-PK fix — it is correct and stays.
+
+## Root causes
+
+### Bug 1 — readable ids rewritten (introduced 2026-08-31, `2a19048def`)
+
+`2a19048def` correctly removed the `hasId` (PK exactly `id`) gate from
+`buildIdMaps` so that ~25 composite-PK tables get fresh ids. Five of those tables
+back their `id` with a global `UNIQUE (id)`, so leaving source ids in place made a
+cross-company restore collide with the source company's still-live rows.
+
+But five OTHER tables have PK `(id, companyId)` where `id` is not an identifier at
+all — it is a human-authored readable key that foreign-keys (by value, with no FK
+constraint) to `item."readableId"`:
+
+| table | example id |
+|---|---|
+| `part` | `ADCS-001` |
+| `material` | `MAT-AL7075-PLT` |
+| `consumable` | `CN-GREASE-001` |
+| `service` | `SVC-TVT` |
+| `tool` | `TL-PROBE-VNA` |
+
+Verified in healthy company `dame5i2iq0gg29pkj26g`: all five join 1:1 to
+`item."readableId"` (22/22, 6/6, 2/2, 1/1, 2/2). In the restored company all five
+hold nanoids and join zero rows.
+
+**Structural separation that makes the fix safe:** the five tables the August fix
+targeted (`changeOrderRequiredAction`, `balloon`, `inspectionDocument`,
+`inspectionFeature`, `demandProjection`) all carry a global `UNIQUE (id)`. The five
+readable-id tables carry ONLY the composite PK — verified via `pg_index`. So
+excluding the readable-id five cannot reintroduce the collision the August fix
+solved: they are disjoint sets, separated by a real schema property.
+
+### Bug 2 — model artifact paths not rewritten (introduced 2026-07-20, `1cce52f44a`)
+
+That commit changed `STORAGE_PATH_COLUMNS` from `{modelPath, thumbnailPath}` to
+`{thumbnailPath}`, with the rationale that raw models had moved to the transient
+`temp-staging` bucket and were therefore never carried by a backup. The same commit
+added `glbPath` and `graphPath` columns to `modelUpload` and did not add them to the
+set.
+
+**The rationale is stale.** `company-export.ts:246` builds the asset list by
+LISTING the private bucket recursively under `{companyId}/`, not by reading path
+columns — so everything under `{companyId}/models/` is backed up, raw CAD included.
+
+Measured on the restored company (8 `modelUpload` rows):
+
+| column | rows still pointing at source company |
+|---|---|
+| `thumbnailPath` | 0 (in the set — works) |
+| `modelPath` | 8 |
+| `glbPath` | 4 |
+| `graphPath` | 4 |
+
+## Design
+
+### Change 1 — `READABLE_ID_TABLES` exclusion in `buildIdMaps`
+
+Add to `packages/jobs/src/inngest/functions/tasks/company-backup.ts`, beside
+`STORAGE_PATH_COLUMNS`:
+
+```ts
+export const READABLE_ID_TABLES = new Set([
+ "part", "material", "consumable", "service", "tool"
+]);
+```
+
+`buildIdMaps` (`company-backup.transforms.ts`) skips these tables, minting no map,
+so `buildRowTransforms` copies `id` verbatim (it already keeps ids for tables absent
+from `idMaps` — covered by the existing "does NOT crash on an int/serial-id table
+absent from idMaps" test).
+
+Why an explicit list rather than a derived rule: a schema-derived predicate was
+tested and rejected. `composite PK + text id + no global UNIQUE(id)` matches **65**
+tables including `workflow`, `kanban`, `inventoryCount`, `stockTransfer` — all of
+which legitimately need remapping. No structural marker distinguishes the five
+(no `itemId` column, no FK on `id`).
+
+### Change 2 — restore `modelPath` and add the new artifact columns
+
+```ts
+export const STORAGE_PATH_COLUMNS = new Set([
+ "thumbnailPath", "modelPath", "glbPath", "graphPath"
+]);
+```
+
+Replaces the stale "raw models are not backed up" comment with the listing-based
+reality.
+
+### Change 3 — regression guards (pure, no DB)
+
+In `company-backup.closure.test.ts`:
+
+1. **Readable-id preservation:** `buildIdMaps` over a fixture including `part` and a
+ normal table asserts `part` gets no map and the normal table does; a
+ `buildRowTransforms` case asserts `part.id` survives verbatim under `remap=true`.
+2. **Disjointness invariant:** assert `READABLE_ID_TABLES` contains no table that
+ the August fix requires remapping (the `UNIQUE (id)` five), encoded as a literal
+ list — so a future edit that adds one to both fails.
+3. **Path-column coverage:** assert `STORAGE_PATH_COLUMNS` contains every known
+ `modelUpload` artifact column, from a literal list of that table's path columns.
+ A newly added artifact column must be added to both lists, and the test names
+ what is missing.
+
+The guards are fixture-based, matching the existing suite (no DB access).
+
+## Design Decisions
+
+| Decision | Choice | Rationale |
+|---|---|---|
+| How to identify readable-id tables | Explicit `READABLE_ID_TABLES` constant | Derived rule tested and rejected — matches 65 tables including ones that must remap. User chose explicit. |
+| Behaviour on additive reseed/import | Skip in both paths | A readable id must never be rewritten regardless of path. Restore is wipe-first so it is safe; on reseed a same-named part would hit the composite PK and fail loudly rather than corrupt data. User chose this. |
+| `modelPath` in `STORAGE_PATH_COLUMNS` | Include, with `glbPath`/`graphPath` | Backup enumerates the bucket by listing, so raw models ARE carried; 8 rows measured stale. User chose this. |
+| Repair existing restored companies | Out of scope | Re-restoring after the fix is simpler and safer than a one-off data migration. |
+| Guard style | Pure fixture tests | Existing suite is pure; a schema-reading test would need a live DB in CI. |
+
+## Acceptance criteria
+
+1. `buildIdMaps` over a fixture containing `part` returns no map for `part`, and
+ returns a map for a normal composite-PK table (e.g. `workflow`).
+2. `buildRowTransforms` with `remap=true` leaves `part.id = "ADCS-001"` unchanged
+ while re-stamping `companyId`.
+3. `STORAGE_PATH_COLUMNS` contains `thumbnailPath`, `modelPath`, `glbPath`, `graphPath`.
+4. A test fails if a `READABLE_ID_TABLES` entry also appears in the `UNIQUE (id)`
+ remap-required list.
+5. A test fails if a known `modelUpload` artifact path column is missing from
+ `STORAGE_PATH_COLUMNS`, naming the missing column.
+6. `pnpm --filter @carbon/jobs test` and `typecheck` pass.
+7. Manual (user): re-restore into a fresh company; Parts list shows rows and an
+ assembly loads its model.
+
+## Open Questions
+
+- [x] How should `buildIdMaps` identify readable-id tables? — **Answer:** explicit
+ `READABLE_ID_TABLES` constant. A derived schema rule was tested and matches 65
+ tables including ones that must keep remapping.
+- [x] Should the five be skipped on the additive import path too? — **Answer:** yes,
+ skip in both. Restore is wipe-first; on reseed the composite PK fails loudly
+ rather than corrupting. A readable id must never be rewritten.
+- [x] Should `modelPath` rejoin `STORAGE_PATH_COLUMNS`? — **Answer:** yes, with
+ `glbPath`/`graphPath`. The "not backed up" rationale is contradicted by the
+ listing-based backup, and 8 rows are provably stale.
+
+## Changelog
+
+- 2026-09-18 — Initial spec, written after resolving three design questions with the user.
diff --git a/.claude/rules/company-backup-restore.md b/.claude/rules/company-backup-restore.md
index 8de8e81949..0bc00092e7 100644
--- a/.claude/rules/company-backup-restore.md
+++ b/.claude/rules/company-backup-restore.md
@@ -133,7 +133,14 @@ both use it; `company-backup.ts` re-exports it), exported to app code as
`("id","companyId")`) and `demandProjection` (PK
`("itemId","locationId","periodId")`). Leaving their source ids in place made a
cross-company restore collide with the SOURCE company's still-live rows and roll
- the whole thing back. Serial/int ids are left alone. A
+ the whole thing back. Five OTHER composite-PK tables are excluded BY NAME
+ (`READABLE_ID_TABLES`: `part`, `material`, `consumable`, `service`, `tool`)
+ because their `id` is a human-authored part number matched by VALUE against
+ `item."readableId"`, not an identifier — minting a fresh one orphans every row
+ from its item and every list view renders empty against a full table. They carry
+ only the composite PK (no global `UNIQUE (id)`), so preserving their ids cannot
+ collide; the two sets are disjoint by construction and a test enforces it.
+ Serial/int ids are left alone. A
1:1 extension table whose `id` is itself an FK (`purchaseOrderDelivery.id ->
purchaseOrder.id`) SHARES its parent's map rather than minting a second id,
which would split the pair — and under `session_replication_role='replica'`
@@ -141,10 +148,12 @@ both use it; `company-backup.ts` re-exports it), exported to app code as
- Storage path rewriting: `rewriteStoragePath` (swap `{sourceCompanyId}/` →
`{targetCompanyId}/` + remapped id segments), `rewriteToTemplateAssetPath`
(`{co}/…` → `_templates/{industryId}/…`). `STORAGE_PATH_COLUMNS` =
- `thumbnailPath` ONLY. `modelPath` (raw CAD) is deliberately excluded — raw
- models live in the transient `temp-staging` bucket, not `private`, so a backup
- never carries them; a restored model keeps its thumbnail and regenerates its 3D
- artifacts if the raw is re-uploaded.
+ `thumbnailPath`, `modelPath`, `originalPath`, `optimizedModelPath`,
+ `glbPath`, `graphPath` — every `modelUpload` artifact column. A backup enumerates assets by LISTING the bucket under
+ `{companyId}/` (`company-export.ts`), not by reading these columns, so raw CAD
+ IS carried; a column missing from this set survives a cross-company restore
+ still pointing at the SOURCE company's prefix (which is what left restored
+ assemblies unable to load their model).
- Asset transport: `copyAssetsToBackup` (server-side `storage.copy`
of `private/{companyId}/…` files into a backup's `assets/` folder) and
`restoreAssetsFromBackup` (copy them back to `private/`, rewriting paths +
diff --git a/apps/erp/app/components/AttachmentsList.tsx b/apps/erp/app/components/AttachmentsList.tsx
index d7c12fb10b..554387d440 100644
--- a/apps/erp/app/components/AttachmentsList.tsx
+++ b/apps/erp/app/components/AttachmentsList.tsx
@@ -1,5 +1,9 @@
import { useCarbon } from "@carbon/auth";
-import { convertKbToString } from "@carbon/files";
+import {
+ convertKbToString,
+ getCompanyPrivateBucket,
+ storage
+} from "@carbon/files";
import { MediaUploader, wasConvertedFromHeic } from "@carbon/files/media";
import {
Badge,
@@ -89,7 +93,7 @@ export default function AttachmentsList({
try {
// HEIC is never stored — convert to JPEG first.
const uploader = new MediaUploader(carbon, {
- bucket: "private",
+ bucket: getCompanyPrivateBucket(company.id),
directory: `${company.id}/tmp`
});
const files = await uploader.prepareForUpload(acceptedFiles);
@@ -97,8 +101,8 @@ export default function AttachmentsList({
const safeName = stripSpecialCharacters(file.name);
const storagePath = `${company.id}/supplier-interaction/${supplierInteractionId}/${safeName}`;
if (wasConvertedFromHeic(file)) {
- const existing = await carbon.storage
- .from("private")
+ const existing = await storage(carbon)
+ .company(company.id)
.info(storagePath);
if (!existing.error && existing.data) {
toast.error(
@@ -107,8 +111,8 @@ export default function AttachmentsList({
continue;
}
}
- const upload = await carbon.storage
- .from("private")
+ const upload = await storage(carbon)
+ .company(company.id)
.upload(storagePath, file, {
cacheControl: `${12 * 60 * 60}`,
upsert: true
@@ -135,14 +139,16 @@ export default function AttachmentsList({
const onRemovePoFile = useCallback(
async (a: ResolvedAttachmentItem) => {
if (!carbon) return;
- const result = await carbon.storage.from("private").remove([a.path]);
- if (result.error) {
- toast.error(result.error.message || t`Error removing file`);
+ const { error } = await storage(carbon)
+ .company(company.id)
+ .remove([a.path]);
+ if (error) {
+ toast.error(error.message || t`Error removing file`);
} else {
revalidator.revalidate();
}
},
- [carbon, revalidator, t]
+ [carbon, company.id, revalidator, t]
);
return (
diff --git a/apps/erp/app/components/DefaultAttachmentsPanel.tsx b/apps/erp/app/components/DefaultAttachmentsPanel.tsx
index cf93c786f8..f78122627f 100644
--- a/apps/erp/app/components/DefaultAttachmentsPanel.tsx
+++ b/apps/erp/app/components/DefaultAttachmentsPanel.tsx
@@ -1,5 +1,5 @@
import { useCarbon } from "@carbon/auth";
-import { convertKbToString, downloadBlob } from "@carbon/files";
+import { convertKbToString, downloadBlob, storage } from "@carbon/files";
import { wasConvertedFromHeic } from "@carbon/files/media";
import { getLogger } from "@carbon/logger";
import {
@@ -75,8 +75,8 @@ export default function DefaultAttachmentsPanel({
for (const file of acceptedFiles) {
const safeName = stripSpecialCharacters(file.name);
if (wasConvertedFromHeic(file)) {
- const existing = await carbon.storage
- .from("private")
+ const existing = await storage(carbon)
+ .company(company.id)
.info(fullPath(safeName));
if (!existing.error && existing.data) {
toast.error(
@@ -85,8 +85,8 @@ export default function DefaultAttachmentsPanel({
continue;
}
}
- const upload = await carbon.storage
- .from("private")
+ const upload = await storage(carbon)
+ .company(company.id)
.upload(fullPath(safeName), file, {
cacheControl: `${12 * 60 * 60}`,
upsert: true
@@ -95,7 +95,7 @@ export default function DefaultAttachmentsPanel({
}
revalidator.revalidate();
},
- [carbon, fullPath, revalidator, t]
+ [carbon, company.id, fullPath, revalidator, t]
);
const onDownload = useCallback(
@@ -121,11 +121,11 @@ export default function DefaultAttachmentsPanel({
const storagePath = fullPath(name);
setDeletingPath(storagePath);
try {
- const result = await carbon.storage
- .from("private")
+ const { error } = await storage(carbon)
+ .company(company.id)
.remove([storagePath]);
- if (result.error) {
- toast.error(result.error.message || t`Error deleting file`);
+ if (error) {
+ toast.error(error.message || t`Error deleting file`);
} else {
toast.success(t`${name} deleted`);
revalidator.revalidate();
@@ -134,7 +134,7 @@ export default function DefaultAttachmentsPanel({
setDeletingPath(null);
}
},
- [carbon, fullPath, revalidator, t]
+ [carbon, company.id, fullPath, revalidator, t]
);
return (
diff --git a/apps/erp/app/components/Documents.tsx b/apps/erp/app/components/Documents.tsx
index fcabf71d49..24a6fa20b1 100644
--- a/apps/erp/app/components/Documents.tsx
+++ b/apps/erp/app/components/Documents.tsx
@@ -1,5 +1,5 @@
import { useCarbon } from "@carbon/auth";
-import { convertKbToString, downloadBlob } from "@carbon/files";
+import { convertKbToString, downloadBlob, storage } from "@carbon/files";
import { getLogger } from "@carbon/logger";
import {
Card,
@@ -109,19 +109,23 @@ const Documents = ({
const deleteFile = useCallback(
async (file: StorageItem) => {
- const fileDelete = await carbon?.storage
- .from("private")
+ if (!carbon) {
+ toast.error(t`Error deleting file`);
+ return;
+ }
+ const { error } = await storage(carbon)
+ .company(company.id)
.remove([getReadPath(file)]);
- if (!fileDelete || fileDelete.error) {
- toast.error(fileDelete?.error?.message || t`Error deleting file`);
+ if (error) {
+ toast.error(error.message || t`Error deleting file`);
return;
}
toast.success(t`${file.name} deleted successfully`);
revalidator.revalidate();
},
- [carbon?.storage, getReadPath, revalidator, t]
+ [carbon, getReadPath, revalidator, t, company.id]
);
const downloadModel = useCallback(
diff --git a/apps/erp/app/components/FileDropzone.tsx b/apps/erp/app/components/FileDropzone.tsx
index 0775e396f8..f575902d05 100644
--- a/apps/erp/app/components/FileDropzone.tsx
+++ b/apps/erp/app/components/FileDropzone.tsx
@@ -1,4 +1,5 @@
import { useCarbon } from "@carbon/auth";
+import { getCompanyPrivateBucket } from "@carbon/files";
import {
DuplicateFileNameError,
isHeic,
@@ -39,7 +40,7 @@ const FileDropzone: React.FC<FileDropzoneProps> = ({
let files = acceptedFiles;
if (carbon && files.some((file) => isHeic(file.name, file.type))) {
const uploader = new MediaUploader(carbon, {
- bucket: "private",
+ bucket: getCompanyPrivateBucket(company.id),
directory: `${company.id}/tmp`
});
setIsConverting(true);
diff --git a/apps/erp/app/components/Form/PdfExtractor.tsx b/apps/erp/app/components/Form/PdfExtractor.tsx
index ce1f684fc1..b8fb8b3cfb 100644
--- a/apps/erp/app/components/Form/PdfExtractor.tsx
+++ b/apps/erp/app/components/Form/PdfExtractor.tsx
@@ -1,3 +1,4 @@
+import { storage } from "@carbon/files";
import { getLogger } from "@carbon/logger";
import { Spinner, useCarbon } from "@carbon/react";
import { useLingui } from "@lingui/react/macro";
@@ -88,8 +89,8 @@ export function PdfExtractor({
setUploading(true);
const storagePath = `${company.id}/extractions/${Date.now()}_${file.name}`;
- const { error } = await supabase.storage
- .from("private")
+ const { error } = await storage(supabase)
+ .company(company.id)
.upload(storagePath, file);
if (error) {
diff --git a/apps/erp/app/components/ImportCSVModal/UploadCSV.tsx b/apps/erp/app/components/ImportCSVModal/UploadCSV.tsx
index 264e3a94bc..f91607314f 100644
--- a/apps/erp/app/components/ImportCSVModal/UploadCSV.tsx
+++ b/apps/erp/app/components/ImportCSVModal/UploadCSV.tsx
@@ -1,5 +1,5 @@
import { useCarbon } from "@carbon/auth";
-import { downloadText } from "@carbon/files";
+import { downloadText, storage } from "@carbon/files";
import {
CSV_CONTENT_TYPE,
encodeCsvTable,
@@ -131,9 +131,8 @@ export const UploadCSV = ({ table }: { table: keyof typeof importSchemas }) => {
setLoading(false);
return;
}
-
- const { data, error } = await carbon.storage
- .from("private")
+ const { data, error } = await storage(carbon)
+ .company(company.id)
.upload(fileName, file);
if (error) {
diff --git a/apps/erp/app/components/ItemThumnailUpload.tsx b/apps/erp/app/components/ItemThumnailUpload.tsx
index b570003b33..1264b71b66 100644
--- a/apps/erp/app/components/ItemThumnailUpload.tsx
+++ b/apps/erp/app/components/ItemThumnailUpload.tsx
@@ -1,4 +1,5 @@
import { useCarbon } from "@carbon/auth";
+import { getCompanyPrivateBucket, storage } from "@carbon/files";
import { prepareImageUpload } from "@carbon/files/media";
import { getLogger } from "@carbon/logger";
import {
@@ -152,7 +153,7 @@ export function ItemThumbnailUpload({
try {
const processed = await prepareImageUpload(carbon, {
- bucket: "private",
+ bucket: getCompanyPrivateBucket(company.id),
directory: `${company.id}/tmp`,
file,
contained: true
@@ -172,9 +173,8 @@ export function ItemThumbnailUpload({
const thumbnailFile = new File([processed], fileName, {
type: processed.type
});
-
- const { data, error } = await carbon.storage
- .from("private")
+ const { data, error } = await storage(carbon)
+ .company(company.id)
.upload(
`${company.id}/thumbnails/${itemId}/${fileName}`,
thumbnailFile,
diff --git a/apps/erp/app/components/Layout/Topbar/Suggestion.tsx b/apps/erp/app/components/Layout/Topbar/Suggestion.tsx
index 4d0c82f32b..fd82e0775b 100644
--- a/apps/erp/app/components/Layout/Topbar/Suggestion.tsx
+++ b/apps/erp/app/components/Layout/Topbar/Suggestion.tsx
@@ -1,4 +1,5 @@
import { CARBON_SLACK_ENABLED, useCarbon } from "@carbon/auth";
+import { getCompanyPrivateBucket, storage } from "@carbon/files";
import { convertHeicToJpeg, isHeic } from "@carbon/files/media";
import {
Hidden,
@@ -110,7 +111,7 @@ const Suggestion = () => {
if (isHeic(file.name, file.type)) {
try {
file = await convertHeicToJpeg(carbon, {
- bucket: "private",
+ bucket: getCompanyPrivateBucket(companyId),
directory: `${companyId}/tmp`,
file
});
@@ -122,8 +123,8 @@ const Suggestion = () => {
const fileExtension = file.name.substring(file.name.lastIndexOf(".") + 1);
const storagePath = `${companyId}/suggestions/${nanoid()}.${fileExtension}`;
- const imageUpload = await carbon.storage
- .from("private")
+ const imageUpload = await storage(carbon)
+ .company(companyId)
.upload(storagePath, file, {
cacheControl: `${12 * 60 * 60}`,
upsert: true
diff --git a/apps/erp/app/components/RecordDocuments.tsx b/apps/erp/app/components/RecordDocuments.tsx
index d2f1f1a66d..4e77bbc196 100644
--- a/apps/erp/app/components/RecordDocuments.tsx
+++ b/apps/erp/app/components/RecordDocuments.tsx
@@ -1,5 +1,5 @@
import { useCarbon } from "@carbon/auth";
-import { convertKbToString } from "@carbon/files";
+import { convertKbToString, storage } from "@carbon/files";
import { getLogger } from "@carbon/logger";
import {
Card,
@@ -274,19 +274,23 @@ export const useRecordDocuments = ({
const deleteAttachment = useCallback(
async (file: FileObject) => {
- const result = await carbon?.storage
- .from("private")
+ if (!carbon) {
+ toast.error(t`Error deleting file`);
+ return;
+ }
+ const { error } = await storage(carbon)
+ .company(company.id)
.remove([getPath(file)]);
- if (!result || result.error) {
- toast.error(result?.error?.message || t`Error deleting file`);
+ if (error) {
+ toast.error(error.message || t`Error deleting file`);
return;
}
toast.success(t`${file.name} deleted successfully`);
revalidator.revalidate();
},
- [carbon?.storage, getPath, revalidator, t]
+ [carbon, company.id, getPath, revalidator, t]
);
const view = useCallback(
diff --git a/apps/erp/app/components/SlidesEditor.tsx b/apps/erp/app/components/SlidesEditor.tsx
index 184a133b0a..4585b76781 100644
--- a/apps/erp/app/components/SlidesEditor.tsx
+++ b/apps/erp/app/components/SlidesEditor.tsx
@@ -1,5 +1,6 @@
import { useCarbon } from "@carbon/auth";
import type { Database } from "@carbon/database";
+import { storage } from "@carbon/files";
import { supportedModelTypes } from "@carbon/files/cad";
import { Button, cn, IconButton, Label, VStack } from "@carbon/react";
import { useLingui } from "@lingui/react/macro";
@@ -33,8 +34,8 @@ export async function uploadStepSlideModel(
): Promise<string | null> {
const modelUploadId = nanoid();
const ext = file.name.split(".").pop();
- const upload = await carbon.storage
- .from("private")
+ const upload = await storage(carbon)
+ .company(companyId)
.upload(`${companyId}/models/${modelUploadId}.${ext}`, file, {
upsert: true
});
diff --git a/apps/erp/app/hooks/useFileUpload.ts b/apps/erp/app/hooks/useFileUpload.ts
index 2470dda0ec..58f63b4e2b 100644
--- a/apps/erp/app/hooks/useFileUpload.ts
+++ b/apps/erp/app/hooks/useFileUpload.ts
@@ -1,4 +1,5 @@
import { useCarbon } from "@carbon/auth";
+import { getCompanyPrivateBucket, storage } from "@carbon/files";
import {
DuplicateFileNameError,
MediaUploader,
@@ -19,7 +20,7 @@ export type FileUploadOptions = {
};
/**
- * The one private-bucket upload mutation for document panels: prepare the
+ * The one company-private-bucket upload mutation for document panels: prepare the
* files (HEIC → JPEG, duplicate-name refusal), store each one, surface
* failures. Panels supply only what differs — the path and what a stored file
* means — either once at the hook (the common case) or per call when a
@@ -40,7 +41,7 @@ export function useFileUpload(options: FileUploadOptions = {}) {
() =>
carbon
? new MediaUploader(carbon, {
- bucket: "private",
+ bucket: getCompanyPrivateBucket(company.id),
directory: `${company.id}/tmp`
})
: null,
@@ -85,8 +86,8 @@ export function useFileUpload(options: FileUploadOptions = {}) {
// the user never mentioned. Plain same-name re-uploads keep the
// replace-by-name behavior; only the masked case is refused.
if (wasConvertedFromHeic(file)) {
- const existing = await carbon.storage
- .from("private")
+ const existing = await storage(carbon)
+ .company(company.id)
.info(targetPath);
if (!existing.error && existing.data) {
toast.error(
@@ -97,8 +98,8 @@ export function useFileUpload(options: FileUploadOptions = {}) {
}
}
toast.info(t`Uploading ${file.name}`);
- const result = await carbon.storage
- .from("private")
+ const result = await storage(carbon)
+ .company(company.id)
.upload(targetPath, file, {
cacheControl: `${12 * 60 * 60}`,
upsert: true
@@ -116,7 +117,7 @@ export function useFileUpload(options: FileUploadOptions = {}) {
}
},
// options fields are destructured above so callers may pass an inline object
- [carbon, uploader, t, baseGetPath, baseOnSuccess, baseOnError]
+ [carbon, uploader, company.id, t, baseGetPath, baseOnSuccess, baseOnError]
);
return { upload, isUploading };
diff --git a/apps/erp/app/hooks/useImageUpload.ts b/apps/erp/app/hooks/useImageUpload.ts
index 9568fcbdee..d9d7ea5942 100644
--- a/apps/erp/app/hooks/useImageUpload.ts
+++ b/apps/erp/app/hooks/useImageUpload.ts
@@ -1,4 +1,5 @@
import { useCarbon } from "@carbon/auth";
+import { getCompanyPrivateBucket, storage } from "@carbon/files";
import { isHeic, MediaUploader } from "@carbon/files/media";
import { toast } from "@carbon/react";
import { useLingui } from "@lingui/react/macro";
@@ -9,8 +10,8 @@ import { useUser } from "./useUser";
/**
* Shared editor/notes image-upload handler. HEIC is converted to JPEG before
- * anything is stored (HEIC is never persisted); the file lands in the private
- * bucket under `{companyId}/{directory}/{nanoid}.{ext}` and the preview URL
+ * anything is stored (HEIC is never persisted); the file lands in the company's
+ * private bucket under `{companyId}/{directory}/{nanoid}.{ext}` and the preview URL
* is returned for the editor to embed.
*/
export function useImageUpload(directory: string) {
@@ -22,7 +23,7 @@ export function useImageUpload(directory: string) {
() =>
carbon
? new MediaUploader(carbon, {
- bucket: "private",
+ bucket: getCompanyPrivateBucket(company.id),
directory: `${company.id}/tmp`
})
: null,
@@ -46,8 +47,8 @@ export function useImageUpload(directory: string) {
const fileType = upload.name.split(".").pop();
const fileName = `${company.id}/${directory}/${nanoid()}.${fileType}`;
- const result = await carbon.storage
- .from("private")
+ const result = await storage(carbon)
+ .company(company.id)
.upload(fileName, upload);
if (result.error) {
diff --git a/apps/erp/app/modules/account/ui/Profile/ProfilePhotoForm.tsx b/apps/erp/app/modules/account/ui/Profile/ProfilePhotoForm.tsx
index e5dd0e113b..d0db2272d5 100644
--- a/apps/erp/app/modules/account/ui/Profile/ProfilePhotoForm.tsx
+++ b/apps/erp/app/modules/account/ui/Profile/ProfilePhotoForm.tsx
@@ -1,4 +1,5 @@
import { useCarbon } from "@carbon/auth";
+import { getCompanyPrivateBucket } from "@carbon/files";
import { prepareImageUpload } from "@carbon/files/media";
import { getLogger } from "@carbon/logger";
import {
@@ -37,7 +38,7 @@ const ProfilePhotoForm = ({ user }: ProfilePhotoFormProps) => {
try {
const processed = await prepareImageUpload(carbon, {
- bucket: "private",
+ bucket: getCompanyPrivateBucket(company.id),
directory: `${company.id}/tmp`,
file: avatarFile
});
diff --git a/apps/erp/app/modules/account/ui/UserAttributes/UserAttributesForm.tsx b/apps/erp/app/modules/account/ui/UserAttributes/UserAttributesForm.tsx
index f001675d8d..164bd17234 100644
--- a/apps/erp/app/modules/account/ui/UserAttributes/UserAttributesForm.tsx
+++ b/apps/erp/app/modules/account/ui/UserAttributes/UserAttributesForm.tsx
@@ -1,4 +1,5 @@
import { useCarbon } from "@carbon/auth";
+import { storage } from "@carbon/files";
import { ValidatedForm } from "@carbon/form";
import {
Button,
@@ -769,8 +770,8 @@ function FileAttributeForm({
const fileName = `${company.id}/person/${userId}/${fileUpload.name}`;
- const upload = await carbon?.storage
- .from("private")
+ const upload = await storage(carbon)
+ .company(company.id)
.upload(fileName, fileUpload, {
cacheControl: `${12 * 60 * 60}`,
upsert: true
diff --git a/apps/erp/app/modules/documents/documents.service.ts b/apps/erp/app/modules/documents/documents.service.ts
index d7c813f978..0de0c21a51 100644
--- a/apps/erp/app/modules/documents/documents.service.ts
+++ b/apps/erp/app/modules/documents/documents.service.ts
@@ -1,4 +1,5 @@
import type { Database } from "@carbon/database";
+import { storage } from "@carbon/files";
import { isHeic } from "@carbon/files/media";
import { trigger } from "@carbon/jobs";
import type { SupabaseClient } from "@supabase/supabase-js";
@@ -228,8 +229,8 @@ export async function createDocumentUploadUrl(
const documentPath = isHeic(args.name)
? buildStagedUploadPath(args)
: buildDocumentUploadPath(args);
- return client.storage
- .from("private")
+ return storage(client)
+ .company(args.companyId)
.createSignedUploadUrl(documentPath, { upsert: true });
}
@@ -271,8 +272,8 @@ export async function insertUploadedDocument(
// memory, no wasm in the app bundle.
const staged = parseStagedUploadPath(path);
if (staged) {
- const converted = await client.storage
- .from("private")
+ const converted = await storage(client)
+ .company(args.companyId)
.download(path, { transform: { quality: 85 } });
if (converted.error || !converted.data) {
return {
@@ -291,8 +292,8 @@ export async function insertUploadedDocument(
entityId: staged.entityId,
name
});
- const stored = await client.storage
- .from("private")
+ const stored = await storage(client)
+ .company(args.companyId)
.upload(finalPath, converted.data, {
contentType: converted.data.type || "image/jpeg",
upsert: true
@@ -303,7 +304,7 @@ export async function insertUploadedDocument(
error: stored.error ?? new Error("Failed to store the converted image")
};
}
- await client.storage.from("private").remove([path]);
+ await storage(client).company(args.companyId).remove([path]);
path = stored.data.path;
size = Math.round(converted.data.size / 1024);
}
diff --git a/apps/erp/app/modules/documents/ui/Documents/DocumentCreateForm.tsx b/apps/erp/app/modules/documents/ui/Documents/DocumentCreateForm.tsx
index 97a908dfa9..3af6627a41 100644
--- a/apps/erp/app/modules/documents/ui/Documents/DocumentCreateForm.tsx
+++ b/apps/erp/app/modules/documents/ui/Documents/DocumentCreateForm.tsx
@@ -1,4 +1,5 @@
import { useCarbon } from "@carbon/auth";
+import { getCompanyPrivateBucket, storage } from "@carbon/files";
import { convertHeicToJpeg, isHeic } from "@carbon/files/media";
import { getLogger } from "@carbon/logger";
import { File, toast } from "@carbon/react";
@@ -28,7 +29,7 @@ const DocumentCreateForm = () => {
if (isHeic(file.name, file.type)) {
try {
file = await convertHeicToJpeg(carbon, {
- bucket: "private",
+ bucket: getCompanyPrivateBucket(companyId),
directory: `${companyId}/tmp`,
file
});
@@ -41,8 +42,8 @@ const DocumentCreateForm = () => {
const fileExtension = file.name.substring(file.name.lastIndexOf(".") + 1);
const fileName = `${companyId}/${nanoid()}.${fileExtension}`;
- const fileUpload = await carbon.storage
- .from("private")
+ const fileUpload = await storage(carbon)
+ .company(companyId)
.upload(fileName, file, {
cacheControl: `${12 * 60 * 60}`,
upsert: true
diff --git a/apps/erp/app/modules/documents/ui/Documents/useDocument.ts b/apps/erp/app/modules/documents/ui/Documents/useDocument.ts
index 857f60e4ff..b5232f87d7 100644
--- a/apps/erp/app/modules/documents/ui/Documents/useDocument.ts
+++ b/apps/erp/app/modules/documents/ui/Documents/useDocument.ts
@@ -1,5 +1,5 @@
import { useCarbon } from "@carbon/auth";
-import { downloadBlob } from "@carbon/files";
+import { downloadBlob, storage } from "@carbon/files";
import { getLogger } from "@carbon/logger";
import { toast } from "@carbon/react";
import { useCallback } from "react";
@@ -159,16 +159,22 @@ export const useDocument = () => {
const makePreview = useCallback(
async (doc: DocumentType) => {
if (!doc.path) throw new Error("Document path is undefined");
- const result = await carbon?.storage.from("private").download(doc.path);
+ if (!carbon) {
+ toast.error("Error previewing file");
+ return null;
+ }
+ const { data, error } = await storage(carbon)
+ .company(user.company.id)
+ .download(doc.path);
- if (!result || result.error) {
- toast.error(result?.error?.message || "Error previewing file");
+ if (!data) {
+ toast.error(error?.message || "Error previewing file");
return null;
}
- return window.URL.createObjectURL(result.data);
+ return window.URL.createObjectURL(data);
},
- [carbon]
+ [carbon, user.company.id]
);
const removeLabel = useCallback(
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index b1d67cf5e0..2185979214 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -6,6 +6,7 @@ import {
linesideCredit
} from "@carbon/database/picked-consumption";
import { consumableInWholeAssemblies } from "@carbon/database/supersession-pick";
+import { storage } from "@carbon/files";
import type { TrackedEntityAttributes } from "@carbon/utils";
import { datetime } from "@carbon/utils";
import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";
@@ -748,8 +749,8 @@ export async function getReceiptFiles(
lineIds: string[]
): Promise<{ data: StorageItem[]; error: string | null }> {
const promises = lineIds.map((lineId) =>
- client.storage
- .from("private")
+ storage(client)
+ .company(companyId)
.list(`${companyId}/inventory/${lineId}`)
.then((result) => ({
...result,
@@ -759,13 +760,9 @@ export async function getReceiptFiles(
const results = await Promise.all(promises);
- // Check for errors
- const firstError = results.find((result) => result.error);
+ const firstError = results.find((result) => result.error)?.error;
if (firstError) {
- return {
- data: [],
- error: firstError.error?.message ?? "Failed to fetch files"
- };
+ return { data: [], error: firstError.message || "Failed to fetch files" };
}
// Merge data arrays and add lineId as bucketName
@@ -1204,8 +1201,8 @@ export async function getShipmentFiles(
lineIds: string[]
): Promise<{ data: StorageItem[]; error: string | null }> {
const promises = lineIds.map((lineId) =>
- client.storage
- .from("private")
+ storage(client)
+ .company(companyId)
.list(`${companyId}/inventory/${lineId}`)
.then((result) => ({
...result,
@@ -1215,13 +1212,9 @@ export async function getShipmentFiles(
const results = await Promise.all(promises);
- // Check for errors
- const firstError = results.find((result) => result.error);
+ const firstError = results.find((result) => result.error)?.error;
if (firstError) {
- return {
- data: [],
- error: firstError.error?.message ?? "Failed to fetch files"
- };
+ return { data: [], error: firstError.message || "Failed to fetch files" };
}
// Merge data arrays and add lineId as bucketName
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
index 77b52c12ef..989ff946f6 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
@@ -1,5 +1,5 @@
import { useCarbon } from "@carbon/auth";
-import { isPreviewableDocumentType } from "@carbon/files";
+import { isPreviewableDocumentType, storage } from "@carbon/files";
import { Number, Submit, ValidatedForm } from "@carbon/form";
import {
Button,
@@ -1329,12 +1329,11 @@ function useReceiptFiles(receiptId: string) {
toast.error(t`Carbon client not available`);
return;
}
-
for (const file of files) {
const fileName = getPath({ name: file.name }, lineId);
toast.info(`Uploading ${file.name}`);
- const fileUpload = await carbon.storage
- .from("private")
+ const fileUpload = await storage(carbon)
+ .company(company.id)
.upload(fileName, file, {
cacheControl: `${12 * 60 * 60}`,
upsert: true
@@ -1361,24 +1360,28 @@ function useReceiptFiles(receiptId: string) {
}
revalidator.revalidate();
},
- [carbon, revalidator, getPath, receiptId, submit, t]
+ [carbon, company.id, revalidator, getPath, receiptId, submit, t]
);
const deleteFile = useCallback(
async (file: StorageItem, lineId: string) => {
- const fileDelete = await carbon?.storage
- .from("private")
+ if (!carbon) {
+ toast.error("Error deleting file");
+ return;
+ }
+ const { error } = await storage(carbon)
+ .company(company.id)
.remove([getPath(file, lineId)]);
- if (!fileDelete || fileDelete.error) {
- toast.error(fileDelete?.error?.message || "Error deleting file");
+ if (error) {
+ toast.error(error.message || "Error deleting file");
return;
}
toast.success(`${file.name} deleted successfully`);
revalidator.revalidate();
},
- [getPath, carbon?.storage, revalidator]
+ [getPath, carbon, company.id, revalidator]
);
return { upload, deleteFile, getPath };
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index a5261ce08a..519e27d8e3 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -6,6 +6,7 @@ import type {
KyselyDatabase,
KyselyTx
} from "@carbon/database/client";
+import { storage } from "@carbon/files";
import { getLogger } from "@carbon/logger";
import { datetime } from "@carbon/utils";
import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";
@@ -788,10 +789,10 @@ export async function getItemFiles(
itemId: string,
companyId: string
) {
- const result = await client.storage
- .from("private")
+ const result = await storage(client)
+ .company(companyId)
.list(`${companyId}/parts/${itemId}`);
- return result.data || [];
+ return result.data ?? [];
}
export async function getItemPostingGroup(
diff --git a/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx b/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx
index 5114f4e615..1a78beb3e2 100644
--- a/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx
+++ b/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx
@@ -1,5 +1,6 @@
"use client";
import { useCarbon } from "@carbon/auth";
+import { getCompanyPrivateBucket, storage } from "@carbon/files";
import { convertHeicToJpeg, isHeic } from "@carbon/files/media";
import { Array as ArrayInput, Input, ValidatedForm } from "@carbon/form";
import type { JSONContent } from "@carbon/react";
@@ -2012,15 +2013,15 @@ function AttributesForm({
try {
const upload = isHeic(file.name, file.type)
? await convertHeicToJpeg(carbon, {
- bucket: "private",
+ bucket: getCompanyPrivateBucket(companyId),
directory: `${companyId}/tmp`,
file
})
: file;
const ext = upload.name.split(".").pop();
const fileName = `${companyId}/parts/${nanoid()}.${ext}`;
- const result = await carbon.storage
- .from("private")
+ const result = await storage(carbon)
+ .company(companyId)
.upload(fileName, upload);
if (result.error || !result.data) {
toast.error(t`Failed to upload image`);
@@ -3083,15 +3084,15 @@ function StepSlides({
try {
const upload = isHeic(file.name, file.type)
? await convertHeicToJpeg(carbon, {
- bucket: "private",
+ bucket: getCompanyPrivateBucket(companyId),
directory: `${companyId}/tmp`,
file
})
: file;
const ext = upload.name.split(".").pop();
const fileName = `${companyId}/parts/${nanoid()}.${ext}`;
- const result = await carbon.storage
- .from("private")
+ const result = await storage(carbon)
+ .company(companyId)
.upload(fileName, upload);
if (result.error || !result.data) {
toast.error(t`Failed to upload image`);
diff --git a/apps/erp/app/modules/items/ui/Item/ItemDocuments.tsx b/apps/erp/app/modules/items/ui/Item/ItemDocuments.tsx
index c0e4b9e961..2a4297a8e4 100644
--- a/apps/erp/app/modules/items/ui/Item/ItemDocuments.tsx
+++ b/apps/erp/app/modules/items/ui/Item/ItemDocuments.tsx
@@ -1,5 +1,5 @@
import { useCarbon } from "@carbon/auth";
-import { convertKbToString, downloadBlob } from "@carbon/files";
+import { convertKbToString, downloadBlob, storage } from "@carbon/files";
import { getLogger } from "@carbon/logger";
import {
Card,
@@ -344,19 +344,23 @@ export const useItemDocuments = ({ itemId, type }: Props) => {
const deleteFile = useCallback(
async (file: FileObject) => {
- const fileDelete = await carbon?.storage
- .from("private")
+ if (!carbon) {
+ toast.error(t`Error deleting file`);
+ return;
+ }
+ const { error } = await storage(carbon)
+ .company(company.id)
.remove([getPath(file)]);
- if (!fileDelete || fileDelete.error) {
- toast.error(fileDelete?.error?.message || t`Error deleting file`);
+ if (error) {
+ toast.error(error.message || t`Error deleting file`);
return;
}
toast.success(t`File deleted successfully`);
revalidator.revalidate();
},
- [getPath, carbon?.storage, revalidator, t]
+ [getPath, carbon, revalidator, t, company.id]
);
const deleteModel = useCallback(async () => {
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 6df58e745f..1b3a2fed17 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -3,6 +3,7 @@ import { fetchAllFromTable } from "@carbon/database";
import type { Kysely, KyselyDatabase } from "@carbon/database/client";
import { consumableInWholeAssemblies } from "@carbon/database/supersession-pick";
import { ASSEMBLER_SERVICE_API_KEY, ASSEMBLER_SERVICE_URL } from "@carbon/env";
+import { storage } from "@carbon/files";
import type { JobSource } from "@carbon/lib/telemetry";
import { asJobSource, trackWorkEvent } from "@carbon/lib/telemetry";
import { raiseMoment } from "@carbon/lib/workflows";
@@ -28,7 +29,6 @@ import {
indexAssemblyGraph
} from "@carbon/viewer";
import { parseDate } from "@internationalized/date";
-import type { FileObject, StorageError } from "@supabase/storage-js";
import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";
import type { ExpressionBuilder } from "kysely";
import { sql } from "kysely";
@@ -844,45 +844,39 @@ export async function getJobDocuments(
itemId?: string | null;
}
): Promise<StorageItem[]> {
- const promises: Promise<
- | {
- data: FileObject[];
- error: null;
- }
- | {
- data: null;
- error: StorageError;
- }
- >[] = [client.storage.from("private").list(`${companyId}/job/${job.id}`)];
-
- // Add opportunity line files if available
- if (job.salesOrderLineId || job.quoteLineId) {
- const opportunityLine = job.salesOrderLineId || job.quoteLineId;
- promises.push(
- client.storage
- .from("private")
- .list(`${companyId}/opportunity-line/${opportunityLine}`)
- );
- }
-
- // Add parts files if itemId is available
- if (job.itemId) {
- promises.push(
- client.storage.from("private").list(`${companyId}/parts/${job.itemId}`)
- );
- }
-
- const results = await Promise.all(promises);
- const [jobFiles, opportunityLineFiles, partsFiles] = results;
+ // Fixed positions, not a conditionally-grown array: the destructuring below
+ // is positional, so a job with an itemId but no sales/quote line would
+ // otherwise land its PARTS listing in `opportunityLineFiles` and label those
+ // files `bucket: "opportunity-line"`, which resolves the wrong storage path.
+ const opportunityLine = job.salesOrderLineId || job.quoteLineId;
+ const [jobFiles, opportunityLineFiles, partsFiles] = await Promise.all([
+ storage(client).company(companyId).list(`${companyId}/job/${job.id}`),
+ opportunityLine
+ ? storage(client)
+ .company(companyId)
+ .list(`${companyId}/opportunity-line/${opportunityLine}`)
+ : null,
+ job.itemId
+ ? storage(client)
+ .company(companyId)
+ .list(`${companyId}/parts/${job.itemId}`)
+ : null
+ ]);
// Combine and return all sets of files with their respective buckets
return [
- ...(jobFiles.data?.map((f) => ({ ...f, bucket: "job" })) || []),
- ...(opportunityLineFiles?.data?.map((f) => ({
+ ...(jobFiles.data ?? []).map((f) => ({
+ ...f,
+ bucket: "job"
+ })),
+ ...(opportunityLineFiles?.data ?? []).map((f) => ({
...f,
bucket: "opportunity-line"
- })) || []),
- ...(partsFiles?.data?.map((f) => ({ ...f, bucket: "parts" })) || [])
+ })),
+ ...(partsFiles?.data ?? []).map((f) => ({
+ ...f,
+ bucket: "parts"
+ }))
];
}
@@ -892,13 +886,17 @@ export const getPartDocuments = async (
...items: Array<{ itemId: string }>
) => {
const getFile = async (id: string) => {
- const res = await client.storage
- .from("private")
+ const res = await storage(client)
+ .company(companyId)
.list(`${companyId}/parts/${id}`);
- if (res.error || !res.data) return null;
+ if (res.error) return null;
- return res.data.map((f) => ({ ...f, bucket: "parts", itemId: id }));
+ return res.data.map((f) => ({
+ ...f,
+ bucket: "parts",
+ itemId: id
+ }));
};
const elems = items.map((el) => getFile(el.itemId));
@@ -920,28 +918,28 @@ export async function getJobDocumentsWithItemId(
const opportunityLine = job.salesOrderLineId || job.quoteLineId;
const [opportunityLineFiles, jobFiles] = await Promise.all([
- client.storage
- .from("private")
+ storage(client)
+ .company(companyId)
.list(`${companyId}/opportunity-line/${opportunityLine}`),
- client.storage.from("private").list(`${companyId}/job/${job.id}`)
+ storage(client).company(companyId).list(`${companyId}/job/${job.id}`)
]);
// Combine and return both sets of files
return [
- ...(opportunityLineFiles.data?.map((f) => ({
+ ...(opportunityLineFiles.data ?? []).map((f) => ({
...f,
bucket: "opportunity-line"
- })) || []),
- ...(jobFiles.data?.map((f) => ({ ...f, bucket: "job" })) || []),
+ })),
+ ...(jobFiles.data ?? []).map((f) => ({ ...f, bucket: "job" })),
...itemFiles
];
} else {
- const [jobFiles] = await Promise.all([
- client.storage.from("private").list(`${companyId}/job/${job.id}`)
- ]);
+ const jobFiles = await storage(client)
+ .company(companyId)
+ .list(`${companyId}/job/${job.id}`);
return [
- ...(jobFiles.data?.map((f) => ({ ...f, bucket: "job" })) || []),
+ ...(jobFiles.data ?? []).map((f) => ({ ...f, bucket: "job" })),
...itemFiles
];
}
@@ -7007,7 +7005,9 @@ async function invalidateAssemblyPlanCache(
// Best-effort artifact cleanup (removing a nonexistent path is a no-op);
// deleting the rows below is what actually invalidates the cache
// (getLatestAssemblyPlan then finds nothing).
- await client.storage.from("private").remove(planPaths);
+ // Private object paths are prefixed with the owning company's id.
+ const companyId = planPaths[0].split("/")[0];
+ await storage(client).company(companyId).remove(planPaths);
}
await client
@@ -7067,7 +7067,10 @@ export async function invalidateAssemblyModelCache(
if (paths.size > 0) {
// Best-effort file cleanup; the row updates below are what invalidate.
- await client.storage.from("private").remove([...paths]);
+ // Private object paths are prefixed with the owning company's id.
+ const objectPaths = [...paths];
+ const companyId = objectPaths[0].split("/")[0];
+ await storage(client).company(companyId).remove(objectPaths);
}
await client
@@ -7815,8 +7818,10 @@ export async function syncAssemblyStepMaterialsFromMappings(
const steps = await stepsQuery;
if (!steps.data?.length) return { created: 0 };
- const graphFile = await client.storage.from("private").download(graphPath);
- if (graphFile.error || !graphFile.data) return { created: 0 };
+ const graphFile = await storage(client)
+ .company(args.companyId)
+ .download(graphPath);
+ if (!graphFile.data) return { created: 0 };
let graphIndex: AssemblyGraphIndex;
try {
graphIndex = indexAssemblyGraph(
@@ -8002,8 +8007,12 @@ export async function getAssemblyPlanJson(
const job = await getLatestAssemblyPlan(client, modelUploadId);
if (!job.data?.planPath) return null;
- const file = await client.storage.from("private").download(job.data.planPath);
- if (file.error || !file.data) return null;
+ // Private object paths are prefixed with the owning company's id.
+ const planCompanyId = job.data.planPath.split("/")[0];
+ const file = await storage(client)
+ .company(planCompanyId)
+ .download(job.data.planPath);
+ if (!file.data) return null;
try {
const plan = JSON.parse(await file.data.text()) as AssemblyPlan;
@@ -8169,8 +8178,10 @@ export async function autoMatchAssemblyComponents(
return { error: "The model has not been processed" };
}
- const graphFile = await client.storage.from("private").download(graphPath);
- if (graphFile.error || !graphFile.data) {
+ const graphFile = await storage(client)
+ .company(args.companyId)
+ .download(graphPath);
+ if (!graphFile.data) {
return { error: "Failed to load the model graph" };
}
let graph: AssemblyGraph;
@@ -9009,7 +9020,9 @@ export async function generateAssemblyStepsFromPlan(
let graphIndex: AssemblyGraphIndex | null = null;
const graphPath = instruction.data.modelUpload?.graphPath;
if (graphPath) {
- const graphFile = await client.storage.from("private").download(graphPath);
+ const graphFile = await storage(client)
+ .company(args.companyId)
+ .download(graphPath);
if (graphFile.data) {
try {
const graph = JSON.parse(await graphFile.data.text()) as AssemblyGraph;
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepSlides.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepSlides.tsx
index 11b1bab839..906059e42a 100644
--- a/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepSlides.tsx
+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepSlides.tsx
@@ -1,4 +1,5 @@
import { useCarbon } from "@carbon/auth";
+import { getCompanyPrivateBucket, storage } from "@carbon/files";
import { convertHeicToJpeg, isHeic } from "@carbon/files/media";
import { toast } from "@carbon/react";
import { nanoid } from "nanoid";
@@ -53,15 +54,15 @@ export default function AssemblyStepSlides({
try {
const upload = isHeic(file.name, file.type)
? await convertHeicToJpeg(carbon, {
- bucket: "private",
+ bucket: getCompanyPrivateBucket(companyId),
directory: `${companyId}/tmp`,
file
})
: file;
const ext = upload.name.split(".").pop();
const fileName = `${companyId}/assembly/${instructionId}/${nanoid()}.${ext}`;
- const result = await carbon.storage
- .from("private")
+ const result = await storage(carbon)
+ .company(companyId)
.upload(fileName, upload);
if (result.error || !result.data) {
toast.error("Failed to upload image");
diff --git a/apps/erp/app/modules/production/ui/InspectionDocument/InspectionDocumentEditor.tsx b/apps/erp/app/modules/production/ui/InspectionDocument/InspectionDocumentEditor.tsx
index 94116a0f99..b23a19a621 100644
--- a/apps/erp/app/modules/production/ui/InspectionDocument/InspectionDocumentEditor.tsx
+++ b/apps/erp/app/modules/production/ui/InspectionDocument/InspectionDocumentEditor.tsx
@@ -29,6 +29,7 @@ import { Document, Page } from "react-pdf";
import "react-pdf/dist/Page/AnnotationLayer.css";
import "react-pdf/dist/Page/TextLayer.css";
import type { Database } from "@carbon/database";
+import { storage } from "@carbon/files";
import type { ColumnDef } from "@tanstack/react-table";
import {
LuChevronDown,
@@ -2214,8 +2215,8 @@ export default function InspectionDocumentEditor({
setUploading(true);
const storagePath = `${companyId}/inspectionDocument/${diagramId}/${nanoid()}.pdf`;
- const result = await carbon.storage
- .from("private")
+ const result = await storage(carbon)
+ .company(companyId)
.upload(storagePath, file);
setUploading(false);
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
index 6cc29a8db6..78f2400cfc 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
@@ -1,6 +1,7 @@
"use client";
import { useCarbon } from "@carbon/auth";
import type { Database } from "@carbon/database";
+import { getCompanyPrivateBucket, storage } from "@carbon/files";
import { convertHeicToJpeg, isHeic } from "@carbon/files/media";
import { Array as ArrayInput, Input, ValidatedForm } from "@carbon/form";
import { getLogger } from "@carbon/logger";
@@ -1308,15 +1309,15 @@ function StepsForm({
try {
const upload = isHeic(file.name, file.type)
? await convertHeicToJpeg(carbon, {
- bucket: "private",
+ bucket: getCompanyPrivateBucket(companyId),
directory: `${companyId}/tmp`,
file
})
: file;
const ext = upload.name.split(".").pop();
const fileName = `${companyId}/parts/${nanoid()}.${ext}`;
- const result = await carbon.storage
- .from("private")
+ const result = await storage(carbon)
+ .company(companyId)
.upload(fileName, upload);
if (result.error || !result.data) {
toast.error(t`Failed to upload image`);
@@ -1944,15 +1945,15 @@ function JobStepSlides({
try {
const upload = isHeic(file.name, file.type)
? await convertHeicToJpeg(carbon, {
- bucket: "private",
+ bucket: getCompanyPrivateBucket(companyId),
directory: `${companyId}/tmp`,
file
})
: file;
const ext = upload.name.split(".").pop();
const fileName = `${companyId}/parts/${nanoid()}.${ext}`;
- const result = await carbon.storage
- .from("private")
+ const result = await storage(carbon)
+ .company(companyId)
.upload(fileName, upload);
if (result.error || !result.data) {
toast.error(t`Failed to upload image`);
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobDocuments.tsx b/apps/erp/app/modules/production/ui/Jobs/JobDocuments.tsx
index fccce8c540..a53fd997e8 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobDocuments.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobDocuments.tsx
@@ -1,5 +1,5 @@
import { useCarbon } from "@carbon/auth";
-import { convertKbToString, downloadBlob } from "@carbon/files";
+import { convertKbToString, downloadBlob, storage } from "@carbon/files";
import { getLogger } from "@carbon/logger";
import {
Card,
@@ -86,19 +86,23 @@ const useJobDocuments = ({
const deleteFile = useCallback(
async (file: FileObject & { bucket?: string }) => {
const bucket = file.bucket === "parts" ? "parts" : "job";
- const fileDelete = await carbon?.storage
- .from("private")
+ if (!carbon) {
+ toast.error("Error deleting file");
+ return;
+ }
+ const { error } = await storage(carbon)
+ .company(company.id)
.remove([getPath(file, bucket as "job" | "parts")]);
- if (!fileDelete || fileDelete.error) {
- toast.error(fileDelete?.error?.message || "Error deleting file");
+ if (error) {
+ toast.error(error.message || "Error deleting file");
return;
}
toast.success(t`${file.name} deleted successfully`);
revalidator.revalidate();
},
- [getPath, carbon?.storage, revalidator, t]
+ [getPath, carbon, company.id, revalidator, t]
);
const deleteModel = useCallback(async () => {
@@ -232,8 +236,8 @@ const useJobDocuments = ({
try {
// Download the file first
const sourcePath = getPath(file, currentBucket);
- const { data: downloadData } = await carbon.storage
- .from("private")
+ const { data: downloadData } = await storage(carbon)
+ .company(company.id)
.download(sourcePath);
if (!downloadData) {
@@ -243,8 +247,8 @@ const useJobDocuments = ({
// Upload to new location
const targetPath = getPath(file, targetBucket);
- const { error: uploadError } = await carbon.storage
- .from("private")
+ const { error: uploadError } = await storage(carbon)
+ .company(company.id)
.upload(targetPath, downloadData, {
cacheControl: `${12 * 60 * 60}`,
upsert: true
@@ -256,8 +260,8 @@ const useJobDocuments = ({
}
// Delete from old location
- const { error: deleteError } = await carbon.storage
- .from("private")
+ const { error: deleteError } = await storage(carbon)
+ .company(company.id)
.remove([sourcePath]);
if (deleteError) {
@@ -276,7 +280,7 @@ const useJobDocuments = ({
logger.error("Failed to process file operation", { error });
}
},
- [carbon, itemId, getPath, revalidator, t]
+ [carbon, itemId, getPath, revalidator, t, company.id]
);
return {
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.ts
index fd5ec417a9..9f05f3a8ad 100644
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@ -1,6 +1,7 @@
import type { Database, Json } from "@carbon/database";
import { fetchAllFromTable, getCompanyTimeZone } from "@carbon/database";
import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+import { storage } from "@carbon/files";
import { getLogger } from "@carbon/logger";
import {
datetime,
@@ -650,18 +651,21 @@ export async function getSupplierInteractionDocuments(
companyId: string,
interactionId: string
) {
- const result = await client.storage
- .from("private")
+ const result = await storage(client)
+ .company(companyId)
.list(`${companyId}/supplier-interaction/${interactionId}`);
if (result.error) {
- logger.error("Failed to list supplier interaction documents", result.error);
+ logger.error("Failed to list supplier interaction documents", {
+ error: result.error
+ });
return [];
}
- return (
- result.data?.map((f) => ({ ...f, bucket: "supplier-interaction" })) ?? []
- );
+ return result.data.map((f) => ({
+ ...f,
+ bucket: "supplier-interaction"
+ }));
}
export async function getSupplierInteractionLineDocuments(
@@ -669,24 +673,21 @@ export async function getSupplierInteractionLineDocuments(
companyId: string,
lineId: string
) {
- const result = await client.storage
- .from("private")
+ const result = await storage(client)
+ .company(companyId)
.list(`${companyId}/supplier-interaction-line/${lineId}`);
if (result.error) {
- logger.error(
- "Failed to list supplier interaction line documents",
- result.error
- );
+ logger.error("Failed to list supplier interaction line documents", {
+ error: result.error
+ });
return [];
}
- return (
- result.data?.map((f) => ({
- ...f,
- bucket: "supplier-interaction-line"
- })) ?? []
- );
+ return result.data.map((f) => ({
+ ...f,
+ bucket: "supplier-interaction-line"
+ }));
}
export async function getSupplierLocations(
@@ -3076,11 +3077,12 @@ export async function getDefaultAttachmentsForPO(
}
const results = await Promise.all(
- prefixes.map(({ path }) => client.storage.from("private").list(path))
+ prefixes.map(({ path }) => storage(client).company(companyId).list(path))
);
return results.flatMap((result, idx) => {
const { source, path: prefix } = prefixes[idx];
+ // the union helper's structural type omits supabase's metadata field
return (result.data ?? []).map((f) => ({
source,
name: f.name,
diff --git a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierTaxForm.tsx b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierTaxForm.tsx
index 5a1731c70e..30bf6d3b4e 100644
--- a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierTaxForm.tsx
+++ b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierTaxForm.tsx
@@ -1,4 +1,5 @@
import { useCarbon } from "@carbon/auth";
+import { storage } from "@carbon/files";
import { ValidatedForm } from "@carbon/form";
import {
Button,
@@ -54,8 +55,8 @@ const SupplierTaxForm = ({ initialValues }: SupplierTaxFormProps) => {
const fileExtension = file.name.split(".").pop();
const fileName = `${companyId}/tax-certificates/${nanoid()}.${fileExtension}`;
- const result = await carbon.storage
- .from("private")
+ const result = await storage(carbon)
+ .company(companyId)
.upload(fileName, file);
if (result.error) {
diff --git a/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionDocuments.tsx b/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionDocuments.tsx
index fd2d87470c..a719c56e17 100644
--- a/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionDocuments.tsx
+++ b/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionDocuments.tsx
@@ -1,5 +1,5 @@
import { useCarbon } from "@carbon/auth";
-import { convertKbToString } from "@carbon/files";
+import { convertKbToString, storage } from "@carbon/files";
import { getLogger } from "@carbon/logger";
import {
Card,
@@ -227,19 +227,23 @@ export const useSupplierInteractionDocuments = ({
const deleteAttachment = useCallback(
async (attachment: FileObject) => {
- const result = await carbon?.storage
- .from("private")
+ if (!carbon) {
+ toast.error("Error deleting file");
+ return;
+ }
+ const { error } = await storage(carbon)
+ .company(company.id)
.remove([getPath(attachment)]);
- if (!result || result.error) {
- toast.error(result?.error?.message || "Error deleting file");
+ if (error) {
+ toast.error(error.message || "Error deleting file");
return;
}
toast.success(`${attachment.name} deleted successfully`);
revalidator.revalidate();
},
- [carbon?.storage, getPath, revalidator]
+ [carbon, getPath, revalidator, company.id]
);
const download = useCallback(
diff --git a/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionLineDocuments.tsx b/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionLineDocuments.tsx
index 2a2f522ce7..4c7f39bf31 100644
--- a/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionLineDocuments.tsx
+++ b/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionLineDocuments.tsx
@@ -1,5 +1,5 @@
import { useCarbon } from "@carbon/auth";
-import { convertKbToString } from "@carbon/files";
+import { convertKbToString, storage } from "@carbon/files";
import { getLogger } from "@carbon/logger";
import {
Card,
@@ -77,19 +77,23 @@ const useSupplierInteractionLineDocuments = ({
const deleteFile = useCallback(
async (file: ItemFile) => {
- const fileDelete = await carbon?.storage
- .from("private")
+ if (!carbon) {
+ toast.error("Error deleting file");
+ return;
+ }
+ const { error } = await storage(carbon)
+ .company(company.id)
.remove([getPath(file)]);
- if (!fileDelete || fileDelete.error) {
- toast.error(fileDelete?.error?.message || "Error deleting file");
+ if (error) {
+ toast.error(error.message || "Error deleting file");
return;
}
toast.success(`${file.name} deleted successfully`);
revalidator.revalidate();
},
- [getPath, carbon?.storage, revalidator]
+ [getPath, carbon, revalidator, company.id]
);
const download = useCallback(
diff --git a/apps/erp/app/modules/quality/quality.service.ts b/apps/erp/app/modules/quality/quality.service.ts
index 19f7d477fe..d56d1dc0f3 100644
--- a/apps/erp/app/modules/quality/quality.service.ts
+++ b/apps/erp/app/modules/quality/quality.service.ts
@@ -1,5 +1,6 @@
import type { Database, Json } from "@carbon/database";
import { fetchAllFromTable, getCompanyTimeZone } from "@carbon/database";
+import { storage } from "@carbon/files";
import { getLogger } from "@carbon/logger";
import type { JSONContent } from "@carbon/react";
import { datetime } from "@carbon/utils";
@@ -1144,10 +1145,10 @@ export async function getQualityFiles(
id: string,
companyId: string
) {
- const result = await client.storage
- .from("private")
+ const result = await storage(client)
+ .company(companyId)
.list(`${companyId}/quality/${id}`);
- return result.data || [];
+ return result.data ?? [];
}
export async function getRequiredActionsList(
diff --git a/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchNotes.tsx b/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchNotes.tsx
index 4cc7a7107a..fab5a9335f 100644
--- a/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchNotes.tsx
+++ b/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchNotes.tsx
@@ -2,7 +2,8 @@ import { useCarbon } from "@carbon/auth";
import {
convertKbToString,
downloadBlob,
- isPreviewableDocumentType
+ isPreviewableDocumentType,
+ storage
} from "@carbon/files";
import { getLogger } from "@carbon/logger";
import type { JSONContent } from "@carbon/react";
@@ -229,17 +230,19 @@ function MaintenanceFilesContent({
}
const filePath = getFilePath(file.name);
- const result = await carbon.storage.from("private").remove([filePath]);
+ const { error } = await storage(carbon)
+ .company(company.id)
+ .remove([filePath]);
- if (result.error) {
- toast.error(result.error.message || "Error deleting file");
+ if (error) {
+ toast.error(error.message || "Error deleting file");
return;
}
toast.success(t`${file.name} deleted successfully`);
revalidator.revalidate();
},
- [carbon, getFilePath, revalidator, t]
+ [carbon, company.id, getFilePath, revalidator, t]
);
const onDrop = useCallback(
diff --git a/apps/erp/app/modules/sales/sales.import.server.ts b/apps/erp/app/modules/sales/sales.import.server.ts
index f9a976c67c..c9c20145f5 100644
--- a/apps/erp/app/modules/sales/sales.import.server.ts
+++ b/apps/erp/app/modules/sales/sales.import.server.ts
@@ -1,6 +1,7 @@
import type { Database } from "@carbon/database";
import { fetchAllFromTable } from "@carbon/database";
import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+import { storage } from "@carbon/files";
import { parseCsv } from "@carbon/files/csv";
import type { SupabaseClient } from "@supabase/supabase-js";
import { itemType as sellableItemTypes } from "~/modules/shared/shared.models";
@@ -193,11 +194,13 @@ export async function importQuotes(
};
// 1. download + parse ----------------------------------------------------
- const download = await client.storage.from("private").download(filePath);
- if (download.error || !download.data) {
+ const download = await storage(client).company(companyId).download(filePath);
+ if (!download.data) {
return {
data: null,
- error: { message: download.error?.message ?? "Failed to download file" }
+ error: {
+ message: download.error.message || "Failed to download file"
+ }
};
}
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index 315f258ff0..cb2c2ff294 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -1,6 +1,7 @@
import type { Database, Json } from "@carbon/database";
import { fetchAllFromTable, getCompanyTimeZone } from "@carbon/database";
import type { Kysely, KyselyDatabase, KyselyTx } from "@carbon/database/client";
+import { storage } from "@carbon/files";
import { trackWorkEvent } from "@carbon/lib/telemetry";
import { raiseMoment } from "@carbon/lib/workflows";
import { getLogger } from "@carbon/logger";
@@ -11,6 +12,7 @@ import {
getSalesReturnOrderStatus,
round
} from "@carbon/utils";
+import type { FileObject } from "@supabase/storage-js";
import type {
PostgrestError,
PostgrestSingleResponse,
@@ -1146,8 +1148,8 @@ export async function getOpportunityDocuments(
companyId: string,
opportunityId: string
) {
- const result = await client.storage
- .from("private")
+ const result = await storage(client)
+ .company(companyId)
.list(`${companyId}/opportunity/${opportunityId}`);
if (result.error) {
@@ -1157,7 +1159,10 @@ export async function getOpportunityDocuments(
return [];
}
- return result.data?.map((f) => ({ ...f, bucket: "opportunity" })) ?? [];
+ return result.data.map((f) => ({
+ ...f,
+ bucket: "opportunity"
+ }));
}
export async function getOpportunityLineDocuments(
@@ -1167,12 +1172,12 @@ export async function getOpportunityLineDocuments(
itemId?: string | null
) {
const [opportunityLineResult, itemResult] = await Promise.all([
- client.storage
- .from("private")
+ storage(client)
+ .company(companyId)
.list(`${companyId}/opportunity-line/${lineId}`),
itemId
- ? client.storage.from("private").list(`${companyId}/parts/${itemId}`)
- : Promise.resolve({ data: [] as any[], error: null })
+ ? storage(client).company(companyId).list(`${companyId}/parts/${itemId}`)
+ : Promise.resolve({ data: [] as FileObject[], error: null })
]);
if (opportunityLineResult.error) {
@@ -1181,16 +1186,19 @@ export async function getOpportunityLineDocuments(
});
}
if (itemResult.error) {
- logger.error("Failed to list item documents", { error: itemResult.error });
+ logger.error("Failed to list item documents", {
+ error: itemResult.error
+ });
}
- const opportunityLineDocs =
- opportunityLineResult.data?.map((f) => ({
- ...f,
- bucket: "opportunity-line"
- })) ?? [];
- const itemDocs =
- itemResult.data?.map((f) => ({ ...f, bucket: "parts" })) ?? [];
+ const opportunityLineDocs = (opportunityLineResult.data ?? []).map((f) => ({
+ ...f,
+ bucket: "opportunity-line"
+ }));
+ const itemDocs = (itemResult.data ?? []).map((f) => ({
+ ...f,
+ bucket: "parts"
+ }));
return [...opportunityLineDocs, ...itemDocs];
}
diff --git a/apps/erp/app/modules/sales/ui/Customer/CustomerTaxForm.tsx b/apps/erp/app/modules/sales/ui/Customer/CustomerTaxForm.tsx
index 07b5fc3344..ce165a3660 100644
--- a/apps/erp/app/modules/sales/ui/Customer/CustomerTaxForm.tsx
+++ b/apps/erp/app/modules/sales/ui/Customer/CustomerTaxForm.tsx
@@ -1,4 +1,5 @@
import { useCarbon } from "@carbon/auth";
+import { storage } from "@carbon/files";
import { ValidatedForm } from "@carbon/form";
import {
Button,
@@ -54,8 +55,8 @@ const CustomerTaxForm = ({ initialValues }: CustomerTaxFormProps) => {
const fileExtension = file.name.split(".").pop();
const fileName = `${companyId}/tax-certificates/${nanoid()}.${fileExtension}`;
- const result = await carbon.storage
- .from("private")
+ const result = await storage(carbon)
+ .company(companyId)
.upload(fileName, file);
if (result.error) {
diff --git a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityDocuments.tsx b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityDocuments.tsx
index 348ecfdf97..c49cee15ee 100644
--- a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityDocuments.tsx
+++ b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityDocuments.tsx
@@ -1,5 +1,5 @@
import { useCarbon } from "@carbon/auth";
-import { convertKbToString } from "@carbon/files";
+import { convertKbToString, storage } from "@carbon/files";
import { getLogger } from "@carbon/logger";
import {
Badge,
@@ -318,19 +318,23 @@ export const useOpportunityDocuments = ({
const deleteAttachment = useCallback(
async (attachment: FileObject) => {
- const result = await carbon?.storage
- .from("private")
+ if (!carbon) {
+ toast.error("Error deleting file");
+ return;
+ }
+ const { error } = await storage(carbon)
+ .company(company.id)
.remove([getPath(attachment)]);
- if (!result || result.error) {
- toast.error(result?.error?.message || "Error deleting file");
+ if (error) {
+ toast.error(error.message || "Error deleting file");
return;
}
toast.success(t`${attachment.name} deleted successfully`);
revalidator.revalidate();
},
- [carbon?.storage, getPath, revalidator, t]
+ [carbon, getPath, revalidator, t, company.id]
);
const download = useCallback(
diff --git a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx
index f19645dcd7..c80eabcc7c 100644
--- a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx
+++ b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx
@@ -1,5 +1,5 @@
import { useCarbon } from "@carbon/auth";
-import { convertKbToString } from "@carbon/files";
+import { convertKbToString, storage } from "@carbon/files";
import { getLogger } from "@carbon/logger";
import {
Card,
@@ -95,19 +95,23 @@ const useOpportunityLineDocuments = ({
const deleteFile = useCallback(
async (file: FileObject & { bucket?: string }) => {
const bucket = file.bucket === "parts" ? "parts" : "opportunity-line";
- const fileDelete = await carbon?.storage
- .from("private")
+ if (!carbon) {
+ toast.error("Error deleting file");
+ return;
+ }
+ const { error } = await storage(carbon)
+ .company(company.id)
.remove([getPath(file, bucket as "opportunity-line" | "parts")]);
- if (!fileDelete || fileDelete.error) {
- toast.error(fileDelete?.error?.message || "Error deleting file");
+ if (error) {
+ toast.error(error.message || "Error deleting file");
return;
}
toast.success(t`${file.name} deleted successfully`);
revalidator.revalidate();
},
- [getPath, carbon?.storage, revalidator, t]
+ [getPath, carbon, revalidator, t, company.id]
);
const deleteModel = useCallback(
@@ -292,8 +296,8 @@ const useOpportunityLineDocuments = ({
try {
// Download the file first
const sourcePath = getPath(file, currentBucket);
- const { data: downloadData } = await carbon.storage
- .from("private")
+ const { data: downloadData } = await storage(carbon)
+ .company(company.id)
.download(sourcePath);
if (!downloadData) {
@@ -303,8 +307,8 @@ const useOpportunityLineDocuments = ({
// Upload to new location
const targetPath = getPath(file, targetBucket);
- const { error: uploadError } = await carbon.storage
- .from("private")
+ const { error: uploadError } = await storage(carbon)
+ .company(company.id)
.upload(targetPath, downloadData, {
cacheControl: `${12 * 60 * 60}`,
upsert: true
@@ -316,8 +320,8 @@ const useOpportunityLineDocuments = ({
}
// Delete from old location
- const { error: deleteError } = await carbon.storage
- .from("private")
+ const { error: deleteError } = await storage(carbon)
+ .company(company.id)
.remove([sourcePath]);
if (deleteError) {
@@ -336,7 +340,7 @@ const useOpportunityLineDocuments = ({
logger.error("Failed to process file operation", { error });
}
},
- [carbon, itemId, getPath, revalidator, t]
+ [carbon, itemId, getPath, revalidator, t, company.id]
);
return {
diff --git a/apps/erp/app/modules/settings/ui/Company/CompanyLogoForm.tsx b/apps/erp/app/modules/settings/ui/Company/CompanyLogoForm.tsx
index c39c331828..230e66d0aa 100644
--- a/apps/erp/app/modules/settings/ui/Company/CompanyLogoForm.tsx
+++ b/apps/erp/app/modules/settings/ui/Company/CompanyLogoForm.tsx
@@ -1,4 +1,5 @@
import { SUPABASE_URL, useCarbon } from "@carbon/auth";
+import { getCompanyPrivateBucket } from "@carbon/files";
import {
IMAGE_UPLOAD_MIME_TYPES,
isHeic,
@@ -101,7 +102,7 @@ const CompanyLogoForm = ({ company, target }: CompanyLogoFormProps) => {
try {
const processed = await prepareImageUpload(carbon, {
- bucket: "private",
+ bucket: getCompanyPrivateBucket(company.id ?? ""),
directory: `${company.id}/tmp`,
file: logo,
height: resizeHeight
diff --git a/apps/erp/app/modules/shared/shared.server.ts b/apps/erp/app/modules/shared/shared.server.ts
index 47ab8dffc0..841a5b0109 100644
--- a/apps/erp/app/modules/shared/shared.server.ts
+++ b/apps/erp/app/modules/shared/shared.server.ts
@@ -1,5 +1,6 @@
import type { Database } from "@carbon/database";
import { SalesOrderEmail } from "@carbon/documents/email";
+import { storage } from "@carbon/files";
import { trigger } from "@carbon/jobs";
import { redis } from "@carbon/kv";
import type { CalendarDate } from "@internationalized/date";
@@ -187,8 +188,8 @@ export async function generateAndAttachSalesOrderPdf(args: {
// 2. Upload to Supabase storage
const documentFilePath = `${companyId}/opportunity/${opportunityId}/${fileName}`;
- const uploadResult = await serviceRole.storage
- .from("private")
+ const uploadResult = await storage(serviceRole)
+ .company(companyId)
.upload(documentFilePath, file, {
cacheControl: `${12 * 60 * 60}`,
contentType: "application/pdf",
@@ -261,8 +262,8 @@ export async function generateAndAttachSalesReturnOrderPdf(
// 2. Upload to Supabase storage
const documentFilePath = `${companyId}/sales-return-order/${id}/${fileName}`;
- const uploadResult = await serviceRole.storage
- .from("private")
+ const uploadResult = await storage(serviceRole)
+ .company(companyId)
.upload(documentFilePath, file, {
cacheControl: `${12 * 60 * 60}`,
contentType: "application/pdf",
@@ -338,8 +339,8 @@ export async function generateAndAttachPurchaseReturnOrderPdf(
// 2. Upload to Supabase storage
const documentFilePath = `${companyId}/purchase-return-order/${id}/${fileName}`;
- const uploadResult = await serviceRole.storage
- .from("private")
+ const uploadResult = await storage(serviceRole)
+ .company(companyId)
.upload(documentFilePath, file, {
cacheControl: `${12 * 60 * 60}`,
contentType: "application/pdf",
@@ -470,8 +471,8 @@ export async function sendSalesOrderEmail(args: {
const html = await renderAsync(emailTemplate);
const text = await renderAsync(emailTemplate, { plainText: true });
- const { data: signedUrlData } = await serviceRole.storage
- .from("private")
+ const signed = await storage(serviceRole)
+ .company(companyId)
.createSignedUrl(documentFilePath, 3600);
await trigger("send-email", {
@@ -481,10 +482,10 @@ export async function sendSalesOrderEmail(args: {
subject: `Order ${salesOrder.data.salesOrderId} from ${company.data.name}`,
html,
text,
- attachments: signedUrlData?.signedUrl
+ attachments: signed.data
? [
{
- path: signedUrlData.signedUrl,
+ path: signed.data.signedUrl,
filename: fileName
}
]
diff --git a/apps/erp/app/modules/shared/shared.service.ts b/apps/erp/app/modules/shared/shared.service.ts
index 8e232015b2..1e572c0d73 100644
--- a/apps/erp/app/modules/shared/shared.service.ts
+++ b/apps/erp/app/modules/shared/shared.service.ts
@@ -1,5 +1,5 @@
import type { Database, Tables } from "@carbon/database";
-import { getContentType, getFileExtension } from "@carbon/files";
+import { getContentType, getFileExtension, storage } from "@carbon/files";
import type {
PostgrestResponse,
PostgrestSingleResponse,
@@ -56,10 +56,19 @@ export async function getBase64ImageFromSupabase(
const extension = getFileExtension(path);
const heic = extension === "heic" || extension === "heif";
- const { data, error } = await client.storage
- .from("private")
+ // Private object paths are prefixed with the owning company's id. A path
+ // with no leading segment has no company to resolve a bucket from, and
+ // `.company("")` throws — this function's contract is to return null on a
+ // miss, so callers would get a rejected promise instead of the fallback.
+ const companyId = path.split("/")[0];
+ if (!companyId) {
+ return null;
+ }
+
+ const { data } = await storage(client)
+ .company(companyId)
.download(path, heic ? { transform: { quality: 90 } } : undefined);
- if (error) {
+ if (!data) {
return null;
}
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
index 8e91e7806e..0652e60418 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
@@ -1266,7 +1266,7 @@
{"name":"sales_getOpenSalesOrderLinesForItem","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"334d8429d21a","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getOpportunity","classification":"READ","paramCount":1,"schema":"5e54451f6705","response":"cdaf9ce57087","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getOpportunityDocuments","classification":"READ","paramCount":1,"schema":"a4fcfa20a027","response":"18998cbb23b4","injectAuth":"companyId","permission":"sales:view","paginates":false},
- {"name":"sales_getOpportunityLineDocuments","classification":"READ","paramCount":2,"schema":"067400ea63f8","response":"5483e69d7515","injectAuth":"companyId","permission":"sales:view","paginates":false},
+ {"name":"sales_getOpportunityLineDocuments","classification":"READ","paramCount":2,"schema":"067400ea63f8","response":"18998cbb23b4","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getPricingRule","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"f7007e889f64","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getPricingRules","classification":"READ","paramCount":3,"schema":"cae7e7e05408","response":"af7bb9de307a","injectAuth":"companyId","permission":"sales:view","paginates":true},
{"name":"sales_getQuote","classification":"READ","paramCount":1,"schema":"c726ae407913","response":"ee5f623bf074","injectAuth":"companyId","permission":"sales:view","paginates":false},
diff --git a/apps/erp/app/routes/api+/model.artifacts.$modelUploadId.ts b/apps/erp/app/routes/api+/model.artifacts.$modelUploadId.ts
index f9e9f8a049..b7beb88d9e 100644
--- a/apps/erp/app/routes/api+/model.artifacts.$modelUploadId.ts
+++ b/apps/erp/app/routes/api+/model.artifacts.$modelUploadId.ts
@@ -1,6 +1,7 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { ASSEMBLER_SERVICE_URL } from "@carbon/env";
+import { getCompanyPrivateBucket } from "@carbon/files";
import type { LoaderFunctionArgs } from "react-router";
// Resolves a model's optimised / preview artifact storage paths for the
@@ -49,8 +50,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
model.data?.originalPath ??
(modelPath && !modelPath.toLowerCase().endsWith(".zst") ? modelPath : null);
const svc = getCarbonServiceRole();
+ // Durable raws live in the company's own bucket since the per-company
+ // bucket migration; pre-migration raws in legacy `private`; just-uploaded
+ // ones briefly in `temp-staging`. The row is companyId-scoped, so the
+ // session's own bucket is the right one — never derive it from the path.
+ const companyBucket = getCompanyPrivateBucket(companyId);
const exists = async (path: string) => {
- for (const bucket of ["private", "temp-staging"] as const) {
+ for (const bucket of [companyBucket, "private", "temp-staging"]) {
const info = await svc.storage
.from(bucket)
.info(path)
diff --git a/apps/erp/app/routes/api+/model.download.$modelUploadId.ts b/apps/erp/app/routes/api+/model.download.$modelUploadId.ts
index 8bd1b6e638..c6c57e251d 100644
--- a/apps/erp/app/routes/api+/model.download.$modelUploadId.ts
+++ b/apps/erp/app/routes/api+/model.download.$modelUploadId.ts
@@ -1,5 +1,6 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { getCompanyPrivateBucket } from "@carbon/files";
import { isModelRawDownloadable } from "@carbon/files/cad";
import type { LoaderFunctionArgs } from "react-router";
import { redirect } from "react-router";
@@ -43,16 +44,23 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
// compaction settles / when oversized — probe both (same resolution as the
// model.artifacts route).
const serviceRole = getCarbonServiceRole();
- const probe = (bucket: "private" | "temp-staging") =>
+ const probe = (bucket: string) =>
serviceRole.storage
.from(bucket)
.info(candidate)
.catch(() => ({ data: null, error: true as const }));
- const durable = await probe("private");
- let bucket: string | null = !durable.error && durable.data ? "private" : null;
- if (!bucket) {
- const staged = await probe("temp-staging");
- if (!staged.error && staged.data) bucket = "temp-staging";
+ // Durable raws live in the company's own bucket since the per-company bucket
+ // migration; pre-migration raws in legacy `private`; staged ones in
+ // `temp-staging`. The row is companyId-scoped, so the session's own bucket
+ // is the right one — never derive it from the path.
+ const companyBucket = getCompanyPrivateBucket(companyId);
+ let bucket: string | null = null;
+ for (const candidateBucket of [companyBucket, "private", "temp-staging"]) {
+ const found = await probe(candidateBucket);
+ if (!found.error && found.data) {
+ bucket = candidateBucket;
+ break;
+ }
}
if (!bucket) {
throw new Response("Original model file is not available", { status: 404 });
diff --git a/apps/erp/app/routes/api+/sales.digital-quote.$id.tsx b/apps/erp/app/routes/api+/sales.digital-quote.$id.tsx
index 7a11342529..8c6aadd4bb 100644
--- a/apps/erp/app/routes/api+/sales.digital-quote.$id.tsx
+++ b/apps/erp/app/routes/api+/sales.digital-quote.$id.tsx
@@ -4,6 +4,7 @@ import {
dedupeViolations,
evaluateSalesRulesForSalesDocument
} from "@carbon/ee/rules.server";
+import { storage } from "@carbon/files";
import { trigger } from "@carbon/jobs";
import { getLogger } from "@carbon/logger";
import { NotificationEvent } from "@carbon/notifications";
@@ -237,8 +238,8 @@ export async function action(args: ActionFunctionArgs) {
if (file && file instanceof File) {
const purchaseOrderDocumentPath = `${companySettings.data.id}/opportunity/${quote.data.opportunityId}/${file.name}`;
- const fileUpload = await serviceRole.storage
- .from("private")
+ const fileUpload = await storage(serviceRole)
+ .company(quote.data.companyId)
.upload(purchaseOrderDocumentPath, file);
if (fileUpload.error) {
diff --git a/apps/erp/app/routes/download.$token.tsx b/apps/erp/app/routes/download.$token.tsx
index c22aa3fcc9..be48aa402e 100644
--- a/apps/erp/app/routes/download.$token.tsx
+++ b/apps/erp/app/routes/download.$token.tsx
@@ -3,14 +3,11 @@ import {
getUserScopedClient
} from "@carbon/auth/client.server";
import { verifyDownloadToken } from "@carbon/auth/download-token.server";
+import { storage } from "@carbon/files";
import type { LoaderFunctionArgs } from "react-router";
import { redirect } from "react-router";
import { path } from "~/utils/path";
-// Documents live in the "private" storage bucket, keyed directly by `document.path`
-// (mirrors useDocument.ts).
-const DOCUMENTS_BUCKET = "private";
-
// Pure resource route (loader only, no default export): it always returns a
// Response — the file bytes on success, or a redirect to the friendly error page
// on any failure. The token is the credential; the clicker needs no Carbon login.
@@ -48,11 +45,13 @@ export async function loader({ params }: LoaderFunctionArgs) {
if (doc.error || !doc.data?.path) return fail("unavailable");
// Access already proven above; fetch the bytes with the service role.
- const file = await getCarbonServiceRole()
- .storage.from(DOCUMENTS_BUCKET)
+ // Documents live in the company's private bucket (legacy `private`
+ // fallback), keyed directly by `document.path` (mirrors useDocument.ts).
+ const file = await storage(getCarbonServiceRole())
+ .company(companyId)
.download(doc.data.path);
- if (file.error || !file.data) return fail("unavailable");
+ if (!file.data) return fail("unavailable");
// Best-effort audit log mirroring useDocument's "Download" transaction, so
// history stays consistent. Never block the download on a logging failure.
diff --git a/apps/erp/app/routes/file+/model+/public.$.tsx b/apps/erp/app/routes/file+/model+/public.$.tsx
index 9c1e6c7a70..92f2ef2090 100644
--- a/apps/erp/app/routes/file+/model+/public.$.tsx
+++ b/apps/erp/app/routes/file+/model+/public.$.tsx
@@ -1,6 +1,6 @@
import { notFound } from "@carbon/auth";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
-import { getContentType, MEDIA_CONTENT_TYPES } from "@carbon/files";
+import { getContentType, MEDIA_CONTENT_TYPES, storage } from "@carbon/files";
import { supportedModelTypes } from "@carbon/files/cad";
import { getLogger } from "@carbon/logger";
import type { LoaderFunctionArgs } from "react-router";
@@ -28,10 +28,14 @@ export async function loader({ params }: LoaderFunctionArgs) {
throw new Error(`File type ${fileType} not supported`);
const contentType = getContentType(fileType);
+ // 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).
+ const companyId = path.split("/")[0];
+
async function downloadFile() {
- const result = await client.storage.from("private").download(`${path}`);
- if (result.error) {
- logger.error(result.error);
+ const result = await storage(client).company(companyId).download(`${path}`);
+ if (!result.data) {
+ logger.error("Failed to download file", { error: result.error });
return null;
}
return result.data;
diff --git a/apps/erp/app/routes/file+/preview+/$bucket.$.tsx b/apps/erp/app/routes/file+/preview+/$bucket.$.tsx
index 579e6d32a7..97423b6a9d 100644
--- a/apps/erp/app/routes/file+/preview+/$bucket.$.tsx
+++ b/apps/erp/app/routes/file+/preview+/$bucket.$.tsx
@@ -1,6 +1,13 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
-import { effectiveExtension, getContentType } from "@carbon/files";
+import type { CompanyBucket } from "@carbon/files";
+import {
+ effectiveExtension,
+ getCompanyPrivateBucket,
+ getContentType,
+ LEGACY_PRIVATE_BUCKET,
+ storage
+} from "@carbon/files";
import { getLogger } from "@carbon/logger";
import type { LoaderFunctionArgs } from "react-router";
@@ -45,14 +52,31 @@ export let loader = async ({ request, params }: LoaderFunctionArgs) => {
return new Response(null, { status: 403 });
}
+ // `public` and `temp-staging` are shared buckets legitimately served through
+ // this route (DocumentPreview, staged CAD raw downloads); any other bucket id
+ // that isn't the caller's own company bucket (or legacy `private`) would be
+ // another tenant's private bucket — refuse it. The ownsPath check alone is
+ // not enough: a slash-bounded match allows `<otherCo>/x/<yourCo>/file`.
+ const isPrivateBucket =
+ bucket === getCompanyPrivateBucket(companyId) ||
+ bucket === LEGACY_PRIVATE_BUCKET;
+ if (!isPrivateBucket && bucket !== "public" && bucket !== "temp-staging") {
+ return new Response(null, { status: 403 });
+ }
+
const serviceRole = await getCarbonServiceRole();
+ // A company-private request reads the company bucket with legacy fallback;
+ // any other bucket is read as-is.
+ const source: Pick<CompanyBucket, "download"> = isPrivateBucket
+ ? storage(serviceRole).company(companyId)
+ : storage(serviceRole).from(bucket);
async function downloadFile() {
if (!path) throw new Error("Path not found");
if (isHeicFile) {
- const transformed = await serviceRole.storage
- .from(bucket!)
- .download(path, { transform: { quality: 85 } });
+ const transformed = await source.download(path, {
+ transform: { quality: 85 }
+ });
if (!transformed.error) {
// imgproxy may negotiate webp via Accept — trust the blob, not the path
contentType = transformed.data.type || "image/jpeg";
@@ -63,9 +87,9 @@ export let loader = async ({ request, params }: LoaderFunctionArgs) => {
logger.error(transformed.error);
}
// Use the original encoded path for the storage API call
- const result = await serviceRole.storage.from(bucket!).download(path);
+ const result = await source.download(path);
if (result.error) {
- logger.error(result.error);
+ logger.error("Failed to download file", { error: result.error });
return null;
}
return result.data;
diff --git a/apps/erp/app/routes/share+/customer.$id.$.tsx b/apps/erp/app/routes/share+/customer.$id.$.tsx
index 1ece46e6ce..d4a6f786b7 100644
--- a/apps/erp/app/routes/share+/customer.$id.$.tsx
+++ b/apps/erp/app/routes/share+/customer.$id.$.tsx
@@ -1,6 +1,11 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { companyHasFeature } from "@carbon/ee/plan.server";
-import { getContentType, MEDIA_CONTENT_TYPES } from "@carbon/files";
+import {
+ getContentType,
+ hasCompanyPrivateObjectPathPrefix,
+ MEDIA_CONTENT_TYPES,
+ storage
+} from "@carbon/files";
import { supportedModelTypes } from "@carbon/files/cad";
import { Ratelimit, redis } from "@carbon/kv";
import { getLogger } from "@carbon/logger";
@@ -42,24 +47,28 @@ export let loader = async ({ params, request }: LoaderFunctionArgs) => {
throw new Error("Customer not found");
}
- const hasPlan = await companyHasFeature(
- serviceRole,
- customer.data.companyId,
- {
- feature: "CUSTOMER_PORTALS"
- }
- );
+ // hoisted so the narrowing survives into downloadFile's closure
+ const shareCompanyId = customer.data.companyId;
+
+ const hasPlan = await companyHasFeature(serviceRole, shareCompanyId, {
+ feature: "CUSTOMER_PORTALS"
+ });
if (!hasPlan) {
return new Response(null, { status: 403 });
}
let path = params["*"];
- let bucket = "private"; // TODO: refactor to use companyId when we separate the storage buckets
if (!path) throw new Error("Path not found");
path = decodeURIComponent(path);
+ // Private objects are keyed by companyId — a path outside the portal's
+ // company must not resolve to another tenant's bucket.
+ if (!hasCompanyPrivateObjectPathPrefix(customer.data.companyId, path)) {
+ return new Response(null, { status: 404 });
+ }
+
const jobFile = parseJobFilePath(path);
const fileType = path.split(".").pop()?.toLowerCase();
@@ -94,8 +103,10 @@ export let loader = async ({ params, request }: LoaderFunctionArgs) => {
const contentType = getContentType(fileType);
async function downloadFile() {
- const result = await serviceRole.storage.from(bucket!).download(`${path}`);
- if (result.error) {
+ const result = await storage(serviceRole)
+ .company(shareCompanyId)
+ .download(`${path}`);
+ if (!result.data) {
logger.error("Failed to download file", { error: result.error });
return null;
}
diff --git a/apps/erp/app/routes/x+/customer+/$customerId.documents.tsx b/apps/erp/app/routes/x+/customer+/$customerId.documents.tsx
index fe8ab7d7bd..9a8c8ae259 100644
--- a/apps/erp/app/routes/x+/customer+/$customerId.documents.tsx
+++ b/apps/erp/app/routes/x+/customer+/$customerId.documents.tsx
@@ -1,4 +1,5 @@
import { requirePermissions } from "@carbon/auth/auth.server";
+import { storage } from "@carbon/files";
import type { LoaderFunctionArgs } from "react-router";
import { useLoaderData } from "react-router";
import RecordDocuments from "~/components/RecordDocuments";
@@ -11,8 +12,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { customerId } = params;
if (!customerId) throw new Error("Missing customerId");
- const result = await client.storage
- .from("private")
+ const result = await storage(client)
+ .company(companyId)
.list(`${companyId}/customer/${customerId}`);
return {
diff --git a/apps/erp/app/routes/x+/inspection-document+/$id.delete.tsx b/apps/erp/app/routes/x+/inspection-document+/$id.delete.tsx
index 82d3483e3e..f734769ceb 100644
--- a/apps/erp/app/routes/x+/inspection-document+/$id.delete.tsx
+++ b/apps/erp/app/routes/x+/inspection-document+/$id.delete.tsx
@@ -2,6 +2,7 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
+import { storage } from "@carbon/files";
import type {
ActionFunctionArgs,
ClientActionFunctionArgs
@@ -35,7 +36,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const storagePath = result.data?.storagePath;
if (storagePath) {
const serviceRole = await getCarbonServiceRole();
- await serviceRole.storage.from("private").remove([storagePath]);
+ await storage(serviceRole).company(companyId).remove([storagePath]);
}
throw redirect(
diff --git a/apps/erp/app/routes/x+/maintenance+/$dispatchId.tsx b/apps/erp/app/routes/x+/maintenance+/$dispatchId.tsx
index a7ab12cebe..1c0d5ba2a1 100644
--- a/apps/erp/app/routes/x+/maintenance+/$dispatchId.tsx
+++ b/apps/erp/app/routes/x+/maintenance+/$dispatchId.tsx
@@ -1,6 +1,7 @@
import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import { storage } from "@carbon/files";
import type { JSONContent } from "@carbon/react";
import { VStack } from "@carbon/react";
import { msg } from "@lingui/core/macro";
@@ -38,10 +39,10 @@ async function getMaintenanceDispatchFiles(
companyId: string,
dispatchId: string
) {
- const result = await client.storage
- .from("private")
+ const result = await storage(client)
+ .company(companyId)
.list(`${companyId}/maintenance/${dispatchId}`);
- return result.data || [];
+ return result.data ?? [];
}
export async function loader({ request, params }: LoaderFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/purchase-invoice+/new.tsx b/apps/erp/app/routes/x+/purchase-invoice+/new.tsx
index 73cb6b1795..48e12fabf3 100644
--- a/apps/erp/app/routes/x+/purchase-invoice+/new.tsx
+++ b/apps/erp/app/routes/x+/purchase-invoice+/new.tsx
@@ -2,6 +2,7 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
+import { storage } from "@carbon/files";
import { validationError, validator } from "@carbon/form";
import { deriveRate, taxableBase } from "@carbon/utils";
import { msg } from "@lingui/core/macro";
@@ -203,8 +204,8 @@ export async function action({ request }: ActionFunctionArgs) {
const safeFilename = stripSpecialCharacters(originalFilename);
const newStoragePath = `${companyId}/supplier-interaction/${interactionId}/${safeFilename}`;
- const copyResult = await client.storage
- .from("private")
+ const copyResult = await storage(client)
+ .company(companyId)
.copy(extractedStoragePath, newStoragePath);
if (!copyResult.error) {
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
index b773b20438..cf26150d8a 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
@@ -11,6 +11,7 @@ import {
hasPendingApproval,
isApprovalRequired
} from "@carbon/ee/approvals.server";
+import { storage } from "@carbon/files";
import { validationError, validator } from "@carbon/form";
import { trigger } from "@carbon/jobs";
import { trackWorkEvent } from "@carbon/lib/telemetry";
@@ -245,8 +246,8 @@ export async function action(args: ActionFunctionArgs) {
documentFilePath = `${companyId}/supplier-interaction/${purchaseOrder.data.supplierInteractionId}/${fileName}`;
- const documentFileUpload = await serviceRole.storage
- .from("private")
+ const documentFileUpload = await storage(serviceRole)
+ .company(companyId)
.upload(documentFilePath, file, {
cacheControl: `${12 * 60 * 60}`,
contentType: "application/pdf",
@@ -379,13 +380,18 @@ export async function action(args: ActionFunctionArgs) {
);
for (const doc of docs) {
const storagePath = `${companyId}/supplier-interaction/${interactionId}/${doc.name}`;
- const { data: signedUrlData } = await serviceRole.storage
- .from("private")
+ const { data, error } = await storage(serviceRole)
+ .company(companyId)
.createSignedUrl(storagePath, 3600);
- if (signedUrlData?.signedUrl) {
+ if (data) {
attachments.push({
filename: doc.name,
- path: signedUrlData.signedUrl
+ path: data.signedUrl
+ });
+ } else {
+ logger.error("Failed to create signed URL for attachment", {
+ storagePath,
+ error
});
}
}
@@ -405,13 +411,18 @@ export async function action(args: ActionFunctionArgs) {
});
for (const r of defaults) {
- const { data: signedUrlData } = await serviceRole.storage
- .from("private")
+ const { data, error } = await storage(serviceRole)
+ .company(companyId)
.createSignedUrl(r.path, 3600);
- if (signedUrlData?.signedUrl) {
+ if (data) {
attachments.push({
filename: r.name,
- path: signedUrlData.signedUrl
+ path: data.signedUrl
+ });
+ } else {
+ logger.error("Failed to create signed URL for attachment", {
+ storagePath: r.path,
+ error
});
}
}
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
index 829ba9b349..dbbd582eb7 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
@@ -12,6 +12,7 @@ import {
getLowerTierApproverUserIds,
rejectRequest
} from "@carbon/ee/approvals.server";
+import { storage } from "@carbon/files";
import { validationError, validator } from "@carbon/form";
import { trigger } from "@carbon/jobs";
import { getLogger } from "@carbon/logger";
@@ -221,8 +222,8 @@ export async function action(args: ActionFunctionArgs) {
documentFilePath = `${companyId}/supplier-interaction/${purchaseOrder.data.supplierInteractionId}/${fileName}`;
- const documentFileUpload = await serviceRole.storage
- .from("private")
+ const documentFileUpload = await storage(serviceRole)
+ .company(companyId)
.upload(documentFilePath, file, {
cacheControl: `${12 * 60 * 60}`,
contentType: "application/pdf",
@@ -318,9 +319,15 @@ export async function action(args: ActionFunctionArgs) {
const html = await renderAsync(emailTemplate);
const text = await renderAsync(emailTemplate, { plainText: true });
- const { data: signedUrlData } = await serviceRole.storage
- .from("private")
+ const signed = await storage(serviceRole)
+ .company(companyId)
.createSignedUrl(documentFilePath!, 3600);
+ if (signed.error) {
+ logger.error("Failed to create signed URL for attachment", {
+ storagePath: documentFilePath,
+ error: signed.error
+ });
+ }
await trigger("send-email", {
to: [buyer.data.email, supplierEmail],
@@ -329,10 +336,10 @@ export async function action(args: ActionFunctionArgs) {
subject: `Purchase Order ${getPurchaseOrderDisplayId(purchaseOrder.data)} from ${company.data.name}`,
html,
text,
- attachments: signedUrlData?.signedUrl
+ attachments: signed.data
? [
{
- path: signedUrlData.signedUrl,
+ path: signed.data.signedUrl,
filename: fileName!
}
]
diff --git a/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.finalize.tsx b/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.finalize.tsx
index 8cc1797992..6ec015ecdb 100644
--- a/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.finalize.tsx
+++ b/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.finalize.tsx
@@ -1,6 +1,7 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import { storage } from "@carbon/files";
import { validationError, validator } from "@carbon/form";
import { trigger } from "@carbon/jobs";
import { getLogger } from "@carbon/logger";
@@ -240,12 +241,17 @@ export async function action({ request, params }: ActionFunctionArgs) {
for (const doc of rfqDocs) {
const storagePath = `${companyId}/supplier-interaction/${rfqId}/${doc.name}`;
- const { data: signedUrlData } = await client.storage
- .from("private")
+ const { data, error } = await storage(client)
+ .company(companyId)
.createSignedUrl(storagePath, 3600);
- if (signedUrlData?.signedUrl) {
- attachments.push({ filename: doc.name, path: signedUrlData.signedUrl });
+ if (data) {
+ attachments.push({ filename: doc.name, path: data.signedUrl });
+ } else {
+ logger.error("Failed to create signed URL for attachment", {
+ storagePath,
+ error
+ });
}
}
@@ -261,14 +267,19 @@ export async function action({ request, params }: ActionFunctionArgs) {
for (const doc of lineDocs) {
const storagePath = `${companyId}/supplier-interaction-line/${line.id}/${doc.name}`;
- const { data: signedUrlData } = await client.storage
- .from("private")
+ const { data, error } = await storage(client)
+ .company(companyId)
.createSignedUrl(storagePath, 3600);
- if (signedUrlData?.signedUrl) {
+ if (data) {
attachments.push({
filename: doc.name,
- path: signedUrlData.signedUrl
+ path: data.signedUrl
+ });
+ } else {
+ logger.error("Failed to create signed URL for attachment", {
+ storagePath,
+ error
});
}
}
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.drag.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.drag.tsx
index dd0c4b8d77..9c91445cd7 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.drag.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.drag.tsx
@@ -3,6 +3,7 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
+import { storage } from "@carbon/files";
import { supportedModelTypes } from "@carbon/files/cad";
import { trigger } from "@carbon/jobs";
import { getLogger } from "@carbon/logger";
@@ -266,8 +267,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
// Relocate the raw across buckets: attachments live in `private`, but raw
// models must land in `temp-staging` (2.5 GB) for the optimise/assembly jobs
// to read (Supabase has no cross-bucket move).
- const raw = await client.storage.from("private").download(documentPath);
- if (raw.error) {
+ const raw = await storage(client).company(companyId).download(documentPath);
+ if (!raw.data) {
throw redirect(
path.to.quote(quoteId),
await flash(request, error(raw.error, "Failed to read model file"))
@@ -282,7 +283,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
await flash(request, error(staged.error, "Failed to stage model file"))
);
}
- await client.storage.from("private").remove([documentPath]);
+ await storage(client).company(companyId).remove([documentPath]);
// Thumbnail is generated by model-optimize on success (renders the GLB).
await trigger("model-optimize", {
@@ -293,8 +294,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
} else {
newPath = `${companyId}/opportunity-line/${targetLineId}/${fileName}`;
// Move the file to the new path
- const move = await client.storage
- .from("private")
+ const move = await storage(client)
+ .company(companyId)
.move(documentPath, newPath);
if (move.error) {
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx
index 734e12898a..ea076221c5 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx
@@ -9,9 +9,12 @@ import {
evaluateSalesRulesForSalesDocument,
isBlocked
} from "@carbon/ee/rules.server";
+import { storage } from "@carbon/files";
import { validationError, validator } from "@carbon/form";
import { trigger } from "@carbon/jobs";
-import { datetime, type Violation } from "@carbon/utils";
+import { getLogger } from "@carbon/logger";
+import type { Violation } from "@carbon/utils";
+import { datetime } from "@carbon/utils";
import { renderAsync } from "@react-email/components";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
@@ -31,6 +34,8 @@ import { loader as pdfLoader } from "~/routes/file+/quote+/$id[.]pdf";
import { path } from "~/utils/path";
import { stripSpecialCharacters } from "~/utils/string";
+const logger = getLogger("erp", "quote", "finalize");
+
export async function action(args: ActionFunctionArgs) {
const { request, params } = args;
assertIsPost(request);
@@ -138,8 +143,8 @@ export async function action(args: ActionFunctionArgs) {
documentFilePath = `${companyId}/opportunity/${quote.data.opportunityId}/${fileName}`;
- const documentFileUpload = await client.storage
- .from("private")
+ const documentFileUpload = await storage(client)
+ .company(companyId)
.upload(documentFilePath, file, {
cacheControl: `${12 * 60 * 60}`,
contentType: "application/pdf",
@@ -263,9 +268,15 @@ export async function action(args: ActionFunctionArgs) {
const html = await renderAsync(emailTemplate);
const text = await renderAsync(emailTemplate, { plainText: true });
- const { data: signedUrlData } = await client.storage
- .from("private")
+ const signed = await storage(client)
+ .company(companyId)
.createSignedUrl(documentFilePath, 3600);
+ if (signed.error) {
+ logger.error("Failed to create signed URL for attachment", {
+ storagePath: documentFilePath,
+ error: signed.error
+ });
+ }
await trigger("send-email", {
to: [user.data.email, customerContact.data.contact!.email!],
@@ -274,10 +285,10 @@ export async function action(args: ActionFunctionArgs) {
subject: `Quote ${getQuoteDisplayId(quote.data)}`,
html,
text,
- attachments: signedUrlData?.signedUrl
+ attachments: signed.data
? [
{
- path: signedUrlData.signedUrl,
+ path: signed.data.signedUrl,
filename: fileName
}
]
diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx
index acaa95fa46..935189d2e3 100644
--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx
+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx
@@ -9,6 +9,7 @@ import {
evaluateSalesRulesForSalesDocument,
isBlocked
} from "@carbon/ee/rules.server";
+import { storage } from "@carbon/files";
import { validator } from "@carbon/form";
import { trigger } from "@carbon/jobs";
import { trackWorkEvent } from "@carbon/lib/telemetry";
@@ -92,8 +93,8 @@ async function storeStripeInvoicePdf({
);
const filePath = `${companyId}/opportunity/${opportunityId}/${fileName}`;
- const upload = await serviceRole.storage
- .from("private")
+ const upload = await storage(serviceRole)
+ .company(companyId)
.upload(filePath, file, {
cacheControl: `${12 * 60 * 60}`,
contentType: "application/pdf",
@@ -749,8 +750,8 @@ export async function action(args: ActionFunctionArgs) {
documentFilePath = `${companyId}/opportunity/${salesInvoice.data.opportunityId}/${fileName}`;
- const documentFileUpload = await serviceRole.storage
- .from("private")
+ const documentFileUpload = await storage(serviceRole)
+ .company(companyId)
.upload(documentFilePath, file, {
cacheControl: `${12 * 60 * 60}`,
contentType: "application/pdf",
@@ -897,9 +898,15 @@ export async function action(args: ActionFunctionArgs) {
const html = await renderAsync(emailTemplate);
const text = await renderAsync(emailTemplate, { plainText: true });
- const { data: signedUrlData } = await serviceRole.storage
- .from("private")
+ const signed = await storage(serviceRole)
+ .company(companyId)
.createSignedUrl(documentFilePath, 3600);
+ if (signed.error) {
+ logger.error("Failed to create signed URL for attachment", {
+ storagePath: documentFilePath,
+ error: signed.error
+ });
+ }
await trigger("send-email", {
to: [seller.data.email, customer.data.contact.email!],
@@ -908,10 +915,10 @@ export async function action(args: ActionFunctionArgs) {
subject: `Invoice ${salesInvoice.data.invoiceId} from ${company.data.name}`,
html,
text,
- attachments: signedUrlData?.signedUrl
+ attachments: signed.data
? [
{
- path: signedUrlData.signedUrl,
+ path: signed.data.signedUrl,
filename: fileName
}
]
diff --git a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.drag.tsx b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.drag.tsx
index 82b637c9f7..feb17677a0 100644
--- a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.drag.tsx
+++ b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.drag.tsx
@@ -1,6 +1,7 @@
import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import { storage } from "@carbon/files";
import { trigger } from "@carbon/jobs";
import { nanoid } from "nanoid";
import type { ActionFunctionArgs } from "react-router";
@@ -121,8 +122,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
// Relocate the raw across buckets: attachments live in `private`, but raw
// models must land in `temp-staging` (2.5 GB) for the optimise/assembly jobs
// to read (Supabase has no cross-bucket move).
- const raw = await client.storage.from("private").download(documentPath);
- if (raw.error) {
+ const raw = await storage(client).company(companyId).download(documentPath);
+ if (!raw.data) {
throw redirect(
path.to.salesRfqDetails(rfqId),
await flash(request, error(raw.error, "Failed to read model file"))
@@ -137,7 +138,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
await flash(request, error(staged.error, "Failed to stage model file"))
);
}
- await client.storage.from("private").remove([documentPath]);
+ await storage(client).company(companyId).remove([documentPath]);
// Thumbnail is generated by model-optimize on success (renders the GLB).
await trigger("model-optimize", {
@@ -148,8 +149,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
} else {
newPath = `${companyId}/opportunity-line/${targetLineId}/${fileName}`;
// Move the file to the new path
- const move = await client.storage
- .from("private")
+ const move = await storage(client)
+ .company(companyId)
.move(documentPath, newPath);
if (move.error) {
diff --git a/apps/erp/app/routes/x+/sales-rfq+/new.tsx b/apps/erp/app/routes/x+/sales-rfq+/new.tsx
index 2a98afc0c5..a92a776508 100644
--- a/apps/erp/app/routes/x+/sales-rfq+/new.tsx
+++ b/apps/erp/app/routes/x+/sales-rfq+/new.tsx
@@ -1,6 +1,7 @@
import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import { storage } from "@carbon/files";
import { validationError, validator } from "@carbon/form";
import { msg } from "@lingui/core/macro";
import type { ActionFunctionArgs } from "react-router";
@@ -122,8 +123,8 @@ export async function action({ request }: ActionFunctionArgs) {
const safeFilename = stripSpecialCharacters(originalFilename);
const newStoragePath = `${companyId}/opportunity/${opportunityId}/${safeFilename}`;
- const copyResult = await client.storage
- .from("private")
+ const copyResult = await storage(client)
+ .company(companyId)
.copy(extractedStoragePath, newStoragePath);
if (!copyResult.error) {
diff --git a/apps/erp/app/routes/x+/settings+/purchasing.tsx b/apps/erp/app/routes/x+/settings+/purchasing.tsx
index da3b0aae19..a43beed4eb 100644
--- a/apps/erp/app/routes/x+/settings+/purchasing.tsx
+++ b/apps/erp/app/routes/x+/settings+/purchasing.tsx
@@ -1,6 +1,7 @@
import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import { storage } from "@carbon/files";
import {
Input,
PhoneInput,
@@ -69,8 +70,8 @@ export async function loader({ request }: LoaderFunctionArgs) {
await Promise.all([
getCompanySettings(client, companyId),
getAccountsPayableBillingAddress(client, companyId),
- client.storage
- .from("private")
+ storage(client)
+ .company(companyId)
.list(`${companyId}/default-attachments/company`)
]);
diff --git a/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx b/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx
index 404357a411..44f45a20db 100644
--- a/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx
+++ b/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx
@@ -9,6 +9,7 @@ import {
isBlocked,
resolveSalesOrderShipTo
} from "@carbon/ee/rules.server";
+import { storage } from "@carbon/files";
import { trigger } from "@carbon/jobs";
import { trackWorkEvent } from "@carbon/lib/telemetry";
import { raiseMoment } from "@carbon/lib/workflows";
@@ -307,8 +308,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
const documentFilePath = `${companyId}/opportunity/${salesOrder.opportunityId}/${fileName}`;
// Upload the PDF to storage
- const documentFileUpload = await serviceRole.storage
- .from("private")
+ const documentFileUpload = await storage(serviceRole)
+ .company(companyId)
.upload(documentFilePath, file, {
cacheControl: `${12 * 60 * 60}`,
contentType: "application/pdf",
diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.default-attachments.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.default-attachments.tsx
index 67b9b488b5..e00dc08d05 100644
--- a/apps/erp/app/routes/x+/supplier+/$supplierId.default-attachments.tsx
+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.default-attachments.tsx
@@ -1,5 +1,7 @@
import { requirePermissions } from "@carbon/auth/auth.server";
+import { storage } from "@carbon/files";
import { Trans } from "@lingui/react/macro";
+import type { FileObject } from "@supabase/storage-js";
import type { LoaderFunctionArgs } from "react-router";
import { useLoaderData } from "react-router";
import DefaultAttachmentsPanel from "~/components/DefaultAttachmentsPanel";
@@ -11,13 +13,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { supplierId } = params;
if (!supplierId) throw new Error("Missing supplierId");
- const result = await client.storage
- .from("private")
+ const result = await storage(client)
+ .company(companyId)
.list(`${companyId}/default-attachments/supplier/${supplierId}`);
return {
supplierId,
- files: result.data ?? []
+ // the union helper's structural type omits supabase's FileObject fields
+ files: (result.data ?? []) as FileObject[]
};
}
diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.documents.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.documents.tsx
index 6cffeb7942..b637dfc693 100644
--- a/apps/erp/app/routes/x+/supplier+/$supplierId.documents.tsx
+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.documents.tsx
@@ -1,4 +1,5 @@
import { requirePermissions } from "@carbon/auth/auth.server";
+import { storage } from "@carbon/files";
import type { LoaderFunctionArgs } from "react-router";
import { useLoaderData } from "react-router";
import RecordDocuments from "~/components/RecordDocuments";
@@ -11,8 +12,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { supplierId } = params;
if (!supplierId) throw new Error("Missing supplierId");
- const result = await client.storage
- .from("private")
+ const result = await storage(client)
+ .company(companyId)
.list(`${companyId}/supplier/${supplierId}`);
return {
diff --git a/apps/erp/app/routes/x+/supplier-quote+/$id.send.tsx b/apps/erp/app/routes/x+/supplier-quote+/$id.send.tsx
index 04e7f9d33f..e38e163d77 100644
--- a/apps/erp/app/routes/x+/supplier-quote+/$id.send.tsx
+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.send.tsx
@@ -1,8 +1,10 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import { storage } from "@carbon/files";
import { validationError, validator } from "@carbon/form";
import { trigger } from "@carbon/jobs";
+import { getLogger } from "@carbon/logger";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import {
@@ -19,6 +21,8 @@ import { upsertExternalLink } from "~/modules/shared";
import { getUser } from "~/modules/users/users.server";
import { path } from "~/utils/path";
+const logger = getLogger("erp", "supplier-quote", "send");
+
export async function action(args: ActionFunctionArgs) {
const { request, params } = args;
assertIsPost(request);
@@ -122,14 +126,19 @@ export async function action(args: ActionFunctionArgs) {
for (const doc of topDocs) {
const storagePath = `${companyId}/supplier-interaction/${interactionId}/${doc.name}`;
- const { data: signedUrlData } = await client.storage
- .from("private")
+ const { data, error } = await storage(client)
+ .company(companyId)
.createSignedUrl(storagePath, 3600);
- if (signedUrlData?.signedUrl) {
+ if (data) {
attachments.push({
filename: doc.name,
- path: signedUrlData.signedUrl
+ path: data.signedUrl
+ });
+ } else {
+ logger.error("Failed to create signed URL for attachment", {
+ storagePath,
+ error
});
}
}
@@ -148,14 +157,19 @@ export async function action(args: ActionFunctionArgs) {
for (const doc of docs) {
const storagePath = `${companyId}/supplier-interaction-line/${line.id}/${doc.name}`;
- const { data: signedUrlData } = await client.storage
- .from("private")
+ const { data, error } = await storage(client)
+ .company(companyId)
.createSignedUrl(storagePath, 3600);
- if (signedUrlData?.signedUrl) {
+ if (data) {
attachments.push({
filename: doc.name,
- path: signedUrlData.signedUrl
+ path: data.signedUrl
+ });
+ } else {
+ logger.error("Failed to create signed URL for attachment", {
+ storagePath,
+ error
});
}
}
diff --git a/apps/mes/app/components/FileDropzone.tsx b/apps/mes/app/components/FileDropzone.tsx
index dac1464536..55bea62824 100644
--- a/apps/mes/app/components/FileDropzone.tsx
+++ b/apps/mes/app/components/FileDropzone.tsx
@@ -1,4 +1,5 @@
import { useCarbon } from "@carbon/auth";
+import { getCompanyPrivateBucket } from "@carbon/files";
import { isHeic, MediaUploader } from "@carbon/files/media";
import { cn, toast } from "@carbon/react";
import { Trans, useLingui } from "@lingui/react/macro";
@@ -23,7 +24,7 @@ const FileDropzone: React.FC<FileDropzoneProps> = ({ onDrop }) => {
let files = acceptedFiles;
if (carbon && files.some((file) => isHeic(file.name, file.type))) {
const uploader = new MediaUploader(carbon, {
- bucket: "private",
+ bucket: getCompanyPrivateBucket(company.id),
directory: `${company.id}/tmp`
});
setIsConverting(true);
diff --git a/apps/mes/app/components/JobOperation/components/BatchRecordModal.tsx b/apps/mes/app/components/JobOperation/components/BatchRecordModal.tsx
index e573832aed..8fe13dcc58 100644
--- a/apps/mes/app/components/JobOperation/components/BatchRecordModal.tsx
+++ b/apps/mes/app/components/JobOperation/components/BatchRecordModal.tsx
@@ -1,4 +1,5 @@
import { useCarbon } from "@carbon/auth";
+import { storage } from "@carbon/files";
import {
Button,
Checkbox,
@@ -130,8 +131,8 @@ export function BatchRecordModal({
const safeName = stripSpecialCharacters(file.name) || "file";
const uploads = await Promise.all(
changed.map((m) =>
- carbon.storage
- .from("private")
+ storage(carbon)
+ .company(company.id)
.upload(
`${company.id}/job/${m.jobOperationId}/${m.stepId}/${nanoid()}/${safeName}`,
file,
diff --git a/apps/mes/app/components/JobOperation/components/Step.tsx b/apps/mes/app/components/JobOperation/components/Step.tsx
index 9174b98c5d..8bfa12a206 100644
--- a/apps/mes/app/components/JobOperation/components/Step.tsx
+++ b/apps/mes/app/components/JobOperation/components/Step.tsx
@@ -1,4 +1,5 @@
import { useCarbon } from "@carbon/auth";
+import { storage } from "@carbon/files";
import {
Combobox,
DateTimePicker,
@@ -509,8 +510,8 @@ export function RecordModal({
const safeName = stripSpecialCharacters(fileUpload.name) || "file";
const fileName = `${company.id}/job/${attribute.operationId}/${attribute.id}/${nanoid()}/${safeName}`;
- const upload = await carbon?.storage
- .from("private")
+ const upload = await storage(carbon)
+ .company(company.id)
.upload(fileName, fileUpload, {
cacheControl: `${12 * 60 * 60}`,
upsert: true
diff --git a/apps/mes/app/components/Suggestion.tsx b/apps/mes/app/components/Suggestion.tsx
index 329464a602..634da7fcec 100644
--- a/apps/mes/app/components/Suggestion.tsx
+++ b/apps/mes/app/components/Suggestion.tsx
@@ -1,4 +1,5 @@
import { CARBON_SLACK_ENABLED, useCarbon } from "@carbon/auth";
+import { getCompanyPrivateBucket, storage } from "@carbon/files";
import { convertHeicToJpeg, isHeic } from "@carbon/files/media";
import {
Hidden,
@@ -96,7 +97,7 @@ const Suggestion = () => {
if (isHeic(file.name, file.type)) {
try {
file = await convertHeicToJpeg(carbon, {
- bucket: "private",
+ bucket: getCompanyPrivateBucket(companyId),
directory: `${companyId}/tmp`,
file
});
@@ -108,8 +109,8 @@ const Suggestion = () => {
const fileExtension = file.name.substring(file.name.lastIndexOf(".") + 1);
const fileName = `${companyId}/suggestions/${nanoid()}.${fileExtension}`;
- const imageUpload = await carbon.storage
- .from("private")
+ const imageUpload = await storage(carbon)
+ .company(companyId)
.upload(fileName, file, {
cacheControl: `${12 * 60 * 60}`,
upsert: true
diff --git a/apps/mes/app/hooks/useImageUpload.ts b/apps/mes/app/hooks/useImageUpload.ts
index 87e0e57e45..4e1485470c 100644
--- a/apps/mes/app/hooks/useImageUpload.ts
+++ b/apps/mes/app/hooks/useImageUpload.ts
@@ -1,4 +1,5 @@
import { useCarbon } from "@carbon/auth";
+import { getCompanyPrivateBucket, storage } from "@carbon/files";
import { isHeic, MediaUploader } from "@carbon/files/media";
import { toast } from "@carbon/react";
import { useLingui } from "@lingui/react/macro";
@@ -22,7 +23,7 @@ export function useImageUpload(directory: string) {
() =>
carbon
? new MediaUploader(carbon, {
- bucket: "private",
+ bucket: getCompanyPrivateBucket(company.id),
directory: `${company.id}/tmp`
})
: null,
@@ -46,8 +47,8 @@ export function useImageUpload(directory: string) {
const fileType = upload.name.split(".").pop();
const fileName = `${company.id}/${directory}/${nanoid()}.${fileType}`;
- const result = await carbon.storage
- .from("private")
+ const result = await storage(carbon)
+ .company(company.id)
.upload(fileName, upload);
if (result.error) {
diff --git a/apps/mes/app/routes/api+/model.artifacts.$modelUploadId.ts b/apps/mes/app/routes/api+/model.artifacts.$modelUploadId.ts
index 82bf833363..bac4dea56d 100644
--- a/apps/mes/app/routes/api+/model.artifacts.$modelUploadId.ts
+++ b/apps/mes/app/routes/api+/model.artifacts.$modelUploadId.ts
@@ -1,6 +1,7 @@
import { ASSEMBLER_SERVICE_URL } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { getCompanyPrivateBucket } from "@carbon/files";
import type { LoaderFunctionArgs } from "react-router";
// Resolves a model's optimised / preview artifact storage paths for the
@@ -48,8 +49,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
model.data?.originalPath ??
(modelPath && !modelPath.toLowerCase().endsWith(".zst") ? modelPath : null);
const svc = getCarbonServiceRole();
+ // Durable raws live in the company's own bucket since the per-company
+ // bucket migration; pre-migration raws in legacy `private`; just-uploaded
+ // ones briefly in `temp-staging`. The row is companyId-scoped, so the
+ // session's own bucket is the right one — never derive it from the path.
+ const companyBucket = getCompanyPrivateBucket(companyId);
const exists = async (path: string) => {
- for (const bucket of ["private", "temp-staging"] as const) {
+ for (const bucket of [companyBucket, "private", "temp-staging"]) {
const info = await svc.storage
.from(bucket)
.info(path)
diff --git a/apps/mes/app/routes/api+/model.download.$modelUploadId.ts b/apps/mes/app/routes/api+/model.download.$modelUploadId.ts
index 8bd1b6e638..c6c57e251d 100644
--- a/apps/mes/app/routes/api+/model.download.$modelUploadId.ts
+++ b/apps/mes/app/routes/api+/model.download.$modelUploadId.ts
@@ -1,5 +1,6 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { getCompanyPrivateBucket } from "@carbon/files";
import { isModelRawDownloadable } from "@carbon/files/cad";
import type { LoaderFunctionArgs } from "react-router";
import { redirect } from "react-router";
@@ -43,16 +44,23 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
// compaction settles / when oversized — probe both (same resolution as the
// model.artifacts route).
const serviceRole = getCarbonServiceRole();
- const probe = (bucket: "private" | "temp-staging") =>
+ const probe = (bucket: string) =>
serviceRole.storage
.from(bucket)
.info(candidate)
.catch(() => ({ data: null, error: true as const }));
- const durable = await probe("private");
- let bucket: string | null = !durable.error && durable.data ? "private" : null;
- if (!bucket) {
- const staged = await probe("temp-staging");
- if (!staged.error && staged.data) bucket = "temp-staging";
+ // Durable raws live in the company's own bucket since the per-company bucket
+ // migration; pre-migration raws in legacy `private`; staged ones in
+ // `temp-staging`. The row is companyId-scoped, so the session's own bucket
+ // is the right one — never derive it from the path.
+ const companyBucket = getCompanyPrivateBucket(companyId);
+ let bucket: string | null = null;
+ for (const candidateBucket of [companyBucket, "private", "temp-staging"]) {
+ const found = await probe(candidateBucket);
+ if (!found.error && found.data) {
+ bucket = candidateBucket;
+ break;
+ }
}
if (!bucket) {
throw new Response("Original model file is not available", { status: 404 });
diff --git a/apps/mes/app/routes/file+/preview+/$bucket.$.tsx b/apps/mes/app/routes/file+/preview+/$bucket.$.tsx
index 9a099d91e5..400515efef 100644
--- a/apps/mes/app/routes/file+/preview+/$bucket.$.tsx
+++ b/apps/mes/app/routes/file+/preview+/$bucket.$.tsx
@@ -1,6 +1,13 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
-import { effectiveExtension, getContentType } from "@carbon/files";
+import type { CompanyBucket } from "@carbon/files";
+import {
+ effectiveExtension,
+ getCompanyPrivateBucket,
+ getContentType,
+ LEGACY_PRIVATE_BUCKET,
+ storage
+} from "@carbon/files";
import { getLogger } from "@carbon/logger";
import type { LoaderFunctionArgs } from "react-router";
@@ -45,14 +52,31 @@ export let loader = async ({ request, params }: LoaderFunctionArgs) => {
return new Response(null, { status: 403 });
}
+ // `public` and `temp-staging` are shared buckets legitimately served through
+ // this route (file previews, staged CAD raw downloads); any other bucket id
+ // that isn't the caller's own company bucket (or legacy `private`) would be
+ // another tenant's private bucket — refuse it. The ownsPath check alone is
+ // not enough: a slash-bounded match allows `<otherCo>/x/<yourCo>/file`.
+ const isPrivateBucket =
+ bucket === getCompanyPrivateBucket(companyId) ||
+ bucket === LEGACY_PRIVATE_BUCKET;
+ if (!isPrivateBucket && bucket !== "public" && bucket !== "temp-staging") {
+ return new Response(null, { status: 403 });
+ }
+
const serviceRole = await getCarbonServiceRole();
+ // A company-private request reads the company bucket with legacy fallback;
+ // any other bucket is read as-is.
+ const source: Pick<CompanyBucket, "download"> = isPrivateBucket
+ ? storage(serviceRole).company(companyId)
+ : storage(serviceRole).from(bucket);
async function downloadFile() {
if (!path) throw new Error("Path not found");
if (isHeicFile) {
- const transformed = await serviceRole.storage
- .from(bucket!)
- .download(path, { transform: { quality: 85 } });
+ const transformed = await source.download(path, {
+ transform: { quality: 85 }
+ });
if (!transformed.error) {
// imgproxy may negotiate webp via Accept — trust the blob, not the path
contentType = transformed.data.type || "image/jpeg";
@@ -63,7 +87,7 @@ export let loader = async ({ request, params }: LoaderFunctionArgs) => {
log.error("Failed to transform HEIC file", { error: transformed.error });
}
// Use the original encoded path for the storage API call
- const result = await serviceRole.storage.from(bucket!).download(path);
+ const result = await source.download(path);
if (result.error) {
log.error("Failed to download file", { error: result.error });
return null;
diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.ts
index 02638d3ea0..c9b61ddcc8 100644
--- a/apps/mes/app/services/operations.service.ts
+++ b/apps/mes/app/services/operations.service.ts
@@ -1,5 +1,6 @@
import type { Database, Json } from "@carbon/database";
import { activeJobStatuses, getCompanyTimeZone } from "@carbon/database";
+import { storage } from "@carbon/files";
import type { WorkSource } from "@carbon/lib/telemetry";
import { trackWorkEvent } from "@carbon/lib/telemetry";
import { raiseMoment } from "@carbon/lib/workflows";
@@ -681,13 +682,19 @@ const getItemFiles = async (
items: Array<{ itemId: string }>
) => {
const getFile = async (id: string) => {
- const res = await client.storage
- .from("private")
+ const res = await storage(client)
+ .company(companyId)
.list(`${companyId}/parts/${id}`);
- if (res.error || !res.data) return null;
+ if (!res.data?.length) return null;
- return res.data.map((f) => ({ ...f, bucket: "parts", itemId: id }));
+ return res.data.map(
+ (f): StorageItem => ({
+ ...f,
+ bucket: "parts",
+ itemId: id
+ })
+ );
};
const elems = items.map((el) => getFile(el.itemId));
@@ -707,30 +714,30 @@ export async function getJobFiles(
const opportunityLine = job.salesOrderLineId || job.quoteLineId;
const [opportunityLineFiles, jobFiles, itemFiles] = await Promise.all([
- client.storage
- .from("private")
+ storage(client)
+ .company(companyId)
.list(`${companyId}/opportunity-line/${opportunityLine}`),
- client.storage.from("private").list(`${companyId}/job/${job.id}`),
+ storage(client).company(companyId).list(`${companyId}/job/${job.id}`),
getItemFiles(client, companyId, items)
]);
// Combine and return both sets of files
return [
- ...(opportunityLineFiles.data?.map((f) => ({
+ ...(opportunityLineFiles.data ?? []).map((f) => ({
...f,
bucket: "opportunity-line"
- })) || []),
- ...(jobFiles.data?.map((f) => ({ ...f, bucket: "job" })) || []),
+ })),
+ ...(jobFiles.data ?? []).map((f) => ({ ...f, bucket: "job" })),
...itemFiles
];
} else {
const [jobFiles, itemFiles] = await Promise.all([
- client.storage.from("private").list(`${companyId}/job/${job.id}`),
+ storage(client).company(companyId).list(`${companyId}/job/${job.id}`),
getItemFiles(client, companyId, items)
]);
return [
- ...(jobFiles.data?.map((f) => ({ ...f, bucket: "job" })) || []),
+ ...(jobFiles.data ?? []).map((f) => ({ ...f, bucket: "job" })),
...itemFiles
];
}
@@ -991,7 +998,9 @@ export async function getBatchWorkInstructions(
Promise.all(
jobs.map(async (job) => {
const folder = `${args.companyId}/job/${job.id}`;
- const listed = await client.storage.from("private").list(folder);
+ const listed = await storage(client)
+ .company(args.companyId)
+ .list(folder);
return (listed.data ?? []).map(
(file): BatchFile => ({
...file,
@@ -1005,7 +1014,9 @@ export async function getBatchWorkInstructions(
Promise.all(
itemIds.map(async (itemId) => {
const folder = `${args.companyId}/parts/${itemId}`;
- const listed = await client.storage.from("private").list(folder);
+ const listed = await storage(client)
+ .company(args.companyId)
+ .list(folder);
return (listed.data ?? []).map(
(file): BatchFile => ({
...file,
diff --git a/ci/package.json b/ci/package.json
index f59898a4e0..98b615f3ab 100644
--- a/ci/package.json
+++ b/ci/package.json
@@ -15,7 +15,7 @@
"ci:assembler": "tsx src/assembler.ts",
"ci:jobs": "tsx src/jobs.ts",
"ci:upload-backup-templates": "tsx src/upload-backup-templates.ts",
- "test": "echo \"no tests\""
+ "test": "tsx --test src/*.test.ts"
},
"devDependencies": {
"sst": "catalog:"
diff --git a/ci/src/migrations.ts b/ci/src/migrations.ts
index 5243703b42..f4f7b2338c 100644
--- a/ci/src/migrations.ts
+++ b/ci/src/migrations.ts
@@ -1,6 +1,9 @@
+import { createClient } from "@supabase/supabase-js";
import { $ } from "execa";
import { client } from "./client";
+import type { LedgerDatabase } from "./one-off-scripts";
+import { selectPendingScripts } from "./one-off-scripts";
import {
SUPABASE_ACCESS_TOKEN,
SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_ID,
@@ -24,6 +27,81 @@ export type Workspace = {
service_role_key: string | null;
};
+/**
+ * Run the one-off scripts this workspace has not run yet, recording each in the
+ * workspace's OWN `scriptRun` table. The scripts are whatever is in
+ * `scripts/one-off/` — see that folder's README.
+ *
+ * Runs after `supabase db push`, so a script can rely on the schema the same
+ * deploy just applied — the bucket copy needs the buckets that
+ * 20260917163108_company-bucket-provisioning.sql provisions.
+ *
+ * A script is spawned as a subprocess with the per-workspace env explicitly
+ * injected rather than imported and called: `scripts/lib/local-script-config.ts`
+ * lets a `.env.local` file OVERRIDE the passed environment, so an in-process
+ * call could silently target the wrong database on any machine that has one.
+ *
+ * A failure here does NOT abort the workspace's migration — the schema is
+ * already pushed and correct. Returns false instead of throwing so the caller
+ * can mark the run errored without the failure being re-reported as a failed
+ * migration; because nothing is recorded in the ledger, the next deploy
+ * retries it.
+ */
+async function runPendingScripts(
+ workspace: Workspace,
+ $$: typeof $
+): Promise<boolean> {
+ const { database_url, service_role_key } = workspace;
+ if (!database_url || !service_role_key) {
+ console.log(
+ `⏭️ Skipping one-off scripts for ${workspace.id}: missing database url or service role key`
+ );
+ return true;
+ }
+
+ const ledger = createClient<LedgerDatabase>(database_url, service_role_key, {
+ auth: { autoRefreshToken: false, persistSession: false },
+ });
+
+ const pending = await selectPendingScripts(ledger);
+ if (pending.length === 0) return true;
+
+ let succeeded = true;
+
+ for (const script of pending) {
+ console.log(`✅ 📜 Running ${script.name} for ${workspace.id}`);
+ try {
+ const { stdout } = await $$`tsx ${script.path}`;
+ const tail = stdout.trim().split("\n").slice(-20).join("\n");
+
+ const { error } = await ledger
+ .from("scriptRun")
+ .insert({ name: script.name, result: { output: tail } });
+
+ if (error) {
+ // The work is done but unrecorded, so the next deploy runs it again.
+ // Every listed script must be idempotent for exactly this reason.
+ throw new Error(
+ `ran but could not be recorded: ${error.message}. It will run again on the next deploy.`
+ );
+ }
+
+ console.log(`✅ 📜 Completed ${script.name} for ${workspace.id}`);
+ } catch (e) {
+ console.error(`🔴 📜 Script ${script.name} failed for ${workspace.id}`, e);
+ succeeded = false;
+ }
+ }
+
+ if (!succeeded) {
+ console.error(
+ `🔴 📜 One or more one-off scripts failed for ${workspace.id}. Migrations already succeeded; the failed scripts are unrecorded and retry on the next deploy.`
+ );
+ }
+
+ return succeeded;
+}
+
async function migrate(): Promise<void> {
console.log("✅ 🌱 Starting migrations");
@@ -120,6 +198,13 @@ async function migrate(): Promise<void> {
}
console.log(`✅ 🐓 Successfully migrated ${workspace.id}`);
+
+ // After the success log: the schema is pushed and correct regardless of
+ // how the scripts go, so a script failure must not read as a failed
+ // migration. It still fails the overall run via `hasErrors`.
+ if (!(await runPendingScripts(workspace, $$))) {
+ hasErrors = true;
+ }
} catch (error) {
console.error(`🔴 🍳 Failed to migrate ${workspace.id}`, error);
hasErrors = true;
diff --git a/ci/src/one-off-scripts.test.ts b/ci/src/one-off-scripts.test.ts
new file mode 100644
index 0000000000..94299eb084
--- /dev/null
+++ b/ci/src/one-off-scripts.test.ts
@@ -0,0 +1,111 @@
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { test } from "node:test";
+import { discoverOneOffScripts, selectPendingScripts } from "./one-off-scripts";
+
+function withFiles<T>(names: string[], fn: (dir: string) => T): T {
+ const dir = mkdtempSync(join(tmpdir(), "one-off-"));
+ try {
+ for (const name of names) writeFileSync(join(dir, name), "");
+ return fn(`${dir}/`);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+test("discovers kebab-case scripts in a stable order, with absolute paths", () => {
+ withFiles(["b-second.ts", "a-first.ts", "README.md"], (dir) => {
+ const scripts = discoverOneOffScripts(dir);
+ assert.deepEqual(
+ scripts.map((s) => s.name),
+ ["a-first", "b-second"]
+ );
+ assert.ok(scripts.every((s) => s.path.startsWith("/")));
+ assert.ok(scripts.every((s) => s.path.endsWith(".ts")));
+ });
+});
+
+// The blocker this guard exists for: `scripts/lib/` colocates `*.test.ts` with
+// its sources, so a dev following that convention here would otherwise ship a
+// test file that runs against every production database.
+test("refuses a colocated test file rather than running it", () => {
+ withFiles(["migrate-thing.ts", "migrate-thing.test.ts"], (dir) => {
+ assert.throws(
+ () => discoverOneOffScripts(dir),
+ /migrate-thing\.test\.ts/,
+ "a .test.ts file must be refused, never discovered as a script"
+ );
+ });
+});
+
+test("refuses any other unrecognised file rather than silently skipping it", () => {
+ for (const name of ["notes.txt", "helper.d.ts", "Thing.ts", "with_underscore.ts"]) {
+ withFiles(["migrate-thing.ts", name], (dir) => {
+ assert.throws(
+ () => discoverOneOffScripts(dir),
+ new RegExp(name.replace(/[.]/g, "\\.")),
+ `${name} must be refused`
+ );
+ });
+ }
+});
+
+test("a README-only folder yields no scripts", () => {
+ withFiles(["README.md"], (dir) => {
+ assert.deepEqual(discoverOneOffScripts(dir), []);
+ });
+});
+
+function ledgerStub(
+ rows: { name: string }[] | null,
+ error: { message: string } | null = null
+) {
+ return {
+ from: () => ({ select: () => ({ in: async () => ({ data: rows, error }) }) })
+ } as unknown as Parameters<typeof selectPendingScripts>[0];
+}
+
+const SCRIPTS = [
+ { name: "a", path: "/tmp/a.ts" },
+ { name: "b", path: "/tmp/b.ts" }
+];
+
+test("selects only the scripts with no ledger row", async () => {
+ assert.deepEqual(
+ (await selectPendingScripts(ledgerStub([{ name: "a" }]), SCRIPTS)).map(
+ (s) => s.name
+ ),
+ ["b"]
+ );
+ assert.equal(
+ (await selectPendingScripts(ledgerStub([]), SCRIPTS)).length,
+ 2
+ );
+ assert.equal(
+ (
+ await selectPendingScripts(
+ ledgerStub([{ name: "a" }, { name: "b" }]),
+ SCRIPTS
+ )
+ ).length,
+ 0
+ );
+});
+
+// An unreadable ledger means we cannot tell what has already run. Re-running
+// blind is how a non-idempotent script corrupts a production database.
+test("throws when the ledger cannot be read, rather than re-running everything", async () => {
+ await assert.rejects(
+ () => selectPendingScripts(ledgerStub(null, { message: "no relation" }), SCRIPTS),
+ /no relation/
+ );
+});
+
+test("does not query the ledger when there are no scripts", async () => {
+ const exploding = {
+ from: () => assert.fail("must not query the ledger for an empty script list")
+ } as unknown as Parameters<typeof selectPendingScripts>[0];
+ assert.deepEqual(await selectPendingScripts(exploding, []), []);
+});
diff --git a/ci/src/one-off-scripts.ts b/ci/src/one-off-scripts.ts
new file mode 100644
index 0000000000..23966018ac
--- /dev/null
+++ b/ci/src/one-off-scripts.ts
@@ -0,0 +1,147 @@
+import { readdirSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import type { SupabaseClient } from "@supabase/supabase-js";
+
+/**
+ * One-off operational scripts, run once per database and then never again.
+ *
+ * The FOLDER is the registry: every `.ts` file in `scripts/one-off/` is a
+ * script, discovered at runtime. Adding one is adding a file — there is no
+ * list to keep in sync, so a script can never be present but unregistered
+ * (silently never running) or registered but absent (failing every deploy).
+ *
+ * A script runs after `supabase db push`, so it can rely on the schema that
+ * same deploy applied, and is recorded in the TARGET database's own
+ * `scriptRun` table — see 20260921050318_script-run-ledger.sql for why the
+ * ledger lives there rather than on the CI `workspaces` row, and
+ * `scripts/one-off/README.md` for the rules a script must follow.
+ *
+ * NOTE: .github/workflows/supabase.yml only fires on pushes under
+ * `packages/database/supabase/**`. A script that ships without a migration
+ * therefore will NOT deploy on its own; land it alongside one, or run the
+ * workflow manually (workflow_dispatch).
+ */
+export type OneOffScript = {
+ /**
+ * The file's basename without `.ts`, and the `scriptRun` primary key.
+ * Renaming the FILE re-runs the script everywhere, so treat the filename as
+ * the script's permanent identifier.
+ */
+ name: string;
+ /** Absolute path to the script file. */
+ path: string;
+};
+
+/** `scripts/one-off/`, resolved from this module rather than from a cwd. */
+const ONE_OFF_DIR = fileURLToPath(
+ new URL("../../scripts/one-off/", import.meta.url)
+);
+
+/**
+ * What a runnable script is allowed to be named: `<kebab-case>.ts`.
+ *
+ * This is an ALLOWLIST, not a blocklist, because everything this matches gets
+ * executed against every production database. A blocklist arms any filename
+ * nobody thought to exclude; `scripts/lib/` already colocates `*.test.ts`
+ * beside its sources, so a dev following that convention here would otherwise
+ * ship a test file straight into production. Dotted names (`foo.test.ts`,
+ * `foo.d.ts`) do not match, and anything else unrecognised is refused loudly
+ * by `discoverOneOffScripts` rather than silently skipped.
+ */
+const SCRIPT_FILENAME = /^[a-z0-9]+(?:-[a-z0-9]+)*\.ts$/;
+
+/**
+ * Every script in the folder, in a stable (alphabetical) order.
+ *
+ * Paths are absolute: the runner spawns scripts with `cwd: "supabase"` inside
+ * a copied directory, so a relative path would be a hand-counted hop that
+ * breaks the moment either location moves.
+ *
+ * Throws on any file that is neither a runnable script nor obviously
+ * documentation. Refusing beats skipping: a script silently ignored for a
+ * filename typo looks exactly like a script that has already run, and the
+ * deploy would report success having done nothing.
+ */
+export function discoverOneOffScripts(
+ dir: string = ONE_OFF_DIR
+): OneOffScript[] {
+ const entries = readdirSync(dir, { withFileTypes: true }).filter((entry) =>
+ entry.isFile()
+ );
+
+ const unexpected = entries
+ .map((entry) => entry.name)
+ .filter((name) => !SCRIPT_FILENAME.test(name) && name !== "README.md");
+
+ if (unexpected.length > 0) {
+ throw new Error(
+ `Unexpected file(s) in scripts/one-off/: ${unexpected.join(", ")}. ` +
+ "Only kebab-case `<name>.ts` scripts and README.md belong here — " +
+ "every script in this folder runs against every production database. " +
+ "See scripts/one-off/README.md."
+ );
+ }
+
+ return entries
+ .filter((entry) => SCRIPT_FILENAME.test(entry.name))
+ .map((entry) => ({
+ name: entry.name.slice(0, -".ts".length),
+ path: `${dir}${entry.name}`
+ }))
+ .sort((a, b) => a.name.localeCompare(b.name));
+}
+
+/**
+ * Minimal schema for the ledger client. The ledger lives in the TARGET
+ * database, which this package has no generated types for — declaring just
+ * `scriptRun` keeps both the read and the write type-checked without pulling
+ * @carbon/database into the CI package.
+ */
+export type LedgerDatabase = {
+ public: {
+ Tables: {
+ scriptRun: {
+ Row: { name: string; ranAt: string; result: unknown | null };
+ Insert: { name: string; ranAt?: string; result?: unknown | null };
+ Update: { name?: string; ranAt?: string; result?: unknown | null };
+ Relationships: [];
+ };
+ };
+ Views: Record<never, never>;
+ Functions: Record<never, never>;
+ Enums: Record<never, never>;
+ CompositeTypes: Record<never, never>;
+ };
+};
+
+type LedgerClient = SupabaseClient<LedgerDatabase>;
+
+/**
+ * Which discovered scripts have not yet run against this database.
+ *
+ * Throws when the ledger cannot be read, and the caller treats that as fatal:
+ * a missing or unreadable `scriptRun` means we cannot tell what has already
+ * run, and re-running blind is how a non-idempotent script corrupts a
+ * production database. Fail loudly instead.
+ */
+export async function selectPendingScripts(
+ ledger: LedgerClient,
+ scripts: OneOffScript[] = discoverOneOffScripts()
+): Promise<OneOffScript[]> {
+ if (scripts.length === 0) return [];
+
+ const { data, error } = await ledger
+ .from("scriptRun")
+ .select("name")
+ .in(
+ "name",
+ scripts.map((script) => script.name)
+ );
+
+ if (error) {
+ throw new Error(`Failed to read scriptRun ledger: ${error.message}`);
+ }
+
+ const alreadyRan = new Set((data ?? []).map((row) => row.name));
+ return scripts.filter((script) => !alreadyRan.has(script.name));
+}
diff --git a/contrib/deploying/simple-docker-caddy/docker-compose.prod.yml b/contrib/deploying/simple-docker-caddy/docker-compose.prod.yml
index dfb723bab5..d7f7bcf223 100644
--- a/contrib/deploying/simple-docker-caddy/docker-compose.prod.yml
+++ b/contrib/deploying/simple-docker-caddy/docker-compose.prod.yml
@@ -489,6 +489,10 @@ services:
SUPABASE_PUBLIC_URL: ${SUPABASE_URL}
SUPABASE_ANON_KEY: __ANON_KEY__
SUPABASE_SERVICE_KEY: __SERVICE_ROLE_KEY__
+ # Studio's SQL-editor snippets are read from a directory on disk; with the
+ # var unset it throws "SNIPPETS_MANAGEMENT_FOLDER env var is not set" on
+ # the SQL editor page. Studio creates the folder itself if missing.
+ SNIPPETS_MANAGEMENT_FOLDER: /app/snippets
volumes:
- *shim
# The image's built-in healthcheck demands HTTP 200 from /api/platform/profile
diff --git a/packages/database/AGENTS.md b/packages/database/AGENTS.md
index efdce5e0a6..eff2d8cea1 100644
--- a/packages/database/AGENTS.md
+++ b/packages/database/AGENTS.md
@@ -8,6 +8,13 @@ DB types, Supabase/Kysely clients, audit config, event system types, rate limiti
- 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[]`.
- 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`, no
+ composite PK, SELECT-only RLS. It is the per-database ledger of one-off scripts that
+ `ci/src/migrations.ts` runs after `supabase db push` — see `scripts/one-off/README.md`.
+ It is intentionally NOT tenant-scoped so `selectWipeableTables` (company-backup.ts) cannot
+ select it and a company restore cannot erase it. A migration landing in this package is
+ also what triggers those scripts to deploy (`.github/workflows/supabase.yml` only fires on
+ `packages/database/supabase/**`).
- Use `fetchAllFromTable` for paginated reads that exceed the 1000-row Supabase limit. It pages
without `count: "exact"` (a `COUNT(*) OVER ()` per page is not free) and fetches the pages past
the first concurrently. `fetchAllRecords` is the same pager over a query FACTORY (`() => builder`)
diff --git a/packages/database/src/audit.config.ts b/packages/database/src/audit.config.ts
index 05fbbbb15a..298b36f89a 100644
--- a/packages/database/src/audit.config.ts
+++ b/packages/database/src/audit.config.ts
@@ -696,10 +696,13 @@ export const auditConfig = {
/** Retention period before archival (days) */
retentionDays: 30,
- /** Archive storage path template */
- archivePath: "audit-logs/{companyId}/{year}/{month}.jsonl.gz",
+ /** Archive storage path template (company-bucket keys keep the companyId
+ * prefix; pre-migration archives used audit-logs/{companyId}/... in the
+ * legacy bucket — readers resolve via the stored archivePath) */
+ archivePath: "{companyId}/audit-logs/{year}/{month}.jsonl.gz",
- /** Storage bucket name for archives */
+ /** LEGACY shared bucket for pre-migration archives (read fallback only —
+ * new archives are written to the company's own private bucket) */
archiveBucket: "private"
} as const;
diff --git a/packages/database/src/audit.ts b/packages/database/src/audit.ts
index c8346bc220..cf5ebcd4d5 100644
--- a/packages/database/src/audit.ts
+++ b/packages/database/src/audit.ts
@@ -350,7 +350,7 @@ export async function getArchiveDownloadUrl(
// First get the archive record to get the path
const { data: archive, error: fetchError } = await client
.from("auditLogArchive")
- .select("archivePath")
+ .select("archivePath, companyId")
.eq("id", archiveId)
.single();
@@ -358,10 +358,23 @@ export async function getArchiveDownloadUrl(
throw new Error(`Archive not found: ${fetchError?.message}`);
}
- // Generate signed URL (1 hour expiry)
- const { data, error } = await client.storage
- .from(auditConfig.archiveBucket)
- .createSignedUrl((archive as { archivePath: string }).archivePath, 3600);
+ const { archivePath, companyId } = archive as {
+ archivePath: string;
+ companyId: string;
+ };
+
+ // Generate signed URL (1 hour expiry). New archives live in the company's
+ // own private bucket (bucket id = companyId); pre-migration archives live in
+ // the legacy shared bucket (auditConfig.archiveBucket), so fall back.
+ let { data, error } = await client.storage
+ .from(companyId)
+ .createSignedUrl(archivePath, 3600);
+
+ if (error || !data?.signedUrl) {
+ ({ data, error } = await client.storage
+ .from(auditConfig.archiveBucket)
+ .createSignedUrl(archivePath, 3600));
+ }
if (error || !data?.signedUrl) {
throw new Error(`Failed to generate download URL: ${error?.message}`);
diff --git a/packages/database/src/datasets/bootstrap.ts b/packages/database/src/datasets/bootstrap.ts
index c3c3e715d0..23647e8c65 100644
--- a/packages/database/src/datasets/bootstrap.ts
+++ b/packages/database/src/datasets/bootstrap.ts
@@ -139,8 +139,13 @@ export async function seedCompanyReferenceData(
[companyId, companyName, companyGroupId]
);
+ // The AFTER INSERT trigger on company (20260917163108) already provisions
+ // the bucket; keep this explicit insert as a no-op safety net for databases
+ // where that migration hasn't applied yet.
await client.query(
- `INSERT INTO storage.buckets (id, name, public) VALUES ($1, $2, false)`,
+ `INSERT INTO storage.buckets (id, name, public, file_size_limit)
+ VALUES ($1, $2, false, 52428800)
+ ON CONFLICT (id) DO NOTHING`,
[companyId, companyId]
);
diff --git a/packages/database/supabase/functions/import-csv/index.ts b/packages/database/supabase/functions/import-csv/index.ts
index 5693b57016..169ac8311a 100644
--- a/packages/database/supabase/functions/import-csv/index.ts
+++ b/packages/database/supabase/functions/import-csv/index.ts
@@ -968,7 +968,19 @@ serve(async (req: Request) => {
const client = await requirePermissions(req, companyId, userId, { create: "resources" });
- const csvFile = await client.storage.from("private").download(filePath);
+ // The client is service-role and the legacy bucket is shared across
+ // tenants, so the `${companyId}/` key prefix is the tenant boundary on the
+ // caller-supplied path — refuse anything outside it.
+ if (!filePath.startsWith(`${companyId}/`)) {
+ throw new Error("File path is outside the company's storage prefix");
+ }
+
+ // Try the company bucket first; fall back to the legacy shared bucket
+ // for files uploaded before the per-company bucket migration.
+ let csvFile = await client.storage.from(companyId).download(filePath);
+ if (csvFile.error || !csvFile.data) {
+ csvFile = await client.storage.from("private").download(filePath);
+ }
if (!csvFile.data) {
throw new Error("Failed to download file");
}
diff --git a/packages/database/supabase/functions/process-image/index.ts b/packages/database/supabase/functions/process-image/index.ts
index c56e3b7312..008d126dd4 100644
--- a/packages/database/supabase/functions/process-image/index.ts
+++ b/packages/database/supabase/functions/process-image/index.ts
@@ -76,9 +76,12 @@ serve(async (req: Request) => {
}
// imgproxy fallback: stage in the company's temp dir, download the
// transformed rendition, clean up.
+ // Staging is written and read back within this request, so it goes in
+ // the company's own private bucket (bucket id = companyId) — no legacy
+ // fallback is needed for a file this function just created.
const tempPath = `${companyId}/tmp/${nanoid()}.${extension}`;
const upload = await client.storage
- .from("private")
+ .from(companyId)
.upload(tempPath, file, { upsert: true });
if (upload.error) throw new Error(upload.error.message);
try {
@@ -95,7 +98,7 @@ serve(async (req: Request) => {
quality: 90
};
const download = await client.storage
- .from("private")
+ .from(companyId)
.download(tempPath, { transform });
if (download.error) throw new Error(download.error.message);
const contentType =
@@ -105,7 +108,7 @@ serve(async (req: Request) => {
headers: { ...corsHeaders, "Content-Type": contentType }
});
} finally {
- await client.storage.from("private").remove([tempPath]);
+ await client.storage.from(companyId).remove([tempPath]);
}
}
} catch (err) {
diff --git a/packages/database/supabase/migrations/20260917163108_company-bucket-provisioning.sql b/packages/database/supabase/migrations/20260917163108_company-bucket-provisioning.sql
new file mode 100644
index 0000000000..38baff4389
--- /dev/null
+++ b/packages/database/supabase/migrations/20260917163108_company-bucket-provisioning.sql
@@ -0,0 +1,42 @@
+-- Company-private buckets: provisioning.
+-- 20250827181005_company-bucket-rls.sql backfilled one bucket per company that
+-- existed at the time and created the "Company bucket access" RLS policy, but
+-- nothing creates a bucket for a company created since. Backfill the gap and
+-- add an AFTER INSERT trigger so every new company gets its bucket atomically.
+
+-- Belt-and-braces: a company id equal to a shared bucket id would silently
+-- collide with that bucket (the provisioning below no-ops on conflict) while
+-- the "Company bucket access" RLS policy (20250827181005) would then grant
+-- that company's employees FOR ALL on the shared bucket. Generated ids can
+-- never take these values; refuse them outright so no insert path ever can.
+ALTER TABLE "company" ADD CONSTRAINT "company_id_not_reserved_bucket_id"
+ CHECK ("id" NOT IN ('private', 'public', 'avatars', 'feedback', 'temp-staging', 'company-templates'));
+
+-- Backfill buckets for companies created after 20250827181005 (50 MB cap,
+-- matching the limit 20260715150742 put on the legacy "private" bucket).
+INSERT INTO storage.buckets (id, name, public, file_size_limit)
+SELECT id, id, false, 52428800
+FROM company
+ON CONFLICT (id) DO NOTHING;
+
+-- The 2025 backfill created rows with a NULL file_size_limit; normalize.
+UPDATE storage.buckets
+SET file_size_limit = 52428800
+WHERE id IN (SELECT id FROM company)
+ AND file_size_limit IS NULL;
+
+-- SECURITY DEFINER: the inserting role (authenticated user during onboarding)
+-- has no grant on storage.buckets.
+CREATE OR REPLACE FUNCTION public.create_company_private_bucket()
+RETURNS TRIGGER AS $$
+BEGIN
+ INSERT INTO storage.buckets (id, name, public, file_size_limit)
+ VALUES (NEW.id, NEW.id, false, 52428800)
+ ON CONFLICT (id) DO NOTHING;
+ RETURN NEW;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER SET search_path = public, storage;
+
+CREATE TRIGGER create_company_private_bucket_trigger
+AFTER INSERT ON "company"
+FOR EACH ROW EXECUTE FUNCTION public.create_company_private_bucket();
diff --git a/packages/database/supabase/migrations/20260921050318_script-run-ledger.sql b/packages/database/supabase/migrations/20260921050318_script-run-ledger.sql
new file mode 100644
index 0000000000..ffe2a31320
--- /dev/null
+++ b/packages/database/supabase/migrations/20260921050318_script-run-ledger.sql
@@ -0,0 +1,35 @@
+-- Ledger of one-off operational scripts that have already run against THIS
+-- database. `ci/src/migrations.ts` reads it after `supabase db push` and runs
+-- only the scripts it has no row for, so a deploy re-runs nothing.
+--
+-- Why this lives here and not on the CI control plane's `workspaces` table:
+-- "has this script run?" is a fact about this database, so it travels with it.
+-- A workspace that is cloned, restored or re-pointed at a different project
+-- carries the correct answer instead of inheriting a stale flag, and a
+-- self-hosted instance gets the same bookkeeping from `supabase db push`
+-- alone, with no control-plane table to replicate.
+--
+-- Deliberately NOT tenant-scoped: it has neither "companyId" nor
+-- "companyGroupId", so `selectWipeableTables` (company-backup.ts) cannot
+-- select it and a company restore can never erase the ledger.
+CREATE TABLE "scriptRun" (
+ -- The script's stable name, e.g. 'migrate-private-buckets'. Renaming a
+ -- script re-runs it, so treat this as the script's permanent identifier.
+ "name" TEXT NOT NULL,
+ "ranAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ -- Free-form result summary from the run (counts, skips, failures).
+ "result" JSONB,
+
+ CONSTRAINT "scriptRun_pkey" PRIMARY KEY ("name")
+);
+
+-- Operational metadata: readable by signed-in users for debugging, writable
+-- only by the service role (no INSERT/UPDATE/DELETE policy exists), matching
+-- how "config" is governed.
+ALTER TABLE "scriptRun" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "SELECT" ON "scriptRun"
+FOR SELECT
+USING (
+ auth.role() = 'authenticated'
+);
diff --git a/packages/dev/docker/docker-compose.dev.yml b/packages/dev/docker/docker-compose.dev.yml
index 427ccef035..6bfdeee6e8 100644
--- a/packages/dev/docker/docker-compose.dev.yml
+++ b/packages/dev/docker/docker-compose.dev.yml
@@ -294,6 +294,11 @@ services:
SUPABASE_PUBLIC_URL: ${SUPABASE_URL}
SUPABASE_ANON_KEY: ${SUPABASE_ANON_KEY}
SUPABASE_SERVICE_KEY: ${SUPABASE_SERVICE_ROLE_KEY}
+ # Studio's SQL-editor snippets are read from a directory on disk; with the
+ # var unset it throws "SNIPPETS_MANAGEMENT_FOLDER env var is not set" on
+ # the SQL editor page. Studio creates the folder itself if missing. Not a
+ # mounted volume on purpose — snippets are scratch SQL, not project state.
+ SNIPPETS_MANAGEMENT_FOLDER: /app/snippets
inbucket:
image: inbucket/inbucket:3.1.1
diff --git a/packages/ee/src/accounting/providers/rillet/entities/charge.ts b/packages/ee/src/accounting/providers/rillet/entities/charge.ts
index c4452cabf7..79e4d6c400 100644
--- a/packages/ee/src/accounting/providers/rillet/entities/charge.ts
+++ b/packages/ee/src/accounting/providers/rillet/entities/charge.ts
@@ -1,3 +1,4 @@
+import { storage } from "@carbon/files";
import {
type CardChargeSource,
chargeLineDescription,
@@ -349,10 +350,12 @@ export class RilletChargeSyncer extends RilletTransactionSyncer<
const { getCarbonServiceRole } = await import(
"@carbon/auth/client.server"
);
- const storage = getCarbonServiceRole().storage.from("private");
+ const bucket = storage(getCarbonServiceRole()).company(this.companyId);
for (const document of documents) {
- const downloaded = await storage.download(document.path);
- if (downloaded.error || !downloaded.data) {
+ // Falls back to the legacy shared bucket, so a receipt stored before
+ // the per-company copy ran still reaches Rillet.
+ const downloaded = await bucket.download(document.path);
+ if (!downloaded.data) {
console.warn(
`[rillet] charge ${localId}: could not download receipt ${document.path}`,
downloaded.error
diff --git a/packages/ee/src/paperless-parts/lib/lib.ts b/packages/ee/src/paperless-parts/lib/lib.ts
index 5d0c690db9..410d13b1c2 100644
--- a/packages/ee/src/paperless-parts/lib/lib.ts
+++ b/packages/ee/src/paperless-parts/lib/lib.ts
@@ -1,6 +1,7 @@
import { openai } from "@ai-sdk/openai";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import type { Database } from "@carbon/database";
+import { storage } from "@carbon/files";
import { supportedModelTypes } from "@carbon/files/cad";
import { processImage } from "@carbon/files/media";
import { initNodeImageCodecs } from "@carbon/files/media/node";
@@ -840,8 +841,8 @@ async function uploadModelFile(
logger.info(`Uploading CAD model ${file.name} to ${modelPath}`);
// Upload model to storage
- const modelUpload = await carbon.storage
- .from("private")
+ const modelUpload = await storage(carbon)
+ .company(companyId)
.upload(modelPath, file, {
upsert: true
});
@@ -929,8 +930,8 @@ async function uploadFileToItem(
logger.info(`Uploading ${file.name} to ${storagePath}`);
- const fileUpload = await carbon.storage
- .from("private")
+ const fileUpload = await storage(carbon)
+ .company(companyId)
.upload(storagePath, file, {
cacheControl: `${12 * 60 * 60}`,
upsert: true
@@ -1977,10 +1978,10 @@ async function downloadAndUploadThumbnail(
type: processed.contentType
});
- // Upload to private bucket
+ // Upload to the company's private bucket
const storagePath = `${companyId}/thumbnails/${itemId}/${fileName}`;
- const { data, error } = await carbon.storage
- .from("private")
+ const { data, error } = await storage(carbon)
+ .company(companyId)
.upload(storagePath, thumbnailFile, {
upsert: true
});
diff --git a/packages/files/AGENTS.md b/packages/files/AGENTS.md
index 4539d8d0b3..2a92598c90 100644
--- a/packages/files/AGENTS.md
+++ b/packages/files/AGENTS.md
@@ -6,7 +6,7 @@ in the codebase, shared by the browser, Node, and the Supabase edge runtime.
| Subpath | Provides |
|---------|----------|
-| `.` (root) | Cross-type helpers: `MEDIA_CONTENT_TYPES` + `getContentType` (the one extension→MIME map every file-serving route uses), `getFileExtension` / `effectiveExtension` (`.zst` unwrap), `getDocumentType` / `documentTypes` / `isPreviewableDocumentType` (file classification for the Documents UI), `convertKbToString`, and `downloadBlob` / `downloadText` — THE browser "save this as a file" sequence (object URL → anchor click → revoke); never hand-roll it |
+| `.` (root) | Cross-type helpers: `MEDIA_CONTENT_TYPES` + `getContentType` (the one extension→MIME map every file-serving route uses), `getFileExtension` / `effectiveExtension` (`.zst` unwrap), `getDocumentType` / `documentTypes` / `isPreviewableDocumentType` (file classification for the Documents UI), `convertKbToString`, and `downloadBlob` / `downloadText` — THE browser "save this as a file" sequence (object URL → anchor click → revoke); never hand-roll it. **`storage(client)`** — the Carbon storage client, supabase-shaped: `.from(bucket)` is plain supabase for `public` / `temp-staging`; `.company(companyId)` is that company's private bucket (bucket id = companyId, THROWS on an empty id) with the legacy shared `private` bucket folded in — reads (`download` / `info` / `createSignedUrl`) fall back to it, `list` unions both, `remove` deletes from both, writes (`upload` / `move` / `copy` / `createSignedUploadUrl`) go to the company bucket only. Every key must sit under `${companyId}/` (under a service-role client that prefix is the ONLY tenant boundary on the shared legacy bucket); anything else gets `{ data: null, error }` without touching storage. This is the contract for document keys (`${companyId}/parts/…`, `/job/…`, `/tmp/…`, everything `getPrivateUrl` serves); the backup and audit-archive layouts (`exports/…`, `audit/…`) share the bucket under their own keys and keep using plain `client.storage.from(companyId)`. All legacy-bucket fallback lives in `storage.ts` so removing it later is a one-file change; `getCompanyPrivateBucket` / `LEGACY_PRIVATE_BUCKET` / `hasCompanyPrivateObjectPathPrefix` are exported for the few places that need the bucket *name* (MediaUploader staging, route authorization, the assembler's bucket resolver) |
| `./csv` | `encodeCsv` (object rows) / `encodeCsvTable` (header + cells) — the ONE CSV encoder, injection-safe by construction (`stripCsvFormulaPrefix` on every string cell); `parseCsv` (text) / `parseCsvFile` (browser File, streamed); `downloadCsv`; `CSV_CONTENT_TYPE`. papaparse underneath, in every runtime. The Table export button, report exports, import templates, import-error re-exports and the sales CSV import all go through here — before this there were two libraries (`json-2-csv` + papaparse) and two hand-rolled encoders, and only ONE of the five export sites protected against formula injection |
| `./media` | Images. **`MediaUploader`** — the configured client (constructor takes the storage client + HEIC staging location once, files-sdk style): `prepareForUpload(files)` (HEIC → JPEG sequentially + duplicate-name refusal, throws `DuplicateFileNameError`), `convertHeic(file)`, `prepareImage(file, shape)`. Underneath: `processImage` (the pipeline), `prepareImageUpload` (pipeline → native-decode fallback → imgproxy fallback), `convertHeicToJpeg` / `convertHeicFiles` / `findDuplicateFileName`, `transformImageViaStorage` (imgproxy round-trip), `isHeic`, `IMAGE_UPLOAD_MIME_TYPES`, plus the storage-path helpers `getPrivateUrl` / `getRawModelUrl` / `parseJobFilePath` |
| `./media/node` | `initNodeImageCodecs()` — Node-only wasm pre-instantiation; call once before the pipeline in Node (jobs, paperless, vitest). Touches `node:fs`: never import from client code |
diff --git a/packages/files/package.json b/packages/files/package.json
index 4fa732ccc3..21a26b6b85 100644
--- a/packages/files/package.json
+++ b/packages/files/package.json
@@ -24,6 +24,7 @@
"@jsquash/png": "3.1.1",
"@jsquash/resize": "2.1.1",
"@jsquash/webp": "1.5.0",
+ "@supabase/storage-js": "catalog:",
"@supabase/supabase-js": "catalog:",
"libheif-js": "1.23.2",
"nanoid": "catalog:",
diff --git a/packages/files/src/index.ts b/packages/files/src/index.ts
index 75b286f23d..715d4be435 100644
--- a/packages/files/src/index.ts
+++ b/packages/files/src/index.ts
@@ -10,3 +10,4 @@ export {
isPreviewableDocumentType,
MEDIA_CONTENT_TYPES
} from "./media/media";
+export * from "./storage";
diff --git a/packages/files/src/media/storage.ts b/packages/files/src/media/storage.ts
index f0a127f223..8a792247a6 100644
--- a/packages/files/src/media/storage.ts
+++ b/packages/files/src/media/storage.ts
@@ -10,9 +10,14 @@ const encodeStoragePath = (path: string) =>
path.split("/").map(encodeURIComponent).join("/");
export const getPrivateUrl = (path: string) => {
+ // Private files live in one bucket PER COMPANY and stored paths keep the
+ // `${companyId}/...` first segment, so the bucket is that segment. The
+ // preview route also accepts the legacy shared `private` bucket, which is
+ // the fallback when a path has no leading segment.
+ const bucket = path.split("/")[0] || "private";
return (
getDatasetAssetUrl(path) ??
- `/file/preview/private/${encodeStoragePath(path)}`
+ `/file/preview/${encodeURIComponent(bucket)}/${encodeStoragePath(path)}`
);
};
diff --git a/packages/files/src/storage.test.ts b/packages/files/src/storage.test.ts
new file mode 100644
index 0000000000..ac341f2d37
--- /dev/null
+++ b/packages/files/src/storage.test.ts
@@ -0,0 +1,388 @@
+import type { StorageClient } from "@supabase/storage-js";
+import { describe, expect, it, vi } from "vitest";
+import {
+ getCompanyPrivateBucket,
+ hasCompanyPrivateObjectPathPrefix,
+ LEGACY_PRIVATE_BUCKET,
+ normalizeStorageSegment,
+ storage
+} from "./storage";
+
+const ok = <T>(data: T) => Promise.resolve({ data, error: null });
+const fail = (message: string) =>
+ Promise.resolve({ data: null, error: { message } });
+
+type Bucket = ReturnType<StorageClient["from"]>;
+
+// A fake `client.storage`: every bucket method misses unless overridden.
+// Stubs are loosely typed on purpose: they return the minimum shape a test needs.
+const makeClient = (buckets: Record<string, Record<string, unknown>>) => ({
+ storage: {
+ from: (bucket: string) =>
+ ({
+ upload: vi.fn(() => ok({ path: "p" })),
+ update: vi.fn(() => ok({ path: "p" })),
+ uploadToSignedUrl: vi.fn(() => ok({ path: "p" })),
+ move: vi.fn(() => ok({ message: "ok" })),
+ copy: vi.fn(() => ok({ path: "p" })),
+ createSignedUploadUrl: vi.fn(() => ok({ signedUrl: "u" })),
+ exists: vi.fn(() => fail("not found")),
+ info: vi.fn(() => fail("not found")),
+ download: vi.fn(() => fail("not found")),
+ createSignedUrl: vi.fn(() => fail("not found")),
+ list: vi.fn(() => ok([])),
+ remove: vi.fn(() => ok([])),
+ ...buckets[bucket]
+ }) as unknown as Bucket
+ } as unknown as StorageClient
+});
+
+describe("normalizeStorageSegment", () => {
+ it("trims and collapses separators", () => {
+ expect(normalizeStorageSegment(" abc ")).toBe("abc");
+ expect(normalizeStorageSegment("a/b\\c")).toBe("a-b-c");
+ expect(normalizeStorageSegment("/abc/")).toBe("abc");
+ expect(normalizeStorageSegment("-abc-")).toBe("abc");
+ });
+});
+
+describe("getCompanyPrivateBucket", () => {
+ it("is the normalized companyId", () => {
+ expect(getCompanyPrivateBucket("cs868u84gfk07v78v9e0")).toBe(
+ "cs868u84gfk07v78v9e0"
+ );
+ expect(getCompanyPrivateBucket(" abc ")).toBe("abc");
+ });
+
+ it('refuses an empty companyId rather than resolving bucket ""', () => {
+ expect(() => getCompanyPrivateBucket("")).toThrow();
+ expect(() => getCompanyPrivateBucket(" / ")).toThrow();
+ });
+});
+
+describe("hasCompanyPrivateObjectPathPrefix", () => {
+ it("requires the companyId segment prefix", () => {
+ expect(hasCompanyPrivateObjectPathPrefix("co1", "co1/docs/a.pdf")).toBe(
+ true
+ );
+ expect(hasCompanyPrivateObjectPathPrefix("co1", "co12/docs/a.pdf")).toBe(
+ false
+ );
+ expect(hasCompanyPrivateObjectPathPrefix("co1", "other/co1/a.pdf")).toBe(
+ false
+ );
+ });
+
+ it("never matches for an empty companyId", () => {
+ expect(hasCompanyPrivateObjectPathPrefix("", "/models/a.step")).toBe(false);
+ expect(hasCompanyPrivateObjectPathPrefix("", "anything")).toBe(false);
+ });
+});
+
+describe("storage(client).from", () => {
+ it("is the plain supabase bucket", () => {
+ const client = makeClient({});
+ const spy = vi.spyOn(client.storage, "from");
+ storage(client).from("public");
+ expect(spy).toHaveBeenCalledWith("public");
+ });
+});
+
+describe("storage(client).company", () => {
+ it("throws on an empty companyId", () => {
+ expect(() => storage(makeClient({})).company("")).toThrow();
+ });
+
+ describe("writes go to the company bucket only", () => {
+ it.each([
+ ["upload", (b: Bucket) => b.upload("co1/docs/a.pdf", new Blob())],
+ ["update", (b: Bucket) => b.update("co1/docs/a.pdf", new Blob())],
+ [
+ "uploadToSignedUrl",
+ (b: Bucket) => b.uploadToSignedUrl("co1/docs/a.pdf", "tok", new Blob())
+ ],
+ [
+ "createSignedUploadUrl",
+ (b: Bucket) => b.createSignedUploadUrl("co1/docs/a.pdf")
+ ]
+ ] as const)("%s", async (method, call) => {
+ const legacy = vi.fn(() => ok({ path: "leak" }));
+ const client = makeClient({
+ [LEGACY_PRIVATE_BUCKET]: { [method]: legacy }
+ });
+ const result = await call(
+ storage(client).company("co1") as unknown as Bucket
+ );
+ expect(result.error).toBeNull();
+ expect(legacy).not.toHaveBeenCalled();
+ });
+
+ it.each(["move", "copy"] as const)("%s", async (method) => {
+ const legacy = vi.fn(() => ok({ path: "leak" }));
+ const client = makeClient({
+ [LEGACY_PRIVATE_BUCKET]: { [method]: legacy }
+ });
+ const result = await storage(client)
+ .company("co1")
+ [method]("co1/a.pdf", "co1/b.pdf");
+ expect(result.error).toBeNull();
+ expect(legacy).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("refuses a key outside the company prefix without touching storage", () => {
+ const client = makeClient({
+ co1: {
+ download: vi.fn(() => ok(new Blob())),
+ upload: vi.fn(() => ok({ path: "leak" }))
+ },
+ [LEGACY_PRIVATE_BUCKET]: {
+ download: vi.fn(() => ok(new Blob())),
+ remove: vi.fn(() => ok([{ name: "leak" }]))
+ }
+ });
+ const bucket = storage(client).company("co1");
+ const touched = () =>
+ [client.storage.from("co1"), client.storage.from(LEGACY_PRIVATE_BUCKET)]
+ .flatMap((b) => Object.values(b))
+ .some((fn) => (fn as ReturnType<typeof vi.fn>).mock?.calls.length);
+
+ it.each([
+ ["upload", () => bucket.upload("co2/a.pdf", new Blob())],
+ ["update", () => bucket.update("co2/a.pdf", new Blob())],
+ [
+ "uploadToSignedUrl",
+ () => bucket.uploadToSignedUrl("co2/a.pdf", "tok", new Blob())
+ ],
+ ["move", () => bucket.move("co1/a.pdf", "co2/a.pdf")],
+ ["copy", () => bucket.copy("co2/a.pdf", "co1/a.pdf")],
+ [
+ "createSignedUploadUrl",
+ () => bucket.createSignedUploadUrl("co2/a.pdf")
+ ],
+ ["exists", () => bucket.exists("co2/a.pdf")],
+ ["info", () => bucket.info("co2/a.pdf")],
+ ["download", () => bucket.download("co2/a.pdf")],
+ ["createSignedUrl", () => bucket.createSignedUrl("co2/a.pdf", 60)],
+ ["list", () => bucket.list("co2/docs")],
+ ["remove", () => bucket.remove(["co1/a.pdf", "co2/a.pdf"])],
+ ["a prefix-lookalike", () => bucket.download("co12/a.pdf")],
+ ["an empty key", () => bucket.download("")]
+ ])("%s", async (_, call) => {
+ const result = await call();
+ // `exists` answers false rather than null — supabase's own shape.
+ expect(result.data).toBeFalsy();
+ expect(result.error?.message).toMatch(
+ /outside the "co1\/" storage prefix/
+ );
+ expect(touched()).toBe(false);
+ });
+
+ it("names only the offending keys", async () => {
+ const { error } = await bucket.remove(["co1/a.pdf", "co2/a.pdf"]);
+ expect(error?.message).toBe(
+ 'co2/a.pdf is outside the "co1/" storage prefix'
+ );
+ });
+ });
+
+ describe("reads fall back to the legacy bucket", () => {
+ it.each([
+ ["exists", (b: Bucket) => b.exists("co1/a.pdf"), true],
+ ["info", (b: Bucket) => b.info("co1/a.pdf"), { name: "a.pdf" }],
+ ["download", (b: Bucket) => b.download("co1/a.pdf"), new Blob(["x"])],
+ [
+ "createSignedUrl",
+ (b: Bucket) => b.createSignedUrl("co1/a.pdf", 60),
+ { signedUrl: "https://x/y" }
+ ]
+ ] as const)("%s", async (method, call, hit) => {
+ const legacyMiss = vi.fn(() => fail("legacy miss"));
+
+ // Company hit: legacy never touched.
+ let client = makeClient({
+ co1: { [method]: vi.fn(() => ok(hit)) },
+ [LEGACY_PRIVATE_BUCKET]: { [method]: legacyMiss }
+ });
+ let result = await call(
+ storage(client).company("co1") as unknown as Bucket
+ );
+ expect(result.data).toBe(hit);
+ expect(legacyMiss).not.toHaveBeenCalled();
+
+ // Company miss, legacy hit.
+ client = makeClient({
+ [LEGACY_PRIVATE_BUCKET]: { [method]: vi.fn(() => ok(hit)) }
+ });
+ result = await call(storage(client).company("co1") as unknown as Bucket);
+ expect(result.data).toBe(hit);
+ expect(result.error).toBeNull();
+
+ // Both miss: the company bucket's error is reported.
+ client = makeClient({
+ co1: { [method]: vi.fn(() => fail("company miss")) },
+ [LEGACY_PRIVATE_BUCKET]: { [method]: legacyMiss }
+ });
+ result = await call(storage(client).company("co1") as unknown as Bucket);
+ expect(result.data).toBeNull();
+ expect(result.error?.message).toBe("company miss");
+ });
+
+ it("download forwards transform options to both buckets", async () => {
+ const companyDownload = vi.fn(() => fail("miss"));
+ const legacyDownload = vi.fn(() => ok(new Blob()));
+ const client = makeClient({
+ co1: { download: companyDownload },
+ [LEGACY_PRIVATE_BUCKET]: { download: legacyDownload }
+ });
+ const options = { transform: { quality: 85 } };
+ await storage(client).company("co1").download("co1/a.heic", options);
+ expect(companyDownload).toHaveBeenCalledWith("co1/a.heic", options);
+ expect(legacyDownload).toHaveBeenCalledWith("co1/a.heic", options);
+ });
+ });
+
+ describe("list", () => {
+ it("unions both buckets with the company bucket winning ties", async () => {
+ const client = makeClient({
+ co1: { list: vi.fn(() => ok([{ name: "a.pdf", id: "new" }])) },
+ [LEGACY_PRIVATE_BUCKET]: {
+ list: vi.fn(() =>
+ ok([
+ { name: "a.pdf", id: "old" },
+ { name: "b.pdf", id: "legacy-only" }
+ ])
+ )
+ }
+ });
+ const { data, error } = await storage(client)
+ .company("co1")
+ .list("co1/docs", { limit: 10 });
+ expect(error).toBeNull();
+ expect(data?.map((f) => [f.name, f.id]).sort()).toEqual([
+ ["a.pdf", "new"],
+ ["b.pdf", "legacy-only"]
+ ]);
+ expect(client.storage.from("co1").list).toHaveBeenCalledWith("co1/docs", {
+ limit: 10
+ });
+ });
+
+ it("still returns the healthy bucket's rows when the other errors", async () => {
+ const client = makeClient({
+ co1: { list: vi.fn(() => fail("bucket missing")) },
+ [LEGACY_PRIVATE_BUCKET]: { list: vi.fn(() => ok([{ name: "b.pdf" }])) }
+ });
+ const { data, error } = await storage(client)
+ .company("co1")
+ .list("co1/docs");
+ expect(error).toBeNull();
+ expect(data?.map((f) => f.name)).toEqual(["b.pdf"]);
+ });
+
+ it("reports the company error when both buckets fail", async () => {
+ const client = makeClient({
+ co1: { list: vi.fn(() => fail("company down")) },
+ [LEGACY_PRIVATE_BUCKET]: { list: vi.fn(() => fail("legacy down")) }
+ });
+ const { data, error } = await storage(client)
+ .company("co1")
+ .list("co1/docs");
+ expect(data).toBeNull();
+ expect(error?.message).toBe("company down");
+ });
+ });
+
+ describe("remove", () => {
+ it("removes from both buckets and tolerates misses", async () => {
+ const companyRemove = vi.fn(() => ok([]));
+ const legacyRemove = vi.fn(() => ok([{ name: "a.pdf" }]));
+ const client = makeClient({
+ co1: { remove: companyRemove },
+ [LEGACY_PRIVATE_BUCKET]: { remove: legacyRemove }
+ });
+ const { data, error } = await storage(client)
+ .company("co1")
+ .remove(["co1/docs/a.pdf"]);
+ expect(error).toBeNull();
+ expect(data).toEqual([{ name: "a.pdf" }]);
+ expect(companyRemove).toHaveBeenCalledWith(["co1/docs/a.pdf"]);
+ expect(legacyRemove).toHaveBeenCalledWith(["co1/docs/a.pdf"]);
+ });
+
+ it("surfaces a failure on either bucket", async () => {
+ const client = makeClient({
+ [LEGACY_PRIVATE_BUCKET]: {
+ remove: vi.fn(() => fail("permission denied"))
+ }
+ });
+ const { data, error } = await storage(client)
+ .company("co1")
+ .remove(["co1/docs/a.pdf"]);
+ expect(data).toBeNull();
+ expect(error?.message).toBe("permission denied");
+ });
+ });
+});
+
+describe("move falls back to a cross-bucket move out of the legacy bucket", () => {
+ it("moves within the company bucket when the file is already there", async () => {
+ const legacyMove = vi.fn(() => ok({ message: "legacy" }));
+ const client = makeClient({
+ co1: { move: vi.fn(() => ok({ message: "company" })) },
+ [LEGACY_PRIVATE_BUCKET]: { move: legacyMove }
+ });
+
+ const result = await storage(client)
+ .company("co1")
+ .move("co1/a.pdf", "co1/b.pdf");
+
+ expect(result.data).toEqual({ message: "company" });
+ expect(legacyMove).not.toHaveBeenCalled();
+ });
+
+ // A file uploaded before the per-company copy ran is only in the legacy
+ // bucket, so the company-bucket move misses and the retry must carry it
+ // across in one operation rather than leaving the drag broken.
+ it("retries out of the legacy bucket into the company bucket on a miss", async () => {
+ const legacyMove = vi.fn(() => ok({ message: "legacy" }));
+ const client = makeClient({
+ co1: { move: vi.fn(() => fail("not found")) },
+ [LEGACY_PRIVATE_BUCKET]: { move: legacyMove }
+ });
+
+ const result = await storage(client)
+ .company("co1")
+ .move("co1/a.pdf", "co1/b.pdf");
+
+ expect(result.data).toEqual({ message: "legacy" });
+ expect(legacyMove).toHaveBeenCalledWith("co1/a.pdf", "co1/b.pdf", {
+ destinationBucket: "co1"
+ });
+ });
+
+ it("reports the company bucket's error when both buckets miss", async () => {
+ const client = makeClient({
+ co1: { move: vi.fn(() => fail("company miss")) },
+ [LEGACY_PRIVATE_BUCKET]: { move: vi.fn(() => fail("legacy miss")) }
+ });
+
+ const result = await storage(client)
+ .company("co1")
+ .move("co1/a.pdf", "co1/b.pdf");
+
+ expect(result.error).toEqual({ message: "company miss" });
+ });
+
+ it("refuses a key outside the company prefix without touching storage", async () => {
+ const companyMove = vi.fn(() => ok({ message: "company" }));
+ const client = makeClient({ co1: { move: companyMove } });
+
+ const result = await storage(client)
+ .company("co1")
+ .move("co1/a.pdf", "co2/b.pdf");
+
+ expect(result.error).toBeTruthy();
+ expect(companyMove).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/files/src/storage.ts b/packages/files/src/storage.ts
new file mode 100644
index 0000000000..1223cc2e59
--- /dev/null
+++ b/packages/files/src/storage.ts
@@ -0,0 +1,199 @@
+/**
+ * Company-private storage.
+ *
+ * Private files live in one bucket PER COMPANY (bucket id = companyId).
+ * Object keys keep the legacy `${companyId}/...` first segment so paths
+ * stored in the database stay valid and the legacy→company copy is same-key.
+ *
+ * The legacy shared `private` bucket is a read-only fallback until the copy
+ * script has run everywhere; every fallback lives in this file so removing
+ * it later is a one-file change.
+ *
+ * const { data, error } = await storage(client).company(companyId).download(path);
+ * await storage(client).company(companyId).upload(path, file, { upsert: true });
+ * await storage(client).from("public").upload(path, file);
+ */
+
+import {
+ type DownloadResult,
+ type SearchOptions,
+ type StorageClient,
+ StorageError,
+ type TransformOptions
+} from "@supabase/storage-js";
+
+export const LEGACY_PRIVATE_BUCKET = "private";
+export const COMPANY_BUCKET_FILE_SIZE_LIMIT = 52428800; // 50 MB
+
+export const normalizeStorageSegment = (value: string) =>
+ value
+ .trim()
+ .replace(/[\\/]+/g, "-")
+ .replace(/^[-/]+|[-/]+$/g, "");
+
+export const getCompanyPrivateBucket = (companyId: string) => {
+ const bucket = normalizeStorageSegment(companyId);
+ if (!bucket) {
+ // `.from("")` would silently probe a non-existent bucket and fall through
+ // to whatever fallback the caller has — refuse loudly instead.
+ throw new Error(
+ "companyId is required to resolve a company private bucket"
+ );
+ }
+ return bucket;
+};
+
+export const hasCompanyPrivateObjectPathPrefix = (
+ companyId: string,
+ objectPath: string
+) => {
+ const bucket = normalizeStorageSegment(companyId);
+ return bucket ? objectPath.startsWith(`${bucket}/`) : false;
+};
+
+type Bucket = ReturnType<StorageClient["from"]>;
+
+/**
+ * A company's private bucket with the supabase `StorageFileApi` shape. Writes
+ * go to the company bucket only; reads fall back to the legacy bucket; `list`
+ * unions both and `remove` deletes from both. Every key must sit under
+ * `${companyId}/` — under a service-role client that prefix is the only
+ * tenant boundary on the shared legacy bucket, and a company bucket must never
+ * hold a key that `getPrivateUrl` would resolve to another company's bucket.
+ *
+ * Deliberately absent: `getPublicUrl` (private bucket), `createSignedUrls`
+ * and `listV2` (batch shapes with no single fallback answer). Use `.from()`
+ * if one is ever needed.
+ */
+export type CompanyBucket = {
+ upload: Bucket["upload"];
+ update: Bucket["update"];
+ uploadToSignedUrl: Bucket["uploadToSignedUrl"];
+ move: Bucket["move"];
+ copy: Bucket["copy"];
+ createSignedUploadUrl: Bucket["createSignedUploadUrl"];
+ exists: Bucket["exists"];
+ info: Bucket["info"];
+ download(
+ path: string,
+ options?: { transform?: TransformOptions }
+ ): Promise<DownloadResult<Blob>>;
+ createSignedUrl: Bucket["createSignedUrl"];
+ list(prefix: string, options?: SearchOptions): ReturnType<Bucket["list"]>;
+ remove: Bucket["remove"];
+};
+
+export type CarbonStorage = {
+ /** Any other bucket (`public`, `temp-staging`, …) — plain supabase. */
+ from(bucket: string): Bucket;
+ company(companyId: string): CompanyBucket;
+};
+
+export function storage(client: { storage: StorageClient }): CarbonStorage {
+ return {
+ from: (bucket) => client.storage.from(bucket),
+ company: (companyId) => companyBucket(client.storage, companyId)
+ };
+}
+
+function companyBucket(
+ storage: StorageClient,
+ companyId: string
+): CompanyBucket {
+ const id = getCompanyPrivateBucket(companyId);
+ const own = storage.from(id);
+ const legacy = storage.from(LEGACY_PRIVATE_BUCKET);
+
+ const owned = (path: string) =>
+ hasCompanyPrivateObjectPathPrefix(companyId, path);
+ const owns = (...paths: string[]) => paths.every(owned);
+ const refuse = (...paths: string[]) =>
+ Promise.resolve({
+ data: null,
+ error: new StorageError(
+ `${paths.filter((path) => !owned(path)).join(", ")} is outside the "${id}/" storage prefix`
+ )
+ });
+
+ // Company bucket first, legacy second; when both miss, the company bucket's
+ // error is the one reported since that is where the file belongs.
+ const withFallback = async <R extends { error: unknown }>(
+ read: (bucket: Bucket) => PromiseLike<R>
+ ) => {
+ const primary = await read(own);
+ if (!primary.error) return primary;
+ const fallback = await read(legacy);
+ return fallback.error ? primary : fallback;
+ };
+
+ return {
+ upload: (path, ...rest) =>
+ owns(path) ? own.upload(path, ...rest) : refuse(path),
+ update: (path, ...rest) =>
+ owns(path) ? own.update(path, ...rest) : refuse(path),
+ uploadToSignedUrl: (path, ...rest) =>
+ owns(path) ? own.uploadToSignedUrl(path, ...rest) : refuse(path),
+ // A file uploaded before the per-company copy ran still lives only in the
+ // legacy bucket, so a move within the company bucket finds nothing. Retry
+ // it as a cross-bucket move OUT of legacy: `/object/move` takes a
+ // `destinationBucket`, so this stays one server-side operation rather than
+ // a download/upload/remove dance. Honours an explicit destinationBucket.
+ move: async (from, to, options) => {
+ if (!owns(from, to)) return refuse(from, to);
+ const primary = await own.move(from, to, options);
+ if (!primary.error) return primary;
+ const fallback = await legacy.move(from, to, {
+ ...options,
+ destinationBucket: options?.destinationBucket ?? id
+ });
+ return fallback.error ? primary : fallback;
+ },
+ copy: (from, to, options) =>
+ owns(from, to) ? own.copy(from, to, options) : refuse(from, to),
+ createSignedUploadUrl: (path, options) =>
+ owns(path) ? own.createSignedUploadUrl(path, options) : refuse(path),
+
+ exists: (path) =>
+ owns(path)
+ ? withFallback((b) => b.exists(path))
+ : refuse(path).then(({ error }) => ({ data: false, error })),
+ info: (path) =>
+ owns(path) ? withFallback((b) => b.info(path)) : refuse(path),
+ download: (path, options) =>
+ owns(path)
+ ? withFallback((b) => b.download(path, options))
+ : refuse(path),
+ createSignedUrl: (path, expiresIn, options) =>
+ owns(path)
+ ? withFallback((b) => b.createSignedUrl(path, expiresIn, options))
+ : refuse(path),
+
+ list: async (prefix, options) => {
+ if (!owns(prefix)) return refuse(prefix);
+ const [primary, fallback] = await Promise.all([
+ own.list(prefix, options),
+ legacy.list(prefix, options)
+ ]);
+ if (primary.error && fallback.error) return primary;
+ // Union by name with the company copy winning: during the fallback
+ // window a file sits in either bucket, after the copy script in both.
+ const byName = new Map((fallback.data ?? []).map((f) => [f.name, f]));
+ for (const f of primary.data ?? []) byName.set(f.name, f);
+ return { data: [...byName.values()], error: null };
+ },
+
+ remove: async (paths) => {
+ if (!owns(...paths)) return refuse(...paths);
+ const [primary, fallback] = await Promise.all([
+ own.remove(paths),
+ legacy.remove(paths)
+ ]);
+ // A miss is not an error (supabase returns an empty array), so any
+ // error is a real failure — and a file left behind in the legacy bucket
+ // would still be readable through the fallback.
+ if (primary.error) return primary;
+ if (fallback.error) return fallback;
+ return { data: [...primary.data, ...fallback.data], error: null };
+ }
+ };
+}
diff --git a/packages/jobs/src/inngest/functions/extraction/extract-document.ts b/packages/jobs/src/inngest/functions/extraction/extract-document.ts
index 8a9fd8f830..f73b942489 100644
--- a/packages/jobs/src/inngest/functions/extraction/extract-document.ts
+++ b/packages/jobs/src/inngest/functions/extraction/extract-document.ts
@@ -1,5 +1,6 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { EXTRACTION_CONFIDENCE_THRESHOLD } from "@carbon/env";
+import { storage } from "@carbon/files";
import { extractPdfText } from "@carbon/files/pdf";
import { inngest } from "../../client";
import { invoiceExtractionSchema, rfqExtractionSchema } from "./schemas";
@@ -64,12 +65,12 @@ export const extractDocumentFunction = inngest.createFunction(
try {
// 3. Download PDF from Supabase Storage
- const { data: fileData, error: downloadErr } = await client.storage
- .from("private")
+ const { data: fileData, error: downloadError } = await storage(client)
+ .company(companyId)
.download(extraction.storagePath);
- if (downloadErr || !fileData) {
- throw new Error(`Failed to download PDF: ${downloadErr?.message}`);
+ if (!fileData) {
+ throw new Error(`Failed to download PDF: ${downloadError.message}`);
}
// 4. Extract text from PDF
diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-attach.ts b/packages/jobs/src/inngest/functions/integrations/onshape-attach.ts
index b6d25c80f4..638d0b9b6f 100644
--- a/packages/jobs/src/inngest/functions/integrations/onshape-attach.ts
+++ b/packages/jobs/src/inngest/functions/integrations/onshape-attach.ts
@@ -1,5 +1,6 @@
import { openAsBlob } from "node:fs";
import type { Database } from "@carbon/database";
+import { getCompanyPrivateBucket, storage } from "@carbon/files";
import type { SupabaseClient } from "@supabase/supabase-js";
import { nanoid } from "nanoid";
import { resolveModelSourceBucket } from "../tasks/assembler-client";
@@ -50,7 +51,8 @@ export interface AttachOnshapeAssetsResult {
preservedPriorModelAsDocument: boolean;
}
-const BUCKET = "private";
+// Durable files land in the company's own private bucket (bucket id =
+// companyId; object keys keep the companyId prefix).
// Raw model sources live in temp-staging (same as manual CadModel uploads); the
// model-optimize job reads from there and later zstd-compacts the raw in place.
const STAGING_BUCKET = "temp-staging";
@@ -245,8 +247,8 @@ export async function attachModelThumbnail(
input: { companyId: string; modelUploadId: string; pngBytes: Uint8Array }
): Promise<void> {
const thumbnailPath = `${input.companyId}/thumbnails/${input.modelUploadId}/${input.modelUploadId}.png`;
- const uploaded = await carbon.storage
- .from(BUCKET)
+ const uploaded = await storage(carbon)
+ .company(input.companyId)
.upload(thumbnailPath, input.pngBytes, {
upsert: true,
contentType: "image/png"
@@ -449,8 +451,9 @@ export async function attachOnshapeAssetsToItem(
);
const preservedPath = `${companyId}/parts/${itemId}/${preservedName}`;
// Raw sources live in temp-staging since the assembler pipeline;
- // pre-pipeline rows live in private. Copy into private either way so
- // the preserved file sits with the item's documents.
+ // older rows live in the company or legacy private bucket. Copy into
+ // the company bucket so the preserved file sits with the item's
+ // documents.
const priorBucket = await resolveModelSourceBucket(
carbon,
priorModel.modelPath
@@ -458,7 +461,7 @@ export async function attachOnshapeAssetsToItem(
const copied = await carbon.storage
.from(priorBucket)
.copy(priorModel.modelPath, preservedPath, {
- destinationBucket: BUCKET
+ destinationBucket: getCompanyPrivateBucket(companyId)
});
if (copied.error && !/already exists/i.test(copied.error.message)) {
console.error(
@@ -506,8 +509,8 @@ export async function attachOnshapeAssetsToItem(
const safeName = stripSpecialCharacters(document.fileName);
const documentPath = `${companyId}/parts/${itemId}/${safeName}`;
- const documentUpload = await carbon.storage
- .from(BUCKET)
+ const documentUpload = await storage(carbon)
+ .company(companyId)
.upload(documentPath, document.bytes, { upsert: true });
if (documentUpload.error) {
throw new Error(
diff --git a/packages/jobs/src/inngest/functions/integrations/ramp-sync-bill.ts b/packages/jobs/src/inngest/functions/integrations/ramp-sync-bill.ts
index 86228d53ff..d5b30cce34 100644
--- a/packages/jobs/src/inngest/functions/integrations/ramp-sync-bill.ts
+++ b/packages/jobs/src/inngest/functions/integrations/ramp-sync-bill.ts
@@ -5,6 +5,7 @@ import {
type RampClient,
resolveRampSupplier
} from "@carbon/ee/ramp.server";
+import { storage } from "@carbon/files";
import { round } from "@carbon/utils";
import {
isPostedRampBill,
@@ -241,8 +242,8 @@ async function attachBillDocuments(
const name = stripSpecialCharacters(basename);
const path = `${ctx.companyId}/purchase-invoice/${args.invoiceRowId}/${name}`;
- const uploaded = await ctx.client.storage
- .from("private")
+ const uploaded = await storage(ctx.client)
+ .company(ctx.companyId)
.upload(path, bytes, { upsert: true });
if (uploaded.error) {
console.error(
diff --git a/packages/jobs/src/inngest/functions/integrations/ramp-sync-card.ts b/packages/jobs/src/inngest/functions/integrations/ramp-sync-card.ts
index 0c5d054786..1d5d60432a 100644
--- a/packages/jobs/src/inngest/functions/integrations/ramp-sync-card.ts
+++ b/packages/jobs/src/inngest/functions/integrations/ramp-sync-card.ts
@@ -10,6 +10,7 @@ import {
resolveMerchantSupplier,
scaleLinesToTotal
} from "@carbon/ee/ramp.server";
+import { storage } from "@carbon/files";
import { stageOrResumeRampCardTransaction } from "./ramp-sync-card-stage";
import { recordRampFamilyError } from "./ramp-sync-observability";
import {
@@ -72,8 +73,8 @@ async function attachReceipts(
);
const path = `${ctx.companyId}/card-transaction/${args.cardTransactionId}/${name}`;
- const uploaded = await ctx.client.storage
- .from("private")
+ const uploaded = await storage(ctx.client)
+ .company(ctx.companyId)
.upload(path, bytes, { upsert: true });
if (uploaded.error) {
console.error(
diff --git a/packages/jobs/src/inngest/functions/scheduled/audit-archive.ts b/packages/jobs/src/inngest/functions/scheduled/audit-archive.ts
index 486ab792cf..41d5296c34 100644
--- a/packages/jobs/src/inngest/functions/scheduled/audit-archive.ts
+++ b/packages/jobs/src/inngest/functions/scheduled/audit-archive.ts
@@ -3,6 +3,7 @@ import { CONTROLLED_ENVIRONMENT } from "@carbon/auth";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { auditConfig } from "@carbon/database/audit.config";
import type { AuditLogEntry } from "@carbon/database/audit.types";
+import { getCompanyPrivateBucket } from "@carbon/files";
import { getLogger } from "@carbon/logger";
import { datetime } from "@carbon/utils";
import { inngest } from "../../client";
@@ -65,11 +66,18 @@ async function archiveCompanyLogs(
const month = String(utcToday.month).padStart(2, "0");
const day = String(utcToday.day).padStart(2, "0");
const timestamp = `${year}-${month}-${day}`;
- const archivePath = `audit-logs/${companyId}/${year}/${month}/${timestamp}.jsonl.gz`;
-
- // Upload to storage
+ // Keys in the company bucket start with `${companyId}/` — the module-wide
+ // private-storage invariant (it is what backup listing and the prefix-guarded
+ // helpers key off). Pre-migration archives used `audit-logs/${companyId}/...`
+ // in the legacy shared bucket; readers resolve via the stored `archivePath`,
+ // so both shapes stay readable.
+ const archivePath = `${companyId}/audit-logs/${year}/${month}/${timestamp}.jsonl.gz`;
+
+ // Upload to the company's own private bucket (auditConfig.archiveBucket is
+ // the legacy shared bucket, kept only as a read fallback for old archives).
+ const archiveBucket = getCompanyPrivateBucket(companyId);
const { error: uploadError } = await client.storage
- .from(auditConfig.archiveBucket)
+ .from(archiveBucket)
.upload(archivePath, gzipped, {
contentType: "application/gzip",
upsert: true
@@ -95,7 +103,7 @@ async function archiveCompanyLogs(
if (archiveError) {
// Try to clean up uploaded file
- await client.storage.from(auditConfig.archiveBucket).remove([archivePath]);
+ await client.storage.from(archiveBucket).remove([archivePath]);
throw new Error(`Failed to record archive: ${archiveError.message}`);
}
diff --git a/packages/jobs/src/inngest/functions/scheduled/cleanup.ts b/packages/jobs/src/inngest/functions/scheduled/cleanup.ts
index 970f88c73f..56cc289489 100644
--- a/packages/jobs/src/inngest/functions/scheduled/cleanup.ts
+++ b/packages/jobs/src/inngest/functions/scheduled/cleanup.ts
@@ -1,4 +1,5 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { LEGACY_PRIVATE_BUCKET, storage } from "@carbon/files";
import { NotificationEvent } from "@carbon/notifications";
import { inngest } from "../../client";
@@ -423,17 +424,23 @@ export const cleanupFunction = inngest.createFunction(
// reader probes/falls back to `private`.
const relocated = new Set<string>();
const CHUNK = 20;
+ // A durable copy may live in the company's own bucket (current pipeline)
+ // or the legacy shared `private` bucket (pre-migration relocations);
+ // `info` probes both. Object keys start with the companyId segment, and
+ // a key without one can't have a durable copy anywhere.
+ const probeDurableCopy = async (name: string) => {
+ const companyId = name.split("/")[0];
+ if (!companyId) return null;
+ const found = await storage(serviceRole)
+ .company(companyId)
+ .info(name)
+ .then((r) => !r.error)
+ .catch(() => false);
+ return found ? name : null;
+ };
for (let i = 0; i < staleNames.length; i += CHUNK) {
const chunk = staleNames.slice(i, i + CHUNK);
- const probes = await Promise.all(
- chunk.map((name) =>
- serviceRole.storage
- .from("private")
- .info(name)
- .then((r) => (!r.error && r.data ? name : null))
- .catch(() => null)
- )
- );
+ const probes = await Promise.all(chunk.map(probeDurableCopy));
for (const name of probes) {
if (name) relocated.add(name);
}
@@ -502,11 +509,14 @@ export const cleanupFunction = inngest.createFunction(
Date.now() - TMP_STAGING_TTL_HOURS * 60 * 60 * 1000
).toISOString();
+ // Staging now lives in each company's own bucket (bucket id = companyId),
+ // with the legacy shared `private` bucket still holding pre-migration
+ // objects — so select the bucket alongside the name and prune per bucket
+ // rather than assuming one shared bucket.
const stale = await serviceRole
.schema("storage")
.from("objects")
- .select("name")
- .eq("bucket_id", "private")
+ .select("name, bucket_id")
.like("name", "%/tmp/%")
.lt("created_at", cutoff)
.limit(1000);
@@ -519,27 +529,48 @@ export const cleanupFunction = inngest.createFunction(
// The LIKE matches "/tmp/" anywhere; only the SECOND segment being
// `tmp` marks the transient prefix (`{companyId}/tmp/…`). Entity
// folders are never named tmp, but don't rely on that for a delete.
- const toRemove = (stale.data ?? [])
- .map((o) => o.name)
- .filter(
- (n): n is string => typeof n === "string" && n.split("/")[1] === "tmp"
- );
+ const byBucket = new Map<string, string[]>();
+ for (const object of stale.data ?? []) {
+ const name = object.name;
+ const bucketId = object.bucket_id;
+ if (typeof name !== "string" || typeof bucketId !== "string") continue;
+ if (name.split("/")[1] !== "tmp") continue;
+ // A company bucket is named for its company, and its object keys keep
+ // the `{companyId}/` prefix — so a key whose first segment is not this
+ // bucket belongs to neither this company nor the legacy bucket layout.
+ if (
+ bucketId !== LEGACY_PRIVATE_BUCKET &&
+ name.split("/")[0] !== bucketId
+ )
+ continue;
+ const existing = byBucket.get(bucketId);
+ if (existing) existing.push(name);
+ else byBucket.set(bucketId, [name]);
+ }
- if (toRemove.length === 0) {
+ const toRemoveCount = [...byBucket.values()].reduce(
+ (total, names) => total + names.length,
+ 0
+ );
+ if (toRemoveCount === 0) {
logger.info("No stale tmp staging objects");
return;
}
- const removed = await serviceRole.storage
- .from("private")
- .remove(toRemove);
- if (removed.error) {
- logger.error("Error pruning tmp staging objects", {
- error: removed.error
- });
- } else {
+ let failed = false;
+ for (const [bucketId, names] of byBucket) {
+ const removed = await serviceRole.storage.from(bucketId).remove(names);
+ if (removed.error) {
+ failed = true;
+ logger.error("Error pruning tmp staging objects", {
+ bucket: bucketId,
+ error: removed.error
+ });
+ }
+ }
+ if (!failed) {
logger.info("Pruned stale tmp staging objects", {
- count: toRemove.length
+ count: toRemoveCount
});
}
});
diff --git a/packages/jobs/src/inngest/functions/tasks/assembler-client.ts b/packages/jobs/src/inngest/functions/tasks/assembler-client.ts
index 8e2727a317..60951f4ae2 100644
--- a/packages/jobs/src/inngest/functions/tasks/assembler-client.ts
+++ b/packages/jobs/src/inngest/functions/tasks/assembler-client.ts
@@ -10,6 +10,7 @@ import {
SESSION_SECRET,
SUPABASE_URL
} from "@carbon/env";
+import { getCompanyPrivateBucket, LEGACY_PRIVATE_BUCKET } from "@carbon/files";
import type { SupabaseClient } from "@supabase/supabase-js";
import { NonRetriableError } from "inngest";
@@ -78,11 +79,13 @@ export function assemblerBaseUrl(): string {
}
// Where a retained raw lands: uploads/compaction stage in `temp-staging`
-// (EPHEMERAL, 2.5 GB), and the retained raw is relocated to `private` (DURABLE,
-// 50 MB served cap) so it survives — or pruned when it can't fit and a GLB
-// preview already exists. The 50 MB gate is `MODEL_RAW_KEEP_MAX_BYTES`.
+// (EPHEMERAL, 2.5 GB), and the retained raw is relocated to the company's own
+// private bucket (DURABLE, 50 MB served cap) so it survives — or pruned when it
+// can't fit and a GLB preview already exists. The 50 MB gate is
+// `MODEL_RAW_KEEP_MAX_BYTES`. Object keys start with the companyId segment,
+// which is also the durable bucket's id; pre-migration raws still live in the
+// legacy `private` bucket, so readers probe both.
export const RAW_STAGING_BUCKET = "temp-staging";
-export const RAW_DURABLE_BUCKET = "private";
/**
* COPY a staged object into the durable bucket, same key, server-side (no
@@ -99,9 +102,15 @@ export async function copyRawToDurable(
client: SupabaseClient<Database>,
path: string
): Promise<string | null> {
+ // The durable home is the company's own bucket; keys start with companyId.
+ // A key with no companyId segment has no durable home — refuse rather than
+ // resolve to a wrong bucket.
+ const companySegment = path.split("/")[0] ?? "";
+ if (!companySegment) return `path has no companyId prefix: ${path}`;
+ const durableBucket = getCompanyPrivateBucket(companySegment);
const { error } = await client.storage
.from(RAW_STAGING_BUCKET)
- .copy(path, path, { destinationBucket: RAW_DURABLE_BUCKET });
+ .copy(path, path, { destinationBucket: durableBucket });
if (!error) return null;
return /already exists|duplicate/i.test(error.message) ? null : error.message;
}
@@ -134,19 +143,30 @@ export async function signSourceUrl(
/**
* Resolve which bucket a model's raw source lives in. Current uploads land in
- * `temp-staging`; rows from before the assembler pipeline live in `private` —
- * signing against the wrong bucket fails with "Object not found", so probe
- * temp-staging and fall back (same resolution as the ERP model.artifacts route).
+ * `temp-staging`, durable copies in the company's own bucket, and pre-migration
+ * rows in the legacy `private` bucket — signing against the wrong bucket fails
+ * with "Object not found", so probe in that order (same resolution as the ERP
+ * model.artifacts route).
*/
export async function resolveModelSourceBucket(
client: SupabaseClient<Database>,
modelPath: string
-): Promise<"temp-staging" | "private"> {
- const staged = await client.storage
- .from("temp-staging")
- .info(modelPath)
- .catch(() => ({ data: null, error: true as const }));
- return staged.error || !staged.data ? "private" : "temp-staging";
+): Promise<string> {
+ const companySegment = modelPath.split("/")[0] ?? "";
+ const buckets = [
+ RAW_STAGING_BUCKET,
+ // A key with no companyId segment can't resolve a company bucket.
+ ...(companySegment ? [getCompanyPrivateBucket(companySegment)] : []),
+ LEGACY_PRIVATE_BUCKET
+ ];
+ for (const bucket of buckets) {
+ const probe = await client.storage
+ .from(bucket)
+ .info(modelPath)
+ .catch(() => ({ data: null, error: true as const }));
+ if (!probe.error && probe.data) return bucket;
+ }
+ return LEGACY_PRIVATE_BUCKET;
}
/**
diff --git a/packages/jobs/src/inngest/functions/tasks/assembly-convert.ts b/packages/jobs/src/inngest/functions/tasks/assembly-convert.ts
index fde12f260a..8a587dd432 100644
--- a/packages/jobs/src/inngest/functions/tasks/assembly-convert.ts
+++ b/packages/jobs/src/inngest/functions/tasks/assembly-convert.ts
@@ -1,5 +1,6 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import type { Json } from "@carbon/database";
+import { storage } from "@carbon/files";
import { inngest } from "../../client";
import {
ASSEMBLER_CONCURRENCY,
@@ -172,11 +173,11 @@ export const assemblyConvertFunction = inngest.createFunction(
mintUploadUrls: async () => {
const client = getCarbonServiceRole();
const [glbUpload, graphUpload] = await Promise.all([
- client.storage
- .from("private")
+ storage(client)
+ .company(companyId)
.createSignedUploadUrl(glbPath, { upsert: true }),
- client.storage
- .from("private")
+ storage(client)
+ .company(companyId)
.createSignedUploadUrl(graphPath, { upsert: true })
]);
const urls: Record<string, string> = {};
diff --git a/packages/jobs/src/inngest/functions/tasks/assembly-plan.ts b/packages/jobs/src/inngest/functions/tasks/assembly-plan.ts
index e82284d0fd..f5b4d4ebe8 100644
--- a/packages/jobs/src/inngest/functions/tasks/assembly-plan.ts
+++ b/packages/jobs/src/inngest/functions/tasks/assembly-plan.ts
@@ -1,5 +1,6 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import type { Json } from "@carbon/database";
+import { storage } from "@carbon/files";
import type { AssemblyPlan } from "@carbon/viewer/steps";
import { inngest } from "../../client";
import {
@@ -232,8 +233,8 @@ export const assemblyPlanFunction = inngest.createFunction(
},
mintUploadUrls: async () => {
const client = getCarbonServiceRole();
- const upload = await client.storage
- .from("private")
+ const upload = await storage(client)
+ .company(companyId)
.createSignedUploadUrl(planPath, { upsert: true });
const urls: Record<string, string> = {};
if (upload.data)
@@ -256,8 +257,8 @@ export const assemblyPlanFunction = inngest.createFunction(
await step.run("persist-plan", async () => {
const client = getCarbonServiceRole();
if (inlinePlan) {
- const upload = await client.storage
- .from("private")
+ const upload = await storage(client)
+ .company(companyId)
.upload(donePlanPath, JSON.stringify(inlinePlan), {
contentType: "application/json",
upsert: true
@@ -290,12 +291,12 @@ export const assemblyPlanFunction = inngest.createFunction(
const client = getCarbonServiceRole();
let plan = inlinePlan;
if (!plan) {
- const download = await client.storage
- .from("private")
+ const download = await storage(client)
+ .company(companyId)
.download(donePlanPath);
- if (download.error || !download.data) {
+ if (!download.data) {
throw new Error(
- `Failed to download plan.json for re-motion: ${download.error?.message ?? "not found"}`
+ `Failed to download plan.json for re-motion: ${download.error.message}`
);
}
plan = JSON.parse(await download.data.text()) as AssemblyPlan;
diff --git a/packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts
index 6c3ff311e1..fcdebb52b5 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts
@@ -1,3 +1,5 @@
+import type { Database } from "@carbon/database";
+import { Constants } from "@carbon/database";
import { describe, expect, it } from "vitest";
import {
type Catalog,
@@ -5,6 +7,8 @@ import {
type CompanyBackup,
type ForeignKey,
isUserScopedIdentityTable,
+ READABLE_ID_TABLES,
+ STORAGE_PATH_COLUMNS,
selectWipeableTables,
type TableInfo
} from "./company-backup";
@@ -742,3 +746,131 @@ describe("mapCollidingRows", () => {
expect(skippedSourceIds.size).toBe(0);
});
});
+
+// ── Cross-company restore: readable ids and storage paths ────────────────────
+// Both guards pin a hardcoded list that a future schema change can silently
+// invalidate. Each list went stale exactly once already and produced a restore
+// that looked successful and was not: the Items pages rendered empty
+// (readable ids rewritten) and assemblies would not load (path columns left
+// pointing at the source company).
+describe("cross-company restore invariants", () => {
+ // Composite-PK tables backed by a global UNIQUE (id). Their ids MUST be
+ // remapped or a cross-company restore collides with the source company's
+ // still-live rows. Verified against pg_index on 2026-09-18.
+ const GLOBAL_UNIQUE_ID_TABLES = [
+ "balloon",
+ "changeOrderRequiredAction",
+ "demandProjection",
+ "inspectionDocument",
+ "inspectionFeature"
+ ];
+
+ // Every `modelUpload` column whose name ends in `Path`, typed against the
+ // GENERATED row type: `satisfies` makes this list fail to COMPILE if a column
+ // is renamed or removed, and the `Exclude` below fails to compile if a new
+ // `*Path` column is added and not listed. The runtime assertion then checks
+ // STORAGE_PATH_COLUMNS covers them all.
+ type ModelUploadPathColumn = Extract<
+ keyof Database["public"]["Tables"]["modelUpload"]["Row"],
+ `${string}Path`
+ >;
+ const MODEL_UPLOAD_PATH_COLUMNS = [
+ "modelPath",
+ "thumbnailPath",
+ "originalPath",
+ "optimizedModelPath",
+ "glbPath",
+ "graphPath"
+ ] as const satisfies readonly ModelUploadPathColumn[];
+ // Fails to compile when a new `*Path` column exists that the list omits.
+ type _EveryPathColumnListed =
+ Exclude<
+ ModelUploadPathColumn,
+ (typeof MODEL_UPLOAD_PATH_COLUMNS)[number]
+ > extends never
+ ? true
+ : [
+ "unlisted modelUpload *Path column",
+ Exclude<
+ ModelUploadPathColumn,
+ (typeof MODEL_UPLOAD_PATH_COLUMNS)[number]
+ >
+ ];
+ const _pathColumnsExhaustive: _EveryPathColumnListed = true;
+ void _pathColumnsExhaustive;
+
+ it("keeps a readable-id table out of the id maps, but maps a normal table", () => {
+ const part = table("part", [col("id"), col("companyId"), col("name")], [], {
+ pkColumns: ["id", "companyId"]
+ });
+ const workflow = table("workflow", [col("id"), col("companyId")], [], {
+ pkColumns: ["id", "companyId"]
+ });
+ const idMaps = buildIdMaps([part, workflow], {
+ part: [{ id: "ADCS-001", companyId: "src-co", name: "Widget" }],
+ workflow: [{ id: "wf_1", companyId: "src-co" }]
+ });
+ expect(idMaps.has("part")).toBe(false);
+ expect(idMaps.get("workflow")?.get("wf_1")).toBeTypeOf("string");
+ expect(idMaps.get("workflow")?.get("wf_1")).not.toBe("wf_1");
+ });
+
+ it("preserves a part number verbatim through a cross-company restamp", () => {
+ // The `parts` view inner-joins part.id = item."readableId"; a rewritten id
+ // matches nothing and the Parts page renders empty against a full table.
+ const part = table("part", [col("id"), col("companyId"), col("name")], [], {
+ pkColumns: ["id", "companyId"]
+ });
+ const idMaps = buildIdMaps([part], {
+ part: [{ id: "ADCS-001", companyId: "src-co", name: "Widget" }]
+ });
+ const transforms = buildRowTransforms(part, part.columns, {
+ remap: true,
+ companyId: "target-co",
+ userId: "importer",
+ targetGroupId: "target-grp",
+ sourceCompanyId: "src-co",
+ idMaps,
+ idRewrite: new Map<string, string>()
+ });
+ const row: Record<string, unknown> = {
+ id: "ADCS-001",
+ companyId: "src-co",
+ name: "Widget"
+ };
+ const out: Record<string, unknown> = {};
+ part.columns.forEach((c, i) => {
+ out[c.name] = transforms[i]!(row[c.name]);
+ });
+ expect(out).toEqual({
+ id: "ADCS-001",
+ companyId: "target-co",
+ name: "Widget"
+ });
+ });
+
+ it("exempts the child table of every item type", () => {
+ // Derived from the GENERATED enum, not a hand-copied list: adding an
+ // itemType member ships a new child table keyed on the same readable id,
+ // and `fixture` is unpopulated in every local database, so a data-driven
+ // sweep cannot see it. Regenerating types is what makes this test fail.
+ const missing = Constants.public.Enums.itemType
+ .map((t) => t.toLowerCase())
+ .filter((t) => !READABLE_ID_TABLES.has(t));
+ expect(missing).toEqual([]);
+ });
+
+ it("never exempts a table that needs a fresh id to avoid a unique collision", () => {
+ const overlap = GLOBAL_UNIQUE_ID_TABLES.filter((t) =>
+ READABLE_ID_TABLES.has(t)
+ );
+ expect(overlap).toEqual([]);
+ });
+
+ it("covers every modelUpload artifact column in STORAGE_PATH_COLUMNS", () => {
+ const missing = MODEL_UPLOAD_PATH_COLUMNS.filter(
+ (c) => !STORAGE_PATH_COLUMNS.has(c)
+ );
+ expect(missing).toEqual([]);
+ });
+});
diff --git a/packages/jobs/src/inngest/functions/tasks/company-backup.transforms.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.transforms.ts
index 4f0cd723e4..045e1a5a11 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-backup.transforms.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.transforms.ts
@@ -6,6 +6,7 @@ import {
type CompanyBackup,
mapWithConcurrency,
newIdForTable,
+ READABLE_ID_TABLES,
RETAINED_REF_TABLES,
rewriteStoragePath,
rewriteToTemplateAssetPath,
@@ -238,6 +239,13 @@ export function buildIdMaps(
): Map<string, Map<string, string>> {
const idMaps = new Map<string, Map<string, string>>();
for (const table of tables) {
+ // A readable-id table's `id` is a part number other rows match by value
+ // (`item."readableId"`), not an identifier — minting a fresh one orphans
+ // every row from its item. Skipped in BOTH the restore and the reseed/import
+ // path: the restore wipes the target first so the original values are free,
+ // and on an additive reseed a genuine duplicate hits the composite PK and
+ // fails loudly rather than silently corrupting the readable key.
+ if (READABLE_ID_TABLES.has(table.name)) continue;
const idType = table.columns.find((c) => c.name === "id")?.udtName;
if (idType !== "uuid" && idType !== "text") continue;
const idFk = table.foreignKeys.find(
diff --git a/packages/jobs/src/inngest/functions/tasks/company-backup.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.ts
index cda689af1a..2470d10b1e 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-backup.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.ts
@@ -3,6 +3,7 @@ import { createInterface } from "node:readline";
import { Readable } from "node:stream";
import { createGunzip, createGzip } from "node:zlib";
import type { KyselyDatabase } from "@carbon/database/client";
+import { getCompanyPrivateBucket } from "@carbon/files";
import { getLogger } from "@carbon/logger";
import type { SupabaseClient } from "@supabase/supabase-js";
import { type Kysely, sql } from "kysely";
@@ -42,25 +43,58 @@ export const EXPORTS_PREFIX = "exports";
export const TEMPLATE_BUCKET = "company-templates";
/**
- * The bucket the app stores per-company assets in (3D models, item thumbnails,
- * document attachments), all under a `{companyId}/` prefix. A backup copies these
- * into its own `assets/` folder (see `copyAssetsToBackup`); they are NOT in the
- * per-company bucket.
+ * The LEGACY shared bucket that held per-company assets (3D models, item
+ * thumbnails, document attachments) under a `{companyId}/` prefix. Current
+ * writes go to the company's own bucket (bucket id = companyId, same object
+ * keys); files uploaded before the per-company bucket migration may still live
+ * here, so backup reads try the company bucket first and fall back.
*/
export const STORAGE_BUCKET = "private";
/**
- * TEXT columns that hold a storage path (`{companyId}/…/{id}.ext`) in the
- * `private` backup bucket. On reseed the companyId and the embedded ids both
- * change, so these must be rewritten in lock-step with the files they point at
- * (see `rewriteStoragePath`).
+ * TEXT columns holding a storage path (`{companyId}/…/{id}.ext`). A cross-company
+ * restore changes both the companyId and the embedded ids, so these are rewritten
+ * in lock-step with the files they point at (`rewriteStoragePath`).
*
- * `modelPath` (the raw CAD source) is intentionally excluded — raw models live in
- * the `temp-staging` bucket (2.5 GB, transient), not `private`, so they are not
- * carried by a backup. A restored model keeps its thumbnail; its 3D artifacts are
- * regenerated by re-optimising if the raw is re-uploaded.
+ * A backup collects assets by LISTING the bucket under `{companyId}/`, not from
+ * these columns — so every `modelUpload` artifact is carried regardless, and a
+ * column missing here silently survives the restore still pointing at the SOURCE
+ * company. Add a new `modelUpload` path column here too; the coverage test in
+ * `company-backup.closure.test.ts` fails to COMPILE otherwise — it derives the
+ * column set from the generated `modelUpload` row type.
*/
-export const STORAGE_PATH_COLUMNS = new Set(["thumbnailPath"]);
+export const STORAGE_PATH_COLUMNS = new Set([
+ "thumbnailPath",
+ "modelPath",
+ "originalPath",
+ "optimizedModelPath",
+ "glbPath",
+ "graphPath"
+]);
+
+/**
+ * Item-child tables — one per `itemType` enum member — whose `id` is a
+ * human-authored part number (`ADCS-001`), not an identifier. Rows match it by
+ * VALUE against `item."readableId"` with no FK expressing the link, so
+ * `buildIdMaps` must leave it alone: minting a fresh id orphans every row from
+ * its item and the list views render empty against a full table.
+ *
+ * Keeping these ids is safe only because they carry no global `UNIQUE (id)` —
+ * that is what separates them from the composite-PK tables the id-remap exists
+ * for (`balloon`, `inspectionDocument`, …), whose preserved ids WOULD collide
+ * with the source company's live rows. The two sets must stay disjoint, and an
+ * explicit list is required: the schema shape alone also matches ~65 tables
+ * (`workflow`, `kanban`, …) that do need remapping. Both invariants are pinned
+ * in `company-backup.closure.test.ts`.
+ */
+export const READABLE_ID_TABLES = new Set([
+ "part",
+ "material",
+ "consumable",
+ "service",
+ "tool",
+ "fixture"
+]);
/**
* Prefix in the `private` bucket where onboarding demo-template assets live ONCE
@@ -633,12 +667,27 @@ export async function copyAssetsToBackup(
sourcePaths,
ASSET_COPY_CONCURRENCY,
async (path) => {
- const { ok, error } = await copyStorageObject(client, {
- srcBucket: STORAGE_BUCKET,
+ // Assets live in the company's own bucket (keys start with companyId);
+ // pre-migration files still live in the legacy shared bucket. A key with
+ // no companyId segment can only live in the legacy bucket.
+ const companySegment = path.split("/")[0] ?? "";
+ const companyBucket = companySegment
+ ? getCompanyPrivateBucket(companySegment)
+ : STORAGE_BUCKET;
+ let { ok, error } = await copyStorageObject(client, {
+ srcBucket: companyBucket,
srcPath: path,
destBucket,
destPath: `${destPrefix}/${path}`
});
+ if (!ok) {
+ ({ ok, error } = await copyStorageObject(client, {
+ srcBucket: STORAGE_BUCKET,
+ srcPath: path,
+ destBucket,
+ destPath: `${destPrefix}/${path}`
+ }));
+ }
if (ok) {
copied++;
} else {
@@ -652,9 +701,9 @@ export async function copyAssetsToBackup(
}
/**
- * Copy a backup's stored assets back into the shared `private` bucket for the
- * target company, rewriting each path for a foreign/reseed restore (no-op for an
- * own restore). Server-side, best-effort. Every write is guarded to the target
+ * Copy a backup's stored assets back into the target company's own private
+ * bucket, rewriting each path for a foreign/reseed restore (no-op for an own
+ * restore). Server-side, best-effort. Every write is guarded to the target
* company's own `{companyId}/` prefix so a malformed path can never land in
* another tenant's space.
*/
@@ -695,7 +744,7 @@ export async function restoreAssetsFromBackup(
const { ok, error } = await copyStorageObject(client, {
srcBucket,
srcPath: `${srcPrefix}/${file.path}`,
- destBucket: STORAGE_BUCKET,
+ destBucket: getCompanyPrivateBucket(companyId),
destPath: targetPath
});
if (ok) {
diff --git a/packages/jobs/src/inngest/functions/tasks/company-export.ts b/packages/jobs/src/inngest/functions/tasks/company-export.ts
index 8139b926c5..34c795755a 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-export.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-export.ts
@@ -1,4 +1,5 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { getCompanyPrivateBucket } from "@carbon/files";
import { getLogger } from "@carbon/logger";
import { NonRetriableError } from "inngest";
import { sql } from "kysely";
@@ -240,11 +241,21 @@ export async function buildCompanyBackup(
if (includeStorage === "all") {
let totalBytes = 0;
- const paths = await listBucketFilesRecursive(
- client,
- STORAGE_BUCKET,
- companyId
- );
+ // Assets live in the company's own bucket; files uploaded before the
+ // per-company bucket migration still live in the legacy shared bucket.
+ // Union both listings (same keys), preferring the company bucket's copy.
+ const [companyPaths, legacyPaths] = await Promise.all([
+ listBucketFilesRecursive(
+ client,
+ getCompanyPrivateBucket(companyId),
+ companyId
+ ),
+ listBucketFilesRecursive(client, STORAGE_BUCKET, companyId)
+ ]);
+ const byPath = new Map<string, { path: string; size: number }>();
+ for (const file of legacyPaths) byPath.set(file.path, file);
+ for (const file of companyPaths) byPath.set(file.path, file);
+ const paths = Array.from(byPath.values());
for (const file of paths) {
const included = totalBytes + file.size <= MAX_STORAGE_TOTAL_BYTES;
if (included) {
diff --git a/packages/jobs/src/inngest/functions/tasks/model-optimize.ts b/packages/jobs/src/inngest/functions/tasks/model-optimize.ts
index fd6a811fd1..f1cc6c5b8c 100644
--- a/packages/jobs/src/inngest/functions/tasks/model-optimize.ts
+++ b/packages/jobs/src/inngest/functions/tasks/model-optimize.ts
@@ -1,5 +1,6 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import type { Json } from "@carbon/database";
+import { storage } from "@carbon/files";
import { modelPathOptimizeFormat } from "@carbon/files/cad";
import { inngest } from "../../client";
import {
@@ -188,8 +189,8 @@ export const modelOptimizeFunction = inngest.createFunction(
},
mintUploadUrls: async () => {
const client = getCarbonServiceRole();
- const upload = await client.storage
- .from("private")
+ const upload = await storage(client)
+ .company(companyId)
.createSignedUploadUrl(optimizedPath, { upsert: true });
const urls: Record<string, string> = {};
if (upload.data)
@@ -205,12 +206,11 @@ export const modelOptimizeFunction = inngest.createFunction(
// it via the late-mint URL, so the job never holds the bytes) to surface
// the reduction against the untouched source `size`.
const dir = `${companyId}/models/${modelUploadId}`;
- const listed = await client.storage
- .from("private")
+ const listed = await storage(client)
+ .company(companyId)
.list(dir, { search: "optimized.glb" });
- const optimizedSize =
- listed.data?.find((o) => o.name === "optimized.glb")?.metadata?.size ??
- null;
+ const optimized = listed.data?.find((o) => o.name === "optimized.glb");
+ const optimizedSize = optimized?.metadata?.size ?? null;
await client
.from("modelUpload")
diff --git a/packages/jobs/src/inngest/functions/tasks/model-thumbnail.ts b/packages/jobs/src/inngest/functions/tasks/model-thumbnail.ts
index 42e1507d93..cf460b4068 100644
--- a/packages/jobs/src/inngest/functions/tasks/model-thumbnail.ts
+++ b/packages/jobs/src/inngest/functions/tasks/model-thumbnail.ts
@@ -5,6 +5,7 @@ import {
SUPABASE_INTERNAL_URL,
VERCEL_URL
} from "@carbon/env";
+import { storage } from "@carbon/files";
import { nanoid } from "nanoid";
import { inngest } from "../../client";
@@ -92,8 +93,8 @@ export const modelThumbnailFunction = inngest.createFunction(
logger.info("Uploading thumbnail", { fileName });
- const { data, error } = await client.storage
- .from("private")
+ const { data, error } = await storage(client)
+ .company(companyId)
.upload(
`${companyId}/thumbnails/${modelId}/${fileName}`,
thumbnailFile,
@@ -125,8 +126,8 @@ export const modelThumbnailFunction = inngest.createFunction(
// Drop the superseded thumbnail (best-effort — never fail the run over it).
if (previousPath && previousPath !== data?.path) {
- await client.storage
- .from("private")
+ await storage(client)
+ .company(companyId)
.remove([previousPath])
.catch(() => undefined);
}
diff --git a/packages/jobs/src/inngest/functions/tasks/print-job/renderers.tsx b/packages/jobs/src/inngest/functions/tasks/print-job/renderers.tsx
index c016c91cef..8a39f9a68e 100644
--- a/packages/jobs/src/inngest/functions/tasks/print-job/renderers.tsx
+++ b/packages/jobs/src/inngest/functions/tasks/print-job/renderers.tsx
@@ -15,6 +15,7 @@ import {
generateStorageUnitLabelZPL
} from "@carbon/documents/zpl";
import { ERP_URL, SUPABASE_INTERNAL_URL } from "@carbon/env";
+import { storage } from "@carbon/files";
import { renderWithBinderyPress } from "@carbon/printing/printing.server";
import type { LabelSize, ProductLabelItem } from "@carbon/utils";
import { labelSizes } from "@carbon/utils";
@@ -201,8 +202,10 @@ async function renderKanbanCardPDF(
let thumbnail: string | null = null;
if (item.thumbnailPath) {
- const { data } = await client.storage
- .from("private")
+ // Private object paths are prefixed with the owning companyId segment.
+ const companyId = item.thumbnailPath.split("/")[0] ?? "";
+ const { data } = await storage(client)
+ .company(companyId)
.download(item.thumbnailPath);
if (data) {
const buffer = Buffer.from(await data.arrayBuffer());
diff --git a/packages/lib/package.json b/packages/lib/package.json
index 9ee5fdac13..2f301340ad 100644
--- a/packages/lib/package.json
+++ b/packages/lib/package.json
@@ -3,9 +3,11 @@
"dependencies": {
"@carbon/database": "workspace:*",
"@carbon/env": "workspace:*",
+ "@carbon/files": "workspace:*",
"@carbon/kv": "workspace:*",
"@carbon/logger": "workspace:*",
"@carbon/notifications": "workspace:*",
+ "@carbon/utils": "workspace:*",
"@carbon/workflows": "workspace:*",
"@slack/web-api": "catalog:",
"@supabase/supabase-js": "catalog:",
diff --git a/packages/lib/src/slack.server.ts b/packages/lib/src/slack.server.ts
index 8bec832f6b..8a81c41721 100644
--- a/packages/lib/src/slack.server.ts
+++ b/packages/lib/src/slack.server.ts
@@ -1,5 +1,6 @@
import type { Database } from "@carbon/database";
import { getAppUrl, SLACK_BOT_TOKEN } from "@carbon/env";
+import { storage } from "@carbon/files";
import { getLogger } from "@carbon/logger";
import type { WebClientOptions } from "@slack/web-api";
import { WebClient } from "@slack/web-api";
@@ -114,8 +115,8 @@ export async function postSuggestionToCarbonSlack(
.single()
: Promise.resolve(null),
input.attachmentPath
- ? client.storage
- .from("private")
+ ? storage(client)
+ .company(input.companyId)
.createSignedUrl(input.attachmentPath, 60 * 60 * 24 * 7)
.then((result) => result.data?.signedUrl ?? null)
: Promise.resolve(null)
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 32e7246e6e..ddca23a006 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2484,6 +2484,9 @@ importers:
'@jsquash/webp':
specifier: 1.5.0
version: 1.5.0
+ '@supabase/storage-js':
+ specifier: 'catalog:'
+ version: 2.80.0
'@supabase/supabase-js':
specifier: 'catalog:'
version: 2.80.0
@@ -2858,6 +2861,9 @@ importers:
'@carbon/env':
specifier: workspace:*
version: link:../env
+ '@carbon/files':
+ specifier: workspace:*
+ version: link:../files
'@carbon/kv':
specifier: workspace:*
version: link:../kv
@@ -2867,6 +2873,9 @@ importers:
'@carbon/notifications':
specifier: workspace:*
version: link:../notifications
+ '@carbon/utils':
+ specifier: workspace:*
+ version: link:../utils
'@carbon/workflows':
specifier: workspace:*
version: link:../workflows
diff --git a/scripts/model-upload.ts b/scripts/model-upload.ts
index c208c8141a..52737c281e 100644
--- a/scripts/model-upload.ts
+++ b/scripts/model-upload.ts
@@ -42,7 +42,7 @@ const {
const client = createScriptClient(carbonApiUrl, carbonPublicKey, apiKey);
const { error: uploadError } = await client.storage
- .from("private")
+ .from(companyId)
.upload(modelPath, fileBuffer, {
contentType: "application/octet-stream"
});
diff --git a/scripts/one-off/README.md b/scripts/one-off/README.md
new file mode 100644
index 0000000000..676b0724c9
--- /dev/null
+++ b/scripts/one-off/README.md
@@ -0,0 +1,73 @@
+# One-off scripts
+
+Scripts in this folder run **exactly once per database**, automatically, on the
+next deploy — and then never again.
+
+Everything else belongs in `scripts/`. This folder is only for one-time data
+migrations: work that must happen once against existing data, that a SQL
+migration cannot do (because it talks to Storage, an external API, or needs
+application logic), and that is meaningless to run a second time.
+
+## How a script here gets run
+
+1. `.github/workflows/supabase.yml` runs `pnpm --filter ci ci:migrations` on
+ pushes to `main` under `packages/database/supabase/**`.
+2. For each workspace, `ci/src/migrations.ts` applies migrations
+ (`supabase db push`), then calls `runPendingScripts`.
+3. That reads the **target database's own** `scriptRun` table, runs the listed
+ scripts with no row there, and inserts a row for each one that succeeds.
+
+Nobody runs these by hand in production. Merging is what ships them.
+
+## Adding a script
+
+1. Drop a `<kebab-case>.ts` file in this folder. That is the registration —
+ every such file is discovered automatically, so there is no list to update.
+ The name must be lower-case words separated by hyphens; anything else
+ (dotted names, underscores, capitals, non-`.ts` files) fails the deploy
+ with an error rather than being silently skipped.
+2. Take configuration from `SUPABASE_URL` and `SUPABASE_SERVICE_ROLE_KEY` in
+ the environment; the runner injects the per-workspace values. Support
+ `--dry-run` if the script writes anything.
+3. Ship it **alongside a migration**, or it will not deploy on its own — the
+ workflow only triggers on `packages/database/supabase/**` changes. Without
+ one, run the workflow manually (`workflow_dispatch`).
+
+Anything that is not a one-time data migration does not belong in this folder:
+putting it here means it runs against every production database on the next
+deploy. **In particular, do not colocate tests here** — `scripts/lib/` keeps
+`*.test.ts` beside its sources, but that convention is refused in this folder
+precisely because a discovered file gets executed in production. Put tests for
+a one-off script in `ci/src/` or beside the code it exercises.
+
+### Two rules that are not optional
+
+**It must be idempotent.** The ledger row is written *after* the script
+succeeds, so a crash between the work and the record means the next deploy runs
+it again. A script that cannot survive a second run will corrupt data here.
+
+**Its filename is permanent.** The `scriptRun` table is keyed on the file's
+basename. Renaming the file makes every database look like it has never run
+the script, and it runs again everywhere.
+
+## Why the ledger lives in the target database
+
+"Has this script run here?" is a fact about a specific database, so it travels
+with it: a workspace that is cloned, restored, or re-pointed at another project
+carries the right answer rather than inheriting a stale flag from elsewhere.
+Self-hosted instances get the same bookkeeping from `supabase db push` alone,
+with no control-plane table to replicate.
+
+`scriptRun` is deliberately not tenant-scoped — it has no `companyId` or
+`companyGroupId` — so `selectWipeableTables` in `company-backup.ts` cannot
+select it and a company restore can never erase the ledger and cause a re-run.
+
+Note this is separate from the database **seed** (`packages/database/src/seed.ts`),
+which is gated by the `seeded` boolean on the CI `workspaces` row and is not
+part of this mechanism.
+
+## Removing a script
+
+Once every deployment has run it, delete the file. Leave the `scriptRun` row
+alone — it is the record that the work happened.
+Each script's header comment should say what condition makes it safe to remove.
diff --git a/scripts/one-off/migrate-private-buckets.ts b/scripts/one-off/migrate-private-buckets.ts
new file mode 100644
index 0000000000..88ffb0eeee
--- /dev/null
+++ b/scripts/one-off/migrate-private-buckets.ts
@@ -0,0 +1,165 @@
+import { createRequire } from "node:module";
+import { readLocalScriptConfig } from "../lib/local-script-config";
+
+// One-off, idempotent migration: copy the legacy shared `private` bucket's
+// objects into each company's own bucket (bucket id = companyId). Object keys
+// are identical in both buckets (they start with `${companyId}/`).
+// Nothing is ever deleted. Re-running skips objects that already exist.
+//
+// COVERAGE: only objects under a LIVE company's `${companyId}/` prefix are
+// copied. Legacy objects under any other prefix — pre-migration audit
+// archives at `audit-logs/{companyId}/...`, prefixes of deleted companies —
+// are NOT copied and remain readable only via the legacy-bucket fallback.
+// Do not decommission the legacy bucket until those are handled explicitly.
+//
+// Usage:
+// pnpm exec tsx scripts/one-off/migrate-private-buckets.ts # migrate
+// pnpm exec tsx scripts/one-off/migrate-private-buckets.ts --dry-run # read-only
+
+const LEGACY_BUCKET = "private";
+const BUCKET_FILE_SIZE_LIMIT = 52428800; // 50 MB
+const LIST_PAGE_SIZE = 1000;
+
+const isDryRun = process.argv.includes("--dry-run");
+
+const { SUPABASE_URL: supabaseUrl, SUPABASE_SERVICE_ROLE_KEY: serviceRoleKey } =
+ readLocalScriptConfig(
+ ["SUPABASE_URL", "SUPABASE_SERVICE_ROLE_KEY"],
+ process.env
+ );
+
+function createServiceRoleClient(url: string, serviceRole: string) {
+ // The database workspace declares and pins this dependency; root scripts do not.
+ const fromDatabase = createRequire(
+ new URL("../../packages/database/package.json", import.meta.url)
+ );
+ const { createClient } = fromDatabase("@supabase/supabase-js");
+ return createClient(url, serviceRole, {
+ auth: { autoRefreshToken: false, persistSession: false }
+ });
+}
+
+const client = createServiceRoleClient(supabaseUrl, serviceRoleKey);
+
+type CompanySummary = { copied: number; skipped: number; failed: number };
+
+function isAlreadyExistsError(error: { message?: string; statusCode?: string | number }) {
+ const message = error.message ?? "";
+ return (
+ /already exists/i.test(message) ||
+ /duplicate/i.test(message) ||
+ String(error.statusCode) === "409"
+ );
+}
+
+async function getCompanyIds(): Promise<string[]> {
+ const ids: string[] = [];
+ for (let offset = 0; ; offset += LIST_PAGE_SIZE) {
+ const { data, error } = await client
+ .from("company")
+ .select("id")
+ .order("id")
+ .range(offset, offset + LIST_PAGE_SIZE - 1);
+ if (error) throw new Error(`Failed to read company table: ${error.message}`);
+ ids.push(...data.map((row: { id: string }) => row.id));
+ if (data.length < LIST_PAGE_SIZE) break;
+ }
+ return ids;
+}
+
+// Recursively list every object key under `prefix` in the legacy bucket.
+// Storage list returns folders as entries with id === null; recurse into them.
+async function listObjectKeys(prefix: string): Promise<string[]> {
+ const keys: string[] = [];
+ for (let offset = 0; ; offset += LIST_PAGE_SIZE) {
+ const { data, error } = await client.storage
+ .from(LEGACY_BUCKET)
+ .list(prefix, { limit: LIST_PAGE_SIZE, offset });
+ if (error) {
+ throw new Error(`Failed to list ${LEGACY_BUCKET}/${prefix}: ${error.message}`);
+ }
+ for (const entry of data as Array<{ name: string; id: string | null }>) {
+ if (entry.id === null) {
+ keys.push(...(await listObjectKeys(`${prefix}/${entry.name}`)));
+ } else {
+ keys.push(`${prefix}/${entry.name}`);
+ }
+ }
+ if (data.length < LIST_PAGE_SIZE) break;
+ }
+ return keys;
+}
+
+async function ensureBucket(companyId: string) {
+ const { error } = await client.storage.createBucket(companyId, {
+ public: false,
+ fileSizeLimit: BUCKET_FILE_SIZE_LIMIT
+ });
+ if (error && !isAlreadyExistsError(error)) {
+ throw new Error(`Failed to create bucket ${companyId}: ${error.message}`);
+ }
+}
+
+async function migrateCompany(companyId: string): Promise<CompanySummary> {
+ const summary: CompanySummary = { copied: 0, skipped: 0, failed: 0 };
+
+ if (!isDryRun) {
+ await ensureBucket(companyId);
+ }
+
+ const keys = await listObjectKeys(companyId);
+
+ for (const key of keys) {
+ if (isDryRun) {
+ process.stdout.write(` would copy ${LEGACY_BUCKET}/${key} -> ${companyId}/${key}\n`);
+ summary.copied += 1;
+ continue;
+ }
+
+ const { error } = await client.storage
+ .from(LEGACY_BUCKET)
+ .copy(key, key, { destinationBucket: companyId });
+
+ if (!error) {
+ summary.copied += 1;
+ } else if (isAlreadyExistsError(error)) {
+ summary.skipped += 1;
+ } else {
+ summary.failed += 1;
+ process.stderr.write(` FAILED ${companyId}: ${key} — ${error.message}\n`);
+ }
+ }
+
+ return summary;
+}
+
+(async () => {
+ if (isDryRun) {
+ process.stdout.write("Dry run — no buckets created, no objects copied.\n");
+ }
+
+ const companyIds = await getCompanyIds();
+ process.stdout.write(`Found ${companyIds.length} companies.\n`);
+
+ const total: CompanySummary = { copied: 0, skipped: 0, failed: 0 };
+
+ for (const companyId of companyIds) {
+ process.stdout.write(`\nCompany ${companyId}\n`);
+ const summary = await migrateCompany(companyId);
+ total.copied += summary.copied;
+ total.skipped += summary.skipped;
+ total.failed += summary.failed;
+ process.stdout.write(` ${JSON.stringify(summary)}\n`);
+ }
+
+ process.stdout.write(
+ `\nTotal${isDryRun ? " (dry run)" : ""}: ${JSON.stringify(total)}\n`
+ );
+
+ if (total.failed > 0) {
+ process.exitCode = 1;
+ }
+})().catch((err) => {
+ process.stderr.write(`Migration failed: ${(err as Error).message}\n`);
+ process.exitCode = 1;
+});