f24b26a139
* fix(security): gate replace_sie_import behind owner/admin membership The RPC was SECURITY DEFINER with EXECUTE granted to PUBLIC and anon, no company_members lookup, no auth.uid() reference and no unauthorized raise, while setting gnubok.allow_delete to disarm the BFL immutability and retention triggers. Any caller holding a company_id and an import id could hard delete another tenant's verifikationer. Confirmed live in production. Applies the same fail closed owner/admin guard that undo_sie_import already carries (migration 20260624120000), resolving the actor from COALESCE(p_user_id, auth.uid()) so it denies when the role is NULL, then revokes EXECUTE from PUBLIC and anon. search_path and the raised statement_timeout are restated, since CREATE OR REPLACE drops settings that are not repeated. userId is a required parameter on replaceSIEImport: the service client has a NULL auth.uid(), so a caller without an explicit actor now fails to compile rather than hitting the closed gate at runtime. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(security): validate arcim OAuth callback state server side The callback route is skipAuth and decoded the state parameter as plain base64url JSON, trusting consentId and provider from it. A one time code was minted at flow start and never read. An unauthenticated attacker who learned a consent id could run an OAuth flow on their own provider account and post the callback with a forged state, landing their tokens on another tenant's consent, so the victim's next migration imported the attacker's ledger. State is now an opaque randomBytes(32) pointer to a provider_otc row, consumed by a single atomic UPDATE guarded on used_at IS NULL and expires_at, so a replay loses the row lock race and updates nothing. provider is read from provider_consents rather than trusted from the client. provider_otc already existed for exactly this purpose and was never wired up. Also scopes getConsent to an owning company, closing a cross tenant status oracle where the preview and migrate paths echoed a consent's status before the scoped check ran. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(security): scope documents storage to company_id (phase A) The documents bucket policies matched on auth.uid(), and upload keys were documents/{userId}/..., so company membership was never consulted. Removing a member revoked nothing: their session still authenticated and they kept direct Storage read access to every receipt, supplier invoice and bank statement they had uploaded. The same bug was fixed for sie-files in 20260416120000; this bucket was left behind. Phase A is additive. Company scoped policies are added alongside the uploader scoped ones, uploads move to documents/{companyId}/{userId}/..., and reads accept either layout so nothing breaks mid migration. Phase C, which drops the old policies, is gated on the backfill reporting zero remaining legacy prefix objects. The policy compares the company segment as text rather than casting to uuid the way sie-files does: this bucket holds keys whose second segment is not a uuid (MCP audit packages), and Postgres does not guarantee the bucket prefix qual runs before the cast, so a planner reordering would raise 22P02 and fail the whole query instead of filtering the row out. deleteDocument now removes both candidate keys. Removing only the stored pointer would leave a readable orphan copy of a document the user asked to erase. The backfill script is included but has never been run. It defaults to dry run, refuses .env.local by name, and verifies each copy is readable and SHA-256 identical before repointing the row. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(security): enforce events:read scope and membership on /api/events This was the only one of the three validateApiKey call sites with no downstream guard: v1 and the MCP server both check scope and re-verify company membership, this route did neither. An events:read scope existed and was documented as gating the endpoint but was never called, so a legacy key falling back to DEFAULT_SCOPES read the full log. The bound company id went straight from the api_keys row into a service role query, so a key whose user had been removed from the company kept reading. Adds the scope check before any database access, re-verifies company_members with archived_at IS NULL, honours test mode by stamping X-Gnubok-Mode instead of ignoring it, applies minimisePayload so the pull surface can never return a wider payload than the push surface, and replaces the three flat error strings with the canonical envelope. Test key reads are served rather than blocked: TEST_KEY_WRITE_BLOCKED is gated on mutations in with-api-v1, so a read gets the same treatment as every other v1 read endpoint. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * perf(bookkeeping): sweep remaining journal_entries!inner embeds A previous refactor removed this pattern from lib/reports and introduced fetchEntryLines, but the class was never swept. Seventeen sites remained and had become the top application consumer of production database time: measured across the resulting query shapes, 32,694 calls and 25,848 seconds of execution, mean 790ms, with shapes averaging 2.6s and 3.0s and maxing at 7,962ms against the 8s statement_timeout, which surfaced to users as 500s on the booking path. PostgREST compiles an embed with filters on the embedded side into a correlated INNER JOIN LATERAL with a parameterized LIMIT, which stops Postgres reordering the join, so each query walked the whole journal_entry_lines table across all tenants. Driving from the entries side instead turns that into two indexed round trips. Converted sites keep their existing shape: the helper reattaches the parent entry under the same key the embed produced. Several conversions also remove a latent silent truncation where an unpaginated query was capped at PostgREST's 1000 row ceiling. Two deliberate exceptions. The free text ilike legs of the MCP display query stay on the embed, because each is capped at legLimit and that cap drives the truncation contract the tool reports, while the helper is unbounded. The accounts route moves to the existing get_account_usage_counts RPC instead, since its embed was a head count and the helper returns rows. commitEntry's write path is untouched: the change there is confined to the read query of the pre-commit dimension rule check. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(api): anchor v1 list cursors on created_at Page two returned page one, forever, while still advertising a fresh next_cursor. The three routes sorted by and encoded a Postgres date column, which serializes as YYYY-MM-DD, but decodeDefaultCursor validates the cursor timestamp as full ISO-8601 and returned null, so the keyset filter was never applied and has_more never went false. An integrator syncing verifikat looped on the newest rows indefinitely. The transactions route already solved this and its comment names the trap; the fix was never ported. All three now order and encode on created_at with an id tie break, matching the transactions keyset predicate exactly. ISO_TIMESTAMP is deliberately left alone: relaxing it would silently change sort semantics on the route that currently works. Default ordering therefore moves from business date to insert order. Every business date is still on the row, and the invoices list gains date_from and date_to filters so a date range is still reachable; the other two already had them. The tests use an in-memory PostgREST that actually evaluates the filters, because the repo's pass-through mock cannot catch this class of bug: the bug is that the filter is never sent. They walk to exhaustion with a hard iteration cap, so an unterminated walk fails instead of hanging. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(api): separate dry run from commit in the idempotency hash The request hash was built from url.pathname, which excludes the query string, so a dry run and its commit hashed identically. Following the flow documented in dry-run.ts, re-issuing the request with the same Idempotency-Key returned the cached preview with Idempotent-Replayed set and wrote nothing, while reporting 200. An agent or integrator saw success for a write that never happened. dry_run is folded into the hash only when true, not as an unconditional boolean. Including it as false would change the hash of every ordinary write, and with a 24h idempotency TTL any key in flight across the deploy would fail the request_hash comparison and 409 on a legitimate retry. Both hash call sites now go through one shared helper so they cannot drift into a permanent cache miss, and dry run responses are no longer stored at all. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * ci: install the Bedrock SDK out of tree in the compliance review The Swedish accounting compliance gate had failed ten consecutive runs and so was posting nothing. With --no-package-lock npm discarded the lockfile and re-resolved the whole tree from package.json, floating @hookform/resolvers to 5.4.3, whose valibot ^1 peer conflicts with the pinned valibot 0.39.0. Installing into the parent of the checkout resolves only that one package, so an unrelated peer conflict can never take the gate down again. Node still finds it because ESM bare specifiers walk up parent node_modules; NODE_PATH would not have worked, as it is CommonJS only. --legacy-peer-deps was rejected because it masks future genuine peer conflicts and still reifies the full tree. The same step's SDK version is aligned from 0.31.0 back to the 0.29.1 that package.json and check:guards enforce after the streaming outage. That drift went unnoticed because the pin guard only inspects package.json and the lockfile, never workflow files. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * build(docker): generate crontabs from vercel.json vercel.json defines 16 cron jobs; both Docker crontabs carried 9, and were byte identical to each other. Self hosted deployments therefore never sent recurring invoices, never dispatched webhooks and never cleaned up idempotency keys. tax-deadlines also ran once a year on 2 January instead of daily, and documents/verify weekly instead of daily. Extension crons are included rather than excluded. The Dockerfile copies the whole tree before building, so every extension cron route is compiled into the image regardless of the enabled preset, and each returns 200 when its extension is unconfigured, so curl -sf logs no failure. Two such entries were already present in the crontab for extensions absent from the preset, which settles the intent. documents/verify is treated as drift rather than a self hosted concession: the weekly cadence was present in the hosted crontab too, and the run is capped at 200 documents walking a nulls-first queue, so weekly drains the integrity queue seven times slower on a check that exists for BFL retention. webhooks/dispatch keeps its per minute cadence, adding 1,440 requests a day on self hosted. A gentler tick would silently stretch the first retry, since the retry ladder opens at 60 seconds. SCHEDULE_OVERRIDES is the one line place to change that. A parity test asserts the path sets match minus a documented exclusion list, and ratchets three cron routes that are currently scheduled nowhere so they are named rather than silently rotting. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * chore(observability): add a provider agnostic error sink There is no error tracking in this codebase: logs go to console and Vercel retention and nowhere else, nothing alerts on the 16 cron jobs, and seven code comments across lib, app, components and extensions asserted that Sentry captures errors when Sentry is not a dependency. The two most recent bug fixes on this repo were both discovered by customer email. This adds the sink, not a vendor. No dependency is taken: the interface has a no-op default and a registration point, so behaviour is unchanged until an adapter is registered. Releases are tagged from the build id already inlined by next.config.ts. Redaction moved out of lib/logger.ts into a leaf module that both the logger and the sink import, so there is one denylist and no path from application data to a third party can skip the personnummer regex, including direct sink calls that bypass the logger. That matters here because these logs carry personnummer and financial data. verifyCronSecret now reports its own 401s, which covers all 16 jobs without touching a route file and catches the case where CRON_SECRET is rotated without updating the scheduler and every job silently 401s forever. The threshold is one failure rather than the backup alert's three: suppressing the first occurrence is precisely how an outage stays invisible. The seven misleading comments are corrected to describe what the code actually does, including the two cases that still are not covered: the client side one, since the sink is server side, and a warn level call that is not forwarded. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix: remediate the 2026-07-26 similar-sweep findings across all surfaces Resolves the ~150-finding sweep (dev_docs/similar-sweep-2026-07-26.md) with one agent per finding; every behavioural fix carries a regression test proven to fail at HEAD. Full status, corrections to the sweep, refusals and open decisions in dev_docs/similar-sweep-2026-07-26-remediation-status.md. Structural roots closed: - resolveSekAmountOrNull(): honest SEK resolution refuses instead of booking 1:1; four duplicated toSek closures now refuse via INVOICE_FX_RATE_MISSING - ledger-line-amount.ts: journal_entry_lines.currency labels the document, not the amount; SQL pre-filter decoy proven and fixed - sparse-patch.ts: .partial() does not strip .default() in Zod 4.4.3; the exploitable salary payslip-line PATCH and KPI preferences sinks fixed - tests/schema: migration-replay phantom-column guard (13k+ refs, closed CHECK sets, onConflict targets); found 28 real defects, all fixed, all four baselines now empty - three new ratchet guards: sek-labelled-amount, cross-extension-import, ungated-extension-route Highlights: lawful VAT-rate set on all seven invoice surfaces (ML 6 kap), RC input VAT mismatch wired on web + both MCP callers, missing-underlag resource delegates to the shared RPC predicate, push-notifications consent polarity fail-closed, deadlines undo honours requested state, silent-failure and read-side-fabrication classes fixed across settings/KPI/inbox/Stripe/ Arcim/kassaflodesanalys, error-envelope stringification fixed at 10+ sites with isSwedishUserMessage extended. Also includes the parallel session's MCP invoice tools (update_invoice, recurring schedules, invoice deliveries) which share files with the sweep work and are verified green together. 13 new migrations are NOT applied anywhere; they apply via branch merge. 20260726120000 backfills 1247 supplier-invoice rows. pg tests for new DDL are written but unrun (no local Postgres). Verified: 11088 tests / 881 files green, tsc 0 non-test errors, lint 0 errors, check:guards passing, MCP payload 57475/57500. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(migrations): rename replace_sie_import migration off main's 20260726090000 version origin/main shipped 20260726090000_agent_quota_rpc_caller_guard.sql; keeping our replace_sie_import migration on the same version would abort the Supabase apply with a schema_migrations_pkey duplicate at merge time. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(review): remediate pre-publish deep-review findings across all slices A 13-agent review of the full branch diff surfaced 1 critical, 5 high and ~45 further findings; this commit resolves them in one pass: - replace_sie_import / undo_sie_import: p_user_id honored only for service_role callers; any other caller is pinned to auth.uid() (impersonation gate bypass), authz raise errcode 42501 mapped to a Swedish 403 in the route, new caller-guard migration for undo - bulk_book_transactions refuses homogeneous non-SEK batches instead of writing foreign magnitudes into SEK ledger columns - credit-note cap trigger: company-match on credited_invoice_id, no cross-tenant figures in exception text - link_voucher RPCs resolve NULL invoice currency as SEK end to end - personal-number ciphertext CHECK split into NOT VALID + VALIDATE - same-currency foreign settlements clear 1510 at booking rate and book realized diff to 3960/7960; rate-less foreign write paths refuse - receivables revaluation covers partially_paid and outstanding amounts - period lock guard paginates candidates past the PostgREST 1000 cap - documents: service-client storage removals after authz, dual-layout reads in integrity cron and archive export, backfill delete-source sweep actually deletes with hash verification and shared-key grouping - invoice matching normalizes NULL/lowercase currencies (regression), duplicate candidates stop claiming amount matches they never ran - match-invoice aborts on any booking failure (no paid-without-verifikat) - refresh-exchange-rate reverts on concurrent booking (TOCTOU window) - KPI preferences upsert arbiter aligned to the company-scoped constraint - personnummer_last4 stripped from all salary responses incl. MCP tools - worked-hours batch restores destroyed rows on conflict and error paths - MCP: shared duplicate-claim builder (no more 'null kr'), short-circuit on tag_journal_lines overflow, auto_send schedules stage as high risk - observability sink redacts emails/IBANs/API keys and keeps redacted stacks in prod; assorted small guards (safe-return-to /@, dry_run=True, cursor helper off-by-one, OAuth state TTL 10 min, arcim saveMappings call removed) Full dispositions, deferred items and hand-verified accounting numbers are documented in the PR body and DECISIONS.md. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(personnummer): implement masking and encryption for personal numbers with tests * fix(review): address CI and compliance-bot findings for PR #1215 pg-real: the CI image's auth shim reads the legacy request.jwt.claim.role GUC, so both service-role simulations (runAsServiceRole and the invoice-delivery test's local helper) never satisfied auth.role() = 'service_role' and every legitimate p_user_id path failed closed; the shared helper now sets both GUC shapes plus SET LOCAL ROLE with a fail-loud sanity check, and the delivery test reuses it. The link-voucher migration had recreated both RPCs from pre-rewrite file text, reintroducing the NULL-unsafe membership pattern the null-safe-tenant-guards ratchet bans; both guards now use public.caller_is_company_member() with all currency changes preserved. Compliance bots: the customers export now emits the standard masked form instead of raw AES-256-GCM ciphertext in the Org-/personnummer column, and maskCustomerRow returns a non-round-trippable placeholder on decrypt failure instead of 500ing the list. MCP parity: gnubok_lock_period's staging pre-check now runs the exact countUnbookedInPeriod the commit path enforces (exported from period-service; local mirror deleted), and gnubok_agi_status resolves AGI state run-scoped so a correction run no longer renders as already filed. Declined with evidence: PR-Agent's opening-balances null-zeroing concern (all mergeable columns are NOT NULL with defaults per 20260713101000). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(review): address codex review findings on PR #1215 - restore 20260726140000 to its preview-recorded content and restate the NULL-safe tenant guard under 20260727130000: a recorded migration version never re-runs, so the in-place edit could not reach the preview branch - replace toFixed() with sv-SE two-decimal formatting in the ROT/RUT cap warning texts and update the pinned test expectations - drop the em dash in the fiscal-periods route comment - strip trailing whitespace in import-existing.test.ts Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(reports): raise timeout on real PDF render tests renderToBuffer does real @react-pdf layout work and exceeds the 5s default when the full suite saturates the CPU; tests pass in isolation. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
901 lines
34 KiB
TypeScript
901 lines
34 KiB
TypeScript
#!/usr/bin/env npx tsx
|
|
/**
|
|
* ============================================================================
|
|
* !! DESTRUCTIVE. READ THIS BEFORE YOU RUN ANYTHING. !!
|
|
* ============================================================================
|
|
*
|
|
* This script MOVES räkenskapsinformation. The objects it touches are kvitton,
|
|
* leverantorsfakturor and kontoutdrag held under the Bokforingslagen 7 kap 2 §
|
|
* SEVEN-YEAR RETENTION requirement. Losing one is a legal incident, not a bug.
|
|
*
|
|
* * ALWAYS run against STAGING first and confirm the counts there.
|
|
* * NEVER point this at .env.local. That file targets the REAL customer
|
|
* database. Pass --env <file> explicitly and read the banner it prints.
|
|
* * The default mode is --dry-run. Moving data requires the explicit
|
|
* --apply flag. Removing the source copies requires --apply AND
|
|
* --delete-source, which should be a SEPARATE run, days after --apply,
|
|
* once the app has been observed serving the new keys.
|
|
*
|
|
* ============================================================================
|
|
* WHAT IT DOES (Phase B of the 3-phase rollout)
|
|
* ============================================================================
|
|
*
|
|
* Phase A (migration 20260726092000_documents_bucket_company_scope.sql) added
|
|
* company-scoped storage policies for the key layout
|
|
*
|
|
* documents/{companyId}/{userId}/{timestamp}_{filename}
|
|
*
|
|
* and switched lib/core/documents/document-service.ts to write that layout.
|
|
* Legacy objects still sit at
|
|
*
|
|
* documents/{userId}/{timestamp}_{filename}
|
|
*
|
|
* where the RLS policy can only scope on auth.uid(), so a removed company
|
|
* member keeps read access to everything they ever uploaded.
|
|
*
|
|
* This script re-homes those legacy objects. Rows are grouped by storage key
|
|
* first: document_attachments.storage_path has NO unique constraint, so
|
|
* several rows can point at one object, and the object may only be released
|
|
* once every one of those rows has been repointed. Per source key, in order:
|
|
*
|
|
* 1. resolve the owning company_id(s) from document_attachments
|
|
* 2. skip rows whose storage_path is already company-scoped (idempotent /
|
|
* resumable)
|
|
* 3. COPY the object to the company-scoped key(s) (never move, never
|
|
* rename; one copy per owning company)
|
|
* 4. VERIFY each new key is readable and byte-identical (SHA-256 compared
|
|
* against document_attachments.sha256_hash when present, otherwise
|
|
* against the source bytes)
|
|
* 5. only then UPDATE storage_path for EVERY row on that key, checking the
|
|
* row count of each UPDATE: a row deleted between fetch and migrate
|
|
* must not count as migrated, or the fresh scoped copy would resurrect
|
|
* an erased document (a copy no row ended up pointing at is rolled
|
|
* back; the source is never touched by that rollback)
|
|
* 6. only with --delete-source, and only after 3-5 succeeded for ALL rows
|
|
* on the key AND the live table confirms zero rows still reference it,
|
|
* remove the legacy object
|
|
*
|
|
* A --delete-source run additionally SWEEPS rows that an earlier --apply run
|
|
* already repointed: their legacy key is derived from the scoped one (the
|
|
* forward mapping is a pure prefix insertion, so the inverse is exact), the
|
|
* scoped copy is re-verified (readable + hash), the live table is checked
|
|
* for remaining references, and only then is the leftover legacy object
|
|
* removed. Without this sweep the documented two-step workflow (--apply
|
|
* first, --delete-source days later) would be a no-op: after --apply no row
|
|
* carries a legacy pointer any more, yet every legacy object still sits in
|
|
* storage, readable by its uploader (including ex-members: the exact hole
|
|
* Phase A exists to close).
|
|
*
|
|
* The source is NEVER deleted before the new key has been confirmed readable
|
|
* and every referencing row repointed. A failure at any step logs the
|
|
* document id and the script continues to the next object; it never aborts
|
|
* the run on a single bad document.
|
|
*
|
|
* ============================================================================
|
|
* PHASE C GATE
|
|
* ============================================================================
|
|
*
|
|
* The final summary prints two counters:
|
|
*
|
|
* legacy_prefix_remaining rows still pointing at a legacy key
|
|
* legacy_objects_remaining legacy objects still present in storage for
|
|
* rows that are already company-scoped (found by
|
|
* the storage-level sweep, which runs read-only
|
|
* in every mode)
|
|
*
|
|
* Phase C (the migration that drops `documents_select_own` /
|
|
* `documents_insert_own`) may only be applied when a --dry-run of this
|
|
* script reports BOTH counters at 0. Dropping those policies earlier makes
|
|
* every un-migrated document unreadable to everyone except the service role,
|
|
* and leftover legacy objects would stay uploader-readable forever.
|
|
*
|
|
* ============================================================================
|
|
* USAGE
|
|
* ============================================================================
|
|
*
|
|
* # 1. Inspect. Changes nothing. This is the default.
|
|
* npx tsx scripts/backfill-document-storage-paths.ts --env .env.staging.local
|
|
*
|
|
* # 2. Copy + verify + repoint. Leaves the legacy objects in place.
|
|
* npx tsx scripts/backfill-document-storage-paths.ts --env .env.staging.local --apply
|
|
*
|
|
* # 3. Days later, after the app has been observed serving new keys:
|
|
* # migrates any stragglers, then sweeps the already-migrated rows and
|
|
* # removes their verified leftover legacy objects.
|
|
* npx tsx scripts/backfill-document-storage-paths.ts --env .env.staging.local --apply --delete-source
|
|
*
|
|
* Flags:
|
|
* --env <file> dotenv file to load. REQUIRED. No default: an implicit
|
|
* .env.local would point at production.
|
|
* --apply actually copy/verify/repoint. Without it: dry run.
|
|
* --delete-source additionally remove legacy objects whose every row has
|
|
* a verified company-scoped copy. Requires --apply.
|
|
* --company <uuid> restrict the run to one company. Use this for the first
|
|
* production batch.
|
|
* --limit <n> process at most n documents this run (resumable: run
|
|
* again to continue). A shared-key group is never split,
|
|
* so the last group may overshoot the limit. Also caps
|
|
* how many leftover legacy objects a --delete-source
|
|
* sweep removes.
|
|
* --yes skip the interactive confirmation prompt.
|
|
*/
|
|
|
|
import { createHash } from 'node:crypto'
|
|
import { basename, resolve } from 'node:path'
|
|
import { createInterface } from 'node:readline/promises'
|
|
import { config } from 'dotenv'
|
|
import { createClient, type SupabaseClient } from '@supabase/supabase-js'
|
|
|
|
const BUCKET = 'documents'
|
|
const PATH_ROOT = 'documents'
|
|
const PAGE_SIZE = 500
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Argument parsing
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function flagValue(name: string): string | undefined {
|
|
const idx = process.argv.indexOf(`--${name}`)
|
|
if (idx === -1) return undefined
|
|
const value = process.argv[idx + 1]
|
|
if (!value || value.startsWith('--')) {
|
|
console.error(`--${name} requires a value`)
|
|
process.exit(1)
|
|
}
|
|
return value
|
|
}
|
|
|
|
const envFile = flagValue('env')
|
|
const apply = process.argv.includes('--apply')
|
|
const deleteSource = process.argv.includes('--delete-source')
|
|
const skipPrompt = process.argv.includes('--yes')
|
|
const onlyCompany = flagValue('company')
|
|
const limitRaw = flagValue('limit')
|
|
const limit = limitRaw ? Number.parseInt(limitRaw, 10) : Number.POSITIVE_INFINITY
|
|
|
|
if (!envFile) {
|
|
console.error(
|
|
'Refusing to run without an explicit --env <file>. An implicit .env.local ' +
|
|
'points at the PRODUCTION database. Example: --env .env.staging.local',
|
|
)
|
|
process.exit(1)
|
|
}
|
|
|
|
// Refuse .env.local no matter how the path is spelled ('./.env.local', an
|
|
// absolute path, backslashes on Windows): normalize before comparing. An
|
|
// exact string compare here was trivially bypassed by './.env.local'. The
|
|
// check runs BEFORE config() so the production env file is never even read.
|
|
if (basename(resolve(envFile)).toLowerCase() === '.env.local') {
|
|
console.error(
|
|
'REFUSING: .env.local points at the production database. If you really ' +
|
|
'intend to run against production, copy the credentials into an ' +
|
|
'explicitly named file (e.g. .env.production.backfill) so the intent ' +
|
|
'is recorded in the command line.',
|
|
)
|
|
process.exit(1)
|
|
}
|
|
|
|
if (deleteSource && !apply) {
|
|
console.error('--delete-source requires --apply.')
|
|
process.exit(1)
|
|
}
|
|
|
|
if (limitRaw && (!Number.isFinite(limit) || limit <= 0)) {
|
|
console.error('--limit must be a positive integer.')
|
|
process.exit(1)
|
|
}
|
|
|
|
config({ path: envFile })
|
|
|
|
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
|
|
const serviceRoleKey = process.env.SUPABASE_SERVICE_ROLE_KEY
|
|
|
|
if (!supabaseUrl || !serviceRoleKey) {
|
|
console.error(`Missing NEXT_PUBLIC_SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY in ${envFile}`)
|
|
process.exit(1)
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Types
|
|
// ---------------------------------------------------------------------------
|
|
|
|
interface DocumentRow {
|
|
id: string
|
|
company_id: string | null
|
|
storage_path: string | null
|
|
file_name: string | null
|
|
mime_type: string | null
|
|
sha256_hash: string | null
|
|
}
|
|
|
|
interface Failure {
|
|
documentId: string
|
|
storagePath: string | null
|
|
step: string
|
|
reason: string
|
|
}
|
|
|
|
/** All rows (possibly from several companies) that share one legacy key. */
|
|
interface PathGroup {
|
|
sourcePath: string
|
|
rows: DocumentRow[]
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Path helpers.
|
|
//
|
|
// Deliberately duplicated from lib/core/documents/document-service.ts instead
|
|
// of imported: this script runs standalone under tsx and must not drag the
|
|
// service module's Next.js/event-bus imports into a plain node process. Keep
|
|
// the two in sync if the layout ever changes again.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function isCompanyScoped(storagePath: string, companyId: string): boolean {
|
|
return storagePath.startsWith(`${PATH_ROOT}/${companyId}/`)
|
|
}
|
|
|
|
function isLegacyDocumentPath(storagePath: string): boolean {
|
|
return storagePath.startsWith(`${PATH_ROOT}/`)
|
|
}
|
|
|
|
function companyScopedPath(storagePath: string, companyId: string): string | null {
|
|
if (isCompanyScoped(storagePath, companyId)) return null
|
|
if (!isLegacyDocumentPath(storagePath)) return null
|
|
return `${PATH_ROOT}/${companyId}/${storagePath.slice(`${PATH_ROOT}/`.length)}`
|
|
}
|
|
|
|
/**
|
|
* Inverse of companyScopedPath: derive the legacy key a company-scoped key
|
|
* was (or would have been) migrated from. The forward mapping is a pure
|
|
* prefix insertion, so the inverse is exact. Returns null when the key is
|
|
* not company-scoped for the given company.
|
|
*/
|
|
function legacyPathFor(storagePath: string, companyId: string): string | null {
|
|
const prefix = `${PATH_ROOT}/${companyId}/`
|
|
if (!storagePath.startsWith(prefix)) return null
|
|
return `${PATH_ROOT}/${storagePath.slice(prefix.length)}`
|
|
}
|
|
|
|
function sha256Hex(buffer: ArrayBuffer): string {
|
|
return createHash('sha256').update(Buffer.from(buffer)).digest('hex')
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Safety banner + confirmation
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function projectRef(url: string): string {
|
|
try {
|
|
return new URL(url).hostname.split('.')[0] ?? url
|
|
} catch {
|
|
return url
|
|
}
|
|
}
|
|
|
|
async function confirmOrExit(): Promise<void> {
|
|
const ref = projectRef(supabaseUrl!)
|
|
|
|
console.log('')
|
|
console.log('='.repeat(78))
|
|
console.log(' documents bucket backfill: legacy uploader-scoped keys -> company-scoped')
|
|
console.log('='.repeat(78))
|
|
console.log(` env file : ${envFile}`)
|
|
console.log(` supabase project: ${ref}`)
|
|
console.log(` mode : ${apply ? 'APPLY (writes data)' : 'DRY RUN (no changes)'}`)
|
|
console.log(` delete source : ${deleteSource ? 'YES (legacy objects removed)' : 'no'}`)
|
|
console.log(` company filter : ${onlyCompany ?? '(all companies)'}`)
|
|
console.log(` limit : ${Number.isFinite(limit) ? limit : '(none)'}`)
|
|
console.log('='.repeat(78))
|
|
console.log('')
|
|
|
|
if (!apply || skipPrompt) return
|
|
|
|
const rl = createInterface({ input: process.stdin, output: process.stdout })
|
|
const answer = await rl.question(
|
|
`Type the project ref (${ref}) to proceed, anything else to abort: `,
|
|
)
|
|
rl.close()
|
|
if (answer.trim() !== ref) {
|
|
console.error('Aborted.')
|
|
process.exit(1)
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Data access
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/**
|
|
* Page through document_attachments. PostgREST caps a single response at
|
|
* 1000 rows, so never rely on an unbounded select here.
|
|
*/
|
|
async function fetchAllDocuments(supabase: SupabaseClient): Promise<DocumentRow[]> {
|
|
const rows: DocumentRow[] = []
|
|
let from = 0
|
|
|
|
for (;;) {
|
|
let query = supabase
|
|
.from('document_attachments')
|
|
.select('id, company_id, storage_path, file_name, mime_type, sha256_hash')
|
|
.not('storage_path', 'is', null)
|
|
// created_at alone is not unique: without the id tiebreaker, rows
|
|
// sharing a timestamp can be skipped or duplicated across .range()
|
|
// pages, and a skipped row silently stays on the legacy key.
|
|
.order('created_at', { ascending: true })
|
|
.order('id', { ascending: true })
|
|
.range(from, from + PAGE_SIZE - 1)
|
|
|
|
if (onlyCompany) query = query.eq('company_id', onlyCompany)
|
|
|
|
const { data, error } = await query
|
|
if (error) throw new Error(`Failed to page document_attachments: ${error.message}`)
|
|
if (!data || data.length === 0) break
|
|
|
|
rows.push(...(data as DocumentRow[]))
|
|
if (data.length < PAGE_SIZE) break
|
|
from += PAGE_SIZE
|
|
}
|
|
|
|
return rows
|
|
}
|
|
|
|
async function objectExists(supabase: SupabaseClient, path: string): Promise<boolean> {
|
|
const segments = path.split('/')
|
|
const name = segments.pop()!
|
|
const folder = segments.join('/')
|
|
const { data, error } = await supabase.storage.from(BUCKET).list(folder, { search: name })
|
|
// Surface list failures instead of treating them as "missing": a transient
|
|
// error must never make a leftover object look already-swept.
|
|
if (error) throw new Error(`Failed to list ${folder}: ${error.message}`)
|
|
return !!data?.some((entry) => entry.name === name)
|
|
}
|
|
|
|
/**
|
|
* Authoritative check that at least one document_attachments row still points
|
|
* at the given storage key. Deliberately queries the LIVE table rather than
|
|
* this run's in-memory snapshot: a --company or --limit window, a
|
|
* NULL-company row, or a concurrent writer must never be able to hide a row
|
|
* whose only object the key is.
|
|
*/
|
|
async function pathStillReferenced(supabase: SupabaseClient, path: string): Promise<boolean> {
|
|
const { data, error } = await supabase
|
|
.from('document_attachments')
|
|
.select('id')
|
|
.eq('storage_path', path)
|
|
.limit(1)
|
|
if (error) throw new Error(`Failed to check references for ${path}: ${error.message}`)
|
|
return (data?.length ?? 0) > 0
|
|
}
|
|
|
|
/**
|
|
* Remove a legacy object, but only when the live table confirms zero rows
|
|
* still reference it. Every caller has already verified a company-scoped
|
|
* copy for every row that pointed here; this function is the ONLY place the
|
|
* script deletes a legacy source object. Returns true when the object was
|
|
* actually removed.
|
|
*/
|
|
async function removeLegacySourceIfUnreferenced(
|
|
supabase: SupabaseClient,
|
|
legacyPath: string,
|
|
): Promise<boolean> {
|
|
try {
|
|
if (await pathStillReferenced(supabase, legacyPath)) {
|
|
console.warn(` [${legacyPath}] source kept: still referenced by at least one row`)
|
|
return false
|
|
}
|
|
} catch (err) {
|
|
console.warn(
|
|
` [${legacyPath}] source kept: reference check failed: ${
|
|
err instanceof Error ? err.message : String(err)
|
|
}`,
|
|
)
|
|
return false
|
|
}
|
|
|
|
const { error: removeError } = await supabase.storage.from(BUCKET).remove([legacyPath])
|
|
if (removeError) {
|
|
console.warn(` [${legacyPath}] source not removed: ${removeError.message}`)
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Per-object migration (all rows sharing one legacy key, together)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
interface TargetState {
|
|
targetPath: string
|
|
copyHash: string
|
|
uploadedThisRun: boolean
|
|
repointed: number
|
|
}
|
|
|
|
async function migrateGroup(
|
|
supabase: SupabaseClient,
|
|
group: PathGroup,
|
|
failures: Failure[],
|
|
): Promise<{ migratedRows: number; failedRows: number; sourceRemoved: boolean }> {
|
|
const { sourcePath, rows } = group
|
|
|
|
const fail = (row: DocumentRow, step: string, reason: string) => {
|
|
failures.push({ documentId: row.id, storagePath: sourcePath, step, reason })
|
|
}
|
|
|
|
// ---- 3. COPY (never move: the source must survive until step 6).
|
|
// Downloaded once per key: several rows can share the object. ------------
|
|
const { data: sourceBlob, error: downloadError } = await supabase.storage
|
|
.from(BUCKET)
|
|
.download(sourcePath)
|
|
|
|
if (downloadError || !sourceBlob) {
|
|
const reason = downloadError?.message ?? 'no data returned'
|
|
for (const row of rows) fail(row, 'download-source', reason)
|
|
return { migratedRows: 0, failedRows: rows.length, sourceRemoved: false }
|
|
}
|
|
|
|
const sourceBytes = await sourceBlob.arrayBuffer()
|
|
const sourceHash = sha256Hex(sourceBytes)
|
|
|
|
// One scoped target per company referencing this source key: rows from
|
|
// different companies sharing one object each get their own copy.
|
|
const companies = [...new Set(rows.map((row) => row.company_id!))]
|
|
const targets = new Map<string, TargetState>()
|
|
|
|
for (const companyId of companies) {
|
|
const companyRows = rows.filter((row) => row.company_id === companyId)
|
|
const targetPath = companyScopedPath(sourcePath, companyId)!
|
|
let uploadedThisRun = false
|
|
|
|
try {
|
|
// An already-present target means a previous run got this far: fall
|
|
// through to verification rather than failing on the upsert:false
|
|
// conflict.
|
|
if (!(await objectExists(supabase, targetPath))) {
|
|
const { error: uploadError } = await supabase.storage
|
|
.from(BUCKET)
|
|
.upload(targetPath, sourceBytes, {
|
|
contentType: companyRows[0]!.mime_type ?? 'application/octet-stream',
|
|
upsert: false,
|
|
})
|
|
|
|
if (uploadError) {
|
|
for (const row of companyRows) fail(row, 'upload-copy', uploadError.message)
|
|
continue
|
|
}
|
|
uploadedThisRun = true
|
|
}
|
|
} catch (err) {
|
|
const reason = err instanceof Error ? err.message : String(err)
|
|
for (const row of companyRows) fail(row, 'upload-copy', reason)
|
|
continue
|
|
}
|
|
|
|
// ---- 4. VERIFY the new key is readable, once per target --------------
|
|
const { data: copyBlob, error: verifyError } = await supabase.storage
|
|
.from(BUCKET)
|
|
.download(targetPath)
|
|
|
|
if (verifyError || !copyBlob) {
|
|
const reason = verifyError?.message ?? 'copy not readable at the new key'
|
|
for (const row of companyRows) fail(row, 'verify-readable', reason)
|
|
continue
|
|
}
|
|
|
|
targets.set(companyId, {
|
|
targetPath,
|
|
copyHash: sha256Hex(await copyBlob.arrayBuffer()),
|
|
uploadedThisRun,
|
|
repointed: 0,
|
|
})
|
|
}
|
|
|
|
let migratedRows = 0
|
|
|
|
for (const row of rows) {
|
|
const target = targets.get(row.company_id!)
|
|
if (!target) continue // upload/readability failure already recorded above
|
|
|
|
// The stored hash is the strongest reference; fall back to the source
|
|
// bytes for rows written before sha256_hash was populated.
|
|
const expectedHash = row.sha256_hash ?? sourceHash
|
|
if (target.copyHash !== expectedHash) {
|
|
fail(row, 'verify-hash', `copy hash ${target.copyHash} does not match expected ${expectedHash}`)
|
|
continue
|
|
}
|
|
|
|
// ---- 5. Repoint the DB, only now that the copy is proven. The row
|
|
// count matters: a row deleted between fetch and migrate makes this a
|
|
// 0-row UPDATE, which must NOT count as migrated (the scoped copy would
|
|
// resurrect an erased document). ---------------------------------------
|
|
const { data: updated, error: updateError } = await supabase
|
|
.from('document_attachments')
|
|
.update({ storage_path: target.targetPath })
|
|
.eq('id', row.id)
|
|
.select('id')
|
|
|
|
if (updateError) {
|
|
fail(row, 'update-pointer', updateError.message)
|
|
continue
|
|
}
|
|
if (!updated || updated.length === 0) {
|
|
fail(row, 'update-pointer', 'no row matched: deleted between fetch and migrate')
|
|
continue
|
|
}
|
|
|
|
target.repointed++
|
|
migratedRows++
|
|
}
|
|
|
|
// Roll back any scoped copy created THIS RUN that no row ended up pointing
|
|
// at, so it cannot linger as an unreferenced resurrected duplicate. Safe:
|
|
// the copy is seconds old, the live table confirms nothing references it,
|
|
// and the SOURCE object is never touched here.
|
|
for (const target of targets.values()) {
|
|
if (!target.uploadedThisRun || target.repointed > 0) continue
|
|
try {
|
|
if (await pathStillReferenced(supabase, target.targetPath)) continue
|
|
const { error: cleanupError } = await supabase.storage
|
|
.from(BUCKET)
|
|
.remove([target.targetPath])
|
|
if (cleanupError) {
|
|
console.warn(
|
|
` [${target.targetPath}] unreferenced fresh copy not rolled back: ${cleanupError.message}`,
|
|
)
|
|
}
|
|
} catch (err) {
|
|
console.warn(
|
|
` [${target.targetPath}] unreferenced fresh copy not rolled back: ${
|
|
err instanceof Error ? err.message : String(err)
|
|
}`,
|
|
)
|
|
}
|
|
}
|
|
|
|
const failedRows = rows.length - migratedRows
|
|
|
|
// ---- 6. Optional source removal, strictly last: only when EVERY row on
|
|
// this key is repointed, and the live table double-checks that. ----------
|
|
let sourceRemoved = false
|
|
if (deleteSource && failedRows === 0) {
|
|
sourceRemoved = await removeLegacySourceIfUnreferenced(supabase, sourcePath)
|
|
}
|
|
|
|
return { migratedRows, failedRows, sourceRemoved }
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Storage-level sweep over rows that are ALREADY company-scoped
|
|
// ---------------------------------------------------------------------------
|
|
|
|
interface SweepResult {
|
|
/** Distinct derived legacy keys whose object still exists in storage. */
|
|
keysWithLeftovers: number
|
|
objectsRemoved: number
|
|
}
|
|
|
|
/**
|
|
* An --apply run repoints rows and leaves the legacy objects behind, so a
|
|
* later --delete-source run can no longer find them through the pointers:
|
|
* it has to derive each legacy key from the scoped one (legacyPathFor) and
|
|
* check storage directly. For every derived key whose object still exists:
|
|
*
|
|
* - without --delete-source: count it (input to the Phase C gate)
|
|
* - with --delete-source: verify the scoped copy is readable and matches
|
|
* the expected hash for EVERY row mapping to the key, confirm via the
|
|
* live table that no row still references the key, and only then remove
|
|
* it (capped by --limit).
|
|
*/
|
|
async function sweepLegacyObjects(
|
|
supabase: SupabaseClient,
|
|
scopedRows: DocumentRow[],
|
|
skipKeys: Set<string>,
|
|
failures: Failure[],
|
|
deleteBudget: number,
|
|
): Promise<SweepResult> {
|
|
// Group scoped rows by derived legacy key: several rows (even from
|
|
// different companies) can map to one key, and the key may only be removed
|
|
// when every one of them has a verified scoped copy.
|
|
const byLegacyKey = new Map<string, DocumentRow[]>()
|
|
for (const row of scopedRows) {
|
|
const legacyKey = legacyPathFor(row.storage_path!, row.company_id!)
|
|
if (!legacyKey) continue
|
|
if (skipKeys.has(legacyKey)) continue // handled by this run's migration phase
|
|
const list = byLegacyKey.get(legacyKey)
|
|
if (list) list.push(row)
|
|
else byLegacyKey.set(legacyKey, [row])
|
|
}
|
|
|
|
const result: SweepResult = { keysWithLeftovers: 0, objectsRemoved: 0 }
|
|
|
|
for (const [legacyKey, rows] of byLegacyKey) {
|
|
let counted = false
|
|
try {
|
|
// Most keys belong to uploads born company-scoped: no legacy object
|
|
// ever existed for them, and this check is all they cost.
|
|
if (!(await objectExists(supabase, legacyKey))) continue
|
|
result.keysWithLeftovers++
|
|
counted = true
|
|
|
|
if (!deleteSource) continue // report-only: feeds legacy_objects_remaining
|
|
if (result.objectsRemoved >= deleteBudget) continue
|
|
|
|
// VERIFY: every row mapping to this key must have a readable scoped
|
|
// copy with the expected hash before the legacy object may go.
|
|
let allVerified = true
|
|
let legacyHash: string | null = null
|
|
for (const row of rows) {
|
|
const { data: copyBlob, error: copyError } = await supabase.storage
|
|
.from(BUCKET)
|
|
.download(row.storage_path!)
|
|
|
|
if (copyError || !copyBlob) {
|
|
failures.push({
|
|
documentId: row.id,
|
|
storagePath: legacyKey,
|
|
step: 'sweep-verify-readable',
|
|
reason: copyError?.message ?? 'scoped copy not readable',
|
|
})
|
|
allVerified = false
|
|
break
|
|
}
|
|
const copyHash = sha256Hex(await copyBlob.arrayBuffer())
|
|
|
|
let expectedHash = row.sha256_hash
|
|
if (!expectedHash) {
|
|
// No stored hash: the legacy bytes themselves are the reference.
|
|
if (legacyHash === null) {
|
|
const { data: legacyBlob, error: legacyError } = await supabase.storage
|
|
.from(BUCKET)
|
|
.download(legacyKey)
|
|
if (legacyError || !legacyBlob) {
|
|
failures.push({
|
|
documentId: row.id,
|
|
storagePath: legacyKey,
|
|
step: 'sweep-download-legacy',
|
|
reason: legacyError?.message ?? 'legacy object listed but not readable',
|
|
})
|
|
allVerified = false
|
|
break
|
|
}
|
|
legacyHash = sha256Hex(await legacyBlob.arrayBuffer())
|
|
}
|
|
expectedHash = legacyHash
|
|
}
|
|
|
|
if (copyHash !== expectedHash) {
|
|
failures.push({
|
|
documentId: row.id,
|
|
storagePath: legacyKey,
|
|
step: 'sweep-verify-hash',
|
|
reason: `scoped copy hash ${copyHash} does not match expected ${expectedHash}`,
|
|
})
|
|
allVerified = false
|
|
break
|
|
}
|
|
}
|
|
|
|
if (!allVerified) continue // stays counted as a leftover; gate stays closed
|
|
|
|
if (await removeLegacySourceIfUnreferenced(supabase, legacyKey)) {
|
|
console.log(
|
|
` [sweep] removed ${legacyKey} (${rows.length} row(s) verified at scoped keys)`,
|
|
)
|
|
result.objectsRemoved++
|
|
}
|
|
} catch (err) {
|
|
// Unknown state: count the key as remaining so the gate stays closed.
|
|
if (!counted) result.keysWithLeftovers++
|
|
failures.push({
|
|
documentId: rows[0]!.id,
|
|
storagePath: legacyKey,
|
|
step: 'sweep-unexpected',
|
|
reason: err instanceof Error ? err.message : String(err),
|
|
})
|
|
}
|
|
}
|
|
|
|
return result
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Main
|
|
// ---------------------------------------------------------------------------
|
|
|
|
async function main(): Promise<void> {
|
|
await confirmOrExit()
|
|
|
|
const supabase = createClient(supabaseUrl!, serviceRoleKey!, {
|
|
auth: { persistSession: false, autoRefreshToken: false },
|
|
})
|
|
|
|
const rows = await fetchAllDocuments(supabase)
|
|
|
|
const alreadyScoped: DocumentRow[] = []
|
|
const candidates: DocumentRow[] = []
|
|
const unmapped: DocumentRow[] = []
|
|
|
|
for (const row of rows) {
|
|
if (!row.storage_path) continue
|
|
if (!row.company_id) {
|
|
unmapped.push(row)
|
|
continue
|
|
}
|
|
if (isCompanyScoped(row.storage_path, row.company_id)) {
|
|
alreadyScoped.push(row)
|
|
} else if (isLegacyDocumentPath(row.storage_path)) {
|
|
candidates.push(row)
|
|
} else {
|
|
// Shapes this backfill deliberately does not touch, e.g. the MCP
|
|
// audit-package keys `{userId}/audit-packages/...` and the demo-seed
|
|
// `{userId}/{companyId}/inbox/...` keys. They are not covered by the
|
|
// documents_*_company policies and are not document_attachments
|
|
// underlag in the BFL sense.
|
|
unmapped.push(row)
|
|
}
|
|
}
|
|
|
|
// Group the legacy rows by source key: storage_path has no unique
|
|
// constraint, so several rows can share one object. The object is copied
|
|
// once, ALL its rows are repointed, and only then may the source go;
|
|
// migrating rows one by one deleted the source after the first row and
|
|
// stranded every later row on a dead pointer.
|
|
const groupsByPath = new Map<string, DocumentRow[]>()
|
|
for (const row of candidates) {
|
|
const list = groupsByPath.get(row.storage_path!)
|
|
if (list) list.push(row)
|
|
else groupsByPath.set(row.storage_path!, [row])
|
|
}
|
|
const groups: PathGroup[] = [...groupsByPath.entries()].map(([sourcePath, groupRows]) => ({
|
|
sourcePath,
|
|
rows: groupRows,
|
|
}))
|
|
|
|
console.log(`document_attachments rows with a storage_path : ${rows.length}`)
|
|
console.log(` already company-scoped : ${alreadyScoped.length}`)
|
|
console.log(
|
|
` legacy prefix, need migration : ${candidates.length} (${groups.length} distinct objects)`,
|
|
)
|
|
console.log(` outside the documents/ layout (skipped) : ${unmapped.length}`)
|
|
console.log('')
|
|
|
|
if (unmapped.length > 0) {
|
|
console.log('Skipped rows (first 20):')
|
|
for (const row of unmapped.slice(0, 20)) {
|
|
console.log(` ${row.id} company=${row.company_id ?? 'NULL'} path=${row.storage_path}`)
|
|
}
|
|
console.log('')
|
|
}
|
|
|
|
// --limit caps processed rows, but a shared-key group is never split:
|
|
// repointing only some of a key's rows would let a later --delete-source
|
|
// remove an object the remaining rows still need.
|
|
const batch: PathGroup[] = []
|
|
let batchRows = 0
|
|
for (const group of groups) {
|
|
if (batchRows >= limit) break
|
|
batch.push(group)
|
|
batchRows += group.rows.length
|
|
}
|
|
|
|
const failures: Failure[] = []
|
|
let migratedRows = 0
|
|
let sourcesRemoved = 0
|
|
// Groups fully migrated this run whose legacy object was (deliberately or
|
|
// not) left in storage: they count as leftover legacy objects below.
|
|
let sourcesKept = 0
|
|
|
|
if (!apply) {
|
|
console.log('DRY RUN: nothing was changed. Planned moves (first 20):')
|
|
const preview = batch.flatMap((group) => group.rows).slice(0, 20)
|
|
for (const row of preview) {
|
|
console.log(` ${row.id}`)
|
|
console.log(` from ${row.storage_path}`)
|
|
console.log(` to ${companyScopedPath(row.storage_path!, row.company_id!)}`)
|
|
}
|
|
console.log('')
|
|
} else {
|
|
for (const [index, group] of batch.entries()) {
|
|
const progress = `${index + 1}/${batch.length}`
|
|
const rowCount = group.rows.length
|
|
console.log(
|
|
`[${progress}] ${group.sourcePath} (${rowCount} row${rowCount === 1 ? '' : 's'})`,
|
|
)
|
|
try {
|
|
const outcome = await migrateGroup(supabase, group, failures)
|
|
migratedRows += outcome.migratedRows
|
|
if (outcome.failedRows === 0) {
|
|
if (outcome.sourceRemoved) sourcesRemoved++
|
|
else sourcesKept++
|
|
}
|
|
} catch (err) {
|
|
// Never abort the run on one bad object.
|
|
const reason = err instanceof Error ? err.message : String(err)
|
|
for (const row of group.rows) {
|
|
failures.push({
|
|
documentId: row.id,
|
|
storagePath: group.sourcePath,
|
|
step: 'unexpected',
|
|
reason,
|
|
})
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Storage-level sweep over already-migrated rows. Without it, an --apply
|
|
// run followed by a later --delete-source run finds zero legacy POINTERS
|
|
// and deletes nothing, while every legacy OBJECT still sits in the bucket
|
|
// readable by its uploader. Read-only unless --delete-source; the keys
|
|
// this run already handled as migration sources are skipped.
|
|
console.log('')
|
|
console.log(
|
|
`Sweeping ${alreadyScoped.length} already-scoped row(s) for leftover legacy objects` +
|
|
(deleteSource ? ' (verify + delete)...' : ' (read-only)...'),
|
|
)
|
|
const batchSourcePaths = new Set(batch.map((group) => group.sourcePath))
|
|
const sweep = await sweepLegacyObjects(
|
|
supabase,
|
|
alreadyScoped,
|
|
batchSourcePaths,
|
|
failures,
|
|
limit,
|
|
)
|
|
|
|
const legacyRowsRemaining = candidates.length - migratedRows
|
|
const legacyObjectsRemaining =
|
|
sweep.keysWithLeftovers - sweep.objectsRemoved + sourcesKept
|
|
|
|
console.log('')
|
|
console.log('='.repeat(78))
|
|
console.log(` rows migrated : ${migratedRows}`)
|
|
console.log(` failures : ${failures.length}`)
|
|
console.log(` legacy objects removed : ${sourcesRemoved + sweep.objectsRemoved}`)
|
|
console.log(` legacy_prefix_remaining : ${legacyRowsRemaining}`)
|
|
console.log(` legacy_objects_remaining : ${legacyObjectsRemaining}`)
|
|
console.log('='.repeat(78))
|
|
|
|
if (failures.length > 0) {
|
|
console.log('')
|
|
console.log('Failures (document id / step / reason):')
|
|
for (const failure of failures) {
|
|
console.log(` ${failure.documentId} [${failure.step}] ${failure.reason}`)
|
|
console.log(` path: ${failure.storagePath}`)
|
|
}
|
|
}
|
|
|
|
// The gate needs BOTH counters at zero: rows still on legacy pointers make
|
|
// documents unreadable after Phase C, and leftover legacy objects keep the
|
|
// uploader-scoped read hole open.
|
|
const gateOpen =
|
|
legacyRowsRemaining === 0 && legacyObjectsRemaining === 0 && failures.length === 0
|
|
|
|
console.log('')
|
|
if (gateOpen) {
|
|
console.log(
|
|
apply
|
|
? 'PHASE C GATE: OPEN. Re-run with --dry-run to confirm, then apply the Phase C migration.'
|
|
: 'PHASE C GATE: OPEN. Zero legacy-prefix rows and zero leftover legacy objects; the Phase C migration may be applied.',
|
|
)
|
|
} else {
|
|
const next =
|
|
legacyRowsRemaining > 0
|
|
? 'Run with --apply until legacy_prefix_remaining reaches 0.'
|
|
: legacyObjectsRemaining > 0
|
|
? 'Run with --apply --delete-source to remove the leftover legacy objects.'
|
|
: 'Resolve the failures above and re-run.'
|
|
console.log(
|
|
`PHASE C GATE: CLOSED. Do NOT drop documents_select_own / documents_insert_own yet. ${next}`,
|
|
)
|
|
}
|
|
|
|
// Non-zero exit on failures so a CI/ops wrapper notices, but only AFTER the
|
|
// full report has been printed.
|
|
if (failures.length > 0) process.exitCode = 1
|
|
}
|
|
|
|
main().catch((err) => {
|
|
console.error(err)
|
|
process.exit(1)
|
|
})
|