fix: similar-sweep currency remediation, security hardening and v1 API fixes (#1215)
* fix(security): gate replace_sie_import behind owner/admin membership The RPC was SECURITY DEFINER with EXECUTE granted to PUBLIC and anon, no company_members lookup, no auth.uid() reference and no unauthorized raise, while setting gnubok.allow_delete to disarm the BFL immutability and retention triggers. Any caller holding a company_id and an import id could hard delete another tenant's verifikationer. Confirmed live in production. Applies the same fail closed owner/admin guard that undo_sie_import already carries (migration 20260624120000), resolving the actor from COALESCE(p_user_id, auth.uid()) so it denies when the role is NULL, then revokes EXECUTE from PUBLIC and anon. search_path and the raised statement_timeout are restated, since CREATE OR REPLACE drops settings that are not repeated. userId is a required parameter on replaceSIEImport: the service client has a NULL auth.uid(), so a caller without an explicit actor now fails to compile rather than hitting the closed gate at runtime. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(security): validate arcim OAuth callback state server side The callback route is skipAuth and decoded the state parameter as plain base64url JSON, trusting consentId and provider from it. A one time code was minted at flow start and never read. An unauthenticated attacker who learned a consent id could run an OAuth flow on their own provider account and post the callback with a forged state, landing their tokens on another tenant's consent, so the victim's next migration imported the attacker's ledger. State is now an opaque randomBytes(32) pointer to a provider_otc row, consumed by a single atomic UPDATE guarded on used_at IS NULL and expires_at, so a replay loses the row lock race and updates nothing. provider is read from provider_consents rather than trusted from the client. provider_otc already existed for exactly this purpose and was never wired up. Also scopes getConsent to an owning company, closing a cross tenant status oracle where the preview and migrate paths echoed a consent's status before the scoped check ran. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(security): scope documents storage to company_id (phase A) The documents bucket policies matched on auth.uid(), and upload keys were documents/{userId}/..., so company membership was never consulted. Removing a member revoked nothing: their session still authenticated and they kept direct Storage read access to every receipt, supplier invoice and bank statement they had uploaded. The same bug was fixed for sie-files in 20260416120000; this bucket was left behind. Phase A is additive. Company scoped policies are added alongside the uploader scoped ones, uploads move to documents/{companyId}/{userId}/..., and reads accept either layout so nothing breaks mid migration. Phase C, which drops the old policies, is gated on the backfill reporting zero remaining legacy prefix objects. The policy compares the company segment as text rather than casting to uuid the way sie-files does: this bucket holds keys whose second segment is not a uuid (MCP audit packages), and Postgres does not guarantee the bucket prefix qual runs before the cast, so a planner reordering would raise 22P02 and fail the whole query instead of filtering the row out. deleteDocument now removes both candidate keys. Removing only the stored pointer would leave a readable orphan copy of a document the user asked to erase. The backfill script is included but has never been run. It defaults to dry run, refuses .env.local by name, and verifies each copy is readable and SHA-256 identical before repointing the row. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(security): enforce events:read scope and membership on /api/events This was the only one of the three validateApiKey call sites with no downstream guard: v1 and the MCP server both check scope and re-verify company membership, this route did neither. An events:read scope existed and was documented as gating the endpoint but was never called, so a legacy key falling back to DEFAULT_SCOPES read the full log. The bound company id went straight from the api_keys row into a service role query, so a key whose user had been removed from the company kept reading. Adds the scope check before any database access, re-verifies company_members with archived_at IS NULL, honours test mode by stamping X-Gnubok-Mode instead of ignoring it, applies minimisePayload so the pull surface can never return a wider payload than the push surface, and replaces the three flat error strings with the canonical envelope. Test key reads are served rather than blocked: TEST_KEY_WRITE_BLOCKED is gated on mutations in with-api-v1, so a read gets the same treatment as every other v1 read endpoint. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * perf(bookkeeping): sweep remaining journal_entries!inner embeds A previous refactor removed this pattern from lib/reports and introduced fetchEntryLines, but the class was never swept. Seventeen sites remained and had become the top application consumer of production database time: measured across the resulting query shapes, 32,694 calls and 25,848 seconds of execution, mean 790ms, with shapes averaging 2.6s and 3.0s and maxing at 7,962ms against the 8s statement_timeout, which surfaced to users as 500s on the booking path. PostgREST compiles an embed with filters on the embedded side into a correlated INNER JOIN LATERAL with a parameterized LIMIT, which stops Postgres reordering the join, so each query walked the whole journal_entry_lines table across all tenants. Driving from the entries side instead turns that into two indexed round trips. Converted sites keep their existing shape: the helper reattaches the parent entry under the same key the embed produced. Several conversions also remove a latent silent truncation where an unpaginated query was capped at PostgREST's 1000 row ceiling. Two deliberate exceptions. The free text ilike legs of the MCP display query stay on the embed, because each is capped at legLimit and that cap drives the truncation contract the tool reports, while the helper is unbounded. The accounts route moves to the existing get_account_usage_counts RPC instead, since its embed was a head count and the helper returns rows. commitEntry's write path is untouched: the change there is confined to the read query of the pre-commit dimension rule check. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(api): anchor v1 list cursors on created_at Page two returned page one, forever, while still advertising a fresh next_cursor. The three routes sorted by and encoded a Postgres date column, which serializes as YYYY-MM-DD, but decodeDefaultCursor validates the cursor timestamp as full ISO-8601 and returned null, so the keyset filter was never applied and has_more never went false. An integrator syncing verifikat looped on the newest rows indefinitely. The transactions route already solved this and its comment names the trap; the fix was never ported. All three now order and encode on created_at with an id tie break, matching the transactions keyset predicate exactly. ISO_TIMESTAMP is deliberately left alone: relaxing it would silently change sort semantics on the route that currently works. Default ordering therefore moves from business date to insert order. Every business date is still on the row, and the invoices list gains date_from and date_to filters so a date range is still reachable; the other two already had them. The tests use an in-memory PostgREST that actually evaluates the filters, because the repo's pass-through mock cannot catch this class of bug: the bug is that the filter is never sent. They walk to exhaustion with a hard iteration cap, so an unterminated walk fails instead of hanging. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(api): separate dry run from commit in the idempotency hash The request hash was built from url.pathname, which excludes the query string, so a dry run and its commit hashed identically. Following the flow documented in dry-run.ts, re-issuing the request with the same Idempotency-Key returned the cached preview with Idempotent-Replayed set and wrote nothing, while reporting 200. An agent or integrator saw success for a write that never happened. dry_run is folded into the hash only when true, not as an unconditional boolean. Including it as false would change the hash of every ordinary write, and with a 24h idempotency TTL any key in flight across the deploy would fail the request_hash comparison and 409 on a legitimate retry. Both hash call sites now go through one shared helper so they cannot drift into a permanent cache miss, and dry run responses are no longer stored at all. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * ci: install the Bedrock SDK out of tree in the compliance review The Swedish accounting compliance gate had failed ten consecutive runs and so was posting nothing. With --no-package-lock npm discarded the lockfile and re-resolved the whole tree from package.json, floating @hookform/resolvers to 5.4.3, whose valibot ^1 peer conflicts with the pinned valibot 0.39.0. Installing into the parent of the checkout resolves only that one package, so an unrelated peer conflict can never take the gate down again. Node still finds it because ESM bare specifiers walk up parent node_modules; NODE_PATH would not have worked, as it is CommonJS only. --legacy-peer-deps was rejected because it masks future genuine peer conflicts and still reifies the full tree. The same step's SDK version is aligned from 0.31.0 back to the 0.29.1 that package.json and check:guards enforce after the streaming outage. That drift went unnoticed because the pin guard only inspects package.json and the lockfile, never workflow files. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * build(docker): generate crontabs from vercel.json vercel.json defines 16 cron jobs; both Docker crontabs carried 9, and were byte identical to each other. Self hosted deployments therefore never sent recurring invoices, never dispatched webhooks and never cleaned up idempotency keys. tax-deadlines also ran once a year on 2 January instead of daily, and documents/verify weekly instead of daily. Extension crons are included rather than excluded. The Dockerfile copies the whole tree before building, so every extension cron route is compiled into the image regardless of the enabled preset, and each returns 200 when its extension is unconfigured, so curl -sf logs no failure. Two such entries were already present in the crontab for extensions absent from the preset, which settles the intent. documents/verify is treated as drift rather than a self hosted concession: the weekly cadence was present in the hosted crontab too, and the run is capped at 200 documents walking a nulls-first queue, so weekly drains the integrity queue seven times slower on a check that exists for BFL retention. webhooks/dispatch keeps its per minute cadence, adding 1,440 requests a day on self hosted. A gentler tick would silently stretch the first retry, since the retry ladder opens at 60 seconds. SCHEDULE_OVERRIDES is the one line place to change that. A parity test asserts the path sets match minus a documented exclusion list, and ratchets three cron routes that are currently scheduled nowhere so they are named rather than silently rotting. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * chore(observability): add a provider agnostic error sink There is no error tracking in this codebase: logs go to console and Vercel retention and nowhere else, nothing alerts on the 16 cron jobs, and seven code comments across lib, app, components and extensions asserted that Sentry captures errors when Sentry is not a dependency. The two most recent bug fixes on this repo were both discovered by customer email. This adds the sink, not a vendor. No dependency is taken: the interface has a no-op default and a registration point, so behaviour is unchanged until an adapter is registered. Releases are tagged from the build id already inlined by next.config.ts. Redaction moved out of lib/logger.ts into a leaf module that both the logger and the sink import, so there is one denylist and no path from application data to a third party can skip the personnummer regex, including direct sink calls that bypass the logger. That matters here because these logs carry personnummer and financial data. verifyCronSecret now reports its own 401s, which covers all 16 jobs without touching a route file and catches the case where CRON_SECRET is rotated without updating the scheduler and every job silently 401s forever. The threshold is one failure rather than the backup alert's three: suppressing the first occurrence is precisely how an outage stays invisible. The seven misleading comments are corrected to describe what the code actually does, including the two cases that still are not covered: the client side one, since the sink is server side, and a warn level call that is not forwarded. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix: remediate the 2026-07-26 similar-sweep findings across all surfaces Resolves the ~150-finding sweep (dev_docs/similar-sweep-2026-07-26.md) with one agent per finding; every behavioural fix carries a regression test proven to fail at HEAD. Full status, corrections to the sweep, refusals and open decisions in dev_docs/similar-sweep-2026-07-26-remediation-status.md. Structural roots closed: - resolveSekAmountOrNull(): honest SEK resolution refuses instead of booking 1:1; four duplicated toSek closures now refuse via INVOICE_FX_RATE_MISSING - ledger-line-amount.ts: journal_entry_lines.currency labels the document, not the amount; SQL pre-filter decoy proven and fixed - sparse-patch.ts: .partial() does not strip .default() in Zod 4.4.3; the exploitable salary payslip-line PATCH and KPI preferences sinks fixed - tests/schema: migration-replay phantom-column guard (13k+ refs, closed CHECK sets, onConflict targets); found 28 real defects, all fixed, all four baselines now empty - three new ratchet guards: sek-labelled-amount, cross-extension-import, ungated-extension-route Highlights: lawful VAT-rate set on all seven invoice surfaces (ML 6 kap), RC input VAT mismatch wired on web + both MCP callers, missing-underlag resource delegates to the shared RPC predicate, push-notifications consent polarity fail-closed, deadlines undo honours requested state, silent-failure and read-side-fabrication classes fixed across settings/KPI/inbox/Stripe/ Arcim/kassaflodesanalys, error-envelope stringification fixed at 10+ sites with isSwedishUserMessage extended. Also includes the parallel session's MCP invoice tools (update_invoice, recurring schedules, invoice deliveries) which share files with the sweep work and are verified green together. 13 new migrations are NOT applied anywhere; they apply via branch merge. 20260726120000 backfills 1247 supplier-invoice rows. pg tests for new DDL are written but unrun (no local Postgres). Verified: 11088 tests / 881 files green, tsc 0 non-test errors, lint 0 errors, check:guards passing, MCP payload 57475/57500. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(migrations): rename replace_sie_import migration off main's 20260726090000 version origin/main shipped 20260726090000_agent_quota_rpc_caller_guard.sql; keeping our replace_sie_import migration on the same version would abort the Supabase apply with a schema_migrations_pkey duplicate at merge time. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(review): remediate pre-publish deep-review findings across all slices A 13-agent review of the full branch diff surfaced 1 critical, 5 high and ~45 further findings; this commit resolves them in one pass: - replace_sie_import / undo_sie_import: p_user_id honored only for service_role callers; any other caller is pinned to auth.uid() (impersonation gate bypass), authz raise errcode 42501 mapped to a Swedish 403 in the route, new caller-guard migration for undo - bulk_book_transactions refuses homogeneous non-SEK batches instead of writing foreign magnitudes into SEK ledger columns - credit-note cap trigger: company-match on credited_invoice_id, no cross-tenant figures in exception text - link_voucher RPCs resolve NULL invoice currency as SEK end to end - personal-number ciphertext CHECK split into NOT VALID + VALIDATE - same-currency foreign settlements clear 1510 at booking rate and book realized diff to 3960/7960; rate-less foreign write paths refuse - receivables revaluation covers partially_paid and outstanding amounts - period lock guard paginates candidates past the PostgREST 1000 cap - documents: service-client storage removals after authz, dual-layout reads in integrity cron and archive export, backfill delete-source sweep actually deletes with hash verification and shared-key grouping - invoice matching normalizes NULL/lowercase currencies (regression), duplicate candidates stop claiming amount matches they never ran - match-invoice aborts on any booking failure (no paid-without-verifikat) - refresh-exchange-rate reverts on concurrent booking (TOCTOU window) - KPI preferences upsert arbiter aligned to the company-scoped constraint - personnummer_last4 stripped from all salary responses incl. MCP tools - worked-hours batch restores destroyed rows on conflict and error paths - MCP: shared duplicate-claim builder (no more 'null kr'), short-circuit on tag_journal_lines overflow, auto_send schedules stage as high risk - observability sink redacts emails/IBANs/API keys and keeps redacted stacks in prod; assorted small guards (safe-return-to /@, dry_run=True, cursor helper off-by-one, OAuth state TTL 10 min, arcim saveMappings call removed) Full dispositions, deferred items and hand-verified accounting numbers are documented in the PR body and DECISIONS.md. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(personnummer): implement masking and encryption for personal numbers with tests * fix(review): address CI and compliance-bot findings for PR #1215 pg-real: the CI image's auth shim reads the legacy request.jwt.claim.role GUC, so both service-role simulations (runAsServiceRole and the invoice-delivery test's local helper) never satisfied auth.role() = 'service_role' and every legitimate p_user_id path failed closed; the shared helper now sets both GUC shapes plus SET LOCAL ROLE with a fail-loud sanity check, and the delivery test reuses it. The link-voucher migration had recreated both RPCs from pre-rewrite file text, reintroducing the NULL-unsafe membership pattern the null-safe-tenant-guards ratchet bans; both guards now use public.caller_is_company_member() with all currency changes preserved. Compliance bots: the customers export now emits the standard masked form instead of raw AES-256-GCM ciphertext in the Org-/personnummer column, and maskCustomerRow returns a non-round-trippable placeholder on decrypt failure instead of 500ing the list. MCP parity: gnubok_lock_period's staging pre-check now runs the exact countUnbookedInPeriod the commit path enforces (exported from period-service; local mirror deleted), and gnubok_agi_status resolves AGI state run-scoped so a correction run no longer renders as already filed. Declined with evidence: PR-Agent's opening-balances null-zeroing concern (all mergeable columns are NOT NULL with defaults per 20260713101000). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(review): address codex review findings on PR #1215 - restore 20260726140000 to its preview-recorded content and restate the NULL-safe tenant guard under 20260727130000: a recorded migration version never re-runs, so the in-place edit could not reach the preview branch - replace toFixed() with sv-SE two-decimal formatting in the ROT/RUT cap warning texts and update the pinned test expectations - drop the em dash in the fiscal-periods route comment - strip trailing whitespace in import-existing.test.ts Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(reports): raise timeout on real PDF render tests renderToBuffer does real @react-pdf layout work and exceeds the 5s default when the full suite saturates the CPU; tests pass in isolation. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
a43a8b03cf
commit
f24b26a139
@@ -0,0 +1,95 @@
|
||||
import { describe, it, expect, afterEach, vi } from 'vitest'
|
||||
import { failureDescription, type ActionFailure } from '@/lib/browser/action-failure'
|
||||
import { downloadFile } from '@/lib/browser/download-file'
|
||||
import { postAction } from '@/lib/browser/post-action'
|
||||
|
||||
const originalFetch = globalThis.fetch
|
||||
|
||||
afterEach(() => {
|
||||
globalThis.fetch = originalFetch
|
||||
})
|
||||
|
||||
const COPY = {
|
||||
timeout: 'Servern svarade inte i tid. Ingen betalfil sparades. Försök igen.',
|
||||
network: 'Ingen kontakt med servern. Ingen betalfil sparades. Kontrollera din internetanslutning och försök igen.',
|
||||
}
|
||||
|
||||
describe('failureDescription', () => {
|
||||
it('names a timeout as a timeout', () => {
|
||||
expect(failureDescription({ ok: false, reason: 'timeout' }, COPY)).toBe(COPY.timeout)
|
||||
})
|
||||
|
||||
it('names a network failure as a network failure', () => {
|
||||
// The union's own message for this arm is the generic "Något gick fel",
|
||||
// which cannot be told apart from a server error. The caller's copy can.
|
||||
const failure: ActionFailure = {
|
||||
ok: false,
|
||||
reason: 'network',
|
||||
message: 'Något gick fel. Försök igen.',
|
||||
}
|
||||
expect(failureDescription(failure, COPY)).toBe(COPY.network)
|
||||
expect(failureDescription(failure, COPY)).not.toBe(COPY.timeout)
|
||||
})
|
||||
|
||||
it("keeps the server's own reason, which is more specific than any panel copy", () => {
|
||||
const failure: ActionFailure = {
|
||||
ok: false,
|
||||
reason: 'server',
|
||||
status: 400,
|
||||
message: 'Bankgironummer saknas i företagsinställningar. Krävs för Bankgirot LB-fil.',
|
||||
}
|
||||
expect(failureDescription(failure, COPY)).toBe(
|
||||
'Bankgironummer saknas i företagsinställningar. Krävs för Bankgirot LB-fil.',
|
||||
)
|
||||
})
|
||||
|
||||
it('gives the three reasons three different sentences', () => {
|
||||
const said = new Set([
|
||||
failureDescription({ ok: false, reason: 'timeout' }, COPY),
|
||||
failureDescription({ ok: false, reason: 'network', message: 'x' }, COPY),
|
||||
failureDescription({ ok: false, reason: 'server', status: 500, message: 'Serverfel' }, COPY),
|
||||
])
|
||||
expect(said.size).toBe(3)
|
||||
})
|
||||
})
|
||||
|
||||
describe('failure arms of downloadFile and postAction are interchangeable', () => {
|
||||
// The panels feed both into one failureDescription call. If either union
|
||||
// drifts, this stops compiling, which is the point.
|
||||
it('accepts a downloadFile failure', async () => {
|
||||
globalThis.fetch = (() => Promise.reject(new TypeError('fetch failed'))) as typeof fetch
|
||||
const result = await downloadFile({ url: '/x', filename: 'f.txt', saveBlob: () => {} })
|
||||
expect(result.ok).toBe(false)
|
||||
if (!result.ok) expect(failureDescription(result, COPY)).toBe(COPY.network)
|
||||
})
|
||||
|
||||
it('accepts a postAction failure', async () => {
|
||||
globalThis.fetch = (() => Promise.reject(new TypeError('fetch failed'))) as typeof fetch
|
||||
const result = await postAction({ url: '/x' })
|
||||
expect(result.ok).toBe(false)
|
||||
if (!result.ok) expect(failureDescription(result, COPY)).toBe(COPY.network)
|
||||
})
|
||||
|
||||
it('still surfaces the salary route 400 verbatim, as the old inline handler did', async () => {
|
||||
// The dominant real failure on the payment-file panels: the run is approved
|
||||
// but company settings are incomplete. The route answers a plain-string
|
||||
// envelope, not the structured one, and that sentence is the whole point of
|
||||
// the toast: it names the field the user has to go and fill in. It must
|
||||
// survive the move from the inline getErrorMessage call into downloadFile.
|
||||
const message = 'Bankgironummer saknas i företagsinställningar. Krävs för Bankgirot LB-fil.'
|
||||
globalThis.fetch = (() =>
|
||||
Promise.resolve(
|
||||
new Response(JSON.stringify({ error: message }), {
|
||||
status: 400,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}),
|
||||
)) as typeof fetch
|
||||
const saveBlob = vi.fn()
|
||||
|
||||
const result = await downloadFile({ url: '/x', filename: 'lon_2026-04.txt', saveBlob })
|
||||
|
||||
expect(saveBlob).not.toHaveBeenCalled()
|
||||
expect(result.ok).toBe(false)
|
||||
if (!result.ok) expect(failureDescription(result, COPY)).toBe(message)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,62 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { copyToClipboard } from '@/lib/browser/copy-to-clipboard'
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
describe('copyToClipboard', () => {
|
||||
it('reports copied and forwards the exact text on success', async () => {
|
||||
const writeText = vi.fn(async () => undefined)
|
||||
vi.stubGlobal('navigator', { clipboard: { writeText } })
|
||||
|
||||
await expect(copyToClipboard('gnubok_sk_live_abc123')).resolves.toBe('copied')
|
||||
expect(writeText).toHaveBeenCalledWith('gnubok_sk_live_abc123')
|
||||
})
|
||||
|
||||
it('reports failed when the write is rejected, never copied', async () => {
|
||||
// The regression guard: the old call sites either swallowed this rejection
|
||||
// in an empty catch (no check mark, no message) or never awaited it at all
|
||||
// (check mark shown regardless). Both told the user the secret was on the
|
||||
// clipboard when it was not.
|
||||
const writeText = vi.fn(async () => {
|
||||
throw new DOMException('Write permission denied.', 'NotAllowedError')
|
||||
})
|
||||
vi.stubGlobal('navigator', { clipboard: { writeText } })
|
||||
|
||||
const result = await copyToClipboard('JBSWY3DPEHPK3PXP')
|
||||
expect(result).toBe('failed')
|
||||
expect(result).not.toBe('copied')
|
||||
})
|
||||
|
||||
it('reports failed on a non-Error rejection', async () => {
|
||||
vi.stubGlobal('navigator', {
|
||||
clipboard: { writeText: vi.fn(() => Promise.reject('nope')) },
|
||||
})
|
||||
|
||||
await expect(copyToClipboard('secret')).resolves.toBe('failed')
|
||||
})
|
||||
|
||||
it('reports unavailable when the Clipboard API is missing (insecure context)', async () => {
|
||||
vi.stubGlobal('navigator', {})
|
||||
|
||||
await expect(copyToClipboard('secret')).resolves.toBe('unavailable')
|
||||
})
|
||||
|
||||
it('reports unavailable when clipboard exists but writeText does not', async () => {
|
||||
vi.stubGlobal('navigator', { clipboard: { read: vi.fn() } })
|
||||
|
||||
await expect(copyToClipboard('secret')).resolves.toBe('unavailable')
|
||||
})
|
||||
|
||||
it('is SSR-safe: reports unavailable with no navigator, and does not throw', async () => {
|
||||
vi.stubGlobal('navigator', undefined)
|
||||
|
||||
await expect(copyToClipboard('secret')).resolves.toBe('unavailable')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,243 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import {
|
||||
downloadFile,
|
||||
saveBlobToDisk,
|
||||
DOWNLOAD_TIMEOUT_MS,
|
||||
OBJECT_URL_REVOKE_DELAY_MS,
|
||||
} from '@/lib/browser/download-file'
|
||||
|
||||
const originalFetch = globalThis.fetch
|
||||
|
||||
const EXPORT_BODY = JSON.stringify({ version: 1, templates: [{ name: 'Inköp EU-varor' }] })
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return new Response(typeof body === 'string' ? body : JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
|
||||
/** A fetch that never resolves and rejects the way the platform does on abort. */
|
||||
function hangingFetch() {
|
||||
return vi.fn((_url: unknown, init?: RequestInit) => {
|
||||
return new Promise<Response>((_resolve, reject) => {
|
||||
init?.signal?.addEventListener('abort', () => {
|
||||
const err = new Error('The operation was aborted due to timeout')
|
||||
err.name = 'TimeoutError'
|
||||
reject(err)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
globalThis.fetch = originalFetch
|
||||
})
|
||||
|
||||
describe('downloadFile', () => {
|
||||
it('saves the file when the server answers 2xx', async () => {
|
||||
globalThis.fetch = vi.fn().mockResolvedValue(jsonResponse(EXPORT_BODY))
|
||||
const saveBlob = vi.fn()
|
||||
|
||||
const result = await downloadFile({
|
||||
url: '/api/settings/booking-templates/export',
|
||||
filename: 'bokforingsmallar.json',
|
||||
saveBlob,
|
||||
})
|
||||
|
||||
expect(result).toEqual({ ok: true, filename: 'bokforingsmallar.json' })
|
||||
expect(saveBlob).toHaveBeenCalledTimes(1)
|
||||
const [blob, filename] = saveBlob.mock.calls[0]
|
||||
expect(filename).toBe('bokforingsmallar.json')
|
||||
await expect((blob as Blob).text()).resolves.toBe(EXPORT_BODY)
|
||||
})
|
||||
|
||||
it('writes NO file on a 500 and reports the envelope message', async () => {
|
||||
// The regression guard. The old handler called res.blob() with no res.ok
|
||||
// check, so this error envelope was saved to disk as bokforingsmallar.json
|
||||
// and the download was reported as a success.
|
||||
globalThis.fetch = vi.fn().mockResolvedValue(
|
||||
jsonResponse(
|
||||
{
|
||||
error: {
|
||||
code: 'INTERNAL_ERROR',
|
||||
message: 'Kunde inte hämta mallarna. Försök igen.',
|
||||
message_en: 'Could not load the templates. Please try again.',
|
||||
},
|
||||
},
|
||||
500,
|
||||
),
|
||||
)
|
||||
const saveBlob = vi.fn()
|
||||
|
||||
const result = await downloadFile({
|
||||
url: '/api/settings/booking-templates/export',
|
||||
filename: 'bokforingsmallar.json',
|
||||
saveBlob,
|
||||
})
|
||||
|
||||
expect(saveBlob).not.toHaveBeenCalled()
|
||||
expect(result.ok).toBe(false)
|
||||
expect(result).toEqual({
|
||||
ok: false,
|
||||
reason: 'server',
|
||||
status: 500,
|
||||
message: 'Kunde inte hämta mallarna. Försök igen.',
|
||||
})
|
||||
})
|
||||
|
||||
it('falls back to the status message when the error body is not JSON', async () => {
|
||||
globalThis.fetch = vi.fn().mockResolvedValue(
|
||||
new Response('<html>502 Bad Gateway</html>', {
|
||||
status: 502,
|
||||
headers: { 'Content-Type': 'text/html' },
|
||||
}),
|
||||
)
|
||||
const saveBlob = vi.fn()
|
||||
|
||||
const result = await downloadFile({ url: '/x', filename: 'f.json', saveBlob })
|
||||
|
||||
expect(saveBlob).not.toHaveBeenCalled()
|
||||
expect(result).toEqual({
|
||||
ok: false,
|
||||
reason: 'server',
|
||||
status: 502,
|
||||
message: 'Servern är tillfälligt otillgänglig. Försök igen om en stund.',
|
||||
})
|
||||
})
|
||||
|
||||
it('reports a server error in English for an English UI', async () => {
|
||||
globalThis.fetch = vi.fn().mockResolvedValue(
|
||||
jsonResponse({ error: { code: 'INTERNAL_ERROR', message: 'Ett oväntat serverfel uppstod.' } }, 500),
|
||||
)
|
||||
const saveBlob = vi.fn()
|
||||
|
||||
const result = await downloadFile({
|
||||
url: '/x',
|
||||
filename: 'f.json',
|
||||
locale: 'en',
|
||||
saveBlob,
|
||||
})
|
||||
|
||||
expect(saveBlob).not.toHaveBeenCalled()
|
||||
expect(result).toMatchObject({ ok: false, reason: 'server', message: 'Internal server error.' })
|
||||
})
|
||||
|
||||
it('writes NO file when the request throws', async () => {
|
||||
globalThis.fetch = vi.fn().mockRejectedValue(new TypeError('fetch failed'))
|
||||
const saveBlob = vi.fn()
|
||||
|
||||
const result = await downloadFile({ url: '/x', filename: 'f.json', saveBlob })
|
||||
|
||||
expect(saveBlob).not.toHaveBeenCalled()
|
||||
expect(result).toEqual({
|
||||
ok: false,
|
||||
reason: 'network',
|
||||
message: 'Något gick fel. Försök igen.',
|
||||
})
|
||||
})
|
||||
|
||||
it('writes NO file when the body is truncated mid-read', async () => {
|
||||
const res = new Response(EXPORT_BODY, { status: 200 })
|
||||
vi.spyOn(res, 'blob').mockRejectedValue(new TypeError('network error'))
|
||||
globalThis.fetch = vi.fn().mockResolvedValue(res)
|
||||
const saveBlob = vi.fn()
|
||||
|
||||
const result = await downloadFile({ url: '/x', filename: 'f.json', saveBlob })
|
||||
|
||||
expect(saveBlob).not.toHaveBeenCalled()
|
||||
expect(result).toMatchObject({ ok: false, reason: 'network' })
|
||||
})
|
||||
|
||||
it('reports a hung request as a timeout, not as a generic failure', async () => {
|
||||
globalThis.fetch = hangingFetch()
|
||||
const saveBlob = vi.fn()
|
||||
|
||||
const result = await downloadFile({
|
||||
url: '/x',
|
||||
filename: 'f.json',
|
||||
timeoutMs: 20,
|
||||
saveBlob,
|
||||
})
|
||||
|
||||
expect(saveBlob).not.toHaveBeenCalled()
|
||||
expect(result).toEqual({ ok: false, reason: 'timeout' })
|
||||
// The call site branches on this to say "took too long" instead of the
|
||||
// generic "something went wrong".
|
||||
expect(result).not.toMatchObject({ reason: 'network' })
|
||||
})
|
||||
|
||||
it('passes the deadline to fetch as an abort signal', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse(EXPORT_BODY))
|
||||
globalThis.fetch = fetchMock
|
||||
|
||||
await downloadFile({ url: '/x', filename: 'f.json', saveBlob: vi.fn() })
|
||||
|
||||
const init = fetchMock.mock.calls[0][1] as RequestInit
|
||||
expect(init.signal).toBeInstanceOf(AbortSignal)
|
||||
expect(DOWNLOAD_TIMEOUT_MS).toBe(15_000)
|
||||
})
|
||||
})
|
||||
|
||||
describe('saveBlobToDisk', () => {
|
||||
const originalCreateObjectURL = URL.createObjectURL
|
||||
const originalRevokeObjectURL = URL.revokeObjectURL
|
||||
|
||||
function stubDom() {
|
||||
const anchor = { href: '', download: '', rel: '', click: vi.fn(), remove: vi.fn() }
|
||||
const body = { appendChild: vi.fn() }
|
||||
;(globalThis as Record<string, unknown>).document = {
|
||||
createElement: vi.fn(() => anchor),
|
||||
body,
|
||||
}
|
||||
const createObjectURL = vi.fn(() => 'blob:test-url')
|
||||
const revokeObjectURL = vi.fn()
|
||||
URL.createObjectURL = createObjectURL as typeof URL.createObjectURL
|
||||
URL.revokeObjectURL = revokeObjectURL as typeof URL.revokeObjectURL
|
||||
return { anchor, body, revokeObjectURL }
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
delete (globalThis as Record<string, unknown>).document
|
||||
URL.createObjectURL = originalCreateObjectURL
|
||||
URL.revokeObjectURL = originalRevokeObjectURL
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('defers object-URL revocation so the browser can finish reading the blob', () => {
|
||||
// Revoking synchronously in a finally right after a.click() can abort the
|
||||
// save in Firefox/Safari: the click only STARTS the download.
|
||||
vi.useFakeTimers()
|
||||
const { anchor, revokeObjectURL } = stubDom()
|
||||
|
||||
saveBlobToDisk(new Blob(['x']), 'f.json')
|
||||
|
||||
expect(anchor.click).toHaveBeenCalledTimes(1)
|
||||
expect(revokeObjectURL).not.toHaveBeenCalled()
|
||||
|
||||
vi.advanceTimersByTime(OBJECT_URL_REVOKE_DELAY_MS - 1)
|
||||
expect(revokeObjectURL).not.toHaveBeenCalled()
|
||||
|
||||
vi.advanceTimersByTime(1)
|
||||
expect(revokeObjectURL).toHaveBeenCalledTimes(1)
|
||||
expect(revokeObjectURL).toHaveBeenCalledWith('blob:test-url')
|
||||
})
|
||||
|
||||
it('revokes immediately when the click never happened', () => {
|
||||
// Nothing is reading the URL if the DOM threw before the click, so the
|
||||
// blob memory is released right away instead of leaking for 10 seconds.
|
||||
vi.useFakeTimers()
|
||||
const { body, revokeObjectURL } = stubDom()
|
||||
body.appendChild.mockImplementation(() => {
|
||||
throw new Error('detached document')
|
||||
})
|
||||
|
||||
expect(() => saveBlobToDisk(new Blob(['x']), 'f.json')).toThrow('detached document')
|
||||
expect(revokeObjectURL).toHaveBeenCalledTimes(1)
|
||||
expect(revokeObjectURL).toHaveBeenCalledWith('blob:test-url')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,157 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { postAction, POST_ACTION_TIMEOUT_MS } from '@/lib/browser/post-action'
|
||||
|
||||
const originalFetch = globalThis.fetch
|
||||
|
||||
const MARK_PAID_URL = '/api/skatteverket/tax-payments/2026-04/mark-paid'
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
|
||||
/** A fetch that never resolves and rejects the way the platform does on abort. */
|
||||
function hangingFetch() {
|
||||
return vi.fn((_url: unknown, init?: RequestInit) => {
|
||||
return new Promise<Response>((_resolve, reject) => {
|
||||
init?.signal?.addEventListener('abort', () => {
|
||||
const err = new Error('The operation was aborted due to timeout')
|
||||
err.name = 'TimeoutError'
|
||||
reject(err)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
globalThis.fetch = originalFetch
|
||||
})
|
||||
|
||||
describe('postAction', () => {
|
||||
it('reports success on 2xx without reading the body', async () => {
|
||||
const res = jsonResponse({ data: { ok: true } })
|
||||
const jsonSpy = vi.spyOn(res, 'json')
|
||||
globalThis.fetch = vi.fn().mockResolvedValue(res)
|
||||
|
||||
const result = await postAction({ url: MARK_PAID_URL })
|
||||
|
||||
expect(result).toEqual({ ok: true })
|
||||
// The success shape is the route's business, not the button's.
|
||||
expect(jsonSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('sends POST', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ data: { ok: true } }))
|
||||
globalThis.fetch = fetchMock
|
||||
|
||||
await postAction({ url: MARK_PAID_URL })
|
||||
|
||||
const init = fetchMock.mock.calls[0][1] as RequestInit
|
||||
expect(init.method).toBe('POST')
|
||||
})
|
||||
|
||||
it('reports the envelope message on 404', async () => {
|
||||
// The regression guard for the missing catch: this used to be the only
|
||||
// branch that spoke to the user at all.
|
||||
globalThis.fetch = vi
|
||||
.fn()
|
||||
.mockResolvedValue(jsonResponse({ error: 'Ingen AGI för perioden 2026-04.' }, 404))
|
||||
|
||||
const result = await postAction({ url: MARK_PAID_URL })
|
||||
|
||||
expect(result).toEqual({
|
||||
ok: false,
|
||||
reason: 'server',
|
||||
status: 404,
|
||||
// The plain-string envelope this route emits is not recognized as a
|
||||
// finished user sentence, so the status map answers: same text the old
|
||||
// inline getErrorMessage(result, { statusCode }) produced.
|
||||
message: 'Resursen kunde inte hittas.',
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps a Swedish server message verbatim', async () => {
|
||||
globalThis.fetch = vi
|
||||
.fn()
|
||||
.mockResolvedValue(jsonResponse({ error: 'Kunde inte markera som betald. Försök igen.' }, 500))
|
||||
|
||||
const result = await postAction({ url: MARK_PAID_URL })
|
||||
|
||||
expect(result).toMatchObject({
|
||||
reason: 'server',
|
||||
status: 500,
|
||||
message: 'Kunde inte markera som betald. Försök igen.',
|
||||
})
|
||||
})
|
||||
|
||||
it('falls back to the status message when the error body is not JSON', async () => {
|
||||
globalThis.fetch = vi.fn().mockResolvedValue(
|
||||
new Response('<html>502 Bad Gateway</html>', {
|
||||
status: 502,
|
||||
headers: { 'Content-Type': 'text/html' },
|
||||
}),
|
||||
)
|
||||
|
||||
const result = await postAction({ url: MARK_PAID_URL })
|
||||
|
||||
expect(result).toEqual({
|
||||
ok: false,
|
||||
reason: 'server',
|
||||
status: 502,
|
||||
message: 'Servern är tillfälligt otillgänglig. Försök igen om en stund.',
|
||||
})
|
||||
})
|
||||
|
||||
it('reports a server error in English for an English UI', async () => {
|
||||
globalThis.fetch = vi
|
||||
.fn()
|
||||
.mockResolvedValue(jsonResponse({ error: { code: 'INTERNAL_ERROR', message: 'Serverfel' } }, 500))
|
||||
|
||||
const result = await postAction({ url: MARK_PAID_URL, locale: 'en' })
|
||||
|
||||
expect(result).toMatchObject({ reason: 'server', message: 'Internal server error.' })
|
||||
})
|
||||
|
||||
it('reports a thrown request as a network failure, not as success', async () => {
|
||||
// The finding: with try/finally and no catch this rejection escaped as an
|
||||
// unhandled rejection and the user was told nothing at all.
|
||||
globalThis.fetch = vi.fn().mockRejectedValue(new TypeError('fetch failed'))
|
||||
|
||||
const result = await postAction({ url: MARK_PAID_URL })
|
||||
|
||||
expect(result).toEqual({
|
||||
ok: false,
|
||||
reason: 'network',
|
||||
message: 'Något gick fel. Försök igen.',
|
||||
})
|
||||
})
|
||||
|
||||
it('reports a hung request as a timeout, not as a generic failure', async () => {
|
||||
globalThis.fetch = hangingFetch()
|
||||
|
||||
const result = await postAction({ url: MARK_PAID_URL, timeoutMs: 20 })
|
||||
|
||||
// A timeout on a write is ambiguous (the update may have landed), so the
|
||||
// call site needs to tell it apart to say "reload and check".
|
||||
expect(result).toEqual({ ok: false, reason: 'timeout' })
|
||||
})
|
||||
|
||||
it('bounds the request with an abort signal on the default deadline', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ data: { ok: true } }))
|
||||
globalThis.fetch = fetchMock
|
||||
|
||||
await postAction({ url: MARK_PAID_URL })
|
||||
|
||||
const init = fetchMock.mock.calls[0][1] as RequestInit
|
||||
expect(init.signal).toBeInstanceOf(AbortSignal)
|
||||
// Never shorter than the download deadline: aborting a mutation early
|
||||
// reports a failure for a write that may have landed.
|
||||
expect(POST_ACTION_TIMEOUT_MS).toBe(15_000)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* The three ways a click that talks to the server can fail, and the one
|
||||
* sentence the user gets for each.
|
||||
*
|
||||
* Shared by `downloadFile` (whose failure arms are structurally identical) and
|
||||
* `postAction`, so a panel that has both a "generate the file" button and a
|
||||
* "mark it paid" button describes both kinds of failure the same way.
|
||||
*
|
||||
* Exactly one sentence, never two: TOAST_LIMIT is 1
|
||||
* (components/ui/use-toast.tsx), so a second toast emitted in the same tick
|
||||
* evicts the first and only the last one is ever rendered. A handler that
|
||||
* wants to report a failure must therefore report it once, completely.
|
||||
*/
|
||||
|
||||
export type ActionFailure =
|
||||
/** The deadline passed. Nothing was saved and nothing was reported back. */
|
||||
| { ok: false; reason: 'timeout' }
|
||||
/** The server answered non-2xx. `message` is the envelope's own message when it carries one. */
|
||||
| { ok: false; reason: 'server'; status: number; message: string }
|
||||
/** The request never completed (offline, DNS, connection reset, truncated body). */
|
||||
| { ok: false; reason: 'network'; message: string }
|
||||
|
||||
export interface ActionFailureCopy {
|
||||
/** Say the request took too long. "Something went wrong" is not actionable; "it timed out, try again" is. */
|
||||
timeout: string
|
||||
/** Say the browser never reached the server, so the user checks the connection instead of the data. */
|
||||
network: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick the single description for a failed click.
|
||||
*
|
||||
* A `server` failure keeps the server's own message: the route knows exactly
|
||||
* why it refused (bankgiro missing from company settings, the salary run is
|
||||
* not approved yet), and no copy the panel could supply comes close.
|
||||
*
|
||||
* The two client-side reasons take the caller's copy instead. `getErrorMessage`
|
||||
* has nothing better than the generic "Något gick fel" for a fetch that never
|
||||
* produced a response, and that sentence cannot tell a user whose request timed
|
||||
* out (retry, and the artefact may already have been generated server-side)
|
||||
* apart from one whose browser is offline (fix the connection first). The
|
||||
* discriminated union already separates them, so the copy should too.
|
||||
*/
|
||||
export function failureDescription(
|
||||
failure: ActionFailure,
|
||||
copy: ActionFailureCopy,
|
||||
): string {
|
||||
switch (failure.reason) {
|
||||
case 'timeout':
|
||||
return copy.timeout
|
||||
case 'network':
|
||||
return copy.network
|
||||
case 'server':
|
||||
return failure.message
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Copy text to the clipboard and report honestly whether it worked.
|
||||
*
|
||||
* Why: `navigator.clipboard.writeText` rejects for ordinary, non-exceptional
|
||||
* reasons (insecure context on plain http, a Permissions-Policy that blocks
|
||||
* clipboard-write, the document having lost focus) and the API is absent
|
||||
* entirely in older or hardened browsers. A copy button that swallows the
|
||||
* rejection, or that never awaits it before flipping to a check mark, tells
|
||||
* the user "copied" when nothing was copied. On a one-time secret (an API key
|
||||
* shown once, a TOTP enrolment key) that turns a recoverable click into an
|
||||
* unrecoverable one: the key is gone and every integration has to be
|
||||
* re-pointed at a new one.
|
||||
*
|
||||
* Callers must render a visible failure state and keep the text on screen as
|
||||
* selectable content. No clipboard means no programmatic fallback either, so
|
||||
* manual selection is the only fallback that actually works.
|
||||
*
|
||||
* Call this as the first `await` in a click handler: a clipboard write issued
|
||||
* after some other await runs outside the click's transient user activation
|
||||
* and is rejected on that ground alone.
|
||||
*/
|
||||
export type CopyResult =
|
||||
/** The write resolved: the text is on the clipboard. */
|
||||
| 'copied'
|
||||
/** No Clipboard API at all (SSR, pre-2018 browser, stripped navigator). */
|
||||
| 'unavailable'
|
||||
/** The API exists but the write was rejected (permissions, focus, http). */
|
||||
| 'failed'
|
||||
|
||||
export async function copyToClipboard(text: string): Promise<CopyResult> {
|
||||
const clipboard =
|
||||
typeof navigator !== 'undefined'
|
||||
? (navigator.clipboard as Clipboard | undefined)
|
||||
: undefined
|
||||
|
||||
if (!clipboard || typeof clipboard.writeText !== 'function') {
|
||||
return 'unavailable'
|
||||
}
|
||||
|
||||
try {
|
||||
await clipboard.writeText(text)
|
||||
return 'copied'
|
||||
} catch {
|
||||
return 'failed'
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
/**
|
||||
* Fetch a server-generated file and save it to disk only if the server
|
||||
* actually produced one.
|
||||
*
|
||||
* Why: the download boilerplate that repeats across the app reads
|
||||
* `await res.blob()` straight after `fetch`, with no `res.ok` check. A failing
|
||||
* route answers with a JSON error envelope, and `blob()` happily wraps that
|
||||
* envelope. The anchor click then writes it to disk under the real file's
|
||||
* name, so the user ends up holding `bokforingsmallar.json` (or an .sie, or a
|
||||
* .zip) that contains `{"error":{"code":"INTERNAL_ERROR",...}}` while the UI
|
||||
* reports nothing at all. That file looks like an export, gets filed as a
|
||||
* backup, gets mailed to an accountant, and only fails much later when someone
|
||||
* tries to import it.
|
||||
*
|
||||
* Content-Type cannot be used to tell the two apart: a JSON export and a JSON
|
||||
* error envelope are both `application/json`, and a 500 from a route that
|
||||
* streams a ZIP is still JSON. `res.ok` is the only honest discriminator, so
|
||||
* the status is checked before the body is ever turned into a blob.
|
||||
*
|
||||
* The request is also bounded. An unbounded artefact fetch on a click leaves
|
||||
* the button spinning forever when a serverless instance hangs, and the user's
|
||||
* only recourse is to click again.
|
||||
*
|
||||
* The result is a discriminated union rather than a thrown error so the call
|
||||
* site can pick exactly one truthful message. That matters here: TOAST_LIMIT
|
||||
* is 1 (components/ui/use-toast.tsx), so two toasts emitted in the same tick
|
||||
* leave the user seeing only the last one.
|
||||
*/
|
||||
|
||||
import { fetchWithTimeout, isTimeoutError } from '@/lib/http/fetch-with-timeout'
|
||||
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
|
||||
|
||||
/**
|
||||
* Default deadline for an interactive artefact download.
|
||||
*
|
||||
* These payloads are small (a JSON export, a declaration file) and produced by
|
||||
* a single indexed query, so the realistic worst case is a serverless cold
|
||||
* start plus one eu-north-1 round trip: a few seconds. 15s leaves several times
|
||||
* that headroom, so we never abort a request that was about to succeed, while
|
||||
* still ending the spinner soon enough after the ~10s mark where the user has
|
||||
* already concluded the app is dead. Callers that generate genuinely heavy
|
||||
* artefacts (full-archive ZIPs) should pass a larger `timeoutMs`.
|
||||
*/
|
||||
export const DOWNLOAD_TIMEOUT_MS = 15_000
|
||||
|
||||
export type DownloadFileResult =
|
||||
/** 2xx and a complete body: the file was handed to the browser. */
|
||||
| { ok: true; filename: string }
|
||||
/** The deadline passed. Nothing was saved; report it as a timeout, not as a generic failure. */
|
||||
| { ok: false; reason: 'timeout' }
|
||||
/** The server answered non-2xx. `message` is the envelope's own message when it carries one. */
|
||||
| { ok: false; reason: 'server'; status: number; message: string }
|
||||
/** The request never completed (offline, DNS, connection reset, truncated body). */
|
||||
| { ok: false; reason: 'network'; message: string }
|
||||
|
||||
export interface DownloadFileOptions {
|
||||
url: string
|
||||
/** Name the file is saved under. */
|
||||
filename: string
|
||||
/** UI locale, so a server error is reported in the language the user reads. */
|
||||
locale?: ErrorLocale
|
||||
timeoutMs?: number
|
||||
/** Seam for tests; defaults to the DOM anchor implementation below. */
|
||||
saveBlob?: (blob: Blob, filename: string) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* How long the object URL outlives the click before it is revoked.
|
||||
*
|
||||
* Revoking synchronously right after `a.click()` can abort the save in
|
||||
* Firefox and Safari: the click only STARTS the download, and the browser may
|
||||
* still be reading from the blob URL when it is revoked. 10 seconds is far
|
||||
* beyond any realistic gap between the click and the browser opening its own
|
||||
* handle on the blob, while still guaranteeing the URL (and the blob memory
|
||||
* it pins) is released.
|
||||
*/
|
||||
export const OBJECT_URL_REVOKE_DELAY_MS = 10_000
|
||||
|
||||
/**
|
||||
* Hand a blob to the browser as a download.
|
||||
*
|
||||
* The anchor is attached to the document before it is clicked: a detached
|
||||
* anchor is ignored by some browsers, which turns the download into a silent
|
||||
* no-op.
|
||||
*/
|
||||
export function saveBlobToDisk(blob: Blob, filename: string): void {
|
||||
const url = URL.createObjectURL(blob)
|
||||
let clicked = false
|
||||
try {
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = filename
|
||||
a.rel = 'noopener'
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
clicked = true
|
||||
a.remove()
|
||||
} finally {
|
||||
if (clicked) {
|
||||
// The download started: defer revocation so the browser can finish
|
||||
// reading the blob (see OBJECT_URL_REVOKE_DELAY_MS).
|
||||
setTimeout(() => URL.revokeObjectURL(url), OBJECT_URL_REVOKE_DELAY_MS)
|
||||
} else {
|
||||
// The click never happened (DOM threw): nothing is reading the URL,
|
||||
// so release it immediately rather than leaking it for 10 seconds.
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function downloadFile({
|
||||
url,
|
||||
filename,
|
||||
locale = 'sv',
|
||||
timeoutMs = DOWNLOAD_TIMEOUT_MS,
|
||||
saveBlob = saveBlobToDisk,
|
||||
}: DownloadFileOptions): Promise<DownloadFileResult> {
|
||||
let blob: Blob
|
||||
|
||||
try {
|
||||
const res = await fetchWithTimeout(
|
||||
url,
|
||||
{ method: 'GET' },
|
||||
{ timeoutMs, description: `download ${filename}` },
|
||||
)
|
||||
|
||||
if (!res.ok) {
|
||||
// Read the body only now that we know it is not the file. A body that is
|
||||
// not JSON (an HTML error page, an empty 502) leaves `null`, and
|
||||
// getErrorMessage falls back to the status map.
|
||||
const body = await res.json().catch(() => null)
|
||||
return {
|
||||
ok: false,
|
||||
reason: 'server',
|
||||
status: res.status,
|
||||
message: getErrorMessage(body, { statusCode: res.status, locale }),
|
||||
}
|
||||
}
|
||||
|
||||
blob = await res.blob()
|
||||
} catch (err) {
|
||||
if (isTimeoutError(err)) return { ok: false, reason: 'timeout' }
|
||||
return { ok: false, reason: 'network', message: getErrorMessage(err, { locale }) }
|
||||
}
|
||||
|
||||
// Only reached with a 2xx and a body that was read in full.
|
||||
saveBlob(blob, filename)
|
||||
return { ok: true, filename }
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* Fire a state-changing POST from a click and report exactly why it failed.
|
||||
*
|
||||
* Why this lives next to `downloadFile`: the same try/finally-with-no-catch
|
||||
* shape that silently swallowed download failures also sits on the mutation
|
||||
* buttons beside them, and `downloadFile` cannot serve those (it exists to save
|
||||
* a blob). The result union is deliberately the same one, so a panel maps a
|
||||
* failed download and a failed mutation through a single `failureDescription`.
|
||||
*
|
||||
* The request is bounded for the same reason a download is: an unbounded POST
|
||||
* on a click leaves the button spinning forever when a serverless instance
|
||||
* hangs, and the user's only recourse is to click again, which is the one thing
|
||||
* you least want on a mutation.
|
||||
*
|
||||
* The success body is deliberately not parsed. `res.ok` is the whole contract:
|
||||
* validating a success shape would couple every button to its route's payload,
|
||||
* and the server has already committed the write by the time it flushes
|
||||
* headers, so a body that never finishes arriving would not change the outcome.
|
||||
*/
|
||||
|
||||
import { fetchWithTimeout, isTimeoutError } from '@/lib/http/fetch-with-timeout'
|
||||
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
|
||||
import type { ActionFailure } from './action-failure'
|
||||
|
||||
/**
|
||||
* Deadline for an interactive mutation.
|
||||
*
|
||||
* Same realistic worst case as an artefact download: a serverless cold start
|
||||
* plus one eu-north-1 round trip, a few seconds. It is deliberately no shorter
|
||||
* than DOWNLOAD_TIMEOUT_MS, because aborting a mutation early reports a failure
|
||||
* for a write that may well have landed, and that ambiguity is worse than a few
|
||||
* extra seconds of spinner.
|
||||
*/
|
||||
export const POST_ACTION_TIMEOUT_MS = 15_000
|
||||
|
||||
export type PostActionResult = { ok: true } | ActionFailure
|
||||
|
||||
export interface PostActionOptions {
|
||||
url: string
|
||||
/** UI locale, so a server error is reported in the language the user reads. */
|
||||
locale?: ErrorLocale
|
||||
timeoutMs?: number
|
||||
}
|
||||
|
||||
export async function postAction({
|
||||
url,
|
||||
locale = 'sv',
|
||||
timeoutMs = POST_ACTION_TIMEOUT_MS,
|
||||
}: PostActionOptions): Promise<PostActionResult> {
|
||||
try {
|
||||
const res = await fetchWithTimeout(
|
||||
url,
|
||||
{ method: 'POST' },
|
||||
{ timeoutMs, description: `post ${url}` },
|
||||
)
|
||||
|
||||
if (!res.ok) {
|
||||
// A body that is not JSON (an HTML error page, an empty 502) leaves
|
||||
// `null`, and getErrorMessage falls back to the status map.
|
||||
const body = await res.json().catch(() => null)
|
||||
return {
|
||||
ok: false,
|
||||
reason: 'server',
|
||||
status: res.status,
|
||||
message: getErrorMessage(body, { statusCode: res.status, locale }),
|
||||
}
|
||||
}
|
||||
|
||||
return { ok: true }
|
||||
} catch (err) {
|
||||
if (isTimeoutError(err)) return { ok: false, reason: 'timeout' }
|
||||
return { ok: false, reason: 'network', message: getErrorMessage(err, { locale }) }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user