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
+3270
-362
No files matched your search
@@ -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 };
|
||||
}
|
||||
Reference in new issue
Block a user