diff --git a/app/(auth)/error.tsx b/app/(auth)/error.tsx new file mode 100644 index 0000000..b1ced88 --- /dev/null +++ b/app/(auth)/error.tsx @@ -0,0 +1,44 @@ +"use client"; + +export default function AuthError({ + error, + reset, +}: { + error: Error & { digest?: string }; + reset: () => void; +}) { + return ( +
+
+
+ + + +
+
+

+ Something went wrong +

+

+ {error.message || "An unexpected error occurred."} +

+
+ +
+
+ ); +} diff --git a/app/(auth)/friends/actions.ts b/app/(auth)/friends/actions.ts new file mode 100644 index 0000000..bcaf7c2 --- /dev/null +++ b/app/(auth)/friends/actions.ts @@ -0,0 +1,42 @@ +"use server"; + +import { revalidatePath } from "next/cache"; +import { sendFriendRequest, acceptFriend } from "@/utils/friends/friends"; +import { UUID_REGEX } from "@/utils/validation"; + +export type AddFriendState = { + success?: boolean; + error?: string; +} | null; + +export async function addFriendAction( + _prevState: AddFriendState, + formData: FormData, +): Promise { + const userId = formData.get("userId"); + if (typeof userId !== "string" || !userId.trim()) { + return { error: "User ID is required." }; + } + + const trimmed = userId.trim(); + + if (!UUID_REGEX.test(trimmed)) { + return { error: "Please enter a valid user ID (UUID format)." }; + } + + try { + const result = await sendFriendRequest(trimmed); + if (result === false) { + return { error: "Could not send friend request. It may already exist." }; + } + revalidatePath("/friends"); + return { success: true }; + } catch { + return { error: "Something went wrong. Please try again." }; + } +} + +export async function acceptRequestAction(senderId: string) { + await acceptFriend(senderId); + revalidatePath("/friends"); +} diff --git a/app/(auth)/friends/add-friend-form.tsx b/app/(auth)/friends/add-friend-form.tsx new file mode 100644 index 0000000..c2809a0 --- /dev/null +++ b/app/(auth)/friends/add-friend-form.tsx @@ -0,0 +1,41 @@ +"use client"; + +import { useActionState } from "react"; +import { addFriendAction, type AddFriendState } from "./actions"; + +const initialState: AddFriendState = null; + +export function AddFriendForm() { + const [state, action, pending] = useActionState(addFriendAction, initialState); + + return ( +
+ +
+ + +
+ {state?.error && ( +

{state.error}

+ )} + {state?.success && ( +

Friend request sent!

+ )} +
+ ); +} diff --git a/app/(auth)/friends/add/page.tsx b/app/(auth)/friends/add/page.tsx new file mode 100644 index 0000000..cdbeef4 --- /dev/null +++ b/app/(auth)/friends/add/page.tsx @@ -0,0 +1,192 @@ +import { createClient } from "@/utils/supabase/server"; +import { redirect } from "next/navigation"; +import { sendFriendRequest } from "@/utils/friends/friends"; +import { UUID_REGEX } from "@/utils/validation"; +import Link from "next/link"; + +type ResultStatus = "success" | "already_friends" | "error"; + +export default async function AddFriendPage({ + searchParams, +}: { + searchParams: Promise<{ id?: string }>; +}) { + const { id } = await searchParams; + + // Validate the ID parameter + if (!id || !UUID_REGEX.test(id)) { + return ( +
+ +
+ ); + } + + const supabase = await createClient(); + const { + data: { user }, + } = await supabase.auth.getUser(); + + // Must be authenticated — redirect to login with return URL + if (!user) { + redirect(`/login?next=%2Ffriends%2Fadd%3Fid%3D${id}`); + } + + // Can't add yourself + if (user.id === id) { + return ( +
+ +
+ ); + } + + // Look up the target user + const { data: targetUser } = await supabase + .from("users") + .select("id, name") + .eq("id", id) + .single(); + + if (!targetUser) { + return ( +
+ +
+ ); + } + + // Check if already friends + const { data: existing } = await supabase + .from("friends") + .select("user_id") + .eq("user_id", user.id) + .eq("friend_id", id) + .maybeSingle(); + + if (existing) { + return ( +
+ +
+ ); + } + + // Send the friend request + let status: ResultStatus; + let message: string; + + try { + const sent = await sendFriendRequest(id); + if (sent === false) { + status = "error"; + message = + "Could not send friend request. It may already exist."; + } else { + status = "success"; + message = `Friend request sent to ${targetUser.name}!`; + } + } catch { + status = "error"; + message = "Something went wrong. Please try again."; + } + + return ( +
+ +
+ ); +} + +function ResultCard({ + status, + message, +}: { + status: ResultStatus; + message: string; +}) { + const isSuccess = status === "success"; + const isAlreadyFriends = status === "already_friends"; + + return ( +
+
+
+ {isSuccess ? ( + + + + ) : isAlreadyFriends ? ( + + + + ) : ( + + + + )} +
+ +

+ {isSuccess + ? "Request Sent!" + : isAlreadyFriends + ? "Already Friends" + : "Something went wrong"} +

+

{message}

+ +
+ + Back to Friends + + + Go to Rooms + +
+
+
+ ); +} diff --git a/app/(auth)/friends/friends-list.tsx b/app/(auth)/friends/friends-list.tsx new file mode 100644 index 0000000..3cc2632 --- /dev/null +++ b/app/(auth)/friends/friends-list.tsx @@ -0,0 +1,67 @@ +import Image from "next/image"; + +export interface FriendEntry { + friend_id: string; + friend_alias: string; + avatar_url: string | null; +} + +export function FriendsList({ friends }: { friends: FriendEntry[] }) { + if (friends.length === 0) { + return ( +
+ + + +

No friends yet

+
+ ); + } + + return ( +
+

+ Friends + + {friends.length} + +

+ +
+ ); +} diff --git a/app/(auth)/friends/page.tsx b/app/(auth)/friends/page.tsx new file mode 100644 index 0000000..5272436 --- /dev/null +++ b/app/(auth)/friends/page.tsx @@ -0,0 +1,55 @@ +import { createClient } from "@/utils/supabase/server"; +import { listFriends, listRequests } from "@/utils/friends/friends"; +import { AddFriendForm } from "./add-friend-form"; +import { RequestsList, type FriendRequest } from "./requests-list"; +import { FriendsList, type FriendEntry } from "./friends-list"; + +export default async function FriendsPage() { + const supabase = await createClient(); + + // Fetch incoming friend requests with sender names + const rawRequests = await listRequests(); + let requests: FriendRequest[] = []; + + if (rawRequests && rawRequests.length > 0) { + const senderIds = rawRequests.map((r) => r.sender_id); + const { data: senders } = await supabase + .from("users") + .select("id, name") + .in("id", senderIds); + + const senderMap = new Map(senders?.map((s) => [s.id, s.name])); + + requests = rawRequests.map((r) => ({ + id: r.id, + sender_id: r.sender_id, + sender_name: senderMap.get(r.sender_id) ?? "Unknown", + })); + } + + // Fetch friends list + const rawFriends = await listFriends(); + const friends: FriendEntry[] = rawFriends ?? []; + + return ( +
+

Friends

+

+ Manage your friends and requests. +

+ +
+ {/* Add friend */} +
+ +
+ + {/* Incoming requests */} + + + {/* Friends list */} + +
+
+ ); +} diff --git a/app/(auth)/friends/requests-list.tsx b/app/(auth)/friends/requests-list.tsx new file mode 100644 index 0000000..01bcd7c --- /dev/null +++ b/app/(auth)/friends/requests-list.tsx @@ -0,0 +1,54 @@ +"use client"; + +import { useTransition } from "react"; +import { acceptRequestAction } from "./actions"; + +export interface FriendRequest { + id: string; + sender_id: string; + sender_name: string; +} + +export function RequestsList({ requests }: { requests: FriendRequest[] }) { + if (requests.length === 0) return null; + + return ( +
+

+ Incoming Requests + + {requests.length} + +

+ +
+ ); +} + +function RequestItem({ req }: { req: FriendRequest }) { + const [pending, startTransition] = useTransition(); + + return ( +
  • +
    +
    + {req.sender_name.charAt(0).toUpperCase()} +
    + + {req.sender_name} + +
    + +
  • + ); +} diff --git a/app/(auth)/layout.tsx b/app/(auth)/layout.tsx new file mode 100644 index 0000000..d68d66c --- /dev/null +++ b/app/(auth)/layout.tsx @@ -0,0 +1,43 @@ +import { createClient } from "@/utils/supabase/server"; +import { Sidebar } from "./sidebar"; +import { getSignedAvatarUrl } from "@/utils/assets/avatars"; + +export default async function AuthLayout({ + children, +}: { + children: React.ReactNode; +}) { + const supabase = await createClient(); + const { + data: { user }, + } = await supabase.auth.getUser(); + + let displayName = "User"; + let avatarURL = ""; + + if (user) { + const { data } = await supabase + .from("users") + .select("name, id, avatar_url") + .eq("id", user.id) + .single(); + if (data?.name) displayName = data.name; + if (data?.id) { + const fetchedAvatarUrl = await getSignedAvatarUrl(data.id); + if (fetchedAvatarUrl) { + avatarURL = fetchedAvatarUrl; + } + } + } + + return ( +
    + +
    {children}
    +
    + ); +} diff --git a/app/(auth)/loading.tsx b/app/(auth)/loading.tsx new file mode 100644 index 0000000..d6b31b7 --- /dev/null +++ b/app/(auth)/loading.tsx @@ -0,0 +1,10 @@ +export default function AuthLoading() { + return ( +
    +
    +
    +

    Loading...

    +
    +
    + ); +} diff --git a/app/(auth)/profile/actions.ts b/app/(auth)/profile/actions.ts new file mode 100644 index 0000000..faf4c41 --- /dev/null +++ b/app/(auth)/profile/actions.ts @@ -0,0 +1,107 @@ +"use server"; + +import { revalidatePath } from "next/cache"; +import { createClient } from "@/utils/supabase/server"; + +export type UpdateNameState = { error: string } | { success: true } | null; + +export async function updateNameAction( + _prevState: UpdateNameState, + formData: FormData, +): Promise { + const name = formData.get("name"); + if (typeof name !== "string" || !name.trim()) { + return { error: "Name cannot be empty." }; + } + + const trimmed = name.trim(); + if (trimmed.length > 50) { + return { error: "Name must be 50 characters or less." }; + } + + const supabase = await createClient(); + const { + data: { user }, + } = await supabase.auth.getUser(); + if (!user) return { error: "Not authenticated" }; + + const { error } = await supabase + .from("users") + .update({ name: trimmed }) + .eq("id", user.id); + + if (error) { + return { error: error.message }; + } + + // Update friend_alias in all friends rows where this user is the friend + // so that other users see the new display name + await supabase + .from("friends") + .update({ friend_alias: trimmed }) + .eq("friend_id", user.id); + + revalidatePath("/profile"); + revalidatePath("/friends"); + return { success: true }; +} + +export type UploadAvatarState = { error: string } | { success: true } | null; + +export async function uploadAvatarAction( + _prevState: UploadAvatarState, + formData: FormData, +): Promise { + const file = formData.get("avatar"); + if (!(file instanceof File) || file.size === 0) { + return { error: "Please select an image file." }; + } + + // Validate file type + if (file.type !== "image/png" && file.type !== "image/jpeg") { + return { error: "Only PNG and JPG images are allowed." }; + } + + // Validate file size (2MB) + if (file.size > 2 * 1024 * 1024) { + return { error: "Image must be smaller than 2MB." }; + } + + const supabase = await createClient(); + const { + data: { user }, + } = await supabase.auth.getUser(); + if (!user) return { error: "Not authenticated" }; + + const arrayBuffer = await file.arrayBuffer(); + const filePath = `${user.id}/avatar`; + + const { error: uploadError } = await supabase.storage + .from("avatars") + .upload(filePath, arrayBuffer, { + contentType: file.type, + upsert: true, + }); + + if (uploadError) { + return { error: uploadError.message }; + } + + // Store the storage path — signed URLs are generated on read + const avatarPath = filePath; + + // Update user's avatar_url with the storage path + const { error: updateError } = await supabase + .from("users") + .update({ avatar_url: avatarPath }) + .eq("id", user.id); + + if (updateError) { + return { error: updateError.message }; + } + + revalidatePath("/profile"); + revalidatePath("/friends"); + revalidatePath("/rooms"); + return { success: true }; +} diff --git a/app/(auth)/profile/avatar-upload.tsx b/app/(auth)/profile/avatar-upload.tsx new file mode 100644 index 0000000..27f7e70 --- /dev/null +++ b/app/(auth)/profile/avatar-upload.tsx @@ -0,0 +1,81 @@ +"use client"; + +import { useActionState, useRef } from "react"; +import { uploadAvatarAction, type UploadAvatarState } from "./actions"; +import Image from "next/image"; + +const initialState: UploadAvatarState = null; + +export function AvatarUpload({ avatarUrl }: { avatarUrl: string | null }) { + const [state, action, pending] = useActionState( + uploadAvatarAction, + initialState, + ); + const inputRef = useRef(null); + + const handleClick = () => { + inputRef.current?.click(); + }; + + const handleChange = () => { + const file = inputRef.current?.files?.[0]; + if (!file) return; + + const formData = new FormData(); + formData.append("avatar", file); + + // Submit via the form's requestSubmit to trigger the action + const form = inputRef.current?.closest("form"); + if (form) { + form.requestSubmit(); + } + }; + + return ( +
    + + + {state && "error" in state && ( +

    {state.error}

    + )} +
    + ); +} diff --git a/app/(auth)/profile/editable-name.tsx b/app/(auth)/profile/editable-name.tsx new file mode 100644 index 0000000..5022784 --- /dev/null +++ b/app/(auth)/profile/editable-name.tsx @@ -0,0 +1,81 @@ +"use client"; + +import { + useActionState, + useRef, + useEffect, + useState, + useCallback, +} from "react"; +import { updateNameAction, type UpdateNameState } from "./actions"; + +const initialState: UpdateNameState = null; + +export function EditableName({ currentName }: { currentName: string }) { + const [editing, setEditing] = useState(false); + const [state, action, pending] = useActionState( + updateNameAction, + initialState, + ); + const inputRef = useRef(null); + + // Focus input when entering edit mode + useEffect(() => { + if (editing) { + inputRef.current?.focus(); + inputRef.current?.select(); + } + }, [editing]); + + const handleEdit = useCallback(() => setEditing(true), []); + + if (!editing) { + return ( +
    +

    + {currentName} +

    + +
    + ); + } + + return ( +
    +
    + + + +
    + {state && "error" in state && ( +

    {state.error}

    + )} +
    + ); +} diff --git a/app/(auth)/profile/page.tsx b/app/(auth)/profile/page.tsx new file mode 100644 index 0000000..b0f4972 --- /dev/null +++ b/app/(auth)/profile/page.tsx @@ -0,0 +1,148 @@ +import { createClient } from "@/utils/supabase/server"; +import { redirect } from "next/navigation"; +import { headers } from "next/headers"; +import type { Profile } from "@/types/profile"; +import { getSignedAvatarUrl } from "@/utils/assets/avatars"; +import { EditableName } from "./editable-name"; +import { ShareProfileButton } from "./share-profile"; +import { AvatarUpload } from "./avatar-upload"; + +export default async function ProfilePage() { + const supabase = await createClient(); + const { + data: { user }, + } = await supabase.auth.getUser(); + + if (!user) return redirect("/login"); + + const { data: profile } = await supabase + .from("users") + .select("*") + .eq("id", user.id) + .single(); + + if (!profile) { + return ( +
    +

    Profile not found.

    +
    + ); + } + + // Generate a signed URL for the user's own avatar + const avatarUrl = profile.avatar_url + ? await getSignedAvatarUrl(profile.id) + : null; + + const memberSince = new Date(profile.created_at).toLocaleDateString("en-US", { + year: "numeric", + month: "long", + day: "numeric", + }); + + // Build the full share URL for the QR code + const requestHeaders = await headers(); + const host = requestHeaders.get("host") ?? "localhost:3000"; + const protocol = requestHeaders.get("x-forwarded-proto") ?? "https"; + const basePath = process.env.BASE_PATH ?? ""; + const shareUrl = `${protocol}://${host}${basePath}/friends/add?id=${profile.id}`; + + return ( +
    + {/* Header */} +

    Profile

    +

    + Manage your account information. +

    + + {/* Profile Card */} +
    + {/* Banner area */} +
    + + {/* Avatar + name */} +
    + + + +
    +

    {profile.email}

    + +
    +
    +
    + + {/* Details */} +
    +
    +
    +

    + Account Details +

    +
    +
    + + + + + + +
    +
    +
    +
    + ); +} + +function DetailRow({ + label, + value, + mono, + badge, +}: { + label: string; + value: string; + mono?: boolean; + badge?: "green" | "yellow"; +}) { + return ( +
    +
    {label}
    +
    + {badge ? ( + + {value} + + ) : ( + + {value} + + )} +
    +
    + ); +} diff --git a/app/(auth)/profile/share-profile.tsx b/app/(auth)/profile/share-profile.tsx new file mode 100644 index 0000000..5dd24e3 --- /dev/null +++ b/app/(auth)/profile/share-profile.tsx @@ -0,0 +1,99 @@ +"use client"; + +import { useState, useCallback } from "react"; +import { QRCodeSVG } from "qrcode.react"; + +export function ShareProfileButton({ userId, shareUrl }: { userId: string; shareUrl: string }) { + const [open, setOpen] = useState(false); + const [copied, setCopied] = useState(false); + + const handleCopy = useCallback(() => { + navigator.clipboard.writeText(shareUrl).then(() => { + setCopied(true); + setTimeout(() => setCopied(false), 2000); + }); + }, [shareUrl]); + + return ( + <> + + + {open && ( + <> + {/* Backdrop */} +
    setOpen(false)} + /> + + {/* Modal */} +
    +
    +
    +

    + Share Profile +

    + +
    + +

    + Scan this QR code or share the link to add you as a friend. +

    + + {/* QR Code */} +
    + +
    + + {/* Link + Copy */} +
    + + +
    + + {/* User ID reference */} +

    + User ID: {userId} +

    +
    +
    + + )} + + ); +} diff --git a/app/(auth)/rooms/[id]/actions.ts b/app/(auth)/rooms/[id]/actions.ts new file mode 100644 index 0000000..7292f40 --- /dev/null +++ b/app/(auth)/rooms/[id]/actions.ts @@ -0,0 +1,34 @@ +"use server"; + +import { revalidatePath } from "next/cache"; +import { sendMessage, decryptIncomingMessage } from "@/utils/rooms/messages"; + +export type SendMessageState = { error: string } | { messageId: string } | null; + +export async function sendMessageAction( + roomId: string, + _prevState: SendMessageState, + formData: FormData, +): Promise { + const value = formData.get("message"); + if (typeof value !== "string" || !value.trim()) { + return { error: "Message cannot be empty." }; + } + + const result = await sendMessage(roomId, value.trim()); + if (result.error) { + return { error: result.error }; + } + + revalidatePath(`/rooms/${roomId}`); + return { messageId: result.messageId }; +} + +export async function decryptMessageAction( + roomId: string, + encryptedValue: string, + iv: string, + authTag: string, +): Promise<{ plaintext: string } | { error: string }> { + return decryptIncomingMessage(roomId, encryptedValue, iv, authTag); +} diff --git a/app/(auth)/rooms/[id]/chat.tsx b/app/(auth)/rooms/[id]/chat.tsx new file mode 100644 index 0000000..92b61d4 --- /dev/null +++ b/app/(auth)/rooms/[id]/chat.tsx @@ -0,0 +1,326 @@ +"use client"; + +import { + useActionState, + useRef, + useEffect, + useState, + useCallback, + useMemo, +} from "react"; +import Image from "next/image"; +import { createClient } from "@/utils/supabase/client"; +import type { Message } from "@/types/chat"; +import { + sendMessageAction, + decryptMessageAction, + type SendMessageState, +} from "./actions"; +import type { MemberInfo } from "./member-map"; + +const initialState: SendMessageState = null; + +// Prefix for temporary optimistic IDs +const OPTIMISTIC_PREFIX = "optimistic-"; + +export function Chat({ + roomId, + initialMessages, + currentUserId, + memberMap, +}: { + roomId: string; + initialMessages: Message[]; + currentUserId: string; + memberMap: Map; +}) { + const boundAction = sendMessageAction.bind(null, roomId); + const [state, action, pending] = useActionState(boundAction, initialState); + const formRef = useRef(null); + const bottomRef = useRef(null); + const optimisticCounter = useRef(0); + + const [localMessages, setLocalMessages] = useState([]); + + // Merge server messages (prop) with local messages (optimistic + realtime) + // Server messages that match local optimistic ones by user+value are replaced + // by the local version (which may have a real ID from realtime confirmation) + const messages = useMemo(() => { + const serverIds = new Set(initialMessages.map((m) => m.id)); + const optimisticConfirmed = new Set(); + + for (const local of localMessages) { + if (!local.id.startsWith(OPTIMISTIC_PREFIX) && !serverIds.has(local.id)) { + const match = initialMessages.find( + (s) => s.user_id === local.user_id && s.value === local.value, + ); + if (match) optimisticConfirmed.add(match.id); + } + } + + const serverFiltered = initialMessages.filter( + (m) => !optimisticConfirmed.has(m.id), + ); + + const localFiltered = localMessages.filter((m) => { + if (serverIds.has(m.id)) return false; + if (m.id.startsWith(OPTIMISTIC_PREFIX)) { + const serverValues = new Set( + initialMessages + .filter((s) => s.user_id === m.user_id) + .map((s) => s.value), + ); + if (serverValues.has(m.value)) return false; + } + return true; + }); + + const merged = [...serverFiltered, ...localFiltered]; + merged.sort( + (a, b) => + new Date(b.created_at).getTime() - new Date(a.created_at).getTime(), + ); + return merged; + }, [initialMessages, localMessages]); + + const scrollToBottom = useCallback(() => { + bottomRef.current?.scrollIntoView({ behavior: "smooth" }); + }, []); + + const messageCount = messages.length; + + useEffect(() => { + scrollToBottom(); + }, [messageCount, scrollToBottom]); + + // Clear input after successful send + useEffect(() => { + if (state !== null && !("error" in state) && !pending) { + formRef.current?.reset(); + } + }, [state, pending]); + + const handleAction = useCallback( + (formData: FormData) => { + const value = formData.get("message"); + if (typeof value === "string" && value.trim()) { + const tempId = `${OPTIMISTIC_PREFIX}${++optimisticCounter.current}`; + + const optimisticMsg: Message = { + id: tempId, + value: value.trim(), + created_at: new Date().toISOString(), + user_id: currentUserId, + room_id: roomId, + user: { + name: memberMap.get(currentUserId)?.name ?? "You", + avatar_url: memberMap.get(currentUserId)?.avatar_url ?? null, + }, + }; + + setLocalMessages((prev) => [optimisticMsg, ...prev]); + } + action(formData); + }, + [action, currentUserId, roomId, memberMap], + ); + + useEffect(() => { + const supabase = createClient(); + + const channel = supabase + .channel(`room-messages:${roomId}`) + .on( + "postgres_changes", + { + event: "INSERT", + schema: "public", + table: "messages", + filter: `room_id=eq.${roomId}`, + }, + (payload: { new: Record }) => { + const realId = payload.new.id; + const realUserId = payload.new.user_id; + + if (realUserId === currentUserId) { + // Own message confirmed by server — swap optimistic ID → real ID + setLocalMessages((prev) => { + if (prev.some((m) => m.id === realId)) return prev; + + const optimisticIdx = prev.findIndex( + (m) => + m.id.startsWith(OPTIMISTIC_PREFIX) && + m.user_id === currentUserId, + ); + + if (optimisticIdx !== -1) { + const updated = [...prev]; + updated[optimisticIdx] = { + ...updated[optimisticIdx], + id: realId, + created_at: payload.new.created_at, + }; + return updated; + } + + return prev; + }); + } else { + // Other user's message — decrypt via server action + void decryptMessageAction( + roomId, + payload.new.value, + payload.new.iv ?? "", + payload.new.auth_tag ?? "", + ).then((result) => { + if ("plaintext" in result) { + const msg: Message = { + id: realId, + value: result.plaintext, + created_at: payload.new.created_at, + user_id: realUserId, + room_id: payload.new.room_id, + user: { + name: memberMap.get(realUserId)?.name ?? "Unknown", + avatar_url: memberMap.get(realUserId)?.avatar_url ?? null, + }, + }; + setLocalMessages((prev) => { + if (prev.some((m) => m.id === realId)) return prev; + return [msg, ...prev]; + }); + } + }); + } + }, + ) + .subscribe(); + + return () => { + void supabase.removeChannel(channel); + }; + }, [roomId, memberMap, currentUserId]); + + const displayMessages = [...messages].reverse(); + + return ( +
    + {/* Messages area */} +
    + {displayMessages.length === 0 ? ( +
    +

    + No messages yet. Start the conversation! +

    +
    + ) : ( +
    + {displayMessages.map((msg) => { + const isOwn = msg.user_id === currentUserId; + const isPending = msg.id.startsWith(OPTIMISTIC_PREFIX); + return ( +
    +
    + {!isOwn && ( +
    + + + {msg.user?.name ?? "Unknown"} + +
    + )} +

    + {msg.value} +

    +

    + {isPending ? "Sending..." : formatTime(msg.created_at)} +

    +
    +
    + ); + })} +
    +
    + )} +
    + + {/* Send bar */} +
    +
    + + +
    + {state && "error" in state && ( +

    {state.error}

    + )} +
    +
    + ); +} + +function formatTime(isoString: string): string { + const date = new Date(isoString); + return date.toLocaleTimeString("en-US", { + hour: "2-digit", + minute: "2-digit", + }); +} + +function Avatar({ + name, + avatarUrl, + size = "md", +}: { + name: string; + avatarUrl: string | null; + size?: "sm" | "md"; +}) { + const sizeClass = size === "sm" ? "size-5" : "size-8"; + const textSize = size === "sm" ? "text-[10px]" : "text-xs"; + + if (avatarUrl) { + return ( + + ); + } + + return ( +
    + {name.charAt(0).toUpperCase()} +
    + ); +} diff --git a/app/(auth)/rooms/[id]/loading.tsx b/app/(auth)/rooms/[id]/loading.tsx new file mode 100644 index 0000000..051e481 --- /dev/null +++ b/app/(auth)/rooms/[id]/loading.tsx @@ -0,0 +1,21 @@ +export default function RoomDetailLoading() { + return ( +
    + {/* Header skeleton */} +
    +
    +
    +
    +
    +
    +
    + {/* Chat area skeleton */} +
    +
    +
    +

    Loading room...

    +
    +
    +
    + ); +} diff --git a/app/(auth)/rooms/[id]/member-map.ts b/app/(auth)/rooms/[id]/member-map.ts new file mode 100644 index 0000000..5144a3b --- /dev/null +++ b/app/(auth)/rooms/[id]/member-map.ts @@ -0,0 +1,16 @@ +import type { MemberEntry } from "./members-list"; + +export interface MemberInfo { + name: string; + avatar_url: string | null; +} + +export function buildMemberMap( + members: MemberEntry[], +): Map { + const map = new Map(); + for (const m of members) { + map.set(m.user_id, { name: m.name, avatar_url: m.avatar_url }); + } + return map; +} diff --git a/app/(auth)/rooms/[id]/members-list.tsx b/app/(auth)/rooms/[id]/members-list.tsx new file mode 100644 index 0000000..6e15195 --- /dev/null +++ b/app/(auth)/rooms/[id]/members-list.tsx @@ -0,0 +1,84 @@ +import Image from "next/image"; + +export interface MemberEntry { + user_id: string; + name: string; + avatar_url: string | null; +} + +export function MembersList({ + members, + currentUserId, + onRemoveMember, + disableActions, +}: { + members: MemberEntry[]; + currentUserId?: string; + onRemoveMember?: (userId: string) => void; + disableActions?: boolean; +}) { + if (members.length === 0) return null; + + return ( +
    +

    + Members + + {members.length} + +

    +
      + {members.map((member) => { + const isSelf = member.user_id === currentUserId; + + return ( +
    • + {member.avatar_url ? ( + + ) : ( +
      + {member.name.charAt(0).toUpperCase()} +
      + )} + + {member.name} + {isSelf && ( + + (you) + + )} + + {!isSelf && onRemoveMember && ( + + )} +
    • + ); + })} +
    +
    + ); +} diff --git a/app/(auth)/rooms/[id]/page.tsx b/app/(auth)/rooms/[id]/page.tsx new file mode 100644 index 0000000..a2cada5 --- /dev/null +++ b/app/(auth)/rooms/[id]/page.tsx @@ -0,0 +1,90 @@ +import { createClient } from "@/utils/supabase/server"; +import { listMembers } from "@/utils/rooms/rooms"; +import { getMessages } from "@/utils/rooms/messages"; +import { notFound } from "next/navigation"; +import Link from "next/link"; +import { Chat } from "./chat"; +import { RoomSettings } from "./room-settings"; +import { buildMemberMap } from "./member-map"; + +export default async function RoomDetailPage({ + params, +}: { + params: Promise<{ id: string }>; +}) { + const { id } = await params; + const supabase = await createClient(); + + const { + data: { user }, + } = await supabase.auth.getUser(); + if (!user) return notFound(); + + const { data: membership } = await supabase + .from("rooms_users") + .select("room_id") + .eq("room_id", id) + .eq("user_id", user.id) + .single(); + + if (!membership) return notFound(); + + const { data: room } = await supabase + .from("rooms") + .select("id, name, created_at") + .eq("id", id) + .single(); + + if (!room) return notFound(); + + const [members, { messages }] = await Promise.all([ + listMembers(id), + getMessages(id), + ]); + + return ( +
    + {/* Header */} +
    +
    + + + + + +
    +

    + {room.name} +

    +

    + {members.length} {members.length === 1 ? "member" : "members"} +

    +
    +
    + +
    + + {/* Chat */} +
    + +
    +
    + ); +} diff --git a/app/(auth)/rooms/[id]/room-settings.tsx b/app/(auth)/rooms/[id]/room-settings.tsx new file mode 100644 index 0000000..b32bbf9 --- /dev/null +++ b/app/(auth)/rooms/[id]/room-settings.tsx @@ -0,0 +1,107 @@ +"use client"; + +import { useState, useTransition } from "react"; +import type { MemberEntry } from "./members-list"; +import { MembersList } from "./members-list"; +import { AddMemberForm } from "../add-member-form"; +import { deleteRoomAction, removeMemberAction } from "../actions"; + +export function RoomSettings({ + roomId, + members, + currentUserId, +}: { + roomId: string; + members: MemberEntry[]; + currentUserId: string; +}) { + const [open, setOpen] = useState(false); + const [deleting, setDeleting] = useState(false); + const [removeError, setRemoveError] = useState(null); + const [isPending, startTransition] = useTransition(); + + const handleDeleteRoom = () => { + if ( + !confirm( + "Are you sure you want to delete this room? This cannot be undone.", + ) + ) { + return; + } + setDeleting(true); + startTransition(() => { + deleteRoomAction(roomId); + }); + }; + + const handleRemoveMember = (userId: string) => { + setRemoveError(null); + startTransition(async () => { + const result = await removeMemberAction(roomId, userId); + if (result.error) { + setRemoveError(result.error); + } + }); + }; + + return ( +
    + + + {open && ( + <> + {/* Backdrop */} +
    setOpen(false)} /> + {/* Panel */} +
    +

    + Room Settings +

    + + {removeError && ( +

    {removeError}

    + )} + +
    + + +
    + + {/* Danger zone */} +
    + +
    +
    + + )} +
    + ); +} diff --git a/app/(auth)/rooms/actions.ts b/app/(auth)/rooms/actions.ts new file mode 100644 index 0000000..c060345 --- /dev/null +++ b/app/(auth)/rooms/actions.ts @@ -0,0 +1,82 @@ +"use server"; + +import { revalidatePath } from "next/cache"; +import { redirect } from "next/navigation"; +import { + createRoom, + addMember, + deleteRoom, + removeMember, +} from "@/utils/rooms/rooms"; +import { UUID_REGEX } from "@/utils/validation"; + +export type CreateRoomState = { + error?: string; +} | null; + +export async function createRoomAction( + _prevState: CreateRoomState, + formData: FormData, +): Promise { + const name = formData.get("name"); + if (typeof name !== "string" || !name.trim()) { + return { error: "Room name is required." }; + } + + const result = await createRoom(name.trim()); + if (result.error) { + return { error: result.error }; + } + + revalidatePath("/rooms"); + redirect(`/rooms/${result.roomId}`); +} + +export type AddMemberState = { + success?: boolean; + error?: string; +} | null; + +export async function addMemberAction( + roomId: string, + _prevState: AddMemberState, + formData: FormData, +): Promise { + const userId = formData.get("userId"); + if (typeof userId !== "string" || !userId.trim()) { + return { error: "User ID is required." }; + } + + const trimmed = userId.trim(); + if (!UUID_REGEX.test(trimmed)) { + return { error: "Please enter a valid user ID (UUID format)." }; + } + + const result = await addMember(roomId, trimmed); + if (result.error) { + return { error: result.error }; + } + + revalidatePath("/rooms"); + return { success: true }; +} + +export async function deleteRoomAction(roomId: string) { + const result = await deleteRoom(roomId); + if (result.error) { + return { error: result.error }; + } + + revalidatePath("/rooms"); + redirect("/rooms"); +} + +export async function removeMemberAction(roomId: string, userId: string) { + const result = await removeMember(roomId, userId); + if (result.error) { + return { error: result.error }; + } + + revalidatePath(`/rooms/${roomId}`); + return { success: true }; +} diff --git a/app/(auth)/rooms/add-member-form.tsx b/app/(auth)/rooms/add-member-form.tsx new file mode 100644 index 0000000..b9e8277 --- /dev/null +++ b/app/(auth)/rooms/add-member-form.tsx @@ -0,0 +1,43 @@ +"use client"; + +import { useActionState } from "react"; +import { addMemberAction, type AddMemberState } from "./actions"; + +const initialState: AddMemberState = null; + +export function AddMemberForm({ roomId }: { roomId: string }) { + const boundAction = addMemberAction.bind(null, roomId); + const [state, action, pending] = useActionState(boundAction, initialState); + + return ( +
    + +
    + + +
    + {state?.error &&

    {state.error}

    } + {state?.success && ( +

    Member added!

    + )} +
    + ); +} diff --git a/app/(auth)/rooms/create-room-form.tsx b/app/(auth)/rooms/create-room-form.tsx new file mode 100644 index 0000000..cdcfc84 --- /dev/null +++ b/app/(auth)/rooms/create-room-form.tsx @@ -0,0 +1,42 @@ +"use client"; + +import { useActionState } from "react"; +import { createRoomAction, type CreateRoomState } from "./actions"; + +const initialState: CreateRoomState = null; + +export function CreateRoomForm() { + const [state, action, pending] = useActionState( + createRoomAction, + initialState, + ); + + return ( +
    + +
    + + +
    + {state?.error &&

    {state.error}

    } +
    + ); +} diff --git a/app/(auth)/rooms/page.tsx b/app/(auth)/rooms/page.tsx new file mode 100644 index 0000000..ff160a3 --- /dev/null +++ b/app/(auth)/rooms/page.tsx @@ -0,0 +1,27 @@ +import { listRooms } from "@/utils/rooms/rooms"; +import { CreateRoomForm } from "./create-room-form"; +import { RoomsList, type RoomEntry } from "./rooms-list"; + +export default async function RoomsPage() { + const rawRooms = await listRooms(); + const rooms: RoomEntry[] = rawRooms ?? []; + + return ( +
    +

    Rooms

    +

    + Your conversations will appear here. +

    + +
    + {/* Create room */} +
    + +
    + + {/* Rooms list */} + +
    +
    + ); +} diff --git a/app/(auth)/rooms/rooms-list.tsx b/app/(auth)/rooms/rooms-list.tsx new file mode 100644 index 0000000..9cc2f5f --- /dev/null +++ b/app/(auth)/rooms/rooms-list.tsx @@ -0,0 +1,75 @@ +import Link from "next/link"; + +export interface RoomEntry { + id: string; + name: string; + created_at: string; + member_count: number; +} + +export function RoomsList({ rooms }: { rooms: RoomEntry[] }) { + if (rooms.length === 0) { + return ( +
    + + + +

    No rooms yet

    +
    + ); + } + + return ( +
    +

    + Your Rooms + + {rooms.length} + +

    +
      + {rooms.map((room) => ( +
    • + +
      +

      + {room.name} +

      +

      + {room.member_count}{" "} + {room.member_count === 1 ? "member" : "members"} +

      +
      + + + + +
    • + ))} +
    +
    + ); +} diff --git a/app/(auth)/sidebar.tsx b/app/(auth)/sidebar.tsx new file mode 100644 index 0000000..1f92b1a --- /dev/null +++ b/app/(auth)/sidebar.tsx @@ -0,0 +1,165 @@ +"use client"; + +import Link from "next/link"; +import { usePathname } from "next/navigation"; +import { signOut } from "@/utils/profile/profile"; +import Image from "next/image"; + +const navItems = [ + { + label: "Rooms", + href: "/rooms", + icon: ( + + + + ), + }, + { + label: "Friends", + href: "/friends", + icon: ( + + + + ), + }, + { + label: "Profile", + href: "/profile", + icon: ( + + + + ), + }, +]; + +export function Sidebar({ + displayName, + email, + avatarUrl, +}: { + displayName: string; + email: string; + avatarUrl: string; +}) { + const pathname = usePathname(); + return ( + + ); +} diff --git a/app/globals.css b/app/globals.css index a2dc41e..7267fcc 100644 --- a/app/globals.css +++ b/app/globals.css @@ -1,26 +1,19 @@ @import "tailwindcss"; :root { - --background: #ffffff; - --foreground: #171717; -} - -@theme inline { - --color-background: var(--background); - --color-foreground: var(--foreground); - --font-sans: var(--font-geist-sans); - --font-mono: var(--font-geist-mono); + --background: #ffffff; + --foreground: #171717; } @media (prefers-color-scheme: dark) { - :root { - --background: #0a0a0a; - --foreground: #ededed; - } + :root { + --background: #0a0a0a; + --foreground: #ededed; + } } body { - background: var(--background); - color: var(--foreground); - font-family: Arial, Helvetica, sans-serif; + background: var(--background); + color: var(--foreground); + font-family: Arial, Helvetica, sans-serif; } diff --git a/app/layout.tsx b/app/layout.tsx index 976eb90..d4294f4 100644 --- a/app/layout.tsx +++ b/app/layout.tsx @@ -13,8 +13,8 @@ const geistMono = Geist_Mono({ }); export const metadata: Metadata = { - title: "Create Next App", - description: "Generated by create next app", + title: "Fastchat", + description: "A real-time encrypted chat application", }; export default function RootLayout({ diff --git a/app/login/actions.ts b/app/login/actions.ts new file mode 100644 index 0000000..3b0489c --- /dev/null +++ b/app/login/actions.ts @@ -0,0 +1,35 @@ +"use server"; + +import { redirect } from "next/navigation"; +import { login } from "@/utils/authentication/signin"; + +export type LoginState = { + error?: string; +} | null; + +export async function loginAction( + _prevState: LoginState, + formData: FormData, +): Promise { + const email = formData.get("email"); + const password = formData.get("password"); + const next = formData.get("next"); + + if (typeof email !== "string" || typeof password !== "string") { + return { error: "Email and password are required." }; + } + + try { + const result = await login(email, password); + if (result?.error) { + return { error: result.error.message ?? "Login failed." }; + } + } catch (error) { + const message = error instanceof Error ? error.message : "Login failed."; + return { error: message }; + } + + const redirectTo = + typeof next === "string" && next.startsWith("/") ? next : "/profile"; + redirect(redirectTo); +} diff --git a/app/login/login-form.tsx b/app/login/login-form.tsx new file mode 100644 index 0000000..8832757 --- /dev/null +++ b/app/login/login-form.tsx @@ -0,0 +1,70 @@ +"use client"; + +import Link from "next/link"; +import { useActionState } from "react"; +import { loginAction, type LoginState } from "./actions"; + +const initialState: LoginState = null; + +export default function LoginForm({ next }: { next?: string }) { + const [state, action, pending] = useActionState(loginAction, initialState); + + return ( +
    +
    +

    Log in

    +

    + Sign in to start chatting with your friends. +

    +
    +
    + {next && } +
    + + +
    +
    + + +
    + {state?.error ? ( +

    {state.error}

    + ) : null} + +
    +

    + Don't have an account?{" "} + + Register + +

    +
    + ); +} diff --git a/app/login/page.tsx b/app/login/page.tsx new file mode 100644 index 0000000..7a52cc8 --- /dev/null +++ b/app/login/page.tsx @@ -0,0 +1,14 @@ +import LoginForm from "./login-form"; + +export default async function LoginPage({ + searchParams, +}: { + searchParams: Promise<{ next?: string }>; +}) { + const { next } = await searchParams; + return ( +
    + +
    + ); +} diff --git a/app/page.tsx b/app/page.tsx index 13eccca..7331fc1 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -1,102 +1,5 @@ -import Image from "next/image"; -import changeBasePath from "@/utils/assets/basepath"; +import { redirect } from "next/navigation"; export default function Home() { - return ( -
    -
    - Next.js logo -
      -
    1. - Get started by editing{" "} - - app/page.tsx - - . -
    2. -
    3. Save and see your changes instantly.
    4. -
    - - -
    - -
    - ); + redirect("/profile"); } diff --git a/app/register/actions.ts b/app/register/actions.ts new file mode 100644 index 0000000..63a9a86 --- /dev/null +++ b/app/register/actions.ts @@ -0,0 +1,31 @@ +"use server"; + +import { signup } from "@/utils/authentication/register"; + +export type RegisterState = { + error?: string; +} | null; + +export async function registerAction( + _prevState: RegisterState, + formData: FormData, +): Promise { + const email = formData.get("email"); + const password = formData.get("password"); + + if (typeof email !== "string" || typeof password !== "string") { + return { error: "Email and password are required." }; + } + + try { + const result = await signup(email, password); + if (result?.error) { + return { error: result.error.message ?? "Registration failed." }; + } + } catch (error) { + const message = error instanceof Error ? error.message : "Registration failed."; + return { error: message }; + } + + return null; +} diff --git a/app/register/page.tsx b/app/register/page.tsx new file mode 100644 index 0000000..3a9c1b3 --- /dev/null +++ b/app/register/page.tsx @@ -0,0 +1,9 @@ +import RegisterForm from "./register-form"; + +export default function RegisterPage() { + return ( +
    + +
    + ); +} diff --git a/app/register/register-form.tsx b/app/register/register-form.tsx new file mode 100644 index 0000000..92fc740 --- /dev/null +++ b/app/register/register-form.tsx @@ -0,0 +1,69 @@ +"use client"; + +import Link from "next/link"; +import { useActionState } from "react"; +import { registerAction, type RegisterState } from "./actions"; + +const initialState: RegisterState = null; + +export default function RegisterForm() { + const [state, action, pending] = useActionState( + registerAction, + initialState, + ); + + return ( +
    +
    +

    Create an account

    +

    + Sign up to start chatting with your friends. +

    +
    +
    +
    + + +
    +
    + + +
    + {state?.error ? ( +

    {state.error}

    + ) : null} + +
    +

    + Already have an account?{" "} + + Log in + +

    +
    + ); +} diff --git a/bun.lock b/bun.lock index 98e685b..a37ce09 100644 --- a/bun.lock +++ b/bun.lock @@ -7,6 +7,7 @@ "dependencies": { "@supabase/ssr": "^0.10.3", "next": "16.2.6", + "qrcode.react": "^4.2.0", "react": "19.2.4", "react-dom": "19.2.4", }, @@ -735,6 +736,8 @@ "punycode": ["punycode@2.3.1", "", {}, "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg=="], + "qrcode.react": ["qrcode.react@4.2.0", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-QpgqWi8rD9DsS9EP3z7BT+5lY5SFhsqGjpgW5DY/i3mK4M9DTBNz3ErMi8BWYEfI3L0d8GIbGmcdFAS1uIRGjA=="], + "queue-microtask": ["queue-microtask@1.2.3", "", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="], "react": ["react@19.2.4", "", {}, "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ=="], diff --git a/next.config.ts b/next.config.ts index 70f8a62..6aa68c0 100644 --- a/next.config.ts +++ b/next.config.ts @@ -3,6 +3,17 @@ import type { NextConfig } from "next"; const nextConfig: NextConfig = { output: "standalone", basePath: process.env.BASE_PATH, + allowedDevOrigins: ["100.64.0.10"], + images: { + remotePatterns: [ + { + protocol: "https", + hostname: "supabase.pascalyazid.com", + port: "", + pathname: "/storage/v1/object/sign/avatars/**", + }, + ], + }, }; export default nextConfig; diff --git a/package.json b/package.json index 122556b..9c3d79d 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ "dependencies": { "@supabase/ssr": "^0.10.3", "next": "16.2.6", + "qrcode.react": "^4.2.0", "react": "19.2.4", "react-dom": "19.2.4" }, diff --git a/proxy.ts b/proxy.ts new file mode 100644 index 0000000..5e840cb --- /dev/null +++ b/proxy.ts @@ -0,0 +1,19 @@ +import { type NextRequest } from "next/server"; +import { updateSession } from "@/utils/supabase/middleware"; + +export async function proxy(request: NextRequest) { + return await updateSession(request); +} + +export const config = { + matcher: [ + /* + * Match all request paths except: + * - _next/static (static files) + * - _next/image (image optimization files) + * - favicon.ico (favicon file) + * - public files (svg, png, jpg, etc.) + */ + "/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)", + ], +}; diff --git a/types/chat.ts b/types/chat.ts index 4cefdae..5cb1d5d 100644 --- a/types/chat.ts +++ b/types/chat.ts @@ -12,5 +12,6 @@ export interface Message { room_id: string; user: { name: string; - }; + avatar_url: string | null; + } | null; } diff --git a/types/profile.ts b/types/profile.ts index 0b29f19..1885de3 100644 --- a/types/profile.ts +++ b/types/profile.ts @@ -2,6 +2,12 @@ export interface Profile { id: string; email: string; name: string; - avatar_url: string; - createdAt: string; + avatar_url: string | null; + created_at: string; + has_identity: boolean; + private_key_enc: string | null; + public_key_dec: string | null; + salt: string | null; + iv: string | null; + auth_tag: string | null; } diff --git a/utils/assets/avatars.ts b/utils/assets/avatars.ts new file mode 100644 index 0000000..f013b72 --- /dev/null +++ b/utils/assets/avatars.ts @@ -0,0 +1,75 @@ +"use server"; + +import { createClient } from "@/utils/supabase/server"; + +/** + * Generate a signed URL for a user's avatar from Supabase storage. + * The bucket is private, so signed URLs are required to access avatars. + * + * @param userId - The user ID whose avatar to fetch + * @param expiresIn - URL expiry in seconds (default: 1 hour) + * @returns Signed URL string, or null if not found/error + */ +export async function getSignedAvatarUrl( + userId: string, + expiresIn: number = 3600, +): Promise { + const supabase = await createClient(); + const { data, error } = await supabase.storage + .from("avatars") + .createSignedUrl(`${userId}/avatar`, expiresIn); + + if (error || !data?.signedUrl) { + return null; + } + + return data.signedUrl; +} + +/** + * Generate signed avatar URLs for multiple users at once. + * Returns a Map of userId -> signedUrl (null if no avatar). + * + * @param userIds - Array of user IDs + * @param expiresIn - URL expiry in seconds (default: 1 hour) + */ +export async function getSignedAvatarUrls( + userIds: string[], + expiresIn: number = 3600, +): Promise> { + const result = new Map(); + + if (userIds.length === 0) return result; + + const supabase = await createClient(); + + // Build the paths for all users + const paths = userIds.map((id) => `${id}/avatar`); + + // createSignedUrl supports an array of paths + const { data, error } = await supabase.storage + .from("avatars") + .createSignedUrls(paths, expiresIn); + + if (error || !data) { + // Fallback: return null for all + for (const id of userIds) { + result.set(id, null); + } + return result; + } + + // data is an array of { path, signedUrl } or { path, error } + const urlByPath = new Map(); + for (const item of data) { + if (item.path) { + urlByPath.set(item.path, item.signedUrl ?? null); + } + } + + for (const id of userIds) { + result.set(id, urlByPath.get(`${id}/avatar`) ?? null); + } + + return result; +} diff --git a/utils/authentication/register.ts b/utils/authentication/register.ts index 5d917d8..d26ec19 100644 --- a/utils/authentication/register.ts +++ b/utils/authentication/register.ts @@ -8,35 +8,27 @@ import { createClient } from "@/utils/supabase/server"; export async function signup(email: string, password: string) { const supabase = await createClient(); - // type-casting here for convenience - // in practice, you should validate your inputs - const login_data = { - email: email, - password: password, - }; - const { data, error } = await supabase.auth.signUp(login_data); + const { data, error } = await supabase.auth.signUp({ email, password }); if (error) { return { data, error }; - } else { - if ( - data.user?.identities?.length == undefined || - data.user.identities.length < 1 - ) { - const error = { message: "Email already in use" }; - return { data, error }; - } else { - //TODO add username field and insert it - const name = "anon"; - //TODO add avatar url field and insert it - const { error } = await supabase - .from("users") - .insert({ id: data.user.id, name: name, email: data.user.email }); - if (error) { - throw error; - } - revalidatePath("/", "layout"); - redirect("/"); - } } + + if ( + data.user?.identities?.length === undefined || + data.user.identities.length < 1 + ) { + return { data, error: { message: "Email already in use" } }; + } + + // TODO: add username field and insert it + const { error: insertError } = await supabase + .from("users") + .insert({ id: data.user.id, name: "anon", email: data.user.email }); + if (insertError) { + throw insertError; + } + + revalidatePath("/", "layout"); + redirect("/"); } diff --git a/utils/authentication/signin.ts b/utils/authentication/signin.ts index 18a303a..48b182c 100644 --- a/utils/authentication/signin.ts +++ b/utils/authentication/signin.ts @@ -1,7 +1,6 @@ "use server"; import { revalidatePath } from "next/cache"; -import { redirect } from "next/navigation"; import { createClient } from "@/utils/supabase/server"; import { validateIdentity } from "@/utils/security/validate_identity"; import { storeAccessKey_Cookie } from "@/utils/security/access_storage"; @@ -10,30 +9,29 @@ import { deriveKey } from "@/utils/security/encryption"; export async function login(email: string, password: string) { const supabase = await createClient(); - const login_data = { - email: email, - password: password, - }; - const { data, error } = await supabase.auth.signInWithPassword(login_data); + const { data, error } = await supabase.auth.signInWithPassword({ + email, + password, + }); if (error) { return { data, error }; - } else { - await validateIdentity(password); - const { data, error } = await supabase - .from("users") - .select("salt") - .eq("id", (await supabase.auth.getUser()).data.user?.id) - .single(); - - if (error) { - throw error; - } - - const salt = Uint8Array.from(atob(data.salt), (c) => c.charCodeAt(0)); - const key = await deriveKey(password, salt); - storeAccessKey_Cookie(key); - revalidatePath("/profile", "layout"); - redirect("/profile"); } + + await validateIdentity(password); + const { data: saltData, error: saltError } = await supabase + .from("users") + .select("salt") + .eq("id", (await supabase.auth.getUser()).data.user?.id) + .single(); + + if (saltError) { + throw saltError; + } + + const salt = Uint8Array.from(atob(saltData.salt), (c) => c.charCodeAt(0)); + const key = await deriveKey(password, salt); + await storeAccessKey_Cookie(key); + revalidatePath("/profile", "layout"); + return { success: true }; } diff --git a/utils/friends/friends.ts b/utils/friends/friends.ts index 671de47..948dd5f 100644 --- a/utils/friends/friends.ts +++ b/utils/friends/friends.ts @@ -1,68 +1,67 @@ "use server"; import { createClient } from "@/utils/supabase/server"; - -export interface Friend { - friend_id: string; - friend_alias: string; -} +import { getSignedAvatarUrls } from "@/utils/assets/avatars"; export async function acceptFriend(sender_id: string) { - const supabase = createClient(); + const supabase = await createClient(); const { data: { user }, - } = await (await supabase).auth.getUser(); + } = await supabase.auth.getUser(); if (!user) return; const receiver_id = user.id; - const add_user = async (sender_id: string, receiver_id: string) => { - const { data: friend } = await (await supabase) - .from("users") - .select("name, public_key_dec") - .eq("id", receiver_id) - .single(); - if (!friend) { - return false; - } + // Look up both users' info + const { data: users } = await supabase + .from("users") + .select("id, name, public_key_dec") + .in("id", [sender_id, receiver_id]); - const { error } = await (await supabase).from("friends").insert({ + if (!users || users.length < 2) { + throw new Error("Could not find both users"); + } + + const senderUser = users.find((u) => u.id === sender_id)!; + const receiverUser = users.find((u) => u.id === receiver_id)!; + + // Insert one row per user: each user gets the other as a friend + const { error: insertError } = await supabase.from("friends").insert([ + { user_id: sender_id, friend_id: receiver_id, - friend_alias: friend.name, - friend_public_key: friend.public_key_dec, - }); - if (error) { - throw error; - } - return true; - }; + friend_alias: receiverUser.name, + friend_public_key: receiverUser.public_key_dec, + }, + { + user_id: receiver_id, + friend_id: sender_id, + friend_alias: senderUser.name, + friend_public_key: senderUser.public_key_dec, + }, + ]); + if (insertError) { + throw insertError; + } - const remove_request = async (sender_id: string, receiver_id: string) => { - const { data, error } = await (await supabase) - .from("friend_requests") - .delete() - .eq("sender_id", sender_id) - .eq("receiver_id", receiver_id); - if (error) { - throw error; - } - if (data) { - return true; - } - }; - add_user(sender_id, receiver_id); - add_user(receiver_id, sender_id); - remove_request(sender_id, receiver_id); + // Remove the accepted request + const { error: deleteError } = await supabase + .from("friend_requests") + .delete() + .eq("sender_id", sender_id) + .eq("receiver_id", receiver_id); + if (deleteError) { + throw deleteError; + } } export async function listRequests() { - const supabase = createClient(); + const supabase = await createClient(); const { data: { user }, - } = await (await supabase).auth.getUser(); + } = await supabase.auth.getUser(); if (!user) return; - const { data, error } = await (await supabase) + const { data, error } = await supabase .from("friend_requests") .select("id, sender_id") .eq("receiver_id", user.id); @@ -70,27 +69,25 @@ export async function listRequests() { if (error) { throw error; } - if (data) { - return data; - } + return data ?? []; } export async function sendFriendRequest(receiver_id: string) { - const supabase = createClient(); + const supabase = await createClient(); const { data: { user }, - } = await (await supabase).auth.getUser(); + } = await supabase.auth.getUser(); if (!user) return; - const isReverse = await reverseRequest(receiver_id); + const isReverse = await reverseRequest(receiver_id); if (isReverse) { - acceptFriend(receiver_id); + await acceptFriend(receiver_id); return true; } - const { error } = await (await supabase) + const { error } = await supabase .from("friend_requests") - .insert([{ sender_id: user.id, receiver_id: receiver_id }]); + .insert([{ sender_id: user.id, receiver_id }]); if (error) { return false; } @@ -98,31 +95,42 @@ export async function sendFriendRequest(receiver_id: string) { } export async function listFriends() { - const supabase = createClient(); + const supabase = await createClient(); const { data: { user }, - } = await (await supabase).auth.getUser(); - if (!user) return; - const { data, error } = await (await supabase) + } = await supabase.auth.getUser(); + if (!user) return null; + + const { data, error } = await supabase .from("friends") .select("friend_id, friend_alias") .eq("user_id", user.id); + if (error) { throw error; } - if (data) { - return data; - } - return null; + + if (!data || data.length === 0) return []; + + // Fetch avatar URLs for all friends using signed URLs + const friendIds = data.map((f) => f.friend_id); + const avatarMap = await getSignedAvatarUrls(friendIds); + + return data.map((f) => ({ + friend_id: f.friend_id, + friend_alias: f.friend_alias, + avatar_url: avatarMap.get(f.friend_id) ?? null, + })); } export async function reverseRequest(friend_id: string) { - const supabase = createClient(); + const supabase = await createClient(); const { data: { user }, - } = await (await supabase).auth.getUser(); + } = await supabase.auth.getUser(); if (!user) return; - const { data, error } = await (await supabase) + + const { data, error } = await supabase .from("friend_requests") .select("sender_id, receiver_id") .eq("sender_id", friend_id) @@ -130,13 +138,5 @@ export async function reverseRequest(friend_id: string) { if (error) { throw error; } - if (data) { - if (data.length == 1) { - return true; - } - if (data.length < 1) { - return false; - } - } - return false; + return data?.length === 1; } diff --git a/utils/profile/profile.ts b/utils/profile/profile.ts index cd0531c..2453374 100644 --- a/utils/profile/profile.ts +++ b/utils/profile/profile.ts @@ -5,8 +5,8 @@ import { redirect } from "next/navigation"; import { removeAccessKey_Cookie } from "@/utils/security/access_storage"; export async function signOut() { - const supabase = createClient(); - removeAccessKey_Cookie(); - (await supabase).auth.signOut(); + const supabase = await createClient(); + await removeAccessKey_Cookie(); + await supabase.auth.signOut(); redirect("/login"); } diff --git a/utils/rooms/chat.ts b/utils/rooms/chat.ts deleted file mode 100644 index 4cc1789..0000000 --- a/utils/rooms/chat.ts +++ /dev/null @@ -1,17 +0,0 @@ -"use server"; -import { privateEncrypt } from "crypto"; -import { decryptPrivateKey } from "@/utils/security/decrypt_private_key"; -export async function encryptMessage(message: string) { - const privateKey = await decryptPrivateKey(); - if (privateKey == null) { - return null; - } - try { - const message_buffer = Buffer.from(message, "utf-8"); - const message_encrypted = privateEncrypt(privateKey, message_buffer); - - return message_encrypted; - } catch (err) { - throw err; - } -} diff --git a/utils/rooms/message_encryption.ts b/utils/rooms/message_encryption.ts deleted file mode 100644 index 4cc1789..0000000 --- a/utils/rooms/message_encryption.ts +++ /dev/null @@ -1,17 +0,0 @@ -"use server"; -import { privateEncrypt } from "crypto"; -import { decryptPrivateKey } from "@/utils/security/decrypt_private_key"; -export async function encryptMessage(message: string) { - const privateKey = await decryptPrivateKey(); - if (privateKey == null) { - return null; - } - try { - const message_buffer = Buffer.from(message, "utf-8"); - const message_encrypted = privateEncrypt(privateKey, message_buffer); - - return message_encrypted; - } catch (err) { - throw err; - } -} diff --git a/utils/rooms/messages.ts b/utils/rooms/messages.ts new file mode 100644 index 0000000..648dd97 --- /dev/null +++ b/utils/rooms/messages.ts @@ -0,0 +1,182 @@ +"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" }; + } +} diff --git a/utils/rooms/rooms.ts b/utils/rooms/rooms.ts new file mode 100644 index 0000000..9cc7c8c --- /dev/null +++ b/utils/rooms/rooms.ts @@ -0,0 +1,237 @@ +"use server"; + +import { createClient } from "@/utils/supabase/server"; +import { + generateRoomKey, + wrapRoomKeyForUser, + getDecryptedRoomKey, +} from "@/utils/security/room_crypto"; +import { getSignedAvatarUrls } from "@/utils/assets/avatars"; + +export async function createRoom(name: string) { + const supabase = await createClient(); + const { + data: { user }, + } = await supabase.auth.getUser(); + if (!user) return { error: "Not authenticated" }; + + // Insert room + membership atomically via RPC + const { data, error } = await supabase.rpc("create_room_with_member", { + room_name: name, + creator_id: user.id, + }); + + if (error) { + return { error: error.message }; + } + + const roomId: string = data; + + // Generate room key and encrypt for the creator + const { data: creator } = await supabase + .from("users") + .select("public_key_dec") + .eq("id", user.id) + .single(); + + if (!creator?.public_key_dec) { + return { error: "User has no encryption key. Please log out and back in." }; + } + + const roomKey = generateRoomKey(); + const encryptedKey = wrapRoomKeyForUser(roomKey, creator.public_key_dec); + + const { error: keyError } = await supabase.from("room_keys").insert({ + room_id: roomId, + user_id: user.id, + encrypted_key: encryptedKey, + }); + + if (keyError) { + console.error("Failed to insert room key:", keyError); + } + + return { roomId }; +} + +export async function listRooms() { + const supabase = await createClient(); + const { + data: { user }, + } = await supabase.auth.getUser(); + if (!user) return []; + + // Get all room_ids the user is a member of + const { data: memberships, error: memError } = await supabase + .from("rooms_users") + .select("room_id") + .eq("user_id", user.id); + + if (memError || !memberships || memberships.length === 0) { + return []; + } + + const roomIds = memberships.map((m) => m.room_id); + + const { data: rooms, error: roomsError } = await supabase + .from("rooms") + .select("id, name, created_at") + .in("id", roomIds) + .order("created_at", { ascending: false }); + + if (roomsError) { + throw roomsError; + } + + // Get member counts per room + const { data: counts } = await supabase + .from("rooms_users") + .select("room_id") + .in("room_id", roomIds); + + const countMap = new Map(); + for (const c of counts ?? []) { + countMap.set(c.room_id, (countMap.get(c.room_id) ?? 0) + 1); + } + + return (rooms ?? []).map((room) => ({ + id: room.id, + name: room.name, + created_at: room.created_at, + member_count: countMap.get(room.id) ?? 0, + })); +} + +export async function addMember(roomId: string, userId: string) { + const supabase = await createClient(); + const { + data: { user }, + } = await supabase.auth.getUser(); + if (!user) return { error: "Not authenticated" }; + + // Verify the target user exists and has a public key + const { data: targetUser } = await supabase + .from("users") + .select("id, public_key_dec") + .eq("id", userId) + .single(); + + if (!targetUser) { + return { error: "User not found" }; + } + + if (!targetUser.public_key_dec) { + return { error: "User has no encryption key" }; + } + + // Add to room membership + const { error } = await supabase + .from("rooms_users") + .insert({ room_id: roomId, user_id: userId }); + + if (error) { + return { error: error.message }; + } + + // Decrypt room key, then encrypt for the new member + const roomKey = await getDecryptedRoomKey(roomId); + if (!roomKey) { + return { error: "Could not access room encryption key" }; + } + + const encryptedKey = wrapRoomKeyForUser(roomKey, targetUser.public_key_dec); + + const { error: keyError } = await supabase.from("room_keys").insert({ + room_id: roomId, + user_id: userId, + encrypted_key: encryptedKey, + }); + + if (keyError) { + console.error("Failed to insert room key for new member:", keyError); + return { error: "Failed to set up encryption for new member" }; + } + + return { success: true }; +} + +export async function listMembers(roomId: string) { + const supabase = await createClient(); + + const { data, error } = await supabase + .from("rooms_users") + .select("user_id, users(name)") + .eq("room_id", roomId); + + if (error) { + throw error; + } + + const rawMembers = (data ?? []).map((row) => { + const user = row.users as unknown as { name: string } | null; + return { + user_id: row.user_id, + name: user?.name ?? "Unknown", + }; + }); + + // Generate signed avatar URLs for all members + const memberIds = rawMembers.map((m) => m.user_id); + const avatarMap = await getSignedAvatarUrls(memberIds); + + return rawMembers.map((m) => ({ + user_id: m.user_id, + name: m.name, + avatar_url: avatarMap.get(m.user_id) ?? null, + })); +} + +export async function deleteRoom(roomId: string) { + const supabase = await createClient(); + const { + data: { user }, + } = await supabase.auth.getUser(); + if (!user) return { error: "Not authenticated" }; + + // Delete the room — CASCADE will remove rooms_users, room_keys, and messages + const { error } = await supabase.from("rooms").delete().eq("id", roomId); + + if (error) { + return { error: error.message }; + } + + return { success: true }; +} + +export async function removeMember(roomId: string, userId: string) { + const supabase = await createClient(); + const { + data: { user }, + } = await supabase.auth.getUser(); + if (!user) return { error: "Not authenticated" }; + + // Can't remove yourself — use "leave room" or "delete room" instead + if (user.id === userId) { + return { error: "You cannot remove yourself. Delete the room instead." }; + } + + // Remove membership + const { error } = await supabase + .from("rooms_users") + .delete() + .eq("room_id", roomId) + .eq("user_id", userId); + + if (error) { + return { error: error.message }; + } + + // Remove their room keys + await supabase + .from("room_keys") + .delete() + .eq("room_id", roomId) + .eq("user_id", userId); + + return { success: true }; +} diff --git a/utils/security/access_storage.ts b/utils/security/access_storage.ts index 7738a43..ec29681 100644 --- a/utils/security/access_storage.ts +++ b/utils/security/access_storage.ts @@ -1,43 +1,33 @@ "use server"; -import { error } from "console"; import { subtle } from "crypto"; import { cookies } from "next/headers"; export async function storeAccessKey_Cookie(key: CryptoKey) { - if (key.extractable) { - try { - const exported = await subtle.exportKey("raw", key); - const exportedKeyBuffer = new Uint8Array(exported); - const key_base64 = Buffer.from(exportedKeyBuffer).toString("base64"); - (await cookies()).set("user_identity", key_base64); - } catch (err) { - throw error.apply(err); - } - } else { - return; - } + if (!key.extractable) return; + + const exported = await subtle.exportKey("raw", key); + const exportedKeyBuffer = new Uint8Array(exported); + const key_base64 = Buffer.from(exportedKeyBuffer).toString("base64"); + (await cookies()).set("user_identity", key_base64); } export async function removeAccessKey_Cookie() { - (await cookies()).set("user_identity", ""); + (await cookies()).set("user_identity", "", { maxAge: 0 }); } -export async function retreiveAccessKey_Cookie() { +export async function retrieveAccessKey_Cookie() { const cookieStore = await cookies(); - try { - const key_base64 = cookieStore.get("user_identity"); - if (key_base64 == null || key_base64.value.length < 1) { - return null; - } - const key_raw = Uint8Array.from(atob(key_base64.value), (c) => - c.charCodeAt(0), - ); - const key = subtle.importKey("raw", key_raw, "AES-GCM", true, [ - "encrypt", - "decrypt", - ]); - return key; - } catch (err) { - return error.apply(err); + const key_base64 = cookieStore.get("user_identity"); + if (key_base64 == null || key_base64.value.length < 1) { + return null; } + + const key_raw = Uint8Array.from(atob(key_base64.value), (c) => + c.charCodeAt(0), + ); + const key = await subtle.importKey("raw", key_raw, "AES-GCM", true, [ + "encrypt", + "decrypt", + ]); + return key; } diff --git a/utils/security/decrypt_private_key.ts b/utils/security/decrypt_private_key.ts index ec4d824..96b0f76 100644 --- a/utils/security/decrypt_private_key.ts +++ b/utils/security/decrypt_private_key.ts @@ -1,44 +1,7 @@ "use server"; import { subtle } from "crypto"; import { createClient } from "@/utils/supabase/server"; -import { deriveKey } from "./encryption"; -import { retreiveAccessKey_Cookie } from "./access_storage"; - -export async function setAccessKey(plain_pw: string) { - const supabase = await createClient(); - const { data: key_data, error } = await supabase - .from("users") - .select("private_key_enc, salt, iv, auth_tag") - .eq("id", (await supabase.auth.getUser()).data.user?.id) - .single(); - - if (error) { - return null; - } - const salt_Base64 = key_data?.salt || ""; - const encryptedPrivateKey_Base64 = key_data?.private_key_enc || ""; - const authTag_base64 = key_data?.auth_tag || ""; - - const encodedPrivateKey = Uint8Array.from( - atob(encryptedPrivateKey_Base64), - (c) => c.charCodeAt(0), - ); - const authTag = Uint8Array.from(atob(authTag_base64), (c) => c.charCodeAt(0)); - const salt = Uint8Array.from(atob(salt_Base64), (c) => c.charCodeAt(0)); - - const dataWithAuthTag = new Uint8Array( - encodedPrivateKey.length + authTag.length, - ); - dataWithAuthTag.set(encodedPrivateKey, 0); - dataWithAuthTag.set(authTag, encodedPrivateKey.length); - - const key = await deriveKey(plain_pw, salt); - - if (key == null) { - return null; - } - return key; -} +import { retrieveAccessKey_Cookie } from "./access_storage"; export async function decryptPrivateKey() { const supabase = await createClient(); @@ -68,7 +31,7 @@ export async function decryptPrivateKey() { dataWithAuthTag.set(encodedPrivateKey, 0); dataWithAuthTag.set(authTag, encodedPrivateKey.length); - const key = await retreiveAccessKey_Cookie(); + const key = await retrieveAccessKey_Cookie(); if (key == null) { return null; } diff --git a/utils/security/encryption.ts b/utils/security/encryption.ts index 072eda8..85f793a 100644 --- a/utils/security/encryption.ts +++ b/utils/security/encryption.ts @@ -1,4 +1,3 @@ -"use server"; import { subtle } from "crypto"; export async function deriveKey(passphrase: string, salt: Uint8Array) { diff --git a/utils/security/room_crypto.ts b/utils/security/room_crypto.ts new file mode 100644 index 0000000..0083d68 --- /dev/null +++ b/utils/security/room_crypto.ts @@ -0,0 +1,162 @@ +import { + getRandomValues, + publicEncrypt, + privateDecrypt, + constants, + subtle, +} from "crypto"; +import { decryptPrivateKey } from "./decrypt_private_key"; +import { createClient } from "@/utils/supabase/server"; + +/** + * Generate a random 256-bit AES room key. + */ +export function generateRoomKey(): Uint8Array { + return getRandomValues(new Uint8Array(32)); +} + +/** + * RSA-OAEP encrypt a room key with a user's public key. + * Returns base64-encoded encrypted key. + */ +export function wrapRoomKeyForUser( + roomKey: Uint8Array, + publicKeyPem: string, +): string { + const encrypted = publicEncrypt( + { + key: publicKeyPem, + padding: constants.RSA_PKCS1_OAEP_PADDING, + oaepHash: "sha256", + }, + Buffer.from(roomKey), + ); + return encrypted.toString("base64"); +} + +/** + * RSA-OAEP decrypt an encrypted room key using the current user's private key. + * Returns the raw room key bytes, or null on failure. + */ +export async function unwrapRoomKey( + encryptedKeyBase64: string, +): Promise { + const privateKeyPem = await decryptPrivateKey(); + if (!privateKeyPem) return null; + + try { + const encryptedKey = Buffer.from(encryptedKeyBase64, "base64"); + const decrypted = privateDecrypt( + { + key: privateKeyPem, + passphrase: "", + padding: constants.RSA_PKCS1_OAEP_PADDING, + oaepHash: "sha256", + }, + encryptedKey, + ); + return new Uint8Array(decrypted); + } catch { + return null; + } +} + +/** + * AES-256-GCM encrypt a plaintext message with a room key. + * Returns base64-encoded ciphertext, IV, and auth tag. + */ +export async function encryptMessageValue( + plaintext: string, + roomKey: Uint8Array, +): Promise<{ ciphertext: string; iv: string; authTag: string }> { + const iv = getRandomValues(new Uint8Array(12)); + + const key = await subtle.importKey( + "raw", + roomKey, + { name: "AES-GCM" }, + false, + ["encrypt"], + ); + + const encoded = new TextEncoder().encode(plaintext); + const encrypted = await subtle.encrypt( + { name: "AES-GCM", iv, tagLength: 128 }, + key, + encoded, + ); + + // Web Crypto AES-GCM output = ciphertext || authTag (last 16 bytes) + const buf = Buffer.from(encrypted); + const ciphertext = buf.slice(0, buf.length - 16).toString("base64"); + const authTag = buf.slice(buf.length - 16).toString("base64"); + + return { + ciphertext, + iv: Buffer.from(iv).toString("base64"), + authTag, + }; +} + +/** + * AES-256-GCM decrypt a message with a room key. + */ +export async function decryptMessageValue( + ciphertextBase64: string, + ivBase64: string, + authTagBase64: string, + roomKey: Uint8Array, +): Promise { + const ciphertext = Buffer.from(ciphertextBase64, "base64"); + const iv = new Uint8Array(Buffer.from(ivBase64, "base64")); + const authTag = Buffer.from(authTagBase64, "base64"); + + // Reassemble ciphertext + authTag for Web Crypto API + const combined = new Uint8Array(ciphertext.length + authTag.length); + combined.set(ciphertext, 0); + combined.set(authTag, ciphertext.length); + + const key = await subtle.importKey( + "raw", + roomKey, + { name: "AES-GCM" }, + false, + ["decrypt"], + ); + + const decrypted = await subtle.decrypt( + { name: "AES-GCM", iv, tagLength: 128 }, + key, + combined, + ); + + return new TextDecoder().decode(decrypted); +} + +/** + * Get the decrypted room key for the current user in a given room. + * Fetches the latest key version from the database and decrypts it. + * Returns null if the user has no key for this room. + */ +export async function getDecryptedRoomKey( + roomId: string, +): Promise { + const supabase = await createClient(); + const { + data: { user }, + } = await supabase.auth.getUser(); + if (!user) return null; + + const { data, error } = await supabase + .from("room_keys") + .select("encrypted_key") + .eq("room_id", roomId) + .eq("user_id", user.id) + .order("key_version", { ascending: false }) + .limit(1) + .maybeSingle(); + + if (error || !data) return null; + + return unwrapRoomKey(data.encrypted_key); +} diff --git a/utils/security/validate_identity.ts b/utils/security/validate_identity.ts index 5c46059..5c5a68b 100644 --- a/utils/security/validate_identity.ts +++ b/utils/security/validate_identity.ts @@ -4,12 +4,15 @@ import { generateKeyPair } from "@/utils/security/encrypt_private_key"; import { createClient } from "@/utils/supabase/server"; export async function validateIdentity(plain_pw: string) { - const supabase = createClient(); - const user_id = (await (await supabase).auth.getUser()).data.user?.id; + const supabase = await createClient(); + const { + data: { user }, + } = await supabase.auth.getUser(); + const user_id = user?.id; if (user_id == null) { return null; } - const { data, error } = await (await supabase) + const { data, error } = await supabase .from("users") .select("has_identity") .eq("id", user_id) @@ -20,14 +23,13 @@ export async function validateIdentity(plain_pw: string) { } if (!data.has_identity) { - generateKeyPair(plain_pw, user_id); - const { error } = await (await supabase) + await generateKeyPair(plain_pw, user_id); + const { error: updateError } = await supabase .from("users") .update({ has_identity: true }) - .eq("id", user_id) - .single(); - if (error) { - throw error; + .eq("id", user_id); + if (updateError) { + throw updateError; } } } diff --git a/utils/supabase/realtime.ts b/utils/supabase/realtime.ts index 3ef321b..525da42 100644 --- a/utils/supabase/realtime.ts +++ b/utils/supabase/realtime.ts @@ -3,10 +3,9 @@ import { createClient } from "./server"; export async function realtimeToken() { - const supabase = createClient(); + const supabase = await createClient(); - const token = (await (await supabase).auth.getSession()).data.session - ?.access_token; + const token = (await supabase.auth.getSession()).data.session?.access_token; if (!token) return null; return token; } diff --git a/utils/validation.ts b/utils/validation.ts new file mode 100644 index 0000000..95a5dfd --- /dev/null +++ b/utils/validation.ts @@ -0,0 +1,2 @@ +export const UUID_REGEX = + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;