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

Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i
server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma
strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
2026-11-10 09:37:22 +01:00
parent 077251ac94
commit e7f0070e84
6135 changed files with 1718997 additions and 4 deletions
@@ -0,0 +1,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,96 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { openDeferredTab } from '@/lib/browser/deferred-tab'
function makeFakeTab() {
return {
closed: false,
opener: {} as unknown,
close: vi.fn(),
location: { href: '' },
document: {
title: '',
body: { appendChild: vi.fn() },
createElement: vi.fn(() => ({ textContent: '', style: { cssText: '' } })),
},
}
}
beforeEach(() => {
vi.clearAllMocks()
vi.unstubAllGlobals()
})
afterEach(() => {
vi.unstubAllGlobals()
})
describe('openDeferredTab', () => {
it('is SSR-safe: reports blocked when window is undefined', () => {
const tab = openDeferredTab()
expect(tab.blocked).toBe(true)
expect(tab.navigate('https://example.com')).toBe(false)
expect(() => tab.close()).not.toThrow()
})
it('reports blocked and refuses navigation when window.open returns null', () => {
vi.stubGlobal('window', { open: vi.fn(() => null) })
const tab = openDeferredTab('Laddar...')
expect(tab.blocked).toBe(true)
expect(tab.navigate('https://example.com')).toBe(false)
expect(() => tab.close()).not.toThrow()
})
it('opens synchronously, severs opener, and navigates the pending tab', () => {
const fake = makeFakeTab()
const open = vi.fn(() => fake)
vi.stubGlobal('window', { open })
const tab = openDeferredTab('Genererar...')
expect(open).toHaveBeenCalledWith('', '_blank')
expect(tab.blocked).toBe(false)
expect(fake.opener).toBeNull()
expect(fake.document.title).toBe('Genererar...')
expect(fake.document.body.appendChild).toHaveBeenCalledTimes(1)
expect(tab.navigate('blob:https://app/abc')).toBe(true)
expect(fake.location.href).toBe('blob:https://app/abc')
})
it('skips the placeholder when none is given', () => {
const fake = makeFakeTab()
vi.stubGlobal('window', { open: vi.fn(() => fake) })
openDeferredTab()
expect(fake.document.body.appendChild).not.toHaveBeenCalled()
expect(fake.document.title).toBe('')
})
it('fails navigation once the user closed the pending tab', () => {
const fake = makeFakeTab()
vi.stubGlobal('window', { open: vi.fn(() => fake) })
const tab = openDeferredTab()
fake.closed = true
expect(tab.navigate('https://example.com')).toBe(false)
})
it('close() closes an open tab and is a no-op afterwards', () => {
const fake = makeFakeTab()
vi.stubGlobal('window', { open: vi.fn(() => fake) })
const tab = openDeferredTab()
tab.close()
expect(fake.close).toHaveBeenCalledTimes(1)
fake.closed = true
tab.close()
expect(fake.close).toHaveBeenCalledTimes(1)
})
it('survives a placeholder document that throws', () => {
const fake = makeFakeTab()
fake.document.createElement = vi.fn(() => {
throw new Error('detached')
})
vi.stubGlobal('window', { open: vi.fn(() => fake) })
const tab = openDeferredTab('Laddar...')
expect(tab.blocked).toBe(false)
expect(tab.navigate('https://example.com')).toBe(true)
})
})
+243
View File
@@ -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')
})
})
+157
View File
@@ -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 route's own Swedish sentence is shown as-is (issue #2086): it
// used to be dropped for lacking one of getErrorMessage's keywords and
// replaced by the status map's "Resursen kunde inte hittas.".
message: 'Ingen AGI för perioden 2026-04.',
})
})
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)
})
})
+56
View File
@@ -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
}
}
+46
View File
@@ -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'
}
}
+69
View File
@@ -0,0 +1,69 @@
/**
* Pre-open a browser tab inside a click handler, then point it at a URL once
* an async result arrives.
*
* Why: window.open() called after an `await` runs outside the click's
* transient user activation. Browsers expire that activation after ~5 seconds
* (Safari sooner), so popup blocking kicks in exactly when the request is
* slow: a cold serverless start made "Förhandsgranska PDF" silently do
* nothing (support: cbysea.se). Opening the tab synchronously keeps the
* trusted gesture; the tab is then navigated to the real URL, or closed again
* if the request fails. Same pattern as AGIPanel's signing tab.
*/
export interface DeferredTab {
/** True when even the synchronous open was blocked (strict popup blocker). */
blocked: boolean
/** Point the pending tab at the final URL. False if the tab is gone. */
navigate(url: string): boolean
/** Close the pending tab; call on request failure so no blank tab lingers. */
close(): void
}
/**
* Must be called synchronously from a user-gesture handler (click), before
* any `await`, or the open is popup-blocked in the exact slow cases this
* helper exists for.
*/
export function openDeferredTab(placeholder?: string): DeferredTab {
const tab = typeof window !== 'undefined' ? window.open('', '_blank') : null
if (tab) {
try {
// Sever the reverse channel up front: the final page never gets a
// window.opener, preserving the noopener semantics the direct
// window.open(url, '_blank', 'noopener') call sites had.
tab.opener = null
if (placeholder) {
tab.document.title = placeholder
const note = tab.document.createElement('p')
note.textContent = placeholder
note.style.cssText =
'font-family: system-ui, sans-serif; color: #666; padding: 24px;'
tab.document.body.appendChild(note)
}
} catch {
// The placeholder is cosmetic; never let it break the open.
}
}
return {
blocked: tab === null,
navigate(url: string): boolean {
if (!tab || tab.closed) return false
try {
tab.location.href = url
return true
} catch {
return false
}
},
close() {
try {
if (tab && !tab.closed) tab.close()
} catch {
// Already gone; nothing to clean up.
}
},
}
}
+149
View File
@@ -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 }
}
+112
View File
@@ -0,0 +1,112 @@
/**
* The settings panels' server calls (Stripe, Shopify, WooCommerce), each
* classified into exactly one outcome. Never throws: every arm resolves to a
* member of the union, so a call site cannot have a silent path by forgetting
* a `catch`. One toast sentence per click; the classification lives outside
* the component because component logic has no tests in this repo.
*/
import { fetchWithTimeout, isTimeoutError } from '@/lib/http/fetch-with-timeout'
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
import type { ActionFailure } from '@/lib/browser/action-failure'
/** Deadline for the quick calls (status, toggle, disconnect). */
export const PANEL_ACTION_TIMEOUT_MS = 15_000
export type PanelRequestResult<T> =
/** 2xx. `data` is null when the body was not readable JSON. */
| { ok: true; data: T | null }
| ActionFailure
export interface PanelRequestOptions {
url: string
/** Defaults to POST: most of the panel calls are mutations. */
method?: 'GET' | 'POST' | 'DELETE'
/** JSON request body. Omitted entirely for the routes that ignore it. */
body?: unknown
/** UI locale, so a server error is reported in the language the user reads. */
locale?: ErrorLocale
timeoutMs?: number
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null
}
/**
* The one sentence for a non-2xx.
*
* The extension routes refuse with a hand-written Swedish sentence in
* `{ error }`, and that sentence is the most specific thing anyone can say:
* "Inget anslutet Stripe-konto." tells the user to reconnect, where the status
* map's "Resursen kunde inte hittas." tells them nothing. `getErrorMessage`
* keeps such a sentence only when it happens to carry one of its Swedish
* trigger words, which this route copy does not, so the string is preferred
* explicitly.
*
* `error_en` is honoured first for an English UI because the shared capability
* guard emits both (`capabilityBlockedResponse` in
* lib/entitlements/has-capability.ts), and `getErrorMessage` only reads
* `message_en` inside a structured envelope, not a top-level `error_en`.
*
* Everything else is `getErrorMessage`'s: a structured envelope, an HTML 502
* from the platform, a body that never parsed.
*/
export function serverErrorMessage(
body: unknown,
status: number,
locale: ErrorLocale,
): string {
if (isRecord(body)) {
if (locale === 'en' && typeof body.error_en === 'string' && body.error_en.trim()) {
return body.error_en.trim()
}
if (typeof body.error === 'string' && body.error.trim()) {
return body.error.trim()
}
}
return getErrorMessage(body, { statusCode: status, locale })
}
/** Call one of a panel's endpoints and report exactly why it failed. */
export async function panelRequest<T>({
url,
method = 'POST',
body,
locale = 'sv',
timeoutMs = PANEL_ACTION_TIMEOUT_MS,
}: PanelRequestOptions): Promise<PanelRequestResult<T>> {
try {
const res = await fetchWithTimeout(
url,
body === undefined
? { method }
: {
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
},
{ timeoutMs, description: `${method} ${url}` },
)
// Read the body on both arms: the failure arm needs the route's own
// sentence, the success arm needs the sync counts. A body that is not JSON
// (an HTML error page, an empty 502, a response truncated mid-stream) leaves
// null, and neither arm then claims anything it cannot support.
const payload = await res.json().catch(() => null)
if (!res.ok) {
return {
ok: false,
reason: 'server',
status: res.status,
message: serverErrorMessage(payload, res.status, locale),
}
}
return { ok: true, data: payload as T | null }
} catch (err) {
if (isTimeoutError(err)) return { ok: false, reason: 'timeout' }
return { ok: false, reason: 'network', message: getErrorMessage(err, { locale }) }
}
}
+74
View File
@@ -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 }) }
}
}