[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M796EA8SFR1D5MA445NKVHA9":3,"skill-same:01M796EA8SFR1D5MA445NKVHA9":60},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":37,"commitSha":38,"skillDirectory":39,"forksCount":40,"repositoryHtmlUrl":41,"repositoryHomepageUrl":6,"ownerHtmlUrl":42,"ownerBlogUrl":43,"ownerDescription":44,"updatedAt":45,"install":46,"resources":59},"01M796EA8SFR1D5MA445NKVHA9","supabase-data-handling",null,"Implement GDPR\u002FCCPA compliance with Supabase: RLS for data isolation, user deletion\nvia auth.admin.deleteUser(), data export via SQL, PII column management,\nbackup\u002Frestore workflows, and retention policies.\nUse when handling sensitive data, implementing right-to-deletion, configuring data retention,\nor auditing PII in Supabase database columns.\nTrigger: \"supabase GDPR\", \"supabase data handling\", \"supabase PII\", \"supabase compliance\",\n\"supabase data retention\", \"supabase delete user\", \"supabase data export\".","jukeyman\u002Fjukeyman-skills","jukeyman","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F142960420?v=4","01M78FR4Y3DHMMCBCC0GXXNB3F","RICK JEFFERSON","01M78FR4Z8RVQRAD31Y5J7V6EB",1,"MIT","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsaas-packs--supabase-pack--supabase-data-handling\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: supabase-data-handling\ndescription: |\n  Implement GDPR\u002FCCPA compliance with Supabase: RLS for data isolation, user deletion\n  via auth.admin.deleteUser(), data export via SQL, PII column management,\n  backup\u002Frestore workflows, and retention policies.\n  Use when handling sensitive data, implementing right-to-deletion, configuring data retention,\n  or auditing PII in Supabase database columns.\n  Trigger: \"supabase GDPR\", \"supabase data handling\", \"supabase PII\", \"supabase compliance\",\n  \"supabase data retention\", \"supabase delete user\", \"supabase data export\".\nallowed-tools: Read, Write, Edit, Bash(npx supabase:*), Bash(supabase:*), Bash(psql:*), Grep, Glob\nversion: 1.0.0\nlicense: MIT\nauthor: Jeremy Longshore \u003Cjeremy@intentsolutions.io>\ncompatible-with: claude-code, codex, openclaw\ntags: [saas, supabase, gdpr, ccpa, compliance, data-handling, privacy]\n---\n\n# Supabase Data Handling\n\n## Overview\n\nGDPR and CCPA compliance with Supabase requires a layered approach: Row Level Security (RLS) for tenant data isolation, `supabase.auth.admin.deleteUser()` for right-to-deletion requests, SQL-based data exports for subject access requests, PII detection across database columns, automated retention policies using `pg_cron`, and point-in-time recovery for backup\u002Frestore. This skill implements every compliance requirement using real Supabase SDK methods and PostgreSQL features.\n\n**When to use:** Implementing GDPR right-to-deletion, responding to data subject access requests (DSARs), auditing PII in your database, configuring automated data retention, setting up tenant isolation with RLS, or planning backup\u002Frestore procedures.\n\n## Prerequisites\n\n- `@supabase\u002Fsupabase-js` v2+ with service role key for admin operations\n- Supabase project on Pro plan (for `pg_cron` and point-in-time recovery)\n- Understanding of GDPR Articles 15-17 (access, rectification, erasure)\n- Database access via SQL Editor or `psql` for schema changes\n\n## Instructions\n\n### Step 1: RLS for Data Isolation and PII Column Management\n\nConfigure Row Level Security to ensure users can only access their own data, and identify which columns contain PII.\n\n**Tenant isolation with RLS:**\n\n```sql\n-- Enable RLS on all tables containing user data\nALTER TABLE public.profiles ENABLE ROW LEVEL SECURITY;\nALTER TABLE public.orders ENABLE ROW LEVEL SECURITY;\nALTER TABLE public.documents ENABLE ROW LEVEL SECURITY;\n\n-- Users can only read their own profile\nCREATE POLICY \"users_read_own_profile\" ON public.profiles\n  FOR SELECT USING (auth.uid() = id);\n\n-- Users can update their own profile\nCREATE POLICY \"users_update_own_profile\" ON public.profiles\n  FOR UPDATE USING (auth.uid() = id)\n  WITH CHECK (auth.uid() = id);\n\n-- Users can only see their own orders\nCREATE POLICY \"users_read_own_orders\" ON public.orders\n  FOR SELECT USING (auth.uid() = user_id);\n\n-- Organization-scoped isolation (multi-tenant)\nCREATE POLICY \"org_members_read_documents\" ON public.documents\n  FOR SELECT USING (\n    org_id IN (\n      SELECT org_id FROM public.org_members\n      WHERE user_id = auth.uid()\n    )\n  );\n```\n\n**PII column audit — identify sensitive data across your schema:**\n\n```sql\n-- Find columns likely containing PII based on naming patterns\nSELECT table_schema, table_name, column_name, data_type\nFROM information_schema.columns\nWHERE table_schema = 'public'\n  AND (\n    column_name ILIKE '%email%'\n    OR column_name ILIKE '%phone%'\n    OR column_name ILIKE '%name%'\n    OR column_name ILIKE '%address%'\n    OR column_name ILIKE '%ssn%'\n    OR column_name ILIKE '%birth%'\n    OR column_name ILIKE '%ip%'\n    OR column_name ILIKE '%location%'\n  )\nORDER BY table_name, column_name;\n\n-- Add comments to mark PII columns for documentation\nCOMMENT ON COLUMN public.profiles.email IS 'PII: email address — GDPR Art. 4(1)';\nCOMMENT ON COLUMN public.profiles.full_name IS 'PII: personal name — GDPR Art. 4(1)';\nCOMMENT ON COLUMN public.profiles.phone IS 'PII: phone number — GDPR Art. 4(1)';\n\n-- Create a PII registry view\nCREATE OR REPLACE VIEW pii_registry AS\nSELECT c.table_name, c.column_name, c.data_type,\n       pg_catalog.col_description(\n         (quote_ident(c.table_schema) || '.' || quote_ident(c.table_name))::regclass,\n         c.ordinal_position\n       ) AS pii_classification\nFROM information_schema.columns c\nWHERE c.table_schema = 'public'\n  AND pg_catalog.col_description(\n    (quote_ident(c.table_schema) || '.' || quote_ident(c.table_name))::regclass,\n    c.ordinal_position\n  ) LIKE 'PII:%';\n```\n\n**PII detection from the SDK:**\n\n```typescript\nimport { createClient } from '@supabase\u002Fsupabase-js';\n\nconst supabase = createClient(\n  process.env.NEXT_PUBLIC_SUPABASE_URL!,\n  process.env.SUPABASE_SERVICE_ROLE_KEY!,\n  { auth: { autoRefreshToken: false, persistSession: false } }\n);\n\n\u002F\u002F Scan a table for PII patterns in text columns\nasync function scanTableForPII(tableName: string, sampleSize = 100) {\n  const PII_PATTERNS = [\n    { type: 'email', regex: \u002F[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\u002Fg },\n    { type: 'phone', regex: \u002F\\b\\d{3}[-.]?\\d{3}[-.]?\\d{4}\\b\u002Fg },\n    { type: 'ssn', regex: \u002F\\b\\d{3}-\\d{2}-\\d{4}\\b\u002Fg },\n    { type: 'ip_address', regex: \u002F\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b\u002Fg },\n  ];\n\n  const { data, error } = await supabase\n    .from(tableName)\n    .select('*')\n    .limit(sampleSize);\n\n  if (error) throw error;\n\n  const findings: { column: string; type: string; count: number }[] = [];\n\n  for (const row of data ?? []) {\n    for (const [column, value] of Object.entries(row)) {\n      if (typeof value !== 'string') continue;\n      for (const pattern of PII_PATTERNS) {\n        const matches = value.match(pattern.regex);\n        if (matches) {\n          findings.push({ column, type: pattern.type, count: matches.length });\n        }\n      }\n    }\n  }\n\n  return findings;\n}\n```\n\n### Step 2: User Deletion and Data Export\n\nImplement GDPR Article 17 (right to erasure) with `auth.admin.deleteUser()` and Article 15 (right of access) with SQL-based data export.\n\n**Right to deletion — complete user erasure:**\n\n```typescript\nimport { createClient } from '@supabase\u002Fsupabase-js';\n\nconst supabase = createClient(\n  process.env.NEXT_PUBLIC_SUPABASE_URL!,\n  process.env.SUPABASE_SERVICE_ROLE_KEY!,\n  { auth: { autoRefreshToken: false, persistSession: false } }\n);\n\ninterface DeletionResult {\n  userId: string;\n  tablesProcessed: string[];\n  storageFilesDeleted: number;\n  authDeleted: boolean;\n  auditLogId: string;\n  completedAt: string;\n}\n\nasync function deleteUserData(userId: string): Promise\u003CDeletionResult> {\n  const tablesProcessed: string[] = [];\n  let storageFilesDeleted = 0;\n\n  \u002F\u002F 1. Delete user data from application tables (cascade order)\n  const tablesToPurge = ['comments', 'orders', 'documents', 'profiles'];\n\n  for (const table of tablesToPurge) {\n    const { error } = await supabase\n      .from(table)\n      .delete()\n      .eq('user_id', userId);\n\n    if (error && !error.message.includes('does not exist')) {\n      console.error(`Failed to delete from ${table}:`, error.message);\n    } else {\n      tablesProcessed.push(table);\n    }\n  }\n\n  \u002F\u002F 2. Delete user files from storage\n  const { data: buckets } = await supabase.storage.listBuckets();\n  for (const bucket of buckets ?? []) {\n    const { data: files } = await supabase.storage\n      .from(bucket.name)\n      .list(`users\u002F${userId}`);\n\n    if (files && files.length > 0) {\n      const paths = files.map((f) => `users\u002F${userId}\u002F${f.name}`);\n      const { error } = await supabase.storage\n        .from(bucket.name)\n        .remove(paths);\n\n      if (!error) storageFilesDeleted += paths.length;\n    }\n  }\n\n  \u002F\u002F 3. Delete the auth user (removes from auth.users)\n  const { error: authError } = await supabase.auth.admin.deleteUser(userId);\n  const authDeleted = !authError;\n\n  if (authError) {\n    console.error('Auth deletion failed:', authError.message);\n  }\n\n  \u002F\u002F 4. Create audit log entry (required — must survive deletion)\n  const { data: auditEntry } = await supabase\n    .from('gdpr_audit_log')\n    .insert({\n      action: 'USER_DELETION',\n      subject_id: userId,\n      tables_purged: tablesProcessed,\n      storage_files_deleted: storageFilesDeleted,\n      auth_deleted: authDeleted,\n      performed_by: 'system',\n      legal_basis: 'GDPR Article 17 — Right to Erasure',\n    })\n    .select('id')\n    .single();\n\n  return {\n    userId,\n    tablesProcessed,\n    storageFilesDeleted,\n    authDeleted,\n    auditLogId: auditEntry?.id ?? 'unknown',\n    completedAt: new Date().toISOString(),\n  };\n}\n\n\u002F\u002F GDPR audit log table (create this migration)\n\u002F\u002F CREATE TABLE gdpr_audit_log (\n\u002F\u002F   id uuid DEFAULT gen_random_uuid() PRIMARY KEY,\n\u002F\u002F   action text NOT NULL,\n\u002F\u002F   subject_id uuid NOT NULL,\n\u002F\u002F   tables_purged text[] DEFAULT '{}',\n\u002F\u002F   storage_files_deleted int DEFAULT 0,\n\u002F\u002F   auth_deleted boolean DEFAULT false,\n\u002F\u002F   performed_by text NOT NULL,\n\u002F\u002F   legal_basis text,\n\u002F\u002F   created_at timestamptz DEFAULT now()\n\u002F\u002F );\n\u002F\u002F -- Audit logs must NEVER be deleted (compliance requirement)\n\u002F\u002F ALTER TABLE gdpr_audit_log ENABLE ROW LEVEL SECURITY;\n\u002F\u002F CREATE POLICY \"admin_only\" ON gdpr_audit_log FOR ALL USING (false);\n```\n\n**Data subject access request (DSAR) — export all user data:**\n\n```typescript\nimport { createClient } from '@supabase\u002Fsupabase-js';\n\nconst supabase = createClient(\n  process.env.NEXT_PUBLIC_SUPABASE_URL!,\n  process.env.SUPABASE_SERVICE_ROLE_KEY!,\n  { auth: { autoRefreshToken: false, persistSession: false } }\n);\n\ninterface DataExport {\n  exportedAt: string;\n  subjectId: string;\n  legalBasis: string;\n  data: Record\u003Cstring, unknown[]>;\n  storageFiles: string[];\n}\n\nasync function exportUserData(userId: string): Promise\u003CDataExport> {\n  const exportData: Record\u003Cstring, unknown[]> = {};\n\n  \u002F\u002F Export from each table containing user data\n  const tables = ['profiles', 'orders', 'documents', 'comments'];\n\n  for (const table of tables) {\n    const { data, error } = await supabase\n      .from(table)\n      .select('*')\n      .eq('user_id', userId);\n\n    if (!error && data) {\n      exportData[table] = data;\n    }\n  }\n\n  \u002F\u002F List user files in storage\n  const storageFiles: string[] = [];\n  const { data: buckets } = await supabase.storage.listBuckets();\n  for (const bucket of buckets ?? []) {\n    const { data: files } = await supabase.storage\n      .from(bucket.name)\n      .list(`users\u002F${userId}`);\n\n    for (const file of files ?? []) {\n      storageFiles.push(`${bucket.name}\u002Fusers\u002F${userId}\u002F${file.name}`);\n    }\n  }\n\n  \u002F\u002F Log the export for compliance\n  await supabase.from('gdpr_audit_log').insert({\n    action: 'DATA_EXPORT',\n    subject_id: userId,\n    performed_by: 'system',\n    legal_basis: 'GDPR Article 15 — Right of Access',\n  });\n\n  return {\n    exportedAt: new Date().toISOString(),\n    subjectId: userId,\n    legalBasis: 'GDPR Article 15 — Right of Access',\n    data: exportData,\n    storageFiles,\n  };\n}\n```\n\n### Step 3: Retention Policies and Backup\u002FRestore\n\nSee [retention policies and backup\u002Frestore](references\u002Fretention-and-backup.md) for `pg_cron` automated retention schedules (30\u002F90\u002F730-day tiers), SDK-based retention monitoring, `pg_dump`\u002F`pg_restore` commands, and point-in-time recovery configuration.\n\n## Output\n\nAfter completing this skill, you will have:\n\n- **RLS tenant isolation** — row-level security policies ensuring users only access their own data\n- **PII column registry** — documented and classified PII columns across all tables\n- **PII scanner** — SDK-based pattern detection for emails, phones, SSNs, and IPs in text columns\n- **User deletion pipeline** — complete `auth.admin.deleteUser()` flow with cascade table deletion, storage cleanup, and audit logging\n- **Data export** — DSAR-compliant export of all user data from tables and storage\n- **GDPR audit log** — immutable log of all deletion and export operations with legal basis\n- **Automated retention** — `pg_cron` jobs for 30\u002F90\u002F730-day retention tiers\n- **Backup\u002Frestore** — `pg_dump`\u002F`pg_restore` commands and PITR configuration\n\n## Error Handling\n\n| Error | Cause | Solution |\n|-------|-------|----------|\n| `auth.admin.deleteUser()` returns 404 | User already deleted or wrong ID | Check `auth.users` table; may have been deleted by another process |\n| `violates foreign key constraint` during deletion | Child rows reference user | Delete in cascade order (comments → orders → profiles) or use `ON DELETE CASCADE` |\n| `permission denied for function cron.schedule` | `pg_cron` not enabled or wrong plan | Enable `pg_cron` extension; requires Supabase Pro plan |\n| `pg_dump: connection refused` | Using wrong port or pooler URL | Use direct connection (port 5432), not pooler (port 6543) for `pg_dump` |\n| `RLS policy blocks admin operations` | Service role key not used | Use `createClient` with `SUPABASE_SERVICE_ROLE_KEY` to bypass RLS |\n| Audit log entries missing | Table has RLS blocking inserts | Use `SECURITY DEFINER` function or service role for audit writes |\n| Retention job not running | `pg_cron` job disabled or errored | Check `cron.job_run_details` for error messages |\n\n## Examples\n\n**Example 1 — Handle a GDPR deletion request:**\n\n```typescript\nimport { createClient } from '@supabase\u002Fsupabase-js';\n\nconst supabase = createClient(url, serviceRoleKey, {\n  auth: { autoRefreshToken: false, persistSession: false },\n});\n\n\u002F\u002F API endpoint for GDPR deletion\nasync function handleDeletionRequest(userId: string) {\n  \u002F\u002F Verify the request is legitimate (e.g., authenticated user or admin)\n  const result = await deleteUserData(userId);\n\n  console.log(`User ${userId} deleted:`, {\n    tables: result.tablesProcessed.join(', '),\n    files: result.storageFilesDeleted,\n    auth: result.authDeleted,\n    auditId: result.auditLogId,\n  });\n\n  \u002F\u002F GDPR requires completion within 30 days\n  return { status: 'completed', auditId: result.auditLogId };\n}\n```\n\n**Example 2 — Quick PII audit:**\n\n```sql\n-- Count rows with email-like patterns in unexpected columns\nSELECT 'profiles' AS table_name, 'bio' AS column_name,\n       count(*) AS rows_with_email\nFROM public.profiles\nWHERE bio ~ '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}'\nUNION ALL\nSELECT 'orders', 'notes',\n       count(*)\nFROM public.orders\nWHERE notes ~ '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}';\n```\n\n**Example 3 — Verify retention job execution:**\n\n```typescript\nimport { createClient } from '@supabase\u002Fsupabase-js';\n\nconst supabase = createClient(url, serviceRoleKey, {\n  auth: { autoRefreshToken: false, persistSession: false },\n});\n\nasync function checkRetentionJobs() {\n  const { data, error } = await supabase.rpc('get_cron_status');\n  if (error) throw error;\n\n  for (const job of data ?? []) {\n    console.log(`Job \"${job.jobname}\": last_run=${job.last_run}, status=${job.status}`);\n  }\n}\n```\n\n## Resources\n\n- [Row Level Security — Supabase Docs](https:\u002F\u002Fsupabase.com\u002Fdocs\u002Fguides\u002Fdatabase\u002Fpostgres\u002Frow-level-security)\n- [Auth Admin deleteUser — Supabase Docs](https:\u002F\u002Fsupabase.com\u002Fdocs\u002Freference\u002Fjavascript\u002Fauth-admin-deleteuser)\n- [Database Backups — Supabase Docs](https:\u002F\u002Fsupabase.com\u002Fdocs\u002Fguides\u002Fplatform\u002Fbackups)\n- [pg_cron Extension — Supabase Docs](https:\u002F\u002Fsupabase.com\u002Fdocs\u002Fguides\u002Fdatabase\u002Fextensions\u002Fpg_cron)\n- [GDPR Developer Guide](https:\u002F\u002Fgdpr.eu\u002Fdevelopers\u002F)\n- [CCPA Compliance Guide](https:\u002F\u002Foag.ca.gov\u002Fprivacy\u002Fccpa)\n\n## Next Steps\n\n- For enterprise role-based access control, see `supabase-enterprise-rbac`\n- For security hardening and API key scoping, see `supabase-security-basics`\n- For observability and audit trail monitoring, see `supabase-observability`\n","# Supabase Data Handling\n\n## Overview\n\nGDPR and CCPA compliance with Supabase requires a layered approach: Row Level Security (RLS) for tenant data isolation, `supabase.auth.admin.deleteUser()` for right-to-deletion requests, SQL-based data exports for subject access requests, PII detection across database columns, automated retention policies using `pg_cron`, and point-in-time recovery for backup\u002Frestore. This skill implements every compliance requirement using real Supabase SDK methods and PostgreSQL features.\n\n**When to use:** Implementing GDPR right-to-deletion, responding to data subject access requests (DSARs), auditing PII in your database, configuring automated data retention, setting up tenant isolation with RLS, or planning backup\u002Frestore procedures.\n\n## Prerequisites\n\n- `@supabase\u002Fsupabase-js` v2+ with service role key for admin operations\n- Supabase project on Pro plan (for `pg_cron` and point-in-time recovery)\n- Understanding of GDPR Articles 15-17 (access, rectification, erasure)\n- Database access via SQL Editor or `psql` for schema changes\n\n## Instructions\n\n### Step 1: RLS for Data Isolation and PII Column Management\n\nConfigure Row Level Security to ensure users can only access their own data, and identify which columns contain PII.\n\n**Tenant isolation with RLS:**\n\n```sql\n-- Enable RLS on all tables containing user data\nALTER TABLE public.profiles ENABLE ROW LEVEL SECURITY;\nALTER TABLE public.orders ENABLE ROW LEVEL SECURITY;\nALTER TABLE public.documents ENABLE ROW LEVEL SECURITY;\n\n-- Users can only read their own profile\nCREATE POLICY \"users_read_own_profile\" ON public.profiles\n  FOR SELECT USING (auth.uid() = id);\n\n-- Users can update their own profile\nCREATE POLICY \"users_update_own_profile\" ON public.profiles\n  FOR UPDATE USING (auth.uid() = id)\n  WITH CHECK (auth.uid() = id);\n\n-- Users can only see their own orders\nCREATE POLICY \"users_read_own_orders\" ON public.orders\n  FOR SELECT USING (auth.uid() = user_id);\n\n-- Organization-scoped isolation (multi-tenant)\nCREATE POLICY \"org_members_read_documents\" ON public.documents\n  FOR SELECT USING (\n    org_id IN (\n      SELECT org_id FROM public.org_members\n      WHERE user_id = auth.uid()\n    )\n  );\n```\n\n**PII column audit — identify sensitive data across your schema:**\n\n```sql\n-- Find columns likely containing PII based on naming patterns\nSELECT table_schema, table_name, column_name, data_type\nFROM information_schema.columns\nWHERE table_schema = 'public'\n  AND (\n    column_name ILIKE '%email%'\n    OR column_name ILIKE '%phone%'\n    OR column_name ILIKE '%name%'\n    OR column_name ILIKE '%address%'\n    OR column_name ILIKE '%ssn%'\n    OR column_name ILIKE '%birth%'\n    OR column_name ILIKE '%ip%'\n    OR column_name ILIKE '%location%'\n  )\nORDER BY table_name, column_name;\n\n-- Add comments to mark PII columns for documentation\nCOMMENT ON COLUMN public.profiles.email IS 'PII: email address — GDPR Art. 4(1)';\nCOMMENT ON COLUMN public.profiles.full_name IS 'PII: personal name — GDPR Art. 4(1)';\nCOMMENT ON COLUMN public.profiles.phone IS 'PII: phone number — GDPR Art. 4(1)';\n\n-- Create a PII registry view\nCREATE OR REPLACE VIEW pii_registry AS\nSELECT c.table_name, c.column_name, c.data_type,\n       pg_catalog.col_description(\n         (quote_ident(c.table_schema) || '.' || quote_ident(c.table_name))::regclass,\n         c.ordinal_position\n       ) AS pii_classification\nFROM information_schema.columns c\nWHERE c.table_schema = 'public'\n  AND pg_catalog.col_description(\n    (quote_ident(c.table_schema) || '.' || quote_ident(c.table_name))::regclass,\n    c.ordinal_position\n  ) LIKE 'PII:%';\n```\n\n**PII detection from the SDK:**\n\n```typescript\nimport { createClient } from '@supabase\u002Fsupabase-js';\n\nconst supabase = createClient(\n  process.env.NEXT_PUBLIC_SUPABASE_URL!,\n  process.env.SUPABASE_SERVICE_ROLE_KEY!,\n  { auth: { autoRefreshToken: false, persistSession: false } }\n);\n\n\u002F\u002F Scan a table for PII patterns in text columns\nasync function scanTableForPII(tableName: string, sampleSize = 100) {\n  const PII_PATTERNS = [\n    { type: 'email', regex: \u002F[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\u002Fg },\n    { type: 'phone', regex: \u002F\\b\\d{3}[-.]?\\d{3}[-.]?\\d{4}\\b\u002Fg },\n    { type: 'ssn', regex: \u002F\\b\\d{3}-\\d{2}-\\d{4}\\b\u002Fg },\n    { type: 'ip_address', regex: \u002F\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b\u002Fg },\n  ];\n\n  const { data, error } = await supabase\n    .from(tableName)\n    .select('*')\n    .limit(sampleSize);\n\n  if (error) throw error;\n\n  const findings: { column: string; type: string; count: number }[] = [];\n\n  for (const row of data ?? []) {\n    for (const [column, value] of Object.entries(row)) {\n      if (typeof value !== 'string') continue;\n      for (const pattern of PII_PATTERNS) {\n        const matches = value.match(pattern.regex);\n        if (matches) {\n          findings.push({ column, type: pattern.type, count: matches.length });\n        }\n      }\n    }\n  }\n\n  return findings;\n}\n```\n\n### Step 2: User Deletion and Data Export\n\nImplement GDPR Article 17 (right to erasure) with `auth.admin.deleteUser()` and Article 15 (right of access) with SQL-based data export.\n\n**Right to deletion — complete user erasure:**\n\n```typescript\nimport { createClient } from '@supabase\u002Fsupabase-js';\n\nconst supabase = createClient(\n  process.env.NEXT_PUBLIC_SUPABASE_URL!,\n  process.env.SUPABASE_SERVICE_ROLE_KEY!,\n  { auth: { autoRefreshToken: false, persistSession: false } }\n);\n\ninterface DeletionResult {\n  userId: string;\n  tablesProcessed: string[];\n  storageFilesDeleted: number;\n  authDeleted: boolean;\n  auditLogId: string;\n  completedAt: string;\n}\n\nasync function deleteUserData(userId: string): Promise\u003CDeletionResult> {\n  const tablesProcessed: string[] = [];\n  let storageFilesDeleted = 0;\n\n  \u002F\u002F 1. Delete user data from application tables (cascade order)\n  const tablesToPurge = ['comments', 'orders', 'documents', 'profiles'];\n\n  for (const table of tablesToPurge) {\n    const { error } = await supabase\n      .from(table)\n      .delete()\n      .eq('user_id', userId);\n\n    if (error && !error.message.includes('does not exist')) {\n      console.error(`Failed to delete from ${table}:`, error.message);\n    } else {\n      tablesProcessed.push(table);\n    }\n  }\n\n  \u002F\u002F 2. Delete user files from storage\n  const { data: buckets } = await supabase.storage.listBuckets();\n  for (const bucket of buckets ?? []) {\n    const { data: files } = await supabase.storage\n      .from(bucket.name)\n      .list(`users\u002F${userId}`);\n\n    if (files && files.length > 0) {\n      const paths = files.map((f) => `users\u002F${userId}\u002F${f.name}`);\n      const { error } = await supabase.storage\n        .from(bucket.name)\n        .remove(paths);\n\n      if (!error) storageFilesDeleted += paths.length;\n    }\n  }\n\n  \u002F\u002F 3. Delete the auth user (removes from auth.users)\n  const { error: authError } = await supabase.auth.admin.deleteUser(userId);\n  const authDeleted = !authError;\n\n  if (authError) {\n    console.error('Auth deletion failed:', authError.message);\n  }\n\n  \u002F\u002F 4. Create audit log entry (required — must survive deletion)\n  const { data: auditEntry } = await supabase\n    .from('gdpr_audit_log')\n    .insert({\n      action: 'USER_DELETION',\n      subject_id: userId,\n      tables_purged: tablesProcessed,\n      storage_files_deleted: storageFilesDeleted,\n      auth_deleted: authDeleted,\n      performed_by: 'system',\n      legal_basis: 'GDPR Article 17 — Right to Erasure',\n    })\n    .select('id')\n    .single();\n\n  return {\n    userId,\n    tablesProcessed,\n    storageFilesDeleted,\n    authDeleted,\n    auditLogId: auditEntry?.id ?? 'unknown',\n    completedAt: new Date().toISOString(),\n  };\n}\n\n\u002F\u002F GDPR audit log table (create this migration)\n\u002F\u002F CREATE TABLE gdpr_audit_log (\n\u002F\u002F   id uuid DEFAULT gen_random_uuid() PRIMARY KEY,\n\u002F\u002F   action text NOT NULL,\n\u002F\u002F   subject_id uuid NOT NULL,\n\u002F\u002F   tables_purged text[] DEFAULT '{}',\n\u002F\u002F   storage_files_deleted int DEFAULT 0,\n\u002F\u002F   auth_deleted boolean DEFAULT false,\n\u002F\u002F   performed_by text NOT NULL,\n\u002F\u002F   legal_basis text,\n\u002F\u002F   created_at timestamptz DEFAULT now()\n\u002F\u002F );\n\u002F\u002F -- Audit logs must NEVER be deleted (compliance requirement)\n\u002F\u002F ALTER TABLE gdpr_audit_log ENABLE ROW LEVEL SECURITY;\n\u002F\u002F CREATE POLICY \"admin_only\" ON gdpr_audit_log FOR ALL USING (false);\n```\n\n**Data subject access request (DSAR) — export all user data:**\n\n```typescript\nimport { createClient } from '@supabase\u002Fsupabase-js';\n\nconst supabase = createClient(\n  process.env.NEXT_PUBLIC_SUPABASE_URL!,\n  process.env.SUPABASE_SERVICE_ROLE_KEY!,\n  { auth: { autoRefreshToken: false, persistSession: false } }\n);\n\ninterface DataExport {\n  exportedAt: string;\n  subjectId: string;\n  legalBasis: string;\n  data: Record\u003Cstring, unknown[]>;\n  storageFiles: string[];\n}\n\nasync function exportUserData(userId: string): Promise\u003CDataExport> {\n  const exportData: Record\u003Cstring, unknown[]> = {};\n\n  \u002F\u002F Export from each table containing user data\n  const tables = ['profiles', 'orders', 'documents', 'comments'];\n\n  for (const table of tables) {\n    const { data, error } = await supabase\n      .from(table)\n      .select('*')\n      .eq('user_id', userId);\n\n    if (!error && data) {\n      exportData[table] = data;\n    }\n  }\n\n  \u002F\u002F List user files in storage\n  const storageFiles: string[] = [];\n  const { data: buckets } = await supabase.storage.listBuckets();\n  for (const bucket of buckets ?? []) {\n    const { data: files } = await supabase.storage\n      .from(bucket.name)\n      .list(`users\u002F${userId}`);\n\n    for (const file of files ?? []) {\n      storageFiles.push(`${bucket.name}\u002Fusers\u002F${userId}\u002F${file.name}`);\n    }\n  }\n\n  \u002F\u002F Log the export for compliance\n  await supabase.from('gdpr_audit_log').insert({\n    action: 'DATA_EXPORT',\n    subject_id: userId,\n    performed_by: 'system',\n    legal_basis: 'GDPR Article 15 — Right of Access',\n  });\n\n  return {\n    exportedAt: new Date().toISOString(),\n    subjectId: userId,\n    legalBasis: 'GDPR Article 15 — Right of Access',\n    data: exportData,\n    storageFiles,\n  };\n}\n```\n\n### Step 3: Retention Policies and Backup\u002FRestore\n\nSee [retention policies and backup\u002Frestore](references\u002Fretention-and-backup.md) for `pg_cron` automated retention schedules (30\u002F90\u002F730-day tiers), SDK-based retention monitoring, `pg_dump`\u002F`pg_restore` commands, and point-in-time recovery configuration.\n\n## Output\n\nAfter completing this skill, you will have:\n\n- **RLS tenant isolation** — row-level security policies ensuring users only access their own data\n- **PII column registry** — documented and classified PII columns across all tables\n- **PII scanner** — SDK-based pattern detection for emails, phones, SSNs, and IPs in text columns\n- **User deletion pipeline** — complete `auth.admin.deleteUser()` flow with cascade table deletion, storage cleanup, and audit logging\n- **Data export** — DSAR-compliant export of all user data from tables and storage\n- **GDPR audit log** — immutable log of all deletion and export operations with legal basis\n- **Automated retention** — `pg_cron` jobs for 30\u002F90\u002F730-day retention tiers\n- **Backup\u002Frestore** — `pg_dump`\u002F`pg_restore` commands and PITR configuration\n\n## Error Handling\n\n| Error | Cause | Solution |\n|-------|-------|----------|\n| `auth.admin.deleteUser()` returns 404 | User already deleted or wrong ID | Check `auth.users` table; may have been deleted by another process |\n| `violates foreign key constraint` during deletion | Child rows reference user | Delete in cascade order (comments → orders → profiles) or use `ON DELETE CASCADE` |\n| `permission denied for function cron.schedule` | `pg_cron` not enabled or wrong plan | Enable `pg_cron` extension; requires Supabase Pro plan |\n| `pg_dump: connection refused` | Using wrong port or pooler URL | Use direct connection (port 5432), not pooler (port 6543) for `pg_dump` |\n| `RLS policy blocks admin operations` | Service role key not used | Use `createClient` with `SUPABASE_SERVICE_ROLE_KEY` to bypass RLS |\n| Audit log entries missing | Table has RLS blocking inserts | Use `SECURITY DEFINER` function or service role for audit writes |\n| Retention job not running | `pg_cron` job disabled or errored | Check `cron.job_run_details` for error messages |\n\n## Examples\n\n**Example 1 — Handle a GDPR deletion request:**\n\n```typescript\nimport { createClient } from '@supabase\u002Fsupabase-js';\n\nconst supabase = createClient(url, serviceRoleKey, {\n  auth: { autoRefreshToken: false, persistSession: false },\n});\n\n\u002F\u002F API endpoint for GDPR deletion\nasync function handleDeletionRequest(userId: string) {\n  \u002F\u002F Verify the request is legitimate (e.g., authenticated user or admin)\n  const result = await deleteUserData(userId);\n\n  console.log(`User ${userId} deleted:`, {\n    tables: result.tablesProcessed.join(', '),\n    files: result.storageFilesDeleted,\n    auth: result.authDeleted,\n    auditId: result.auditLogId,\n  });\n\n  \u002F\u002F GDPR requires completion within 30 days\n  return { status: 'completed', auditId: result.auditLogId };\n}\n```\n\n**Example 2 — Quick PII audit:**\n\n```sql\n-- Count rows with email-like patterns in unexpected columns\nSELECT 'profiles' AS table_name, 'bio' AS column_name,\n       count(*) AS rows_with_email\nFROM public.profiles\nWHERE bio ~ '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}'\nUNION ALL\nSELECT 'orders', 'notes',\n       count(*)\nFROM public.orders\nWHERE notes ~ '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}';\n```\n\n**Example 3 — Verify retention job execution:**\n\n```typescript\nimport { createClient } from '@supabase\u002Fsupabase-js';\n\nconst supabase = createClient(url, serviceRoleKey, {\n  auth: { autoRefreshToken: false, persistSession: false },\n});\n\nasync function checkRetentionJobs() {\n  const { data, error } = await supabase.rpc('get_cron_status');\n  if (error) throw error;\n\n  for (const job of data ?? []) {\n    console.log(`Job \"${job.jobname}\": last_run=${job.last_run}, status=${job.status}`);\n  }\n}\n```\n\n## Resources\n\n- [Row Level Security — Supabase Docs](https:\u002F\u002Fsupabase.com\u002Fdocs\u002Fguides\u002Fdatabase\u002Fpostgres\u002Frow-level-security)\n- [Auth Admin deleteUser — Supabase Docs](https:\u002F\u002Fsupabase.com\u002Fdocs\u002Freference\u002Fjavascript\u002Fauth-admin-deleteuser)\n- [Database Backups — Supabase Docs](https:\u002F\u002Fsupabase.com\u002Fdocs\u002Fguides\u002Fplatform\u002Fbackups)\n- [pg_cron Extension — Supabase Docs](https:\u002F\u002Fsupabase.com\u002Fdocs\u002Fguides\u002Fdatabase\u002Fextensions\u002Fpg_cron)\n- [GDPR Developer Guide](https:\u002F\u002Fgdpr.eu\u002Fdevelopers\u002F)\n- [CCPA Compliance Guide](https:\u002F\u002Foag.ca.gov\u002Fprivacy\u002Fccpa)\n\n## Next Steps\n\n- For enterprise role-based access control, see `supabase-enterprise-rbac`\n- For security hardening and API key scoping, see `supabase-security-basics`\n- For observability and audit trail monitoring, see `supabase-observability`\n",{"name":5,"tags":24,"author":32,"license":15,"version":33,"description":34,"allowed-tools":35,"compatible-with":36},[25,26,27,28,29,30,31],"saas","supabase","gdpr","ccpa","compliance","data-handling","privacy","Jeremy Longshore \u003Cjeremy@intentsolutions.io>","1.0.0","Implement GDPR\u002FCCPA compliance with Supabase: RLS for data isolation, user deletion\nvia auth.admin.deleteUser(), data export via SQL, PII column management,\nbackup\u002Frestore workflows, and retention policies.\nUse when handling sensitive data, implementing right-to-deletion, configuring data retention,\nor auditing PII in Supabase database columns.\nTrigger: \"supabase GDPR\", \"supabase data handling\", \"supabase PII\", \"supabase compliance\",\n\"supabase data retention\", \"supabase delete user\", \"supabase data export\".\n","Read, Write, Edit, Bash(npx supabase:*), Bash(supabase:*), Bash(psql:*), Grep, Glob","claude-code, codex, openclaw","main","99825ad3f3bcc6597ddcc7294a14e6e922f2b67b","skills\u002Fsaas-packs--supabase-pack--supabase-data-handling",0,"https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills","https:\u002F\u002Fgithub.com\u002Fjukeyman","https:\u002F\u002FRJBUSINESSSOLUTIONS.ORG","Credit and Finance Expert | Developer\r\n\r\nI'm Rick Jefferson, a seasoned credit and finance expert with over a decade of experience in financial literacy,","2026-07-13 07:03:29",{"source":8,"skillName":5,"commands":47,"prompt":57,"zipAvailable":58},[48,51,54],{"tool":49,"command":50},"npx","npx skills add jukeyman\u002Fjukeyman-skills --skill supabase-data-handling",{"tool":52,"command":53},"bunx","bunx skills add jukeyman\u002Fjukeyman-skills --skill supabase-data-handling",{"tool":55,"command":56},"pnpm","pnpm dlx skills add jukeyman\u002Fjukeyman-skills --skill supabase-data-handling","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsaas-packs--supabase-pack--supabase-data-handling\u002FSKILL.md",true,[],[61,68,75,82,89,97],{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":19},"01M79ANS2SM329NEP5ZCX106RR","zustand-store-creator","Create zustand store creator operations. Auto-activating skill for Frontend Development.\nTriggers on: zustand store creator, zustand store creator\nPart of the Frontend Development skill category. Use when working with zustand store creator functionality. Trigger with phrases like \"zustand store creator\", \"zustand creator\", \"zustand\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzustand-store-creator\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":19},"01M79AMZKP4YDEZ7EHG1Y7PP74","zero-trust-config-helper","Configure with zero trust config helper operations. Auto-activating skill for Security Advanced.\nTriggers on: zero trust config helper, zero trust config helper\nPart of the Security Advanced skill category. Use when configuring systems or services. Trigger with phrases like \"zero trust config helper\", \"zero helper\", \"zero\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzero-trust-config-helper\u002FSKILL.md",[],[],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":19},"01M79AMJSBCEJQNBTYNAHYN5HM","zapier-integration-helper","Assist with zapier integration helper operations. Auto-activating skill for Business Automation.\nTriggers on: zapier integration helper, zapier integration helper\nPart of the Business Automation skill category. Use when working with APIs or building integrations. Trigger with phrases like \"zapier integration helper\", \"zapier helper\", \"zapier\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzapier-integration-helper\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":19},"01M79AHJZGVMARS13VFQYRR1MP","yaml-config-validator","Validate yaml config validator operations. Auto-activating skill for DevOps Basics.\nTriggers on: yaml config validator, yaml config validator\nPart of the DevOps Basics skill category. Use when configuring systems or services. Trigger with phrases like \"yaml config validator\", \"yaml validator\", \"yaml\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fyaml-config-validator\u002FSKILL.md",[],[],{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":93,"sourceHtmlUrl":94,"categories":95,"keywords":96,"publishedAt":19},"01M79AHGDZRN0020RDQSQDPAM8","xvary-stock-research","Thesis-driven equity analysis from public SEC EDGAR and market data; \u002Fanalyze, \u002Fscore, \u002Fcompare workflows with bundled Python tools (Claude Code, Cursor, Codex).","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxvary-stock-research\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxvary-stock-research\u002FSKILL.md",[],[],{"skillNo":98,"name":99,"nameZh":6,"description":100,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":101,"categories":102,"keywords":103,"publishedAt":19},"01M79AHCYJ9FV9RMHQ24HDRN33","xss-vulnerability-scanner","Scan xss vulnerability scanner operations. Auto-activating skill for Security Fundamentals.\nTriggers on: xss vulnerability scanner, xss vulnerability scanner\nPart of the Security Fundamentals skill category. Use when working with xss vulnerability scanner functionality. Trigger with phrases like \"xss vulnerability scanner\", \"xss scanner\", \"xss\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxss-vulnerability-scanner\u002FSKILL.md",[],[]]