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:
pascalyazid committed 2026-05-11 21:35:28 +02:00
1 parent 508f17315e
commit 32e4bf8b32
58 files changed
+3270 -362

No files matched your search

+20 -30
View File
@@ -1,43 +1,33 @@
"use server";
import { error } from "console";
import { subtle } from "crypto";
import { cookies } from "next/headers";
export async function storeAccessKey_Cookie(key: CryptoKey) {
if (key.extractable) {
try {
const exported = await subtle.exportKey("raw", key);
const exportedKeyBuffer = new Uint8Array(exported);
const key_base64 = Buffer.from(exportedKeyBuffer).toString("base64");
(await cookies()).set("user_identity", key_base64);
} catch (err) {
throw error.apply(err);
}
} else {
return;
}
if (!key.extractable) return;
const exported = await subtle.exportKey("raw", key);
const exportedKeyBuffer = new Uint8Array(exported);
const key_base64 = Buffer.from(exportedKeyBuffer).toString("base64");
(await cookies()).set("user_identity", key_base64);
}
export async function removeAccessKey_Cookie() {
(await cookies()).set("user_identity", "");
(await cookies()).set("user_identity", "", { maxAge: 0 });
}
export async function retreiveAccessKey_Cookie() {
export async function retrieveAccessKey_Cookie() {
const cookieStore = await cookies();
try {
const key_base64 = cookieStore.get("user_identity");
if (key_base64 == null || key_base64.value.length < 1) {
return null;
}
const key_raw = Uint8Array.from(atob(key_base64.value), (c) =>
c.charCodeAt(0),
);
const key = subtle.importKey("raw", key_raw, "AES-GCM", true, [
"encrypt",
"decrypt",
]);
return key;
} catch (err) {
return error.apply(err);
const key_base64 = cookieStore.get("user_identity");
if (key_base64 == null || key_base64.value.length < 1) {
return null;
}
const key_raw = Uint8Array.from(atob(key_base64.value), (c) =>
c.charCodeAt(0),
);
const key = await subtle.importKey("raw", key_raw, "AES-GCM", true, [
"encrypt",
"decrypt",
]);
return key;
}
+2 -39
View File
@@ -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
View File
@@ -1,4 +1,3 @@
"use server";
import { subtle } from "crypto";
export async function deriveKey(passphrase: string, salt: Uint8Array) {
+162
View File
@@ -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);
}
+11 -9
View File
@@ -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;
}
}
}