* 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>
340 lines
13 KiB
TypeScript
340 lines
13 KiB
TypeScript
'use client'
|
|
|
|
import { useState, useEffect } from 'react'
|
|
import { useParams, useRouter } from 'next/navigation'
|
|
import Image from 'next/image'
|
|
import Link from 'next/link'
|
|
import { Button } from '@/components/ui/button'
|
|
import { Card } from '@/components/ui/card'
|
|
import { Loader2, Building2, AlertCircle } from 'lucide-react'
|
|
import { createClient } from '@/lib/supabase/client'
|
|
import { useToast } from '@/components/ui/use-toast'
|
|
import { getBranding } from '@/lib/branding/service'
|
|
|
|
const branding = getBranding()
|
|
|
|
interface InviteInfo {
|
|
type: 'company'
|
|
companyName?: string
|
|
email: string
|
|
expired: boolean
|
|
alreadyHasAccount: boolean
|
|
}
|
|
|
|
export default function InvitePage() {
|
|
const params = useParams()
|
|
const router = useRouter()
|
|
const { toast } = useToast()
|
|
const token = params.token as string
|
|
|
|
const [isLoading, setIsLoading] = useState(true)
|
|
const [error, setError] = useState<string | null>(null)
|
|
const [invite, setInvite] = useState<InviteInfo | null>(null)
|
|
// Email of the currently signed-in user (if any). Used to short-circuit
|
|
// the login redirect for users who are already authenticated.
|
|
const [currentUserEmail, setCurrentUserEmail] = useState<string | null>(null)
|
|
const [isJoining, setIsJoining] = useState(false)
|
|
|
|
useEffect(() => {
|
|
async function loadInvite() {
|
|
try {
|
|
// Load invite info and current session in parallel — the page needs
|
|
// both to decide which CTA to render.
|
|
const supabase = createClient()
|
|
const [inviteRes, sessionRes] = await Promise.all([
|
|
fetch(`/api/team/accept?token=${encodeURIComponent(token)}`),
|
|
supabase.auth.getUser(),
|
|
])
|
|
|
|
const data = await inviteRes.json()
|
|
if (!inviteRes.ok) {
|
|
setError(data.error || 'Inbjudan är ogiltig.')
|
|
return
|
|
}
|
|
|
|
setInvite(data.data)
|
|
setCurrentUserEmail(sessionRes.data.user?.email ?? null)
|
|
} catch {
|
|
setError('Kunde inte ladda inbjudan.')
|
|
} finally {
|
|
setIsLoading(false)
|
|
}
|
|
}
|
|
loadInvite()
|
|
}, [token])
|
|
|
|
const secureCookieFlag = typeof window !== 'undefined' && window.location.protocol === 'https:' ? '; secure' : ''
|
|
|
|
// True when the signed-in user's email matches the invite — in that case
|
|
// we can accept the invite with a single click, no re-login required.
|
|
const isLoggedInAsInvitee =
|
|
!!currentUserEmail &&
|
|
!!invite &&
|
|
currentUserEmail.toLowerCase() === invite.email.toLowerCase()
|
|
|
|
// True when someone is signed in but with a different email than the
|
|
// invite is for. They need to sign out first.
|
|
const isLoggedInAsOther =
|
|
!!currentUserEmail && !!invite && !isLoggedInAsInvitee
|
|
|
|
const handleAccept = () => {
|
|
// Store invite token in cookie before redirecting to register
|
|
document.cookie = `gnubok-invite-token=${token}; path=/; max-age=3600; samesite=lax${secureCookieFlag}`
|
|
router.push(`/register?invite=${encodeURIComponent(token)}`)
|
|
}
|
|
|
|
const handleAcceptExistingUser = () => {
|
|
// Store invite token in cookie before redirecting to login
|
|
document.cookie = `gnubok-invite-token=${token}; path=/; max-age=3600; samesite=lax${secureCookieFlag}`
|
|
router.push('/login')
|
|
}
|
|
|
|
// Already signed in as the invitee — accept directly, no login detour.
|
|
// POST /api/team/accept handles the membership insert + sets the active
|
|
// company; we then full-reload to '/' so middleware picks up the new
|
|
// company context and the switcher shows it.
|
|
const handleJoinNow = async () => {
|
|
setIsJoining(true)
|
|
try {
|
|
const res = await fetch('/api/team/accept', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ token }),
|
|
})
|
|
const body = await res.json().catch(() => ({}))
|
|
|
|
if (!res.ok) {
|
|
toast({
|
|
title: 'Kunde inte gå med',
|
|
description: body.error || 'Ett oväntat fel uppstod. Försök igen.',
|
|
variant: 'destructive',
|
|
})
|
|
setIsJoining(false)
|
|
return
|
|
}
|
|
|
|
toast({
|
|
title: 'Välkommen!',
|
|
description: invite?.companyName
|
|
? `Du är nu medlem i ${invite.companyName}.`
|
|
: 'Du är nu medlem.',
|
|
})
|
|
// Full reload so the middleware re-resolves company context from the
|
|
// updated user_preferences.active_company_id.
|
|
window.location.href = '/'
|
|
} catch (err) {
|
|
console.error('[invite] join failed:', err)
|
|
toast({
|
|
title: 'Kunde inte gå med',
|
|
description: 'Ett oväntat fel uppstod. Försök igen.',
|
|
variant: 'destructive',
|
|
})
|
|
setIsJoining(false)
|
|
}
|
|
}
|
|
|
|
const handleSignOutAndRetry = async () => {
|
|
const supabase = createClient()
|
|
await supabase.auth.signOut()
|
|
// Keep the invite cookie alive so the next login/register picks it up.
|
|
document.cookie = `gnubok-invite-token=${token}; path=/; max-age=3600; samesite=lax${secureCookieFlag}`
|
|
if (invite?.alreadyHasAccount) {
|
|
router.push('/login')
|
|
} else {
|
|
router.push(`/register?invite=${encodeURIComponent(token)}`)
|
|
}
|
|
}
|
|
|
|
if (isLoading) {
|
|
return (
|
|
<div className="min-h-screen flex items-center justify-center bg-background">
|
|
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
|
</div>
|
|
)
|
|
}
|
|
|
|
return (
|
|
<div className="min-h-screen flex flex-col bg-background">
|
|
<header className="relative bg-[#141414] text-white overflow-hidden">
|
|
<div className="absolute inset-0 pointer-events-none" aria-hidden>
|
|
<div
|
|
className="absolute inset-0"
|
|
style={{
|
|
background: 'radial-gradient(ellipse at 30% -20%, rgba(255,255,255,0.04) 0%, transparent 50%)',
|
|
}}
|
|
/>
|
|
</div>
|
|
<div className="relative z-10 max-w-2xl mx-auto w-full px-6 md:px-10 pt-5 pb-6 md:pt-6 md:pb-8">
|
|
<div className="flex items-center gap-2.5 mb-5 md:mb-6">
|
|
<Image
|
|
src={branding.logoPath}
|
|
alt={branding.appName}
|
|
width={30}
|
|
height={30}
|
|
className="invert opacity-90"
|
|
/>
|
|
<span className="font-display text-base tracking-tight">{branding.appName.toLowerCase()}</span>
|
|
</div>
|
|
<div className="animate-fade-in">
|
|
<h1 className="font-display text-2xl md:text-3xl font-medium tracking-tight leading-[1.1]">
|
|
{error ? 'Ogiltig inbjudan' : 'Du har blivit inbjuden'}
|
|
</h1>
|
|
</div>
|
|
</div>
|
|
</header>
|
|
|
|
<main className="flex-1">
|
|
<div className="max-w-lg mx-auto px-6 md:px-10 py-6 md:py-8">
|
|
<div className="animate-slide-up">
|
|
{error ? (
|
|
<Card className="p-6">
|
|
<div className="flex items-start gap-3">
|
|
<AlertCircle className="h-5 w-5 text-destructive flex-shrink-0 mt-0.5" />
|
|
<div>
|
|
<p className="font-medium">{error}</p>
|
|
<p className="text-sm text-muted-foreground mt-1">
|
|
Kontakta personen som bjöd in dig för en ny inbjudan.
|
|
</p>
|
|
<Link
|
|
href="/login"
|
|
className="text-sm text-primary hover:underline mt-3 inline-block"
|
|
>
|
|
Gå till inloggning
|
|
</Link>
|
|
</div>
|
|
</div>
|
|
</Card>
|
|
) : invite?.expired ? (
|
|
<Card className="p-6">
|
|
<div className="flex items-start gap-3">
|
|
<AlertCircle className="h-5 w-5 text-muted-foreground flex-shrink-0 mt-0.5" />
|
|
<div>
|
|
<p className="font-medium">Inbjudan har gått ut</p>
|
|
<p className="text-sm text-muted-foreground mt-1">
|
|
Be personen som bjöd in dig att skicka en ny inbjudan.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
</Card>
|
|
) : isLoggedInAsInvitee ? (
|
|
// Already signed in as the invitee — one-click join.
|
|
// Prioritized over alreadyHasAccount to avoid the broken flow
|
|
// where a false-negative from the email check would send a
|
|
// logged-in user to /register, which middleware bounces to /.
|
|
<div className="space-y-6">
|
|
<Card className="p-6">
|
|
<div className="flex items-start gap-4">
|
|
<div className="p-2.5 rounded-lg bg-muted/50">
|
|
<Building2 className="h-5 w-5 text-muted-foreground" />
|
|
</div>
|
|
<div>
|
|
<p className="font-medium">{invite.companyName}</p>
|
|
<p className="text-sm text-muted-foreground mt-0.5">
|
|
Du har bjudits in som medlem till detta företag.
|
|
</p>
|
|
<p className="text-sm text-muted-foreground mt-1">
|
|
Inloggad som <strong>{currentUserEmail}</strong>.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
</Card>
|
|
|
|
<Button
|
|
size="lg"
|
|
className="w-full"
|
|
onClick={handleJoinNow}
|
|
disabled={isJoining}
|
|
>
|
|
{isJoining ? (
|
|
<>
|
|
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
|
Går med…
|
|
</>
|
|
) : (
|
|
<>Gå med i {invite.companyName}</>
|
|
)}
|
|
</Button>
|
|
</div>
|
|
) : isLoggedInAsOther ? (
|
|
// Signed in as a different user — ask them to sign out first.
|
|
<div className="space-y-6">
|
|
<Card className="p-6">
|
|
<div className="flex items-start gap-4">
|
|
<div className="p-2.5 rounded-lg bg-muted/50">
|
|
<Building2 className="h-5 w-5 text-muted-foreground" />
|
|
</div>
|
|
<div>
|
|
<p className="font-medium">{invite.companyName}</p>
|
|
<p className="text-sm text-muted-foreground mt-0.5">
|
|
Inbjudan är skickad till <strong>{invite.email}</strong>, men
|
|
du är inloggad som <strong>{currentUserEmail}</strong>.
|
|
</p>
|
|
<p className="text-sm text-muted-foreground mt-1">
|
|
Logga ut och logga in igen med rätt konto för att gå med.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
</Card>
|
|
|
|
<Button size="lg" className="w-full" onClick={handleSignOutAndRetry}>
|
|
Logga ut och byt konto
|
|
</Button>
|
|
</div>
|
|
) : invite?.alreadyHasAccount ? (
|
|
// Not signed in — email has an existing account, bounce to login.
|
|
<div className="space-y-6">
|
|
<Card className="p-6">
|
|
<div className="flex items-start gap-4">
|
|
<div className="p-2.5 rounded-lg bg-muted/50">
|
|
<Building2 className="h-5 w-5 text-muted-foreground" />
|
|
</div>
|
|
<div>
|
|
<p className="font-medium">{invite.companyName}</p>
|
|
<p className="text-sm text-muted-foreground mt-0.5">
|
|
Du har bjudits in som medlem till detta företag.
|
|
</p>
|
|
<p className="text-sm text-muted-foreground mt-1">
|
|
<strong>{invite.email}</strong> har redan ett konto på {branding.appName.toLowerCase()}.
|
|
Logga in för att gå med.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
</Card>
|
|
|
|
<Button size="lg" className="w-full" onClick={handleAcceptExistingUser}>
|
|
Logga in och gå med
|
|
</Button>
|
|
</div>
|
|
) : invite ? (
|
|
// Not signed in, no existing account — register.
|
|
<div className="space-y-6">
|
|
<Card className="p-6">
|
|
<div className="flex items-start gap-4">
|
|
<div className="p-2.5 rounded-lg bg-muted/50">
|
|
<Building2 className="h-5 w-5 text-muted-foreground" />
|
|
</div>
|
|
<div>
|
|
<p className="font-medium">{invite.companyName}</p>
|
|
<p className="text-sm text-muted-foreground mt-0.5">
|
|
Du har bjudits in som medlem till detta företag.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
</Card>
|
|
|
|
<Button size="lg" className="w-full" onClick={handleAccept}>
|
|
Skapa konto och gå med
|
|
</Button>
|
|
|
|
<p className="text-center text-xs text-muted-foreground">
|
|
Genom att skapa ett konto godkänner du våra villkor.
|
|
</p>
|
|
</div>
|
|
) : null}
|
|
</div>
|
|
</div>
|
|
</main>
|
|
</div>
|
|
)
|
|
}
|