This commit is contained in:
jjbrunton committed 2025-12-30 11:15:47 +00:00
1 parent a15089f607
commit 456459bb00
41 files changed
+6018

No files matched your search

@@ -0,0 +1,175 @@
-- Security Hardening Migration
-- Fixes: Weak invite codes, overly permissive RLS, password settings
-- ============================================
-- 1. Strengthen invite code generation
-- Use crypto-secure random with alphanumeric chars (8 chars retained for UX)
-- ============================================
-- Create a function to generate secure invite codes
CREATE OR REPLACE FUNCTION generate_secure_invite_code()
RETURNS TEXT AS $$
DECLARE
chars TEXT := 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; -- Removed confusing chars: I, O, 0, 1
result TEXT := '';
i INTEGER;
rand_bytes BYTEA;
BEGIN
-- Get 8 cryptographically secure random bytes
rand_bytes := gen_random_bytes(8);
FOR i IN 1..8 LOOP
result := result || substr(chars, (get_byte(rand_bytes, i-1) % 32) + 1, 1);
END LOOP;
RETURN result;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- Update the default for new couples to use secure generation
ALTER TABLE public.couples
ALTER COLUMN invite_code SET DEFAULT generate_secure_invite_code();
-- Add rate limiting tracking table for invite code attempts
CREATE TABLE IF NOT EXISTS public.invite_code_attempts (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
ip_hash TEXT NOT NULL, -- Hashed IP for privacy
user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
attempted_at TIMESTAMPTZ DEFAULT NOW(),
was_successful BOOLEAN DEFAULT FALSE
);
-- Index for efficient rate limiting queries
CREATE INDEX IF NOT EXISTS idx_invite_attempts_user_time
ON public.invite_code_attempts(user_id, attempted_at);
-- Enable RLS on attempts table
ALTER TABLE public.invite_code_attempts ENABLE ROW LEVEL SECURITY;
-- Only allow inserts from authenticated users
CREATE POLICY "Authenticated users can log attempts"
ON public.invite_code_attempts
FOR INSERT
WITH CHECK (auth.role() = 'authenticated');
-- ============================================
-- 2. Fix overly permissive couples RLS policy
-- ============================================
-- Drop the overly permissive policy
DROP POLICY IF EXISTS "Users can view couple by invite code" ON public.couples;
-- Replace with a more restrictive policy
-- Users can only view their own couple OR look up a couple via RPC (not direct table access)
CREATE POLICY "Users can only view their own couple"
ON public.couples FOR SELECT
USING (
id IN (SELECT couple_id FROM public.profiles WHERE id = auth.uid())
);
-- Create a secure RPC function for invite code lookup
-- This only returns success/failure, not couple data
CREATE OR REPLACE FUNCTION public.verify_invite_code(code TEXT)
RETURNS JSONB AS $$
DECLARE
couple_record RECORD;
member_count INTEGER;
BEGIN
-- Normalize the code
code := UPPER(TRIM(code));
-- Check if code exists
SELECT id INTO couple_record
FROM public.couples
WHERE UPPER(invite_code) = code;
IF couple_record.id IS NULL THEN
RETURN jsonb_build_object('valid', false, 'error', 'Invalid invite code');
END IF;
-- Check member count
SELECT COUNT(*) INTO member_count
FROM public.profiles
WHERE couple_id = couple_record.id;
IF member_count >= 2 THEN
RETURN jsonb_build_object('valid', false, 'error', 'This couple already has two partners');
END IF;
RETURN jsonb_build_object('valid', true, 'couple_id', couple_record.id);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- Grant execute permission to authenticated users
GRANT EXECUTE ON FUNCTION public.verify_invite_code(TEXT) TO authenticated;
-- ============================================
-- 3. Optional: Add password policy comment
-- (Password length is enforced client-side, but should also be in Supabase Auth config)
-- ============================================
COMMENT ON SCHEMA public IS 'Password policy: Minimum 8 characters required. Configure in Supabase Dashboard > Auth > Policies';
-- ============================================
-- 4. Protect push tokens from being accessed by other users
-- Push tokens should only be accessible via service role for notifications
-- ============================================
-- Create a secure view for partner profile access that excludes sensitive fields
CREATE OR REPLACE VIEW public.partner_profiles AS
SELECT
id,
name,
avatar_url,
is_premium,
couple_id,
created_at,
updated_at,
show_explicit_content
-- Explicitly excluding: push_token
FROM public.profiles;
-- Allow authenticated users to query the view
GRANT SELECT ON public.partner_profiles TO authenticated;
-- Add comment explaining the security rationale
COMMENT ON VIEW public.partner_profiles IS
'Secure view of profiles excluding push_token. Use this view when displaying partner information. Push tokens are only accessible via service role for sending notifications.';
-- Create a function to safely get partner info without exposing push_token
CREATE OR REPLACE FUNCTION public.get_partner_profile()
RETURNS JSONB AS $$
DECLARE
current_couple_id UUID;
partner_data JSONB;
BEGIN
-- Get current user's couple_id
SELECT couple_id INTO current_couple_id
FROM public.profiles
WHERE id = auth.uid();
IF current_couple_id IS NULL THEN
RETURN NULL;
END IF;
-- Get partner profile without sensitive fields
SELECT jsonb_build_object(
'id', p.id,
'name', p.name,
'avatar_url', p.avatar_url,
'is_premium', p.is_premium,
'couple_id', p.couple_id,
'created_at', p.created_at
) INTO partner_data
FROM public.profiles p
WHERE p.couple_id = current_couple_id
AND p.id != auth.uid();
RETURN partner_data;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
GRANT EXECUTE ON FUNCTION public.get_partner_profile() TO authenticated;
@@ -0,0 +1,17 @@
-- Allow super admins to manage subscriptions manually
-- This enables the "Grant Premium" feature in the admin dashboard
-- Allow super admins to insert new manual subscriptions
CREATE POLICY "Super admins can insert subscriptions"
ON public.subscriptions FOR INSERT
WITH CHECK (public.is_super_admin());
-- Allow super admins to update subscriptions (e.g. extending expiry)
CREATE POLICY "Super admins can update subscriptions"
ON public.subscriptions FOR UPDATE
USING (public.is_super_admin());
-- Allow super admins to delete subscriptions (e.g. revoking access)
CREATE POLICY "Super admins can delete subscriptions"
ON public.subscriptions FOR DELETE
USING (public.is_super_admin());
@@ -0,0 +1,115 @@
-- Ensure gender column exists on profiles (if not already present)
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'profiles' AND column_name = 'gender') THEN
ALTER TABLE public.profiles ADD COLUMN gender TEXT CHECK (gender IN ('male', 'female', 'non-binary', 'prefer-not-to-say'));
END IF;
END $$;
-- Add allowed_couple_genders to questions
ALTER TABLE public.questions
ADD COLUMN IF NOT EXISTS allowed_couple_genders TEXT[] DEFAULT NULL;
COMMENT ON COLUMN public.questions.allowed_couple_genders IS 'Array of allowed gender pairings (e.g., ["female+male", "female+female"]). Null means all allowed.';
-- Update get_recommended_questions to respect gender context
DROP FUNCTION IF EXISTS public.get_recommended_questions(uuid);
CREATE OR REPLACE FUNCTION public.get_recommended_questions(target_pack_id UUID DEFAULT NULL)
RETURNS TABLE (
id UUID,
text TEXT,
pack_id UUID,
intensity INT,
partner_answered BOOLEAN,
allowed_couple_genders TEXT[]
) LANGUAGE plpgsql SECURITY DEFINER AS $$
DECLARE
v_user_id UUID;
v_couple_id UUID;
v_user_gender TEXT;
v_partner_gender TEXT;
v_couple_type TEXT;
BEGIN
v_user_id := auth.uid();
-- Get user info including gender
SELECT p.couple_id, p.gender INTO v_couple_id, v_user_gender
FROM public.profiles p
WHERE p.id = v_user_id;
IF v_couple_id IS NULL THEN
RETURN;
END IF;
-- Get partner gender
SELECT p.gender INTO v_partner_gender
FROM public.profiles p
WHERE p.couple_id = v_couple_id AND p.id != v_user_id
LIMIT 1;
-- Determine couple type
IF v_user_gender IS NOT NULL AND v_partner_gender IS NOT NULL THEN
-- Sort genders to create a consistent type string
-- We assume binary genders for the primary logic as requested: male/male, male/female, female/female
IF v_user_gender < v_partner_gender THEN
v_couple_type := v_user_gender || '+' || v_partner_gender;
ELSE
v_couple_type := v_partner_gender || '+' || v_user_gender;
END IF;
END IF;
RETURN QUERY
WITH user_config_exists AS (
SELECT 1 FROM public.couple_packs WHERE couple_id = v_couple_id LIMIT 1
),
active_packs AS (
-- Case 0: Specific pack requested
SELECT target_pack_id AS pack_id
WHERE target_pack_id IS NOT NULL
UNION ALL
-- Case 1: No specific pack, config exists -> use enabled packs
SELECT cp.pack_id
FROM public.couple_packs cp
WHERE target_pack_id IS NULL
AND cp.couple_id = v_couple_id AND cp.enabled = TRUE
AND EXISTS (SELECT 1 FROM user_config_exists)
UNION ALL
-- Case 2: No specific pack, no config -> use all public packs
SELECT p.id AS pack_id
FROM public.question_packs p
WHERE target_pack_id IS NULL
AND p.is_public = TRUE
AND NOT EXISTS (SELECT 1 FROM user_config_exists)
)
SELECT
q.id,
q.text,
q.pack_id,
q.intensity,
EXISTS (
SELECT 1 FROM public.responses r
WHERE r.question_id = q.id
AND r.couple_id = v_couple_id
AND r.user_id != v_user_id
) AS partner_answered,
q.allowed_couple_genders
FROM public.questions q
WHERE q.pack_id IN (SELECT ap.pack_id FROM active_packs ap)
AND (
q.allowed_couple_genders IS NULL
OR v_couple_type IS NULL
OR v_couple_type = ANY(q.allowed_couple_genders)
)
AND NOT EXISTS (
SELECT 1 FROM public.responses r
WHERE r.question_id = q.id
AND r.user_id = v_user_id
);
END;
$$;