* feat: invoicing & account-security polish bundle Five independent improvements bundled to ship together: - BankID/password lockout fix: BankID-only users could enroll MFA and brick themselves (Supabase requires AAL2 to change password or unenroll MFA, and AAL2 needs a password sign-in). New app_metadata.has_password flag tracks this; middleware gates /mfa/enroll behind it, /account/set- password is the unlock path, SecuritySettings shows a banner, and /api/account/password is the single write path that flips the flag. Backfill script for existing users. - Swish invoice payment method: company_settings.swish + invoice_show_swish columns, validation in lib/api/schemas.ts (accepts 123XXXXXXX företag or 07XXXXXXXX mobile, strips whitespace/hyphens), rendered on invoice PDFs. - Send-reminders kill switch: per-company company_settings.send_invoice_ reminders toggle in PdfPrintSettings/Automatisering. Reminder processor also tightened: positive status allowlist (sent + overdue) so terminal statuses can never match; skip when customer already responded via reminder link; race-window re-check before send. - First-invoice logo prompt: one-shot dialog when creating the first invoice without a logo (issue #520). Self-limits via head-only count. - SIE export opening-balance fallback: route IB through getOpeningBalances so the compute_prior_opening_balances RPC supplies #IB after multi-year imports where opening_balance_entry_id is intentionally NULL. Previously #IB silently went to zero and #UB collapsed to current-period movements. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(account-polish): address PR review feedback - BankID-link path (extensions/general/tic/index.ts): read-merge-write app_metadata instead of passing { bankid_linked: true } alone. updateUserById REPLACES app_metadata wholesale, so the previous code would have wiped has_password for any user who later linked BankID, causing the set-password banner to (incorrectly) reappear and blocking the standard MFA enrollment button. The comment is now corrected. - Middleware (lib/supabase/middleware.ts): thread inner returnTo through the /mfa/enroll → /account/set-password redirect so the user lands on their original destination after the full chain completes, not on /. - safeReturnTo helper (lib/auth/safe-return-to.ts): replace the starts-with-/-but-not-// guard on mfa/enroll and set-password pages. The previous guard let /\evil.com and /@evil.com through. The new helper parses against a synthetic base origin and verifies it matches. - set-password page (app/(auth)/account/set-password/page.tsx): remove CLAUDE.md design system violations — bg-gradient-to-b on page bg, inline shadow-md style on the card, space-y-5, font-medium on the h1, rounded-xl on the card. Flat surface, hairline border, font-display h1 per the design tokens. - Swish dedup (lib/payments/swish.ts): extract normaliseSwish() and isValidSwish() helpers and use them in lib/api/schemas.ts, components/settings/BankDetailsForm.tsx, and the invoicing settings page. Single source of truth for the regex. - Password route (app/api/account/password/route.ts): emit a structured success log so the audit pipeline can detect password-set events, not just failures. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
328 lines
11 KiB
TypeScript
328 lines
11 KiB
TypeScript
'use client'
|
|
|
|
import { useState, useEffect } from 'react'
|
|
import { useRouter } from 'next/navigation'
|
|
import { createClient } from '@/lib/supabase/client'
|
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
|
import { Button } from '@/components/ui/button'
|
|
import { Input } from '@/components/ui/input'
|
|
import { Label } from '@/components/ui/label'
|
|
import { useToast } from '@/components/ui/use-toast'
|
|
import { Loader2, ShieldCheck, ShieldOff, KeyRound } from 'lucide-react'
|
|
import { isMfaRequired } from '@/lib/auth/mfa'
|
|
import { isBankIdEnabled } from '@/lib/auth/bankid'
|
|
import { BankIdSettings } from '@/components/settings/BankIdSettings'
|
|
import { userHasPassword } from '@/lib/auth/has-password'
|
|
|
|
const isSelfHosted = process.env.NEXT_PUBLIC_SELF_HOSTED === 'true'
|
|
const mfaRequired = isMfaRequired()
|
|
const bankIdEnabled = isBankIdEnabled()
|
|
|
|
export function SecuritySettings() {
|
|
const [newPassword, setNewPassword] = useState('')
|
|
const [confirmPassword, setConfirmPassword] = useState('')
|
|
const [isChangingPassword, setIsChangingPassword] = useState(false)
|
|
const [hasMfa, setHasMfa] = useState(false)
|
|
const [isLoadingMfa, setIsLoadingMfa] = useState(true)
|
|
const [isUnenrolling, setIsUnenrolling] = useState(false)
|
|
const [mfaFactorId, setMfaFactorId] = useState<string | null>(null)
|
|
const [hasPassword, setHasPassword] = useState<boolean | null>(null)
|
|
const { toast } = useToast()
|
|
const router = useRouter()
|
|
const supabase = createClient()
|
|
|
|
useEffect(() => {
|
|
async function loadStatus() {
|
|
const [{ data: factors }, { data: userData }] = await Promise.all([
|
|
supabase.auth.mfa.listFactors(),
|
|
supabase.auth.getUser(),
|
|
])
|
|
const verifiedFactor = factors?.totp?.find(f => f.status === 'verified')
|
|
setHasMfa(!!verifiedFactor)
|
|
setMfaFactorId(verifiedFactor?.id ?? null)
|
|
setHasPassword(userData?.user ? userHasPassword(userData.user) : null)
|
|
setIsLoadingMfa(false)
|
|
}
|
|
loadStatus()
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [])
|
|
|
|
const handleChangePassword = async (e: React.FormEvent<HTMLFormElement>) => {
|
|
e.preventDefault()
|
|
setIsChangingPassword(true)
|
|
|
|
const strong = newPassword.length >= 8
|
|
&& /[a-z]/.test(newPassword)
|
|
&& /[A-Z]/.test(newPassword)
|
|
&& /[0-9]/.test(newPassword)
|
|
&& /[^a-zA-Z0-9]/.test(newPassword)
|
|
|
|
if (!strong) {
|
|
toast({
|
|
title: 'Lösenordet är för svagt',
|
|
description: 'Lösenordet måste vara minst 8 tecken och innehålla versaler, gemener, siffror och specialtecken.',
|
|
variant: 'destructive',
|
|
})
|
|
setIsChangingPassword(false)
|
|
return
|
|
}
|
|
|
|
if (newPassword !== confirmPassword) {
|
|
toast({
|
|
title: 'Lösenorden matchar inte',
|
|
description: 'Kontrollera att du skrev samma lösenord i båda fälten.',
|
|
variant: 'destructive',
|
|
})
|
|
setIsChangingPassword(false)
|
|
return
|
|
}
|
|
|
|
try {
|
|
const res = await fetch('/api/account/password', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ password: newPassword }),
|
|
})
|
|
|
|
if (!res.ok) {
|
|
const body = (await res.json().catch(() => ({}))) as { error?: string }
|
|
toast({
|
|
title: 'Kunde inte uppdatera lösenord',
|
|
description: body.error || 'Försök igen senare.',
|
|
variant: 'destructive',
|
|
})
|
|
return
|
|
}
|
|
|
|
toast({
|
|
title: 'Lösenord uppdaterat',
|
|
description: 'Ditt lösenord har ändrats.',
|
|
})
|
|
setNewPassword('')
|
|
setConfirmPassword('')
|
|
setHasPassword(true)
|
|
} catch {
|
|
toast({
|
|
title: 'Något gick fel',
|
|
description: 'Försök igen senare.',
|
|
variant: 'destructive',
|
|
})
|
|
} finally {
|
|
setIsChangingPassword(false)
|
|
}
|
|
}
|
|
|
|
const handleUnenrollMfa = async () => {
|
|
if (!mfaFactorId) return
|
|
setIsUnenrolling(true)
|
|
|
|
try {
|
|
const { error } = await supabase.auth.mfa.unenroll({ factorId: mfaFactorId })
|
|
|
|
if (error) {
|
|
toast({
|
|
title: 'Kunde inte inaktivera 2FA',
|
|
description: error.message,
|
|
variant: 'destructive',
|
|
})
|
|
return
|
|
}
|
|
|
|
toast({
|
|
title: 'Tvåfaktorsautentisering inaktiverad',
|
|
description: '2FA har tagits bort från ditt konto.',
|
|
})
|
|
setHasMfa(false)
|
|
setMfaFactorId(null)
|
|
} catch {
|
|
toast({
|
|
title: 'Något gick fel',
|
|
description: 'Försök igen senare.',
|
|
variant: 'destructive',
|
|
})
|
|
} finally {
|
|
setIsUnenrolling(false)
|
|
}
|
|
}
|
|
|
|
return (
|
|
<div className="space-y-6">
|
|
{bankIdEnabled && <BankIdSettings />}
|
|
|
|
{/* BankID-only users with no password — banner above everything else */}
|
|
{hasPassword === false && (
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle className="flex items-center gap-2 text-base">
|
|
<KeyRound className="h-4 w-4" />
|
|
Sätt ett lösenord
|
|
</CardTitle>
|
|
<CardDescription>
|
|
Du loggade in med BankID och har inget lösenord ännu. Sätt ett
|
|
lösenord för att kunna aktivera 2FA eller logga in när BankID
|
|
inte är tillgängligt.
|
|
</CardDescription>
|
|
</CardHeader>
|
|
<CardContent>
|
|
<Button
|
|
onClick={() =>
|
|
router.push('/account/set-password?returnTo=/settings/account')
|
|
}
|
|
>
|
|
Sätt lösenord
|
|
</Button>
|
|
</CardContent>
|
|
</Card>
|
|
)}
|
|
|
|
{/* Change password — hidden when the user has no password (the banner
|
|
above handles the set-initial-password flow). */}
|
|
{hasPassword !== false && (
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle className="flex items-center gap-2">
|
|
<KeyRound className="h-5 w-5" />
|
|
Ändra lösenord
|
|
</CardTitle>
|
|
<CardDescription>
|
|
Uppdatera ditt lösenord. Om du loggar in med e-postlänk kan du sätta ett lösenord här.
|
|
</CardDescription>
|
|
</CardHeader>
|
|
<CardContent>
|
|
<form onSubmit={handleChangePassword} className="space-y-4 max-w-md">
|
|
<div className="space-y-2">
|
|
<Label htmlFor="new_password">Nytt lösenord</Label>
|
|
<Input
|
|
id="new_password"
|
|
type="password"
|
|
autoComplete="new-password"
|
|
placeholder="Minst 8 tecken"
|
|
value={newPassword}
|
|
onChange={(e) => setNewPassword(e.target.value)}
|
|
required
|
|
minLength={8}
|
|
disabled={isChangingPassword}
|
|
/>
|
|
</div>
|
|
<div className="space-y-2">
|
|
<Label htmlFor="confirm_new_password">Bekräfta nytt lösenord</Label>
|
|
<Input
|
|
id="confirm_new_password"
|
|
type="password"
|
|
autoComplete="new-password"
|
|
placeholder="Upprepa lösenordet"
|
|
value={confirmPassword}
|
|
onChange={(e) => setConfirmPassword(e.target.value)}
|
|
required
|
|
minLength={8}
|
|
disabled={isChangingPassword}
|
|
/>
|
|
</div>
|
|
<Button type="submit" disabled={isChangingPassword}>
|
|
{isChangingPassword ? (
|
|
<>
|
|
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
|
Sparar...
|
|
</>
|
|
) : (
|
|
'Uppdatera lösenord'
|
|
)}
|
|
</Button>
|
|
</form>
|
|
</CardContent>
|
|
</Card>
|
|
)}
|
|
|
|
{/* MFA — hidden for self-hosted */}
|
|
{!isSelfHosted && (
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle className="flex items-center gap-2">
|
|
<ShieldCheck className="h-5 w-5" />
|
|
Tvåfaktorsautentisering (2FA)
|
|
</CardTitle>
|
|
<CardDescription>
|
|
Skydda ditt konto med en autentiseringsapp. Vid varje inloggning behöver du ange en kod
|
|
utöver ditt lösenord.
|
|
</CardDescription>
|
|
</CardHeader>
|
|
<CardContent>
|
|
{isLoadingMfa ? (
|
|
<div className="flex items-center gap-2 text-muted-foreground">
|
|
<Loader2 className="h-4 w-4 animate-spin" />
|
|
Laddar...
|
|
</div>
|
|
) : hasMfa ? (
|
|
<div className="space-y-4">
|
|
<div className="flex items-center gap-3 p-4 rounded-lg border bg-green-50 dark:bg-green-950/20 border-green-200 dark:border-green-900">
|
|
<ShieldCheck className="h-5 w-5 text-green-600 dark:text-green-500" />
|
|
<div>
|
|
<p className="font-medium text-green-900 dark:text-green-100">2FA är aktiverad</p>
|
|
<p className="text-sm text-green-700 dark:text-green-400">
|
|
Ditt konto skyddas med tvåfaktorsautentisering.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
{!mfaRequired && (
|
|
<Button
|
|
variant="outline"
|
|
onClick={handleUnenrollMfa}
|
|
disabled={isUnenrolling}
|
|
>
|
|
{isUnenrolling ? (
|
|
<>
|
|
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
|
Inaktiverar...
|
|
</>
|
|
) : (
|
|
<>
|
|
<ShieldOff className="mr-2 h-4 w-4" />
|
|
Inaktivera 2FA
|
|
</>
|
|
)}
|
|
</Button>
|
|
)}
|
|
{mfaRequired && (
|
|
<p className="text-xs text-muted-foreground">
|
|
Tvåfaktorsautentisering är obligatorisk och kan inte inaktiveras.
|
|
</p>
|
|
)}
|
|
</div>
|
|
) : (
|
|
<div className="space-y-4">
|
|
<div className="flex items-center gap-3 p-4 rounded-lg border">
|
|
<ShieldOff className="h-5 w-5 text-muted-foreground" />
|
|
<div>
|
|
<p className="font-medium">2FA är inte aktiverad</p>
|
|
<p className="text-sm text-muted-foreground">
|
|
Vi rekommenderar att du aktiverar tvåfaktorsautentisering.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
{hasPassword === false ? (
|
|
<Button
|
|
onClick={() =>
|
|
router.push(
|
|
'/account/set-password?returnTo=/mfa/enroll',
|
|
)
|
|
}
|
|
>
|
|
Sätt ett lösenord först
|
|
</Button>
|
|
) : (
|
|
<Button
|
|
onClick={() => router.push(`/mfa/enroll?returnTo=${encodeURIComponent('/settings/account')}`)}
|
|
>
|
|
<ShieldCheck className="mr-2 h-4 w-4" />
|
|
Aktivera 2FA
|
|
</Button>
|
|
)}
|
|
</div>
|
|
)}
|
|
</CardContent>
|
|
</Card>
|
|
)}
|
|
</div>
|
|
)
|
|
}
|