Fix/mcp and req (#753)
* feat(api): test-mode API keys force dry-run on the v1 REST API A key created with mode='test' (prefix gnubok_sk_test_) binds to the real company, but the v1 wrapper forces dry_run on every write so nothing is persisted or sent. Mutations on endpoints that can't be simulated (dryRunSupported=false or unregistered) are refused with 403 TEST_KEY_WRITE_BLOCKED — fail-closed. Reads pass through unchanged and every test-key response carries X-Gnubok-Mode: test. Live keys are unaffected (mode defaults to 'live'). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(invoices): company default "Vår referens" + per-line sales-account override Add company_settings.default_our_reference (settings form, schema, type); the invoice editor pre-fills our_reference from it on new invoices only, never overwriting an edited draft. Separately, add an optional per-line försäljningskonto (class-3) override in the editor — left blank, the engine still derives the revenue account from the VAT rate, and reverse-charge/export lines ignore the override. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(invoices): render a Swish payment QR on invoice PDFs Build the Swish "Type C" QR payload offline (no Swish API call) and embed it as a PNG in the invoice PDF payment box when Swish display is enabled, the invoice is in SEK, and the amount is positive. Also surface the invoice number in the payment box. Wired through every PDF render path: send, mark-sent and pdf routes (both legacy and v1), the recurring-schedule sender, and the staged-send commit. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(bookkeeping): draft exclusion + correction-chain collapse on verifikationslista Extend list_fiscal_period_entries_with_related with two opt-in params: p_exclude_draft (keep drafts off the committed list — they get their own surface) and p_collapse_corrections (render a correction group as the single live correction, hiding the mechanical storno and the reversed original). Both default false; nothing is deleted, every voucher keeps its number, and a "show all" toggle exposes the full chain. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(reports): link multi-year SIE periods so resultatrapport shows the prior year SIE import now sets fiscal_periods.previous_period_id in both directions when creating a period, so multi-year files chain correctly regardless of #RAR order. A backfill migration repairs periods imported before this (idempotent; only touches NULL links on first-of-month periods). generateResultatrapport falls back to the date-adjacent prior period when the chain is still null, so the comparison column works for legacy data too. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(articles): hide the VAT field for non-momsregistrerade companies The article form reads company_settings.vat_registered and, when false, hides the moms field and forces vat_rate to 0 on submit — mirroring the invoice editor so a non-VAT-registered company never sets a rate it can't charge. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(import): allow file-based imports in the sandbox Bank-file, CSV/Excel and SIE imports run entirely on uploaded data with no external service, so they're now reachable in the sandbox. Only the API-backed options that need live third-party credentials (PSD2 bank connection, provider migration) stay disabled. Updates the sandbox notice copy to match. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(bookkeeping): add edit draft functionality for journal entries * feat(database): add default "Vår referens" column to company_settings for invoicing * fix(tests): set SHOW_SWISH_ON_INVOICE to false in PDF template mocks * @ fix(payments): use roundOre for Swish amount formatting Replace naive Math.round(x*100)/100 with roundOre from @/lib/money to satisfy the antipattern guard. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> @ --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
2d6ddeafc5
commit
241959513b
@@ -1061,6 +1061,7 @@ export const UpdateSettingsSchema = z.object({
|
||||
next_invoice_number: z.number().int().positive().optional(),
|
||||
invoice_default_days: z.number().int().positive().optional(),
|
||||
invoice_default_notes: z.string().nullable().optional(),
|
||||
default_our_reference: z.string().max(200).nullable().optional(),
|
||||
phone: z.string().optional(),
|
||||
email: z.string().email().optional().or(z.literal('')),
|
||||
website: z.string().optional().or(z.literal('')),
|
||||
|
||||
@@ -388,6 +388,76 @@ describe('withApiV1 — dry-run', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('withApiV1 — test mode', () => {
|
||||
it('blocks a test-key write on a non-simulatable endpoint (403 TEST_KEY_WRITE_BLOCKED)', async () => {
|
||||
// No route modules are imported here, so the endpoint registry is empty →
|
||||
// getEndpointByConcretePath returns undefined → the wrapper must refuse the
|
||||
// write rather than let a test key mutate real data.
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
scopes: ['invoices:write'],
|
||||
mode: 'test',
|
||||
})
|
||||
mockServiceClient.mockReturnValue(makeSupabaseStub({ company_id: 'company-1', role: 'owner' }))
|
||||
|
||||
let handlerCalled = false
|
||||
const handler = withApiV1(
|
||||
'invoices.create',
|
||||
async (_req, ctx) => {
|
||||
handlerCalled = true
|
||||
return ok({ ok: true }, { requestId: ctx.requestId })
|
||||
},
|
||||
{ requireScope: 'invoices:write' },
|
||||
)
|
||||
|
||||
const res = await handler(
|
||||
makeRequest('https://x.test/api/v1/companies/company-1/invoices', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer gnubok_sk_x', 'Content-Type': 'application/json' },
|
||||
body: '{}',
|
||||
}),
|
||||
companyParams('company-1'),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('TEST_KEY_WRITE_BLOCKED')
|
||||
expect(handlerCalled).toBe(false)
|
||||
})
|
||||
|
||||
it('allows a test-key READ unchanged — no forced dry-run, real data, X-Gnubok-Mode header', async () => {
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
scopes: ['companies:read'],
|
||||
mode: 'test',
|
||||
})
|
||||
mockServiceClient.mockReturnValue(makeSupabaseStub({ company_id: 'company-1', role: 'owner' }))
|
||||
|
||||
let observedDryRun: boolean | null = null
|
||||
const handler = withApiV1(
|
||||
'companies.get',
|
||||
async (_req, ctx) => {
|
||||
observedDryRun = ctx.dryRun
|
||||
return ok({ ok: true }, { requestId: ctx.requestId })
|
||||
},
|
||||
{ requireScope: 'companies:read' },
|
||||
)
|
||||
|
||||
const res = await handler(
|
||||
makeRequest('https://x.test/api/v1/companies/company-1', {
|
||||
headers: { Authorization: 'Bearer gnubok_sk_x' },
|
||||
}),
|
||||
companyParams('company-1'),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(observedDryRun).toBe(false)
|
||||
expect(res.headers.get('X-Gnubok-Mode')).toBe('test')
|
||||
})
|
||||
})
|
||||
|
||||
describe('withApiV1 — public endpoints', () => {
|
||||
it('invokes the handler without authentication for /api/v1/health', async () => {
|
||||
let observedUserId: string | null = null
|
||||
|
||||
@@ -135,6 +135,26 @@ export function getEndpoint(method: HttpMethod, path: string): EndpointDefinitio
|
||||
return ENDPOINTS.get(`${method} ${path}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the registered endpoint for a CONCRETE request path (e.g.
|
||||
* `/api/v1/companies/abc/customers`) by matching it against the registered
|
||||
* `:param` patterns. Used by the wrapper to read an endpoint's `dryRunSupported`
|
||||
* flag at request time — the route module being served has already run its
|
||||
* `registerEndpoint()` call, so its pattern is present. Returns undefined when
|
||||
* no pattern matches (the wrapper treats that as "cannot be simulated").
|
||||
*/
|
||||
export function getEndpointByConcretePath(
|
||||
method: string,
|
||||
concretePath: string,
|
||||
): EndpointDefinition | undefined {
|
||||
for (const def of ENDPOINTS.values()) {
|
||||
if (def.method !== method) continue
|
||||
const regex = new RegExp('^' + def.path.replace(/:[^/]+/g, '[^/]+') + '$')
|
||||
if (regex.test(concretePath)) return def
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
// Minimal Zod → JSON Schema converter
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -51,6 +51,7 @@ import {
|
||||
// idempotent (guarded by a module-level boolean).
|
||||
ensureInitialized()
|
||||
import { resolveRequiredScope } from '@/lib/auth/scopes'
|
||||
import { getEndpointByConcretePath } from './registry'
|
||||
import {
|
||||
checkIdempotencyKey,
|
||||
hashRequest,
|
||||
@@ -79,7 +80,11 @@ export interface ApiV1Context {
|
||||
apiKeyName: string | undefined
|
||||
/** Scopes granted to the calling key. */
|
||||
scopes: ApiKeyScope[]
|
||||
/** test|live — handlers branch on this to short-circuit external providers in test mode. */
|
||||
/**
|
||||
* test|live. Test keys are simulation-only — the wrapper forces `dryRun` on
|
||||
* for every write, so handlers never need to special-case `mode`; they just
|
||||
* honor `dryRun` as usual.
|
||||
*/
|
||||
mode: ApiKeyMode
|
||||
/** Service-role Supabase client (no cookies). All queries MUST filter by company_id. */
|
||||
supabase: SupabaseClient
|
||||
@@ -353,6 +358,28 @@ export function withApiV1<P extends DynamicParams = { params: Promise<Record<str
|
||||
const idempotencyKey = request.headers.get(IDEMPOTENCY_HEADER)
|
||||
const isMutation = REQUIRES_IDEMPOTENCY.has(request.method)
|
||||
|
||||
// Test keys are simulation-only: every write is forced to dry-run so
|
||||
// nothing persists (the credential bakes in `?dry_run=true`). A mutating
|
||||
// endpoint that can't be simulated (dryRunSupported=false, or unregistered)
|
||||
// would otherwise write for real — block it outright so a test key can
|
||||
// never touch real data. Reads pass through unchanged (real data, no write).
|
||||
let forceDryRun = false
|
||||
if (auth.mode === 'test' && isMutation) {
|
||||
const endpoint = getEndpointByConcretePath(request.method, path)
|
||||
if (!endpoint || !endpoint.dryRunSupported) {
|
||||
userLog.warn('test key blocked from non-simulatable endpoint', {
|
||||
path,
|
||||
method: request.method,
|
||||
...forensic,
|
||||
})
|
||||
return await v1ErrorResponseFromCode('TEST_KEY_WRITE_BLOCKED', userLog, {
|
||||
requestId,
|
||||
details: { path, method: request.method },
|
||||
})
|
||||
}
|
||||
forceDryRun = true
|
||||
}
|
||||
|
||||
if (options.requireIdempotencyKey && isMutation && !idempotencyKey) {
|
||||
userLog.warn('missing idempotency key on mutating request')
|
||||
return await v1ErrorResponseFromCode('VALIDATION_ERROR', userLog, {
|
||||
@@ -391,8 +418,8 @@ export function withApiV1<P extends DynamicParams = { params: Promise<Record<str
|
||||
}
|
||||
}
|
||||
|
||||
// 8. Dry-run resolution.
|
||||
const dryRun = isDryRun(workingRequest, url)
|
||||
// 8. Dry-run resolution. Test keys force it on regardless of the flag.
|
||||
const dryRun = isDryRun(workingRequest, url) || forceDryRun
|
||||
|
||||
const ctx: ApiV1Context = {
|
||||
requestId,
|
||||
@@ -411,6 +438,12 @@ export function withApiV1<P extends DynamicParams = { params: Promise<Record<str
|
||||
// 9. Invoke handler.
|
||||
const response = await handler(workingRequest, ctx, params)
|
||||
|
||||
// Signal test mode on every test-key response so integrators can see the
|
||||
// request was simulation-only without inspecting the body.
|
||||
if (ctx.mode === 'test') {
|
||||
response.headers.set('X-Gnubok-Mode', 'test')
|
||||
}
|
||||
|
||||
// 10. Persist idempotency cache (best-effort).
|
||||
if (idempotencyKey && isMutation && companyId && response.status < 500) {
|
||||
try {
|
||||
|
||||
Reference in New Issue
Block a user