Reimplemented outdated code, added encryption keys for each room, added support for profile images, added friend requests via url/qr-code
This commit is contained in:
1 parent
508f17315e
commit
32e4bf8b32
58 files changed
+3225
-317
No files matched your search
@@ -0,0 +1,44 @@
|
||||
"use client";
|
||||
|
||||
export default function AuthError({
|
||||
error,
|
||||
reset,
|
||||
}: {
|
||||
error: Error & { digest?: string };
|
||||
reset: () => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<div className="flex flex-col items-center gap-4 text-center">
|
||||
<div className="flex size-12 items-center justify-center rounded-full bg-red-50">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
className="size-6 text-red-500"
|
||||
>
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
d="M18 10a8 8 0 1 1-16 0 8 8 0 0 1 16 0Zm-8-5a.75.75 0 0 1 .75.75v4.5a.75.75 0 0 1-1.5 0v-4.5A.75.75 0 0 1 10 5Zm0 10a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-neutral-900">
|
||||
Something went wrong
|
||||
</h2>
|
||||
<p className="mt-1 text-sm text-neutral-500">
|
||||
{error.message || "An unexpected error occurred."}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={reset}
|
||||
className="rounded-lg bg-neutral-900 px-4 py-2 text-sm font-medium text-white shadow-sm transition hover:bg-neutral-800"
|
||||
>
|
||||
Try again
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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<AddFriendState> {
|
||||
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");
|
||||
}
|
||||
@@ -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 (
|
||||
<form action={action} className="space-y-3">
|
||||
<label htmlFor="userId" className="block text-sm font-medium text-neutral-700">
|
||||
Add by User ID
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
id="userId"
|
||||
name="userId"
|
||||
type="text"
|
||||
placeholder="e.g. 3b241101-e2bb-..."
|
||||
required
|
||||
className="flex-1 rounded-lg border border-neutral-300 bg-white px-3 py-2 text-sm text-neutral-900 shadow-sm placeholder:text-neutral-400 focus:border-neutral-900 focus:outline-none"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={pending}
|
||||
className="rounded-lg bg-neutral-900 px-4 py-2 text-sm font-medium text-white shadow-sm transition hover:bg-neutral-800 disabled:cursor-not-allowed disabled:bg-neutral-400"
|
||||
>
|
||||
{pending ? "Sending..." : "Add"}
|
||||
</button>
|
||||
</div>
|
||||
{state?.error && (
|
||||
<p className="text-sm text-red-600">{state.error}</p>
|
||||
)}
|
||||
{state?.success && (
|
||||
<p className="text-sm text-emerald-600">Friend request sent!</p>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<div className="mx-auto max-w-3xl px-6 py-10">
|
||||
<ResultCard
|
||||
status="error"
|
||||
message="Invalid or missing user ID in the link."
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<div className="mx-auto max-w-3xl px-6 py-10">
|
||||
<ResultCard
|
||||
status="error"
|
||||
message="You can't send yourself a friend request."
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Look up the target user
|
||||
const { data: targetUser } = await supabase
|
||||
.from("users")
|
||||
.select("id, name")
|
||||
.eq("id", id)
|
||||
.single();
|
||||
|
||||
if (!targetUser) {
|
||||
return (
|
||||
<div className="mx-auto max-w-3xl px-6 py-10">
|
||||
<ResultCard status="error" message="User not found." />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 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 (
|
||||
<div className="mx-auto max-w-3xl px-6 py-10">
|
||||
<ResultCard
|
||||
status="already_friends"
|
||||
message={`You are already friends with ${targetUser.name}.`}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 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 (
|
||||
<div className="mx-auto max-w-3xl px-6 py-10">
|
||||
<ResultCard status={status} message={message} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ResultCard({
|
||||
status,
|
||||
message,
|
||||
}: {
|
||||
status: ResultStatus;
|
||||
message: string;
|
||||
}) {
|
||||
const isSuccess = status === "success";
|
||||
const isAlreadyFriends = status === "already_friends";
|
||||
|
||||
return (
|
||||
<div className="rounded-xl border border-neutral-200 bg-white p-8 shadow-sm">
|
||||
<div className="flex flex-col items-center text-center">
|
||||
<div
|
||||
className={`flex size-12 items-center justify-center rounded-full ${
|
||||
isSuccess
|
||||
? "bg-emerald-100"
|
||||
: isAlreadyFriends
|
||||
? "bg-blue-100"
|
||||
: "bg-red-100"
|
||||
}`}
|
||||
>
|
||||
{isSuccess ? (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
className="size-6 text-emerald-600"
|
||||
>
|
||||
<path d="M10 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM3.465 14.493a1.23 1.23 0 0 0 .41 1.412A9.957 9.957 0 0 0 10 18c2.31 0 4.438-.784 6.131-2.1.43-.333.604-.903.408-1.41a7.002 7.002 0 0 0-13.074.003Z" />
|
||||
</svg>
|
||||
) : isAlreadyFriends ? (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
className="size-6 text-blue-600"
|
||||
>
|
||||
<path d="M10 9a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM6 8a2 2 0 1 1-4 0 2 2 0 0 1 4 0ZM1.49 15.326a.75.75 0 0 0 .41.18 9.957 9.957 0 0 0 2.1.196 9.957 9.957 0 0 0 2.1-.196.75.75 0 0 0 .41-.18 7.002 7.002 0 0 0-5.02 0ZM16.9 15.326a7.002 7.002 0 0 1-5.02 0 .75.75 0 0 1 .41.18 9.957 9.957 0 0 0 4.2 0 .75.75 0 0 1 .41-.18ZM18 8a2 2 0 1 1-4 0 2 2 0 0 1 4 0ZM5.304 16.255A7.025 7.025 0 0 0 10 17.5c1.792 0 3.44-.672 4.696-1.783A5.98 5.98 0 0 0 10 15a5.98 5.98 0 0 0-4.696 1.255Z" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
className="size-6 text-red-600"
|
||||
>
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
d="M18 10a8 8 0 1 1-16 0 8 8 0 0 1 16 0Zm-8-5a.75.75 0 0 1 .75.75v4.5a.75.75 0 0 1-1.5 0v-4.5A.75.75 0 0 1 10 5Zm0 10a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<h1 className="mt-4 text-lg font-semibold text-neutral-900">
|
||||
{isSuccess
|
||||
? "Request Sent!"
|
||||
: isAlreadyFriends
|
||||
? "Already Friends"
|
||||
: "Something went wrong"}
|
||||
</h1>
|
||||
<p className="mt-2 text-sm text-neutral-600">{message}</p>
|
||||
|
||||
<div className="mt-6 flex gap-3">
|
||||
<Link
|
||||
href="/friends"
|
||||
className="rounded-lg bg-neutral-900 px-4 py-2 text-sm font-medium text-white shadow-sm transition hover:bg-neutral-800"
|
||||
>
|
||||
Back to Friends
|
||||
</Link>
|
||||
<Link
|
||||
href="/rooms"
|
||||
className="rounded-lg border border-neutral-300 px-4 py-2 text-sm font-medium text-neutral-700 transition hover:bg-neutral-50"
|
||||
>
|
||||
Go to Rooms
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<div className="flex flex-col items-center rounded-xl border border-dashed border-neutral-300 py-12">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={1}
|
||||
className="size-10 text-neutral-300"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M15 19.128a9.38 9.38 0 0 0 2.625.372 9.337 9.337 0 0 0 4.121-.952 4.125 4.125 0 0 0-7.533-2.493M15 19.128v-.003c0-1.113-.285-2.16-.786-3.07M15 19.128v.106A12.318 12.318 0 0 1 8.624 21c-2.331 0-4.512-.645-6.374-1.766l-.001-.109a6.375 6.375 0 0 1 11.964-3.07M12 6.375a3.375 3.375 0 1 1-6.75 0 3.375 3.375 0 0 1 6.75 0Zm8.25 2.25a2.625 2.625 0 1 1-5.25 0 2.625 2.625 0 0 1 5.25 0Z"
|
||||
/>
|
||||
</svg>
|
||||
<p className="mt-3 text-sm text-neutral-400">No friends yet</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold text-neutral-900">
|
||||
Friends
|
||||
<span className="ml-2 text-xs font-normal text-neutral-500">
|
||||
{friends.length}
|
||||
</span>
|
||||
</h2>
|
||||
<ul className="mt-3 divide-y divide-neutral-100 rounded-xl border border-neutral-200 bg-white">
|
||||
{friends.map((friend) => (
|
||||
<li
|
||||
key={friend.friend_id}
|
||||
className="flex items-center gap-3 px-4 py-3"
|
||||
>
|
||||
{friend.avatar_url ? (
|
||||
<Image
|
||||
src={friend.avatar_url}
|
||||
alt=""
|
||||
width={200}
|
||||
height={200}
|
||||
className="size-16 rounded-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex size-8 items-center justify-center rounded-full bg-neutral-100 text-xs font-medium text-neutral-600">
|
||||
{friend.friend_alias.charAt(0).toUpperCase()}
|
||||
</div>
|
||||
)}
|
||||
<span className="text-sm font-medium text-neutral-900">
|
||||
{friend.friend_alias} - {friend.friend_id}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<div className="mx-auto max-w-3xl px-6 py-10">
|
||||
<h1 className="text-2xl font-semibold text-neutral-900">Friends</h1>
|
||||
<p className="mt-1 text-sm text-neutral-500">
|
||||
Manage your friends and requests.
|
||||
</p>
|
||||
|
||||
<div className="mt-8 space-y-8">
|
||||
{/* Add friend */}
|
||||
<div className="rounded-xl border border-neutral-200 bg-white p-5 shadow-sm">
|
||||
<AddFriendForm />
|
||||
</div>
|
||||
|
||||
{/* Incoming requests */}
|
||||
<RequestsList requests={requests} />
|
||||
|
||||
{/* Friends list */}
|
||||
<FriendsList friends={friends} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold text-neutral-900">
|
||||
Incoming Requests
|
||||
<span className="ml-2 inline-flex size-5 items-center justify-center rounded-full bg-neutral-900 text-xs text-white">
|
||||
{requests.length}
|
||||
</span>
|
||||
</h2>
|
||||
<ul className="mt-3 divide-y divide-neutral-100 rounded-xl border border-neutral-200 bg-white">
|
||||
{requests.map((req) => (
|
||||
<RequestItem key={req.id} req={req} />
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RequestItem({ req }: { req: FriendRequest }) {
|
||||
const [pending, startTransition] = useTransition();
|
||||
|
||||
return (
|
||||
<li className="flex items-center justify-between px-4 py-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex size-8 items-center justify-center rounded-full bg-neutral-100 text-xs font-medium text-neutral-600">
|
||||
{req.sender_name.charAt(0).toUpperCase()}
|
||||
</div>
|
||||
<span className="text-sm font-medium text-neutral-900">
|
||||
{req.sender_name}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
disabled={pending}
|
||||
onClick={() => startTransition(() => acceptRequestAction(req.sender_id))}
|
||||
className="rounded-lg bg-neutral-900 px-3 py-1.5 text-xs font-medium text-white transition hover:bg-neutral-800 disabled:cursor-not-allowed disabled:bg-neutral-400"
|
||||
>
|
||||
{pending ? "Accepting..." : "Accept"}
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<div className="flex h-screen bg-neutral-50">
|
||||
<Sidebar
|
||||
displayName={displayName}
|
||||
email={user?.email ?? ""}
|
||||
avatarUrl={avatarURL}
|
||||
/>
|
||||
<main className="flex-1 overflow-y-auto">{children}</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
export default function AuthLoading() {
|
||||
return (
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<div className="size-8 animate-spin rounded-full border-2 border-neutral-300 border-t-neutral-900" />
|
||||
<p className="text-sm text-neutral-500">Loading...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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<UpdateNameState> {
|
||||
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<UploadAvatarState> {
|
||||
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 };
|
||||
}
|
||||
@@ -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<HTMLInputElement>(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 (
|
||||
<form action={action} className="inline-block">
|
||||
<input
|
||||
ref={inputRef}
|
||||
name="avatar"
|
||||
type="file"
|
||||
accept="image/png,image/jpeg,image/jpg"
|
||||
className="hidden"
|
||||
onChange={handleChange}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleClick}
|
||||
disabled={pending}
|
||||
className="group relative"
|
||||
>
|
||||
{avatarUrl ? (
|
||||
<Image
|
||||
src={avatarUrl}
|
||||
alt=""
|
||||
width={200}
|
||||
height={200}
|
||||
className="size-20 rounded-full border-4 border-white object-cover shadow-md transition group-hover:opacity-80"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex size-20 items-center justify-center rounded-full border-4 border-white bg-neutral-900 text-2xl font-semibold text-white shadow-md transition group-hover:bg-neutral-700">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
className="size-6"
|
||||
>
|
||||
<path d="M10 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM3.465 14.493a1.23 1.23 0 0 0 .41 1.412A9.957 9.957 0 0 0 10 18c2.31 0 4.438-.784 6.131-2.1.43-.333.604-.903.408-1.41a7.002 7.002 0 0 0-13.074.003Z" />
|
||||
</svg>
|
||||
</div>
|
||||
)}
|
||||
{pending && (
|
||||
<div className="absolute inset-0 flex items-center justify-center rounded-full bg-black/30">
|
||||
<div className="size-5 animate-spin rounded-full border-2 border-white border-t-transparent" />
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
{state && "error" in state && (
|
||||
<p className="mt-2 text-center text-xs text-red-600">{state.error}</p>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -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<HTMLInputElement>(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 (
|
||||
<div className="mt-3 flex items-center gap-3">
|
||||
<h2 className="text-xl font-semibold text-neutral-900">
|
||||
{currentName}
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleEdit}
|
||||
className="rounded-md px-2 py-1 text-xs font-medium text-neutral-500 transition hover:bg-neutral-100 hover:text-neutral-900"
|
||||
>
|
||||
Edit
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<form action={action} className="mt-3">
|
||||
<div className="flex items-start gap-2">
|
||||
<input
|
||||
ref={inputRef}
|
||||
name="name"
|
||||
type="text"
|
||||
defaultValue={currentName}
|
||||
required
|
||||
maxLength={50}
|
||||
className="w-64 rounded-lg border border-neutral-300 bg-white px-3 py-1.5 text-lg font-semibold text-neutral-900 shadow-sm focus:border-neutral-900 focus:outline-none"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={pending}
|
||||
className="rounded-lg bg-neutral-900 px-3 py-1.5 text-sm font-medium text-white shadow-sm transition hover:bg-neutral-800 disabled:cursor-not-allowed disabled:bg-neutral-400"
|
||||
>
|
||||
{pending ? "..." : "Save"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setEditing(false)}
|
||||
className="rounded-lg border border-neutral-300 px-3 py-1.5 text-sm font-medium text-neutral-700 transition hover:bg-neutral-50"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
{state && "error" in state && (
|
||||
<p className="mt-1 text-xs text-red-600">{state.error}</p>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -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<Profile>();
|
||||
|
||||
if (!profile) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<p className="text-neutral-500">Profile not found.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 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 (
|
||||
<div className="mx-auto max-w-3xl px-6 py-10">
|
||||
{/* Header */}
|
||||
<h1 className="text-2xl font-semibold text-neutral-900">Profile</h1>
|
||||
<p className="mt-1 text-sm text-neutral-500">
|
||||
Manage your account information.
|
||||
</p>
|
||||
|
||||
{/* Profile Card */}
|
||||
<div className="mt-8 rounded-xl border border-neutral-200 bg-white shadow-sm">
|
||||
{/* Banner area */}
|
||||
<div className="h-28 rounded-t-xl bg-linear-to-br from-neutral-800 to-neutral-600" />
|
||||
|
||||
{/* Avatar + name */}
|
||||
<div className="relative px-6 pb-6">
|
||||
<AvatarUpload avatarUrl={avatarUrl} />
|
||||
|
||||
<EditableName key={profile.name} currentName={profile.name} />
|
||||
<div className="mt-3 flex items-center gap-3">
|
||||
<p className="text-sm text-neutral-500">{profile.email}</p>
|
||||
<ShareProfileButton userId={profile.id} shareUrl={shareUrl} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Details */}
|
||||
<div className="mt-6 space-y-4">
|
||||
<div className="rounded-xl border border-neutral-200 bg-white shadow-sm">
|
||||
<div className="border-b border-neutral-100 px-6 py-4">
|
||||
<h3 className="text-sm font-semibold text-neutral-900">
|
||||
Account Details
|
||||
</h3>
|
||||
</div>
|
||||
<dl className="divide-y divide-neutral-100">
|
||||
<DetailRow label="User ID" value={profile.id} mono />
|
||||
<DetailRow label="Display Name" value={profile.name} />
|
||||
<DetailRow label="Email" value={profile.email} />
|
||||
<DetailRow label="Member Since" value={memberSince} />
|
||||
<DetailRow
|
||||
label="Identity Verified"
|
||||
value={profile.has_identity ? "Yes" : "No"}
|
||||
badge={profile.has_identity ? "green" : "yellow"}
|
||||
/>
|
||||
<DetailRow
|
||||
label="Encryption Keys"
|
||||
value={
|
||||
profile.private_key_enc && profile.public_key_dec
|
||||
? "Set up"
|
||||
: "Not configured"
|
||||
}
|
||||
badge={
|
||||
profile.private_key_enc && profile.public_key_dec
|
||||
? "green"
|
||||
: "yellow"
|
||||
}
|
||||
/>
|
||||
</dl>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DetailRow({
|
||||
label,
|
||||
value,
|
||||
mono,
|
||||
badge,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
mono?: boolean;
|
||||
badge?: "green" | "yellow";
|
||||
}) {
|
||||
return (
|
||||
<div className="flex items-center justify-between px-6 py-3.5">
|
||||
<dt className="text-sm text-neutral-500">{label}</dt>
|
||||
<dd>
|
||||
{badge ? (
|
||||
<span
|
||||
className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${
|
||||
badge === "green"
|
||||
? "bg-emerald-50 text-emerald-700"
|
||||
: "bg-amber-50 text-amber-700"
|
||||
}`}
|
||||
>
|
||||
{value}
|
||||
</span>
|
||||
) : (
|
||||
<span
|
||||
className={`text-sm text-neutral-900 ${mono ? "font-mono text-xs" : ""}`}
|
||||
>
|
||||
{value}
|
||||
</span>
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen(true)}
|
||||
className="rounded-lg bg-neutral-900 px-4 py-2 text-sm font-medium text-white shadow-sm transition hover:bg-neutral-800"
|
||||
>
|
||||
Share Profile
|
||||
</button>
|
||||
|
||||
{open && (
|
||||
<>
|
||||
{/* Backdrop */}
|
||||
<div
|
||||
className="fixed inset-0 z-40 bg-black/40"
|
||||
onClick={() => setOpen(false)}
|
||||
/>
|
||||
|
||||
{/* Modal */}
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
|
||||
<div className="w-full max-w-sm rounded-2xl border border-neutral-200 bg-white p-6 shadow-xl">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-lg font-semibold text-neutral-900">
|
||||
Share Profile
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen(false)}
|
||||
className="flex size-8 items-center justify-center rounded-lg text-neutral-400 transition hover:bg-neutral-100 hover:text-neutral-600"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
className="size-5"
|
||||
>
|
||||
<path d="M6.28 5.22a.75.75 0 0 0-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 1 0 1.06 1.06L10 11.06l3.72 3.72a.75.75 0 1 0 1.06-1.06L11.06 10l3.72-3.72a.75.75 0 0 0-1.06-1.06L10 8.94 6.28 5.22Z" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p className="mt-2 text-sm text-neutral-500">
|
||||
Scan this QR code or share the link to add you as a friend.
|
||||
</p>
|
||||
|
||||
{/* QR Code */}
|
||||
<div className="mt-5 flex justify-center rounded-xl border border-neutral-100 bg-white p-4">
|
||||
<QRCodeSVG
|
||||
value={shareUrl}
|
||||
size={200}
|
||||
level="M"
|
||||
includeMargin={false}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Link + Copy */}
|
||||
<div className="mt-4 flex items-center gap-2">
|
||||
<input
|
||||
type="text"
|
||||
readOnly
|
||||
value={shareUrl}
|
||||
className="flex-1 rounded-lg border border-neutral-200 bg-neutral-50 px-3 py-2 text-xs font-mono text-neutral-600 focus:outline-none"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCopy}
|
||||
className="shrink-0 rounded-lg border border-neutral-200 px-3 py-2 text-xs font-medium text-neutral-700 transition hover:bg-neutral-100"
|
||||
>
|
||||
{copied ? "Copied!" : "Copy"}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* User ID reference */}
|
||||
<p className="mt-3 text-center text-xs text-neutral-400">
|
||||
User ID: {userId}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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<SendMessageState> {
|
||||
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);
|
||||
}
|
||||
@@ -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<string, MemberInfo>;
|
||||
}) {
|
||||
const boundAction = sendMessageAction.bind(null, roomId);
|
||||
const [state, action, pending] = useActionState(boundAction, initialState);
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
const bottomRef = useRef<HTMLDivElement>(null);
|
||||
const optimisticCounter = useRef(0);
|
||||
|
||||
const [localMessages, setLocalMessages] = useState<Message[]>([]);
|
||||
|
||||
// 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<string>();
|
||||
|
||||
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<string, string> }) => {
|
||||
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 (
|
||||
<div className=" rounded-xl border border-neutral-200 bg-white shadow-sm">
|
||||
{/* Messages area */}
|
||||
<div className="h-[calc(100vh-20rem)] overflow-y-auto p-4">
|
||||
{displayMessages.length === 0 ? (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<p className="text-sm text-neutral-400">
|
||||
No messages yet. Start the conversation!
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{displayMessages.map((msg) => {
|
||||
const isOwn = msg.user_id === currentUserId;
|
||||
const isPending = msg.id.startsWith(OPTIMISTIC_PREFIX);
|
||||
return (
|
||||
<div
|
||||
key={msg.id}
|
||||
className={`flex ${isOwn ? "justify-end" : "justify-start"}`}
|
||||
>
|
||||
<div
|
||||
className={`max-w-[75%] rounded-2xl px-4 py-2.5 transition-opacity ${
|
||||
isOwn
|
||||
? "bg-neutral-900 text-white"
|
||||
: "bg-neutral-100 text-neutral-900"
|
||||
} ${isPending ? "opacity-60" : "opacity-100"}`}
|
||||
>
|
||||
{!isOwn && (
|
||||
<div className="mb-1 flex items-center gap-2">
|
||||
<Avatar
|
||||
name={msg.user?.name ?? "Unknown"}
|
||||
avatarUrl={msg.user?.avatar_url ?? null}
|
||||
size="md"
|
||||
/>
|
||||
<span className="text-xs font-semibold text-neutral-500">
|
||||
{msg.user?.name ?? "Unknown"}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<p className="text-sm whitespace-pre-wrap wrap-break-words">
|
||||
{msg.value}
|
||||
</p>
|
||||
<p className="mt-1 text-right text-[10px] text-neutral-400">
|
||||
{isPending ? "Sending..." : formatTime(msg.created_at)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<div ref={bottomRef} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Send bar */}
|
||||
<div className="border-t border-neutral-200 p-3">
|
||||
<form ref={formRef} action={handleAction} className="flex gap-2">
|
||||
<input
|
||||
name="message"
|
||||
type="text"
|
||||
placeholder="Type a message..."
|
||||
required
|
||||
autoComplete="off"
|
||||
className="flex-1 rounded-lg border border-neutral-300 bg-white px-3 py-2 text-sm text-neutral-900 shadow-sm placeholder:text-neutral-400 focus:border-neutral-900 focus:outline-none"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={pending}
|
||||
className="rounded-lg bg-neutral-900 px-4 py-2 text-sm font-medium text-white shadow-sm transition hover:bg-neutral-800 disabled:cursor-not-allowed disabled:bg-neutral-400"
|
||||
>
|
||||
{pending ? "Sending..." : "Send"}
|
||||
</button>
|
||||
</form>
|
||||
{state && "error" in state && (
|
||||
<p className="mt-2 text-xs text-red-600">{state.error}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<Image
|
||||
src={avatarUrl}
|
||||
alt=""
|
||||
width={200}
|
||||
height={200}
|
||||
className={`${sizeClass} shrink-0 rounded-full object-cover`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`flex ${sizeClass} shrink-0 items-center justify-center rounded-full bg-neutral-200 font-medium text-neutral-600 ${textSize}`}
|
||||
>
|
||||
{name.charAt(0).toUpperCase()}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
export default function RoomDetailLoading() {
|
||||
return (
|
||||
<div className="flex h-full flex-col">
|
||||
{/* Header skeleton */}
|
||||
<div className="flex items-center gap-3 border-b border-neutral-200 bg-white px-6 py-3">
|
||||
<div className="size-8 animate-pulse rounded-lg bg-neutral-200" />
|
||||
<div className="space-y-2">
|
||||
<div className="h-4 w-32 animate-pulse rounded bg-neutral-200" />
|
||||
<div className="h-3 w-20 animate-pulse rounded bg-neutral-200" />
|
||||
</div>
|
||||
</div>
|
||||
{/* Chat area skeleton */}
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<div className="size-8 animate-spin rounded-full border-2 border-neutral-300 border-t-neutral-900" />
|
||||
<p className="text-sm text-neutral-500">Loading room...</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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<string, MemberInfo> {
|
||||
const map = new Map<string, MemberInfo>();
|
||||
for (const m of members) {
|
||||
map.set(m.user_id, { name: m.name, avatar_url: m.avatar_url });
|
||||
}
|
||||
return map;
|
||||
}
|
||||
@@ -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 (
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold text-neutral-900">
|
||||
Members
|
||||
<span className="ml-2 text-xs font-normal text-neutral-500">
|
||||
{members.length}
|
||||
</span>
|
||||
</h2>
|
||||
<ul className="mt-3 divide-y divide-neutral-100 rounded-xl border border-neutral-200 bg-white">
|
||||
{members.map((member) => {
|
||||
const isSelf = member.user_id === currentUserId;
|
||||
|
||||
return (
|
||||
<li
|
||||
key={member.user_id}
|
||||
className="flex items-center gap-3 px-4 py-3"
|
||||
>
|
||||
{member.avatar_url ? (
|
||||
<Image
|
||||
src={member.avatar_url}
|
||||
alt=""
|
||||
width={200}
|
||||
height={200}
|
||||
className="size-8 rounded-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex size-8 items-center justify-center rounded-full bg-neutral-100 text-xs font-medium text-neutral-600">
|
||||
{member.name.charAt(0).toUpperCase()}
|
||||
</div>
|
||||
)}
|
||||
<span className="flex-1 text-sm font-medium text-neutral-900">
|
||||
{member.name}
|
||||
{isSelf && (
|
||||
<span className="ml-1.5 text-xs font-normal text-neutral-400">
|
||||
(you)
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
{!isSelf && onRemoveMember && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onRemoveMember(member.user_id)}
|
||||
disabled={disableActions}
|
||||
className="shrink-0 rounded-md px-2 py-1 text-xs text-neutral-400 transition hover:bg-red-50 hover:text-red-600 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
title={`Remove ${member.name}`}
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
className="size-4"
|
||||
>
|
||||
<path d="M6.28 5.22a.75.75 0 0 0-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 1 0 1.06 1.06L10 11.06l3.72 3.72a.75.75 0 1 0 1.06-1.06L11.06 10l3.72-3.72a.75.75 0 0 0-1.06-1.06L10 8.94 6.28 5.22Z" />
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<div className="flex h-full flex-col">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between border-b border-neutral-200 bg-white px-6 py-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<Link
|
||||
href="/rooms"
|
||||
className="flex size-8 items-center justify-center rounded-lg text-neutral-500 transition hover:bg-neutral-100 hover:text-neutral-900"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
className="size-5"
|
||||
>
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
d="M17 10a.75.75 0 0 1-.75.75H5.612l4.158 3.96a.75.75 0 0 1-1.04 1.08l-5.5-5.25a.75.75 0 0 1 0-1.08l5.5-5.25a.75.75 0 1 1 1.04 1.08L5.612 9.25H16.25A.75.75 0 0 1 17 10Z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
</Link>
|
||||
<div>
|
||||
<h1 className="text-base font-semibold text-neutral-900">
|
||||
{room.name}
|
||||
</h1>
|
||||
<p className="text-xs text-neutral-500">
|
||||
{members.length} {members.length === 1 ? "member" : "members"}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<RoomSettings roomId={id} members={members} currentUserId={user.id} />
|
||||
</div>
|
||||
|
||||
{/* Chat */}
|
||||
<div className="flex-1 overflow-hidden">
|
||||
<Chat
|
||||
roomId={id}
|
||||
initialMessages={messages}
|
||||
currentUserId={user.id}
|
||||
memberMap={buildMemberMap(members)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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<string | null>(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 (
|
||||
<div className="relative">
|
||||
<button
|
||||
onClick={() => setOpen(!open)}
|
||||
aria-label="Room settings"
|
||||
className="flex size-8 items-center justify-center rounded-lg text-neutral-500 transition hover:bg-neutral-100 hover:text-neutral-900"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
className="size-5"
|
||||
>
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
d="M2 4.75A.75.75 0 0 1 2.75 4h14.5a.75.75 0 0 1 0 1.5H2.75A.75.75 0 0 1 2 4.75ZM2 10a.75.75 0 0 1 .75-.75h14.5a.75.75 0 0 1 0 1.5H2.75A.75.75 0 0 1 2 10Zm0 5.25a.75.75 0 0 1 .75-.75h14.5a.75.75 0 0 1 0 1.5H2.75a.75.75 0 0 1-.75-.75Z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
{open && (
|
||||
<>
|
||||
{/* Backdrop */}
|
||||
<div className="fixed inset-0 z-40" onClick={() => setOpen(false)} />
|
||||
{/* Panel */}
|
||||
<div className="absolute right-0 top-full z-50 mt-2 w-80 rounded-xl border border-neutral-200 bg-white p-5 shadow-lg">
|
||||
<h2 className="text-sm font-semibold text-neutral-900">
|
||||
Room Settings
|
||||
</h2>
|
||||
|
||||
{removeError && (
|
||||
<p className="mt-2 text-xs text-red-600">{removeError}</p>
|
||||
)}
|
||||
|
||||
<div className="mt-4 space-y-5">
|
||||
<AddMemberForm roomId={roomId} />
|
||||
<MembersList
|
||||
members={members}
|
||||
currentUserId={currentUserId}
|
||||
onRemoveMember={handleRemoveMember}
|
||||
disableActions={isPending}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Danger zone */}
|
||||
<div className="mt-5 border-t border-neutral-100 pt-4">
|
||||
<button
|
||||
onClick={handleDeleteRoom}
|
||||
disabled={deleting}
|
||||
className="w-full rounded-lg border border-red-200 bg-white px-3 py-2 text-sm font-medium text-red-600 transition hover:bg-red-50 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
{deleting ? "Deleting..." : "Delete Room"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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<CreateRoomState> {
|
||||
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<AddMemberState> {
|
||||
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 };
|
||||
}
|
||||
@@ -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 (
|
||||
<form action={action} className="space-y-3">
|
||||
<label
|
||||
htmlFor="addMemberId"
|
||||
className="block text-sm font-medium text-neutral-700"
|
||||
>
|
||||
Add Member
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
id="addMemberId"
|
||||
name="userId"
|
||||
type="text"
|
||||
placeholder="User ID (UUID)"
|
||||
required
|
||||
className="flex-1 rounded-lg border border-neutral-300 bg-white px-3 py-2 text-sm text-neutral-900 shadow-sm placeholder:text-neutral-400 focus:border-neutral-900 focus:outline-none"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={pending}
|
||||
className="rounded-lg bg-neutral-900 px-4 py-2 text-sm font-medium text-white shadow-sm transition hover:bg-neutral-800 disabled:cursor-not-allowed disabled:bg-neutral-400"
|
||||
>
|
||||
{pending ? "Adding..." : "Add"}
|
||||
</button>
|
||||
</div>
|
||||
{state?.error && <p className="text-sm text-red-600">{state.error}</p>}
|
||||
{state?.success && (
|
||||
<p className="text-sm text-emerald-600">Member added!</p>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<form action={action} className="space-y-3">
|
||||
<label
|
||||
htmlFor="roomName"
|
||||
className="block text-sm font-medium text-neutral-700"
|
||||
>
|
||||
Create a Room
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
id="roomName"
|
||||
name="name"
|
||||
type="text"
|
||||
placeholder="Room name"
|
||||
required
|
||||
className="flex-1 rounded-lg border border-neutral-300 bg-white px-3 py-2 text-sm text-neutral-900 shadow-sm placeholder:text-neutral-400 focus:border-neutral-900 focus:outline-none"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={pending}
|
||||
className="rounded-lg bg-neutral-900 px-4 py-2 text-sm font-medium text-white shadow-sm transition hover:bg-neutral-800 disabled:cursor-not-allowed disabled:bg-neutral-400"
|
||||
>
|
||||
{pending ? "Creating..." : "Create"}
|
||||
</button>
|
||||
</div>
|
||||
{state?.error && <p className="text-sm text-red-600">{state.error}</p>}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<div className="mx-auto max-w-3xl px-6 py-10">
|
||||
<h1 className="text-2xl font-semibold text-neutral-900">Rooms</h1>
|
||||
<p className="mt-1 text-sm text-neutral-500">
|
||||
Your conversations will appear here.
|
||||
</p>
|
||||
|
||||
<div className="mt-8 space-y-8">
|
||||
{/* Create room */}
|
||||
<div className="rounded-xl border border-neutral-200 bg-white p-5 shadow-sm">
|
||||
<CreateRoomForm />
|
||||
</div>
|
||||
|
||||
{/* Rooms list */}
|
||||
<RoomsList rooms={rooms} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<div className="flex flex-col items-center rounded-xl border border-dashed border-neutral-300 py-12">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={1}
|
||||
className="size-10 text-neutral-300"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M7.5 8.25h9m-9 3H12m-9.75 1.51c0 1.6 1.123 2.994 2.707 3.227 1.087.16 2.185.283 3.293.369V21l4.076-4.076a1.526 1.526 0 0 1 1.037-.443 48.282 48.282 0 0 0 5.68-.494c1.584-.233 2.707-1.626 2.707-3.228V6.741c0-1.602-1.123-2.995-2.707-3.228A48.394 48.394 0 0 0 12 3c-2.392 0-4.744.175-7.043.513C3.373 3.746 2.25 5.14 2.25 6.741v6.018Z"
|
||||
/>
|
||||
</svg>
|
||||
<p className="mt-3 text-sm text-neutral-400">No rooms yet</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold text-neutral-900">
|
||||
Your Rooms
|
||||
<span className="ml-2 text-xs font-normal text-neutral-500">
|
||||
{rooms.length}
|
||||
</span>
|
||||
</h2>
|
||||
<ul className="mt-3 space-y-2">
|
||||
{rooms.map((room) => (
|
||||
<li key={room.id}>
|
||||
<Link
|
||||
href={`/rooms/${room.id}`}
|
||||
className="flex items-center justify-between rounded-xl border border-neutral-200 bg-white px-4 py-3 shadow-sm transition hover:border-neutral-300"
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-medium text-neutral-900">
|
||||
{room.name}
|
||||
</p>
|
||||
<p className="mt-0.5 text-xs text-neutral-500">
|
||||
{room.member_count}{" "}
|
||||
{room.member_count === 1 ? "member" : "members"}
|
||||
</p>
|
||||
</div>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
className="size-5 text-neutral-400"
|
||||
>
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
d="M8.22 5.22a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.75.75 0 0 1-1.06-1.06L11.94 10 8.22 6.28a.75.75 0 0 1 0-1.06Z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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: (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={1.5}
|
||||
className="size-5"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M7.5 8.25h9m-9 3H12m-9.75 1.51c0 1.6 1.123 2.994 2.707 3.227 1.087.16 2.185.283 3.293.369V21l4.076-4.076a1.526 1.526 0 0 1 1.037-.443 48.282 48.282 0 0 0 5.68-.494c1.584-.233 2.707-1.626 2.707-3.228V6.741c0-1.602-1.123-2.995-2.707-3.228A48.394 48.394 0 0 0 12 3c-2.392 0-4.744.175-7.043.513C3.373 3.746 2.25 5.14 2.25 6.741v6.018Z"
|
||||
/>
|
||||
</svg>
|
||||
),
|
||||
},
|
||||
{
|
||||
label: "Friends",
|
||||
href: "/friends",
|
||||
icon: (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={1.5}
|
||||
className="size-5"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M15 19.128a9.38 9.38 0 0 0 2.625.372 9.337 9.337 0 0 0 4.121-.952 4.125 4.125 0 0 0-7.533-2.493M15 19.128v-.003c0-1.113-.285-2.16-.786-3.07M15 19.128v.106A12.318 12.318 0 0 1 8.624 21c-2.331 0-4.512-.645-6.374-1.766l-.001-.109a6.375 6.375 0 0 1 11.964-3.07M12 6.375a3.375 3.375 0 1 1-6.75 0 3.375 3.375 0 0 1 6.75 0Zm8.25 2.25a2.625 2.625 0 1 1-5.25 0 2.625 2.625 0 0 1 5.25 0Z"
|
||||
/>
|
||||
</svg>
|
||||
),
|
||||
},
|
||||
{
|
||||
label: "Profile",
|
||||
href: "/profile",
|
||||
icon: (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={1.5}
|
||||
className="size-5"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M15.75 6a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0ZM4.501 20.118a7.5 7.5 0 0 1 14.998 0A17.933 17.933 0 0 1 12 21.75c-2.676 0-5.216-.584-7.499-1.632Z"
|
||||
/>
|
||||
</svg>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
export function Sidebar({
|
||||
displayName,
|
||||
email,
|
||||
avatarUrl,
|
||||
}: {
|
||||
displayName: string;
|
||||
email: string;
|
||||
avatarUrl: string;
|
||||
}) {
|
||||
const pathname = usePathname();
|
||||
return (
|
||||
<aside className="flex w-64 flex-col border-r border-neutral-200 bg-white">
|
||||
{/* Brand */}
|
||||
<div className="flex h-16 items-center gap-2 border-b border-neutral-200 px-6">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="currentColor"
|
||||
className="size-6 text-neutral-900"
|
||||
>
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
d="M4.848 2.771A49.144 49.144 0 0 1 12 2.25c2.43 0 4.817.178 7.152.52 1.978.292 3.348 2.024 3.348 3.97v6.02c0 1.946-1.37 3.678-3.348 3.97a48.901 48.901 0 0 1-3.476.383.39.39 0 0 0-.297.17l-2.755 4.133a.75.75 0 0 1-1.248 0l-2.755-4.133a.39.39 0 0 0-.297-.17 48.9 48.9 0 0 1-3.476-.384c-1.978-.29-3.348-2.024-3.348-3.97V6.741c0-1.946 1.37-3.68 3.348-3.97ZM6.75 8.25a.75.75 0 0 1 .75-.75h9a.75.75 0 0 1 0 1.5h-9a.75.75 0 0 1-.75-.75Zm.75 2.25a.75.75 0 0 0 0 1.5H12a.75.75 0 0 0 0-1.5H7.5Z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
<span className="text-lg font-semibold tracking-tight">Fastchat</span>
|
||||
</div>
|
||||
|
||||
{/* Navigation */}
|
||||
<nav aria-label="Main navigation" className="flex-1 space-y-1 px-3 py-4">
|
||||
{navItems.map((item) => {
|
||||
const active = pathname === item.href;
|
||||
return (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
className={`flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-colors ${
|
||||
active
|
||||
? "bg-neutral-100 text-neutral-900"
|
||||
: "text-neutral-600 hover:bg-neutral-50 hover:text-neutral-900"
|
||||
}`}
|
||||
>
|
||||
{item.icon}
|
||||
{item.label}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
|
||||
{/* User section */}
|
||||
<div className="border-t border-neutral-200 p-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex size-9 items-center justify-center rounded-full bg-neutral-900 text-sm font-medium text-white">
|
||||
<Image
|
||||
src={avatarUrl}
|
||||
alt=""
|
||||
width={200}
|
||||
height={200}
|
||||
className="size-9 rounded-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-sm font-medium text-neutral-900">
|
||||
{displayName}
|
||||
</p>
|
||||
<p className="truncate text-xs text-neutral-500">{email}</p>
|
||||
</div>
|
||||
</div>
|
||||
<form action={signOut}>
|
||||
<button
|
||||
type="submit"
|
||||
className="mt-3 flex w-full items-center gap-2 rounded-lg px-3 py-2 text-sm text-neutral-600 transition-colors hover:bg-neutral-50 hover:text-neutral-900"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={1.5}
|
||||
className="size-4"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M15.75 9V5.25A2.25 2.25 0 0 0 13.5 3h-6a2.25 2.25 0 0 0-2.25 2.25v13.5A2.25 2.25 0 0 0 7.5 21h6a2.25 2.25 0 0 0 2.25-2.25V15m3 0 3-3m0 0-3-3m3 3H9"
|
||||
/>
|
||||
</svg>
|
||||
Sign out
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -5,13 +5,6 @@
|
||||
--foreground: #171717;
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--font-sans: var(--font-geist-sans);
|
||||
--font-mono: var(--font-geist-mono);
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--background: #0a0a0a;
|
||||
|
||||
+2
-2
@@ -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({
|
||||
|
||||
@@ -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<LoginState> {
|
||||
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);
|
||||
}
|
||||
@@ -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 (
|
||||
<div className="w-full max-w-md space-y-6">
|
||||
<div className="space-y-1">
|
||||
<h1 className="text-2xl font-semibold">Log in</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Sign in to start chatting with your friends.
|
||||
</p>
|
||||
</div>
|
||||
<form action={action} className="space-y-4">
|
||||
{next && <input type="hidden" name="next" value={next} />}
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="email" className="text-sm font-medium">
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
required
|
||||
className="w-full rounded-md border border-neutral-300 bg-white px-3 py-2 text-sm text-neutral-900 shadow-sm focus:border-neutral-900 focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="password" className="text-sm font-medium">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
className="w-full rounded-md border border-neutral-300 bg-white px-3 py-2 text-sm text-neutral-900 shadow-sm focus:border-neutral-900 focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
{state?.error ? (
|
||||
<p className="text-sm text-red-600">{state.error}</p>
|
||||
) : null}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={pending}
|
||||
className="w-full rounded-md bg-neutral-900 px-4 py-2 text-sm font-medium text-white shadow-sm transition disabled:cursor-not-allowed disabled:bg-neutral-400"
|
||||
>
|
||||
{pending ? "Logging in..." : "Log in"}
|
||||
</button>
|
||||
</form>
|
||||
<p className="text-sm text-neutral-600">
|
||||
Don't have an account?{" "}
|
||||
<Link
|
||||
className="font-medium text-neutral-900 hover:underline"
|
||||
href="/register"
|
||||
>
|
||||
Register
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import LoginForm from "./login-form";
|
||||
|
||||
export default async function LoginPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ next?: string }>;
|
||||
}) {
|
||||
const { next } = await searchParams;
|
||||
return (
|
||||
<main className="flex min-h-screen items-center justify-center bg-neutral-50 px-6 py-12">
|
||||
<LoginForm next={next} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
+2
-99
@@ -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 (
|
||||
<div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-sans">
|
||||
<main className="flex flex-col gap-8 row-start-2 items-center sm:items-start">
|
||||
<Image
|
||||
className="dark:invert"
|
||||
src={changeBasePath("/next.svg")}
|
||||
alt="Next.js logo"
|
||||
width={180}
|
||||
height={38}
|
||||
priority
|
||||
/>
|
||||
<ol className="list-inside list-decimal text-sm text-center sm:text-left font-(family-name:--font-geist-mono)">
|
||||
<li className="mb-2">
|
||||
Get started by editing{" "}
|
||||
<code className="bg-black/0.5 dark:bg-white/6 px-1 py-0.5 rounded font-semibold">
|
||||
app/page.tsx
|
||||
</code>
|
||||
.
|
||||
</li>
|
||||
<li>Save and see your changes instantly.</li>
|
||||
</ol>
|
||||
|
||||
<div className="flex gap-4 items-center flex-col sm:flex-row">
|
||||
<a
|
||||
className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5"
|
||||
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Image
|
||||
className="dark:invert"
|
||||
src={changeBasePath("/vercel.svg")}
|
||||
alt="Vercel logomark"
|
||||
width={20}
|
||||
height={20}
|
||||
/>
|
||||
Deploy now
|
||||
</a>
|
||||
<a
|
||||
className="rounded-full border border-solid border-black/.08 dark:border-white/[.145] transition-colors flex items-center justify-center hover:bg-[#f2f2f2] dark:hover:bg-[#1a1a1a] hover:border-transparent text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 sm:min-w-44"
|
||||
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Read our docs
|
||||
</a>
|
||||
</div>
|
||||
</main>
|
||||
<footer className="row-start-3 flex gap-6 flex-wrap items-center justify-center">
|
||||
<a
|
||||
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
|
||||
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Image
|
||||
aria-hidden
|
||||
src={changeBasePath("/file.svg")}
|
||||
alt="File icon"
|
||||
width={16}
|
||||
height={16}
|
||||
/>
|
||||
Learn
|
||||
</a>
|
||||
<a
|
||||
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
|
||||
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Image
|
||||
aria-hidden
|
||||
src={changeBasePath("/window.svg")}
|
||||
alt="Window icon"
|
||||
width={16}
|
||||
height={16}
|
||||
/>
|
||||
Examples
|
||||
</a>
|
||||
<a
|
||||
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
|
||||
href="https://nextjs.org?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Image
|
||||
aria-hidden
|
||||
src={changeBasePath("/globe.svg")}
|
||||
alt="Globe icon"
|
||||
width={16}
|
||||
height={16}
|
||||
/>
|
||||
Go to nextjs.org →
|
||||
</a>
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
redirect("/profile");
|
||||
}
|
||||
@@ -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<RegisterState> {
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import RegisterForm from "./register-form";
|
||||
|
||||
export default function RegisterPage() {
|
||||
return (
|
||||
<main className="flex min-h-screen items-center justify-center bg-neutral-50 px-6 py-12">
|
||||
<RegisterForm />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<div className="w-full max-w-md space-y-6">
|
||||
<div className="space-y-1">
|
||||
<h1 className="text-2xl font-semibold">Create an account</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Sign up to start chatting with your friends.
|
||||
</p>
|
||||
</div>
|
||||
<form action={action} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="email" className="text-sm font-medium">
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
required
|
||||
className="w-full rounded-md border border-neutral-300 bg-white px-3 py-2 text-sm text-neutral-900 shadow-sm focus:border-neutral-900 focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="password" className="text-sm font-medium">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
required
|
||||
className="w-full rounded-md border border-neutral-300 bg-white px-3 py-2 text-sm text-neutral-900 shadow-sm focus:border-neutral-900 focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
{state?.error ? (
|
||||
<p className="text-sm text-red-600">{state.error}</p>
|
||||
) : null}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={pending}
|
||||
className="w-full rounded-md bg-neutral-900 px-4 py-2 text-sm font-medium text-white shadow-sm transition disabled:cursor-not-allowed disabled:bg-neutral-400"
|
||||
>
|
||||
{pending ? "Creating account..." : "Register"}
|
||||
</button>
|
||||
</form>
|
||||
<p className="text-sm text-neutral-600">
|
||||
Already have an account?{" "}
|
||||
<Link className="font-medium text-neutral-900 hover:underline" href="/login">
|
||||
Log in
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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=="],
|
||||
|
||||
@@ -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;
|
||||
@@ -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"
|
||||
},
|
||||
|
||||
@@ -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)$).*)",
|
||||
],
|
||||
};
|
||||
+2
-1
@@ -12,5 +12,6 @@ export interface Message {
|
||||
room_id: string;
|
||||
user: {
|
||||
name: string;
|
||||
};
|
||||
avatar_url: string | null;
|
||||
} | null;
|
||||
}
|
||||
+8
-2
@@ -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;
|
||||
}
|
||||
@@ -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<string | null> {
|
||||
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<Map<string, string | null>> {
|
||||
const result = new Map<string, string | null>();
|
||||
|
||||
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<string, string | null>();
|
||||
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;
|
||||
}
|
||||
@@ -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 === 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;
|
||||
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("/");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
const { data: saltData, error: saltError } = await supabase
|
||||
.from("users")
|
||||
.select("salt")
|
||||
.eq("id", (await supabase.auth.getUser()).data.user?.id)
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
throw error;
|
||||
if (saltError) {
|
||||
throw saltError;
|
||||
}
|
||||
|
||||
const salt = Uint8Array.from(atob(data.salt), (c) => c.charCodeAt(0));
|
||||
const salt = Uint8Array.from(atob(saltData.salt), (c) => c.charCodeAt(0));
|
||||
const key = await deriveKey(password, salt);
|
||||
storeAccessKey_Cookie(key);
|
||||
await storeAccessKey_Cookie(key);
|
||||
revalidatePath("/profile", "layout");
|
||||
redirect("/profile");
|
||||
}
|
||||
return { success: true };
|
||||
}
|
||||
+65
-65
@@ -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)
|
||||
// Look up both users' info
|
||||
const { data: users } = await supabase
|
||||
.from("users")
|
||||
.select("name, public_key_dec")
|
||||
.eq("id", receiver_id)
|
||||
.single();
|
||||
if (!friend) {
|
||||
return false;
|
||||
.select("id, name, public_key_dec")
|
||||
.in("id", [sender_id, receiver_id]);
|
||||
|
||||
if (!users || users.length < 2) {
|
||||
throw new Error("Could not find both users");
|
||||
}
|
||||
|
||||
const { error } = await (await supabase).from("friends").insert({
|
||||
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;
|
||||
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;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const remove_request = async (sender_id: string, receiver_id: string) => {
|
||||
const { data, error } = await (await supabase)
|
||||
// Remove the accepted request
|
||||
const { error: deleteError } = await supabase
|
||||
.from("friend_requests")
|
||||
.delete()
|
||||
.eq("sender_id", sender_id)
|
||||
.eq("receiver_id", receiver_id);
|
||||
if (error) {
|
||||
throw error;
|
||||
if (deleteError) {
|
||||
throw deleteError;
|
||||
}
|
||||
if (data) {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
add_user(sender_id, receiver_id);
|
||||
add_user(receiver_id, sender_id);
|
||||
remove_request(sender_id, receiver_id);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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" };
|
||||
}
|
||||
}
|
||||
@@ -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<string, number>();
|
||||
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 };
|
||||
}
|
||||
@@ -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 {
|
||||
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);
|
||||
} catch (err) {
|
||||
throw error.apply(err);
|
||||
}
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
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, [
|
||||
const key = await subtle.importKey("raw", key_raw, "AES-GCM", true, [
|
||||
"encrypt",
|
||||
"decrypt",
|
||||
]);
|
||||
return key;
|
||||
} catch (err) {
|
||||
return error.apply(err);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
"use server";
|
||||
import { subtle } from "crypto";
|
||||
|
||||
export async function deriveKey(passphrase: string, salt: Uint8Array) {
|
||||
|
||||
@@ -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<Uint8Array | null> {
|
||||
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<string> {
|
||||
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<Uint8Array | null> {
|
||||
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);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
Reference in new issue
Block a user