"use server"; import { createClient } from "@/utils/supabase/server"; import type { Message } from "@/types/chat"; import { getDecryptedRoomKey, encryptMessageValue, decryptMessageValue, } from "@/utils/security/room_crypto"; import { getSignedAvatarUrls } from "@/utils/assets/avatars"; const PAGE_SIZE = 50; interface MessageRow { id: string; value: string; created_at: string; user_id: string; room_id: string; iv: string; auth_tag: string; users: { name: string } | null; } export async function getMessages( roomId: string, page: number = 0, ): Promise<{ messages: Message[]; hasMore: boolean }> { const supabase = await createClient(); const { data: { user }, } = await supabase.auth.getUser(); if (!user) return { messages: [], hasMore: false }; const from = page * PAGE_SIZE; const to = from + PAGE_SIZE; const { data, error } = await supabase .from("messages") .select( "id, value, created_at, user_id, room_id, iv, auth_tag, users(name)", ) .eq("room_id", roomId) .order("created_at", { ascending: false }) .range(from, to); if (error) { throw error; } const rows = (data ?? []) as unknown as MessageRow[]; const hasMore = rows.length > PAGE_SIZE; const trimmed = hasMore ? rows.slice(0, PAGE_SIZE) : rows; // Try to get the room key for decryption const roomKey = await getDecryptedRoomKey(roomId); // Collect unique user IDs for batch signed URL generation const userIds = [...new Set(trimmed.map((r) => r.user_id))]; const avatarMap = await getSignedAvatarUrls(userIds); const messages: Message[] = await Promise.all( trimmed.map(async (row) => { let plaintext = row.value; // Decrypt if the room has encryption and the message has crypto fields if (roomKey && row.iv && row.auth_tag) { try { plaintext = await decryptMessageValue( row.value, row.iv, row.auth_tag, roomKey, ); } catch { plaintext = "[Encrypted message]"; } } return { id: row.id, value: plaintext, created_at: row.created_at, user_id: row.user_id, room_id: row.room_id, user: row.users ? { name: row.users.name, avatar_url: avatarMap.get(row.user_id) ?? null, } : null, }; }), ); return { messages, hasMore }; } export async function sendMessage(roomId: string, value: string) { const supabase = await createClient(); const { data: { user }, } = await supabase.auth.getUser(); if (!user) return { error: "Not authenticated" }; if (!value.trim()) { return { error: "Message cannot be empty." }; } // Try to encrypt the message const roomKey = await getDecryptedRoomKey(roomId); if (roomKey) { const encrypted = await encryptMessageValue(value.trim(), roomKey); const { data, error } = await supabase .from("messages") .insert({ room_id: roomId, user_id: user.id, value: encrypted.ciphertext, iv: encrypted.iv, auth_tag: encrypted.authTag, }) .select("id") .single(); if (error) { return { error: error.message }; } return { success: true, messageId: data.id }; } // No room key — send unencrypted (backward compat for pre-encryption rooms) const { data, error } = await supabase .from("messages") .insert({ room_id: roomId, user_id: user.id, value: value.trim(), }) .select("id") .single(); if (error) { return { error: error.message }; } return { success: true, messageId: data.id }; } /** * Decrypt an incoming realtime message for the current user. * Called from the client when a postgres_changes event arrives. */ export async function decryptIncomingMessage( roomId: string, encryptedValue: string, iv: string, authTag: string, ): Promise<{ plaintext: string } | { error: string }> { if (!iv || !authTag) { // Unencrypted message (pre-encryption) return { plaintext: encryptedValue }; } const roomKey = await getDecryptedRoomKey(roomId); if (!roomKey) return { error: "Could not decrypt room key" }; try { const plaintext = await decryptMessageValue( encryptedValue, iv, authTag, roomKey, ); return { plaintext }; } catch { return { error: "Decryption failed" }; } }