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
+69
View File
@@ -0,0 +1,69 @@
# Request latency measurement (auth proxy + route wrapper)
Why this exists: a customer reported that "it takes time before all fields load when clicking around" (2026-08-26). The API handlers themselves are fast (p50 38 ms); the cost is the number of sequential calls a page makes and the fixed per-request tax in front of each one (auth proxy + route wrapper). This page is the protocol for measuring that tax before and after every change in the responsiveness plan, so no PR claims a win without a number.
## What is instrumented
| Surface | Where | Header | Log line |
|---|---|---|---|
| Auth proxy (every page, RSC, prefetch, `/api` request) | `lib/supabase/middleware.ts` via `lib/supabase/proxy-timing.ts` | `Server-Timing: mw-auth, mw-session, mw-company, mw-mfa, mw-total` on page/RSC/prefetch responses; `X-Proxy-Timing` (same value) on `/api` responses | `proxy completed` with `kind` (`page`, `rsc`, `prefetch`, `api`), `route` (ids and tokens collapsed), `status`, `authMs`, `sessionMs`, `companyMs`, `mfaMs`, `totalMs` |
| Route wrapper (`withRouteContext`, 367 of 529 routes) | `lib/api/with-route-context.ts` | `Server-Timing: auth, company, handler` | `op completed` with `operation`, `status`, `durationMs`, `authMs`, `companyMs`, `handlerMs` |
| Browser | `@vercel/speed-insights` mounted in `app/layout.tsx` | n/a | Vercel dashboard > Speed Insights > Routes (p75 TTFB, FCP, LCP, INP, CLS per route) |
Phase meanings for the proxy: `authMs` = `supabase.auth.getUser()` (a network call to Supabase Auth); `sessionMs` = session-timeout cookie state (`getClaims`, HMAC verify, `auto_logout` read when re-minting); `companyMs` = `resolve_active_company` RPC including the write-back on fallback; `mfaMs` = assurance-level check plus `listFactors()` (a second network call) on the enforced-MFA path.
## Reading the numbers
Percentiles per route from production logs (the `vercel` CLI is linked to the project; `--limit` defaults to 100, raise it):
```bash
# route wrapper, grouped by operation
vercel logs --environment production --since 24h --limit 1000 --json --query "op completed" \
| npx tsx scripts/perf/log-percentiles.ts --field durationMs,authMs,companyMs,handlerMs --group operation
# auth proxy, grouped by request kind and route
vercel logs --environment production --since 24h --limit 1000 --json --query "proxy completed" \
| npx tsx scripts/perf/log-percentiles.ts --field totalMs,authMs,sessionMs,companyMs,mfaMs --group kind,route
# auth proxy, one row per kind (the headline fixed cost)
vercel logs --environment production --since 24h --limit 1000 --json --query "proxy completed" \
| npx tsx scripts/perf/log-percentiles.ts --field totalMs,authMs,companyMs,mfaMs --group kind
```
If `--limit` above 100 is not honoured by the installed CLI, loop `--since`/`--until` windows and concatenate before piping. The Vercel MCP `get_runtime_logs` tool (`group_by: route`) gives request counts per route, not percentiles; use it for prefetch volume (`kind=prefetch` per page load).
In the browser: DevTools > Network, pick a document or `_rsc` request, Timing tab, the `mw-*` metrics show the proxy phases; `/api` responses show `auth`/`company`/`handler` from the route wrapper and the proxy numbers in the `X-Proxy-Timing` response header.
Request count per interaction (the number that maps to "fields load late"), in the console after each action on a production build (`next build && next start`):
```js
performance.getEntriesByType('resource')
.filter((r) => /\/api\/|\/rest\/v1\//.test(r.name))
.map((r) => `${Math.round(r.startTime)} ${Math.round(r.duration)}ms ${r.name}`)
```
Interactions to record every time: `/transactions` soft navigation; open Bokför on a row; `/bookkeeping` then Nytt verifikat; `/invoices` then Ny faktura; `/reports`; `/supplier-invoices/new`; a list row to its detail page on customers and invoices. Note the request count and how many dependent rounds (start times that wait on an earlier response).
## Targets (p75 unless stated)
| Metric | Target | Why |
|---|---|---|
| Proxy `page`/`rsc` totalMs | p50 < 40 ms, p90 < 100 ms | Two parallel DB waves at most, no auth network call |
| Proxy `api` totalMs | p50 < 5 ms | Local JWT verification only |
| Route wrapper auth + company | p50 < 45 ms (read), same for write | One company resolution per call, never two |
| TTFB (hard load) | < 400 ms | Layout on two DB waves |
| LCP | < 1.5 s | |
| INP | < 200 ms | The metric "clicking around" maps to |
| Reference-data requests per form open | 0 blocking | Seeded and cached client-side |
## Protocol per PR
1. Before merging: record the current numbers for the interactions above on a production build, and the last 24 h of `proxy completed` / `op completed` percentiles, in the PR description.
2. 24 h after the production deploy: re-run the same three commands and the same interactions; append one row per PR to the table below.
3. A PR that claims a latency win without a before/after row is not done.
## Baseline and results
| Date | Change | Proxy page p50/p90 | Proxy api p50/p90 | Route auth+company p50 | Notes |
|---|---|---|---|---|---|
| 2026-08-26 | Route wrapper only (proxy unmeasured) | n/a | n/a | 44 ms (auth 3, company 41) | 100-call sample; handler p50 38 ms, total p50 96 ms, p90 274 ms |
+139
View File
@@ -0,0 +1,139 @@
#!/usr/bin/env node
/**
* Static import closure of every 'use client' module.
*
* Answers "which client components pull module X into the browser bundle,
* and through which path?" without running `next build`. Walks static
* `import ... from` / `export ... from` edges (NOT dynamic `import()`, which
* splits a chunk, and NOT `import type`, which is erased), resolving `@/`
* and relative specifiers to .ts/.tsx/.js/.mjs files or directory indexes.
* Bare specifiers (packages, Node builtins) are recorded as leaves.
*
* node scripts/perf/client-import-closure.mjs lib/bookkeeping/bas-data/index.ts
* node scripts/perf/client-import-closure.mjs crypto node:crypto buffer vm
*
* Prints, per target, the client files whose closure reaches it and the
* shortest import path for each. Used by the responsiveness plan (B7) and
* by the client-node-builtin guard in scripts/checks.
*/
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..')
const SCAN_DIRS = ['app', 'components', 'contexts', 'extensions', 'lib', 'i18n']
const IGNORE_DIRS = new Set(['node_modules', '.next', '.git', 'dist', 'build', 'coverage', '__tests__'])
const EXTS = ['.ts', '.tsx', '.js', '.mjs', '.jsx']
// Block comment bodies are `(?:[^*]|\*(?!\/))*` so an unclosed `/*` cannot be
// re-split at every later `/*` (CodeQL js/redos on the lazy form).
// Single-character whitespace alternative (not \s+): a `+` inside the outer
// `*` is a nested quantifier on the same character, which CodeQL js/redos
// flags as exponential on long runs of spaces.
const USE_CLIENT_RE = /^(?:\s|\/\/[^\n]*\n|\/\*(?:[^*]|\*(?!\/))*\*\/)*['"]use client['"]/
// Static edges only. `import type {...} from` and `export type {...} from`
// are skipped; `import x, { type Y } from` still counts (x is a value).
// One quantifier per span (a greedy `[^'"]*` up to the specifier's opening
// quote, which it cannot cross) so a run of whitespace has a single parse:
// the earlier `\s+ ... [^'"]*? ... \s` shape backtracked exponentially
// (CodeQL js/redos).
const EDGE_RE = /^[ \t]*(?:import|export) (?!type\b)[^'"]*from[ \t]*['"]([^'"]+)['"]/gm
const SIDE_EFFECT_IMPORT_RE = /^\s*import\s+['"]([^'"]+)['"]/gm
export function walkFiles(root = ROOT) {
const out = []
const visit = (dir) => {
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()) visit(full)
else if (/\.(?:ts|tsx|js|mjs|jsx)$/.test(entry.name) && !/\.(?:test|pg\.test)\.tsx?$/.test(entry.name)) out.push(full)
}
}
for (const d of SCAN_DIRS) visit(path.join(root, d))
return out
}
export function resolveSpecifier(spec, fromFile, root = ROOT) {
let base
if (spec.startsWith('@/')) base = path.join(root, spec.slice(2))
else if (spec.startsWith('.')) base = path.resolve(path.dirname(fromFile), spec)
else return { bare: spec }
const candidates = [base, ...EXTS.map((e) => base + e), ...EXTS.map((e) => path.join(base, 'index' + e))]
for (const c of candidates) {
if (fs.existsSync(c) && fs.statSync(c).isFile()) return { file: c }
}
return { missing: spec }
}
export function importsOf(source) {
const specs = new Set()
for (const m of source.matchAll(EDGE_RE)) specs.add(m[1])
for (const m of source.matchAll(SIDE_EFFECT_IMPORT_RE)) specs.add(m[1])
return [...specs]
}
/** Build the graph once: file -> { edges: [file|bare], client: boolean }. */
export function buildGraph(root = ROOT) {
const graph = new Map()
for (const file of walkFiles(root)) {
const source = fs.readFileSync(file, 'utf8')
const edges = []
for (const spec of importsOf(source)) {
const r = resolveSpecifier(spec, file, root)
if (r.file) edges.push(r.file)
else if (r.bare) edges.push(`bare:${r.bare}`)
}
graph.set(file, { edges, client: USE_CLIENT_RE.test(source) })
}
return graph
}
/**
* For each client file, BFS its closure; return { clientFile -> path[] } for
* closures that contain `target` (a repo-relative file path or `bare:<spec>`).
*/
export function clientReachers(graph, target, root = ROOT) {
const targetKey = target.startsWith('bare:') ? target : path.join(root, target)
const hits = new Map()
for (const [file, node] of graph) {
if (!node.client) continue
const prev = new Map([[file, null]])
const queue = [file]
let found = null
while (queue.length && !found) {
const cur = queue.shift()
const edges = graph.get(cur)?.edges ?? []
for (const next of edges) {
if (prev.has(next)) continue
prev.set(next, cur)
if (next === targetKey) { found = next; break }
if (!next.startsWith('bare:')) queue.push(next)
}
}
if (found) {
const chain = []
for (let n = found; n; n = prev.get(n)) chain.unshift(n)
hits.set(path.relative(root, file), chain.map((n) => (n.startsWith('bare:') ? n : path.relative(root, n))))
}
}
return hits
}
const isMain = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
if (isMain) {
const targets = process.argv.slice(2)
if (!targets.length) {
console.error('usage: node scripts/perf/client-import-closure.mjs <repo-relative file | bare specifier> ...')
process.exit(1)
}
const graph = buildGraph()
for (const t of targets) {
const key = t.includes('/') || t.endsWith('.ts') || t.endsWith('.tsx') ? t : `bare:${t}`
const hits = clientReachers(graph, key)
console.log(`\n== ${t}: ${hits.size} client file(s) reach it`)
for (const [file, chain] of [...hits].sort()) console.log(` ${file}\n ${chain.join('\n > ')}`)
}
}
+205
View File
@@ -0,0 +1,205 @@
/**
* Percentiles over structured log lines.
*
* Reads JSON Lines on stdin (the shape `vercel logs --json` emits, or raw
* logger output) and prints a markdown table of count / p50 / p90 / p99 /
* max per group for the numeric fields asked for. Used for the
* "op completed" lines from lib/api/with-route-context.ts and the
* "proxy completed" lines from lib/supabase/middleware.ts.
*
* vercel logs --environment production --since 24h --limit 1000 --json \
* --query "op completed" \
* | npx tsx scripts/perf/log-percentiles.ts \
* --field durationMs,authMs,companyMs,handlerMs --group operation
*
* vercel logs --environment production --since 24h --limit 1000 --json \
* --query "proxy completed" \
* | npx tsx scripts/perf/log-percentiles.ts \
* --field totalMs,authMs,companyMs,mfaMs --group kind,route
*
* Options: --field a,b (required), --group x,y (default: none, one row),
* --filter key=value (repeatable; exact match on the parsed record),
* --min-count N (drop groups with fewer samples, default 1).
*
* No dependencies on purpose: this must run from a clean checkout.
*/
export type LogRecord = Record<string, unknown>
/**
* Turn one input line into a flat record. `vercel logs --json` wraps the
* application line in a `message` (or `text`) string, so an embedded JSON
* object inside that string is parsed and merged over the envelope; a bare
* JSON logger line is used as-is. Unparseable lines yield null.
*/
export function extractRecord(line: string): LogRecord | null {
const trimmed = line.trim()
if (!trimmed.startsWith('{')) return null
let envelope: LogRecord
try {
envelope = JSON.parse(trimmed) as LogRecord
} catch {
return null
}
const message = envelope.message ?? envelope.text
if (typeof message === 'string') {
const start = message.indexOf('{')
if (start >= 0) {
try {
const embedded = JSON.parse(message.slice(start)) as LogRecord
return { ...envelope, ...embedded }
} catch {
// Not a JSON payload: fall through and use the envelope alone.
}
}
}
return envelope
}
/** Nearest-rank percentile on an ascending-sorted array. */
export function percentile(sorted: number[], p: number): number {
if (sorted.length === 0) return Number.NaN
const rank = Math.ceil((p / 100) * sorted.length)
return sorted[Math.min(sorted.length, Math.max(1, rank)) - 1]
}
export interface FieldStats {
p50: number
p90: number
p99: number
max: number
}
export interface GroupRow {
group: string
count: number
fields: Record<string, FieldStats>
}
export interface SummarizeOptions {
fields: string[]
groupBy?: string[]
filters?: Array<{ key: string; value: string }>
minCount?: number
}
function matchesFilters(record: LogRecord, filters: SummarizeOptions['filters']): boolean {
if (!filters || filters.length === 0) return true
return filters.every(({ key, value }) => String(record[key]) === value)
}
export function summarize(records: LogRecord[], options: SummarizeOptions): GroupRow[] {
const groupBy = options.groupBy ?? []
const minCount = options.minCount ?? 1
const buckets = new Map<string, { count: number; values: Record<string, number[]> }>()
for (const record of records) {
if (!matchesFilters(record, options.filters)) continue
const groupKey = groupBy.length
? groupBy.map((key) => String(record[key] ?? '')).join(' / ')
: 'all'
let bucket = buckets.get(groupKey)
if (!bucket) {
bucket = {
count: 0,
values: Object.fromEntries(options.fields.map((f) => [f, [] as number[]])),
}
buckets.set(groupKey, bucket)
}
bucket.count += 1
for (const field of options.fields) {
const value = record[field]
if (typeof value === 'number' && Number.isFinite(value)) bucket.values[field].push(value)
}
}
const rows: GroupRow[] = []
for (const [group, bucket] of buckets) {
const count = bucket.count
if (count < minCount) continue
const fields: Record<string, FieldStats> = {}
for (const field of options.fields) {
const sorted = [...bucket.values[field]].sort((a, b) => a - b)
fields[field] = {
p50: percentile(sorted, 50),
p90: percentile(sorted, 90),
p99: percentile(sorted, 99),
max: sorted.length ? sorted[sorted.length - 1] : Number.NaN,
}
}
rows.push({ group, count, fields })
}
// Slowest first by the first field's p50 so the table reads as a ranking.
const primary = options.fields[0]
rows.sort((a, b) => (b.fields[primary]?.p50 ?? 0) - (a.fields[primary]?.p50 ?? 0))
return rows
}
function fmt(n: number): string {
return Number.isNaN(n) ? '-' : String(Math.round(n))
}
export function renderMarkdown(rows: GroupRow[], fields: string[]): string {
const header = ['group', 'n', ...fields.flatMap((f) => [`${f} p50`, `${f} p90`, `${f} p99`, `${f} max`])]
const lines = [
`| ${header.join(' | ')} |`,
`|${header.map(() => '---').join('|')}|`,
]
for (const row of rows) {
const cells = [row.group, String(row.count)]
for (const field of fields) {
const s = row.fields[field]
cells.push(fmt(s.p50), fmt(s.p90), fmt(s.p99), fmt(s.max))
}
lines.push(`| ${cells.join(' | ')} |`)
}
return lines.join('\n')
}
export function parseArgs(argv: string[]): SummarizeOptions {
const options: SummarizeOptions = { fields: [], groupBy: [], filters: [], minCount: 1 }
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i]
const next = () => {
i += 1
const value = argv[i]
if (value === undefined) throw new Error(`${arg} needs a value`)
return value
}
if (arg === '--field') options.fields = next().split(',').filter(Boolean)
else if (arg === '--group') options.groupBy = next().split(',').filter(Boolean)
else if (arg === '--filter') {
const [key, ...rest] = next().split('=')
options.filters!.push({ key, value: rest.join('=') })
} else if (arg === '--min-count') options.minCount = Number(next())
else throw new Error(`unknown option ${arg}`)
}
if (options.fields.length === 0) throw new Error('--field is required')
return options
}
async function readStdin(): Promise<string> {
const chunks: Buffer[] = []
for await (const chunk of process.stdin) chunks.push(chunk as Buffer)
return Buffer.concat(chunks).toString('utf8')
}
async function main(): Promise<void> {
const options = parseArgs(process.argv.slice(2))
const input = await readStdin()
const records = input
.split('\n')
.map(extractRecord)
.filter((r): r is LogRecord => r !== null)
const rows = summarize(records, options)
process.stdout.write(`${records.length} records parsed\n\n`)
process.stdout.write(`${renderMarkdown(rows, options.fields)}\n`)
}
if (process.argv[1] && /log-percentiles\.(?:ts|mts|js|mjs)$/.test(process.argv[1])) {
main().catch((err) => {
console.error(err instanceof Error ? err.message : err)
process.exit(1)
})
}