Add/white label (#381)

* feat(branding): add BrandingService with default-preserving env layer

Introduce lib/branding/service.ts mirroring lib/email/service.ts. Defaults
match current gnubok values exactly, so production behaviour is unchanged
unless an env var (NEXT_PUBLIC_BRANDING_*, BRANDING_*) or extension override
(via registerBrandingService) is set.

Resolution order: defaults < env vars < extension override.

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

* feat(branding): route root layout, manifest, and PWA assets through branding service

- app/layout.tsx now reads title, description, themeColor, and apple-touch-icon
  from getBranding() instead of hardcoded values.
- public/manifest.json replaced by dynamic app/manifest.ts so PWA name,
  short_name, description, theme_color, background_color, and icon paths
  are resolved at request time.

The manifest now serves at /manifest.webmanifest (Next.js convention for
the metadata file route). The previous /manifest.json URL is no longer
populated; nothing in core references it after this commit.

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

* feat(branding): route email service and templates through branding service

- resend-service.ts: From line uses getBranding().appName instead of
  hardcoded "Gnubok" in both the with-fromName and bare cases.
- invite-templates.ts: subject, HTML header, body, plain text, and the
  team-invite variants all read from branding (sentence case in prose,
  uppercased for the styled <p> header).
- consent-notification-templates.ts: signature fallback (companyName ||
  branding) for both HTML and plain text variants.

Defaults preserve the exact current strings ("Gnubok", "GNUBOK", "gnubok"
in their respective contexts) so no email content changes for production.

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

* feat(branding): route OAuth consent page through branding service

The MCP OAuth consent page rendered for Claude Desktop / Claude.ai
connector flows now reads the app name from getBranding() for both the
HTML <title> and the body copy. Default still produces "gnubok" in
lowercase prose, matching current behaviour.

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

* feat(branding): route auth, dashboard, and onboarding text through branding service

Replace user-visible "gnubok" / "Gnubok" references with calls to
getBranding(). Touches:

- Auth pages (login, register, mfa/enroll): logo src/alt, MFA TOTP
  friendlyName.
- Onboarding (companies/new, invite, sandbox, WelcomeOnboarding,
  Step2CompanyDetails, NewUserChecklist, BankIdCompanyPicker,
  ArcimMigrationWorkspace): logo, headings, error/help text.
- Dashboard fallback (companyName="gnubok") and settings (backup copy,
  ApiKeysPanel MCP connector name + login note, CompanyDangerZone,
  retention-notice).
- API routes (support contact subject prefix, enable-banking consent
  email companyName fallback, AI inbox receipt-request appUrl,
  pain001 messageId prefix).
- MCP server "open the gnubok web app" review message.
- Salary/reports filings (AGI Programnamn, KU10 Programnamn,
  payslip footer, full-archive system metadata, SRU #PROGRAM line).

Internal identifiers (cookie names gnubok-company-id /
gnubok-invite-token, API key prefix gnubok_sk_, invite token prefix
gnubok_inv_, MCP tool names, npm package gnubok-mcp, GNUBOK_API_KEY
env name) are deliberately left unchanged — they're stable contracts
that whitelabels must not break.

Defaults match current behaviour exactly.

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

* feat(branding): support legal page field-level swaps for entity and contact

Privacy and DPA pages now interpolate appName, legalEntity, and
privacyEmail from the branding service instead of hardcoding "Gnubok",
"Arcim", and "privacy@gnubok.se". Page metadata uses generateMetadata()
so titles also reflect the brand.

lib/support.ts now falls back to getBranding().supportEmail when
SUPPORT_RECIPIENT_EMAIL is unset, so a single BRANDING_SUPPORT_EMAIL
env var configures both the support form recipient and the displayed
support address.

Whitelabels with a different legal jurisdiction or entirely different
DPA text should override the page route from an extension. Phase 1
intentionally only supports field-level swaps.

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

* docs(branding): add WHITELABEL.md and example branding extension

WHITELABEL.md: fork checklist, env var reference, the "do not change"
list (cookies, API key prefixes, invite token prefixes, MCP tool names,
gnubok-mcp npm package, GNUBOK_API_KEY env name), out-of-scope items,
the upstream sync workflow YAML to copy into a fork, conflict avoidance
guidance, and a verification checklist.

extensions/general/_example-branding/: copy-paste starter extension with
index.ts (commented placeholder values for registerBrandingService),
manifest.json, and README.md. Disabled by default (not added to
extensions.config.json); whitelabels cp the folder, edit, and enable.

sectors.test.ts: bumped expected extension count 12 -> 13 to account
for the new starter extension on disk. The generated registry is
unchanged because the example is disabled.

The sync workflow YAML is documented inline in WHITELABEL.md rather
than checked in as a workflow file. It's only meaningful in a fork --
gnubok itself has nothing to sync from.

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

* fix(branding): address PR review — lazy support email + escape brand in HTML/XML

Three issues from code review:

P1 — lib/support.ts: SUPPORT_RECIPIENT_EMAIL was a module-level const,
evaluated at import time before extensions register branding overrides
via ensureInitialized(). Convert to getSupportRecipientEmail() lazy
accessor; update the only caller in app/api/support/contact/route.ts.
Extension-supplied supportEmail values now route correctly.

P2 — app/api/mcp-oauth/authorize/route.ts: appName was interpolated
into the consent page HTML without escapeHtml(), inconsistent with
the existing escaping of companyName. Wrap appName.toLowerCase() in
escapeHtml() at use sites in <title> and the body paragraph.

P2 — lib/salary/agi/xml-generator.ts and lib/salary/ku/ku10-generator.ts:
appName placed inside <gem:Programnamn> / <Programnamn> XML elements
without escapeXml(), the helper already used for other admin-controlled
fields in the same files. Wrap accordingly to prevent malformed XML if
a brand name contains XML reserved characters.

All admin-controlled inputs only — no user-exploitable path. Defense in
depth, not a known incident.

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

* fix(branding): security follow-up — lazy metadata, SRU/email header sanitization

Self-audit after the PR review surfaced four more concerns. Fixes them
with the same defense-in-depth posture as the prior review fixes.

1. app/layout.tsx — same eager-evaluation class as P1 support.ts. The
   module-level `const branding = getBranding()` froze branding before
   extensions registered, so extension-based overrides for title,
   description, themeColor, and apple-touch-icon silently never applied.
   - Convert to generateMetadata() / generateViewport() (lazy, run per
     request, see extension-registered overrides).
   - Inline getBranding() inside RootLayout for the apple-touch-icon
     href so it picks up overrides too.
   - Add ensureInitialized() at module level so extensions are loaded
     before the first metadata call. Mirrors the API route pattern.

2. app/manifest.ts — same class. The dynamic manifest function reads
   getBranding() per request, but if the manifest is requested before
   any other module has triggered ensureInitialized(), extensions are
   still unloaded. Add ensureInitialized() at module level.

3. lib/reports/ink2/sru-generator.ts — appName interpolated into the
   SRU `#PROGRAM` directive without sanitization. SRU's reserved char
   is `#` (directive marker) and CRLF injects new directives. Wrap in
   the existing sanitizeString() helper to match the pattern used for
   other admin-controlled fields in this file (#NAMN, #ADRESS, etc.).

4. extensions/general/email/lib/resend-service.ts — appName and the
   user-controlled fromName both flow into the From header. Resend's
   API does its own validation, but defense in depth: strip CRLF and
   angle brackets via a small sanitizeHeaderPart() helper before
   building the header string. fromName was a pre-existing surface;
   appName is new with this whitelabel work.

All four are admin-controlled inputs (env vars or extension code),
not user-exploitable. No known incidents — defense in depth, and
correctness for extension-based whitelabels.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-04-29 16:32:26 +02:00
committed by GitHub
co-authored by Claude Opus 4.7
parent 2d36dedf34
commit 064fb7f7a9
43 changed files with 673 additions and 161 deletions
+5 -2
View File
@@ -8,6 +8,9 @@ import { useToast } from '@/components/ui/use-toast'
import { Building2 } from 'lucide-react'
import { cn } from '@/lib/utils'
import { ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-extensions'
import { getBranding } from '@/lib/branding/service'
const branding = getBranding()
import type { CompanyLookupResult } from '@/lib/company-lookup/types'
import type { CompanySettings, EntityType, MomsPeriod } from '@/types'
@@ -143,7 +146,7 @@ export default function WelcomeOnboarding({
let backToStep2 = false
if (result.error === 'org_number_exists') {
title = 'Företaget finns redan'
description = 'Det här företaget finns redan i gnubok. Be en befintlig administratör att bjuda in dig.'
description = `Det här företaget finns redan i ${branding.appName.toLowerCase()}. Be en befintlig administratör att bjuda in dig.`
backToStep2 = true
} else if (result.error === 'org_number_invalid') {
title = 'Ogiltigt organisationsnummer'
@@ -191,7 +194,7 @@ export default function WelcomeOnboarding({
<div className="flex flex-col items-start justify-center min-h-[60vh] animate-fade-in">
<p className="text-muted-foreground/50 text-sm mb-2">{greeting}</p>
<h1 className="font-display text-4xl md:text-5xl font-medium tracking-tight leading-[1.05] mb-10">
Välkommen till Gnubok
Välkommen till {branding.appName}
</h1>
<button
onClick={() => setStarted(true)}
@@ -11,6 +11,9 @@ import { cn } from '@/lib/utils'
import { ConfirmationDialog } from '@/components/ui/confirmation-dialog'
import Link from 'next/link'
import { FallbackPrompt } from '@/components/ui/fallback-prompt'
import { getBranding } from '@/lib/branding/service'
const branding = getBranding()
import {
ArrowLeft,
ArrowRight,
@@ -415,8 +418,8 @@ function ConnectStep({
const needsCompanyId = provider === 'bokio' || provider === 'bjornlunden'
const tokenDescription = isClientCredentials
? `Ange ditt företags-ID (GUID) från Björn Lundén. gnubok ansluter automatiskt via sin integrationspartner-åtkomst.`
: `Ange din API-nyckel från ${providerName} för att ge gnubok tillgång att läsa din bokföringsdata.`
? `Ange ditt företags-ID (GUID) från Björn Lundén. ${branding.appName.toLowerCase()} ansluter automatiskt via sin integrationspartner-åtkomst.`
: `Ange din API-nyckel från ${providerName} för att ge ${branding.appName.toLowerCase()} tillgång att läsa din bokföringsdata.`
const tokenHelpText = isClientCredentials
? `Hittas i Björn Lundén under Inställningar \u2192 Företagsinformation (GUID-format).`
@@ -436,7 +439,7 @@ function ConnectStep({
<CardDescription>
{authType === 'token'
? tokenDescription
: `Logga in i ${providerName} för att ge gnubok tillgång att läsa din bokföringsdata.`
: `Logga in i ${providerName} för att ge ${branding.appName.toLowerCase()} tillgång att läsa din bokföringsdata.`
}
</CardDescription>
</CardHeader>
@@ -638,7 +641,7 @@ function PreviewStep({
<div>
<p className="text-sm font-medium text-destructive">SIE-import krävs</p>
<p className="text-xs text-muted-foreground">
Bokföringsdata (kontoplan, verifikationer och balanser) måste importeras via SIE-fil innan kunder, leverantörer och fakturor kan hämtas. Exportera en SIE-fil från {ARCIM_PROVIDERS.find(p => p.id === preview.consent.provider)?.name ?? 'ditt bokföringssystem'} och ladda upp den i gnubok.
Bokföringsdata (kontoplan, verifikationer och balanser) måste importeras via SIE-fil innan kunder, leverantörer och fakturor kan hämtas. Exportera en SIE-fil från {ARCIM_PROVIDERS.find(p => p.id === preview.consent.provider)?.name ?? 'ditt bokföringssystem'} och ladda upp den i {branding.appName.toLowerCase()}.
</p>
<Link
href="/import?mode=sie"
@@ -912,7 +915,7 @@ function OptionsStep({
}}
isSubmitting={false}
title="Starta migrering"
warningText="Bokföringsdata, kunder, leverantörer och fakturor importeras till gnubok. Se till att ingen annan import pågår."
warningText={`Bokföringsdata, kunder, leverantörer och fakturor importeras till ${branding.appName.toLowerCase()}. Se till att ingen annan import pågår.`}
confirmLabel="Starta migrering"
>
<div className="space-y-2">
@@ -9,6 +9,9 @@ import { useToast } from '@/components/ui/use-toast'
import { switchCompany, createCompanyFromTicRole } from '@/lib/company/actions'
import { mapEntityType } from '@/lib/company-lookup/entity-type-map'
import type { CompanyLookupResult, EnrichmentCompanyRole } from '@/lib/company-lookup/types'
import { getBranding } from '@/lib/branding/service'
const branding = getBranding()
export interface MemberCompany {
id: string
@@ -280,7 +283,7 @@ export default function BankIdCompanyPicker({
{memberCompanies.length > 0 && (
<section>
<h2 className="text-xs uppercase tracking-[0.08em] text-muted-foreground mb-3">
Dina företag i gnubok
Dina företag i {branding.appName.toLowerCase()}
</h2>
<ul className="space-y-2">
{memberCompanies.map((c) => {
@@ -348,7 +351,7 @@ export default function BankIdCompanyPicker({
</p>
</div>
<span className="text-[10px] uppercase tracking-wide text-muted-foreground flex-shrink-0">
Finns redan i gnubok
Finns redan i {branding.appName.toLowerCase()}
</span>
</div>
<p className="text-xs text-muted-foreground/70 mt-2">
+4 -1
View File
@@ -10,6 +10,9 @@ import {
} from 'lucide-react'
import { cn } from '@/lib/utils'
import { ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-extensions'
import { getBranding } from '@/lib/branding/service'
const branding = getBranding()
interface NewUserChecklistProps {
onFreshStart: () => void
@@ -29,7 +32,7 @@ export default function NewUserChecklist({
{/* Header */}
<div className="text-center mb-8 md:mb-12">
<h1 className="font-display text-2xl md:text-3xl font-medium tracking-tight">
Välkommen till gnubok
Välkommen till {branding.appName.toLowerCase()}
</h1>
<p className="text-muted-foreground text-sm md:text-base leading-relaxed max-w-md mx-auto mt-3">
Börja med att hämta din bokföring, sedan kopplar du banken.
@@ -11,6 +11,9 @@ import { Label } from '@/components/ui/label'
import { Loader2, ArrowRight, ArrowLeft, CheckCircle2, AlertTriangle } from 'lucide-react'
import type { EntityType } from '@/types'
import type { CompanyLookupResult } from '@/lib/company-lookup/types'
import { getBranding } from '@/lib/branding/service'
const branding = getBranding()
const schema = z.object({
company_name: z.string().min(1, 'Företagsnamn krävs'),
@@ -238,7 +241,7 @@ export default function Step2CompanyDetails({
<div className="flex items-start gap-2 text-sm text-destructive">
<AlertTriangle className="h-3.5 w-3.5 mt-0.5 flex-shrink-0" />
<span>
Det här företaget finns redan i gnubok. Be en befintlig administratör att bjuda in dig.
Det här företaget finns redan i {branding.appName.toLowerCase()}. Be en befintlig administratör att bjuda in dig.
</span>
</div>
)}
+8 -4
View File
@@ -18,6 +18,10 @@ import { Checkbox } from '@/components/ui/checkbox'
import { DestructiveConfirmDialog, useDestructiveConfirm } from '@/components/ui/destructive-confirm-dialog'
import { useToast } from '@/components/ui/use-toast'
import { Loader2, Plus, Copy, Check, Trash2, Key, ChevronDown } from 'lucide-react'
import { getBranding } from '@/lib/branding/service'
const branding = getBranding()
const connectorName = branding.appName.toLowerCase()
const SCOPE_GROUPS = [
{
@@ -335,7 +339,7 @@ export function ApiKeysPanel() {
</div>
<p className="text-xs text-muted-foreground mb-2">
Gå till <strong>Settings &rarr; Integrations &rarr; Add Integration</strong> och klistra in MCP-serverns URL.
Du loggas in via ditt gnubok-konto — ingen API-nyckel behövs.
Du loggas in via ditt {connectorName}-konto — ingen API-nyckel behövs.
</p>
<CopyBlock text={mcpUrl} />
</div>
@@ -345,7 +349,7 @@ export function ApiKeysPanel() {
<p className="text-xs text-muted-foreground mb-2">
Kör i terminalen — loggar in via webbläsaren:
</p>
<CopyBlock text={`claude mcp add gnubok --transport http ${mcpUrl}`} />
<CopyBlock text={`claude mcp add ${connectorName} --transport http ${mcpUrl}`} />
</div>
<div className="border-t pt-4">
@@ -366,7 +370,7 @@ export function ApiKeysPanel() {
</p>
<CopyBlock text={`{
"mcpServers": {
"gnubok": {
"${connectorName}": {
"command": "npx",
"args": ["gnubok-mcp"],
"env": {
@@ -382,7 +386,7 @@ export function ApiKeysPanel() {
<p className="text-xs text-muted-foreground mb-2">
Kör i terminalen med en API-nyckel:
</p>
<CopyBlock text={`claude mcp add gnubok --transport http \\
<CopyBlock text={`claude mcp add ${connectorName} --transport http \\
--url ${mcpUrl} \\
--header "Authorization: Bearer gnubok_sk_..."`} />
</div>
+4 -1
View File
@@ -17,6 +17,9 @@ import {
import { RetentionNotice } from '@/components/ui/retention-notice'
import { Loader2 } from 'lucide-react'
import { useToast } from '@/components/ui/use-toast'
import { getBranding } from '@/lib/branding/service'
const branding = getBranding()
/**
* Danger zone for the currently-active company. Only visible to owners.
@@ -106,7 +109,7 @@ export function CompanyDangerZone() {
<DialogHeader>
<DialogTitle>Radera {company.name}</DialogTitle>
<DialogDescription>
Företaget döljs från gnubok. Bokföringen behålls säkert i 7 år enligt BFL.
Företaget döljs från {branding.appName.toLowerCase()}. Bokföringen behålls säkert i 7 år enligt BFL.
Skriv företagets namn exakt för att bekräfta.
</DialogDescription>
</DialogHeader>
+3 -1
View File
@@ -3,6 +3,7 @@
import Link from 'next/link'
import { AlertTriangle } from 'lucide-react'
import { cn } from '@/lib/utils'
import { getBranding } from '@/lib/branding/service'
interface RetentionNoticeProps {
variant: 'company' | 'account'
@@ -20,6 +21,7 @@ interface RetentionNoticeProps {
* hides it from the UI and anonymizes PII where applicable.
*/
export function RetentionNotice({ variant, className }: RetentionNoticeProps) {
const { appName } = getBranding()
const copy =
variant === 'company'
? {
@@ -27,7 +29,7 @@ export function RetentionNotice({ variant, className }: RetentionNoticeProps) {
body: (
<>
Enligt bokföringslagen (BFL 7 kap. 2§) sparas räkenskapsinformation i 7 år.
När du raderar företaget döljs det i gnubok, men verifikationer, dokument och
När du raderar företaget döljs det i {appName.toLowerCase()}, men verifikationer, dokument och
bokföring behålls säkert tills lagkravet löpt ut. Du kan{' '}
<Link
href="/settings/backup"