deckhearth/pages/api/user/delete.js
Randall Stillwell a84373642e fix(security): drop wildcard CORS + redundant OPTIONS from 24 API routes (P0 #5)
Closes P0 #5 (CORS) from PARTIAL → RESOLVED. fix-auth-bypass
Brief 4 (commit 297afca) cleaned login + register; this brief
sweeps the remaining 24 pages/api/** handlers that carried the
identical scaffolded wildcard-CORS + redundant-OPTIONS pattern,
plus adds a blocking forbidden-cors-headers CI job to lock in
the cleanup against future regression.

Per architect Decision 1 — Option B (sweep all 24 in one PR)
chosen over Option A (narrow verify.js-only + queue separate
sweep). Pattern-drift audit (14 of 24 files spot-checked across
parent + architect) found zero drift; mechanical safety
confirmed.

Per Decision 2 — OPTIONS handler deleted entirely (matches
Brief 4 precedent). Same-origin Vercel deployment doesn't
preflight; method check at top of handler returns 405 if any
client ever sends OPTIONS again.

Per Decision 3 — verify.js's overly-permissive Allow-Methods:
'GET, POST, PUT, DELETE, OPTIONS' is moot (deleted under D2);
the handler's existing `if (req.method !== 'GET') return 405`
guard at line 17 (now line ~5) is the remaining gate.

Per Decision 4 — no new per-route tests this convoy. None of
the 24 routes have vitest coverage today; adding handler-level
tests is the queued fill-vitest-handler-coverage convoy.

Per Decision 5 — new `forbidden-cors-headers` CI job added,
modeled verbatim on `forbidden-endpoints`. Blocking (no
`|| true`, no `continue-on-error`). Greps pages/api/ for any
`Access-Control-Allow-(Origin|Methods|Headers)` reappearance
and exits 1 on hit.

Verification:
  - npm run lint: 128 problems (baseline match)
  - npm run test:run: 21/21 vitest pass (no regression)
  - git grep -nE "Access-Control-Allow-..." -- 'pages/api/**':
    zero matches
  - git grep -nE "OPTIONS" -- 'pages/api/**': zero matches
    (post-sweep)
  - new forbidden-cors-headers grep exits 0 against swept tree

No code paths in lib/**, components/**, scripts/**, or test/**
touched. No package.json / lockfile churn. No workflow YAML
beyond the single ci.yml job addition. No AGENTS.md edits
(doc-writer pass at convoy close).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-24 20:24:47 -05:00

104 lines
No EOL
3.6 KiB
JavaScript

import { del } from '@vercel/blob';
import { sql } from '@vercel/postgres';
import { getUserFromRequest } from '../../../lib/permission-middleware';
export default async function handler(req, res) {
if (req.method !== 'DELETE') {
return res.status(405).json({ error: 'Method not allowed' });
}
try {
// Get authenticated user
const user = await getUserFromRequest(req);
if (!user) {
return res.status(401).json({ error: 'Authentication required' });
}
// Prevent admin users from deleting their own accounts
if (user.role === 'admin') {
return res.status(403).json({
error: 'Admin accounts cannot be self-deleted. Please contact another administrator.'
});
}
try {
// Start transaction-like cleanup
console.log(`Starting account deletion for user ${user.userId}`);
// 1. Delete user avatars from Vercel Blob
const avatarsResult = await sql`
SELECT file_path FROM user_avatars
WHERE user_id = ${user.userId} AND is_active = true
`;
for (const avatar of avatarsResult.rows) {
try {
await del(avatar.file_path);
console.log(`Deleted avatar: ${avatar.file_path}`);
} catch (blobError) {
console.warn(`Failed to delete avatar blob: ${avatar.file_path}`, blobError);
// Continue with deletion even if blob cleanup fails
}
}
// 2. Delete user data in correct order (respecting foreign key constraints)
// Delete deck cards first
await sql`DELETE FROM deck_cards WHERE deck_id IN (SELECT id FROM decks WHERE user_id = ${user.userId})`;
console.log('Deleted deck cards');
// Delete decks
await sql`DELETE FROM decks WHERE user_id = ${user.userId}`;
console.log('Deleted decks');
// Delete collection cards
await sql`DELETE FROM collection_cards WHERE collection_id IN (SELECT id FROM collections WHERE user_id = ${user.userId})`;
console.log('Deleted collection cards');
// Delete collections
await sql`DELETE FROM collections WHERE user_id = ${user.userId}`;
console.log('Deleted collections');
// Delete user cards
await sql`DELETE FROM user_cards WHERE user_id = ${user.userId}`;
console.log('Deleted user cards');
// Delete user avatars records
await sql`DELETE FROM user_avatars WHERE user_id = ${user.userId}`;
console.log('Deleted user avatar records');
// Delete user settings
await sql`DELETE FROM user_settings WHERE user_id = ${user.userId}`;
console.log('Deleted user settings');
// Finally, delete the user account
const deleteResult = await sql`DELETE FROM users WHERE id = ${user.userId}`;
console.log('Deleted user account');
if (deleteResult.rowCount === 0) {
return res.status(404).json({ error: 'User not found' });
}
console.log(`Successfully deleted account for user ${user.userId}`);
res.status(200).json({
message: 'Account deleted successfully. All your data has been permanently removed.'
});
} catch (deleteError) {
console.error('Account deletion error:', deleteError);
// Check if it's a foreign key constraint error
if (deleteError.code === '23503') {
return res.status(400).json({
error: 'Cannot delete account due to data dependencies. Please contact support.'
});
}
res.status(500).json({ error: 'Failed to delete account. Please try again or contact support.' });
}
} catch (error) {
console.error('Account deletion API error:', error);
res.status(500).json({ error: 'Internal server error' });
}
}