diff --git a/supabase/migrations/0002_mfa_recovery.sql b/supabase/migrations/0002_mfa_recovery.sql index 82dc014..d977f61 100644 --- a/supabase/migrations/0002_mfa_recovery.sql +++ b/supabase/migrations/0002_mfa_recovery.sql @@ -16,6 +16,21 @@ create table if not exists public.mfa_recovery_codes ( create index if not exists mfa_recovery_codes_user_id_idx on public.mfa_recovery_codes (user_id); +-- Cascade-delete recovery codes when the owning auth user is removed, so no +-- orphaned rows are left behind (e.g. on account deletion or MFA reset). +do $$ +begin + if not exists ( + select 1 from pg_constraint + where conname = 'mfa_recovery_codes_user_id_fkey' + and conrelid = 'public.mfa_recovery_codes'::regclass + ) then + alter table public.mfa_recovery_codes + add constraint mfa_recovery_codes_user_id_fkey + foreign key (user_id) references auth.users (id) on delete cascade; + end if; +end $$; + -- Fast lookup of an unused code by (user, hash) during redemption. create unique index if not exists mfa_recovery_codes_user_hash_uidx on public.mfa_recovery_codes (user_id, code_hash);