* fix(invoices): embed company logo as PNG so it renders on invoice PDFs (#772) @react-pdf/renderer's <Image> only decodes JPG/PNG, but the logo upload route and the `logos` bucket also accept SVG and WebP. For an SVG/WebP logo @react-pdf silently swallows the decode error (console.warn inside a try/catch in its fetchImage step), so the invoice renders with NO logo and nothing surfaces — "Logotyp kommer inte med på fakturor". Fix: prepareInvoicePdfRender now fetches the stored logo and re-encodes it to a PNG data URL via sharp (SVGs rasterized at higher density), handing the template a company whose logo_url is that data URL. Renders regardless of upload format and removes the render-time dependency on a remote fetch inside @react-pdf. Falls back to the original URL unchanged on any failure (network, unreadable image, sharp unavailable), so behaviour is never worse than before. Result is cached per logo URL (5-min TTL, bounded to 50) since the logo is re-rendered on every invoice — twice per send and once per invoice in recurring/batch loops. prepareInvoicePdfRender becomes async and returns the resolved { branding, company }; all 8 call sites updated (6 routes, recurring-schedule-service, pending-operations/commit) to await it and pass the resolved company. Layered cleanly on top of the Swish-QR feature already on main — both coexist at every call site. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(invoices): bound and dedupe the logo fetch (review hardening) Review (PR Agent security): resolveLogoDataUrl fetched logo_url with no timeout or size limit. Add a 5s AbortSignal.timeout and a 5 MB cap (checked on the declared content-length and the read body) so a slow/oversized logo host can't hang or balloon an invoice render. SSRF itself isn't reachable today — logo_url is only ever set to a Supabase logos-bucket URL by the upload route — so an origin allowlist is intentionally skipped (would break self-hosted storage). Also coalesce concurrent renders of the same logo (preflight+final on a send, and recurring/batch loops) onto one in-flight fetch+encode instead of N. New test covers the size-cap fallback; existing SVG test now asserts the timeout signal. 9/9 pass. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
180 lines
6.4 KiB
TypeScript
180 lines
6.4 KiB
TypeScript
/**
|
|
* Regression tests for issue #772 — "Logotyp kommer inte med på fakturor".
|
|
*
|
|
* Root cause: @react-pdf/renderer's <Image> only decodes JPG/PNG, but the logo
|
|
* upload route and the `logos` bucket accept SVG and WebP. When a logo was an
|
|
* SVG/WebP, @react-pdf silently dropped it (it swallows the decode error in a
|
|
* try/catch), so invoices rendered with no logo and no error.
|
|
*
|
|
* Fix: prepareInvoicePdfRender fetches the stored logo and re-encodes it to a
|
|
* PNG data URL via sharp, so every supported upload format renders. These tests
|
|
* mock `fetch` and exercise the real sharp pipeline.
|
|
*/
|
|
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
import sharp from 'sharp'
|
|
import { prepareInvoicePdfRender } from '@/lib/invoices/pdf-render-helpers'
|
|
import { makeCompanySettings } from '@/tests/helpers'
|
|
|
|
const PNG_DATA_URL_PREFIX = 'data:image/png;base64,'
|
|
|
|
const SVG_LOGO = Buffer.from(
|
|
'<svg xmlns="http://www.w3.org/2000/svg" width="120" height="40">' +
|
|
'<rect width="120" height="40" fill="#1a1a1a"/>' +
|
|
'<text x="8" y="26" fill="#fff" font-size="18">ACME</text></svg>',
|
|
)
|
|
|
|
/** Build a one-shot fetch mock that returns the given bytes + content-type. */
|
|
function mockFetchOnce(buf: Buffer, contentType: string) {
|
|
const arrayBuffer = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
|
|
const fn = vi.fn().mockResolvedValue({
|
|
ok: true,
|
|
headers: { get: () => contentType },
|
|
arrayBuffer: async () => arrayBuffer,
|
|
})
|
|
vi.stubGlobal('fetch', fn)
|
|
return fn
|
|
}
|
|
|
|
/** A data: URL whose payload decodes to a valid PNG via sharp. */
|
|
async function expectValidEmbeddedPng(logoUrl: string | null | undefined) {
|
|
expect(logoUrl).toMatch(new RegExp(`^${PNG_DATA_URL_PREFIX}`))
|
|
const base64 = (logoUrl as string).slice(PNG_DATA_URL_PREFIX.length)
|
|
const meta = await sharp(Buffer.from(base64, 'base64')).metadata()
|
|
expect(meta.format).toBe('png')
|
|
}
|
|
|
|
describe('prepareInvoicePdfRender — logo resolution (issue #772)', () => {
|
|
beforeEach(() => {
|
|
vi.unstubAllGlobals()
|
|
})
|
|
afterEach(() => {
|
|
vi.unstubAllGlobals()
|
|
vi.restoreAllMocks()
|
|
})
|
|
|
|
it('embeds an SVG logo as a PNG data URL so @react-pdf can draw it', async () => {
|
|
const fetchMock = mockFetchOnce(SVG_LOGO, 'image/svg+xml')
|
|
const company = makeCompanySettings({
|
|
logo_url: 'https://example.test/svg-logo-1.svg',
|
|
})
|
|
|
|
const { company: resolved } = await prepareInvoicePdfRender(company)
|
|
|
|
// Fetched with a timeout signal so a slow logo host can't hang the render.
|
|
expect(fetchMock).toHaveBeenCalledWith(
|
|
'https://example.test/svg-logo-1.svg',
|
|
expect.objectContaining({ signal: expect.any(AbortSignal) }),
|
|
)
|
|
await expectValidEmbeddedPng(resolved.logo_url)
|
|
})
|
|
|
|
it('embeds a WebP logo as a PNG data URL', async () => {
|
|
const webp = await sharp(SVG_LOGO).webp().toBuffer()
|
|
mockFetchOnce(webp, 'image/webp')
|
|
const company = makeCompanySettings({
|
|
logo_url: 'https://example.test/webp-logo-1.webp',
|
|
})
|
|
|
|
const { company: resolved } = await prepareInvoicePdfRender(company)
|
|
|
|
await expectValidEmbeddedPng(resolved.logo_url)
|
|
})
|
|
|
|
it('re-encodes a PNG logo to an embedded data URL (no remote fetch at render time)', async () => {
|
|
const png = await sharp(SVG_LOGO).png().toBuffer()
|
|
mockFetchOnce(png, 'image/png')
|
|
const company = makeCompanySettings({
|
|
logo_url: 'https://example.test/png-logo-1.png',
|
|
})
|
|
|
|
const { company: resolved } = await prepareInvoicePdfRender(company)
|
|
|
|
await expectValidEmbeddedPng(resolved.logo_url)
|
|
})
|
|
|
|
it('falls back to the original URL when the logo fetch is not ok', async () => {
|
|
const fn = vi.fn().mockResolvedValue({
|
|
ok: false,
|
|
headers: { get: () => null },
|
|
arrayBuffer: async () => new ArrayBuffer(0),
|
|
})
|
|
vi.stubGlobal('fetch', fn)
|
|
const url = 'https://example.test/missing-logo.png'
|
|
const company = makeCompanySettings({ logo_url: url })
|
|
|
|
const { company: resolved } = await prepareInvoicePdfRender(company)
|
|
|
|
// Unchanged — never worse than before (@react-pdf still fetches PNG/JPEG).
|
|
expect(resolved.logo_url).toBe(url)
|
|
})
|
|
|
|
it('falls back to the original URL when the fetch throws', async () => {
|
|
vi.stubGlobal(
|
|
'fetch',
|
|
vi.fn().mockRejectedValue(new Error('network down')),
|
|
)
|
|
const url = 'https://example.test/network-error-logo.png'
|
|
const company = makeCompanySettings({ logo_url: url })
|
|
|
|
const { company: resolved } = await prepareInvoicePdfRender(company)
|
|
|
|
expect(resolved.logo_url).toBe(url)
|
|
})
|
|
|
|
it('falls back to the original URL when the logo exceeds the size cap', async () => {
|
|
// Declared content-length over the cap is rejected before reading the body.
|
|
const fn = vi.fn().mockResolvedValue({
|
|
ok: true,
|
|
headers: {
|
|
get: (h: string) =>
|
|
h.toLowerCase() === 'content-length' ? String(6 * 1024 * 1024) : 'image/png',
|
|
},
|
|
arrayBuffer: async () => new ArrayBuffer(0),
|
|
})
|
|
vi.stubGlobal('fetch', fn)
|
|
const url = 'https://example.test/oversized-logo.png'
|
|
const company = makeCompanySettings({ logo_url: url })
|
|
|
|
const { company: resolved } = await prepareInvoicePdfRender(company)
|
|
|
|
expect(fn).toHaveBeenCalled()
|
|
expect(resolved.logo_url).toBe(url)
|
|
})
|
|
|
|
it('does not fetch when no logo is configured', async () => {
|
|
const fetchMock = vi.fn()
|
|
vi.stubGlobal('fetch', fetchMock)
|
|
const company = makeCompanySettings({ logo_url: null })
|
|
|
|
const { company: resolved } = await prepareInvoicePdfRender(company)
|
|
|
|
expect(fetchMock).not.toHaveBeenCalled()
|
|
expect(resolved.logo_url).toBeNull()
|
|
})
|
|
|
|
it('passes through an already-embedded data: URL without fetching', async () => {
|
|
const fetchMock = vi.fn()
|
|
vi.stubGlobal('fetch', fetchMock)
|
|
const dataUrl = `${PNG_DATA_URL_PREFIX}iVBORw0KGgo=`
|
|
const company = makeCompanySettings({ logo_url: dataUrl })
|
|
|
|
const { company: resolved } = await prepareInvoicePdfRender(company)
|
|
|
|
expect(fetchMock).not.toHaveBeenCalled()
|
|
expect(resolved.logo_url).toBe(dataUrl)
|
|
})
|
|
|
|
it('still returns branding alongside the resolved company', async () => {
|
|
mockFetchOnce(SVG_LOGO, 'image/svg+xml')
|
|
const company = makeCompanySettings({
|
|
logo_url: 'https://example.test/branding-logo.svg',
|
|
invoice_primary_color: '#c2410c',
|
|
})
|
|
|
|
const { branding } = await prepareInvoicePdfRender(company)
|
|
|
|
expect(branding.primaryColor).toBe('#c2410c')
|
|
})
|
|
})
|