fix: properly handle WhatsApp config save/corruption/reset flow

Root cause of the persistent 'Stored access token is corrupted' error:
handleSave was writing the access_token DIRECTLY to Supabase via the
browser client — WITHOUT calling the server-side POST /api/whatsapp/config
handler. The server handler is what actually encrypts the token with
ENCRYPTION_KEY. So every save stored the token in PLAINTEXT, and every
subsequent decrypt attempt threw 'corrupted'.

This meant no amount of re-saving could ever fix it — each save
re-introduced plaintext data that would fail decryption again.

Changes in src/components/settings/whatsapp-config.tsx:
- handleSave now POSTs to /api/whatsapp/config (server verifies with
  Meta AND encrypts the token before storing).
- On page load, after pulling form values from Supabase, we also
  call GET /api/whatsapp/config to check the config's health. If the
  health check reports needs_reset (decrypt failure), we show a
  prominent amber banner with a "Reset Configuration" button.
- Added handleReset that calls DELETE /api/whatsapp/config to clear
  the broken row and reset local state.
- Added a "Reset Configuration" button in the main action row
  (available whenever a config exists, for manual cleanup).
- Better error messages — shows the actual server-side reason
  (token_corrupted, meta_api_error, no_config).
- Save flow now requires re-entering the access token when updating
  (can't update without a token to verify against Meta).

Changes in src/app/api/whatsapp/config/route.ts:
- GET now returns 200 with { connected, reason, message, needs_reset }
  instead of 500 on decrypt failure. The UI can handle this gracefully.
- Added DELETE handler to remove the user's config row.
- POST also surfaces encryption errors (e.g. missing ENCRYPTION_KEY).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Arnas Donauskas 2026-04-16 20:54:43 +03:00
parent 0bcbdc2a43
commit 43b8e93d6d
No known key found for this signature in database
2 changed files with 309 additions and 95 deletions

View File

@ -6,10 +6,15 @@ import { encrypt, decrypt } from '@/lib/whatsapp/encryption'
/** /**
* GET /api/whatsapp/config * GET /api/whatsapp/config
* *
* Used by the "Test API Connection" button in Settings. * Used by the "Test API Connection" button and by the page to check
* Fetches the user's saved config, decrypts the access token, and pings * whether the saved config is healthy. Returns 200 in all non-auth cases
* Meta to verify the credentials still work. Returns the phone info * so the UI can render an appropriate message rather than show a 500.
* (display_phone_number, verified_name, quality_rating) on success. *
* Response shape:
* { connected: true, phone_info: {...} }
* { connected: false, reason: 'no_config', message: '...' }
* { connected: false, reason: 'token_corrupted', message: '...', needs_reset: true }
* { connected: false, reason: 'meta_api_error', message: '...' }
*/ */
export async function GET() { export async function GET() {
try { try {
@ -33,50 +38,66 @@ export async function GET() {
if (configError) { if (configError) {
console.error('Error fetching whatsapp_config:', configError) console.error('Error fetching whatsapp_config:', configError)
return NextResponse.json( return NextResponse.json(
{ error: 'Failed to fetch configuration' }, { connected: false, reason: 'db_error', message: 'Failed to fetch configuration' },
{ status: 500 } { status: 200 }
) )
} }
if (!config) { if (!config) {
return NextResponse.json( return NextResponse.json(
{ connected: false, error: 'No WhatsApp configuration saved yet' }, {
{ status: 404 } connected: false,
reason: 'no_config',
message: 'No WhatsApp configuration saved yet. Fill in the form and click Save Configuration.',
},
{ status: 200 }
) )
} }
// Decrypt access token and call Meta to verify it still works // Try to decrypt the stored token with the current ENCRYPTION_KEY.
// If this fails, the key changed (or was never consistent across envs).
let accessToken: string let accessToken: string
try { try {
accessToken = decrypt(config.access_token) accessToken = decrypt(config.access_token)
} catch (err) { } catch (err) {
console.error('Failed to decrypt access token:', err) console.error('[whatsapp/config GET] Token decryption failed:', err)
return NextResponse.json( return NextResponse.json(
{ connected: false, error: 'Stored access token is corrupted — please re-save configuration' }, {
{ status: 500 } connected: false,
reason: 'token_corrupted',
needs_reset: true,
message:
'The stored access token cannot be decrypted with the current ENCRYPTION_KEY. This usually means the key changed, or it differs between environments (local vs Hostinger vs Vercel). Click "Reset Configuration" below, then re-save.',
},
{ status: 200 }
) )
} }
// Validate credentials against Meta
try { try {
const phoneInfo = await verifyPhoneNumber( const phoneInfo = await verifyPhoneNumber(
config.phone_number_id, config.phone_number_id,
accessToken accessToken
) )
return NextResponse.json({ return NextResponse.json({ connected: true, phone_info: phoneInfo })
connected: true,
phone_info: phoneInfo,
})
} catch (err) { } catch (err) {
const message = err instanceof Error ? err.message : 'Unknown Meta API error' const message = err instanceof Error ? err.message : 'Unknown Meta API error'
console.error('Meta API verification failed:', message) console.error('[whatsapp/config GET] Meta API verification failed:', message)
return NextResponse.json( return NextResponse.json(
{ connected: false, error: message }, {
{ status: 502 } connected: false,
reason: 'meta_api_error',
message: `Meta API rejected the credentials: ${message}`,
},
{ status: 200 }
) )
} }
} catch (error) { } catch (error) {
console.error('Error in WhatsApp config GET:', error) console.error('Error in WhatsApp config GET:', error)
return NextResponse.json({ error: 'Internal server error' }, { status: 500 }) return NextResponse.json(
{ connected: false, reason: 'unknown', message: 'Internal server error' },
{ status: 500 }
)
} }
} }
@ -84,8 +105,7 @@ export async function GET() {
* POST /api/whatsapp/config * POST /api/whatsapp/config
* *
* Saves or updates the WhatsApp config for the authenticated user. * Saves or updates the WhatsApp config for the authenticated user.
* Verifies the credentials with Meta before saving. Tokens are encrypted * Verifies credentials with Meta first, then encrypts and stores.
* at rest with AES-256-CBC.
*/ */
export async function POST(request: Request) { export async function POST(request: Request) {
try { try {
@ -111,7 +131,7 @@ export async function POST(request: Request) {
} }
// Verify credentials with Meta BEFORE saving // Verify credentials with Meta BEFORE saving
// (function signature is verifyPhoneNumber(phoneNumberId, accessToken)) // Signature: verifyPhoneNumber(phoneNumberId, accessToken)
let phoneInfo let phoneInfo
try { try {
phoneInfo = await verifyPhoneNumber(phone_number_id, access_token) phoneInfo = await verifyPhoneNumber(phone_number_id, access_token)
@ -125,10 +145,24 @@ export async function POST(request: Request) {
} }
// Encrypt sensitive tokens before storing // Encrypt sensitive tokens before storing
const encryptedAccessToken = encrypt(access_token) let encryptedAccessToken: string
const encryptedVerifyToken = verify_token ? encrypt(verify_token) : null let encryptedVerifyToken: string | null
try {
encryptedAccessToken = encrypt(access_token)
encryptedVerifyToken = verify_token ? encrypt(verify_token) : null
} catch (err) {
const message = err instanceof Error ? err.message : 'Unknown encryption error'
console.error('Encryption failed:', message)
return NextResponse.json(
{
error:
'Failed to encrypt token. Check that ENCRYPTION_KEY is a valid 64-character hex string in your environment variables.',
},
{ status: 500 }
)
}
// Upsert // Upsert — overwrite any existing (possibly corrupted) config
const { data: existing } = await supabase const { data: existing } = await supabase
.from('whatsapp_config') .from('whatsapp_config')
.select('id') .select('id')
@ -178,12 +212,49 @@ export async function POST(request: Request) {
} }
} }
return NextResponse.json({ return NextResponse.json({ success: true, phone_info: phoneInfo })
success: true,
phone_info: phoneInfo,
})
} catch (error) { } catch (error) {
console.error('Error in WhatsApp config POST:', error) console.error('Error in WhatsApp config POST:', error)
return NextResponse.json({ error: 'Internal server error' }, { status: 500 }) return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
} }
} }
/**
* DELETE /api/whatsapp/config
*
* Removes the authenticated user's WhatsApp configuration row.
* Used by the "Reset Configuration" button to recover from a corrupted
* encrypted token (mismatched ENCRYPTION_KEY across environments).
*/
export async function DELETE() {
try {
const supabase = await createClient()
const {
data: { user },
error: authError,
} = await supabase.auth.getUser()
if (authError || !user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const { error: deleteError } = await supabase
.from('whatsapp_config')
.delete()
.eq('user_id', user.id)
if (deleteError) {
console.error('Error deleting whatsapp_config:', deleteError)
return NextResponse.json(
{ error: 'Failed to delete configuration' },
{ status: 500 }
)
}
return NextResponse.json({ success: true })
} catch (error) {
console.error('Error in WhatsApp config DELETE:', error)
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
}
}

View File

@ -1,6 +1,6 @@
'use client'; 'use client';
import { useEffect, useState } from 'react'; import { useEffect, useState, useCallback } from 'react';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { import {
Eye, Eye,
@ -11,6 +11,8 @@ import {
Loader2, Loader2,
ExternalLink, ExternalLink,
Zap, Zap,
AlertTriangle,
RotateCcw,
} from 'lucide-react'; } from 'lucide-react';
import { createClient } from '@/lib/supabase/client'; import { createClient } from '@/lib/supabase/client';
import { useAuth } from '@/hooks/use-auth'; import { useAuth } from '@/hooks/use-auth';
@ -29,6 +31,9 @@ import type { WhatsAppConfig as WhatsAppConfigType } from '@/types';
const MASKED_TOKEN = '••••••••••••••••'; const MASKED_TOKEN = '••••••••••••••••';
type ConnectionStatus = 'connected' | 'disconnected' | 'unknown';
type ResetReason = 'token_corrupted' | 'meta_api_error' | null;
export function WhatsAppConfig() { export function WhatsAppConfig() {
const supabase = createClient(); const supabase = createClient();
const { user, loading: authLoading } = useAuth(); const { user, loading: authLoading } = useAuth();
@ -36,9 +41,12 @@ export function WhatsAppConfig() {
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const [testing, setTesting] = useState(false); const [testing, setTesting] = useState(false);
const [resetting, setResetting] = useState(false);
const [showToken, setShowToken] = useState(false); const [showToken, setShowToken] = useState(false);
const [config, setConfig] = useState<WhatsAppConfigType | null>(null); const [config, setConfig] = useState<WhatsAppConfigType | null>(null);
const [connectionStatus, setConnectionStatus] = useState<'connected' | 'disconnected' | 'unknown'>('unknown'); const [connectionStatus, setConnectionStatus] = useState<ConnectionStatus>('unknown');
const [resetReason, setResetReason] = useState<ResetReason>(null);
const [statusMessage, setStatusMessage] = useState<string>('');
const [phoneNumberId, setPhoneNumberId] = useState(''); const [phoneNumberId, setPhoneNumberId] = useState('');
const [wabaId, setWabaId] = useState(''); const [wabaId, setWabaId] = useState('');
@ -51,28 +59,18 @@ export function WhatsAppConfig() {
? `${window.location.origin}/api/whatsapp/webhook` ? `${window.location.origin}/api/whatsapp/webhook`
: ''; : '';
useEffect(() => { const fetchConfig = useCallback(async (userId: string) => {
if (authLoading) return;
if (!user) {
setLoading(false);
return;
}
fetchConfig(user.id);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [authLoading, user?.id]);
async function fetchConfig(userId: string) {
try {
setLoading(true); setLoading(true);
try {
// Load form values from Supabase (shows what's in DB)
const { data, error } = await supabase const { data, error } = await supabase
.from('whatsapp_config') .from('whatsapp_config')
.select('*') .select('*')
.eq('user_id', userId) .eq('user_id', userId)
.single(); .maybeSingle();
if (error && error.code !== 'PGRST116') { if (error) {
throw error; console.error('Failed to load config row:', error);
} }
if (data) { if (data) {
@ -80,65 +78,113 @@ export function WhatsAppConfig() {
setPhoneNumberId(data.phone_number_id || ''); setPhoneNumberId(data.phone_number_id || '');
setWabaId(data.waba_id || ''); setWabaId(data.waba_id || '');
setAccessToken(MASKED_TOKEN); setAccessToken(MASKED_TOKEN);
setVerifyToken(data.verify_token || ''); setVerifyToken('');
setConnectionStatus(data.status || 'disconnected'); setTokenEdited(false);
} else {
setConfig(null);
setPhoneNumberId('');
setWabaId('');
setAccessToken('');
setVerifyToken('');
setTokenEdited(false);
}
// Then verify health via the API (decrypts token + pings Meta)
if (data) {
try {
const res = await fetch('/api/whatsapp/config', { method: 'GET' });
const payload = await res.json();
if (payload.connected) {
setConnectionStatus('connected');
setResetReason(null);
setStatusMessage('');
} else {
setConnectionStatus('disconnected');
setResetReason(payload.needs_reset ? 'token_corrupted' : payload.reason === 'meta_api_error' ? 'meta_api_error' : null);
setStatusMessage(payload.message || '');
} }
} catch (err) { } catch (err) {
console.error('Failed to fetch config:', err); console.error('Health check failed:', err);
setConnectionStatus('disconnected');
}
} else {
setConnectionStatus('disconnected');
setResetReason(null);
setStatusMessage('');
}
} catch (err) {
console.error('fetchConfig error:', err);
toast.error('Failed to load WhatsApp configuration'); toast.error('Failed to load WhatsApp configuration');
} finally { } finally {
setLoading(false); setLoading(false);
} }
}, [supabase]);
useEffect(() => {
if (authLoading) return;
if (!user) {
setLoading(false);
return;
} }
fetchConfig(user.id);
}, [authLoading, user, fetchConfig]);
async function handleSave() { async function handleSave() {
if (!phoneNumberId.trim()) { if (!phoneNumberId.trim()) {
toast.error('Phone Number ID is required'); toast.error('Phone Number ID is required');
return; return;
} }
if (!tokenEdited && !config) { if (!config && (!accessToken.trim() || !tokenEdited)) {
toast.error('Access Token is required'); toast.error('Access Token is required for initial setup');
return; return;
} }
try { try {
setSaving(true); setSaving(true);
if (!user) {
toast.error('Not authenticated');
return;
}
// Always POST through the API — it verifies with Meta and encrypts
// the access_token server-side with ENCRYPTION_KEY. Skipping this
// and writing direct to Supabase stores the token in plaintext,
// which then fails decryption on every subsequent health check.
const payload: Record<string, unknown> = { const payload: Record<string, unknown> = {
user_id: user.id,
phone_number_id: phoneNumberId.trim(), phone_number_id: phoneNumberId.trim(),
waba_id: wabaId.trim() || null, waba_id: wabaId.trim() || null,
verify_token: verifyToken.trim() || null, verify_token: verifyToken.trim() || null,
}; };
if (tokenEdited && accessToken !== MASKED_TOKEN) { if (tokenEdited && accessToken !== MASKED_TOKEN && accessToken.trim()) {
payload.access_token = accessToken.trim(); payload.access_token = accessToken.trim();
} } else if (config) {
// Existing config — reuse stored encrypted token by decrypting on the
if (config?.id) { // server. But our POST handler requires an access_token to verify
const { error } = await supabase // with Meta. If the user didn't change the token, we need to signal
.from('whatsapp_config') // that. Simplest: require token re-entry if they're updating.
.update(payload) toast.error('Please re-enter the Access Token to save changes');
.eq('id', config.id); setSaving(false);
if (error) throw error;
} else {
if (!tokenEdited || !accessToken.trim() || accessToken === MASKED_TOKEN) {
toast.error('Access Token is required for initial setup');
return; return;
} }
payload.access_token = accessToken.trim();
payload.status = 'disconnected'; const res = await fetch('/api/whatsapp/config', {
const { error } = await supabase method: 'POST',
.from('whatsapp_config') headers: { 'Content-Type': 'application/json' },
.insert(payload); body: JSON.stringify(payload),
if (error) throw error; });
const data = await res.json();
if (!res.ok) {
toast.error(data.error || 'Failed to save configuration');
setSaving(false);
return;
} }
toast.success('Configuration saved successfully'); toast.success(
data.phone_info?.verified_name
? `Connected to ${data.phone_info.verified_name}`
: 'Configuration saved successfully'
);
if (user) await fetchConfig(user.id); if (user) await fetchConfig(user.id);
} catch (err) { } catch (err) {
console.error('Save error:', err); console.error('Save error:', err);
@ -151,32 +197,66 @@ export function WhatsAppConfig() {
async function handleTestConnection() { async function handleTestConnection() {
try { try {
setTesting(true); setTesting(true);
const response = await fetch('/api/whatsapp/config', { const res = await fetch('/api/whatsapp/config', { method: 'GET' });
method: 'GET', const payload = await res.json();
});
if (response.ok) { if (payload.connected) {
setConnectionStatus('connected'); setConnectionStatus('connected');
toast.success('API connection successful'); setResetReason(null);
setStatusMessage('');
if (config?.id) { toast.success(
await supabase payload.phone_info?.verified_name
.from('whatsapp_config') ? `Connected to ${payload.phone_info.verified_name}`
.update({ status: 'connected', connected_at: new Date().toISOString() }) : 'API connection successful'
.eq('id', config.id); );
}
} else { } else {
setConnectionStatus('disconnected'); setConnectionStatus('disconnected');
toast.error('API connection failed. Check your credentials.'); setResetReason(payload.needs_reset ? 'token_corrupted' : payload.reason === 'meta_api_error' ? 'meta_api_error' : null);
setStatusMessage(payload.message || '');
toast.error(payload.message || 'API connection failed');
} }
} catch { } catch (err) {
console.error('Test connection error:', err);
setConnectionStatus('disconnected'); setConnectionStatus('disconnected');
toast.error('Connection test failed. Ensure your server is running.'); toast.error('Connection test failed. Check network and try again.');
} finally { } finally {
setTesting(false); setTesting(false);
} }
} }
async function handleReset() {
if (!confirm('This will delete the current WhatsApp config so you can re-enter it. Continue?')) {
return;
}
try {
setResetting(true);
const res = await fetch('/api/whatsapp/config', { method: 'DELETE' });
const data = await res.json();
if (!res.ok) {
toast.error(data.error || 'Failed to reset configuration');
return;
}
toast.success('Configuration cleared. You can now re-enter your credentials.');
setConfig(null);
setPhoneNumberId('');
setWabaId('');
setAccessToken('');
setVerifyToken('');
setTokenEdited(false);
setConnectionStatus('disconnected');
setResetReason(null);
setStatusMessage('');
} catch (err) {
console.error('Reset error:', err);
toast.error('Failed to reset configuration');
} finally {
setResetting(false);
}
}
function handleCopyWebhookUrl() { function handleCopyWebhookUrl() {
navigator.clipboard.writeText(webhookUrl); navigator.clipboard.writeText(webhookUrl);
toast.success('Webhook URL copied to clipboard'); toast.success('Webhook URL copied to clipboard');
@ -190,10 +270,47 @@ export function WhatsAppConfig() {
); );
} }
const showResetBanner = resetReason === 'token_corrupted';
return ( return (
<div className="grid gap-6 lg:grid-cols-[1fr_380px] mt-4"> <div className="grid gap-6 lg:grid-cols-[1fr_380px] mt-4">
{/* Main config form */} {/* Main config form */}
<div className="space-y-6"> <div className="space-y-6">
{/* Corrupted-token reset banner */}
{showResetBanner && (
<Alert className="bg-amber-950/40 border-amber-600/40">
<div className="flex items-start gap-3">
<AlertTriangle className="size-5 text-amber-400 mt-0.5 shrink-0" />
<div className="flex-1">
<AlertTitle className="text-amber-200 mb-1">
Stored token can&apos;t be decrypted
</AlertTitle>
<AlertDescription className="text-amber-100/80 text-sm">
{statusMessage}
</AlertDescription>
<Button
onClick={handleReset}
disabled={resetting}
size="sm"
className="mt-3 bg-amber-600 hover:bg-amber-700 text-white"
>
{resetting ? (
<>
<Loader2 className="size-4 animate-spin" />
Resetting...
</>
) : (
<>
<RotateCcw className="size-4" />
Reset Configuration
</>
)}
</Button>
</div>
</div>
</Alert>
)}
{/* Connection Status */} {/* Connection Status */}
<Alert className="bg-slate-900 border-slate-700"> <Alert className="bg-slate-900 border-slate-700">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
@ -209,7 +326,8 @@ export function WhatsAppConfig() {
<AlertDescription className="text-slate-400"> <AlertDescription className="text-slate-400">
{connectionStatus === 'connected' {connectionStatus === 'connected'
? 'Your WhatsApp Business API is connected and ready to send/receive messages.' ? 'Your WhatsApp Business API is connected and ready to send/receive messages.'
: 'Configure your Meta API credentials below to connect your WhatsApp Business account.'} : statusMessage ||
'Configure your Meta API credentials below to connect your WhatsApp Business account.'}
</AlertDescription> </AlertDescription>
</Alert> </Alert>
@ -269,6 +387,11 @@ export function WhatsAppConfig() {
{showToken ? <EyeOff className="size-4" /> : <Eye className="size-4" />} {showToken ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
</button> </button>
</div> </div>
{config && !tokenEdited && (
<p className="text-xs text-slate-500">
Token is hidden for security. Re-enter it to update configuration.
</p>
)}
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
@ -317,7 +440,7 @@ export function WhatsAppConfig() {
</Card> </Card>
{/* Action Buttons */} {/* Action Buttons */}
<div className="flex gap-3"> <div className="flex flex-wrap gap-3">
<Button <Button
onClick={handleSave} onClick={handleSave}
disabled={saving} disabled={saving}
@ -350,6 +473,26 @@ export function WhatsAppConfig() {
</> </>
)} )}
</Button> </Button>
{config && (
<Button
variant="outline"
onClick={handleReset}
disabled={resetting}
className="border-red-900 text-red-400 hover:text-red-300 hover:bg-red-950/40"
>
{resetting ? (
<>
<Loader2 className="size-4 animate-spin" />
Resetting...
</>
) : (
<>
<RotateCcw className="size-4" />
Reset Configuration
</>
)}
</Button>
)}
</div> </div>
</div> </div>