Files
accounted/lib/invoices/contrast-check.ts
T
MattssonandClaude Opus 4.7 32d9978f1b Fix/chrome pdf preview csp (#572)
* feat: add option to exclude year-end closing entries in SIE export and related reports

* delete docs

* fix: allow Chrome's PDF viewer in verifikat document preview

The /api/documents/:id/inline route shipped with
`object-src 'none'` in its CSP, which blocked Chrome's built-in PDF
viewer (it renders inline PDFs via an internal <embed>). Users on
Chrome saw "Det här innehållet har blockerats" when expanding a PDF
attachment in the bookkeeping view; Firefox (PDF.js) and Edge (own
viewer) were unaffected, and JPGs worked because <img> isn't subject
to object-src.

Drops the CSP for this route to the minimum needed for embeddability:
`frame-ancestors 'self'`. X-Content-Type-Options: nosniff plus the
fixed Content-Type from the handler already block MIME confusion;
X-Frame-Options: SAMEORIGIN + frame-ancestors still block clickjacking.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(auth): add webmail deep link to email confirmation screens

Mirrors Stripe's signup UX: after asking the user to verify their email,
detect their webmail provider from the domain and show a button that
opens the inbox in a new tab. Gmail gets a from:<sender> search
pre-populated; Outlook/Yahoo/iCloud/Proton open the inbox directly.
Unknown / custom domains fall back to the existing copy.

Sender address is configurable via NEXT_PUBLIC_BRANDING_AUTH_EMAIL_FROM
(default noreply@gnubok.se) so white-label installs can match their
Supabase Auth SMTP config.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(auth): unblock first-time password set for BankID users with MFA

Supabase rejects updateUser({password}) and mfa.unenroll with "AAL2 session
is required" whenever a TOTP factor is enrolled. BankID magic-link logins
produce AAL1, and middleware skips MFA enforcement for bankid_linked users,
so they had no path to AAL2 — leaving them unable to set a backup password
or disable MFA without going through the email-recovery escape hatch.

- /api/account/password: branch on app_metadata.has_password. First-time set
  writes via service.auth.admin.updateUserById (no existing credential to
  protect, AAL2 guard does not apply). Change-password keeps the user-session
  updateUser so AAL2 still fires for credential rotation.
- /mfa/verify: accept a safeReturnTo query param and route there after
  successful verify, so step-up flows can land back where they came from.
- SecuritySettings: detect the AAL2 error from both change-password and
  mfa.unenroll and redirect through /mfa/verify?returnTo=/settings/account
  instead of toasting a dead-end error.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* Add tests and rounding utility for öre precision in bokslut calculations

- Implemented `roundOre` function for rounding SEK amounts to two decimal places, ensuring consistent monetary calculations.
- Introduced `ORE_TOLERANCE` constant for comparing rounded amounts, facilitating invariant checks in financial entries.
- Created comprehensive tests for `roundOre`, covering typical cases, edge cases, and idempotency.
- Added year-end invariants tests to verify database-level guarantees for closing entries, ensuring they balance to the öre and reject discrepancies.
- Developed end-to-end tests for the dispositions chain, validating the correctness of calculations across various scenarios.

* fix: update PDF rendering to remove Swish QR code generation and set default to disable Swish visibility

* fix: enhance security by rejecting data URIs in safeReturnTo function tests

* fix: improve rounding logic in roundOre function and add customer_type migration

* fix: add customer_type column to customers and enforce CHECK constraint

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 22:29:41 +02:00

81 lines
2.7 KiB
TypeScript

/**
* WCAG 2.x contrast ratio helpers.
*
* Pure utility — no I/O. Used by the invoice branding settings UI to warn
* users when their chosen primary color would fail AA contrast against a
* white invoice background, and by the branding API to surface the same
* warning in the JSON response.
*
* Reference: WCAG 2.2 §1.4.3 (Contrast — Minimum). The 4.5:1 threshold
* applies to normal text (≤18pt, or ≤14pt bold). The PDF invoice renders
* text at 8-14pt, so 4.5:1 is the right threshold here.
*
* Formula:
* L = 0.2126 * R_lin + 0.7152 * G_lin + 0.0722 * B_lin
* where each channel x in [0, 1]:
* x_lin = x / 12.92 if x <= 0.03928
* x_lin = ((x + 0.055) / 1.055) ** 2.4 otherwise
*
* ratio = (L_lighter + 0.05) / (L_darker + 0.05)
* ratio ∈ [1, 21]
*/
/**
* Parse a hex color string (#RRGGBB) into RGB channels in [0, 1].
* Throws on invalid input — callers should validate format upstream.
*/
function parseHexColor(hex: string): { r: number; g: number; b: number } {
const m = /^#([0-9A-Fa-f]{6})$/.exec(hex.trim())
if (!m) throw new Error(`Invalid hex color: ${hex}`)
const value = m[1]
const r = parseInt(value.slice(0, 2), 16) / 255
const g = parseInt(value.slice(2, 4), 16) / 255
const b = parseInt(value.slice(4, 6), 16) / 255
return { r, g, b }
}
/**
* Linearize a single sRGB channel value [0, 1] per WCAG 2.x.
*/
function linearize(channel: number): number {
return channel <= 0.03928
? channel / 12.92
: Math.pow((channel + 0.055) / 1.055, 2.4)
}
/**
* Compute relative luminance L ∈ [0, 1] for a hex color per WCAG 2.x.
*/
function relativeLuminance(hex: string): number {
const { r, g, b } = parseHexColor(hex)
const rL = linearize(r)
const gL = linearize(g)
const bL = linearize(b)
return 0.2126 * rL + 0.7152 * gL + 0.0722 * bL
}
/**
* Compute the WCAG contrast ratio between two hex colors. Returns a value in
* [1, 21] — 1 = identical colors, 21 = pure black on pure white.
*
* Argument order does not matter (the formula uses the lighter and darker
* luminance regardless of which is foreground).
*/
export function getContrastRatio(hexFg: string, hexBg: string): number {
const l1 = relativeLuminance(hexFg)
const l2 = relativeLuminance(hexBg)
const lighter = Math.max(l1, l2)
const darker = Math.min(l1, l2)
return (lighter + 0.05) / (darker + 0.05)
}
/**
* Returns true when the contrast ratio between fg and bg meets WCAG 2.2 AA
* for normal text (4.5:1). Use this to warn users when their brand color
* would render text that fails AA on the invoice background (which is
* effectively white in the current PDF template).
*/
export function isWcagAACompliant(fg: string, bg: string): boolean {
return getContrastRatio(fg, bg) >= 4.5
}