Files
Fastchat/utils/security/room_crypto.ts
T

163 lines
4.0 KiB
TypeScript

import {
getRandomValues,
publicEncrypt,
privateDecrypt,
constants,
subtle,
} from "node: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, - 16).toString("base64");
const authTag = buf.slice(- 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);
}