An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
feat: add account deletion settings
Yoshiki Miurac12ac5d34f4c
diff --git a/.env.local.example b/.env.local.exampleindex 109e5aa7..72a92ce2 100644--- a/.env.local.example+++ b/.env.local.example@@ -79,10 +79,12 @@ ENABLE_AUTH=falseANONYMOUS_USER_ID=anonymous-user# To enable Supabase authentication for multi-user deployments:-# Get your project URL and anon key from: https://supabase.com/dashboard+# Get your project URL and API keys from: https://supabase.com/dashboard# ENABLE_AUTH=true# NEXT_PUBLIC_SUPABASE_URL=[YOUR_SUPABASE_PROJECT_URL]-# NEXT_PUBLIC_SUPABASE_ANON_KEY=[YOUR_SUPABASE_ANON_KEY]+# NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=[YOUR_SUPABASE_PUBLISHABLE_KEY]+# Required for account deletion. Never expose this key to the browser.+# SUPABASE_SECRET_KEY=[YOUR_SUPABASE_SECRET_KEY]# -----------------------------------------------------------------------------# File Upload (Cloudflare R2 / S3-Compatible)diff --git a/AGENTS.md b/AGENTS.mdindex f43ae69f..3c9e099a 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -43,7 +43,8 @@ To require Supabase authentication, set:```bashENABLE_AUTH=true # or remove ENABLE_AUTH from docker-compose.yamlNEXT_PUBLIC_SUPABASE_URL=[your-supabase-url]-NEXT_PUBLIC_SUPABASE_ANON_KEY=[your-supabase-anon-key]+NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=[your-supabase-publishable-key]+SUPABASE_SECRET_KEY=[your-supabase-secret-key]```**Implementation:**diff --git a/app/api/feedback/route.ts b/app/api/feedback/route.tsindex 6d8a0400..8bd9a19a 100644--- a/app/api/feedback/route.ts+++ b/app/api/feedback/route.ts@@ -1,6 +1,7 @@import { Langfuse } from 'langfuse'import { updateMessageFeedback } from '@/lib/actions/feedback'+import { hasSupabasePublicConfig } from '@/lib/supabase/keys'import { createClient } from '@/lib/supabase/server'import { isTracingEnabled } from '@/lib/utils/telemetry'@@ -46,10 +47,8 @@ export async function POST(req: Request) {// Get current user for RLS contextlet userId: string | null = null- const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL- const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY- if (supabaseUrl && supabaseAnonKey) {+ if (hasSupabasePublicConfig()) {const supabase = await createClient()const {data: { user }diff --git a/app/api/upload/route.ts b/app/api/upload/route.tsindex 483e9bde..a2561c6c 100644--- a/app/api/upload/route.ts+++ b/app/api/upload/route.ts@@ -5,6 +5,7 @@ import { PutObjectCommand } from '@aws-sdk/client-s3'import { getCurrentUserId } from '@/lib/auth/get-current-user'import {getR2Client,+ isObjectStorageConfigured,R2_BUCKET_NAME,R2_PUBLIC_URL} from '@/lib/storage/r2-client'@@ -103,13 +104,3 @@ async function uploadFileToR2(file: File, userId: string, chatId: string) {throw new Error('Upload failed: ' + error.message)}}--function isObjectStorageConfigured() {- const hasCredentials =- !!process.env.R2_ACCESS_KEY_ID && !!process.env.R2_SECRET_ACCESS_KEY- const hasEndpointOrAccount =- !!process.env.S3_ENDPOINT || !!process.env.R2_ACCOUNT_ID- const hasPublicUrl = !!R2_PUBLIC_URL-- return hasCredentials && hasEndpointOrAccount && hasPublicUrl-}diff --git a/app/layout.tsx b/app/layout.tsxindex 3487b883..c1b156d6 100644--- a/app/layout.tsx+++ b/app/layout.tsx@@ -5,6 +5,7 @@ import { Analytics } from '@vercel/analytics/next'import { getCurrentUserId } from '@/lib/auth/get-current-user'import { UserProvider } from '@/lib/contexts/user-context'+import { hasSupabasePublicConfig } from '@/lib/supabase/keys'import { createClient } from '@/lib/supabase/server'import { cn } from '@/lib/utils'@@ -57,10 +58,8 @@ export default async function RootLayout({children: React.ReactNode}>) {let user = null- const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL- const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY- if (supabaseUrl && supabaseAnonKey) {+ if (hasSupabasePublicConfig()) {const supabase = await createClient()const {data: { user: supabaseUser }diff --git a/components/account-settings-dialog.tsx b/components/account-settings-dialog.tsxnew file mode 100644index 00000000..a8d6bdb7--- /dev/null+++ b/components/account-settings-dialog.tsx@@ -0,0 +1,209 @@+'use client'++import { useState, useTransition } from 'react'+import { useRouter } from 'next/navigation'+import { useTheme } from 'next-themes'++import type { User } from '@supabase/supabase-js'+import { Laptop, Moon, Sun, Trash2 } from 'lucide-react'+import { toast } from 'sonner'++import { deleteAccount } from '@/lib/actions/account'+import { createClient } from '@/lib/supabase/client'++import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+ AlertDialogTrigger+} from '@/components/ui/alert-dialog'+import { Button } from '@/components/ui/button'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle+} from '@/components/ui/dialog'+import { Separator } from '@/components/ui/separator'+import { Spinner } from '@/components/ui/spinner'++interface AccountSettingsDialogProps {+ open: boolean+ onOpenChange: (open: boolean) => void+ user: User+}++const themeOptions = [+ { value: 'light', label: 'Light', icon: Sun },+ { value: 'dark', label: 'Dark', icon: Moon },+ { value: 'system', label: 'System', icon: Laptop }+]++export function AccountSettingsDialog({+ open,+ onOpenChange,+ user+}: AccountSettingsDialogProps) {+ const router = useRouter()+ const { setTheme, theme } = useTheme()+ const [isDeleting, startDeleteTransition] = useTransition()+ const [confirmOpen, setConfirmOpen] = useState(false)+ const activeTheme = theme ?? 'system'++ const userName =+ user.user_metadata?.full_name || user.user_metadata?.name || 'User'++ const handleDeleteAccount = () => {+ startDeleteTransition(async () => {+ const result = await deleteAccount()++ if (result.success) {+ try {+ await createClient().auth.signOut()+ } catch (error) {+ console.error('Failed to clear client session:', error)+ }++ toast.success('Account deleted')+ setConfirmOpen(false)+ onOpenChange(false)+ router.push('/')+ router.refresh()+ return+ }++ toast.error(result.error ?? 'Failed to delete account')+ })+ }++ return (+ <Dialog+ open={open}+ onOpenChange={nextOpen => {+ if (!isDeleting) {+ if (!nextOpen) {+ setConfirmOpen(false)+ }+ onOpenChange(nextOpen)+ }+ }}+ >+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>Account</DialogTitle>+ <DialogDescription>+ Manage your account preferences and data.+ </DialogDescription>+ </DialogHeader>++ <div className="grid gap-6">+ <section className="grid gap-3">+ <div className="grid gap-1">+ <h3 className="text-sm font-medium">Profile</h3>+ <div className="text-sm text-muted-foreground">+ <p className="truncate">{userName}</p>+ <p className="truncate">{user.email}</p>+ </div>+ </div>+ </section>++ <Separator />++ <section className="grid gap-3">+ <div className="grid gap-1">+ <h3 className="text-sm font-medium">Theme</h3>+ <p className="text-sm text-muted-foreground">+ Choose how Morphic appears on this device.+ </p>+ </div>+ <div className="grid grid-cols-3 gap-2">+ {themeOptions.map(option => {+ const Icon = option.icon+ const selected = activeTheme === option.value++ return (+ <Button+ key={option.value}+ type="button"+ variant={selected ? 'secondary' : 'outline'}+ className="h-16 flex-col gap-1.5 px-2"+ aria-pressed={selected}+ onClick={() => setTheme(option.value)}+ >+ <Icon className="size-4" />+ <span className="text-xs">{option.label}</span>+ </Button>+ )+ })}+ </div>+ </section>++ <Separator />++ <section className="grid gap-3">+ <div className="grid gap-1">+ <h3 className="text-sm font-medium text-destructive">+ Delete account+ </h3>+ <p className="text-sm text-muted-foreground">+ Permanently delete your account, chat history, and uploaded+ files. This action cannot be undone.+ </p>+ </div>++ <AlertDialog+ open={confirmOpen}+ onOpenChange={nextOpen => {+ if (!isDeleting) {+ setConfirmOpen(nextOpen)+ }+ }}+ >+ <AlertDialogTrigger asChild>+ <Button+ type="button"+ variant="destructive"+ className="w-fit gap-2"+ disabled={isDeleting}+ >+ <Trash2 className="size-4" />+ Delete account+ </Button>+ </AlertDialogTrigger>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Delete your account?</AlertDialogTitle>+ <AlertDialogDescription>+ This action cannot be undone. Your account, chat history,+ and uploaded files will be permanently deleted.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={isDeleting}>+ Cancel+ </AlertDialogCancel>+ <AlertDialogAction+ disabled={isDeleting}+ onClick={event => {+ event.preventDefault()+ handleDeleteAccount()+ }}+ className="bg-destructive text-destructive-foreground hover:bg-destructive/90"+ >+ {isDeleting ? <Spinner /> : 'Delete account'}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </section>+ </div>+ </DialogContent>+ </Dialog>+ )+}diff --git a/components/user-menu.tsx b/components/user-menu.tsxindex b56e43b2..bfc0fccc 100644--- a/components/user-menu.tsx+++ b/components/user-menu.tsx@@ -1,9 +1,10 @@'use client'+import { useState } from 'react'import { useRouter } from 'next/navigation'-import { User } from '@supabase/supabase-js'-import { Link2, LogOut, Palette } from 'lucide-react'+import type { User } from '@supabase/supabase-js'+import { Link2, LogOut, UserRound } from 'lucide-react'import { createClient } from '@/lib/supabase/client'@@ -20,9 +21,10 @@ import {DropdownMenuTrigger} from '@/components/ui/dropdown-menu'+import { AccountSettingsDialog } from '@/components/account-settings-dialog'+import { Button } from './ui/button'import { ExternalLinkItems } from './external-link-items'-import { ThemeMenuItems } from './theme-menu-items'interface UserMenuProps {user: User@@ -30,6 +32,8 @@ interface UserMenuProps {export default function UserMenu({ user }: UserMenuProps) {const router = useRouter()+ const [menuOpen, setMenuOpen] = useState(false)+ const [accountOpen, setAccountOpen] = useState(false)const userName =user.user_metadata?.full_name || user.user_metadata?.name || 'User'const avatarUrl =@@ -56,52 +60,66 @@ export default function UserMenu({ user }: UserMenuProps) {router.refresh()}+ const handleOpenAccount = () => {+ setMenuOpen(false)+ window.setTimeout(() => setAccountOpen(true), 0)+ }+return (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button variant="ghost" className="relative size-6 rounded-full">- <Avatar className="size-6">- <AvatarImage src={avatarUrl} alt={userName} />- <AvatarFallback>{getInitials(userName, user.email)}</AvatarFallback>- </Avatar>- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent className="w-60" align="end" forceMount>- <DropdownMenuLabel className="font-normal">- <div className="flex flex-col space-y-1">- <p className="text-sm font-medium leading-none truncate">- {userName}- </p>- <p className="text-xs leading-none text-muted-foreground truncate">- {user.email}- </p>- </div>- </DropdownMenuLabel>- <DropdownMenuSeparator />- <DropdownMenuSub>- <DropdownMenuSubTrigger>- <Palette className="mr-2 h-4 w-4" />- <span>Theme</span>- </DropdownMenuSubTrigger>- <DropdownMenuSubContent>- <ThemeMenuItems />- </DropdownMenuSubContent>- </DropdownMenuSub>- <DropdownMenuSub>- <DropdownMenuSubTrigger>- <Link2 className="mr-2 h-4 w-4" />- <span>Links</span>- </DropdownMenuSubTrigger>- <DropdownMenuSubContent>- <ExternalLinkItems />- </DropdownMenuSubContent>- </DropdownMenuSub>- <DropdownMenuSeparator />- <DropdownMenuItem onClick={handleLogout}>- <LogOut className="mr-2 h-4 w-4" />- <span>Logout</span>- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>+ <>+ <DropdownMenu open={menuOpen} onOpenChange={setMenuOpen} modal={false}>+ <DropdownMenuTrigger asChild>+ <Button variant="ghost" className="relative size-6 rounded-full">+ <Avatar className="size-6">+ <AvatarImage src={avatarUrl} alt={userName} />+ <AvatarFallback>+ {getInitials(userName, user.email)}+ </AvatarFallback>+ </Avatar>+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent className="w-60" align="end" forceMount>+ <DropdownMenuLabel className="font-normal">+ <div className="flex flex-col space-y-1">+ <p className="text-sm font-medium leading-none truncate">+ {userName}+ </p>+ <p className="text-xs leading-none text-muted-foreground truncate">+ {user.email}+ </p>+ </div>+ </DropdownMenuLabel>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onSelect={event => {+ event.preventDefault()+ handleOpenAccount()+ }}+ >+ <UserRound className="size-4" />+ <span>Account</span>+ </DropdownMenuItem>+ <DropdownMenuSub>+ <DropdownMenuSubTrigger className="gap-2">+ <Link2 className="size-4" />+ <span>Links</span>+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent>+ <ExternalLinkItems />+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ <DropdownMenuSeparator />+ <DropdownMenuItem onClick={handleLogout}>+ <LogOut className="size-4" />+ <span>Logout</span>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ <AccountSettingsDialog+ open={accountOpen}+ onOpenChange={setAccountOpen}+ user={user}+ />+ </>)}diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.mdindex 752f082b..7d66e27c 100644--- a/docs/CONFIGURATION.md+++ b/docs/CONFIGURATION.md@@ -162,12 +162,15 @@ For multi-user deployments:```bashENABLE_AUTH=trueNEXT_PUBLIC_SUPABASE_URL=[YOUR_SUPABASE_PROJECT_URL]-NEXT_PUBLIC_SUPABASE_ANON_KEY=[YOUR_SUPABASE_ANON_KEY]+NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=[YOUR_SUPABASE_PUBLISHABLE_KEY]+# Required for account deletion. Keep server-side only.+SUPABASE_SECRET_KEY=[YOUR_SUPABASE_SECRET_KEY]```3. Obtain your credentials from the Supabase dashboard:- **Project URL**: Settings > API > Project URL- - **Anon Key**: Settings > API > Project API keys > anon/public+ - **Publishable Key**: Settings > API Keys > publishable key (`sb_publishable_...`)+ - **Secret Key**: Settings > API Keys > secret key (`sb_secret_...`)## Guest Modediff --git a/docs/DOCKER.md b/docs/DOCKER.mdindex d59f7c42..54f9ebe6 100644--- a/docs/DOCKER.md+++ b/docs/DOCKER.md@@ -106,7 +106,8 @@ To enable Supabase authentication for multi-user deployments:```bashNEXT_PUBLIC_SUPABASE_URL=your-supabase-url-NEXT_PUBLIC_SUPABASE_ANON_KEY=your-supabase-anon-key+NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=your-supabase-publishable-key+SUPABASE_SECRET_KEY=your-supabase-secret-keyENABLE_AUTH=true```diff --git a/drizzle/0011_feedback_anonymization.sql b/drizzle/0011_feedback_anonymization.sqlnew file mode 100644index 00000000..b5bc798e--- /dev/null+++ b/drizzle/0011_feedback_anonymization.sql@@ -0,0 +1,14 @@+DO $$+BEGIN+ IF NOT EXISTS (+ SELECT 1 FROM pg_policies+ WHERE schemaname = 'public' AND tablename = 'feedback' AND policyname = 'users_anonymize_own_feedback'+ ) THEN+ CREATE POLICY "users_anonymize_own_feedback" ON "feedback"+ AS PERMISSIVE+ FOR UPDATE+ TO public+ USING (user_id = current_setting('app.current_user_id', true))+ WITH CHECK (user_id IS NULL);+ END IF;+END $$;diff --git a/drizzle/meta/0011_snapshot.json b/drizzle/meta/0011_snapshot.jsonnew file mode 100644index 00000000..40ad4dc0--- /dev/null+++ b/drizzle/meta/0011_snapshot.json@@ -0,0 +1,714 @@+{+ "id": "c3a12970-7c51-4d78-9340-5212af9eb46b",+ "prevId": "413889c5-099c-4a0c-8a67-b5b1d0605366",+ "version": "7",+ "dialect": "postgresql",+ "tables": {+ "public.chats": {+ "name": "chats",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": true,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true+ },+ "visibility": {+ "name": "visibility",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": true,+ "default": "'private'"+ }+ },+ "indexes": {+ "chats_user_id_idx": {+ "name": "chats_user_id_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chats_user_id_created_at_idx": {+ "name": "chats_user_id_created_at_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chats_created_at_idx": {+ "name": "chats_created_at_idx",+ "columns": [+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chats_id_user_id_idx": {+ "name": "chats_id_user_id_idx",+ "columns": [+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {+ "users_manage_own_chats": {+ "name": "users_manage_own_chats",+ "as": "PERMISSIVE",+ "for": "ALL",+ "to": ["public"],+ "using": "user_id = current_setting('app.current_user_id', true)",+ "withCheck": "user_id = current_setting('app.current_user_id', true)"+ },+ "public_chats_readable": {+ "name": "public_chats_readable",+ "as": "PERMISSIVE",+ "for": "SELECT",+ "to": ["public"],+ "using": "visibility = 'public'"+ }+ },+ "checkConstraints": {},+ "isRLSEnabled": true+ },+ "public.feedback": {+ "name": "feedback",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false+ },+ "sentiment": {+ "name": "sentiment",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": true+ },+ "message": {+ "name": "message",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "page_url": {+ "name": "page_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "feedback_user_id_idx": {+ "name": "feedback_user_id_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "feedback_created_at_idx": {+ "name": "feedback_created_at_idx",+ "columns": [+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {+ "feedback_select_policy": {+ "name": "feedback_select_policy",+ "as": "PERMISSIVE",+ "for": "SELECT",+ "to": ["public"],+ "using": "true"+ },+ "anyone_can_insert_feedback": {+ "name": "anyone_can_insert_feedback",+ "as": "PERMISSIVE",+ "for": "INSERT",+ "to": ["public"],+ "withCheck": "true"+ },+ "users_anonymize_own_feedback": {+ "name": "users_anonymize_own_feedback",+ "as": "PERMISSIVE",+ "for": "UPDATE",+ "to": ["public"],+ "using": "user_id = current_setting('app.current_user_id', true)",+ "withCheck": "user_id IS NULL"+ }+ },+ "checkConstraints": {},+ "isRLSEnabled": true+ },+ "public.messages": {+ "name": "messages",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": true,+ "notNull": true+ },+ "chat_id": {+ "name": "chat_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "messages_chat_id_idx": {+ "name": "messages_chat_id_idx",+ "columns": [+ {+ "expression": "chat_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "messages_chat_id_created_at_idx": {+ "name": "messages_chat_id_created_at_idx",+ "columns": [+ {+ "expression": "chat_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "messages_chat_id_chats_id_fk": {+ "name": "messages_chat_id_chats_id_fk",+ "tableFrom": "messages",+ "tableTo": "chats",+ "columnsFrom": ["chat_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {+ "users_manage_chat_messages": {+ "name": "users_manage_chat_messages",+ "as": "PERMISSIVE",+ "for": "ALL",+ "to": ["public"],+ "using": "EXISTS (\n SELECT 1 FROM \"chats\"\n WHERE \"chats\".id = chat_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )",+ "withCheck": "EXISTS (\n SELECT 1 FROM \"chats\"\n WHERE \"chats\".id = chat_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )"+ },+ "public_chat_messages_readable": {+ "name": "public_chat_messages_readable",+ "as": "PERMISSIVE",+ "for": "SELECT",+ "to": ["public"],+ "using": "EXISTS (\n SELECT 1 FROM \"chats\"\n WHERE \"chats\".id = chat_id\n AND \"chats\".visibility = 'public'\n )"+ }+ },+ "checkConstraints": {},+ "isRLSEnabled": true+ },+ "public.parts": {+ "name": "parts",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": true,+ "notNull": true+ },+ "message_id": {+ "name": "message_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true+ },+ "order": {+ "name": "order",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": true+ },+ "text_text": {+ "name": "text_text",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "reasoning_text": {+ "name": "reasoning_text",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "file_media_type": {+ "name": "file_media_type",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false+ },+ "file_filename": {+ "name": "file_filename",+ "type": "varchar(1024)",+ "primaryKey": false,+ "notNull": false+ },+ "file_url": {+ "name": "file_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "source_url_source_id": {+ "name": "source_url_source_id",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false+ },+ "source_url_url": {+ "name": "source_url_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "source_url_title": {+ "name": "source_url_title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "source_document_source_id": {+ "name": "source_document_source_id",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false+ },+ "source_document_media_type": {+ "name": "source_document_media_type",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false+ },+ "source_document_title": {+ "name": "source_document_title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "source_document_filename": {+ "name": "source_document_filename",+ "type": "varchar(1024)",+ "primaryKey": false,+ "notNull": false+ },+ "source_document_url": {+ "name": "source_document_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "source_document_snippet": {+ "name": "source_document_snippet",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "tool_tool_call_id": {+ "name": "tool_tool_call_id",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false+ },+ "tool_state": {+ "name": "tool_state",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false+ },+ "tool_error_text": {+ "name": "tool_error_text",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "tool_search_input": {+ "name": "tool_search_input",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_search_output": {+ "name": "tool_search_output",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_fetch_input": {+ "name": "tool_fetch_input",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_fetch_output": {+ "name": "tool_fetch_output",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_question_input": {+ "name": "tool_question_input",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_question_output": {+ "name": "tool_question_output",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_todoWrite_input": {+ "name": "tool_todoWrite_input",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_todoWrite_output": {+ "name": "tool_todoWrite_output",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_todoRead_input": {+ "name": "tool_todoRead_input",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_todoRead_output": {+ "name": "tool_todoRead_output",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_dynamic_input": {+ "name": "tool_dynamic_input",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_dynamic_output": {+ "name": "tool_dynamic_output",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_dynamic_name": {+ "name": "tool_dynamic_name",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false+ },+ "tool_dynamic_type": {+ "name": "tool_dynamic_type",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false+ },+ "data_prefix": {+ "name": "data_prefix",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false+ },+ "data_content": {+ "name": "data_content",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "data_id": {+ "name": "data_id",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false+ },+ "provider_metadata": {+ "name": "provider_metadata",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "parts_message_id_idx": {+ "name": "parts_message_id_idx",+ "columns": [+ {+ "expression": "message_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "parts_message_id_order_idx": {+ "name": "parts_message_id_order_idx",+ "columns": [+ {+ "expression": "message_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "order",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "parts_message_id_messages_id_fk": {+ "name": "parts_message_id_messages_id_fk",+ "tableFrom": "parts",+ "tableTo": "messages",+ "columnsFrom": ["message_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {+ "users_manage_message_parts": {+ "name": "users_manage_message_parts",+ "as": "PERMISSIVE",+ "for": "ALL",+ "to": ["public"],+ "using": "EXISTS (\n SELECT 1 FROM \"messages\"\n INNER JOIN \"chats\" ON \"chats\".id = \"messages\".chat_id\n WHERE \"messages\".id = message_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )",+ "withCheck": "EXISTS (\n SELECT 1 FROM \"messages\"\n INNER JOIN \"chats\" ON \"chats\".id = \"messages\".chat_id\n WHERE \"messages\".id = message_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )"+ },+ "public_chat_parts_readable": {+ "name": "public_chat_parts_readable",+ "as": "PERMISSIVE",+ "for": "SELECT",+ "to": ["public"],+ "using": "EXISTS (\n SELECT 1 FROM \"messages\"\n INNER JOIN \"chats\" ON \"chats\".id = \"messages\".chat_id\n WHERE \"messages\".id = message_id\n AND \"chats\".visibility = 'public'\n )"+ }+ },+ "checkConstraints": {+ "text_text_required": {+ "name": "text_text_required",+ "value": "(type != 'text' OR text_text IS NOT NULL)"+ },+ "reasoning_text_required": {+ "name": "reasoning_text_required",+ "value": "(type != 'reasoning' OR reasoning_text IS NOT NULL)"+ },+ "file_fields_required": {+ "name": "file_fields_required",+ "value": "(type != 'file' OR (file_media_type IS NOT NULL AND file_filename IS NOT NULL AND file_url IS NOT NULL))"+ },+ "tool_state_valid": {+ "name": "tool_state_valid",+ "value": "(tool_state IS NULL OR tool_state IN ('input-streaming', 'input-available', 'output-available', 'output-error'))"+ },+ "tool_fields_required": {+ "name": "tool_fields_required",+ "value": "(type NOT LIKE 'tool-%' OR (tool_tool_call_id IS NOT NULL AND tool_state IS NOT NULL))"+ }+ },+ "isRLSEnabled": true+ }+ },+ "enums": {},+ "schemas": {},+ "sequences": {},+ "roles": {},+ "policies": {},+ "views": {},+ "_meta": {+ "columns": {},+ "schemas": {},+ "tables": {}+ }+}diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.jsonindex 8ff5843c..a4a82ed7 100644--- a/drizzle/meta/_journal.json+++ b/drizzle/meta/_journal.json@@ -78,6 +78,13 @@"when": 1757242257993,"tag": "0010_lonely_kang","breakpoints": true+ },+ {+ "idx": 11,+ "version": "7",+ "when": 1779207879792,+ "tag": "0011_feedback_anonymization",+ "breakpoints": true}]}diff --git a/drizzle/schema.ts b/drizzle/schema.tsindex 6a539555..2646371d 100644--- a/drizzle/schema.ts+++ b/drizzle/schema.ts@@ -236,6 +236,13 @@ export const feedback = pgTable(as: 'permissive',for: 'insert',to: ['public']+ }),+ pgPolicy('users_anonymize_own_feedback', {+ as: 'permissive',+ for: 'update',+ to: ['public'],+ using: sql`user_id = current_setting('app.current_user_id', true)`,+ withCheck: sql`user_id IS NULL`})])diff --git a/lib/actions/__tests__/account.test.ts b/lib/actions/__tests__/account.test.tsnew file mode 100644index 00000000..165e69af--- /dev/null+++ b/lib/actions/__tests__/account.test.ts@@ -0,0 +1,141 @@+import { revalidateTag } from 'next/cache'++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { getCurrentUser } from '@/lib/auth/get-current-user'+import * as dbActions from '@/lib/db/actions'+import { deleteUserObjects } from '@/lib/storage/r2-client'+import { createAdminClient } from '@/lib/supabase/admin'++import { deleteAccount } from '../account'++vi.mock('@/lib/auth/get-current-user')+vi.mock('@/lib/db/actions')+vi.mock('@/lib/storage/r2-client')+vi.mock('@/lib/supabase/admin')++const originalEnableAuth = process.env.ENABLE_AUTH++describe('Account Actions', () => {+ const user = { id: '550e8400-e29b-41d4-a716-446655440000' }+ const deleteUser = vi.fn()++ beforeEach(() => {+ vi.clearAllMocks()+ process.env.ENABLE_AUTH = 'true'++ vi.mocked(getCurrentUser).mockResolvedValue(user as any)+ vi.mocked(dbActions.deleteUserChats).mockResolvedValue({ success: true })+ vi.mocked(dbActions.anonymizeUserFeedback).mockResolvedValue({+ success: true+ })+ vi.mocked(deleteUserObjects).mockResolvedValue({+ deletedCount: 0,+ skipped: true+ })+ deleteUser.mockResolvedValue({ data: { user: null }, error: null })+ vi.mocked(createAdminClient).mockReturnValue({+ auth: { admin: { deleteUser } }+ } as any)+ })++ afterEach(() => {+ process.env.ENABLE_AUTH = originalEnableAuth+ })++ it('returns an error in anonymous mode', async () => {+ process.env.ENABLE_AUTH = 'false'++ const result = await deleteAccount()++ expect(result).toEqual({+ success: false,+ error: 'Account deletion is unavailable in anonymous mode.'+ })+ expect(getCurrentUser).not.toHaveBeenCalled()+ expect(dbActions.deleteUserChats).not.toHaveBeenCalled()+ })++ it('returns an error when the user is not authenticated', async () => {+ vi.mocked(getCurrentUser).mockResolvedValue(null)++ const result = await deleteAccount()++ expect(result).toEqual({+ success: false,+ error: 'User not authenticated'+ })+ expect(createAdminClient).not.toHaveBeenCalled()+ expect(dbActions.deleteUserChats).not.toHaveBeenCalled()+ })++ it('returns an error when Supabase admin is not configured', async () => {+ vi.mocked(createAdminClient).mockImplementation(() => {+ throw new Error('Missing secret key')+ })++ const result = await deleteAccount()++ expect(result).toEqual({+ success: false,+ error: 'Account deletion is not configured. Set SUPABASE_SECRET_KEY.'+ })+ expect(dbActions.deleteUserChats).not.toHaveBeenCalled()+ })++ it('deletes app data, anonymizes feedback, uploaded files, and auth user', async () => {+ const result = await deleteAccount()++ expect(result).toEqual({ success: true })+ expect(dbActions.deleteUserChats).toHaveBeenCalledWith(user.id)+ expect(dbActions.anonymizeUserFeedback).toHaveBeenCalledWith(user.id)+ expect(deleteUserObjects).toHaveBeenCalledWith(user.id)+ expect(deleteUser).toHaveBeenCalledWith(user.id)+ expect(revalidateTag).toHaveBeenCalledWith('chat', 'max')+ })++ it('stops before storage and auth deletion when app data deletion fails', async () => {+ vi.mocked(dbActions.deleteUserChats).mockResolvedValue({+ success: false,+ error: 'Failed to delete user chats'+ })++ const result = await deleteAccount()++ expect(result).toEqual({+ success: false,+ error: 'Failed to delete user chats'+ })+ expect(deleteUserObjects).not.toHaveBeenCalled()+ expect(deleteUser).not.toHaveBeenCalled()+ })++ it('stops before storage and auth deletion when feedback anonymization fails', async () => {+ vi.mocked(dbActions.anonymizeUserFeedback).mockResolvedValue({+ success: false,+ error: 'Failed to anonymize user feedback'+ })++ const result = await deleteAccount()++ expect(result).toEqual({+ success: false,+ error: 'Failed to anonymize user feedback'+ })+ expect(deleteUserObjects).not.toHaveBeenCalled()+ expect(deleteUser).not.toHaveBeenCalled()+ })++ it('stops before auth deletion when uploaded file deletion fails', async () => {+ vi.mocked(deleteUserObjects).mockRejectedValue(new Error('Storage error'))++ const result = await deleteAccount()++ expect(result).toEqual({+ success: false,+ error: 'Storage error'+ })+ expect(dbActions.deleteUserChats).toHaveBeenCalledWith(user.id)+ expect(deleteUser).not.toHaveBeenCalled()+ })+})diff --git a/lib/actions/account.ts b/lib/actions/account.tsnew file mode 100644index 00000000..3814242a--- /dev/null+++ b/lib/actions/account.ts@@ -0,0 +1,79 @@+'use server'++import { revalidateTag } from 'next/cache'++import { getCurrentUser } from '@/lib/auth/get-current-user'+import * as dbActions from '@/lib/db/actions'+import { deleteUserObjects } from '@/lib/storage/r2-client'+import { createAdminClient } from '@/lib/supabase/admin'++function getErrorMessage(error: unknown) {+ if (error instanceof Error && error.message) {+ return error.message+ }++ return 'Failed to delete account'+}++export async function deleteAccount(): Promise<{+ success: boolean+ error?: string+}> {+ if (process.env.ENABLE_AUTH === 'false') {+ return {+ success: false,+ error: 'Account deletion is unavailable in anonymous mode.'+ }+ }++ const user = await getCurrentUser()+ if (!user) {+ return { success: false, error: 'User not authenticated' }+ }++ let adminClient: ReturnType<typeof createAdminClient>+ try {+ adminClient = createAdminClient()+ } catch (error) {+ console.error('Supabase admin client is not configured:', error)+ return {+ success: false,+ error: 'Account deletion is not configured. Set SUPABASE_SECRET_KEY.'+ }+ }++ try {+ const deleteChatsResult = await dbActions.deleteUserChats(user.id)+ if (!deleteChatsResult.success) {+ return {+ success: false,+ error: deleteChatsResult.error ?? 'Failed to delete account data'+ }+ }++ const anonymizeFeedbackResult = await dbActions.anonymizeUserFeedback(+ user.id+ )+ if (!anonymizeFeedbackResult.success) {+ return {+ success: false,+ error:+ anonymizeFeedbackResult.error ?? 'Failed to anonymize user feedback'+ }+ }++ await deleteUserObjects(user.id)++ const { error } = await adminClient.auth.admin.deleteUser(user.id)+ if (error) {+ throw error+ }++ revalidateTag('chat', 'max')++ return { success: true }+ } catch (error) {+ console.error(`Error deleting account for user ${user.id}:`, error)+ return { success: false, error: getErrorMessage(error) }+ }+}diff --git a/lib/actions/site-feedback.ts b/lib/actions/site-feedback.tsindex ae7157dd..7e29a5ee 100644--- a/lib/actions/site-feedback.ts+++ b/lib/actions/site-feedback.ts@@ -3,6 +3,7 @@import { db } from '@/lib/db'import { feedback, generateId } from '@/lib/db/schema'import { withOptionalRLS } from '@/lib/db/with-rls'+import { hasSupabasePublicConfig } from '@/lib/supabase/keys'import { createClient } from '@/lib/supabase/server'export async function submitFeedback(data: {@@ -14,10 +15,8 @@ export async function submitFeedback(data: {// Get current user if logged inlet userId: string | undefinedlet userEmail: string | undefined- const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL- const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY- if (supabaseUrl && supabaseAnonKey) {+ if (hasSupabasePublicConfig()) {const supabase = await createClient()const {data: { user }diff --git a/lib/auth/get-current-user.ts b/lib/auth/get-current-user.tsindex ad48b90b..6b27740f 100644--- a/lib/auth/get-current-user.ts+++ b/lib/auth/get-current-user.ts@@ -1,12 +1,10 @@+import { hasSupabasePublicConfig } from '@/lib/supabase/keys'import { createClient } from '@/lib/supabase/server'import { perfLog } from '@/lib/utils/perf-logging'import { incrementAuthCallCount } from '@/lib/utils/perf-tracking'export async function getCurrentUser() {- const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL- const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY-- if (!supabaseUrl || !supabaseAnonKey) {+ if (!hasSupabasePublicConfig()) {return null // Supabase is not configured}diff --git a/lib/db/actions.ts b/lib/db/actions.tsindex d1910619..a3c2b5b4 100644--- a/lib/db/actions.ts+++ b/lib/db/actions.ts@@ -13,7 +13,7 @@ import { perfLog, perfTime } from '@/lib/utils/perf-logging'import { incrementDbOperationCount } from '@/lib/utils/perf-tracking'import type { Chat, Message } from './schema'-import { chats, generateId, messages, parts } from './schema'+import { chats, feedback, generateId, messages, parts } from './schema'import { withOptionalRLS, withRLS } from './with-rls'import { db } from '.'@@ -344,6 +344,45 @@ export async function deleteChat(}}+/**+ * Delete all chats for a user.+ * Messages and parts are removed by database cascades.+ */+export async function deleteUserChats(+ userId: string+): Promise<{ success: boolean; error?: string }> {+ try {+ return withRLS(userId, async tx => {+ await tx.delete(chats).where(eq(chats.userId, userId))+ return { success: true }+ })+ } catch (error) {+ console.error('Error deleting user chats:', error)+ return { success: false, error: 'Failed to delete user chats' }+ }+}++/**+ * Remove account linkage from feedback while retaining the feedback content.+ */+export async function anonymizeUserFeedback(+ userId: string+): Promise<{ success: boolean; error?: string }> {+ try {+ return withRLS(userId, async tx => {+ await tx+ .update(feedback)+ .set({ userId: null })+ .where(eq(feedback.userId, userId))++ return { success: true }+ })+ } catch (error) {+ console.error('Error anonymizing user feedback:', error)+ return { success: false, error: 'Failed to anonymize user feedback' }+ }+}+/*** Update chat visibility*/diff --git a/lib/db/schema.ts b/lib/db/schema.tsindex 0d4c4e21..804064e3 100644--- a/lib/db/schema.ts+++ b/lib/db/schema.ts@@ -293,6 +293,15 @@ export const feedback = pgTable(for: 'insert',to: 'public',withCheck: sql`true`+ }),++ // Allow users to remove the account link from their own feedback.+ pgPolicy('users_anonymize_own_feedback', {+ as: 'permissive',+ for: 'update',+ to: 'public',+ using: sql`user_id = current_setting('app.current_user_id', true)`,+ withCheck: sql`user_id IS NULL`})]).enableRLS()diff --git a/lib/storage/r2-client.ts b/lib/storage/r2-client.tsindex fa76d91f..cbbaefc6 100644--- a/lib/storage/r2-client.ts+++ b/lib/storage/r2-client.ts@@ -1,4 +1,8 @@-import { S3Client } from '@aws-sdk/client-s3'+import {+ DeleteObjectsCommand,+ ListObjectsV2Command,+ S3Client+} from '@aws-sdk/client-s3'export const R2_BUCKET_NAME = process.env.R2_BUCKET_NAME || 'user-uploads'export const R2_PUBLIC_URL = process.env.R2_PUBLIC_URL || ''@@ -39,3 +43,62 @@ export function getR2Client(): S3Client {return _r2Client}++export function isObjectStorageConfigured() {+ const hasCredentials =+ !!process.env.R2_ACCESS_KEY_ID && !!process.env.R2_SECRET_ACCESS_KEY+ const hasEndpointOrAccount =+ !!process.env.S3_ENDPOINT || !!process.env.R2_ACCOUNT_ID+ const hasPublicUrl = !!R2_PUBLIC_URL++ return hasCredentials && hasEndpointOrAccount && hasPublicUrl+}++export async function deleteObjectsByPrefix(prefix: string) {+ if (!isObjectStorageConfigured()) {+ return { deletedCount: 0, skipped: true }+ }++ const r2Client = getR2Client()+ let continuationToken: string | undefined+ let deletedCount = 0++ do {+ const listedObjects = await r2Client.send(+ new ListObjectsV2Command({+ Bucket: R2_BUCKET_NAME,+ Prefix: prefix,+ ContinuationToken: continuationToken,+ MaxKeys: 1000+ })+ )++ const keys =+ listedObjects.Contents?.map(object => object.Key).filter(+ (key): key is string => Boolean(key)+ ) ?? []++ if (keys.length > 0) {+ await r2Client.send(+ new DeleteObjectsCommand({+ Bucket: R2_BUCKET_NAME,+ Delete: {+ Objects: keys.map(Key => ({ Key })),+ Quiet: true+ }+ })+ )+ deletedCount += keys.length+ }++ continuationToken = listedObjects.IsTruncated+ ? listedObjects.NextContinuationToken+ : undefined+ } while (continuationToken)++ return { deletedCount, skipped: false }+}++export async function deleteUserObjects(userId: string) {+ return deleteObjectsByPrefix(`${userId}/`)+}diff --git a/lib/supabase/admin.ts b/lib/supabase/admin.tsnew file mode 100644index 00000000..b9c6aec5--- /dev/null+++ b/lib/supabase/admin.ts@@ -0,0 +1,19 @@+import { createClient } from '@supabase/supabase-js'++export function createAdminClient() {+ const url = process.env.NEXT_PUBLIC_SUPABASE_URL+ const secretKey = process.env.SUPABASE_SECRET_KEY++ if (!url || !secretKey) {+ throw new Error(+ 'Supabase admin client is not configured. Set SUPABASE_SECRET_KEY.'+ )+ }++ return createClient(url, secretKey, {+ auth: {+ autoRefreshToken: false,+ persistSession: false+ }+ })+}diff --git a/lib/supabase/client.ts b/lib/supabase/client.tsindex d3b8a105..eb0e23c6 100644--- a/lib/supabase/client.ts+++ b/lib/supabase/client.ts@@ -1,13 +1,15 @@import { createBrowserClient } from '@supabase/ssr'+import { getSupabasePublishableKey } from './keys'+export function createClient() {const url = process.env.NEXT_PUBLIC_SUPABASE_URL- const key = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY+ const key = getSupabasePublishableKey()if (!url || !key) {console.warn('Supabase client configuration missing. Authentication features will be unavailable. ' +- 'To enable authentication, set NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY at build time.'+ 'To enable authentication, set NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY at build time.')throw new Error('Supabase not configured')}diff --git a/lib/supabase/keys.ts b/lib/supabase/keys.tsnew file mode 100644index 00000000..cd145ef2--- /dev/null+++ b/lib/supabase/keys.ts@@ -0,0 +1,9 @@+export function getSupabasePublishableKey() {+ return process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY+}++export function hasSupabasePublicConfig() {+ return Boolean(+ process.env.NEXT_PUBLIC_SUPABASE_URL && getSupabasePublishableKey()+ )+}diff --git a/lib/supabase/middleware.ts b/lib/supabase/middleware.tsindex cb3a30b7..30afeb71 100644--- a/lib/supabase/middleware.ts+++ b/lib/supabase/middleware.ts@@ -2,14 +2,17 @@ import { type NextRequest, NextResponse } from 'next/server'import { createServerClient } from '@supabase/ssr'+import { getSupabasePublishableKey } from './keys'+export async function updateSession(request: NextRequest) {let supabaseResponse = NextResponse.next({request})+ const supabaseKey = getSupabasePublishableKey()const supabase = createServerClient(process.env.NEXT_PUBLIC_SUPABASE_URL!,- process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,+ supabaseKey!,{cookies: {getAll() {diff --git a/lib/supabase/server.ts b/lib/supabase/server.tsindex 71948b9b..a9f90f12 100644--- a/lib/supabase/server.ts+++ b/lib/supabase/server.ts@@ -2,12 +2,15 @@ import { cookies } from 'next/headers'import { createServerClient } from '@supabase/ssr'+import { getSupabasePublishableKey } from './keys'+export async function createClient() {const cookieStore = await cookies()+ const supabaseKey = getSupabasePublishableKey()return createServerClient(process.env.NEXT_PUBLIC_SUPABASE_URL!,- process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,+ supabaseKey!,{cookies: {getAll() {