* fix(mcp-oauth): allow ChatGPT connector callbacks and resume OAuth after login Add chatgpt.com/connector/oauth/* (per-instance) and the legacy chatgpt.com/connector_platform_oauth_redirect to the built-in OAuth redirect allowlist so ChatGPT MCP connectors can register and authorize. Fix the login page dropping the ?next= destination: an OAuth-initiated visit that required login previously ended on the dashboard and the connection flow silently died. Login now resumes to the sanitized next path (hard navigation, since the consent page is route-handler HTML), carries it through the MFA step-up as returnTo, and /mfa/verify hard-navigates for /api/ destinations. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(transactions): dedup incoming feed rows against booked hand-entered twins Users who bookkeep via MCP/chat first and connect their bank afterwards got the same movement twice: the synced row's external_id lives in a different namespace, the free-form manual title never text-bridges the bank's raw string, and the cross-channel mirror deliberately excluded manual/mcp rows. Extend the mirror with a booked-hand-entered track: an incoming feed row is skipped when a BOOKED manual/mcp row shares its (date, ore) bucket count- symmetrically. Gates beyond the feed-vs-feed mirror: stored row must be booked (staged rows never consume an import), currencies must not contradict (bucket key is date+ore only), the cash-account guard applies to the count exactly as to consumption, and symmetry uses the Layer-1-unmatched incoming count so an already-stored row cannot inflate it. Consumption stamps the batch cash_account_id onto an account-unbound hand row, so one hand row can never consume feed rows on other accounts in later syncs. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(bookkeeping): inline verifikat rattelse (strike lines + text/date edit) Second sanctioned correction track under BFL 5 kap 5/9 pp, Fortnox-style: strike lines inside a posted verifikat with replacements in the same voucher, and correct description/entry_date without an andringsverifikat. Envelope: posted entries, open unlocked periods, company lock date, same-period date moves, structural/FX/doc-linked lines excluded, and a reconciliation guard preserving per-account net on bank/reskontra sides of externally linked entries. Every rattelse writes an immutable who/when row (journal_entry_rattelse_log, WORM, archived as rakenskapsinformation) and struck originals render struck-through in the verifikat; list rows and the detail header carry a Rattad marker. CLAUDE.md hard rule 1 and the swedish-accounting-compliance skill are amended to state the two-track rule. Staging carries the DDL; prod gets it on merge. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat: live saldo in booking form, prior-year window comparison, hideable assistant FAB - Manual journal entry: saldo column now shows before -> after computed from the typed debit/credit amounts (direction feedback while booking) - Resultatrapport: a narrowed date range now compares against the same window shifted one year back (#862), merged across fiscal periods for brutet rakenskapsar; P&L rows report window activity instead of rolled-forward YTD closing - Assistant FAB: per-user hide toggle (user_preferences.hide_assistant_fab, settings > assistant), sidebar entry unaffected; collapsed sessions keep their reopen handle Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(stripe): sync balance transactions as a bank feed on 1686 Import the connected Stripe balance into the transactions inbox, opt-in per connection (transaction_sync_enabled on stripe_connections): - Balance transactions map to feed rows with the two-row gross+fee split and frozen external_id formats (stripe_{acct}_{txn} / _fee), dated on created, bound to a provisioned "Stripe-saldo" cash account on 1686 so booking settles against the clearing account by construction. - Double-booking protection: settled payment-link charges import pre-linked to their settlement entry; payout rows import pre-linked to the payout entry; processPayoutPaidEvent claims the payout's fee rows at booking time (linkPayoutFeedRows, idempotent from both directions). - Cursor last_balance_txn_synced_at with 24h overlap; first run backfills 90 days floored at the day after the company lock date. - Nightly cron /api/extensions/stripe/transactions/cron (03:30), transaction-sync toggle route, "Synka nu" covers both feeds, settings panel toggle with last-synced/backfill note, sv+en strings. - Migration 20260723200000 (applied to staging). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(transactions): offer match-to-voucher on unbooked history rows Unbooked transactions with is_business already set (e.g. left behind when a voucher was removed without a full uncategorize) land in the history list instead of the inbox, where the match-against-existing-voucher action did not exist, leaving them with no path back to voucher matching. Add the same menu item to the history list for unbooked rows. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(transactions): enhance ownership checks and error handling in journal entry routes --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
239 lines
7.6 KiB
TypeScript
239 lines
7.6 KiB
TypeScript
'use client'
|
|
|
|
import { useState, useEffect, useRef, Suspense } from 'react'
|
|
import { useRouter, useSearchParams } from 'next/navigation'
|
|
import { useTranslations } from 'next-intl'
|
|
import { createClient } from '@/lib/supabase/client'
|
|
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, LogOut } from 'lucide-react'
|
|
import { SupportLink } from '@/components/ui/support-link'
|
|
import { safeReturnTo } from '@/lib/auth/safe-return-to'
|
|
|
|
export default function MfaVerifyPage() {
|
|
return (
|
|
<Suspense>
|
|
<MfaVerifyContent />
|
|
</Suspense>
|
|
)
|
|
}
|
|
|
|
function MfaVerifyContent() {
|
|
const t = useTranslations('mfa')
|
|
const tCommon = useTranslations('common')
|
|
const [code, setCode] = useState('')
|
|
const [isLoading, setIsLoading] = useState(false)
|
|
const [factorId, setFactorId] = useState<string | null>(null)
|
|
const [failedAttempts, setFailedAttempts] = useState(0)
|
|
const [lockoutUntil, setLockoutUntil] = useState<number | null>(null)
|
|
const [lockoutRemaining, setLockoutRemaining] = useState(0)
|
|
const inputRef = useRef<HTMLInputElement>(null)
|
|
const { toast } = useToast()
|
|
const router = useRouter()
|
|
const searchParams = useSearchParams()
|
|
const supabase = createClient()
|
|
|
|
// Step-up landing target. Set by callers that need AAL2 to do something
|
|
// sensitive (set/change password, unenroll MFA, etc.): /api/account/password
|
|
// and SecuritySettings redirect here when GoTrue rejects with "AAL2 session
|
|
// is required". Falls back to the dashboard for direct visits.
|
|
const returnTo = safeReturnTo(searchParams.get('returnTo'), '/')
|
|
|
|
useEffect(() => {
|
|
async function loadFactor() {
|
|
const { data } = await supabase.auth.mfa.listFactors()
|
|
const verifiedFactor = data?.totp?.find(f => f.status === 'verified')
|
|
if (verifiedFactor) {
|
|
setFactorId(verifiedFactor.id)
|
|
} else {
|
|
router.push('/')
|
|
}
|
|
}
|
|
loadFactor()
|
|
inputRef.current?.focus()
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [])
|
|
|
|
useEffect(() => {
|
|
if (!lockoutUntil) return
|
|
const tick = () => {
|
|
const remaining = Math.max(0, Math.ceil((lockoutUntil - Date.now()) / 1000))
|
|
setLockoutRemaining(remaining)
|
|
if (remaining <= 0) setLockoutUntil(null)
|
|
}
|
|
tick()
|
|
const interval = setInterval(tick, 1000)
|
|
return () => clearInterval(interval)
|
|
}, [lockoutUntil])
|
|
|
|
const handleVerify = async (e: React.FormEvent<HTMLFormElement>) => {
|
|
e.preventDefault()
|
|
if (!factorId || code.length !== 6) return
|
|
|
|
setIsLoading(true)
|
|
|
|
try {
|
|
const { data: challenge, error: challengeError } = await supabase.auth.mfa.challenge({
|
|
factorId,
|
|
})
|
|
|
|
if (challengeError) {
|
|
toast({
|
|
title: t('verify_failed_title'),
|
|
description: t('verify_challenge_failed_description'),
|
|
variant: 'destructive',
|
|
})
|
|
setIsLoading(false)
|
|
return
|
|
}
|
|
|
|
const { error: verifyError } = await supabase.auth.mfa.verify({
|
|
factorId,
|
|
challengeId: challenge.id,
|
|
code,
|
|
})
|
|
|
|
if (verifyError) {
|
|
const attempts = failedAttempts + 1
|
|
setFailedAttempts(attempts)
|
|
|
|
if (attempts >= 3) {
|
|
const delays = [5_000, 15_000, 30_000]
|
|
const delay = delays[Math.min(attempts - 3, delays.length - 1)]
|
|
setLockoutUntil(Date.now() + delay)
|
|
}
|
|
|
|
toast({
|
|
title: t('wrong_code_title'),
|
|
description: t('wrong_code_description'),
|
|
variant: 'destructive',
|
|
})
|
|
setCode('')
|
|
inputRef.current?.focus()
|
|
setIsLoading(false)
|
|
return
|
|
}
|
|
|
|
const cookieMatch = document.cookie.match(/gnubok-invite-token=([^;]+)/)
|
|
const inviteToken = cookieMatch?.[1]
|
|
|
|
if (inviteToken) {
|
|
try {
|
|
const res = await fetch('/api/team/accept', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ token: inviteToken }),
|
|
})
|
|
|
|
if (res.ok) {
|
|
document.cookie = 'gnubok-invite-token=; path=/; max-age=0'
|
|
window.location.href = '/'
|
|
return
|
|
}
|
|
} catch (err) {
|
|
console.error('[mfa/verify] invite acceptance failed:', err)
|
|
}
|
|
document.cookie = 'gnubok-invite-token=; path=/; max-age=0'
|
|
}
|
|
|
|
if (returnTo.startsWith('/api/')) {
|
|
// Route-handler destinations (e.g. the MCP OAuth consent page)
|
|
// return raw HTML the client router cannot render: hard-navigate.
|
|
window.location.assign(returnTo)
|
|
return
|
|
}
|
|
|
|
router.push(returnTo)
|
|
router.refresh()
|
|
} catch {
|
|
toast({
|
|
title: t('verify_failed_title'),
|
|
description: t('unexpected_error'),
|
|
variant: 'destructive',
|
|
})
|
|
} finally {
|
|
setIsLoading(false)
|
|
}
|
|
}
|
|
|
|
const handleLogout = async () => {
|
|
await supabase.auth.signOut()
|
|
router.push('/login')
|
|
}
|
|
|
|
return (
|
|
<div className="min-h-screen flex flex-col items-center justify-center bg-gradient-to-b from-background to-primary/[0.03] p-4">
|
|
<div className="w-full max-w-sm animate-slide-up">
|
|
<div className="text-center mb-10">
|
|
<div className="flex justify-center mb-4">
|
|
<div className="h-14 w-14 rounded-2xl bg-primary/8 flex items-center justify-center">
|
|
<ShieldCheck className="h-7 w-7 text-primary" />
|
|
</div>
|
|
</div>
|
|
<h1 className="text-2xl font-medium tracking-tight">{t('verify_title')}</h1>
|
|
<p className="text-muted-foreground text-sm mt-2">
|
|
{t('verify_subtitle_full')}
|
|
</p>
|
|
</div>
|
|
|
|
<div className="rounded-lg border bg-card p-6">
|
|
<form onSubmit={handleVerify} className="space-y-5">
|
|
<div className="space-y-2">
|
|
<Label htmlFor="code">{t('verify_code_label')}</Label>
|
|
<Input
|
|
ref={inputRef}
|
|
id="code"
|
|
type="text"
|
|
inputMode="numeric"
|
|
pattern="[0-9]{6}"
|
|
maxLength={6}
|
|
autoComplete="one-time-code"
|
|
placeholder="000000"
|
|
value={code}
|
|
onChange={(e) => setCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
|
|
required
|
|
disabled={isLoading}
|
|
className="h-11 text-center text-lg tracking-[0.5em] font-mono"
|
|
/>
|
|
</div>
|
|
<Button
|
|
type="submit"
|
|
className="w-full h-11"
|
|
disabled={isLoading || code.length !== 6 || !!lockoutUntil}
|
|
>
|
|
{isLoading ? (
|
|
<>
|
|
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
|
{t('verifying')}
|
|
</>
|
|
) : lockoutUntil ? (
|
|
t('wait_seconds', { seconds: lockoutRemaining })
|
|
) : (
|
|
t('verify_button')
|
|
)}
|
|
</Button>
|
|
</form>
|
|
</div>
|
|
|
|
<Button
|
|
variant="ghost"
|
|
className="w-full mt-4 text-muted-foreground"
|
|
onClick={handleLogout}
|
|
>
|
|
<LogOut className="mr-2 h-4 w-4" />
|
|
{tCommon('logout')}
|
|
</Button>
|
|
|
|
<p className="text-xs text-muted-foreground text-center mt-4">
|
|
{t('lost_authenticator')}{' '}
|
|
<SupportLink variant="muted" subject="MFA: cannot sign in" className="inline">
|
|
{t('contact_support')}
|
|
</SupportLink>
|
|
</p>
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|