fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
masterplan-lock / check (push) Successful in 19s
ci / sonar (push) Failing after 21s
security / scan (push) Failing after 1m37s

Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i
server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma
strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
2026-11-10 09:37:22 +01:00
parent 077251ac94
commit e7f0070e84
6135 changed files with 1718997 additions and 4 deletions
@@ -0,0 +1,411 @@
/**
* Proof that the ambiguous-embed ratchet catches the shape that shipped twice
* and leaves both legitimate hint forms alone. Offending fixtures live only in
* these strings and in an OS temp directory the end-to-end cases create and
* delete.
*/
import { describe, it, expect, afterAll } from 'vitest'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import {
deriveAmbiguousPairs,
findAmbiguousEmbeds,
findAmbiguousEmbedsInSource,
pairKey,
parseEmbeds,
} from '../ambiguous-embed.mjs'
const tempDirs: string[] = []
afterAll(() => {
for (const dir of tempDirs) fs.rmSync(dir, { recursive: true, force: true })
})
const tempRoot = (prefix: string) => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), prefix))
tempDirs.push(root)
return root
}
const write = (root: string, rel: string, content: string) => {
const full = path.join(root, rel)
fs.mkdirSync(path.dirname(full), { recursive: true })
fs.writeFileSync(full, content)
}
// Only the pair this guard exists for. Every other pair the fixtures embed
// (journal_entries -> journal_entry_lines, transactions -> journal_entries) is
// absent from the set, which is exactly how a single-foreign-key pair looks to
// the scanner: it must never be flagged.
const PAIRS = new Set([pairKey('journal_entries', 'fiscal_periods')])
const scan = (source: string) =>
findAmbiguousEmbedsInSource(source, 'fixture.ts', PAIRS).map(
(f: { from: string; target: string }) => `${f.from}->${f.target}`,
)
describe('ambiguous-embed: the shape that shipped', () => {
it('flags an ALIASED embed with no relationship named', () => {
// lib/core/documents/supplier-invoice-underlag.ts as it shipped 2026-07-27.
// A tokenizer that only looks for `<table>(` after a comma, space or paren
// misses this, which is the whole reason the bug survived two reviews.
expect(
scan(
`const { data } = await supabase
.from('journal_entries')
.select('id, status, fiscal_period:fiscal_periods(is_closed, locked_at)')`,
),
).toEqual(['journal_entries->fiscal_periods'])
})
it('flags the bare, unaliased embed too', () => {
expect(scan(`supabase.from('journal_entries').select('id, fiscal_periods(is_closed)')`)).toEqual(
['journal_entries->fiscal_periods'],
)
})
it('flags the embed written in the other direction', () => {
expect(
scan(`supabase.from('fiscal_periods').select('id, journal_entries(voucher_number)')`),
).toEqual(['fiscal_periods->journal_entries'])
})
})
describe('ambiguous-embed: both hint forms PostgREST accepts', () => {
it('accepts the constraint name', () => {
// lib/transactions/inbox-underlag.ts, lib/pending-operations/commit.ts.
expect(
scan(
`supabase.from('journal_entries').select('id, fiscal_period:fiscal_periods!journal_entries_fiscal_period_id_fkey(is_closed, locked_at)')`,
),
).toEqual([])
})
it('accepts the foreign key COLUMN name', () => {
// lib/import/opening-balance/cascade.ts, lib/invoices/invoice-matching.ts.
// A `*_fkey`-only matcher would hard-fail six legitimate lines here.
expect(
scan(
`supabase.from('fiscal_periods').select('id, opening_balance_entry:journal_entries!opening_balance_entry_id(voucher_series, voucher_number)')`,
),
).toEqual([])
})
it('accepts a hint combined with a join modifier, in either order', () => {
expect(
scan(
`supabase.from('journal_entries').select('id, fiscal_periods!journal_entries_fiscal_period_id_fkey!inner(is_closed)')`,
),
).toEqual([])
expect(
scan(
`supabase.from('journal_entries').select('id, fiscal_periods!inner!journal_entries_fiscal_period_id_fkey(is_closed)')`,
),
).toEqual([])
})
it('does NOT accept a bare join modifier: !inner disambiguates nothing', () => {
expect(
scan(`supabase.from('journal_entries').select('id, fiscal_periods!inner(is_closed)')`),
).toEqual(['journal_entries->fiscal_periods'])
expect(
scan(`supabase.from('journal_entries').select('id, fiscal_periods!left(is_closed)')`),
).toEqual(['journal_entries->fiscal_periods'])
})
})
describe('ambiguous-embed: chain resolution', () => {
it('resolves .from() through its OWN chain, not the nearest one above', () => {
// scripts/seed-demo-account.ts: a journal_entries!inner embed from
// journal_entry_lines (a single-foreign-key pair) sits below an unrelated
// .from('journal_entries'). Pairing by proximity flags it wrongly.
const source = `
await supabase.from('journal_entries').select('id, voucher_number')
await supabase
.from('journal_entry_lines')
.select('account_number, debit, journal_entries!inner(entry_date)')
.eq('company_id', companyId)
`
expect(scan(source)).toEqual([])
})
it('reads a select anywhere in the chain, before or after the filters', () => {
expect(
scan(
`supabase.from('journal_entries').select('id, fiscal_periods(is_closed)').eq('company_id', id).in('id', ids)`,
),
).toEqual(['journal_entries->fiscal_periods'])
})
it('ignores a select whose from-table cannot be resolved statically', () => {
expect(scan(`query.select('id, fiscal_periods(is_closed)')`)).toEqual([])
expect(scan(`supabase.from(tableName).select('id, fiscal_periods(is_closed)')`)).toEqual([])
})
})
describe('ambiguous-embed: nesting', () => {
it('resolves a nested embed against its enclosing embed, not the root', () => {
// transactions -> journal_entries is a single-foreign-key pair here, so the
// inner fiscal_periods embed is what must be judged, against journal_entries.
const nested = `supabase.from('transactions').select('id, journal_entries(id, fiscal_periods(is_closed))')`
expect(scan(nested)).toEqual(['journal_entries->fiscal_periods'])
})
it('leaves the enclosing embed alone when the inner one is hinted', () => {
expect(
scan(
`supabase.from('transactions').select('id, journal_entries(id, fiscal_periods!journal_entries_fiscal_period_id_fkey(is_closed))')`,
),
).toEqual([])
})
it('parses plain columns, casts and json paths without inventing embeds', () => {
expect(parseEmbeds('id, amount::text, metadata->>ref, *', 'journal_entries')).toEqual([])
})
})
describe('ambiguous-embed: pair derivation from the migration history', () => {
const migrationsRoot = (files: Record<string, string>) => {
const root = tempRoot('ambiguous-embed-sql-')
for (const [name, sql] of Object.entries(files)) write(root, name, sql)
return root
}
it('counts a pair as ambiguous once a second foreign key joins it', () => {
const dir = migrationsRoot({
'20240101000001_core.sql': `
CREATE TABLE public.journal_entries (
id UUID PRIMARY KEY,
fiscal_period_id UUID REFERENCES public.fiscal_periods(id)
);
`,
})
expect(deriveAmbiguousPairs(dir).size).toBe(0)
const dir2 = migrationsRoot({
'20240101000001_core.sql': `
CREATE TABLE public.journal_entries (
id UUID PRIMARY KEY,
fiscal_period_id UUID REFERENCES public.fiscal_periods(id)
);
`,
'20240101000019_period_closing.sql': `
ALTER TABLE public.fiscal_periods
ADD COLUMN closing_entry_id UUID REFERENCES public.journal_entries(id);
`,
})
expect([...deriveAmbiguousPairs(dir2)]).toEqual([pairKey('fiscal_periods', 'journal_entries')])
})
it('collapses the idempotent re-adds the migration history is full of', () => {
const dir = migrationsRoot({
'20240101000001_a.sql': `
ALTER TABLE public.journal_entry_lines
ADD CONSTRAINT journal_entry_lines_cost_center_id_fkey
FOREIGN KEY (cost_center_id) REFERENCES public.cost_centers(id);
`,
'20240101000002_b.sql': `
ALTER TABLE public.journal_entry_lines
ADD CONSTRAINT journal_entry_lines_cost_center_id_fkey
FOREIGN KEY (cost_center_id) REFERENCES public.cost_centers(id);
`,
})
expect(deriveAmbiguousPairs(dir).size).toBe(0)
})
it('honours DROP COLUMN, DROP CONSTRAINT and DROP TABLE', () => {
const base = `
CREATE TABLE public.a (
id UUID PRIMARY KEY,
b_one_id UUID REFERENCES public.b(id),
b_two_id UUID REFERENCES public.b(id)
);
`
expect([...deriveAmbiguousPairs(migrationsRoot({ '1_a.sql': base }))]).toEqual([pairKey('a', 'b')])
expect(
deriveAmbiguousPairs(
migrationsRoot({ '1_a.sql': base, '2_b.sql': `ALTER TABLE public.a DROP COLUMN b_two_id;` }),
).size,
).toBe(0)
expect(
deriveAmbiguousPairs(
migrationsRoot({
'1_a.sql': base,
'2_b.sql': `ALTER TABLE public.a DROP CONSTRAINT IF EXISTS a_b_two_id_fkey;`,
}),
).size,
).toBe(0)
expect(
deriveAmbiguousPairs(
migrationsRoot({ '1_a.sql': base, '2_b.sql': `DROP TABLE IF EXISTS public.b;` }),
).size,
).toBe(0)
})
it('counts a composite foreign key next to a single-column one', () => {
// 20260902130000_sales_orders.sql + 20260902180000_sales_orders_hardening.sql:
// the composite (sales_order_id, company_id) guard is a second relationship
// in PostgREST's eyes. A single-column-only parser derived one edge here and
// let `items:sales_order_items(*)` ship un-hinted; prod answered PGRST201
// on every kundorder load (2026-09-03).
const dir = migrationsRoot({
'20260902130000_sales_orders.sql': `
CREATE TABLE public.sales_order_items (
id uuid PRIMARY KEY,
company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
sales_order_id uuid NOT NULL REFERENCES public.sales_orders(id) ON DELETE CASCADE
);
`,
'20260902180000_sales_orders_hardening.sql': `
ALTER TABLE public.sales_order_items
DROP CONSTRAINT IF EXISTS sales_order_items_order_company_fkey;
ALTER TABLE public.sales_order_items
ADD CONSTRAINT sales_order_items_order_company_fkey
FOREIGN KEY (sales_order_id, company_id)
REFERENCES public.sales_orders (id, company_id)
ON DELETE CASCADE;
`,
})
expect([...deriveAmbiguousPairs(dir)]).toEqual([pairKey('sales_order_items', 'sales_orders')])
})
it('does not count a composite foreign key that REPLACED the single-column one', () => {
// 20260721101500_harden_tax_assessment_notices.sql shape: the old
// single-column constraint is dropped and the composite added, leaving one
// relationship. Prod agrees: tax_assessment_notices|fiscal_periods is not
// in the pg_constraint list.
const dir = migrationsRoot({
'1_base.sql': `
CREATE TABLE public.tax_assessment_notices (
id uuid PRIMARY KEY,
company_id uuid NOT NULL REFERENCES public.companies(id),
fiscal_period_id uuid REFERENCES public.fiscal_periods(id)
);
`,
'2_harden.sql': `
ALTER TABLE public.tax_assessment_notices
DROP CONSTRAINT IF EXISTS tax_assessment_notices_fiscal_period_id_fkey;
ALTER TABLE public.tax_assessment_notices
ADD CONSTRAINT tax_assessment_notices_fiscal_period_company_fkey
FOREIGN KEY (fiscal_period_id, company_id)
REFERENCES public.fiscal_periods (id, company_id);
`,
})
expect(deriveAmbiguousPairs(dir).size).toBe(0)
})
it('drops a composite edge when DROP COLUMN removes one of its columns', () => {
// Postgres drops every foreign key a column takes part in. Keeping the
// composite edge would arm a pair that no longer exists and reject valid
// embeds (CodeRabbit on PR #2207).
const base = `
CREATE TABLE public.sales_order_items (
id uuid PRIMARY KEY,
company_id uuid NOT NULL,
sales_order_id uuid NOT NULL REFERENCES public.sales_orders(id),
CONSTRAINT sales_order_items_order_company_fkey
FOREIGN KEY (sales_order_id, company_id) REFERENCES public.sales_orders(id, company_id)
);
`
expect([...deriveAmbiguousPairs(migrationsRoot({ '1_a.sql': base }))]).toEqual([
pairKey('sales_order_items', 'sales_orders'),
])
expect(
deriveAmbiguousPairs(
migrationsRoot({
'1_a.sql': base,
'2_b.sql': `ALTER TABLE public.sales_order_items DROP COLUMN company_id;`,
}),
).size,
).toBe(0)
// The dropped constraint's name is released too: a later DROP CONSTRAINT
// by that name must not delete an unrelated edge.
expect(
deriveAmbiguousPairs(
migrationsRoot({
'1_a.sql': base,
'2_b.sql': `ALTER TABLE public.sales_order_items DROP COLUMN company_id;`,
'3_c.sql': `ALTER TABLE public.sales_order_items DROP CONSTRAINT IF EXISTS sales_order_items_order_company_fkey;`,
}),
).size,
).toBe(0)
})
it('reads a composite table-level constraint inside CREATE TABLE', () => {
const dir = migrationsRoot({
'1_a.sql': `
CREATE TABLE public.a (
id uuid PRIMARY KEY,
company_id uuid NOT NULL,
b_id uuid REFERENCES public.b(id),
CONSTRAINT a_b_company_fkey FOREIGN KEY (b_id, company_id) REFERENCES public.b(id, company_id)
);
`,
})
expect([...deriveAmbiguousPairs(dir)]).toEqual([pairKey('a', 'b')])
})
it('matches the live schema on the real migration history', () => {
// Verified against prod (pwxtzglxptnnvjrpixpg) on 2026-09-03 with the
// pg_constraint query in ambiguous-embed.mjs: the same 17 pairs.
const pairs = deriveAmbiguousPairs(
path.join(__dirname, '..', '..', '..', 'supabase', 'migrations'),
)
expect(pairs.has(pairKey('journal_entries', 'fiscal_periods'))).toBe(true)
expect(pairs.has(pairKey('journal_entries', 'salary_runs'))).toBe(true)
expect(pairs.has(pairKey('supplier_invoices', 'transactions'))).toBe(true)
expect(pairs.has(pairKey('sales_order_items', 'sales_orders'))).toBe(true)
// Single-foreign-key pairs that legitimate code embeds without a hint.
expect(pairs.has(pairKey('journal_entries', 'journal_entry_lines'))).toBe(false)
expect(pairs.has(pairKey('supplier_invoice_payments', 'supplier_invoices'))).toBe(false)
expect(pairs.has(pairKey('tax_assessment_notices', 'fiscal_periods'))).toBe(false)
})
})
describe('ambiguous-embed: file scan', () => {
it('reports offenders relative to the root and skips test files', () => {
const root = tempRoot('ambiguous-embed-')
write(
root,
'supabase/migrations/20240101000019_period_closing.sql',
`
CREATE TABLE public.journal_entries (
id UUID PRIMARY KEY,
fiscal_period_id UUID REFERENCES public.fiscal_periods(id)
);
ALTER TABLE public.fiscal_periods
ADD COLUMN closing_entry_id UUID REFERENCES public.journal_entries(id);
`,
)
const bad = `supabase.from('journal_entries').select('id, fiscal_period:fiscal_periods(is_closed)')`
const good = `supabase.from('journal_entries').select('id, fiscal_periods!journal_entries_fiscal_period_id_fkey(is_closed)')`
write(root, 'lib/bad.ts', bad)
write(root, 'lib/good.ts', good)
write(root, 'lib/__tests__/bad.test.ts', bad)
write(root, 'lib/bad.test.ts', bad)
write(root, 'app/api/x/route.ts', `${good}\n${bad}`)
expect(findAmbiguousEmbeds(root)).toEqual([
{ where: 'app/api/x/route.ts:2', from: 'journal_entries', target: 'fiscal_periods' },
{ where: 'lib/bad.ts:1', from: 'journal_entries', target: 'fiscal_periods' },
])
})
it('finds nothing when no pair is ambiguous, whatever the code embeds', () => {
const root = tempRoot('ambiguous-embed-single-')
write(
root,
'supabase/migrations/1_core.sql',
`CREATE TABLE public.journal_entries (id UUID PRIMARY KEY, fiscal_period_id UUID REFERENCES public.fiscal_periods(id));`,
)
write(
root,
'lib/fine.ts',
`supabase.from('journal_entries').select('id, fiscal_period:fiscal_periods(is_closed)')`,
)
expect(findAmbiguousEmbeds(root)).toEqual([])
})
})
@@ -0,0 +1,58 @@
/**
* Proof that the client-node-builtin guard follows static imports from a
* 'use client' module to a Node builtin, and only those. Fixtures live in an
* OS temp directory the test creates and deletes.
*/
import { describe, it, expect, afterAll } from 'vitest'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { findClientNodeBuiltins } from '../client-node-builtin.mjs'
const tempDirs: string[] = []
afterAll(() => {
for (const dir of tempDirs) fs.rmSync(dir, { recursive: true, force: true })
})
function fixture(files: Record<string, string>) {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'client-builtin-'))
tempDirs.push(root)
for (const [rel, content] of Object.entries(files)) {
const full = path.join(root, rel)
fs.mkdirSync(path.dirname(full), { recursive: true })
fs.writeFileSync(full, content)
}
return root
}
describe('client-node-builtin guard', () => {
it('flags a client component whose lib import chain reaches crypto, with the chain', () => {
const root = fixture({
'lib/auth/hashing.ts': `import crypto from 'crypto'\nexport const hash = (s: string) => crypto.createHash('sha256').update(s).digest('hex')\nexport const isEnabled = () => true\n`,
'components/Login.tsx': `'use client'\nimport { isEnabled } from '@/lib/auth/hashing'\nexport default function Login() { return isEnabled() ? null : null }\n`,
})
const findings = findClientNodeBuiltins(root)
expect(findings).toHaveLength(1)
expect(findings[0]).toMatchObject({ file: 'components/Login.tsx', builtin: 'crypto' })
expect(findings[0].chain).toEqual(['components/Login.tsx', 'lib/auth/hashing.ts', 'bare:crypto'])
})
it('ignores server modules, type-only imports and dynamic imports', () => {
const root = fixture({
'lib/auth/hashing.ts': `import crypto from 'crypto'\nexport type Digest = string\nexport const hash = (s: string) => crypto.createHash('sha256').update(s).digest('hex')\n`,
'lib/server-only.ts': `import { hash } from './auth/hashing'\nexport const h = hash\n`,
'components/TypeOnly.tsx': `'use client'\nimport type { Digest } from '@/lib/auth/hashing'\nexport const d: Digest = ''\n`,
'components/Lazy.tsx': `'use client'\nexport async function load() { const m = await import('@/lib/auth/hashing'); return m.hash('x') }\n`,
})
expect(findClientNodeBuiltins(root)).toEqual([])
})
it('resolves the pure sibling pattern as clean', () => {
const root = fixture({
'lib/auth/flags.ts': `export const isEnabled = () => true\n`,
'lib/auth/hashing.ts': `import crypto from 'crypto'\nexport { isEnabled } from './flags'\nexport const hash = (s: string) => crypto.createHash('sha256').update(s).digest('hex')\n`,
'components/Login.tsx': `'use client'\nimport { isEnabled } from '@/lib/auth/flags'\nexport default function Login() { return isEnabled() ? null : null }\n`,
})
expect(findClientNodeBuiltins(root)).toEqual([])
})
})
@@ -0,0 +1,137 @@
/**
* Proof that the sek-labelled-amount ratchet guard actually catches the thing.
*
* The offending fixtures live only in these strings and in an OS temp directory
* the end-to-end case creates and deletes: nothing offending is committed, so
* the guard cannot start failing on its own test data.
*/
import { describe, it, expect, afterAll } from 'vitest'
import { execFileSync } from 'node:child_process'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { findSekLabelledFxAmountsInSource as scan } from '../format-currency-sek-label.mjs'
const GUARD = path.resolve(__dirname, '..', 'format-currency-sek-label.mjs')
const tempDirs: string[] = []
afterAll(() => {
for (const dir of tempDirs) fs.rmSync(dir, { recursive: true, force: true })
})
describe('sek-labelled-amount guard: catches a foreign amount printed as SEK', () => {
it('flags a single-argument call on a record the file reads .currency from', () => {
const source = `
export function InvoiceTotal({ invoice }: { invoice: Invoice }) {
if (invoice.currency !== 'SEK') return null
return (
<span>
{formatCurrency(invoice.total)}
</span>
)
}
`
const findings = scan('components/invoices/Offender.tsx', source)
expect(findings).toHaveLength(1)
expect(findings[0].expr).toBe('invoice.total')
expect(findings[0].where).toBe('components/invoices/Offender.tsx:6')
})
it('sees through Number() / Math.abs() / unary minus wrappers', () => {
const source = `
const label = invoice.currency === 'EUR' ? formatCurrency(-Math.abs(Number(invoice.subtotal))) : ''
`
expect(scan('components/invoices/Wrapped.tsx', source).map((f) => f.expr)).toEqual([
'invoice.subtotal',
])
})
it('flags a ?? fallback whose right side is the foreign figure', () => {
const source = `
const label = invoice.currency ? formatCurrency(invoice.total_sek ?? invoice.total) : ''
`
expect(scan('components/invoices/Fallback.tsx', source).map((f) => f.expr)).toEqual([
'invoice.total',
])
})
it('flags amount_in_currency even with no .currency read in the file', () => {
const source = `const label = formatCurrency(line.amount_in_currency)`
expect(scan('components/bookkeeping/Foreign.tsx', source).map((f) => f.expr)).toEqual([
'line.amount_in_currency',
])
})
})
describe('sek-labelled-amount guard: leaves correct code alone', () => {
it.each([
['the currency is passed', `const s = invoice.currency ? formatCurrency(invoice.total, invoice.currency) : ''`],
['the SEK twin is formatted', `const s = invoice.currency !== 'SEK' && invoice.total_sek ? formatCurrency(invoice.total_sek) : ''`],
['a camelCase SEK twin is formatted', `const s = invoice.currency ? formatCurrency(invoice.totalSek) : ''`],
// journal_entry_lines.debit_amount is ALWAYS SEK; line.currency labels the
// document. See lib/bookkeeping/ledger-line-amount.ts (structural root 4.1).
['a ledger column is formatted', `const s = line.currency !== 'SEK' ? formatCurrency(line.debit_amount) : ''`],
['the owner has no currency in the file', `const s = formatCurrency(row.amount)`],
['a different owner carries the currency', `const s = invoice.currency ? formatCurrency(candidate.amount) : ''`],
// amount * rate is a conversion INTO kronor, so the result is SEK.
['the expression converts to SEK', `const s = invoice.currency ? formatCurrency(invoice.total * rate) : ''`],
['there is no formatCurrency call at all', `const s = invoice.currency + invoice.total`],
])('stays silent when %s', (_label, source) => {
expect(scan('components/invoices/Clean.tsx', source)).toEqual([])
})
})
describe('sek-labelled-amount guard: end to end through the CI entry point', () => {
function fixtureTree(files: Record<string, string>): string {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'sek-label-guard-'))
tempDirs.push(root)
for (const [relPath, text] of Object.entries(files)) {
const full = path.join(root, relPath)
fs.mkdirSync(path.dirname(full), { recursive: true })
fs.writeFileSync(full, text)
}
return root
}
function run(root: string): { status: number; findings: { where: string; expr: string }[] } {
try {
const stdout = execFileSync('node', [GUARD, root, '--json'], { encoding: 'utf8' })
return { status: 0, findings: JSON.parse(stdout) }
} catch (e) {
const err = e as { status: number; stdout: string }
return { status: err.status, findings: JSON.parse(err.stdout) }
}
}
const CLEAN = `
export function SupplierInvoiceRow({ invoice }: { invoice: SupplierInvoice }) {
return <td>{formatCurrency(invoice.total, invoice.currency)}</td>
}
`
const OFFENDING = `
export function SupplierInvoiceRow({ invoice }: { invoice: SupplierInvoice }) {
if (invoice.currency !== 'SEK') return null
return <td>{formatCurrency(invoice.total)}</td>
}
`
it('exits 0 on a tree with only correct calls', () => {
const result = run(fixtureTree({ 'components/suppliers/Row.tsx': CLEAN }))
expect(result.findings).toEqual([])
expect(result.status).toBe(0)
})
it('exits 1 and names the site once the offending call is introduced', () => {
const result = run(fixtureTree({ 'components/suppliers/Row.tsx': OFFENDING }))
expect(result.status).toBe(1)
expect(result.findings).toHaveLength(1)
expect(result.findings[0].where).toBe('components/suppliers/Row.tsx:4')
expect(result.findings[0].expr).toBe('invoice.total')
})
it('ignores test files, so a fixture in a spec cannot fail the build', () => {
const result = run(fixtureTree({ 'components/suppliers/__tests__/Row.test.tsx': OFFENDING }))
expect(result.findings).toEqual([])
expect(result.status).toBe(0)
})
})
@@ -0,0 +1,114 @@
/**
* Proof that the raw-reference-fetch ratchet catches the thing and leaves the
* legitimate shapes alone. Offending fixtures live only in these strings and
* in an OS temp directory the end-to-end case creates and deletes.
*/
import { describe, it, expect, afterAll } from 'vitest'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import {
findRawReferenceFetches,
findRawReferenceFetchesInSource as scan,
isClientSource,
} from '../raw-reference-fetch.mjs'
const tempDirs: string[] = []
afterAll(() => {
for (const dir of tempDirs) fs.rmSync(dir, { recursive: true, force: true })
})
const kinds = (source: string) => scan(source).map((f: { kind: string }) => f.kind)
describe('raw-reference-fetch: GET-shaped API calls', () => {
it('flags a bare GET of each reference path, with or without a query string', () => {
expect(kinds(`const res = await fetch('/api/settings')`)).toEqual(['api'])
expect(kinds('fetch(`/api/bookkeeping/fiscal-periods`)')).toEqual(['api'])
expect(kinds(`fetch('/api/bookkeeping/accounts?active=false')`)).toEqual(['api'])
expect(kinds(`fetch('/api/settings/booking-templates', { signal })`)).toEqual(['api'])
expect(kinds(`fetch('/api/cash-accounts?enabled_only=true', { headers: { a: '1' } })`)).toEqual(['api'])
expect(kinds(`fetch(\n '/api/customers',\n { signal: controller.signal },\n)`)).toEqual(['api'])
})
it('ignores writes: they go through the API and then invalidate the cache', () => {
expect(kinds(`fetch('/api/settings', { method: 'PUT', body })`)).toEqual([])
expect(kinds(`fetch('/api/customers', { method: 'POST', headers: { 'content-type': 'x' }, body })`)).toEqual([])
expect(kinds("fetch(`/api/settings/booking-templates/${id}/touch`, { method: 'POST' })")).toEqual([])
expect(kinds(`fetch('/api/articles/' + id, { method: 'DELETE' })`)).toEqual([])
})
it('does not confuse sub-resources or lookalike paths with the reference lists', () => {
expect(kinds("fetch(`/api/settings/booking-templates/${id}`)")).toEqual([])
expect(kinds(`fetch('/api/settings/banking')`)).toEqual([])
expect(kinds(`fetch('/api/customers/abc')`)).toEqual([])
expect(kinds(`fetch('/api/bookkeeping/accounts/bas-catalog')`)).toEqual([])
})
})
describe('raw-reference-fetch: regex safety', () => {
it('scans a pathological near-miss in linear time (no catastrophic backtracking)', () => {
// A fetch call that never closes, padded with the whitespace/comma mix
// the old `\s*,?\s*\)` tail was ambiguous on.
const source = `fetch('/api/settings'${' ,'.repeat(5000)}${' '.repeat(5000)}X`
const start = performance.now()
expect(scan(source)).toEqual([])
expect(performance.now() - start).toBeLessThan(200)
})
})
describe('raw-reference-fetch: use-client detection is linear too', () => {
it('handles a long run of unclosed block comments without backtracking', () => {
const source = `${'/* '.repeat(3000)}'use client'\n`
const start = performance.now()
expect(isClientSource(source)).toBe(false)
expect(performance.now() - start).toBeLessThan(200)
})
it('still sees the directive behind closed comments', () => {
expect(isClientSource(`/* a */ /* b */\n// c\n'use client'\n`)).toBe(true)
})
})
describe('raw-reference-fetch: browser-side table reads', () => {
const clientRead = `'use client'\nimport x from 'y'\nconst { data } = await supabase.from('fiscal_periods').select('*').eq('company_id', id)`
it('flags a select on a reference table only in a use-client file', () => {
expect(kinds(clientRead)).toEqual(['table'])
expect(kinds(clientRead.replace(`'use client'\n`, ''))).toEqual([])
})
it('recognises the directive behind leading comments and double quotes', () => {
expect(isClientSource(`// header\n/* block */\n"use client"\n`)).toBe(true)
expect(isClientSource(`import a from 'b'\n'use client'`)).toBe(false)
})
it('leaves inserts and updates alone', () => {
expect(kinds(`'use client'\nawait supabase.from('fiscal_periods').insert(row)`)).toEqual([])
expect(kinds(`'use client'\nawait supabase.from('company_settings').update(patch).eq('company_id', id)`)).toEqual([])
})
})
describe('raw-reference-fetch: file scan', () => {
it('reports offending files relative to the root and skips sanctioned, api and test files', () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'raw-ref-'))
tempDirs.push(root)
const write = (rel: string, content: string) => {
const full = path.join(root, rel)
fs.mkdirSync(path.dirname(full), { recursive: true })
fs.writeFileSync(full, content)
}
write('components/Bad.tsx', `'use client'\nfetch('/api/settings')`)
write('components/Fine.tsx', `'use client'\nfetch('/api/settings', { method: 'PUT' })`)
write('components/__tests__/Bad.test.tsx', `fetch('/api/settings')`)
write('components/Bad.test.ts', `fetch('/api/settings')`)
write('lib/reference-data/fetchers.ts', `fetch('/api/settings')`)
write('app/api/x/route.ts', `fetch('/api/settings')`)
write('app/(dashboard)/reports/page.tsx', `'use client'\nconst r = await fetch('/api/bookkeeping/fiscal-periods')`)
write('lib/server-thing.ts', `await supabase.from('company_settings').select('*')`)
expect(findRawReferenceFetches(root)).toEqual([
'app/(dashboard)/reports/page.tsx',
'components/Bad.tsx',
])
})
})
+349
View File
@@ -0,0 +1,349 @@
#!/usr/bin/env node
/**
* Guard: an un-hinted PostgREST embed between two tables that share more than
* one foreign key.
*
* PostgREST resolves `.from('a').select('b(...)')` by looking for THE foreign
* key between a and b, in either direction. When several exist it refuses the
* request with PGRST201 ("Could not embed because more than one relationship
* was found") instead of picking one. The embed must then name the
* relationship, and PostgREST accepts two spellings for that:
*
* b!a_b_id_fkey(...) the constraint name
* b!b_column_id(...) the foreign key COLUMN name
*
* Both are in use here (`fiscal_periods!journal_entries_fiscal_period_id_fkey`
* in lib/transactions/inbox-underlag.ts, `journal_entries!opening_balance_entry_id`
* in lib/import/opening-balance/cascade.ts), so either counts as hinted.
* `!inner` / `!left` are join modifiers, not hints, and do not disambiguate.
*
* Why a static guard is the only thing that can catch this: the failure is a
* runtime PostgREST decision. Unit tests mock the Supabase client and hand back
* an already-joined row shape, so they never resolve a relationship; pg-real
* tests talk to Postgres directly and never go through PostgREST at all. The
* class has now been reasoned about three times and shipped broken twice, both
* on journal_entries -> fiscal_periods, ambiguous since migration
* 20240101000019 added fiscal_periods.closing_entry_id and
* fiscal_periods.opening_balance_entry_id:
* - lib/transactions/inbox-underlag.ts (fixed 2026-08-31, PR #2022): the
* nightly underlag cron read an empty locked-set and then tried to link
* documents into locked periods, ~60 trigger rejections a night.
* - lib/core/documents/supplier-invoice-underlag.ts (fixed 2026-09-01): the
* error was dropped on the floor, so supplier-invoice underlag never once
* anchored in production and users kept seeing "Underlag saknas" on a
* verifikat that plainly showed the invoice PDF.
*
* The ambiguous pairs are DERIVED from supabase/migrations/*.sql rather than
* hardcoded, so a migration that adds a second foreign key between two tables
* arms the guard for that pair on the same commit. To check the derivation
* against the live schema:
*
* select least(s.relname, t.relname) a, greatest(s.relname, t.relname) b, count(*)
* from pg_constraint c
* join pg_class s on s.oid = c.conrelid
* join pg_class t on t.oid = c.confrelid
* join pg_namespace ns on ns.oid = s.relnamespace and ns.nspname = 'public'
* join pg_namespace nt on nt.oid = t.relnamespace and nt.nspname = 'public'
* where c.contype = 'f'
* group by 1, 2 having count(*) > 1 order by 1, 2;
*
* On 2026-09-03 that returned the same 17 pairs the parser derives. Composite
* foreign keys count: until 2026-09-03 the parser only read single-column
* `FOREIGN KEY (col)`, so the composite (sales_order_id, company_id) guard in
* 20260902180000_sales_orders_hardening.sql was invisible to it and the
* un-hinted `items:sales_order_items(*)` embeds shipped, taking every
* kundorder list and detail load down with PGRST201 (fixed 2026-09-03).
*
* No baseline: the count is 0, any new un-hinted ambiguous embed is a hard
* failure.
*/
import fs from 'node:fs'
import path from 'node:path'
import ts from 'typescript'
const SCAN_DIRS = ['app', 'components', 'contexts', 'extensions', 'lib', 'scripts']
const IGNORE_DIRS = new Set([
'node_modules',
'.next',
'.git',
'dist',
'build',
'coverage',
'__tests__',
])
/** Undirected pair key: PostgREST considers foreign keys in both directions. */
export const pairKey = (a, b) => (a < b ? `${a}|${b}` : `${b}|${a}`)
const stripSql = (sql) => sql.replace(/--[^\n]*/g, '').replace(/\/\*[\s\S]*?\*\//g, '')
const normIdent = (t) => t.replace(/"/g, '').replace(/^public\./i, '').toLowerCase()
/**
* Foreign keys declared across the migration history, as a map of
* `<table>.<column>` -> target table. Keying on the column (rather than
* counting statements) makes the repeated idempotent re-adds this repo is full
* of collapse onto one edge, which is what Postgres ends up with.
*
* Only the shapes that actually appear in supabase/migrations are parsed:
* inline `REFERENCES` in a CREATE TABLE column, table-level
* `FOREIGN KEY (col) REFERENCES`, `ADD COLUMN ... REFERENCES`, and
* `ADD CONSTRAINT ... FOREIGN KEY (col) REFERENCES`. Drops are honoured so a
* relationship that was removed again does not keep a pair armed forever.
*/
export function deriveForeignKeys(migrationsDir) {
const edges = new Map()
// Constraint name -> edge key, so DROP CONSTRAINT can find what it removes.
// Unnamed foreign keys get Postgres's default `<table>_<column>_fkey`.
const byConstraint = new Map()
// `column` is one column or a composite list ("sales_order_id, company_id").
// A composite foreign key is its own edge, distinct from a single-column one
// on its leading column: PostgREST counts both, which is what made
// sales_order_items -> sales_orders ambiguous (migration 20260902180000)
// while this parser, then single-column only, still derived one edge.
const addEdge = (table, column, target, constraintName) => {
const columns = column.split(',').map((c) => normIdent(c.trim())).filter(Boolean)
const key = `${table}.${columns.join(',')}`
edges.set(key, target)
byConstraint.set(constraintName ?? `${table}_${columns.join('_')}_fkey`, key)
}
let files
try {
files = fs.readdirSync(migrationsDir).filter((f) => f.endsWith('.sql')).sort()
} catch {
return edges
}
for (const file of files) {
const sql = stripSql(fs.readFileSync(path.join(migrationsDir, file), 'utf8'))
for (const raw of sql.split(';')) {
const stmt = raw.trim()
if (!stmt) continue
const created = stmt.match(/create\s+table\s+(?:if\s+not\s+exists\s+)?([\w".]+)\s*\(/i)
const altered = stmt.match(/alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?([\w".]+)/i)
const dropped = stmt.match(/drop\s+table\s+(?:if\s+exists\s+)?([\w".]+)/i)
if (created) {
const table = normIdent(created[1])
// `col uuid references public.other(id)` inside the column list.
for (const m of stmt.matchAll(/(?:^|,)\s*([\w"]+)\s+[^,()]*?references\s+([\w".]+)/gis)) {
addEdge(table, normIdent(m[1]), normIdent(m[2]))
}
// `foreign key (col[, col]) references public.other(id[, id])` as a
// table constraint, named or not.
for (const m of stmt.matchAll(
/(?:constraint\s+([\w"]+)\s+)?foreign\s+key\s*\(\s*([\w",\s]+?)\s*\)\s*references\s+([\w".]+)/gi,
)) {
addEdge(table, m[2], normIdent(m[3]), m[1] && normIdent(m[1]))
}
continue
}
if (altered) {
const table = normIdent(altered[1])
for (const m of stmt.matchAll(
/(?:add\s+constraint\s+([\w"]+)\s+)?foreign\s+key\s*\(\s*([\w",\s]+?)\s*\)\s*references\s+([\w".]+)/gi,
)) {
addEdge(table, m[2], normIdent(m[3]), m[1] && normIdent(m[1]))
}
for (const m of stmt.matchAll(
/add\s+column\s+(?:if\s+not\s+exists\s+)?([\w"]+)\s+[^,;]*?references\s+([\w".]+)/gi,
)) {
addEdge(table, normIdent(m[1]), normIdent(m[2]))
}
for (const m of stmt.matchAll(/drop\s+column\s+(?:if\s+exists\s+)?([\w"]+)/gi)) {
// Postgres drops every foreign key the column takes part in, so a
// composite edge listing it goes too, not only the single-column key.
const column = normIdent(m[1])
for (const key of [...edges.keys()]) {
if (!key.startsWith(`${table}.`)) continue
if (!key.slice(table.length + 1).split(',').includes(column)) continue
edges.delete(key)
for (const [name, edge] of [...byConstraint]) {
if (edge === key) byConstraint.delete(name)
}
}
}
for (const m of stmt.matchAll(/drop\s+constraint\s+(?:if\s+exists\s+)?([\w"]+)/gi)) {
const edge = byConstraint.get(normIdent(m[1]))
if (edge) edges.delete(edge)
}
continue
}
if (dropped) {
const table = normIdent(dropped[1])
for (const [key, target] of [...edges]) {
if (key.startsWith(`${table}.`) || target === table) edges.delete(key)
}
}
}
}
return edges
}
/** Table pairs joined by more than one foreign key, as `pairKey` strings. */
export function deriveAmbiguousPairs(migrationsDir) {
const counts = new Map()
for (const [key, target] of deriveForeignKeys(migrationsDir)) {
const source = key.slice(0, key.indexOf('.'))
// auth.users and other non-public tables are never embedded through PostgREST here.
if (source.includes('.') || target.includes('.')) continue
const pair = pairKey(source, target)
counts.set(pair, (counts.get(pair) ?? 0) + 1)
}
return new Set([...counts].filter(([, n]) => n > 1).map(([pair]) => pair))
}
const HEAD_CHARS = /[\w!]/
// An embed head is preceded by the start of the select string, a separator, or
// the `:` of an alias. `fiscal_period:fiscal_periods(...)` is the shape both
// production bugs were written in, so `:` MUST be a delimiter here.
const HEAD_DELIMITERS = new Set([',', ':', '(', ' ', '\t', '\n', '\r'])
const JOIN_MODIFIERS = new Set(['inner', 'left'])
/**
* The embed head immediately before `index` (which points at its `(`), or null
* when the paren does not open an embed.
*/
function headBefore(select, index) {
let end = index
while (end > 0 && /\s/.test(select[end - 1])) end--
let start = end
while (start > 0 && HEAD_CHARS.test(select[start - 1])) start--
if (start === end) return null
if (start > 0 && !HEAD_DELIMITERS.has(select[start - 1])) return null
const [target, ...modifiers] = select.slice(start, end).split('!')
if (!target) return null
return { target: target.toLowerCase(), hinted: modifiers.some((m) => !JOIN_MODIFIERS.has(m)) }
}
/**
* Every embed in one select string, paired with the table it is embedded FROM.
* Nested embeds resolve against their enclosing embed, not against the root.
*/
export function parseEmbeds(select, rootTable) {
const embeds = []
const stack = [rootTable]
for (let i = 0; i < select.length; i++) {
if (select[i] === '(') {
const head = headBefore(select, i)
const from = stack[stack.length - 1]
if (head && from) embeds.push({ from, target: head.target, hinted: head.hinted })
stack.push(head ? head.target : null)
} else if (select[i] === ')') {
if (stack.length > 1) stack.pop()
}
}
return embeds
}
/**
* The table a `.select()` call reads from, resolved by walking ITS OWN method
* chain back to `.from()`. Never the nearest preceding `.from()` in the file:
* `.from('journal_entry_lines').select('... journal_entries!inner(...)')` sits
* a few lines below an unrelated `.from('journal_entries')` in
* scripts/seed-demo-account.ts, and pairing by proximity flags it wrongly.
*/
function fromTableOfChain(selectCall) {
let node = selectCall.expression.expression
while (node) {
if (ts.isCallExpression(node)) {
const callee = node.expression
if (ts.isPropertyAccessExpression(callee) && callee.name.text === 'from') {
const arg = node.arguments[0]
return arg && ts.isStringLiteralLike(arg) ? arg.text.toLowerCase() : null
}
node = ts.isPropertyAccessExpression(callee) ? callee.expression : callee
continue
}
if (ts.isPropertyAccessExpression(node)) {
node = node.expression
continue
}
return null
}
return null
}
/**
* Un-hinted embeds of an ambiguous pair in one file's source, as
* `{ line, from, target }`. Exported for the unit test.
*/
export function findAmbiguousEmbedsInSource(sourceText, fileName, ambiguousPairs) {
const source = ts.createSourceFile(
fileName,
sourceText,
ts.ScriptTarget.Latest,
true,
fileName.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS,
)
const findings = []
const visit = (node) => {
if (
ts.isCallExpression(node) &&
ts.isPropertyAccessExpression(node.expression) &&
node.expression.name.text === 'select' &&
node.arguments.length > 0 &&
ts.isStringLiteralLike(node.arguments[0])
) {
const from = fromTableOfChain(node)
if (from) {
for (const embed of parseEmbeds(node.arguments[0].text, from)) {
if (embed.hinted) continue
if (!ambiguousPairs.has(pairKey(embed.from, embed.target))) continue
const pos = source.getLineAndCharacterOfPosition(node.getStart(source))
findings.push({ line: pos.line + 1, from: embed.from, target: embed.target })
}
}
}
ts.forEachChild(node, visit)
}
visit(source)
return findings
}
function walk(dir, out) {
let entries
try {
entries = fs.readdirSync(dir, { withFileTypes: true })
} catch {
return out
}
for (const entry of entries) {
if (entry.name.startsWith('.') || IGNORE_DIRS.has(entry.name)) continue
const full = path.join(dir, entry.name)
if (entry.isDirectory()) walk(full, out)
else if (/\.tsx?$/.test(entry.name) && !/\.test\.tsx?$/.test(entry.name)) out.push(full)
}
return out
}
/** Findings across the repo, as `{ where, from, target }`, sorted. */
export function findAmbiguousEmbeds(root) {
const ambiguousPairs = deriveAmbiguousPairs(path.join(root, 'supabase', 'migrations'))
if (ambiguousPairs.size === 0) return []
const findings = []
for (const dir of SCAN_DIRS) {
for (const file of walk(path.join(root, dir), [])) {
const sourceText = fs.readFileSync(file, 'utf8')
if (!sourceText.includes('.select(')) continue
const relPath = path.relative(root, file).split(path.sep).join('/')
for (const finding of findAmbiguousEmbedsInSource(sourceText, file, ambiguousPairs)) {
findings.push({
where: `${relPath}:${finding.line}`,
from: finding.from,
target: finding.target,
})
}
}
}
return findings.sort((a, b) => a.where.localeCompare(b.where))
}
+67
View File
@@ -0,0 +1,67 @@
{
"_comment": "Ratchet baseline for scripts/checks/no-new-antipatterns.mjs. These counts may only decrease. Re-run with --update after a migration lowers them. Goal: both reach 0 (A1 route-auth campaign, D1 rounding codemod).",
"rawRouteAuth": {
"count": 1,
"files": [
"app/api/mcp-oauth/authorize/route.ts"
]
},
"naiveOreRound": {
"count": 615
},
"handRolledInvariants": {
"count": 113
},
"ledgerScanningReports": {
"count": 4,
"files": [
"lib/bokslut/assets/asset-service.ts",
"lib/bokslut/reserves/periodiseringsfond-service.ts",
"lib/bokslut/tax-provision/bolagsskatt-calculator.ts",
"lib/bokslut/tax-provision/sarskild-loneskatt-calculator.ts"
]
},
"dialogOverflowRisk": {
"count": 7,
"files": [
"app/(dashboard)/supplier-invoices/[id]/page.tsx",
"components/bookkeeping/JournalEntryForm.tsx",
"components/invoices/PaymentBookingDialog.tsx",
"components/invoices/SendInvoiceDialog.tsx",
"components/reports/views/index.tsx",
"components/salary/NewEmployeeDialog.tsx",
"components/transactions/InvoiceMatchDialog.tsx"
]
},
"rawReferenceFetch": {
"count": 0,
"files": []
},
"providerHosts": {
"count": 22,
"files": [
"app/api/connect/bank/[...path]/route.ts",
"extensions/general/bolagsverket/lib/client.ts",
"extensions/general/enable-banking/index.ts",
"extensions/general/enable-banking/lib/api-client.ts",
"extensions/general/mail/lib/gmail-client.ts",
"extensions/general/skatteverket/index.ts",
"extensions/general/skatteverket/lib/connector-mode.ts",
"extensions/general/skatteverket/lib/ombud-client.ts",
"extensions/general/skatteverket/lib/skattekonto-client.ts",
"extensions/general/tic/index.ts",
"extensions/general/tic/lib/bankid-client.ts",
"extensions/general/tic/lib/bankid-types.ts",
"extensions/general/whatsapp-inbox/lib/graph-api.ts",
"lib/connect/upstreams/enable-banking-jwt.ts",
"lib/invoices/transports/qvalia.ts",
"lib/providers/bjornlunden/config.ts",
"lib/providers/bjornlunden/oauth.ts",
"lib/providers/bokio/client.ts",
"lib/providers/bokio/config.ts",
"lib/providers/briox/config.ts",
"lib/providers/fortnox/config.ts",
"lib/providers/visma/config.ts"
]
}
}
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env node
/**
* Guard: a 'use client' module whose static import closure reaches a Node
* builtin (crypto, buffer, vm, stream, fs, ...).
*
* Turbopack polyfills those for the browser (crypto-browserify, vm-browserify,
* Buffer: ~327 KB uncompressed) the moment ANY client module can reach them,
* and the polyfill chunk then ships with every route that renders the
* component. Before the 2026-08-26 split, lib/auth/bankid.ts (login,
* register, security settings), lib/import/bank-file/parser.ts (bank import
* history), lib/salary/personnummer.ts (via tax-column, the employee forms)
* and lib/auth/api-keys.ts (the API key panel) each did this for a function
* that never touched crypto. The fix is always the same: move the pure part
* into a sibling module without the Node import and import that from the
* client (see bankid-flags.ts, bank-file/formats.ts, personnummer-format.ts,
* api-key-scopes.ts).
*
* No baseline: the count is 0, any new reacher is a hard failure. The walk
* is the same static closure scripts/perf/client-import-closure.mjs prints.
*/
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { buildGraph, clientReachers } from '../perf/client-import-closure.mjs'
export const NODE_BUILTINS = ['crypto', 'node:crypto', 'buffer', 'node:buffer', 'vm', 'node:vm', 'stream', 'node:stream', 'fs', 'node:fs', 'path', 'node:path', 'child_process', 'node:child_process']
/** [{ file, builtin, chain }] for every client file reaching a builtin. */
export function findClientNodeBuiltins(root) {
const graph = buildGraph(root)
const findings = []
for (const builtin of NODE_BUILTINS) {
for (const [file, chain] of clientReachers(graph, `bare:${builtin}`, root)) {
findings.push({ file, builtin, chain })
}
}
return findings.sort((a, b) => a.file.localeCompare(b.file) || a.builtin.localeCompare(b.builtin))
}
const isMain = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
if (isMain) {
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..')
const findings = findClientNodeBuiltins(root)
for (const f of findings) console.log(`${f.file} -> ${f.builtin}\n ${f.chain.join('\n > ')}`)
console.log(`${findings.length} client file(s) reach a Node builtin`)
process.exit(findings.length ? 1 : 0)
}
+4
View File
@@ -0,0 +1,4 @@
{
"totalErrors": 0,
"perRule": {}
}
+113
View File
@@ -0,0 +1,113 @@
/**
* Guards for the app/api/extensions carve-out.
*
* Physical routes under `app/api/extensions/<extensionId>/` are the ONE
* sanctioned place where app code may import from `@/extensions/` (see the
* "Check no core imports from extensions" step in
* .github/workflows/core-build.yml, which exempts exactly this directory).
* They exist because Vercel crons and OAuth callbacks need concrete file
* routes; the `ext/[...path]` dispatcher covers everything else.
*
* The carve-out has two invariants this guard enforces:
*
* 1. cross-extension-import (hard fail, count 0 today): a route under
* app/api/extensions/<id>/ may only import from its own extension,
* `@/extensions/<sector>/<id>/`. Reaching into another extension from
* here would create hidden coupling the registry cannot see.
*
* 2. ungated-extension-route (ratchet, may only shrink): these routes
* compile into EVERY build, including the core-with-zero-extensions CI
* build; disabling an extension in extensions.config.json only removes
* it from the runtime registry, never from the filesystem. So a route
* that executes extension code must first check
* `extensionRegistry.get('<id>')` (after loadExtensions()) and refuse
* when the extension is not registered: otherwise a disabled extension
* still exposes a live, invokable surface (this is exactly how the
* disabled push-notifications extension shipped an always-armed cron).
* Pre-existing routes are allowlisted below; the set may only shrink as
* gates are added. A NEW route must ship with the gate.
*/
import fs from 'node:fs'
import path from 'node:path'
/**
* Routes that predate the enablement-gate requirement. Remove an entry once
* its route checks `extensionRegistry.get('<id>')`; never add one.
*/
export const UNGATED_EXTENSION_ROUTES = new Set([
'app/api/extensions/cloud-backup/auto-sync/cron/route.ts',
'app/api/extensions/enable-banking/callback/route.ts',
'app/api/extensions/enable-banking/sync/cron/route.ts',
'app/api/extensions/skatteverket/agi/kvittenser/cron/route.ts',
'app/api/extensions/skatteverket/skattekonto/sync/cron/route.ts',
'app/api/extensions/skatteverket/vat/kvittenser/cron/route.ts',
'app/api/extensions/stripe/callback/route.ts',
'app/api/extensions/stripe/sync/cron/route.ts',
'app/api/extensions/stripe/transactions/cron/route.ts',
])
const EXTENSION_IMPORT_RE = /from\s+['"]@\/extensions\/[^/'"]+\/([^/'"]+)\//g
function walkRouteFiles(dir, out = []) {
let entries
try {
entries = fs.readdirSync(dir, { withFileTypes: true })
} catch {
return out
}
for (const e of entries) {
const full = path.join(dir, e.name)
if (e.isDirectory()) {
if (e.name === '__tests__') continue
walkRouteFiles(full, out)
} else if (e.name === 'route.ts') {
out.push(full)
}
}
return out
}
/**
* Scan app/api/extensions/<id>/ physical routes.
* Returns { crossImports: [{ file, imported }], ungated: [file] } with
* repo-relative, forward-slash paths.
*/
export function findExtensionRouteFindings(ROOT) {
const base = path.join(ROOT, 'app', 'api', 'extensions')
const rel = (p) => path.relative(ROOT, p).split(path.sep).join('/')
const crossImports = []
const ungated = []
for (const file of walkRouteFiles(base)) {
const relPath = rel(file)
const segments = relPath.split('/')
const extensionId = segments[3] // app/api/extensions/<id>/...
// The dispatcher and the generic dynamic-segment routes go through the
// registry already and import nothing from @/extensions/.
if (!extensionId || extensionId === 'ext' || extensionId.startsWith('[')) continue
const src = fs.readFileSync(file, 'utf8')
let importsOwnExtension = false
for (const match of src.matchAll(EXTENSION_IMPORT_RE)) {
if (match[1] === extensionId) {
importsOwnExtension = true
} else {
crossImports.push({ file: relPath, imported: match[1] })
}
}
if (!importsOwnExtension && crossImports.every((c) => c.file !== relPath)) continue
const hasGate =
src.includes(`extensionRegistry.get('${extensionId}')`) ||
src.includes(`extensionRegistry.get("${extensionId}")`)
if (!hasGate) ungated.push(relPath)
}
crossImports.sort((a, b) => a.file.localeCompare(b.file))
ungated.sort()
return { crossImports, ungated }
}
@@ -0,0 +1,277 @@
#!/usr/bin/env node
/**
* Guard: a foreign amount printed with the SEK symbol.
*
* `formatCurrency(amount, currency = 'SEK')` (lib/utils.ts) defaults its second
* argument, and that default is deliberate: `formatCurrency(amount)` is the
* right call on the ~hundreds of values that ARE kronor, and sv-SE/SEK output
* in both locales is a Swedish accounting convention rather than a UI string
* (.claude/rules/i18n.md). What the default cannot do is notice when the number
* handed to it came off a record that carries its own currency: there the
* omitted argument silently relabels 100 EUR as "100,00 kr".
*
* So this check does not touch the signature; it fails CI on the ONE shape the
* default cannot defend against:
*
* 1. A single-argument call whose amount is read off an owner that the SAME
* file also reads `.currency` from. The file demonstrably knows the unit
* and dropped it: `formatCurrency(invoice.total)` two lines under
* `invoice.currency !== 'SEK'`. The currency argument (or the `*_sek`
* twin) is right there.
* 2. A single-argument call on `amount_in_currency`, which is by definition
* the foreign figure on a journal entry line and never kronor.
*
* NOT flagged, on purpose:
* - `debit_amount` / `credit_amount` (and the bare `debit` / `credit` used by
* preview rows). Journal entry line amounts are ALWAYS SEK; `line.currency`
* labels the DOCUMENT, not the figure (lib/bookkeeping/ledger-line-amount.ts).
* A file that correctly reads both must not be accused.
* - Any `*_sek` / `*Sek` field: that IS the kronor twin, and rendering it with
* the SEK symbol is exactly right (see the five call sites this rule was
* calibrated against, e.g. components/invoices/SendInvoiceDialog.tsx).
* - A multiplicative expression (`total * exchangeRate`): that is a
* conversion INTO kronor, so the result is SEK.
* - Owners the file never reads a currency from. Judging a bare local like
* `formatCurrency(totalDebit)` would need whole-program dataflow, and
* guessing there is how a guard earns its way onto an ignore list.
*
* Escape hatch: add `<relative path>#<owner>.<field>` to SANCTIONED below with
* a justification. Line numbers are deliberately not part of the key, so an
* unrelated edit above the call cannot break the entry.
*
* Usage:
* node scripts/checks/format-currency-sek-label.mjs # scan the repo
* node scripts/checks/format-currency-sek-label.mjs <dir> # scan a tree
* node scripts/checks/format-currency-sek-label.mjs <dir> --json
*
* Wired into `npm run check:guards` (scripts/checks/no-new-antipatterns.mjs).
*/
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import ts from 'typescript'
/** Subtrees scanned, relative to the root passed in. */
const SCAN_DIRS = ['lib', 'app', 'components', 'extensions']
const IGNORE_DIRS = new Set(['node_modules', '.next', '.git', 'dist', 'build', 'coverage'])
/**
* Deliberate single-argument calls on a currency-bearing owner, keyed
* `<relative path>#<owner>.<field>`. Empty today: every such call in the repo
* formats a `*_sek` twin or a ledger column and is excluded by rule.
*/
const SANCTIONED = new Set()
/** Fields whose value is kronor no matter what currency the owner carries. */
const ALWAYS_SEK_FIELDS = new Set([
// Journal entry line columns. See lib/bookkeeping/ledger-line-amount.ts.
'debit_amount',
'credit_amount',
'debit',
'credit',
'total_debit',
'total_credit',
])
/** By definition the foreign figure: never kronor, so never single-argument. */
const NEVER_SEK_FIELDS = new Set(['amount_in_currency'])
/** Calls that pass the unit through unchanged, so we look at their argument. */
const UNIT_PRESERVING_CALLS = new Set([
'Number',
'parseFloat',
'parseInt',
'abs',
'round',
'trunc',
'roundOre',
'roundToOre',
])
const UNWRAP_KINDS = new Set([
ts.SyntaxKind.ParenthesizedExpression,
ts.SyntaxKind.AsExpression,
ts.SyntaxKind.SatisfiesExpression,
ts.SyntaxKind.NonNullExpression,
ts.SyntaxKind.TypeAssertionExpression,
])
function walk(dir, out = []) {
let entries
try {
entries = fs.readdirSync(dir, { withFileTypes: true })
} catch {
return out
}
for (const entry of entries) {
if (entry.name.startsWith('.')) continue
const full = path.join(dir, entry.name)
if (entry.isDirectory()) {
if (!IGNORE_DIRS.has(entry.name)) walk(full, out)
} else if (/\.tsx?$/.test(entry.name) && !/\.test\.tsx?$/.test(entry.name)) {
out.push(full)
}
}
return out
}
/** `a.b.c` -> { owner: 'a.b', field: 'c' }; anything not identifier-rooted -> null. */
function accessChain(node) {
const parts = []
let current = node
while (ts.isPropertyAccessExpression(current)) {
parts.unshift(current.name.text)
current = current.expression
}
if (!ts.isIdentifier(current) || parts.length === 0) return null
const field = parts.pop()
return { owner: [current.text, ...parts].join('.'), field }
}
/**
* Every property access whose value the expression forwards in the SAME unit.
* Both branches of `??` / `||` / `?:` and both operands of `+` / `-` count: a
* `total_sek ?? total` fallback is precisely the shape that prints a foreign
* number when the SEK twin is missing.
*/
function unitBearingAccesses(node, out = []) {
if (!node) return out
if (UNWRAP_KINDS.has(node.kind) && node.expression) return unitBearingAccesses(node.expression, out)
if (
ts.isPrefixUnaryExpression(node) &&
(node.operator === ts.SyntaxKind.MinusToken || node.operator === ts.SyntaxKind.PlusToken)
) {
return unitBearingAccesses(node.operand, out)
}
if (ts.isConditionalExpression(node)) {
unitBearingAccesses(node.whenTrue, out)
unitBearingAccesses(node.whenFalse, out)
return out
}
if (ts.isBinaryExpression(node)) {
const kind = node.operatorToken.kind
const forwards =
kind === ts.SyntaxKind.QuestionQuestionToken ||
kind === ts.SyntaxKind.BarBarToken ||
kind === ts.SyntaxKind.PlusToken ||
kind === ts.SyntaxKind.MinusToken
// Multiplication / division is a CONVERSION (amount * exchangeRate), so the
// result is no longer the operand's unit and must not be judged as one.
if (!forwards) return out
unitBearingAccesses(node.left, out)
unitBearingAccesses(node.right, out)
return out
}
if (ts.isCallExpression(node) && node.arguments.length >= 1) {
const callee = node.expression
const name = ts.isIdentifier(callee)
? callee.text
: ts.isPropertyAccessExpression(callee)
? callee.name.text
: ''
if (UNIT_PRESERVING_CALLS.has(name)) return unitBearingAccesses(node.arguments[0], out)
return out
}
if (ts.isPropertyAccessExpression(node)) {
const chain = accessChain(node)
if (chain) out.push(chain)
return out
}
return out
}
function isSekTwin(field) {
return /(?:_sek|sek)$/i.test(field)
}
/** Findings for one source file. `relPath` is only used to build the message. */
export function findSekLabelledFxAmountsInSource(relPath, text) {
if (!text.includes('formatCurrency(')) return []
const source = ts.createSourceFile(
relPath,
text,
ts.ScriptTarget.Latest,
true,
relPath.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS,
)
// Owners this file reads a currency off: `invoice.currency`, `tx?.currency`,
// `data.invoice.currency`. Matched as a full owner path, not just the root
// identifier, so knowing `invoice.currency` says nothing about `line.amount`.
const currencyOwners = new Set()
const calls = []
const collect = (node) => {
if (ts.isPropertyAccessExpression(node) && node.name.text === 'currency') {
const chain = accessChain(node)
if (chain) currencyOwners.add(chain.owner)
}
if (ts.isCallExpression(node) && node.arguments.length === 1) {
const callee = node.expression
const name = ts.isIdentifier(callee)
? callee.text
: ts.isPropertyAccessExpression(callee)
? callee.name.text
: ''
if (name === 'formatCurrency') calls.push(node)
}
ts.forEachChild(node, collect)
}
collect(source)
const findings = []
for (const call of calls) {
for (const { owner, field } of unitBearingAccesses(call.arguments[0])) {
if (SANCTIONED.has(`${relPath}#${owner}.${field}`)) continue
const foreignByName = NEVER_SEK_FIELDS.has(field)
if (!foreignByName) {
if (!currencyOwners.has(owner)) continue
if (ALWAYS_SEK_FIELDS.has(field) || isSekTwin(field)) continue
}
const line = source.getLineAndCharacterOfPosition(call.getStart(source)).line + 1
findings.push({
where: `${relPath}:${line}`,
expr: `${owner}.${field}`,
reason: foreignByName
? `${field} is the amount in the document's own currency, never SEK`
: `${relPath.split('/').pop()} reads ${owner}.currency, so ${owner}.${field} may not be SEK`,
})
}
}
return findings
}
/** Findings across `SCAN_DIRS` under `root`, sorted and de-duplicated. */
export function findSekLabelledFxAmounts(root) {
const files = SCAN_DIRS.flatMap((dir) => walk(path.join(root, dir)))
const findings = []
for (const file of files) {
const relPath = path.relative(root, file).split(path.sep).join('/')
findings.push(...findSekLabelledFxAmountsInSource(relPath, fs.readFileSync(file, 'utf8')))
}
const seen = new Set()
return findings
.filter((f) => {
const key = `${f.where}|${f.expr}`
if (seen.has(key)) return false
seen.add(key)
return true
})
.sort((a, b) => `${a.where}|${a.expr}`.localeCompare(`${b.where}|${b.expr}`))
}
// Standalone entry point: also what the unit test drives, so the CI path and
// the tested path are the same code.
if (process.argv[1] && fileURLToPath(import.meta.url) === path.resolve(process.argv[1])) {
const args = process.argv.slice(2)
const json = args.includes('--json')
const root = args.find((a) => !a.startsWith('--')) ?? path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..')
const findings = findSekLabelledFxAmounts(root)
if (json) {
console.log(JSON.stringify(findings, null, 2))
} else if (findings.length) {
for (const f of findings) console.error(`${f.where} formatCurrency(${f.expr}): ${f.reason}`)
} else {
console.log('✓ no SEK-labelled foreign amounts found.')
}
process.exit(findings.length ? 1 : 0)
}
File diff suppressed because it is too large Load Diff
+123
View File
@@ -0,0 +1,123 @@
#!/usr/bin/env node
/**
* Ratchet guard for ESLint errors (sibling of no-new-antipatterns.mjs).
*
* `npm run lint` was never wired into CI, so ~60 pre-existing errors
* accumulated across the repo. Fixing them all in one PR is churn; gating raw
* `eslint` would break every PR until then. So: ratchet. Error counts are
* tracked per rule in a committed baseline and can only go DOWN, never up:
* a PR introducing a NEW error of any rule fails CI, while legacy errors are
* burned down independently.
*
* Warnings stay advisory (only `--quiet` errors are counted).
*
* Known tradeoff: counts are per-rule repo-wide, not per-location: a PR that
* fixes one legacy error of a rule can absorb one NEW error of the same rule
* without tripping the gate. Acceptable for a burn-down ratchet; tighten to
* per-file fingerprints if that ever bites.
*
* Usage:
* node scripts/checks/no-new-lint-errors.mjs # check (CI)
* node scripts/checks/no-new-lint-errors.mjs --update # re-baseline after fixing legacy errors
*
* Exit code 1 if any rule's error count exceeds its baseline.
*/
import fs from 'node:fs'
import path from 'node:path'
import { spawnSync } from 'node:child_process'
import { fileURLToPath } from 'node:url'
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..')
const BASELINE_PATH = path.join(ROOT, 'scripts', 'checks', 'eslint-baseline.json')
function runEslint() {
const eslintBin = path.join(ROOT, 'node_modules', 'eslint', 'bin', 'eslint.js')
const result = spawnSync(
process.execPath,
[eslintBin, '.', '--quiet', '-f', 'json'],
{ cwd: ROOT, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 },
)
// ESLint exits 1 when errors exist: that's expected; only treat a missing/
// unparsable report as fatal.
if (!result.stdout) {
console.error('no-new-lint-errors: eslint produced no JSON output')
if (result.error) console.error(result.error)
console.error(result.stderr ?? '')
process.exit(2)
}
try {
return JSON.parse(result.stdout)
} catch {
console.error('no-new-lint-errors: failed to parse eslint JSON output')
process.exit(2)
}
}
function collectCounts(report) {
/** @type {Record<string, number>} */
const perRule = {}
/** @type {Record<string, string[]>} */
const locations = {}
for (const file of report) {
for (const msg of file.messages) {
if (msg.severity !== 2) continue
const rule = msg.ruleId ?? 'fatal'
perRule[rule] = (perRule[rule] ?? 0) + 1
const rel = path.relative(ROOT, file.filePath)
;(locations[rule] ??= []).push(`${rel}:${msg.line}:${msg.column}`)
}
}
return { perRule, locations }
}
const { perRule, locations } = collectCounts(runEslint())
const total = Object.values(perRule).reduce((a, b) => a + b, 0)
if (process.argv.includes('--update')) {
const sorted = Object.fromEntries(Object.entries(perRule).sort(([a], [b]) => a.localeCompare(b)))
fs.writeFileSync(
BASELINE_PATH,
JSON.stringify({ totalErrors: total, perRule: sorted }, null, 2) + '\n',
)
console.log(`no-new-lint-errors: baseline updated: ${total} error(s) across ${Object.keys(perRule).length} rule(s).`)
process.exit(0)
}
if (!fs.existsSync(BASELINE_PATH)) {
console.error(`no-new-lint-errors: baseline missing at ${path.relative(ROOT, BASELINE_PATH)}.`)
console.error('Run: node scripts/checks/no-new-lint-errors.mjs --update')
process.exit(2)
}
const baseline = JSON.parse(fs.readFileSync(BASELINE_PATH, 'utf8'))
const baselineRules = baseline.perRule ?? {}
const regressions = []
for (const [rule, count] of Object.entries(perRule)) {
const allowed = baselineRules[rule] ?? 0
if (count > allowed) regressions.push({ rule, count, allowed })
}
if (regressions.length > 0) {
console.error('no-new-lint-errors: FAILED: new ESLint errors beyond the baseline:\n')
for (const { rule, count, allowed } of regressions) {
console.error(` ${rule}: ${count} (baseline ${allowed})`)
for (const loc of (locations[rule] ?? []).slice(0, 10)) {
console.error(` ${loc}`)
}
}
console.error(`
Fix the new error(s): run \`npx eslint . --quiet\` locally to see them.
(If you fixed MORE legacy errors than you added and the rule still trips,
re-baseline with: node scripts/checks/no-new-lint-errors.mjs --update)
`)
process.exit(1)
}
const improved = total < (baseline.totalErrors ?? 0)
console.log(
`no-new-lint-errors: OK: ${total} error(s), baseline ${baseline.totalErrors}.` +
(improved
? ' Count went DOWN: ratchet it: node scripts/checks/no-new-lint-errors.mjs --update'
: ''),
)
+139
View File
@@ -0,0 +1,139 @@
#!/usr/bin/env node
/**
* Ratchet guard for TypeScript errors (sibling of no-new-lint-errors.mjs).
*
* ## Why this exists
*
* `npm test` does not typecheck. Vitest transpiles and throws the types away,
* so a type error passes the entire 18 000-test suite and only surfaces in
* `npm run build`, several minutes later. That happened twice on 2026-08-27
* alone: a widened union in the MCP server that a second declaration in
* lib/events/types.ts still contradicted, and an `interface` that would not
* assign into `Record<string, unknown>[]` because interfaces have no implicit
* index signature. Both were caught by the build. Neither was caught by 18 000
* green tests, which is exactly the wrong order to learn it in.
*
* `tsc --noEmit` finds both in about two minutes, and unlike the build it also
* covers `__tests__` files, which the Next.js build never compiles.
*
* ## Why the baseline is keyed by FILE, not by error code
*
* The lint ratchet counts per rule, and accepts the tradeoff that fixing one
* legacy error of a rule lets a new one in. For types that tradeoff is worse:
* the pre-existing errors are concentrated in a handful of old test files, and
* TS2322 ("not assignable") is common enough that a per-code budget would
* silently absorb a real regression somewhere else entirely. Keyed by file, a
* new error in a previously-clean file trips immediately, which is the case
* that actually matters.
*
* Usage:
* node scripts/checks/no-new-type-errors.mjs # check
* node scripts/checks/no-new-type-errors.mjs --update # re-baseline
*
* Exit code 1 if any file's error count exceeds its baseline.
*/
import fs from 'node:fs'
import path from 'node:path'
import { spawnSync } from 'node:child_process'
import { fileURLToPath } from 'node:url'
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..')
const BASELINE_PATH = path.join(ROOT, 'scripts', 'checks', 'typecheck-baseline.json')
/**
* This project's graph does not fit in Node's default heap: a bare
* `tsc --noEmit` dies with "Ineffective mark-compacts near heap limit" after
* about two minutes of work, which reads like a hang rather than a
* misconfiguration. The build sets the same flag for the same reason.
*/
const HEAP_MB = 8192
function runTsc() {
const tscBin = path.join(ROOT, 'node_modules', 'typescript', 'bin', 'tsc')
const result = spawnSync(process.execPath, [tscBin, '--noEmit', '--pretty', 'false'], {
cwd: ROOT,
encoding: 'utf8',
maxBuffer: 64 * 1024 * 1024,
env: { ...process.env, NODE_OPTIONS: `--max-old-space-size=${HEAP_MB}` },
})
const output = `${result.stdout ?? ''}${result.stderr ?? ''}`
if (/Ineffective mark-compacts|JavaScript heap out of memory/.test(output)) {
console.error(`no-new-type-errors: tsc ran out of memory at ${HEAP_MB} MB. Raise HEAP_MB.`)
process.exit(2)
}
// tsc exits non-zero when errors exist, which is the normal case here.
return output
}
/** `path/to/file.ts(12,34): error TS2322: ...` */
const ERROR_RE = /^(.+?)\((\d+),(\d+)\): error (TS\d+): (.*)$/
function collect(output) {
/** @type {Record<string, number>} */
const perFile = {}
/** @type {Record<string, string[]>} */
const locations = {}
for (const line of output.split('\n')) {
const match = ERROR_RE.exec(line.trim())
if (!match) continue
const [, file, lineNo, col, code, message] = match
const rel = path.relative(ROOT, path.resolve(ROOT, file)).split(path.sep).join('/')
perFile[rel] = (perFile[rel] ?? 0) + 1
;(locations[rel] ??= []).push(`${rel}:${lineNo}:${col} ${code} ${message}`)
}
return { perFile, locations }
}
const { perFile, locations } = collect(runTsc())
const total = Object.values(perFile).reduce((a, b) => a + b, 0)
if (process.argv.includes('--update')) {
const sorted = Object.fromEntries(Object.entries(perFile).sort(([a], [b]) => a.localeCompare(b)))
fs.writeFileSync(
BASELINE_PATH,
JSON.stringify({ totalErrors: total, perFile: sorted }, null, 2) + '\n',
)
console.log(
`no-new-type-errors: baseline updated: ${total} error(s) across ${Object.keys(perFile).length} file(s).`,
)
process.exit(0)
}
if (!fs.existsSync(BASELINE_PATH)) {
console.error(`no-new-type-errors: baseline missing at ${path.relative(ROOT, BASELINE_PATH)}.`)
console.error('Run: node scripts/checks/no-new-type-errors.mjs --update')
process.exit(2)
}
const baseline = JSON.parse(fs.readFileSync(BASELINE_PATH, 'utf8'))
const baselineFiles = baseline.perFile ?? {}
const regressions = []
for (const [file, count] of Object.entries(perFile)) {
const allowed = baselineFiles[file] ?? 0
if (count > allowed) regressions.push({ file, count, allowed })
}
if (regressions.length > 0) {
console.error('no-new-type-errors: FAILED: new TypeScript errors beyond the baseline:\n')
for (const { file, count, allowed } of regressions) {
console.error(` ${file}: ${count} (baseline ${allowed})`)
for (const loc of (locations[file] ?? []).slice(0, 10)) {
console.error(` ${loc}`)
}
}
console.error(`
Fix the new error(s): run \`NODE_OPTIONS=--max-old-space-size=${HEAP_MB} npx tsc --noEmit\` to see them all.
(If you fixed MORE legacy errors than you added and a file still trips,
re-baseline with: node scripts/checks/no-new-type-errors.mjs --update)
`)
process.exit(1)
}
const improved = total < (baseline.totalErrors ?? 0)
console.log(
`no-new-type-errors: OK: ${total} error(s), baseline ${baseline.totalErrors}.` +
(improved
? ' Count went DOWN: ratchet it: node scripts/checks/no-new-type-errors.mjs --update'
: ''),
)
+136
View File
@@ -0,0 +1,136 @@
#!/usr/bin/env node
/**
* Guard: reference data fetched outside lib/reference-data.
*
* Fiscal periods, company settings, the chart of accounts, cash accounts,
* dimensions, booking templates, customers, suppliers and articles are
* session-cached behind the hooks in lib/reference-data/hooks.ts (seeded
* from the dashboard layout, invalidated after writes). Before that layer
* existed the same lists were fetched raw from 47 / 27 / 14 / 8 / 12 / 5
* independent call sites, uncached, on every mount and every dialog open,
* which is what a customer described as "it takes time before all fields
* load when clicking around" (2026-08-26). This check keeps that number
* going down: an existing raw call site is grandfathered in the baseline,
* a NEW one fails CI.
*
* Two shapes are flagged:
* 1. A GET-shaped `fetch('/api/<reference path>')` anywhere under app/,
* components/, extensions/ or lib/ (a relative URL is client code by
* definition). Writes (`method: 'POST' | 'PUT' | ...`) are fine: they
* go through the API and then call invalidateReferenceData().
* 2. A browser-side `.from('<reference table>').select(` in a file that
* carries the 'use client' directive. Server code reading those tables
* is legitimate and is not scanned.
*
* Sanctioned (RAW_REFERENCE_SANCTIONED): the fetchers themselves, the
* pre-existing SWR settings hook, and the static BAS catalog loader (a
* different, module-cached data set).
*/
import fs from 'node:fs'
import path from 'node:path'
export const REFERENCE_API_PATHS = [
'bookkeeping/fiscal-periods',
'settings/booking-templates',
'settings',
'bookkeeping/accounts',
'cash-accounts',
'dimensions',
'customers',
'suppliers',
'articles',
]
export const REFERENCE_TABLES = [
'fiscal_periods',
'company_settings',
'chart_of_accounts',
'cash_accounts',
]
export const RAW_REFERENCE_SANCTIONED = new Set([
'lib/reference-data/fetchers.ts',
'components/settings/useSettings.ts',
'lib/bookkeeping/bas-catalog-client.ts',
])
const SCAN_DIRS = ['app/(dashboard)', 'components', 'extensions', 'lib']
const IGNORE_DIRS = new Set(['node_modules', '.next', '.git', 'dist', 'build', 'coverage', '__tests__'])
const escape = (s) => s.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')
// fetch(`/api/settings`), fetch('/api/settings?x=1'), fetch('/api/settings', { signal })
// The init object may nest one level ({ headers: { ... } }); its text is
// captured so a write method can be excluded. Trailing commas (prettier's
// multi-line call style) are tolerated before the closing paren. Every
// optional whitespace run is anchored by a literal (`,` or `)`) so the
// pattern has no ambiguous backtracking (CodeQL js/redos on the earlier
// `\s*,?\s*\)` shape).
const REFERENCE_URL = String.raw`[\x60'"]/api/(?:${REFERENCE_API_PATHS.map(escape).join('|')})(?:\?[^\x60'"]*)?[\x60'"]`
const INIT_OBJECT = String.raw`\{(?:[^{}]|\{[^{}]*\})*\}`
const API_FETCH_RE = new RegExp(
String.raw`fetch\(\s*${REFERENCE_URL}(?:\s*,\s*(${INIT_OBJECT}))?(?:\s*,)?\s*\)`,
'g',
)
const WRITE_METHOD_RE = /method\s*:\s*[\x60'"](?!GET\b)/i
const TABLE_SELECT_RE = new RegExp(
String.raw`\.from\(\s*['"](?:${REFERENCE_TABLES.map(escape).join('|')})['"]\s*\)\s*\.\s*select\(`,
'g',
)
// Leading whitespace and comments before the directive. A block comment body
// is `(?:[^*]|\*(?!\/))*`, which cannot cross a `*/`, so each iteration of the
// outer star has exactly one parse: the lazy `[\s\S]*?` form let an unclosed
// `/*` be re-split at every later `/*` (CodeQL js/redos).
// Single-character whitespace alternative (not \s+): a `+` inside the outer
// `*` is a nested quantifier on the same character (CodeQL js/redos).
const USE_CLIENT_RE = /^(?:\s|\/\/[^\n]*\n|\/\*(?:[^*]|\*(?!\/))*\*\/)*['"]use client['"]/
export function isClientSource(source) {
return USE_CLIENT_RE.test(source)
}
/**
* Findings for one file's source: `{ kind: 'api' | 'table', index }`.
* Exported for the unit test; the file-level scan below uses it.
*/
export function findRawReferenceFetchesInSource(source) {
const findings = []
for (const match of source.matchAll(API_FETCH_RE)) {
const init = match[1]
if (init && WRITE_METHOD_RE.test(init)) continue
findings.push({ kind: 'api', index: match.index ?? 0 })
}
if (isClientSource(source)) {
for (const match of source.matchAll(TABLE_SELECT_RE)) {
findings.push({ kind: 'table', index: match.index ?? 0 })
}
}
return findings
}
function walk(dir, out) {
if (!fs.existsSync(dir)) return
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
if (IGNORE_DIRS.has(entry.name)) continue
const full = path.join(dir, entry.name)
if (entry.isDirectory()) walk(full, out)
else if (/\.(?:ts|tsx)$/.test(entry.name) && !/\.test\.tsx?$/.test(entry.name)) out.push(full)
}
}
/** Sorted repo-relative paths of files with at least one raw reference fetch. */
export function findRawReferenceFetches(root) {
const files = []
for (const dir of SCAN_DIRS) walk(path.join(root, dir), files)
const offenders = []
for (const file of files) {
const rel = path.relative(root, file).split(path.sep).join('/')
if (rel.startsWith('app/api/') || RAW_REFERENCE_SANCTIONED.has(rel)) continue
const source = fs.readFileSync(file, 'utf8')
if (findRawReferenceFetchesInSource(source).length) offenders.push(rel)
}
return [...new Set(offenders)].sort()
}
+87
View File
@@ -0,0 +1,87 @@
{
"totalErrors": 533,
"perFile": {
"app/api/assets/__tests__/id.test.ts": 9,
"app/api/auth/email-hook/__tests__/route.test.ts": 1,
"app/api/auth/heartbeat/__tests__/route.test.ts": 1,
"app/api/bookkeeping/fiscal-periods/__tests__/route.test.ts": 23,
"app/api/bookkeeping/fiscal-periods/[id]/bokslutsdispositioner/__tests__/route.test.ts": 4,
"app/api/bookkeeping/journal-entries/__tests__/route.test.ts": 26,
"app/api/bookkeeping/journal-entries/[id]/chain/__tests__/route.test.ts": 2,
"app/api/bookkeeping/no-doc-required/batch/__tests__/route.test.ts": 6,
"app/api/bookkeeping/no-doc-required/bulk-missing/__tests__/route.test.ts": 9,
"app/api/bookkeeping/voucher-gaps/__tests__/route.test.ts": 9,
"app/api/customers/__tests__/viewer.test.ts": 2,
"app/api/documents/counts/__tests__/route.test.ts": 11,
"app/api/export/articles/__tests__/route.test.ts": 3,
"app/api/export/suppliers/__tests__/route.test.ts": 2,
"app/api/extensions/shopify/orders/cron/__tests__/route.test.ts": 2,
"app/api/extensions/skatteverket/agi/kvittenser/cron/__tests__/route.test.ts": 4,
"app/api/import/articles/__tests__/execute.test.ts": 23,
"app/api/import/bank-file/__tests__/route.test.ts": 1,
"app/api/import/bank-file/check-duplicates/__tests__/route.test.ts": 8,
"app/api/import/opening-balance/__tests__/correct.test.ts": 28,
"app/api/import/opening-balance/__tests__/execute.test.ts": 18,
"app/api/import/opening-balance/correct/__tests__/route.test.ts": 10,
"app/api/invoices/__tests__/route.test.ts": 24,
"app/api/invoices/[id]/peppol/__tests__/route.test.ts": 1,
"app/api/invoices/[id]/send-payment-confirmation/__tests__/route.test.ts": 8,
"app/api/invoices/bulk-book/__tests__/route.test.ts": 1,
"app/api/invoices/self-billed/__tests__/route.test.ts": 8,
"app/api/onboarding/state/__tests__/route.test.ts": 5,
"app/api/pending-operations/bulk-commit/__tests__/route.test.ts": 11,
"app/api/pending-operations/bulk-reject/__tests__/route.test.ts": 10,
"app/api/reports/audit-trail/__tests__/route.test.ts": 4,
"app/api/reports/bokslutsbilagor/__tests__/route.test.ts": 8,
"app/api/reports/full-archive/__tests__/route.test.ts": 11,
"app/api/rot-rut/__tests__/routes.test.ts": 13,
"app/api/rot-rut/beslut/__tests__/route.test.ts": 4,
"app/api/settings/api-keys/__tests__/route.test.ts": 6,
"app/api/settings/booking-templates/sync/cron/__tests__/route.test.ts": 1,
"app/api/settings/eu-trade-signal/__tests__/route.test.ts": 3,
"app/api/settings/ku-signal/__tests__/route.test.ts": 4,
"app/api/settings/rot-rut-signal/__tests__/route.test.ts": 4,
"app/api/supplier-invoices/__tests__/route.test.ts": 39,
"app/api/supplier-invoices/payment-batches/__tests__/route.test.ts": 12,
"app/api/tax-assessment-notices/__tests__/route.test.ts": 5,
"app/api/transactions/bulk-book/__tests__/route.test.ts": 16,
"app/api/v1/companies/[companyId]/customers/__tests__/route.test.ts": 1,
"app/api/webshop-orders/__tests__/bulk-book.test.ts": 1,
"app/api/webshop-orders/__tests__/list-and-settings.test.ts": 11,
"extensions/general/enable-banking/__tests__/session-expired.test.ts": 4,
"extensions/general/enable-banking/__tests__/supersede.test.ts": 1,
"extensions/general/invoice-inbox/__tests__/match-transaction.test.ts": 1,
"extensions/general/invoice-inbox/__tests__/retry-extraction.test.ts": 1,
"extensions/general/invoice-inbox/__tests__/sandbox-skip-extraction.test.ts": 1,
"extensions/general/invoice-inbox/__tests__/upload-page-count-gate.test.ts": 1,
"extensions/general/mcp-server/__tests__/account-tools.test.ts": 2,
"extensions/general/mcp-server/__tests__/connect-links.test.ts": 1,
"extensions/general/mcp-server/__tests__/payroll-staged-tools.test.ts": 21,
"extensions/general/mcp-server/__tests__/salary-tools.test.ts": 4,
"extensions/general/mcp-server/__tests__/set-voucher-note.test.ts": 1,
"extensions/general/mcp-server/__tests__/skills.test.ts": 2,
"extensions/general/skatteverket/__tests__/api-client.test.ts": 5,
"extensions/general/skatteverket/__tests__/skattekonto-mappers.test.ts": 1,
"lib/__tests__/logger.test.ts": 1,
"lib/api/v1/__tests__/with-api-v1.test.ts": 9,
"lib/auth/__tests__/require-write.test.ts": 15,
"lib/bokslut/__tests__/k3-framework-dispositions.test.ts": 2,
"lib/bokslut/__tests__/readiness-aggregator.test.ts": 6,
"lib/bookkeeping/__tests__/supplier-payment-lines.test.ts": 14,
"lib/branding/__tests__/public-brand.test.ts": 1,
"lib/email/__tests__/brand-mail-snapshots.test.ts": 1,
"lib/email/__tests__/brand-sender.test.ts": 1,
"lib/email/__tests__/reminder-templates.test.ts": 6,
"lib/import/__tests__/account-mapper.test.ts": 1,
"lib/import/__tests__/sie-import.test.ts": 1,
"lib/invoices/__tests__/pdf-template-amounts.test.ts": 1,
"lib/invoices/__tests__/peppol-bis-billing.test.ts": 1,
"lib/invoices/__tests__/reminder-processor.test.ts": 3,
"lib/invoices/__tests__/supplier-invoice-matching.test.ts": 1,
"lib/pending-operations/__tests__/commit-authorization-recoverable.test.ts": 1,
"lib/reports/__tests__/vat-declaration.test.ts": 5,
"lib/supabase/__tests__/middleware.test.ts": 1,
"tests/pg/categorize-calibration-samples.pg.test.ts": 2,
"tests/pg/match-batch-allocate.pg.test.ts": 1
}
}