Remove E2EE and switch to plaintext messaging

🤖 Generated with [Claude Code](https://claude.com/claude-code)
This commit is contained in:
jjbrunton committed 2026-01-08 18:04:48 +00:00
1 parent 43fa7033dc
commit c48936686e
46 files changed
+738 -6874

No files matched your search

@@ -1,315 +0,0 @@
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,355 @@
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",
};
/**
* Migration function to decrypt all E2EE v2 messages and convert to v1 plaintext.
*
* This is a one-time migration function that:
* 1. Fetches all messages with version = 2
* 2. Decrypts text content using admin key
* 3. Downloads, decrypts, and re-uploads encrypted media files
* 4. Updates messages to version = 1 with plaintext content
* 5. Clears E2EE metadata fields
*
* Requires super_admin authentication.
*/
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")!
);
// Authenticate and verify super_admin
const user = await getUserFromRequest(supabaseAdmin, req);
await assertSuperAdmin(supabaseAdmin, user.id);
// Parse options
const body = await req.json().catch(() => ({}));
const dryRun = body?.dryRun === true;
const batchSize = Math.min(body?.batchSize || 50, 100);
console.log(
`Starting E2EE migration (dryRun=${dryRun}, batchSize=${batchSize})`
);
// Fetch all v2 messages
const { data: messages, error: fetchError } = await supabaseAdmin
.from("messages")
.select(
"id, user_id, match_id, content, media_path, media_type, encrypted_content, encryption_iv, keys_metadata, created_at"
)
.eq("version", 2)
.order("created_at", { ascending: true })
.limit(batchSize);
if (fetchError) {
console.error("Failed to fetch messages:", fetchError);
return json({ error: "Failed to fetch messages" }, 500);
}
if (!messages || messages.length === 0) {
return json({
success: true,
message: "No v2 messages to migrate",
stats: { total: 0, text: 0, media: 0, errors: 0 },
});
}
// Get total count for progress tracking
const { count: totalRemaining } = await supabaseAdmin
.from("messages")
.select("id", { count: "exact", head: true })
.eq("version", 2);
const stats = {
total: messages.length,
text: 0,
media: 0,
errors: 0,
remaining: (totalRemaining ?? 0) - messages.length,
};
const errors: Array<{ id: string; error: string }> = [];
for (const message of messages) {
try {
const keysMetadata = message.keys_metadata as KeysMetadata | null;
const hasEncryptedContent = !!message.encrypted_content;
const hasEncryptedMedia =
message.media_path?.endsWith(".enc") ?? false;
// Get admin private key
const adminPrivateKeyJwk = getAdminPrivateKey(keysMetadata?.admin_key_id);
if (!adminPrivateKeyJwk && (hasEncryptedContent || hasEncryptedMedia)) {
throw new Error(
`Admin key ${keysMetadata?.admin_key_id} not configured`
);
}
let decryptedContent: string | null = null;
let newMediaPath: string | null = message.media_path;
// Decrypt text content
if (hasEncryptedContent && keysMetadata && adminPrivateKeyJwk) {
const encryptionIv = message.encryption_iv as string;
if (!encryptionIv) {
throw new Error("Missing encryption_iv for encrypted content");
}
const rawAesKey = await unwrapWithAdminKey(
keysMetadata.admin_wrapped_key,
adminPrivateKeyJwk
);
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(message.encrypted_content as string)
);
decryptedContent = new TextDecoder().decode(plaintext);
stats.text++;
}
// Decrypt and re-upload media
if (hasEncryptedMedia && keysMetadata && adminPrivateKeyJwk) {
const encryptionIv = message.encryption_iv as string;
if (!encryptionIv) {
throw new Error("Missing encryption_iv for encrypted media");
}
// Download encrypted file from storage
const { data: encryptedData, error: downloadError } =
await supabaseAdmin.storage
.from("chat-media")
.download(message.media_path);
if (downloadError || !encryptedData) {
throw new Error(`Failed to download encrypted media: ${downloadError?.message}`);
}
// Decrypt the media
const rawAesKey = await unwrapWithAdminKey(
keysMetadata.admin_wrapped_key,
adminPrivateKeyJwk
);
const aesKey = await crypto.subtle.importKey(
"raw",
rawAesKey,
{ name: "AES-GCM" },
false,
["decrypt"]
);
const encryptedBytes = await encryptedData.arrayBuffer();
const decryptedBytes = await crypto.subtle.decrypt(
{ name: "AES-GCM", iv: base64ToUint8Array(encryptionIv) },
aesKey,
encryptedBytes
);
// New path without .enc extension
newMediaPath = message.media_path.replace(/\.enc$/, "");
if (!dryRun) {
// Upload decrypted file
const { error: uploadError } = await supabaseAdmin.storage
.from("chat-media")
.upload(newMediaPath, decryptedBytes, {
contentType: getContentType(message.media_type),
upsert: true,
});
if (uploadError) {
throw new Error(`Failed to upload decrypted media: ${uploadError.message}`);
}
// Delete old encrypted file
await supabaseAdmin.storage
.from("chat-media")
.remove([message.media_path]);
}
stats.media++;
}
// Update message to v1
if (!dryRun) {
const updateData: Record<string, unknown> = {
version: 1,
content: decryptedContent ?? message.content,
media_path: newMediaPath,
encrypted_content: null,
encryption_iv: null,
keys_metadata: null,
};
const { error: updateError } = await supabaseAdmin
.from("messages")
.update(updateData)
.eq("id", message.id);
if (updateError) {
throw new Error(`Failed to update message: ${updateError.message}`);
}
}
console.log(
`${dryRun ? "[DRY RUN] " : ""}Migrated message ${message.id} (text=${hasEncryptedContent}, media=${hasEncryptedMedia})`
);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : String(err);
console.error(`Failed to migrate message ${message.id}:`, errorMessage);
errors.push({ id: message.id, error: errorMessage });
stats.errors++;
}
}
return json({
success: true,
dryRun,
stats,
errors: errors.length > 0 ? errors : undefined,
message:
stats.remaining > 0
? `Migrated ${stats.total - stats.errors}/${stats.total} messages. ${stats.remaining} remaining - run again to continue.`
: `Migration complete. ${stats.total - stats.errors}/${stats.total} messages migrated.`,
});
} 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("migrate-e2ee-to-plaintext 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, null, 2), {
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");
}
}
function getAdminPrivateKey(keyId?: string | null): JsonWebKey | null {
const keysJson = Deno.env.get("ADMIN_KEYS_JSON");
if (keysJson && keyId) {
try {
const keys = JSON.parse(keysJson);
if (keys[keyId]) {
return keys[keyId];
}
} catch {
console.error("Failed to parse ADMIN_KEYS_JSON");
}
}
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;
}
function getContentType(mediaType: string | null): string {
switch (mediaType) {
case "video":
return "video/mp4";
case "image":
return "image/jpeg";
default:
return "application/octet-stream";
}
}
@@ -1,282 +0,0 @@
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);
}
@@ -1,289 +0,0 @@
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);
}