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
+113
View File
@@ -0,0 +1,113 @@
import { describe, it, expect } from 'vitest'
import { fetchAllRows } from '../fetch-all'
const PAGE_SIZE = 1000
type Row = { id: string; value?: number }
/**
* Build a queryFn that serves predefined pages keyed by the `from` offset.
* Mirrors how `fetchAllRows` drives PostgREST `.range(from, to)`.
*/
function pagedQuery(pages: Record<number, Row[]>) {
return ({ from }: { from: number; to: number }) =>
Promise.resolve({ data: pages[from] ?? [], error: null })
}
function makeRows(start: number, count: number): Row[] {
return Array.from({ length: count }, (_, i) => ({ id: String(start + i), value: 1 }))
}
describe('fetchAllRows', () => {
it('returns a single page as-is and stops (page < PAGE_SIZE)', async () => {
const rows = makeRows(0, 3)
const out = await fetchAllRows<Row>(pagedQuery({ 0: rows }))
expect(out).toHaveLength(3)
expect(out.map((r) => r.id)).toEqual(['0', '1', '2'])
})
it('paginates across multiple pages and concatenates in order', async () => {
const page1 = makeRows(0, PAGE_SIZE) // full page → fetch continues
const page2 = makeRows(PAGE_SIZE, 5) // partial page → stop
const out = await fetchAllRows<Row>(pagedQuery({ 0: page1, [PAGE_SIZE]: page2 }))
expect(out).toHaveLength(PAGE_SIZE + 5)
expect(out[0].id).toBe('0')
expect(out[out.length - 1].id).toBe(String(PAGE_SIZE + 4))
})
it('throws when the query returns an error', async () => {
await expect(
fetchAllRows<Row>(() => Promise.resolve({ data: null, error: { message: 'boom' } })),
).rejects.toThrow('boom')
})
it('propagates the driver SQLSTATE so a timeout stays dispatchable', async () => {
// This is the highest-traffic error strip point in the codebase: every
// paginated read goes through it. It used to throw `new Error(msg)`, which
// dropped `code`, so a statement timeout (57014) reached the structured
// error layer anonymous and resolved to UNKNOWN_ERROR instead of the
// retryable TRANSIENT_ERROR. gnubok_query_journal failed this way 164
// times in 60 days at a p50 of 8 110 ms.
const failure = fetchAllRows<Row>(() =>
Promise.resolve({
data: null,
error: { message: 'canceling statement due to statement timeout', code: '57014' },
}),
)
await expect(failure).rejects.toMatchObject({ code: '57014' })
// And the message stays verbatim: query_journal's sanitizeDbError matches
// on the existing text.
await expect(failure).rejects.toThrow('canceling statement due to statement timeout')
})
it('does not render "undefined" when the driver sends no message', async () => {
await expect(
fetchAllRows<Row>(() => Promise.resolve({ data: null, error: { code: '08006' } as never })),
).rejects.toThrow(/^(?!.*undefined).*$/)
})
it('returns [] when the first page is empty', async () => {
const out = await fetchAllRows<Row>(pagedQuery({ 0: [] }))
expect(out).toEqual([])
})
// ── The regression-critical behaviour: an unstable cross-page order ──
// (a query missing a stable .order()) can return the same row on two
// pages. This is the mechanism behind the doubled-balance bugs (#790/#791).
it('dedupeBy drops a row duplicated across page boundaries (keeps first)', async () => {
const page1 = makeRows(0, PAGE_SIZE) // ids 0..999
// Unstable order: page 2 re-serves id "999" (already on page 1) plus a new id.
const page2: Row[] = [
{ id: '999', value: 1 },
{ id: '1000', value: 1 },
]
const out = await fetchAllRows<Row>(
pagedQuery({ 0: page1, [PAGE_SIZE]: page2 }),
{ dedupeBy: (r) => r.id },
)
// 1001 unique ids (0..1000), the duplicate "999" removed → no doubling.
expect(out).toHaveLength(PAGE_SIZE + 1)
const ids = out.map((r) => r.id)
expect(ids.filter((id) => id === '999')).toHaveLength(1)
expect(new Set(ids).size).toBe(out.length)
})
it('without dedupeBy, cross-page duplicates pass through (unsafe default)', async () => {
const page1 = makeRows(0, PAGE_SIZE)
const page2: Row[] = [{ id: '999', value: 1 }]
const out = await fetchAllRows<Row>(pagedQuery({ 0: page1, [PAGE_SIZE]: page2 }))
expect(out).toHaveLength(PAGE_SIZE + 1)
expect(out.map((r) => r.id).filter((id) => id === '999')).toHaveLength(2)
})
it('dedupeBy is a no-op for a single page (no cross-page duplicates possible)', async () => {
const rows: Row[] = [
{ id: 'a' },
{ id: 'b' },
{ id: 'a' }, // an intra-page repeat is left untouched: single page is trusted
]
const out = await fetchAllRows<Row>(pagedQuery({ 0: rows }), { dedupeBy: (r) => r.id })
expect(out).toHaveLength(3)
})
})
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,83 @@
import { describe, it, expect } from 'vitest'
import {
classifyProxyRequest,
createProxyTimings,
formatProxyServerTiming,
proxyRouteTemplate,
timed,
} from '../proxy-timing'
describe('classifyProxyRequest', () => {
it('treats /api paths as api regardless of headers', () => {
const headers = new Headers({ 'next-router-prefetch': '1', rsc: '1' })
expect(classifyProxyRequest('/api/settings', headers)).toBe('api')
})
it('recognises app-router prefetch and RSC requests by header', () => {
expect(
classifyProxyRequest('/invoices', new Headers({ 'Next-Router-Prefetch': '1', RSC: '1' })),
).toBe('prefetch')
expect(classifyProxyRequest('/invoices', new Headers({ RSC: '1' }))).toBe('rsc')
})
it('falls back to page for a plain document request', () => {
expect(classifyProxyRequest('/invoices', new Headers())).toBe('page')
})
})
describe('proxyRouteTemplate', () => {
it('replaces UUID and numeric segments with placeholders', () => {
expect(proxyRouteTemplate('/invoices/6f1c2a3e-1234-4bcd-9abc-0123456789ab/edit')).toBe(
'/invoices/:id/edit',
)
expect(proxyRouteTemplate('/salary/runs/42')).toBe('/salary/runs/:n')
})
it('collapses token-carrying prefixes so secrets never reach the log', () => {
expect(proxyRouteTemplate('/invite/9f8e7d6c5b4a3928171605f4e3d2c1b0')).toBe('/invite/*')
expect(proxyRouteTemplate('/payslip/abc')).toBe('/payslip/*')
expect(proxyRouteTemplate('/auth/callback')).toBe('/auth/*')
expect(proxyRouteTemplate('/auth')).toBe('/auth/*')
})
it('masks long opaque segments outside the known prefixes', () => {
expect(proxyRouteTemplate('/e/sector/aVeryLongOpaqueSlugThatLooksLikeAToken')).toBe(
'/e/sector/:token',
)
})
it('keeps ordinary routes and the root untouched', () => {
expect(proxyRouteTemplate('/settings/company')).toBe('/settings/company')
expect(proxyRouteTemplate('/')).toBe('/')
})
})
describe('formatProxyServerTiming', () => {
it('emits one mw-* metric per phase plus the total', () => {
const timing = { authMs: 12, sessionMs: 3, companyMs: 40, mfaMs: 0 }
expect(formatProxyServerTiming(timing, 61)).toBe(
'mw-auth;dur=12, mw-session;dur=3, mw-company;dur=40, mw-mfa;dur=0, mw-total;dur=61',
)
})
})
describe('timed', () => {
it('returns the wrapped value and accumulates elapsed time on the key', async () => {
const timing = createProxyTimings()
const value = await timed(timing, 'sessionMs', async () => 'ok')
expect(value).toBe('ok')
await timed(timing, 'sessionMs', async () => undefined)
expect(timing.sessionMs).toBeGreaterThanOrEqual(0)
expect(timing.authMs).toBe(0)
})
it('still records time when the wrapped call throws', async () => {
const timing = createProxyTimings()
await expect(
timed(timing, 'authMs', async () => {
throw new Error('boom')
}),
).rejects.toThrow('boom')
expect(timing.authMs).toBeGreaterThanOrEqual(0)
})
})
+34
View File
@@ -0,0 +1,34 @@
import { describe, expect, it } from 'vitest'
import { insertDraftJournalEntry, seedCompany } from '@/tests/pg/fixtures'
import { withUserContext } from '@/tests/pg/setup'
describe('rls.pg: tenant isolation on journal_entries', () => {
it('returns only the authenticated user\'s company rows', async () => {
const a = await seedCompany()
const b = await seedCompany()
// One entry in each tenant.
const entryA = await insertDraftJournalEntry({
userId: a.userId,
companyId: a.companyId,
fiscalPeriodId: a.fiscalPeriodId,
})
await insertDraftJournalEntry({
userId: b.userId,
companyId: b.companyId,
fiscalPeriodId: b.fiscalPeriodId,
})
// user A should see exactly entryA and nothing from tenant B.
const rows = await withUserContext(a.userId, async (client) => {
const res = await client.query<{ id: string; company_id: string }>(
`SELECT id, company_id FROM public.journal_entries`,
)
return res.rows
})
expect(rows).toHaveLength(1)
expect(rows[0]!.id).toBe(entryA)
expect(rows[0]!.company_id).toBe(a.companyId)
})
})
+47
View File
@@ -0,0 +1,47 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const { createServerClientMock, cookiesMock } = vi.hoisted(() => ({
createServerClientMock: vi.fn(),
cookiesMock: vi.fn(),
}))
vi.mock('@supabase/ssr', () => ({
createServerClient: createServerClientMock,
}))
vi.mock('next/headers', () => ({
cookies: cookiesMock,
}))
describe('createServiceClient', () => {
beforeEach(() => {
vi.resetModules()
vi.clearAllMocks()
vi.stubEnv('NEXT_PUBLIC_SUPABASE_URL', 'https://project.supabase.co')
vi.stubEnv('NEXT_PUBLIC_SUPABASE_ANON_KEY', 'anon-key')
vi.stubEnv('SUPABASE_SERVICE_ROLE_KEY', 'service-role-key')
})
afterEach(() => {
vi.unstubAllEnvs()
})
it('uses the service-role key with a cookie-free client', async () => {
const serviceClient = { kind: 'service' }
createServerClientMock.mockReturnValue(serviceClient)
const { createServiceClient } = await import('../server')
expect(createServiceClient()).toBe(serviceClient)
expect(createServerClientMock).toHaveBeenCalledWith(
'https://project.supabase.co',
'service-role-key',
expect.objectContaining({ cookies: expect.any(Object) }),
)
const options = createServerClientMock.mock.calls[0][2] as {
cookies: { getAll: () => unknown[]; setAll: () => void }
}
expect(options.cookies.getAll()).toEqual([])
expect(() => options.cookies.setAll()).not.toThrow()
expect(cookiesMock).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,84 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
const createClientMock = vi.fn(() => ({ from: vi.fn() }))
vi.mock('@supabase/supabase-js', () => ({
createClient: (...args: unknown[]) => createClientMock(...(args as [])),
}))
import { createServiceRoleClient, SERVER_AUTH_OPTIONS } from '../service-client'
/** The auth block supabase-js was actually constructed with. */
function authArg() {
const [, , options] = createClientMock.mock.calls[0] as unknown as [
string,
string,
{ auth?: Record<string, unknown> } | undefined,
]
return options?.auth
}
describe('createServiceRoleClient', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('disables the auth refresh ticker', () => {
// The whole point: autoRefreshToken defaults to true, and off-browser
// auth-js starts a 30 s setInterval that is never cleared. unref() keeps
// the process exitable but leaves the timer a GC root, so every client
// retains its request scope until the heap is gone.
createServiceRoleClient('https://example.supabase.co', 'service-key')
expect(authArg()).toMatchObject({ autoRefreshToken: false, persistSession: false })
})
it('passes url and key through unchanged', () => {
createServiceRoleClient('https://example.supabase.co', 'service-key')
const [url, key] = createClientMock.mock.calls[0] as unknown as [string, string]
expect(url).toBe('https://example.supabase.co')
expect(key).toBe('service-key')
})
it('keeps caller options that are not auth', () => {
createServiceRoleClient('https://example.supabase.co', 'service-key', {
db: { schema: 'public' },
global: { headers: { 'x-test': '1' } },
})
const [, , options] = createClientMock.mock.calls[0] as unknown as [
string,
string,
{ db?: unknown; global?: unknown },
]
expect(options.db).toEqual({ schema: 'public' })
expect(options.global).toEqual({ headers: { 'x-test': '1' } })
})
it('refuses to let a caller re-enable the ticker', () => {
// SERVER_AUTH_OPTIONS is spread last precisely so this cannot happen: a
// caller copying an old snippet must not be able to reintroduce the leak.
createServiceRoleClient('https://example.supabase.co', 'service-key', {
auth: { autoRefreshToken: true, persistSession: true },
})
expect(authArg()).toMatchObject({ autoRefreshToken: false, persistSession: false })
})
it('keeps unrelated auth options the caller set', () => {
createServiceRoleClient('https://example.supabase.co', 'service-key', {
auth: { storageKey: 'custom-key' },
})
expect(authArg()).toMatchObject({
storageKey: 'custom-key',
autoRefreshToken: false,
persistSession: false,
})
})
it('exports the options it applies', () => {
expect(SERVER_AUTH_OPTIONS).toEqual({ persistSession: false, autoRefreshToken: false })
})
})
+18
View File
@@ -0,0 +1,18 @@
import { createBrowserClient } from '@supabase/ssr'
// During Docker builds, NEXT_PUBLIC_* vars are placeholder sentinels
// (e.g. __NEXT_PUBLIC_SUPABASE_URL__) that get replaced at runtime by
// docker-entrypoint.sh. Provide a dummy URL so the client constructor
// doesn't throw during Next.js static page generation.
const url = process.env.NEXT_PUBLIC_SUPABASE_URL ?? ''
const key = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ?? ''
const isBuildPlaceholder = !url || url.startsWith('__')
// Cookie encoding must match lib/supabase/server.ts (default
// `user-and-tokens`); see the note there before switching to `tokens-only`.
export function createClient() {
return createBrowserClient(
isBuildPlaceholder ? 'https://placeholder.supabase.co' : url,
isBuildPlaceholder ? 'placeholder' : key
)
}
+117
View File
@@ -0,0 +1,117 @@
import { createLogger } from '@/lib/logger'
import { dbError } from '@/lib/errors/db-error'
const log = createLogger('fetch-all')
const PAGE_SIZE = 1000
export interface FetchAllRowsOptions<T> {
/**
* Stable de-duplication key. When supplied AND more than one page was
* fetched, rows are de-duplicated by this key after all pages are collected,
* and a warn is logged if any duplicates were dropped.
*
* This is a safety net, NOT the fix: PostgREST `.range()` paging is only
* correct when the underlying query has a stable TOTAL order (see the
* ordering invariant below). If a duplicate is ever observed here it means a
* caller's query is missing that `.order()`: the warn surfaces the
* regression in logs instead of letting it silently double financial totals.
* Note this only catches *duplicates*; *skipped* rows can only be prevented
* by ordering on a unique column at the call site.
*/
dedupeBy?: (row: T) => string | number
}
/**
* Fetches all rows from a Supabase query by paginating through results.
* Overcomes PostgREST's default 1000-row limit.
*
* **Ordering invariant:** any query that can return more than `PAGE_SIZE` rows
* MUST `.order()` on a unique column (e.g. the table's `id` PK). Postgres
* returns rows in an undefined order that can differ between the two `.range()`
* requests, so without a stable total order, rows on a page boundary are
* silently DUPLICATED and/or SKIPPED across pages. For aggregating reports
* (general ledger, trial balance, grundbok) that means doubled or missing
* balances. Order is purely for paging stability: callers that need a
* different display order should re-sort after fetching.
*
* The callback receives `{ from, to }` range values: append `.range(from, to)`
* to your query builder, AFTER a stable `.order()`:
*
* ```ts
* const accounts = await fetchAllRows(({ from, to }) =>
* supabase
* .from('chart_of_accounts')
* .select('account_number, account_name')
* .eq('company_id', companyId)
* .order('account_number', { ascending: true }) // stable total order
* .range(from, to)
* )
* ```
*
* Pass `{ dedupeBy }` as defense-in-depth for queries where a missing/regressed
* order would corrupt money:
*
* ```ts
* const lines = await fetchAllRows(
* ({ from, to }) => q.order('id').range(from, to),
* { dedupeBy: (r) => r.id },
* )
* ```
*/
export async function fetchAllRows<T>(
queryFn: (range: { from: number; to: number }) => PromiseLike<{
data: T[] | null
error: { message: string } | null
}>,
options?: FetchAllRowsOptions<T>
): Promise<T[]> {
const allRows: T[] = []
let from = 0
let pages = 0
while (true) {
const { data, error } = await queryFn({ from, to: from + PAGE_SIZE - 1 })
// dbError, not `new Error(error.message)`: the bare form discarded the
// driver's SQLSTATE, and `isTransientFailure()` checks that code FIRST.
// A statement timeout (57014) therefore arrived as an anonymous Error and
// resolved to UNKNOWN_ERROR ("Något gick fel. Försök igen.") instead of
// the retryable TRANSIENT_ERROR. This is the single highest-traffic strip
// point in the codebase: every paginated read goes through it, including
// gnubok_query_journal, which failed 164 times in 60 days at a p50 of
// 8 110 ms while every other failing tool sat between 1 and 315 ms.
//
// The message is kept VERBATIM (context: null). Callers such as
// query_journal's sanitizeDbError already match on it, and this change is
// meant to add the code, not to reword anything.
if (error) throw dbError(error, null)
if (!data || data.length === 0) break
allRows.push(...data)
pages += 1
if (data.length < PAGE_SIZE) break
from += PAGE_SIZE
}
// Duplicates are only possible across page boundaries, so single-page results
// never need the dedup pass.
if (options?.dedupeBy && pages > 1) {
const seen = new Set<string | number>()
const deduped: T[] = []
for (const row of allRows) {
const key = options.dedupeBy(row)
if (seen.has(key)) continue
seen.add(key)
deduped.push(row)
}
const dropped = allRows.length - deduped.length
if (dropped > 0) {
log.warn(
'fetchAllRows dropped duplicate rows across pages: a paginated query is missing a stable .order() on a unique column',
{ dropped, total: allRows.length, pages }
)
return deduped
}
}
return allRows
}
File diff suppressed because it is too large Load Diff
+115
View File
@@ -0,0 +1,115 @@
import { UUID_RE } from '@/lib/invariants/uuid'
/**
* Per-request timing for the auth proxy (lib/supabase/middleware.ts).
*
* The proxy runs in front of every page, RSC, prefetch and /api request and
* makes several sequential network calls (Supabase Auth, the active-company
* RPC, MFA factor lookups). Nothing measured that cost until now, while the
* route wrapper (lib/api/with-route-context.ts) has logged authMs/companyMs/
* handlerMs per API call for months. These helpers give the proxy the same
* Server-Timing header and one structured "proxy completed" log line per
* request so the fixed per-request cost can be read off Vercel logs and the
* browser Timing tab instead of guessed.
*
* Pure functions only: the middleware test suite mocks Supabase heavily, so
* classification and formatting live here where they can be unit-tested
* without that harness.
*/
export type ProxyRequestKind = 'api' | 'prefetch' | 'rsc' | 'page'
export interface ProxyTimings {
/** supabase.auth.getUser(): a network round trip to Supabase Auth. */
authMs: number
/** Session-timeout state: getClaims + HMAC verify + auto_logout read. */
sessionMs: number
/** resolve_active_company RPC (or the query fallback) incl. write-back. */
companyMs: number
/** MFA assurance level + listFactors (the latter is a network call). */
mfaMs: number
}
export type ProxyTimingKey = keyof ProxyTimings
/**
* Header used on /api responses. withRouteContext owns `Server-Timing` on
* API routes and only sets it when absent, so the proxy's numbers travel on
* a separate header there; on page/RSC responses nothing else sets
* Server-Timing and the proxy uses the standard header directly.
*/
export const PROXY_TIMING_HEADER = 'X-Proxy-Timing'
export function createProxyTimings(): ProxyTimings {
return { authMs: 0, sessionMs: 0, companyMs: 0, mfaMs: 0 }
}
/** Run `fn` and add its wall time to `timing[key]` (accumulates on repeats). */
export async function timed<T>(
timing: ProxyTimings,
key: ProxyTimingKey,
fn: () => Promise<T>,
): Promise<T> {
const start = Date.now()
try {
return await fn()
} finally {
timing[key] += Date.now() - start
}
}
/**
* Which kind of request the proxy is fronting. Prefetch and RSC requests
* are recognised by the headers the Next.js app router sends
* (`Next-Router-Prefetch: 1`, `RSC: 1`); header names are case-insensitive
* on the Fetch `Headers` interface, so lower-case lookups are fine.
*/
export function classifyProxyRequest(
pathname: string,
headers: Headers,
): ProxyRequestKind {
if (pathname.startsWith('/api')) return 'api'
if (headers.get('next-router-prefetch') === '1') return 'prefetch'
if (headers.get('rsc') === '1') return 'rsc'
return 'page'
}
const NUMERIC_RE = /^\d+$/
/** Prefixes whose tail is a secret (invite tokens, payslip links, PKCE). */
const TOKEN_PREFIXES = ['/invite', '/payslip', '/auth']
/**
* Collapse a concrete pathname to a loggable route template: UUIDs become
* `:id`, numbers `:n`, long opaque segments `:token`, and paths under the
* token-carrying prefixes are cut to the prefix so a secret never lands in
* a log line.
*/
export function proxyRouteTemplate(pathname: string): string {
for (const prefix of TOKEN_PREFIXES) {
if (pathname === prefix || pathname.startsWith(`${prefix}/`)) {
return `${prefix}/*`
}
}
const segments = pathname.split('/').map((segment) => {
if (segment === '') return segment
if (UUID_RE.test(segment)) return ':id'
if (NUMERIC_RE.test(segment)) return ':n'
if (segment.length >= 24) return ':token'
return segment
})
return segments.join('/') || '/'
}
/** `Server-Timing` value: one `mw-*` metric per phase plus the total. */
export function formatProxyServerTiming(
timing: ProxyTimings,
totalMs: number,
): string {
return [
`mw-auth;dur=${timing.authMs}`,
`mw-session;dur=${timing.sessionMs}`,
`mw-company;dur=${timing.companyMs}`,
`mw-mfa;dur=${timing.mfaMs}`,
`mw-total;dur=${totalMs}`,
].join(', ')
}
+70
View File
@@ -0,0 +1,70 @@
import { createServerClient } from '@supabase/ssr'
import { cookies } from 'next/headers'
// During Docker builds, NEXT_PUBLIC_* vars are placeholder sentinels
// replaced at runtime by docker-entrypoint.sh.
const url = process.env.NEXT_PUBLIC_SUPABASE_URL!
const key = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
const isBuildPlaceholder = url?.startsWith('__')
const safeUrl = isBuildPlaceholder ? 'https://placeholder.supabase.co' : url
const safeKey = isBuildPlaceholder ? 'placeholder' : key
/**
* Cookie-session client for server components, server actions and routes.
*
* Cookie encoding stays the default `user-and-tokens` on purpose.
* @supabase/ssr 0.12 offers an experimental `cookies.encode: 'tokens-only'`
* that keeps the user object out of the cookie, but auth-js then substitutes a
* THROWING proxy for `session.user` wherever no user store holds it: every
* fresh server request (app/api/mcp-oauth/authorize/route.ts calls
* `mfa.getAuthenticatorAssuranceLevel()`, which reads `session.user.factors`)
* and, in the browser, every `getSession().user` read after a session minted
* by the server-side PKCE callback (reset-password, SendInvoiceDialog) until
* the next token refresh. The trust problem is solved at the consumers
* instead: lib/supabase/middleware.ts and lib/auth/require-auth.ts never read
* MFA state off the cookie's user object (factors come from getUser() or
* listFactors(), the level from signature-verified claims). Switch the
* encoding only together with those call sites, and identically here, in
* client.ts and in middleware.ts: @supabase/ssr requires the two sides to
* match.
*/
export async function createClient() {
const cookieStore = await cookies()
return createServerClient(
safeUrl,
safeKey,
{
cookies: {
getAll() {
return cookieStore.getAll()
},
setAll(cookiesToSet) {
try {
cookiesToSet.forEach(({ name, value, options }) =>
cookieStore.set(name, value, options)
)
} catch {
// The `setAll` method was called from a Server Component.
// This can be ignored if you have middleware refreshing
// user sessions.
}
},
},
}
)
}
export function createServiceClient() {
// Stateless service-role client: no cookies.
// Passing user session cookies causes @supabase/ssr to send the
// user's JWT as the Authorization header, which overrides the
// service role key and re-enables RLS. A cookie-less client
// ensures the service role key is used for authorization,
// properly bypassing RLS on every query.
return createServerClient(
safeUrl,
process.env.SUPABASE_SERVICE_ROLE_KEY!,
{ cookies: { getAll: () => [], setAll: () => {} } }
)
}
+63
View File
@@ -0,0 +1,63 @@
import { createClient, type SupabaseClient, type SupabaseClientOptions } from '@supabase/supabase-js'
/**
* Auth options every server-side Supabase client MUST use.
*
* `autoRefreshToken` defaults to TRUE in supabase-js, and in a non-browser
* environment @supabase/auth-js starts the refresh ticker unconditionally:
*
* // in non-browser environments the refresh token ticker runs always
* this.startAutoRefresh()
*
* That is a `setInterval` firing every 30 s, stored on the client as
* `autoRefreshTicker`. It calls `.unref()`, so the process can still exit and
* nothing looks wrong in tests or on Vercel, where the process is short-lived
* and torn down before the tickers accumulate. But `unref()` does NOT make a
* timer collectable: it stays registered in the event loop's timer list and
* remains a GC root for its callback, which closes over the GoTrueClient, the
* SupabaseClient, and everything the surrounding request scope captured.
*
* A long-running self-hosted process therefore leaks one timer plus one entire
* request graph (socket, IncomingMessage, ServerResponse, headers, cookies,
* route context: roughly 100 kB) per client constructed. Observed in the wild
* on 2026-08-13: a self-hosted instance died of "JavaScript heap out of memory"
* after 42 h, the last 24 of them completely idle. A heap snapshot showed 445
* retained request graphs and ~1050 Timeouts in the 30 000 ms bucket, retained
* via `autoRefreshTicker`. The rate matched the traffic exactly: the Docker
* healthcheck polls /api/health every 30 s (2 clients/min) and the webhook
* dispatch cron runs every minute (1 client/min), so 3/min x 148 min = 444.
*
* `persistSession` is disabled for the same reason it always is on the server:
* there is no browser storage to persist into, and a service-role client has no
* user session to keep.
*/
export const SERVER_AUTH_OPTIONS = {
persistSession: false,
autoRefreshToken: false,
} as const
/**
* Construct a server-side Supabase client that cannot leak a refresh ticker.
*
* Use this instead of importing `createClient` from '@supabase/supabase-js'
* directly in any code that runs on the server (API routes, crons, extension
* handlers, service-role helpers). `scripts/checks/no-new-antipatterns.mjs`
* enforces it.
*
* The auth options are spread LAST, so a caller passing its own `auth` block
* cannot accidentally re-enable the ticker.
*
* Browser clients are a different case and must keep the ticker: a signed-in
* tab genuinely needs its access token refreshed. Those go through
* `lib/supabase/client.ts`, which is unaffected.
*/
export function createServiceRoleClient(
url: string,
key: string,
options?: SupabaseClientOptions<'public'>,
): SupabaseClient {
return createClient(url, key, {
...options,
auth: { ...options?.auth, ...SERVER_AUTH_OPTIONS },
})
}