Implement E2EE and message content moderation

This commit is contained in:
Jamie Brunton committed 2026-01-02 20:49:11 +00:00
1 parent e1ff87dc03
commit 198cd80dfd
74 files changed
+12939 -2178

No files matched your search

@@ -0,0 +1,38 @@
import { decode, encode } from "https://deno.land/std@0.208.0/encoding/base64.ts";
export interface KeysMetadata {
sender_wrapped_key: string;
recipient_wrapped_key?: string;
admin_wrapped_key: string;
admin_key_id: string;
algorithm: string;
key_wrap_algorithm: string;
pending_recipient?: boolean;
}
export async function unwrapWithAdminKey(
wrappedKeyBase64: string,
adminPrivateKeyJwk: JsonWebKey
): Promise<ArrayBuffer> {
const privateKey = await crypto.subtle.importKey(
"jwk",
adminPrivateKeyJwk,
{ name: "RSA-OAEP", hash: "SHA-256" },
false,
["decrypt"]
);
return await crypto.subtle.decrypt(
{ name: "RSA-OAEP" },
privateKey,
base64ToUint8Array(wrappedKeyBase64)
);
}
export function base64ToUint8Array(base64: string): Uint8Array {
return decode(base64);
}
export function arrayBufferToBase64(buffer: ArrayBuffer): string {
return encode(buffer);
}
@@ -0,0 +1,190 @@
// @ts-nocheck
import "jsr:@supabase/functions-js/edge-runtime.d.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
import { decode } from "https://deno.land/std@0.208.0/encoding/base64.ts";
import { unwrapWithAdminKey, base64ToUint8Array, KeysMetadata } from "../_shared/encryption.ts";
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
"Access-Control-Allow-Methods": "POST, OPTIONS",
};
Deno.serve(async (req) => {
if (req.method === "OPTIONS") {
return new Response("ok", { headers: corsHeaders });
}
if (req.method !== "POST") {
return json({ error: "Method not allowed" }, 405);
}
try {
const supabaseAdmin = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!
);
const user = await getUserFromRequest(supabaseAdmin, req);
await assertSuperAdmin(supabaseAdmin, user.id);
const body = await req.json().catch(() => ({}));
const messageId = typeof body?.messageId === "string" ? body.messageId : null;
if (!messageId) {
return json({ error: "Missing messageId" }, 400);
}
const { data: message, error: messageError } = await supabaseAdmin
.from("messages")
.select(
"id, version, media_path, media_type, encryption_iv, keys_metadata"
)
.eq("id", messageId)
.single();
if (messageError || !message) {
return json({ error: "Message not found" }, 404);
}
const mediaPath = message.media_path as string | null;
const mediaType = message.media_type as ("image" | "video" | null);
const version = message.version ?? 1;
if (!mediaPath) {
return json({ error: "Message has no media" }, 400);
}
const normalizedPath = normalizeChatMediaPath(mediaPath);
const { data: mediaBlob, error: downloadError } = await supabaseAdmin.storage
.from("chat-media")
.download(normalizedPath);
if (downloadError || !mediaBlob) {
return json({ error: `Failed to download media: ${downloadError.message}` }, 500);
}
const encryptedBytes = await mediaBlob.arrayBuffer();
let outputBytes = encryptedBytes;
if (version === 2) {
const encryptionIv = message.encryption_iv as string | null;
const keysMetadata = message.keys_metadata as KeysMetadata | null;
if (!encryptionIv || !keysMetadata) {
return json({ error: "Missing encryption metadata" }, 400);
}
const adminPrivateKeyJwkStr = Deno.env.get("ADMIN_PRIVATE_KEY_JWK");
if (!adminPrivateKeyJwkStr) {
return json({ error: "Admin decryption key not configured" }, 500);
}
const rawAesKey = await unwrapWithAdminKey(
keysMetadata.admin_wrapped_key,
JSON.parse(adminPrivateKeyJwkStr)
);
const aesKey = await crypto.subtle.importKey(
"raw",
rawAesKey,
{ name: "AES-GCM" },
false,
["decrypt"]
);
outputBytes = await crypto.subtle.decrypt(
{ name: "AES-GCM", iv: base64ToUint8Array(encryptionIv) },
aesKey,
encryptedBytes
);
}
const contentType =
mediaType === "video" ? "video/mp4" : mediaType === "image" ? "image/jpeg" : "application/octet-stream";
return new Response(outputBytes, {
status: 200,
headers: {
...corsHeaders,
"Content-Type": contentType,
"Cache-Control": "no-store",
},
});
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
if (message.includes("authorization header") || message.startsWith("Invalid token")) {
return json({ error: "Unauthorized" }, 401);
}
if (message === "Access denied") {
return json({ error: "Forbidden" }, 403);
}
console.error("admin-decrypt-media error:", error);
return json({ error: "Internal server error" }, 500);
}
});
function json(body: unknown, status = 200) {
return new Response(JSON.stringify(body), {
status,
headers: {
...corsHeaders,
"Content-Type": "application/json",
"Cache-Control": "no-store",
},
});
}
async function getUserFromRequest(
supabaseAdmin: ReturnType<typeof createClient>,
req: Request
) {
const authHeader = req.headers.get("Authorization");
if (!authHeader) {
throw new Error("Missing authorization header");
}
const { data, error } = await supabaseAdmin.auth.getUser(
authHeader.replace("Bearer ", "")
);
if (error || !data.user) {
throw new Error(`Invalid token: ${error?.message || "No user"}`);
}
return data.user;
}
async function assertSuperAdmin(
supabaseAdmin: ReturnType<typeof createClient>,
userId: string
) {
const { data, error } = await supabaseAdmin
.from("admin_users")
.select("role")
.eq("user_id", userId)
.maybeSingle();
if (error || !data) {
throw new Error("Access denied");
}
if (data.role !== "super_admin") {
throw new Error("Access denied");
}
}
function normalizeChatMediaPath(mediaPath: string): string {
if (mediaPath.startsWith("http")) {
const parts = mediaPath.split("/chat-media/");
if (parts.length > 1) {
return decodeURIComponent(parts[1]);
}
}
return mediaPath;
}
@@ -0,0 +1,168 @@
// @ts-nocheck
import "jsr:@supabase/functions-js/edge-runtime.d.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
import { unwrapWithAdminKey, base64ToUint8Array, KeysMetadata } from "../_shared/encryption.ts";
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
"Access-Control-Allow-Methods": "POST, OPTIONS",
};
Deno.serve(async (req) => {
if (req.method === "OPTIONS") {
return new Response("ok", { headers: corsHeaders });
}
if (req.method !== "POST") {
return json({ error: "Method not allowed" }, 405);
}
try {
const supabaseAdmin = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!
);
const user = await getUserFromRequest(supabaseAdmin, req);
await assertSuperAdmin(supabaseAdmin, user.id);
const body = await req.json().catch(() => ({}));
const messageId = typeof body?.messageId === "string" ? body.messageId : null;
if (!messageId) {
return json({ error: "Missing messageId" }, 400);
}
const { data: message, error: messageError } = await supabaseAdmin
.from("messages")
.select(
"id, version, content, encrypted_content, encryption_iv, keys_metadata, media_path, media_type"
)
.eq("id", messageId)
.single();
if (messageError || !message) {
return json({ error: "Message not found" }, 404);
}
const version = message.version ?? 1;
if (version !== 2) {
return json({
version,
content: message.content ?? null,
media_path: message.media_path ?? null,
media_type: message.media_type ?? null,
});
}
const encryptedContent = message.encrypted_content as string | null;
const encryptionIv = message.encryption_iv as string | null;
const keysMetadata = message.keys_metadata as KeysMetadata | null;
let decryptedContent: string | null = null;
if (encryptedContent) {
if (!encryptionIv || !keysMetadata) {
return json({ error: "Missing encryption metadata" }, 400);
}
const adminPrivateKeyJwkStr = Deno.env.get("ADMIN_PRIVATE_KEY_JWK");
if (!adminPrivateKeyJwkStr) {
return json({ error: "Admin decryption key not configured" }, 500);
}
const rawAesKey = await unwrapWithAdminKey(
keysMetadata.admin_wrapped_key,
JSON.parse(adminPrivateKeyJwkStr)
);
const aesKey = await crypto.subtle.importKey(
"raw",
rawAesKey,
{ name: "AES-GCM" },
false,
["decrypt"]
);
const plaintext = await crypto.subtle.decrypt(
{ name: "AES-GCM", iv: base64ToUint8Array(encryptionIv) },
aesKey,
base64ToUint8Array(encryptedContent)
);
decryptedContent = new TextDecoder().decode(plaintext);
}
return json({
version,
content: decryptedContent,
media_path: message.media_path ?? null,
media_type: message.media_type ?? null,
});
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
if (message.includes("authorization header") || message.startsWith("Invalid token")) {
return json({ error: "Unauthorized" }, 401);
}
if (message === "Access denied") {
return json({ error: "Forbidden" }, 403);
}
console.error("admin-decrypt-message error:", error);
return json({ error: "Internal server error" }, 500);
}
});
function json(body: unknown, status = 200, extraHeaders: Record<string, string> = {}) {
return new Response(JSON.stringify(body), {
status,
headers: {
...corsHeaders,
"Content-Type": "application/json",
"Cache-Control": "no-store",
...extraHeaders,
},
});
}
async function getUserFromRequest(
supabaseAdmin: ReturnType<typeof createClient>,
req: Request
) {
const authHeader = req.headers.get("Authorization");
if (!authHeader) {
throw new Error("Missing authorization header");
}
const { data, error } = await supabaseAdmin.auth.getUser(
authHeader.replace("Bearer ", "")
);
if (error || !data.user) {
throw new Error(`Invalid token: ${error?.message || "No user"}`);
}
return data.user;
}
async function assertSuperAdmin(
supabaseAdmin: ReturnType<typeof createClient>,
userId: string
) {
const { data, error } = await supabaseAdmin
.from("admin_users")
.select("role")
.eq("user_id", userId)
.maybeSingle();
if (error || !data) {
throw new Error("Access denied");
}
if (data.role !== "super_admin") {
throw new Error("Access denied");
}
}
@@ -0,0 +1,228 @@
// @ts-nocheck
import "jsr:@supabase/functions-js/edge-runtime.d.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
import { unwrapWithAdminKey, base64ToUint8Array, arrayBufferToBase64, KeysMetadata } from "../_shared/encryption.ts";
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
"Access-Control-Allow-Methods": "POST, OPTIONS",
};
Deno.serve(async (req) => {
if (req.method === "OPTIONS") {
return new Response("ok", { headers: corsHeaders });
}
try {
const supabaseAdmin = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!
);
const body = await req.json().catch(() => ({}));
const messageId = body.messageId || body.message_id; // Support both cases
if (!messageId) {
return new Response(JSON.stringify({ error: "Missing message_id" }), { status: 400, headers: corsHeaders });
}
// 1. Fetch AI Config
const { data: config, error: configError } = await supabaseAdmin
.from("ai_config")
.select("*")
.single();
if (configError || !config) {
console.error("Failed to fetch AI config:", configError);
return new Response(JSON.stringify({ error: "Configuration missing" }), { status: 500, headers: corsHeaders });
}
if (!config.classifier_enabled) {
return new Response(JSON.stringify({ message: "Classifier disabled" }), { status: 200, headers: corsHeaders });
}
const apiKey = config.openrouter_api_key || Deno.env.get("OPENROUTER_API_KEY");
if (!apiKey) {
console.error("OpenRouter API Key missing");
return new Response(JSON.stringify({ error: "API Key missing" }), { status: 500, headers: corsHeaders });
}
// 2. Fetch Message
const { data: message, error: messageError } = await supabaseAdmin
.from("messages")
.select("id, version, content, encrypted_content, encryption_iv, keys_metadata, media_path, media_type")
.eq("id", messageId)
.single();
if (messageError || !message) {
return new Response(JSON.stringify({ error: "Message not found" }), { status: 404, headers: corsHeaders });
}
// 3. Decrypt Content
const version = message.version ?? 1;
let decryptedText = message.content;
let mediaBase64: string | null = null;
let mediaMimeType: string | null = null;
if (version === 2) {
const keysMetadata = message.keys_metadata as KeysMetadata;
const encryptionIv = message.encryption_iv;
if (!keysMetadata || !encryptionIv) {
return new Response(JSON.stringify({ error: "Missing encryption metadata" }), { status: 400, headers: corsHeaders });
}
const adminPrivateKeyJwkStr = Deno.env.get("ADMIN_PRIVATE_KEY_JWK");
if (!adminPrivateKeyJwkStr) {
throw new Error("ADMIN_PRIVATE_KEY_JWK not set");
}
const adminPrivateKey = JSON.parse(adminPrivateKeyJwkStr);
const rawAesKey = await unwrapWithAdminKey(keysMetadata.admin_wrapped_key, adminPrivateKey);
const aesKey = await crypto.subtle.importKey(
"raw",
rawAesKey,
{ name: "AES-GCM" },
false,
["decrypt"]
);
// Decrypt Text
if (message.encrypted_content) {
const plaintext = await crypto.subtle.decrypt(
{ name: "AES-GCM", iv: base64ToUint8Array(encryptionIv) },
aesKey,
base64ToUint8Array(message.encrypted_content)
);
decryptedText = new TextDecoder().decode(plaintext);
}
// Decrypt Media (Image only for now)
if (message.media_path && message.media_type === "image") {
const { data: mediaBlob, error: downloadError } = await supabaseAdmin.storage
.from("chat-media")
.download(normalizeChatMediaPath(message.media_path));
if (!downloadError && mediaBlob) {
const encryptedBytes = await mediaBlob.arrayBuffer();
const decryptedBytes = await crypto.subtle.decrypt(
{ name: "AES-GCM", iv: base64ToUint8Array(encryptionIv) },
aesKey,
encryptedBytes
);
mediaBase64 = arrayBufferToBase64(decryptedBytes);
mediaMimeType = "image/jpeg"; // Default or infer?
}
}
} else {
// Version 1 (Plaintext)
if (message.media_path && message.media_type === "image") {
const { data: mediaBlob } = await supabaseAdmin.storage
.from("chat-media")
.download(normalizeChatMediaPath(message.media_path));
if (mediaBlob) {
const buffer = await mediaBlob.arrayBuffer();
mediaBase64 = arrayBufferToBase64(buffer);
mediaMimeType = "image/jpeg";
}
}
}
// 4. Construct LLM Payload
const messages = [
{ role: "system", content: config.classifier_prompt },
{
role: "user",
content: [
decryptedText ? { type: "text", text: decryptedText } : null,
mediaBase64 ? {
type: "image_url",
image_url: { url: `data:${mediaMimeType};base64,${mediaBase64}` }
} : null
].filter(Boolean)
}
];
// If no content to classify, mark safe
if (messages[1].content.length === 0) {
await updateStatus(supabaseAdmin, messageId, "safe", "No content");
return new Response(JSON.stringify({ status: "safe" }), { headers: corsHeaders });
}
// 5. Call OpenRouter
const response = await fetch("https://openrouter.ai/api/v1/chat/completions", {
method: "POST",
headers: {
"Authorization": `Bearer ${apiKey}`,
"Content-Type": "application/json",
"HTTP-Referer": "https://sauci.app",
"X-Title": "Sauci"
},
body: JSON.stringify({
model: config.classifier_model || "openai/gpt-4o",
messages: messages,
response_format: { type: "json_object" }
})
});
if (!response.ok) {
const errText = await response.text();
console.error("OpenRouter Error:", errText);
throw new Error(`OpenRouter API Error: ${response.status}`);
}
const aiResult = await response.json();
const contentStr = aiResult.choices?.[0]?.message?.content;
if (!contentStr) {
throw new Error("Empty response from AI");
}
let classification;
try {
classification = JSON.parse(contentStr);
} catch (e) {
console.error("Failed to parse JSON:", contentStr);
// Fallback: simple text check
const lower = contentStr.toLowerCase();
if (lower.includes("flagged") || lower.includes("unsafe")) {
classification = { status: "flagged", reason: "AI output parsing failed, but keyword detected." };
} else {
classification = { status: "safe" };
}
}
// 6. Update Message
const status = classification.status === "flagged" ? "flagged" : "safe";
const reason = classification.reason || null;
const category = classification.category || "Neutral"; // Default to Neutral if missing
await updateStatus(supabaseAdmin, messageId, status, reason, category);
return new Response(JSON.stringify({ success: true, classification }), { headers: corsHeaders });
} catch (error) {
console.error("Classify Error:", error);
return new Response(JSON.stringify({ error: error.message }), { status: 500, headers: corsHeaders });
}
});
async function updateStatus(supabase, id, status, reason, category) {
await supabase.from("messages").update({
moderation_status: status,
flag_reason: reason,
category: category
}).eq("id", id);
}
function normalizeChatMediaPath(mediaPath: string): string {
if (mediaPath.startsWith("http")) {
const parts = mediaPath.split("/chat-media/");
if (parts.length > 1) {
return decodeURIComponent(parts[1]);
}
}
return mediaPath;
}
@@ -0,0 +1,315 @@
import "jsr:@supabase/functions-js/edge-runtime.d.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
};
// Only re-wrap messages from the last 7 days synchronously
// Older messages will be repaired on-demand via repair-stale-key
const RECENT_DAYS = 7;
const MAX_MESSAGES_PER_REQUEST = 500;
/**
* Handles key rotation when a user gets a new device.
*
* When a user's public key changes (detected via database trigger or called manually),
* this function re-wraps RECENT message AES keys with the user's new public key.
* Older messages are repaired on-demand when the user tries to view them.
* This prevents timeouts for couples with large message histories.
*/
Deno.serve(async (req) => {
// Handle CORS preflight
if (req.method === "OPTIONS") {
return new Response("ok", { headers: corsHeaders });
}
try {
const supabaseAdmin = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!
);
// Get user from JWT
const authHeader = req.headers.get("Authorization");
if (!authHeader) {
return new Response(
JSON.stringify({ error: "Missing authorization header" }),
{ status: 401, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
const { data: { user }, error: authError } = await supabaseAdmin.auth.getUser(
authHeader.replace("Bearer ", "")
);
if (authError || !user) {
return new Response(
JSON.stringify({ error: `Invalid token: ${authError?.message || 'No user found'}` }),
{ status: 401, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Get user's couple_id and new public key
const { data: profile, error: profileError } = await supabaseAdmin
.from("profiles")
.select("couple_id, public_key_jwk")
.eq("id", user.id)
.maybeSingle();
if (profileError || !profile) {
return new Response(
JSON.stringify({ error: "Profile not found" }),
{ status: 404, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
if (!profile.couple_id) {
return new Response(
JSON.stringify({ success: true, updated: 0, reason: "No couple" }),
{ headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
if (!profile.public_key_jwk) {
return new Response(
JSON.stringify({ error: "User has no public key" }),
{ status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Find all matches for this couple
const { data: matches } = await supabaseAdmin
.from("matches")
.select("id")
.eq("couple_id", profile.couple_id);
const matchIds = matches?.map(m => m.id) || [];
if (matchIds.length === 0) {
return new Response(
JSON.stringify({ success: true, updated: 0, reason: "No matches found" }),
{ headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Calculate cutoff date for recent messages
const recentCutoff = new Date(Date.now() - RECENT_DAYS * 24 * 60 * 60 * 1000);
// Find RECENT v2 messages in these matches (lazy re-encryption)
const { data: messages, error: messagesError } = await supabaseAdmin
.from("messages")
.select("id, user_id, keys_metadata, created_at")
.eq("version", 2)
.in("match_id", matchIds)
.gte("created_at", recentCutoff.toISOString())
.order("created_at", { ascending: false })
.limit(MAX_MESSAGES_PER_REQUEST);
if (messagesError) {
console.error("Error fetching messages:", messagesError);
return new Response(
JSON.stringify({ error: "Failed to fetch messages" }),
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Check if there are older messages that weren't processed
const { count: totalCount } = await supabaseAdmin
.from("messages")
.select("id", { count: "exact", head: true })
.eq("version", 2)
.in("match_id", matchIds);
const hasOlderMessages = (totalCount ?? 0) > (messages?.length ?? 0);
let updatedCount = 0;
let errorCount = 0;
for (const message of messages || []) {
const metadata = message.keys_metadata as {
sender_wrapped_key: string;
recipient_wrapped_key?: string;
admin_wrapped_key: string;
admin_key_id: string;
algorithm: string;
key_wrap_algorithm: string;
pending_recipient?: boolean;
};
const isSender = message.user_id === user.id;
try {
// Get admin private key - supports multi-key lookup
const adminPrivateKeyJwk = getAdminPrivateKey(metadata.admin_key_id);
if (!adminPrivateKeyJwk) {
console.error(`Admin key ${metadata.admin_key_id} not found for message ${message.id}`);
errorCount++;
continue;
}
// Unwrap AES key using admin key
const rawAesKey = await unwrapWithAdminKey(
metadata.admin_wrapped_key,
adminPrivateKeyJwk
);
// Re-wrap with new public key
const newWrappedKey = await wrapForRecipient(
rawAesKey,
profile.public_key_jwk
);
// Update the appropriate field based on whether user is sender or recipient
const updatedMetadata = { ...metadata };
if (isSender) {
updatedMetadata.sender_wrapped_key = newWrappedKey;
} else {
updatedMetadata.recipient_wrapped_key = newWrappedKey;
updatedMetadata.pending_recipient = false;
}
const { error: updateError } = await supabaseAdmin
.from("messages")
.update({ keys_metadata: updatedMetadata })
.eq("id", message.id);
if (updateError) {
console.error(`Failed to update message ${message.id}:`, updateError);
errorCount++;
} else {
updatedCount++;
}
} catch (err) {
console.error(`Failed to re-encrypt message ${message.id}:`, err);
errorCount++;
}
}
// Log the key rotation event for audit purposes
console.log(`Key rotation completed for user ${user.id}: ${updatedCount} messages updated, ${errorCount} errors, hasOlderMessages=${hasOlderMessages}`);
return new Response(
JSON.stringify({
success: true,
updated: updatedCount,
errors: errorCount,
has_older_messages: hasOlderMessages,
recent_days: RECENT_DAYS,
}),
{ headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
} catch (error) {
console.error("Error:", error);
return new Response(
JSON.stringify({ error: "Internal server error" }),
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
});
/**
* Get admin private key by ID.
* Supports multi-key format: ADMIN_KEYS_JSON = { "uuid1": {...}, "uuid2": {...} }
* Falls back to single-key format: ADMIN_PRIVATE_KEY_JWK = {...}
*/
function getAdminPrivateKey(keyId: string): JsonWebKey | null {
// Try multi-key format first
const keysJson = Deno.env.get("ADMIN_KEYS_JSON");
if (keysJson) {
try {
const keys = JSON.parse(keysJson);
if (keys[keyId]) {
return keys[keyId];
}
} catch {
console.error("Failed to parse ADMIN_KEYS_JSON");
}
}
// Fall back to single-key format
const singleKeyJson = Deno.env.get("ADMIN_PRIVATE_KEY_JWK");
if (singleKeyJson) {
try {
return JSON.parse(singleKeyJson);
} catch {
console.error("Failed to parse ADMIN_PRIVATE_KEY_JWK");
}
}
return null;
}
// Crypto helper functions
async function unwrapWithAdminKey(
wrappedKeyBase64: string,
adminPrivateKeyJwk: JsonWebKey
): Promise<ArrayBuffer> {
const privateKey = await crypto.subtle.importKey(
"jwk",
adminPrivateKeyJwk,
{ name: "RSA-OAEP", hash: "SHA-256" },
false,
["decrypt"]
);
const wrappedKey = base64ToArrayBuffer(wrappedKeyBase64);
return await crypto.subtle.decrypt(
{ name: "RSA-OAEP" },
privateKey,
wrappedKey
);
}
async function wrapForRecipient(
rawAesKey: ArrayBuffer,
recipientPublicKeyJwk: JsonWebKey
): Promise<string> {
// Sanitize JWK to ensure Base64URL encoding for n and e
const sanitizedJwk = { ...recipientPublicKeyJwk };
if (sanitizedJwk.n) {
sanitizedJwk.n = toBase64Url(sanitizedJwk.n);
}
if (sanitizedJwk.e) {
sanitizedJwk.e = toBase64Url(sanitizedJwk.e);
}
const publicKey = await crypto.subtle.importKey(
"jwk",
sanitizedJwk,
{ name: "RSA-OAEP", hash: "SHA-256" },
false,
["encrypt"]
);
const wrappedKey = await crypto.subtle.encrypt(
{ name: "RSA-OAEP" },
publicKey,
rawAesKey
);
return arrayBufferToBase64(wrappedKey);
}
function toBase64Url(base64: string): string {
return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
function base64ToArrayBuffer(base64: string): ArrayBuffer {
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes.buffer;
}
function arrayBufferToBase64(buffer: ArrayBuffer): string {
const bytes = new Uint8Array(buffer);
let binary = "";
for (let i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
@@ -0,0 +1,282 @@
import "jsr:@supabase/functions-js/edge-runtime.d.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
};
/**
* Re-encrypts pending messages when a partner generates their encryption keys.
*
* Called when a user uploads their public key and their partner already
* sent messages with pending_recipient = true.
*/
Deno.serve(async (req) => {
// Handle CORS preflight
if (req.method === "OPTIONS") {
return new Response("ok", { headers: corsHeaders });
}
try {
const supabaseAdmin = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!
);
// Get user from JWT
const authHeader = req.headers.get("Authorization");
if (!authHeader) {
return new Response(
JSON.stringify({ error: "Missing authorization header" }),
{ status: 401, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
const { data: { user }, error: authError } = await supabaseAdmin.auth.getUser(
authHeader.replace("Bearer ", "")
);
if (authError || !user) {
return new Response(
JSON.stringify({ error: `Invalid token: ${authError?.message || 'No user found'}` }),
{ status: 401, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Get user's couple_id and public key
const { data: profile, error: profileError } = await supabaseAdmin
.from("profiles")
.select("couple_id, public_key_jwk")
.eq("id", user.id)
.maybeSingle();
if (profileError || !profile) {
return new Response(
JSON.stringify({ error: "Profile not found" }),
{ status: 404, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
if (!profile.couple_id) {
return new Response(
JSON.stringify({ success: true, updated: 0, reason: "No couple" }),
{ headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
if (!profile.public_key_jwk) {
return new Response(
JSON.stringify({ error: "User has no public key" }),
{ status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Find matches for this couple
const { data: matches } = await supabaseAdmin
.from("matches")
.select("id")
.eq("couple_id", profile.couple_id);
const matchIds = matches?.map(m => m.id) || [];
if (matchIds.length === 0) {
return new Response(
JSON.stringify({ success: true, updated: 0, reason: "No matches found" }),
{ headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Find v2 messages where this user is the recipient but doesn't have their wrapped key yet
const { data: messages, error: messagesError } = await supabaseAdmin
.from("messages")
.select("id, user_id, keys_metadata")
.eq("version", 2)
.in("match_id", matchIds)
.neq("user_id", user.id); // Messages sent TO this user (they are recipient)
if (messagesError) {
console.error("Error fetching messages:", messagesError);
return new Response(
JSON.stringify({ error: "Failed to fetch messages" }),
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
let updatedCount = 0;
for (const message of messages || []) {
const metadata = message.keys_metadata as {
sender_wrapped_key: string;
recipient_wrapped_key?: string;
admin_wrapped_key: string;
admin_key_id: string;
algorithm: string;
key_wrap_algorithm: string;
pending_recipient?: boolean;
};
// Only process if pending_recipient OR missing recipient key
if (!metadata.pending_recipient && metadata.recipient_wrapped_key) {
continue;
}
try {
// Get admin private key - supports multi-key lookup
const adminPrivateKeyJwk = getAdminPrivateKey(metadata.admin_key_id);
if (!adminPrivateKeyJwk) {
console.error(`Admin key ${metadata.admin_key_id} not found for message ${message.id}`);
continue;
}
// Unwrap AES key using admin key
const rawAesKey = await unwrapWithAdminKey(
metadata.admin_wrapped_key,
adminPrivateKeyJwk
);
// Re-wrap for recipient
const recipientWrappedKey = await wrapForRecipient(
rawAesKey,
profile.public_key_jwk
);
// Update message
const { error: updateError } = await supabaseAdmin
.from("messages")
.update({
keys_metadata: {
...metadata,
recipient_wrapped_key: recipientWrappedKey,
pending_recipient: false,
}
})
.eq("id", message.id);
if (updateError) {
console.error(`Failed to update message ${message.id}:`, updateError);
} else {
updatedCount++;
}
} catch (err) {
console.error(`Failed to re-encrypt message ${message.id}:`, err);
}
}
return new Response(
JSON.stringify({ success: true, updated: updatedCount }),
{ headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
} catch (error) {
console.error("Error:", error);
return new Response(
JSON.stringify({ error: "Internal server error" }),
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
});
/**
* Get admin private key by ID.
* Supports multi-key format: ADMIN_KEYS_JSON = { "uuid1": {...}, "uuid2": {...} }
* Falls back to single-key format: ADMIN_PRIVATE_KEY_JWK = {...}
*/
function getAdminPrivateKey(keyId: string): JsonWebKey | null {
// Try multi-key format first
const keysJson = Deno.env.get("ADMIN_KEYS_JSON");
if (keysJson) {
try {
const keys = JSON.parse(keysJson);
if (keys[keyId]) {
return keys[keyId];
}
} catch {
console.error("Failed to parse ADMIN_KEYS_JSON");
}
}
// Fall back to single-key format
const singleKeyJson = Deno.env.get("ADMIN_PRIVATE_KEY_JWK");
if (singleKeyJson) {
try {
return JSON.parse(singleKeyJson);
} catch {
console.error("Failed to parse ADMIN_PRIVATE_KEY_JWK");
}
}
return null;
}
// Crypto helper functions
async function unwrapWithAdminKey(
wrappedKeyBase64: string,
adminPrivateKeyJwk: JsonWebKey
): Promise<ArrayBuffer> {
const privateKey = await crypto.subtle.importKey(
"jwk",
adminPrivateKeyJwk,
{ name: "RSA-OAEP", hash: "SHA-256" },
false,
["decrypt"]
);
const wrappedKey = base64ToArrayBuffer(wrappedKeyBase64);
return await crypto.subtle.decrypt(
{ name: "RSA-OAEP" },
privateKey,
wrappedKey
);
}
async function wrapForRecipient(
rawAesKey: ArrayBuffer,
recipientPublicKeyJwk: JsonWebKey
): Promise<string> {
// Sanitize JWK to ensure Base64URL encoding for n and e
const sanitizedJwk = { ...recipientPublicKeyJwk };
if (sanitizedJwk.n) {
sanitizedJwk.n = toBase64Url(sanitizedJwk.n);
}
if (sanitizedJwk.e) {
sanitizedJwk.e = toBase64Url(sanitizedJwk.e);
}
const publicKey = await crypto.subtle.importKey(
"jwk",
sanitizedJwk,
{ name: "RSA-OAEP", hash: "SHA-256" },
false,
["encrypt"]
);
const wrappedKey = await crypto.subtle.encrypt(
{ name: "RSA-OAEP" },
publicKey,
rawAesKey
);
return arrayBufferToBase64(wrappedKey);
}
function toBase64Url(base64: string): string {
return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
function base64ToArrayBuffer(base64: string): ArrayBuffer {
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes.buffer;
}
function arrayBufferToBase64(buffer: ArrayBuffer): string {
const bytes = new Uint8Array(buffer);
let binary = "";
for (let i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
@@ -0,0 +1,289 @@
import "jsr:@supabase/functions-js/edge-runtime.d.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
};
/**
* Repairs a message encrypted with a stale recipient key.
*
* When a message was encrypted while offline and the recipient's key changed
* before sync, the recipient can't decrypt. This function uses the admin key
* to re-wrap the AES key for the recipient's current public key.
*/
Deno.serve(async (req) => {
// Handle CORS preflight
if (req.method === "OPTIONS") {
return new Response("ok", { headers: corsHeaders });
}
try {
const supabaseAdmin = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!
);
// Get user from JWT
const authHeader = req.headers.get("Authorization");
if (!authHeader) {
return new Response(
JSON.stringify({ error: "Missing authorization header" }),
{ status: 401, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
const { data: { user }, error: authError } = await supabaseAdmin.auth.getUser(
authHeader.replace("Bearer ", "")
);
if (authError || !user) {
return new Response(
JSON.stringify({ error: `Invalid token: ${authError?.message || 'No user found'}` }),
{ status: 401, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Parse request body
const { message_id } = await req.json();
if (!message_id) {
return new Response(
JSON.stringify({ error: "Missing message_id" }),
{ status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Get user's current public key
const { data: profile, error: profileError } = await supabaseAdmin
.from("profiles")
.select("id, couple_id, public_key_jwk")
.eq("id", user.id)
.maybeSingle();
if (profileError || !profile) {
return new Response(
JSON.stringify({ error: "Profile not found" }),
{ status: 404, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
if (!profile.public_key_jwk) {
return new Response(
JSON.stringify({ error: "User has no public key" }),
{ status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Get the message
const { data: message, error: messageError } = await supabaseAdmin
.from("messages")
.select("id, user_id, match_id, version, keys_metadata")
.eq("id", message_id)
.maybeSingle();
if (messageError || !message) {
return new Response(
JSON.stringify({ error: "Message not found" }),
{ status: 404, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Verify this is a v2 message
if (message.version !== 2) {
return new Response(
JSON.stringify({ error: "Message is not encrypted (v1)" }),
{ status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Verify user has access to this message (via match -> couple)
const { data: match } = await supabaseAdmin
.from("matches")
.select("couple_id")
.eq("id", message.match_id)
.maybeSingle();
if (!match || match.couple_id !== profile.couple_id) {
return new Response(
JSON.stringify({ error: "Access denied" }),
{ status: 403, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Determine if user is sender or recipient
const isSender = message.user_id === user.id;
const metadata = message.keys_metadata as {
sender_wrapped_key: string;
recipient_wrapped_key?: string;
admin_wrapped_key: string;
admin_key_id: string;
algorithm: string;
key_wrap_algorithm: string;
pending_recipient?: boolean;
};
// Get admin private key - supports multi-key lookup
const adminPrivateKeyJwk = getAdminPrivateKey(metadata.admin_key_id);
if (!adminPrivateKeyJwk) {
return new Response(
JSON.stringify({ error: "Admin key not found for this message" }),
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Unwrap AES key using admin key
const rawAesKey = await unwrapWithAdminKey(
metadata.admin_wrapped_key,
adminPrivateKeyJwk
);
// Re-wrap with user's current public key
const newWrappedKey = await wrapForRecipient(
rawAesKey,
profile.public_key_jwk
);
// Update the appropriate field
const updatedMetadata = { ...metadata };
if (isSender) {
updatedMetadata.sender_wrapped_key = newWrappedKey;
} else {
updatedMetadata.recipient_wrapped_key = newWrappedKey;
updatedMetadata.pending_recipient = false;
}
const { error: updateError } = await supabaseAdmin
.from("messages")
.update({ keys_metadata: updatedMetadata })
.eq("id", message.id);
if (updateError) {
console.error(`Failed to update message ${message.id}:`, updateError);
return new Response(
JSON.stringify({ error: "Failed to update message" }),
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
console.log(`Repaired stale key for message ${message.id}, user ${user.id} (${isSender ? 'sender' : 'recipient'})`);
return new Response(
JSON.stringify({ success: true, message_id: message.id }),
{ headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
} catch (error) {
console.error("Error:", error);
return new Response(
JSON.stringify({ error: "Internal server error" }),
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
});
/**
* Get admin private key by ID.
* Supports multi-key format: ADMIN_KEYS_JSON = { "uuid1": {...}, "uuid2": {...} }
* Falls back to single-key format: ADMIN_PRIVATE_KEY_JWK = {...}
*/
function getAdminPrivateKey(keyId: string): JsonWebKey | null {
// Try multi-key format first
const keysJson = Deno.env.get("ADMIN_KEYS_JSON");
if (keysJson) {
try {
const keys = JSON.parse(keysJson);
if (keys[keyId]) {
return keys[keyId];
}
} catch {
console.error("Failed to parse ADMIN_KEYS_JSON");
}
}
// Fall back to single-key format
const singleKeyJson = Deno.env.get("ADMIN_PRIVATE_KEY_JWK");
if (singleKeyJson) {
try {
return JSON.parse(singleKeyJson);
} catch {
console.error("Failed to parse ADMIN_PRIVATE_KEY_JWK");
}
}
return null;
}
// Crypto helper functions
async function unwrapWithAdminKey(
wrappedKeyBase64: string,
adminPrivateKeyJwk: JsonWebKey
): Promise<ArrayBuffer> {
const privateKey = await crypto.subtle.importKey(
"jwk",
adminPrivateKeyJwk,
{ name: "RSA-OAEP", hash: "SHA-256" },
false,
["decrypt"]
);
const wrappedKey = base64ToArrayBuffer(wrappedKeyBase64);
return await crypto.subtle.decrypt(
{ name: "RSA-OAEP" },
privateKey,
wrappedKey
);
}
async function wrapForRecipient(
rawAesKey: ArrayBuffer,
recipientPublicKeyJwk: JsonWebKey
): Promise<string> {
// Sanitize JWK to ensure Base64URL encoding for n and e
const sanitizedJwk = { ...recipientPublicKeyJwk };
if (sanitizedJwk.n) {
sanitizedJwk.n = toBase64Url(sanitizedJwk.n);
}
if (sanitizedJwk.e) {
sanitizedJwk.e = toBase64Url(sanitizedJwk.e);
}
const publicKey = await crypto.subtle.importKey(
"jwk",
sanitizedJwk,
{ name: "RSA-OAEP", hash: "SHA-256" },
false,
["encrypt"]
);
const wrappedKey = await crypto.subtle.encrypt(
{ name: "RSA-OAEP" },
publicKey,
rawAesKey
);
return arrayBufferToBase64(wrappedKey);
}
function toBase64Url(base64: string): string {
return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
function base64ToArrayBuffer(base64: string): ArrayBuffer {
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes.buffer;
}
function arrayBufferToBase64(buffer: ArrayBuffer): string {
const bytes = new Uint8Array(buffer);
let binary = "";
for (let i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}