From c48936686ed9fb981539d32a38dd68c593f3ea9e Mon Sep 17 00:00:00 2001 From: Jamie Brunton Date: Thu, 8 Jan 2026 18:04:48 +0000 Subject: [PATCH] Remove E2EE and switch to plaintext messaging MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- CLAUDE.md | 37 - apps/admin/package.json | 8 +- .../src/components/content/PackFormDialog.tsx | 6 +- apps/admin/src/components/ui/icon-picker.tsx | 231 +++ apps/admin/src/lib/ai/generators/packs.ts | 3 +- .../src/pages/content/CategoriesPage.tsx | 16 +- apps/admin/src/pages/content/PacksPage.tsx | 15 +- apps/mobile/app.json | 4 +- apps/mobile/app/(app)/_layout.tsx | 40 +- apps/mobile/app/_layout.tsx | 2 - .../__tests__/components/InputBar.test.tsx | 25 - .../src/__tests__/lib/encryption.test.ts | 330 ---- .../components/EncryptionKeyInitializer.tsx | 206 --- apps/mobile/src/features/chat/ChatScreen.tsx | 118 +- .../src/features/chat/components/InputBar.tsx | 15 +- .../chat/components/MessageContent.tsx | 247 +-- .../src/features/chat/hooks/useMediaUpload.ts | 152 +- .../src/features/profile/ProfileScreen.tsx | 24 - .../profile/hooks/useCoupleManagement.ts | 2 - apps/mobile/src/hooks/index.ts | 4 - apps/mobile/src/hooks/useDecryptedMedia.ts | 486 ------ apps/mobile/src/hooks/useDecryptedMessage.ts | 466 ------ apps/mobile/src/hooks/useEncryptedSend.ts | 349 ---- apps/mobile/src/hooks/useEncryptionKeys.ts | 426 ----- apps/mobile/src/lib/encryption/adminKeys.ts | 88 - apps/mobile/src/lib/encryption/constants.ts | 30 - apps/mobile/src/lib/encryption/crypto.ts | 226 --- apps/mobile/src/lib/encryption/index.ts | 70 - apps/mobile/src/lib/encryption/keyManager.ts | 294 ---- .../src/lib/encryption/mediaDecryption.ts | 100 -- .../src/lib/encryption/mediaEncryption.ts | 82 - .../src/lib/encryption/messageDecryption.ts | 57 - .../src/lib/encryption/messageEncryption.ts | 67 - .../encryption/reencryptPendingMessages.ts | 77 - .../src/lib/encryption/repairStaleKey.ts | 82 - .../src/lib/encryption/triggerKeyRotation.ts | 102 -- apps/mobile/src/lib/encryption/types.ts | 133 -- apps/mobile/src/lib/encryption/utils.ts | 72 - apps/mobile/src/lib/mediaCache.ts | 22 - apps/mobile/src/lib/packIcons.ts | 72 +- apps/mobile/src/store/authStore.ts | 127 +- .../functions/handle-key-rotation/index.ts | 315 ---- .../migrate-e2ee-to-plaintext/index.ts | 355 ++++ .../reencrypt-pending-messages/index.ts | 282 ---- .../functions/repair-stale-key/index.ts | 289 ---- docs/e2ee-implementation.md | 1458 ----------------- 46 files changed, 738 insertions(+), 6874 deletions(-) create mode 100644 apps/admin/src/components/ui/icon-picker.tsx delete mode 100644 apps/mobile/src/__tests__/lib/encryption.test.ts delete mode 100644 apps/mobile/src/components/EncryptionKeyInitializer.tsx delete mode 100644 apps/mobile/src/hooks/useDecryptedMedia.ts delete mode 100644 apps/mobile/src/hooks/useDecryptedMessage.ts delete mode 100644 apps/mobile/src/hooks/useEncryptedSend.ts delete mode 100644 apps/mobile/src/hooks/useEncryptionKeys.ts delete mode 100644 apps/mobile/src/lib/encryption/adminKeys.ts delete mode 100644 apps/mobile/src/lib/encryption/constants.ts delete mode 100644 apps/mobile/src/lib/encryption/crypto.ts delete mode 100644 apps/mobile/src/lib/encryption/index.ts delete mode 100644 apps/mobile/src/lib/encryption/keyManager.ts delete mode 100644 apps/mobile/src/lib/encryption/mediaDecryption.ts delete mode 100644 apps/mobile/src/lib/encryption/mediaEncryption.ts delete mode 100644 apps/mobile/src/lib/encryption/messageDecryption.ts delete mode 100644 apps/mobile/src/lib/encryption/messageEncryption.ts delete mode 100644 apps/mobile/src/lib/encryption/reencryptPendingMessages.ts delete mode 100644 apps/mobile/src/lib/encryption/repairStaleKey.ts delete mode 100644 apps/mobile/src/lib/encryption/triggerKeyRotation.ts delete mode 100644 apps/mobile/src/lib/encryption/types.ts delete mode 100644 apps/mobile/src/lib/encryption/utils.ts delete mode 100644 apps/mobile/src/lib/mediaCache.ts delete mode 100644 apps/supabase/functions/handle-key-rotation/index.ts create mode 100644 apps/supabase/functions/migrate-e2ee-to-plaintext/index.ts delete mode 100644 apps/supabase/functions/reencrypt-pending-messages/index.ts delete mode 100644 apps/supabase/functions/repair-stale-key/index.ts delete mode 100644 docs/e2ee-implementation.md diff --git a/CLAUDE.md b/CLAUDE.md index 95442db..e029dc1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -179,40 +179,3 @@ backgroundColor: 'rgba(18, 18, 18, 0.85)', The `BlurView` in `tabBarBackground` is unreliable and can fail during re-renders/transitions, causing a fully transparent tab bar. The solid rgba background acts as a fallback while still allowing the blur effect on top. **Location:** `apps/mobile/app/(app)/_layout.tsx` - `tabBarStyle` - -## E2EE (End-to-End Encryption) Implementation - -Chat messages (text, images, videos) are encrypted client-side using AES-256-GCM with triple-wrapped RSA keys. - -### Architecture -- **Full documentation:** See `docs/e2ee-implementation.md` for complete details -- **Encryption library:** `apps/mobile/src/lib/encryption/` -- **React hooks:** `apps/mobile/src/hooks/useEncryptionKeys.ts`, `useDecryptedMessage.ts` -- **Edge functions:** `handle-key-rotation`, `reencrypt-pending-messages` - -### Key Concepts -1. **Message versions:** v1 = plaintext (legacy), v2 = E2EE -2. **Triple-wrapped keys:** Each message's AES key is RSA-encrypted for sender, recipient, and admin -3. **Device recovery:** When user gets new device, admin key re-wraps messages for new user key - -### Database Tables -- `messages.version` - Encryption version (1 or 2) -- `messages.encrypted_content` - Base64 ciphertext -- `messages.encryption_iv` - Base64 IV for AES-GCM -- `messages.keys_metadata` - JSONB with wrapped keys -- `profiles.public_key_jwk` - User's RSA public key -- `master_keys` - Admin RSA public keys - -### Setup Required -1. Run `node scripts/generate-admin-keys.mjs` to generate admin keypair -2. Insert public key into `master_keys` table -3. Store private key in `ADMIN_PRIVATE_KEY_JWK` environment variable for edge functions -4. Install crypto dependency: `npm install react-native-quick-crypto@^0.7.x` -5. Run `npx expo prebuild --clean` after installation - -### Edge Functions for E2EE -| Function | verify_jwt | Purpose | -|----------|------------|---------| -| `handle-key-rotation` | false | Re-wraps message keys when user gets new device | -| `reencrypt-pending-messages` | false | Wraps keys for recipient after they generate keys | - diff --git a/apps/admin/package.json b/apps/admin/package.json index 0512340..7efdf72 100755 --- a/apps/admin/package.json +++ b/apps/admin/package.json @@ -30,9 +30,11 @@ "emoji-mart": "^5.6.0", "lucide-react": "^0.309.0", "openai": "^4.24.0", - "react": "^18.2.0", - "react-dom": "^18.2.0", - "react-router-dom": "^6.21.0", + "react": "^18.2.0", + "react-dom": "^18.2.0", + "react-icons": "^4.12.0", + "react-router-dom": "^6.21.0", + "recharts": "^3.6.0", "sonner": "^1.3.1", "tailwind-merge": "^2.2.0" diff --git a/apps/admin/src/components/content/PackFormDialog.tsx b/apps/admin/src/components/content/PackFormDialog.tsx index 065b4a2..12c5a30 100644 --- a/apps/admin/src/components/content/PackFormDialog.tsx +++ b/apps/admin/src/components/content/PackFormDialog.tsx @@ -4,7 +4,7 @@ import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { Textarea } from '@/components/ui/textarea'; import { Switch } from '@/components/ui/switch'; -import { EmojiPicker } from '@/components/ui/emoji-picker'; +import { IconPicker } from '@/components/ui/icon-picker'; import { Badge } from '@/components/ui/badge'; import { Dialog, @@ -98,9 +98,9 @@ export function PackFormDialog({ {/* Icon */}
- setField('icon', emoji)} + onChange={(iconName) => setField('icon', iconName)} />
diff --git a/apps/admin/src/components/ui/icon-picker.tsx b/apps/admin/src/components/ui/icon-picker.tsx new file mode 100644 index 0000000..e3af52e --- /dev/null +++ b/apps/admin/src/components/ui/icon-picker.tsx @@ -0,0 +1,231 @@ +import { useEffect, useMemo, useRef, useState } from 'react'; +import type { IconType } from 'react-icons'; +import { + IoHeartOutline, + IoHeartHalfOutline, + IoHeartCircleOutline, + IoChatbubblesOutline, + IoChatboxOutline, + IoMailOutline, + IoFlowerOutline, + IoWineOutline, + IoRestaurantOutline, + IoCafeOutline, + IoAirplaneOutline, + IoCarOutline, + IoCompassOutline, + IoMapOutline, + IoHomeOutline, + IoPeopleOutline, + IoPersonOutline, + IoEyeOffOutline, + IoKeyOutline, + IoLockClosedOutline, + IoDiceOutline, + IoGiftOutline, + IoSparklesOutline, + IoStarOutline, + IoFlameOutline, + IoFlashOutline, + IoMoonOutline, + IoSunnyOutline, + IoFlagOutline, + IoCalendarOutline, + IoCheckboxOutline, + IoTrophyOutline, + IoLayersOutline, + IoCubeOutline, + IoFolderOutline, + IoBookmarkOutline, + IoBulbOutline, + IoColorWandOutline, + IoSyncOutline, + IoRefreshOutline, + IoBriefcaseOutline, +} from 'react-icons/io5'; +import { Button } from './button'; +import { Input } from './input'; + +interface IconOption { + name: string; + Icon: IconType; +} + +const ICON_OPTIONS: IconOption[] = [ + // Relationships & Love + { name: 'heart-outline', Icon: IoHeartOutline }, + { name: 'heart-half-outline', Icon: IoHeartHalfOutline }, + { name: 'heart-circle-outline', Icon: IoHeartCircleOutline }, + + // Communication + { name: 'chatbubbles-outline', Icon: IoChatbubblesOutline }, + { name: 'chatbox-outline', Icon: IoChatboxOutline }, + { name: 'mail-outline', Icon: IoMailOutline }, + + // Romance & Dates + { name: 'flower-outline', Icon: IoFlowerOutline }, + { name: 'wine-outline', Icon: IoWineOutline }, + { name: 'restaurant-outline', Icon: IoRestaurantOutline }, + { name: 'cafe-outline', Icon: IoCafeOutline }, + + // Adventure & Travel + { name: 'airplane-outline', Icon: IoAirplaneOutline }, + { name: 'car-outline', Icon: IoCarOutline }, + { name: 'compass-outline', Icon: IoCompassOutline }, + { name: 'map-outline', Icon: IoMapOutline }, + + // Home & Family + { name: 'home-outline', Icon: IoHomeOutline }, + { name: 'people-outline', Icon: IoPeopleOutline }, + { name: 'person-outline', Icon: IoPersonOutline }, + + // Mystery & Secrets + { name: 'eye-off-outline', Icon: IoEyeOffOutline }, + { name: 'key-outline', Icon: IoKeyOutline }, + { name: 'lock-closed-outline', Icon: IoLockClosedOutline }, + + // Fun & Games + { name: 'dice-outline', Icon: IoDiceOutline }, + { name: 'gift-outline', Icon: IoGiftOutline }, + { name: 'sparkles-outline', Icon: IoSparklesOutline }, + { name: 'star-outline', Icon: IoStarOutline }, + + // Intimacy + { name: 'flame-outline', Icon: IoFlameOutline }, + { name: 'flash-outline', Icon: IoFlashOutline }, + { name: 'moon-outline', Icon: IoMoonOutline }, + { name: 'sunny-outline', Icon: IoSunnyOutline }, + + // Goals & Planning + { name: 'flag-outline', Icon: IoFlagOutline }, + { name: 'calendar-outline', Icon: IoCalendarOutline }, + { name: 'checkbox-outline', Icon: IoCheckboxOutline }, + { name: 'trophy-outline', Icon: IoTrophyOutline }, + + // General + { name: 'layers-outline', Icon: IoLayersOutline }, + { name: 'cube-outline', Icon: IoCubeOutline }, + { name: 'folder-outline', Icon: IoFolderOutline }, + { name: 'bookmark-outline', Icon: IoBookmarkOutline }, + { name: 'bulb-outline', Icon: IoBulbOutline }, + { name: 'color-wand-outline', Icon: IoColorWandOutline }, + { name: 'sync-outline', Icon: IoSyncOutline }, + { name: 'refresh-outline', Icon: IoRefreshOutline }, + { name: 'briefcase-outline', Icon: IoBriefcaseOutline }, +]; + +const ICONS_BY_NAME = ICON_OPTIONS.reduce>((acc, option) => { + acc[option.name] = option; + return acc; +}, {}); + +interface IconPreviewProps { + value?: string | null; + fallback?: string; + className?: string; +} + +export function IconPreview({ value, fallback = '?', className }: IconPreviewProps) { + const resolved = value ?? fallback; + const Icon = resolved ? ICONS_BY_NAME[resolved]?.Icon : undefined; + + if (Icon) { + return ; + } + + return {resolved}; +} + +interface IconPickerProps { + value: string; + onChange: (iconName: string) => void; +} + +export function IconPicker({ value, onChange }: IconPickerProps) { + const [open, setOpen] = useState(false); + const [query, setQuery] = useState(''); + const containerRef = useRef(null); + + useEffect(() => { + function handleClickOutside(event: MouseEvent) { + if (containerRef.current && !containerRef.current.contains(event.target as Node)) { + setOpen(false); + } + } + + if (open) { + document.addEventListener('mousedown', handleClickOutside); + } + + return () => { + document.removeEventListener('mousedown', handleClickOutside); + }; + }, [open]); + + const filteredIcons = useMemo(() => { + const normalized = query.trim().toLowerCase(); + if (!normalized) return ICON_OPTIONS; + return ICON_OPTIONS.filter((option) => option.name.includes(normalized)); + }, [query]); + + const SelectedIcon = ICONS_BY_NAME[value]?.Icon; + const buttonLabel = SelectedIcon ? value : value ? 'Legacy icon' : 'Select an icon'; + + return ( +
+ + {open && ( +
+ setQuery(event.target.value)} + placeholder="Search icons..." + className="mb-3" + /> +
+ {filteredIcons.map(({ name, Icon }) => { + const isSelected = name === value; + return ( + + ); + })} + {filteredIcons.length === 0 && ( +
+ No icons found +
+ )} +
+
+ )} +
+ ); +} diff --git a/apps/admin/src/lib/ai/generators/packs.ts b/apps/admin/src/lib/ai/generators/packs.ts index bb52d26..77b62b2 100644 --- a/apps/admin/src/lib/ai/generators/packs.ts +++ b/apps/admin/src/lib/ai/generators/packs.ts @@ -144,7 +144,8 @@ ${explicitInstruction}${crudeLangInstruction}${inspirationInstruction}${avoidIns Return a JSON object with an "ideas" array containing 5 objects, where each object has: - name: Pack name (catchy, 3-6 words) - should evoke activities/experiences, not questions - description: Brief description (1-2 sentences) focusing on the activities/experiences in the pack -- icon: A single descriptive emoji + - icon: An Ionicon name from this list: heart-outline, flame-outline, sparkles-outline, gift-outline, wine-outline, airplane-outline, home-outline, key-outline, flash-outline, sunny-outline, flower-outline, star-outline, dice-outline, compass-outline, bulb-outline + Make them engaging and specific to "${categoryName}".`; diff --git a/apps/admin/src/pages/content/CategoriesPage.tsx b/apps/admin/src/pages/content/CategoriesPage.tsx index d09b140..cb7e1e1 100644 --- a/apps/admin/src/pages/content/CategoriesPage.tsx +++ b/apps/admin/src/pages/content/CategoriesPage.tsx @@ -8,7 +8,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/com import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { Textarea } from '@/components/ui/textarea'; -import { EmojiPicker } from '@/components/ui/emoji-picker'; +import { IconPicker, IconPreview } from '@/components/ui/icon-picker'; import { Skeleton } from '@/components/ui/skeleton'; import { Dialog, @@ -56,11 +56,11 @@ export function CategoriesPage() { // Form state using the new hook const form = useEntityForm( - { name: '', description: '', icon: '📚' }, + { name: '', description: '', icon: 'bookmark-outline' }, (category) => ({ name: category.name, description: category.description || '', - icon: category.icon || '📚', + icon: category.icon || 'bookmark-outline', }) ); @@ -118,7 +118,7 @@ export function CategoriesPage() { form.openCreateWith({ name: idea.name, description: idea.description || '', - icon: idea.icon || '📚', + icon: idea.icon || 'bookmark-outline', }); }; @@ -261,9 +261,9 @@ export function CategoriesPage() {
- form.setField('icon', emoji)} + onChange={(iconName) => form.setField('icon', iconName)} />
@@ -363,7 +363,9 @@ export function CategoriesPage() {
-
{category.icon || '📚'}
+
+ +
-
{pack.icon || '💕'}
+
+ +
{pack.is_premium && ( diff --git a/apps/mobile/app.json b/apps/mobile/app.json index 1c14d1a..51a128b 100644 --- a/apps/mobile/app.json +++ b/apps/mobile/app.json @@ -23,8 +23,8 @@ "remote-notification" ], "NSFaceIDUsageDescription": "Sauci uses Face ID to unlock the app and keep your conversations private.", - "NSCameraUsageDescription": "Sauci uses your camera to take photos and videos that you can share privately with your partner in encrypted chat messages.", - "NSPhotoLibraryUsageDescription": "Sauci uses your photo library so you can select photos and videos to share privately with your partner in encrypted chat messages.", + "NSCameraUsageDescription": "Sauci uses your camera to take photos and videos that you can share privately with your partner.", + "NSPhotoLibraryUsageDescription": "Sauci uses your photo library so you can select photos and videos to share privately with your partner.", "NSPhotoLibraryAddUsageDescription": "Sauci saves photos and videos from your partner's messages to your photo library when you tap the save button.", "NSMicrophoneUsageDescription": "Sauci uses your microphone to record audio when you capture videos to share privately with your partner." }, diff --git a/apps/mobile/app/(app)/_layout.tsx b/apps/mobile/app/(app)/_layout.tsx index 07937a0..b6cc745 100755 --- a/apps/mobile/app/(app)/_layout.tsx +++ b/apps/mobile/app/(app)/_layout.tsx @@ -5,8 +5,6 @@ import { BlurView } from "expo-blur"; import { LinearGradient } from "expo-linear-gradient"; import { useEffect, useState, useCallback, useRef } from "react"; import { useAuthStore, useMatchStore, useMessageStore, useSubscriptionStore, usePacksStore } from "../../src/store"; -import { useDecryptedMessage } from "../../src/hooks"; -import type { KeysMetadata } from "../../src/lib/encryption"; import { colors, gradients, blur, radius, spacing, typography, shadows } from "../../src/theme"; import { supabase } from "../../src/lib/supabase"; import { isBiometricEnabled } from "../../src/lib/biometricAuth"; @@ -20,10 +18,8 @@ type Message = Database["public"]["Tables"]["messages"]["Row"]; function MessageToastPreview({ message, - currentUserId, }: { message: Message; - currentUserId: string; }) { if (message.media_path) { const fallback = message.media_type === 'video' ? 'Sent a video' : 'Sent an image'; @@ -34,41 +30,9 @@ function MessageToastPreview({ ); } - const version = message.version ?? 1; - const isV2 = version === 2; - - const { content, isDecrypting, error } = useDecryptedMessage({ - message: { - id: message.id, - content: message.content, - version, - encrypted_content: message.encrypted_content, - encryption_iv: message.encryption_iv, - keys_metadata: message.keys_metadata as unknown as KeysMetadata | null, - user_id: message.user_id, - }, - currentUserId, - }); - - if (isDecrypting) { - return ( - - Waiting for message... - - ); - } - - if (error) { - return ( - - Encrypted message - - ); - } - return ( - {content ?? (!isV2 ? message.content : null) ?? 'New message'} + {message.content ?? 'New message'} ); } @@ -886,7 +850,7 @@ export default function AppLayout() { New message - + diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx index 2ad7fc2..5dfc605 100755 --- a/apps/mobile/app/_layout.tsx +++ b/apps/mobile/app/_layout.tsx @@ -48,7 +48,6 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import * as Linking from "expo-linking"; import { useAuthStore } from "../src/store"; import { supabase } from "../src/lib/supabase"; -import { EncryptionKeyInitializer } from "../src/components/EncryptionKeyInitializer"; const queryClient = new QueryClient(); @@ -213,7 +212,6 @@ export default function RootLayout() { - { { { { { expect(onSend).toHaveBeenCalledTimes(1); }); - it('disables send when secure messaging is not ready', () => { - const onSend = jest.fn(); - - const { getByTestId } = render( - - ); - - fireEvent.press(getByTestId('chat-input-send')); - expect(onSend).not.toHaveBeenCalled(); - }); - it('calls media actions from menu buttons', () => { const onPickMedia = jest.fn(); const onTakePhoto = jest.fn(); @@ -105,7 +81,6 @@ describe('InputBar', () => { { - let store: Record = {}; - return { - setItemAsync: jest.fn(async (key, value) => { - store[key] = value; - }), - getItemAsync: jest.fn(async (key) => { - return store[key] || null; - }), - deleteItemAsync: jest.fn(async (key) => { - delete store[key]; - }), - _clear: () => { - store = {}; - }, - }; -}); - -jest.mock('react-native', () => ({ - Platform: { - OS: 'ios', // Mock as native platform to allow key generation - }, -})); - -// Mock react-native-quick-crypto's polyfill behavior if needed, -// but Node.js 20+ has global.crypto.subtle. -// If tests fail due to missing crypto, we will need to polyfill it. -if (!global.crypto) { - // @ts-ignore - global.crypto = require('crypto').webcrypto; -} - -describe('E2EE Encryption Library', () => { - // 1. Low-Level Crypto Primitives - describe('Crypto Primitives (AES-GCM)', () => { - it('should generate a valid AES-256 key', async () => { - const key = await generateAESKey(); - expect(key.algorithm.name).toBe('AES-GCM'); - // @ts-ignore - length is present in Web Crypto keys - expect(key.algorithm.length).toBe(256); - expect(key.extractable).toBe(true); - }); - - it('should generate a valid 12-byte IV', () => { - const iv = generateIV(); - expect(iv.length).toBe(12); - expect(iv).toBeInstanceOf(Uint8Array); - }); - - it('should correctly round-trip AES encryption/decryption', async () => { - const plaintext = 'Hello, Secret World!'; - const key = await generateAESKey(); - const iv = generateIV(); - - const ciphertext = await encryptAES(plaintext, key, iv); - const decryptedBuffer = await decryptAES(ciphertext, key, iv); - const decryptedText = new TextDecoder().decode(decryptedBuffer); - - expect(decryptedText).toBe(plaintext); - }); - - it('should export and import AES keys correctly', async () => { - const originalKey = await generateAESKey(); - const rawKey = await exportAESKey(originalKey); - - expect(rawKey.byteLength).toBe(32); // 256 bits = 32 bytes - - const importedKey = await importAESKey(rawKey); - - expect(importedKey.algorithm.name).toBe('AES-GCM'); - // @ts-ignore - expect(importedKey.algorithm.length).toBe(256); - }); - }); - - // 2. RSA Key Wrapping - describe('RSA Key Wrapping', () => { - let aliceKeyPair: CryptoKeyPair; - let alicePublicKeyJwk: RSAPublicKeyJWK; - let alicePrivateKeyJwk: RSAPrivateKeyJWK; - - beforeAll(async () => { - // Generate a real keypair for testing using Web Crypto directly - // simulating what generateAndStoreKeyPair does internally - aliceKeyPair = await crypto.subtle.generateKey( - { - name: 'RSA-OAEP', - modulusLength: 2048, - publicExponent: new Uint8Array([1, 0, 1]), - hash: 'SHA-256', - }, - true, - ['encrypt', 'decrypt'] - ); - - alicePublicKeyJwk = (await crypto.subtle.exportKey('jwk', aliceKeyPair.publicKey)) as RSAPublicKeyJWK; - alicePrivateKeyJwk = (await crypto.subtle.exportKey('jwk', aliceKeyPair.privateKey)) as RSAPrivateKeyJWK; - }); - - it('should wrap and unwrap an AES key using RSA keys', async () => { - const aesKey = await generateAESKey(); - const rawAesKey = await exportAESKey(aesKey); - - // Wrap with Public Key - const wrappedKeyBase64 = await wrapAESKey(rawAesKey, alicePublicKeyJwk); - expect(typeof wrappedKeyBase64).toBe('string'); - - // Unwrap with Private Key - const unwrappedRawKey = await unwrapAESKey(wrappedKeyBase64, alicePrivateKeyJwk); - - // Compare bytes - const originalBytes = new Uint8Array(rawAesKey); - const unwrappedBytes = new Uint8Array(unwrappedRawKey); - expect(unwrappedBytes).toEqual(originalBytes); - }); - - it('should verify matching key pairs', async () => { - const isMatch = await verifyKeyPair(alicePublicKeyJwk, alicePrivateKeyJwk); - expect(isMatch).toBe(true); - }); - - it('should reject mismatched key pairs', async () => { - // Suppress expected console error - const originalError = console.error; - console.error = jest.fn(); - - try { - // Generate a second, different keypair - const bobKeyPair = await crypto.subtle.generateKey( - { - name: 'RSA-OAEP', - modulusLength: 2048, - publicExponent: new Uint8Array([1, 0, 1]), - hash: 'SHA-256', - }, - true, - ['encrypt', 'decrypt'] - ); - const bobPrivateKeyJwk = (await crypto.subtle.exportKey('jwk', bobKeyPair.privateKey)) as RSAPrivateKeyJWK; - - // Check mismatch (Alice's Public + Bob's Private) - const isMatch = await verifyKeyPair(alicePublicKeyJwk, bobPrivateKeyJwk); - expect(isMatch).toBe(false); - } finally { - // Restore console error - console.error = originalError; - } - }); - }); - - // 3. Key Manager (with mocked SecureStore) - describe('Key Manager', () => { - beforeEach(() => { - // Clear mocked store - require('expo-secure-store')._clear(); - }); - - it('should generate and store keys correctly', async () => { - const publicKey = await generateAndStoreKeyPair(); - - expect(publicKey.kty).toBe('RSA'); - expect(publicKey.alg).toBe('RSA-OAEP-256'); - - // Check SecureStore interaction - const storedPrivateKey = await getPrivateKey(); - expect(storedPrivateKey).toBeDefined(); - expect(storedPrivateKey?.d).toBeDefined(); // 'd' is the private exponent - - // Verify they match - const isMatch = await verifyKeyPair(publicKey, storedPrivateKey!); - expect(isMatch).toBe(true); - }); - - it('should clear keys', async () => { - await generateAndStoreKeyPair(); - await clearKeys(); - - const storedPrivateKey = await getPrivateKey(); - expect(storedPrivateKey).toBeNull(); - }); - - it('should validate and sanitize public keys', () => { - // Valid key - const validKey: RSAPublicKeyJWK = { - kty: 'RSA', - n: 'some_base64_string', - e: 'AQAB', - alg: 'RSA-OAEP-256' - }; - expect(isValidPublicKeyJwk(validKey)).toBe(true); - - // Invalid key (missing fields) - expect(isValidPublicKeyJwk({} as any)).toBe(false); - - // Key with trailing dots (sanitization test) - const dirtyKey: RSAPublicKeyJWK = { - ...validKey, - n: 'some_base64_string...', - e: 'AQAB.' - }; - - const cleanKey = sanitizePublicKeyJwk(dirtyKey); - expect(cleanKey.n).toBe('some_base64_string'); - expect(cleanKey.e).toBe('AQAB'); - expect(isValidPublicKeyJwk(dirtyKey)).toBe(true); // Should pass because it sanitizes internally - }); - }); - - // 4. High-Level Message Flow (Alice -> Bob) - describe('Full Message Flow (Alice -> Bob)', () => { - let aliceKeys: { pub: RSAPublicKeyJWK, priv: RSAPrivateKeyJWK }; - let bobKeys: { pub: RSAPublicKeyJWK, priv: RSAPrivateKeyJWK }; - let adminKeys: { pub: RSAPublicKeyJWK, priv: RSAPrivateKeyJWK }; - - beforeAll(async () => { - const genKey = async () => { - const kp = await crypto.subtle.generateKey( - { - name: 'RSA-OAEP', - modulusLength: 2048, - publicExponent: new Uint8Array([1, 0, 1]), - hash: 'SHA-256', - }, - true, - ['encrypt', 'decrypt'] - ); - return { - pub: (await crypto.subtle.exportKey('jwk', kp.publicKey)) as RSAPublicKeyJWK, - priv: (await crypto.subtle.exportKey('jwk', kp.privateKey)) as RSAPrivateKeyJWK, - }; - }; - - aliceKeys = await genKey(); - bobKeys = await genKey(); - adminKeys = await genKey(); - }); - - it('should encrypt and decrypt a message successfully', async () => { - const plaintext = "Meet me at the secret base."; - const adminKeyId = "admin-key-uuid"; - - // 1. Alice Encrypts - const encryptedPayload = await encryptTextMessage( - plaintext, - aliceKeys.pub, - bobKeys.pub, - adminKeys.pub, - adminKeyId - ); - - expect(encryptedPayload.version).toBe(2); - expect(encryptedPayload.keys_metadata.algorithm).toBe('AES-256-GCM'); - expect(encryptedPayload.keys_metadata.sender_wrapped_key).toBeDefined(); - expect(encryptedPayload.keys_metadata.recipient_wrapped_key).toBeDefined(); - expect(encryptedPayload.keys_metadata.admin_wrapped_key).toBeDefined(); - - // 2. Bob Decrypts (as Recipient) - const decryptedByBob = await decryptTextMessage( - encryptedPayload.encrypted_content, - encryptedPayload.encryption_iv, - encryptedPayload.keys_metadata, - bobKeys.priv, - true // isRecipient - ); - - expect(decryptedByBob).toBe(plaintext); - - // 3. Alice Decrypts (as Sender) - e.g. for history - const decryptedByAlice = await decryptTextMessage( - encryptedPayload.encrypted_content, - encryptedPayload.encryption_iv, - encryptedPayload.keys_metadata, - aliceKeys.priv, - false // isRecipient = false - ); - - expect(decryptedByAlice).toBe(plaintext); - }); - - it('should handle pending recipient (no recipient key)', async () => { - const plaintext = "Waiting for you to join..."; - const adminKeyId = "admin-key-uuid"; - - // Encrypt with NO recipient key (null) - const encryptedPayload = await encryptTextMessage( - plaintext, - aliceKeys.pub, - null, // No recipient key - adminKeys.pub, - adminKeyId - ); - - expect(encryptedPayload.keys_metadata.recipient_wrapped_key).toBeUndefined(); - expect(encryptedPayload.keys_metadata.pending_recipient).toBe(true); - - // Sender (Alice) can still decrypt - const decryptedByAlice = await decryptTextMessage( - encryptedPayload.encrypted_content, - encryptedPayload.encryption_iv, - encryptedPayload.keys_metadata, - aliceKeys.priv, - false - ); - expect(decryptedByAlice).toBe(plaintext); - }); - }); -}); diff --git a/apps/mobile/src/components/EncryptionKeyInitializer.tsx b/apps/mobile/src/components/EncryptionKeyInitializer.tsx deleted file mode 100644 index e216cf2..0000000 --- a/apps/mobile/src/components/EncryptionKeyInitializer.tsx +++ /dev/null @@ -1,206 +0,0 @@ -/** - * EncryptionKeyInitializer Component - * - * Handles automatic initialization and upload of E2EE encryption keys. - * Should be placed in the app layout to run after authentication. - * - * Uses global Zustand store for key state to ensure all components - * see the same keys at all times. - */ - -import { useEffect, useRef, useState } from 'react'; -import { Platform } from 'react-native'; -import { useEncryptionKeys } from '../hooks'; -import { useAuthStore } from '../store'; -import { reencryptPendingMessages } from '../lib/encryption/reencryptPendingMessages'; -import { triggerKeyRotation, getAdminPublicKey } from '../lib/encryption'; -import { LoadingOverlay } from './ui/LoadingOverlay'; -import { colors } from '../theme'; - -/** - * Check if crypto is available (react-native-quick-crypto polyfill installed) - */ -function isCryptoAvailable(): boolean { - return typeof crypto !== 'undefined' && crypto.subtle !== undefined; -} - -/** - * Component that initializes encryption keys after user authentication. - * - * Flow: - * 1. When user signs in, check if they have encryption keys - * 2. If not, generate new RSA key pair - * 3. Upload public key to Supabase profile - * 4. If user has a partner without keys, trigger re-encryption when partner generates keys - */ -export function EncryptionKeyInitializer(): JSX.Element | null { - const { initializeAndUploadKeys, isLoading: keysLoading, hasKeys, error } = useEncryptionKeys(); - const user = useAuthStore((s) => s.user); - const couple = useAuthStore((s) => s.couple); - - // Track if keys were regenerated this session (new device, reinstall, etc.) - const [wasRegenerated, setWasRegenerated] = useState(false); - const hasTriggeredRotation = useRef(false); - const hasLoggedCryptoWarning = useRef(false); - const isInitializing = useRef(false); - const hasInitialized = useRef(false); - - // Show loading overlay when we are initializing keys (generating new ones takes time) - // or when rotation is in progress - const [showLoading, setShowLoading] = useState(false); - const [loadingStatus, setLoadingStatus] = useState('Connecting...'); - - // Effect 1: Initialize encryption keys when user is authenticated - useEffect(() => { - // Skip on web - E2EE not supported - if (Platform.OS === 'web') return; - - // Check if crypto is available (native modules rebuilt) - if (!isCryptoAvailable()) { - if (!hasLoggedCryptoWarning.current) { - console.warn('[E2EE Init] Crypto not available. Run: npx expo prebuild --clean'); - hasLoggedCryptoWarning.current = true; - } - return; - } - - // Skip if no user, already initialized, or currently initializing - if (!user?.id || hasInitialized.current || isInitializing.current) return; - - // Wait for initial key loading to complete - if (keysLoading) return; - - // Skip if keys already exist in global state - if (hasKeys) { - console.log('[E2EE Init] Keys already loaded in global state'); - hasInitialized.current = true; - return; - } - - // Skip if there was an error loading keys (avoid retry loop) - if (error) { - console.warn('[E2EE Init] Skipping key initialization due to previous error:', error.message); - return; - } - - const initKeys = async () => { - try { - // Mark as initializing to prevent re-entry - isInitializing.current = true; - // Only show loading if we are generating keys (which might take a second) - // Standard loading is fast enough to not need a full screen blocker - - console.log('[E2EE Init] Starting key initialization...'); - - // Initialize keys and upload in one operation - const result = await initializeAndUploadKeys(); - - console.log('[E2EE Init] Encryption keys initialized and uploaded'); - - // Pre-fetch admin key to warm the cache before user reaches chat - // This reduces the delay before secureReady becomes true - try { - await getAdminPublicKey(); - console.log('[E2EE Init] Admin key pre-fetched successfully'); - } catch (adminKeyError) { - // Non-fatal: admin key will be fetched again when needed - console.warn('[E2EE Init] Failed to pre-fetch admin key:', adminKeyError); - } - - // Track if keys were regenerated (for rotation decision) - if (result.wasRegenerated) { - console.log('[E2EE Init] Keys were regenerated this session'); - setWasRegenerated(true); - } - - hasInitialized.current = true; - } catch (err) { - console.error('[E2EE Init] Failed to initialize encryption keys:', err); - // Reset initialization flag so we can retry on next render - // But only if it's a transient error, not a crypto unavailable error - if (err instanceof Error && !err.message.includes('Crypto')) { - isInitializing.current = false; - } - setShowLoading(false); - } - }; - - initKeys(); - }, [user?.id, keysLoading, hasKeys, error, initializeAndUploadKeys]); - - // Effect 2: Trigger key rotation when keys were regenerated and couple is available - useEffect(() => { - // Skip on web or if crypto not available - if (Platform.OS === 'web' || !isCryptoAvailable()) return; - - // Need user and couple to trigger rotation - if (!user?.id || !couple?.id) return; - - // Only trigger once per session - if (hasTriggeredRotation.current) return; - - // Wait for keys to be initialized in global state - if (!hasKeys) return; - - // Only trigger rotation if keys were actually regenerated this session - // (new device, app reinstall, key corruption recovery, etc.) - if (!wasRegenerated) { - // If we're done initializing but not rotating, hide loading - if (showLoading) { - setShowLoading(false); - isInitializing.current = false; - } - console.log('[E2EE Init] Keys unchanged, skipping rotation'); - return; - } - - const runRotation = async () => { - try { - hasTriggeredRotation.current = true; - // Only show loading for rotation which is a heavier operation - setShowLoading(true); - setLoadingStatus('Updating security...'); - - // Trigger key rotation - re-wraps message keys for the new public key - console.log('[E2EE Init] Keys were regenerated, triggering key rotation...'); - await triggerKeyRotation(); - - // Trigger re-encryption of pending messages (for messages where - // recipient had no key at send time) - await reencryptPendingMessages({ force: true }); - - console.log('[E2EE Init] Key rotation complete'); - } catch (err) { - console.error('[E2EE Init] Failed to run key rotation:', err); - // Reset so we can retry - hasTriggeredRotation.current = false; - } finally { - setShowLoading(false); - isInitializing.current = false; - } - }; - - runRotation(); - }, [user?.id, couple?.id, hasKeys, wasRegenerated, showLoading]); - - // Reset initialization flags when user changes (sign out/sign in) - useEffect(() => { - if (!user?.id) { - hasInitialized.current = false; - setWasRegenerated(false); - isInitializing.current = false; - hasTriggeredRotation.current = false; - setShowLoading(false); - } - }, [user?.id]); - - return ( - - ); -} diff --git a/apps/mobile/src/features/chat/ChatScreen.tsx b/apps/mobile/src/features/chat/ChatScreen.tsx index d21e7e0..d89fcc0 100644 --- a/apps/mobile/src/features/chat/ChatScreen.tsx +++ b/apps/mobile/src/features/chat/ChatScreen.tsx @@ -16,7 +16,7 @@ import type { ReportReason } from "./types"; import { supabase } from "../../lib/supabase"; import { useAuthStore, useMessageStore } from "../../store"; -import { useAmbientOrbAnimation, useMediaPicker, useTypingIndicator, useMessageSubscription, useEncryptedSend, useMediaSaver } from "../../hooks"; +import { useAmbientOrbAnimation, useMediaPicker, useTypingIndicator, useMessageSubscription, useMediaSaver } from "../../hooks"; import { Database } from "../../types/supabase"; import { GradientBackground } from "../../components/ui"; import { colors, gradients, radius, spacing, typography } from "../../theme"; @@ -34,7 +34,7 @@ export const ChatScreen: React.FC = () => { const matchId = id as string; const router = useRouter(); const insets = useSafeAreaInsets(); - const { user, partner, encryptionKeys } = useAuthStore(); + const { user, partner } = useAuthStore(); const { setActiveMatchId, markMatchMessagesAsRead } = useMessageStore(); const [match, setMatch] = useState(null); const [inputText, setInputText] = useState(""); @@ -74,23 +74,6 @@ export const ChatScreen: React.FC = () => { onNewMessage: clearTypingIndicator, }); - // E2EE encryption hook for sending messages - const { encryptMessage, isE2EEAvailable, isAdminKeyReady, isEncrypting } = useEncryptedSend(); - const secureReady = isE2EEAvailable && isAdminKeyReady; - const recoveryMessage = (() => { - if (!encryptionKeys.isRecovering) return null; - switch (encryptionKeys.recoveryReason) { - case 'pending-recipient': - return 'Finishing security setup for older messages...'; - case 'keys-unavailable': - return 'Setting up secure keys...'; - case 'stale-key': - case 'rotation': - return 'Updating security for this device...'; - default: - return 'Updating security...'; - } - })(); // Message actions hook for deletion and reporting const { showDeleteOptions, deleteForSelf } = useMessageActions({ @@ -196,35 +179,18 @@ export const ChatScreen: React.FC = () => { const handleSend = async () => { if (!inputText.trim()) return; if (!user) return; - if (!secureReady) return; - if (isEncrypting) return; const content = inputText.trim(); setInputText(""); try { - // Encrypt the message (secure-only) - console.log(`[E2EE Send] isE2EEAvailable=${isE2EEAvailable}`); - const encryptedPayload = await encryptMessage(content); - console.log(`[E2EE Send] encryptedPayload=`, { - version: encryptedPayload.version, - encrypted_content_length: encryptedPayload.encrypted_content.length, - encryption_iv_length: encryptedPayload.encryption_iv.length, - keys_metadata: encryptedPayload.keys_metadata, - }); - - // Send encrypted message (v2) - const { error, data } = await supabase.from("messages").insert({ + // Send plaintext message (v1) - protected by TLS in transit and RLS policies + const { error } = await supabase.from("messages").insert({ match_id: matchId, user_id: user.id, - content: null, - version: encryptedPayload.version, - encrypted_content: encryptedPayload.encrypted_content, - encryption_iv: encryptedPayload.encryption_iv, - keys_metadata: encryptedPayload.keys_metadata as unknown as Record, - }).select(); - - console.log(`[E2EE Send] Insert result:`, { error, data }); + content: content, + version: 1, + }); if (error) { Alert.alert("Error", "Failed to send message"); @@ -234,26 +200,12 @@ export const ChatScreen: React.FC = () => { } } catch (err) { console.error("Error sending message:", err); - // Show the actual error message if it's user-friendly (from encryption) - const errorMessage = err instanceof Error && err.message - ? err.message - : "Failed to send message"; - - // Map technical/unknown errors to friendly ones - let friendlyMessage = errorMessage; - if (errorMessage.includes('Failed to send') && !errorMessage.includes('connection')) { - friendlyMessage = "Couldn't send secure message. Please check your connection."; - } else if (errorMessage.includes('verification failed')) { - friendlyMessage = "Security check failed. Please restart the app."; - } - - Alert.alert("Delivery Failed", friendlyMessage); + Alert.alert("Delivery Failed", "Couldn't send message. Please check your connection."); setInputText(content); } }; const handlePickMedia = async () => { - if (!secureReady) return; const result = await pickMedia(); if (result) { uploadMedia(result.uri, result.mediaType); @@ -261,7 +213,6 @@ export const ChatScreen: React.FC = () => { }; const handleTakePhoto = async () => { - if (!secureReady) return; const result = await takePhoto(); if (result) { uploadMedia(result.uri, 'image'); @@ -269,7 +220,6 @@ export const ChatScreen: React.FC = () => { }; const handleRecordVideo = async () => { - if (!secureReady) return; const result = await recordVideo(); if (result) { uploadMedia(result.uri, 'video'); @@ -335,13 +285,6 @@ export const ChatScreen: React.FC = () => { onBack={() => router.push('/(app)/matches')} /> - {recoveryMessage && ( - - - {recoveryMessage} - - - )} { {/* Top border glow */} - {!secureReady && ( - - - Finishing security setup... - - )} - void; onSend: () => void; onPickMedia: () => void; @@ -31,7 +30,6 @@ const ACCENT = colors.premium.gold; export function InputBar({ inputText, uploading, - secureReady, onChangeText, onSend, onPickMedia, @@ -65,10 +63,8 @@ export function InputBar({ transform: [{ rotate: `${buttonRotation.value}deg` }], })); - const sendDisabled = !inputText.trim() || !secureReady; - const mediaDisabled = uploading || !secureReady; - // Determine if send is disabled specifically because of security (not empty input) - const waitingForSecurity = !secureReady && inputText.trim().length > 0; + const sendDisabled = !inputText.trim(); + const mediaDisabled = uploading; return ( @@ -153,8 +149,7 @@ export function InputBar({ disabled={sendDisabled} activeOpacity={0.8} accessibilityRole="button" - accessibilityLabel={waitingForSecurity ? "Send message - securing connection" : "Send message"} - accessibilityHint={waitingForSecurity ? "Please wait while we secure your connection" : undefined} + accessibilityLabel="Send message" testID="chat-input-send" > )} diff --git a/apps/mobile/src/features/chat/components/MessageContent.tsx b/apps/mobile/src/features/chat/components/MessageContent.tsx index cbbe95d..ce8013b 100644 --- a/apps/mobile/src/features/chat/components/MessageContent.tsx +++ b/apps/mobile/src/features/chat/components/MessageContent.tsx @@ -1,18 +1,16 @@ /** * MessageContent - Renders message content (text, images, videos) * Handles media reveal logic, expired media, and loading states. - * Supports both v1 (plaintext) and v2 (E2EE encrypted) messages. */ -import React from 'react'; -import { View, TouchableOpacity, Text, StyleSheet, ActivityIndicator, Alert } from 'react-native'; +import React, { useState, useEffect } from 'react'; +import { View, TouchableOpacity, Text, StyleSheet, ActivityIndicator } from 'react-native'; import { Image } from 'expo-image'; import { LinearGradient } from 'expo-linear-gradient'; import { Ionicons } from '@expo/vector-icons'; import { colors, gradients, spacing, radius } from '../../../theme'; import { MessageMeta } from './MessageMeta'; import { ChatVideoPlayer } from './ChatVideoPlayer'; -import { useDecryptedMessage, useDecryptedMedia } from '../../../hooks'; -import type { KeysMetadata } from '../../../lib/encryption'; +import { supabase } from '../../../lib/supabase'; import type { Message } from '../types'; const ACCENT = colors.premium.gold; @@ -52,61 +50,41 @@ export function MessageContent({ ); } - // Use decryption hook for E2EE text messages - const { - content: decryptedContent, - isDecrypting, - error: decryptError, - errorCode: decryptErrorCode, - retry: retryDecrypt, - } = useDecryptedMessage({ - message: { - id: item.id, - content: item.content, - version: item.version, - encrypted_content: item.encrypted_content, - encryption_iv: item.encryption_iv, - keys_metadata: item.keys_metadata as KeysMetadata | null, - user_id: item.user_id, - }, - currentUserId, - }); - const isVideo = (item as any).media_type === 'video'; const isViewed = !!item.media_viewed_at; const isRecipientHidden = !isMe && !isViewed; - // Use decryption hook for E2EE media (images/videos) - const { - uri: mediaUri, - isDecrypting: isDecryptingMedia, - error: mediaError, - errorCode: mediaErrorCode, - retry: retryMedia, - isEncrypted: isMediaEncrypted, - } = useDecryptedMedia({ - messageId: item.id, - mediaPath: item.media_path ?? null, - version: item.version, - encryptionIv: item.encryption_iv, - keysMetadata: item.keys_metadata as KeysMetadata | null, - isMe, - mediaType: isVideo ? 'video' : 'image', - shouldFetch: !!item.media_path && !isRecipientHidden, - }); + // Get signed URL for media + const [mediaUri, setMediaUri] = useState(null); + const [mediaLoading, setMediaLoading] = useState(false); + const [mediaError, setMediaError] = useState(false); - const isPendingMedia = mediaErrorCode === 'E2EE_PENDING_RECIPIENT_KEY'; + useEffect(() => { + if (!item.media_path || isRecipientHidden) { + setMediaUri(null); + return; + } - const showSecureMediaInfo = () => { - Alert.alert( - 'Secure media', - "To keep your chats private, photos and videos are locked to each person’s secure key.\n\nThis media was sent before your secure key was ready, so it’s still locked. We’re now securely updating the lock for your device (without exposing the media) so you can open it.\n\nIf it doesn’t unlock in a few seconds, tap “Try again”.", - [ - { text: 'OK', style: 'cancel' }, - { text: 'Try again', onPress: () => retryMedia() }, - ] - ); - }; + const fetchMediaUrl = async () => { + setMediaLoading(true); + setMediaError(false); + try { + const { data, error } = await supabase.storage + .from('chat-media') + .createSignedUrl(item.media_path!, 3600); // 1 hour expiry + + if (error) throw error; + setMediaUri(data.signedUrl); + } catch (err) { + console.error('Failed to get media URL:', err); + setMediaError(true); + } finally { + setMediaLoading(false); + } + }; + + fetchMediaUrl(); + }, [item.media_path, isRecipientHidden]); // Handle expired videos const isExpired = !!(item as any).media_expired; @@ -135,8 +113,7 @@ export function MessageContent({ // Handle media (images and videos) if (item.media_path || isExpired) { const canOpenFullScreen = (isMe || isViewed) && !isVideo; // Only images can go fullscreen - const hasMediaError = !!mediaError; - const isLoading = isDecryptingMedia || (!mediaUri && !hasMediaError && !isRecipientHidden); + const isLoading = mediaLoading || (!mediaUri && !mediaError && !isRecipientHidden); // Video content if (isVideo) { @@ -166,26 +143,11 @@ export function MessageContent({ Video hidden Tap to reveal - ) : isPendingMedia ? ( - - - - - Secure video - Finishing security setup • Tap for info - {isDecryptingMedia && } - - - ) : mediaUri || hasMediaError ? ( + ) : mediaUri || mediaError ? ( ) : ( @@ -209,17 +171,13 @@ export function MessageContent({ return ( { - if (isPendingMedia) { - showSecureMediaInfo(); - return; - } if (canOpenFullScreen && mediaUri) { onImagePress(mediaUri); } }} - disabled={!(isPendingMedia || (canOpenFullScreen && !!mediaUri))} + disabled={!(canOpenFullScreen && !!mediaUri)} > {isRecipientHidden ? ( - ) : isPendingMedia ? ( - - - - Secure photo - Finishing security setup • Tap for info - {isDecryptingMedia && } - - ) : hasMediaError ? ( + ) : mediaError ? ( Failed to load image @@ -288,73 +233,10 @@ export function MessageContent({ ); } - // Text message - const version = item.version ?? 1; - const isV2 = version === 2; - - const showSecureMessageInfo = () => { - Alert.alert( - 'Secure message', - "To keep your chats private, each message is locked to your device’s secure key.\n\nThis message was sent before your secure key was ready, so it’s still locked. We’re now securely updating the lock for your device (without exposing the message content) so you can read it.\n\nIf it doesn’t unlock in a few seconds, tap “Try again”.", - [ - { text: 'OK', style: 'cancel' }, - { text: 'Try again', onPress: () => retryDecrypt() }, - ] - ); - }; - - const renderText = () => { - if (decryptErrorCode === 'E2EE_PENDING_RECIPIENT_KEY') { - return ( - - - - - Secure message - {isDecrypting && } - - Finishing security setup • Tap for info - - - ); - } - - if (isDecrypting) { - return ( - - - - ); - } - - if (decryptError) { - return ( - - Couldn’t open secure message • Tap to retry - - ); - } - - if (isV2) { - return {decryptedContent ?? 'Secure message'}; - } - - return {item.content ?? 'Failed to load message'}; - }; - + // Text message - display content directly return ( <> - {renderText()} + {item.content ?? 'Message unavailable'} ); @@ -376,61 +258,12 @@ const styles = StyleSheet.create({ fontSize: 16, lineHeight: 22, }, - securePlaceholder: { - gap: spacing.xs, - }, - securePlaceholderRow: { - flexDirection: 'row', - alignItems: 'center', - gap: spacing.xs, - }, - securePlaceholderTitle: { - color: colors.textSecondary, - fontSize: 14, - fontWeight: '600', - }, - securePlaceholderSubtext: { - color: colors.textTertiary, - fontSize: 12, - }, - decryptingContainer: { - paddingVertical: spacing.sm, - paddingHorizontal: spacing.md, - justifyContent: 'center', - alignItems: 'center', - }, - decryptingText: { - color: colors.textSecondary, - fontSize: 11, - marginTop: spacing.xs, - }, - errorText: { - color: colors.textSecondary, - fontStyle: 'italic', - }, messageImage: { width: 200, height: 200, borderRadius: radius.md, backgroundColor: 'rgba(255, 255, 255, 0.05)', }, - secureMediaPlaceholder: { - justifyContent: 'center', - alignItems: 'center', - gap: spacing.sm, - overflow: 'hidden', - }, - secureMediaPlaceholderText: { - color: colors.textSecondary, - fontSize: 12, - fontWeight: '600', - }, - secureMediaPlaceholderSubtext: { - color: colors.textTertiary, - fontSize: 11, - textAlign: 'center', - paddingHorizontal: spacing.md, - }, messageImageLoading: { justifyContent: 'center', alignItems: 'center', diff --git a/apps/mobile/src/features/chat/hooks/useMediaUpload.ts b/apps/mobile/src/features/chat/hooks/useMediaUpload.ts index 0ec1073..9b12531 100644 --- a/apps/mobile/src/features/chat/hooks/useMediaUpload.ts +++ b/apps/mobile/src/features/chat/hooks/useMediaUpload.ts @@ -1,4 +1,4 @@ -import { useRef, useState } from 'react'; +import { useState } from 'react'; import { Alert, Platform } from 'react-native'; import * as FileSystem from 'expo-file-system'; import { Video as VideoCompressor } from 'react-native-compressor'; @@ -7,32 +7,10 @@ import { decode } from 'base64-arraybuffer'; import { supabase } from '../../../lib/supabase'; import { Events } from '../../../lib/analytics'; import { UploadStatus } from '../types'; -import { useAuthStore } from '../../../store'; -import { - encryptMediaFile, - getAdminPublicKey, - getAdminKeyId, - MESSAGE_VERSION_E2EE, - isValidPublicKeyJwk, - sanitizePublicKeyJwk, - verifyKeyPair, -} from '../../../lib/encryption'; -import type { RSAPublicKeyJWK, EncryptedMediaPayload } from '../../../lib/encryption'; -import { useEncryptionKeys } from '../../../hooks'; export function useMediaUpload(matchId: string, userId: string | undefined) { const [uploading, setUploading] = useState(false); const [uploadStatus, setUploadStatus] = useState(null); - const verifiedKeysVersionRef = useRef(null); - const partnerRefreshRef = useRef(0); - const PARTNER_REFRESH_TTL_MS = 2 * 60 * 1000; - - const refreshPartner = useAuthStore((s) => s.refreshPartner); - const { publicKeyJwk, privateKeyJwk, hasKeys, isLoading: keysLoading } = useEncryptionKeys(); - - // Check if E2EE is available for media - const isE2EEAvailable = - Platform.OS !== 'web' && hasKeys && !keysLoading && !!publicKeyJwk && !!privateKeyJwk; const uploadMedia = async (uri: string, mediaType: 'image' | 'video') => { if (!userId) return; @@ -40,17 +18,9 @@ export function useMediaUpload(matchId: string, userId: string | undefined) { setUploadStatus({ mediaType, status: mediaType === 'video' ? 'compressing' : 'uploading', thumbnailUri: uri }); try { - // Block media uploads until encryption is ready (secure-only) - if (!isE2EEAvailable || Platform.OS === 'web') { - const readyError = new Error('Media security not ready. Please check your connection.'); - console.warn('[E2EE Media Upload] E2EE not available, blocking upload'); - throw readyError; - } - let fileUri = uri; let fileBody; let ext = mediaType === 'video' ? 'mp4' : 'jpg'; - let encryptedPayload: EncryptedMediaPayload; // Compress videos on native platforms before upload if (mediaType === 'video' && Platform.OS !== 'web') { @@ -73,108 +43,6 @@ export function useMediaUpload(matchId: string, userId: string | undefined) { } } - // CRITICAL: Read keys directly from global store at encryption time - // This ensures we always use the most current keys, not potentially stale hook state - const currentKeys = useAuthStore.getState().encryptionKeys; - - if (!currentKeys.hasKeys || !currentKeys.publicKeyJwk || !currentKeys.privateKeyJwk) { - console.warn('[E2EE Media Upload] Keys not fully available in global store at encryption time'); - throw new Error('Media security not ready. Please check your connection.'); - } - - const senderPublicKey = currentKeys.publicKeyJwk; - const senderPrivateKey = currentKeys.privateKeyJwk; - - // SAFETY CHECK: Verify the key pair works together before encrypting - if (verifiedKeysVersionRef.current !== currentKeys.keysVersion) { - console.log( - `[E2EE Media Upload] Verifying sender key pair (version ${currentKeys.keysVersion})...` - ); - const isValidKeyPair = await verifyKeyPair( - senderPublicKey as RSAPublicKeyJWK, - senderPrivateKey - ); - - if (!isValidKeyPair) { - console.error('[E2EE Media Upload] CRITICAL: Sender key pair verification failed!'); - throw new Error('Security check failed. Please restart the app.'); - } - - verifiedKeysVersionRef.current = currentKeys.keysVersion; - console.log('[E2EE Media Upload] Sender key pair verified successfully'); - } - - console.log('[E2EE Media Upload] Using sender public key from global store, version:', currentKeys.keysVersion); - - // Refresh partner's profile only when key is missing/invalid or TTL expires - const resolvePartnerProfile = async () => { - const cachedPartner = useAuthStore.getState().partner; - const cachedKey = cachedPartner?.public_key_jwk as RSAPublicKeyJWK | null | undefined; - const hasValidKey = cachedKey ? isValidPublicKeyJwk(cachedKey) : false; - const now = Date.now(); - const shouldRefresh = !hasValidKey || (now - partnerRefreshRef.current) > PARTNER_REFRESH_TTL_MS; - - if (!shouldRefresh) { - return cachedPartner; - } - - console.log('[E2EE Media Upload] Refreshing partner profile...'); - try { - const freshPartner = await refreshPartner(); - partnerRefreshRef.current = Date.now(); - return freshPartner ?? useAuthStore.getState().partner; - } catch (refreshError) { - console.warn('[E2EE Media Upload] Partner refresh failed, using cached key:', refreshError); - partnerRefreshRef.current = Date.now(); - return cachedPartner; - } - }; - - const freshPartner = await resolvePartnerProfile(); - - let adminPublicKey: RSAPublicKeyJWK; - let adminKeyId: string; - - try { - adminPublicKey = await getAdminPublicKey(); - adminKeyId = await getAdminKeyId(); - - if (!isValidPublicKeyJwk(adminPublicKey)) { - throw new Error('Admin public key is invalid'); - } - } catch (adminKeyError) { - console.error('[E2EE Media Upload] Failed to fetch admin key:', adminKeyError); - throw new Error('Connection issue. Please try again.'); - } - - let partnerPublicKey = freshPartner?.public_key_jwk as RSAPublicKeyJWK | null | undefined; - - // Validate and sanitize partner's public key - if (partnerPublicKey) { - if (!isValidPublicKeyJwk(partnerPublicKey)) { - console.warn('[E2EE Media Upload] Partner public key is invalid, treating as unavailable'); - partnerPublicKey = null; - } else { - // Sanitize to remove trailing dots from base64 fields - partnerPublicKey = sanitizePublicKeyJwk(partnerPublicKey); - } - } - - console.log('[E2EE Media Upload] Partner public key available:', !!partnerPublicKey); - - encryptedPayload = await encryptMediaFile( - fileUri, - senderPublicKey as RSAPublicKeyJWK, - partnerPublicKey ?? null, - adminPublicKey, - adminKeyId - ); - - // Use the encrypted file for upload - fileUri = encryptedPayload.encryptedFileUri; - ext = 'enc'; // Encrypted files use .enc extension - console.log('Media encrypted successfully'); - if (Platform.OS === 'web') { const response = await fetch(fileUri); const blob = await response.blob(); @@ -194,11 +62,10 @@ export function useMediaUpload(matchId: string, userId: string | undefined) { } else { const base64 = await FileSystem.readAsStringAsync(fileUri, { encoding: FileSystem.EncodingType.Base64 }); fileBody = decode(base64); - } const fileName = `${matchId}/${Date.now()}_${Math.random().toString(36).substring(7)}.${ext}`; - const contentType = 'application/octet-stream'; + const contentType = mediaType === 'video' ? 'video/mp4' : 'image/jpeg'; const { error: uploadError } = await supabase.storage .from("chat-media") @@ -209,16 +76,7 @@ export function useMediaUpload(matchId: string, userId: string | undefined) { if (uploadError) throw uploadError; - // Clean up encrypted temp file - if (encryptedPayload && encryptedPayload.encryptedFileUri) { - try { - await FileSystem.deleteAsync(encryptedPayload.encryptedFileUri, { idempotent: true }); - } catch (cleanupError) { - console.warn('Failed to clean up encrypted temp file:', cleanupError); - } - } - - // Store the message with encryption metadata + // Store the message (plaintext v1) await supabase.from("messages").insert({ match_id: matchId, user_id: userId, @@ -226,9 +84,7 @@ export function useMediaUpload(matchId: string, userId: string | undefined) { media_path: fileName, media_type: mediaType, media_expired: false, - version: MESSAGE_VERSION_E2EE, - encryption_iv: encryptedPayload.encryption_iv, - keys_metadata: encryptedPayload.keys_metadata as unknown as Record, + version: 1, }); Events.mediaUploaded(); diff --git a/apps/mobile/src/features/profile/ProfileScreen.tsx b/apps/mobile/src/features/profile/ProfileScreen.tsx index d2c6bb7..76e7932 100644 --- a/apps/mobile/src/features/profile/ProfileScreen.tsx +++ b/apps/mobile/src/features/profile/ProfileScreen.tsx @@ -20,7 +20,6 @@ import { useAuthStore, useSubscriptionStore } from '../../store'; import { resetSwipeTutorial } from '../../lib/swipeTutorialSeen'; import { resetMatchesTutorial } from '../../lib/matchesTutorialSeen'; import { supabase } from '../../lib/supabase'; // Needed for debug reset -import { clearKeys } from '../../lib/encryption'; // Hooks import { useProfileSettings, useCoupleManagement } from './hooks'; @@ -294,29 +293,6 @@ export function ProfileScreen() { } }} /> - - { - Alert.alert( - "Clear Keys", - "Are you sure? You will lose access to encrypted messages until keys are regenerated.", - [ - { text: "Cancel", style: "cancel" }, - { - text: "Clear", - style: "destructive", - onPress: async () => { - await clearKeys(); - Alert.alert("Success", "Keys cleared. They will be regenerated on next launch/login."); - } - } - ] - ); - }} - /> )} diff --git a/apps/mobile/src/features/profile/hooks/useCoupleManagement.ts b/apps/mobile/src/features/profile/hooks/useCoupleManagement.ts index b74f688..cf109e0 100644 --- a/apps/mobile/src/features/profile/hooks/useCoupleManagement.ts +++ b/apps/mobile/src/features/profile/hooks/useCoupleManagement.ts @@ -4,7 +4,6 @@ import { useRouter } from 'expo-router'; import { useAuthStore, useMatchStore, useMessageStore, usePacksStore } from '../../../store'; import { supabase } from '../../../lib/supabase'; import { Events } from '../../../lib/analytics'; -import { clearKeys } from '../../../lib/encryption'; export function useCoupleManagement() { const router = useRouter(); @@ -114,7 +113,6 @@ export function useCoupleManagement() { clearMatches(); clearMessages(); clearPacks(); - await clearKeys(); Events.accountDeleted(); diff --git a/apps/mobile/src/hooks/index.ts b/apps/mobile/src/hooks/index.ts index 244b660..ad78263 100644 --- a/apps/mobile/src/hooks/index.ts +++ b/apps/mobile/src/hooks/index.ts @@ -7,8 +7,4 @@ export { useTypingIndicator } from './useTypingIndicator'; export type { UseTypingIndicatorConfig, UseTypingIndicatorReturn } from './useTypingIndicator'; export { useMessageSubscription } from './useMessageSubscription'; export type { UseMessageSubscriptionConfig, UseMessageSubscriptionReturn } from './useMessageSubscription'; -export { useEncryptionKeys } from './useEncryptionKeys'; -export { useDecryptedMessage } from './useDecryptedMessage'; -export { useEncryptedSend } from './useEncryptedSend'; -export { useDecryptedMedia, clearDecryptedMediaCache } from './useDecryptedMedia'; export { useMediaSaver } from './useMediaSaver'; diff --git a/apps/mobile/src/hooks/useDecryptedMedia.ts b/apps/mobile/src/hooks/useDecryptedMedia.ts deleted file mode 100644 index cb030d9..0000000 --- a/apps/mobile/src/hooks/useDecryptedMedia.ts +++ /dev/null @@ -1,486 +0,0 @@ -/** - * useDecryptedMedia Hook - * - * React hook for decrypting E2EE encrypted media files (images/videos). - * Handles downloading, decrypting, and caching decrypted media. - */ - -import { useState, useEffect, useCallback, useRef } from 'react'; -import { Platform } from 'react-native'; -import * as FileSystem from 'expo-file-system'; -import { - decryptMediaFile, - cleanupDecryptedMedia, - MESSAGE_VERSION_E2EE, - repairStaleKey, - triggerAutoKeyRotation, -} from '../lib/encryption'; -import type { KeysMetadata, RSAPrivateKeyJWK } from '../lib/encryption'; -import { useEncryptionKeys } from './useEncryptionKeys'; -import { getCachedSignedUrl, getStoragePath } from '../lib/imageCache'; -import { supabase } from '../lib/supabase'; -import { reencryptPendingMessages } from '../lib/encryption/reencryptPendingMessages'; -import { useAuthStore } from '../store/authStore'; -// Import shared cache from mediaCache to avoid circular dependency -import { decryptedMediaCache, clearDecryptedMediaCache } from '../lib/mediaCache'; - -const AUTO_RETRY_BASE_DELAY_MS = 3000; -const MAX_AUTO_RETRIES = 2; -const autoRetryCountsByMediaKey = new Map(); - -export type DecryptedMediaErrorCode = - | 'E2EE_NOT_SUPPORTED' - | 'E2EE_KEYS_UNAVAILABLE' - | 'E2EE_MISSING_FIELDS' - | 'E2EE_PENDING_RECIPIENT_KEY' - | 'E2EE_DECRYPT_FAILED'; - -// Re-export clearDecryptedMediaCache for backwards compatibility -export { clearDecryptedMediaCache }; - -interface DecryptedMediaState { - /** Local file URI to the decrypted media (or null if not ready) */ - uri: string | null; - /** Whether decryption is in progress */ - isDecrypting: boolean; - /** Error if decryption failed */ - error: Error | null; - /** Optional error code for UX */ - errorCode?: DecryptedMediaErrorCode; -} - -interface UseDecryptedMediaOptions { - /** The message ID (used for cache key) */ - messageId: string; - /** Path to the media file in storage */ - mediaPath: string | null; - /** Message version (1 = plaintext, 2 = encrypted) */ - version: number | null | undefined; - /** Encryption IV (required for v2) */ - encryptionIv: string | null | undefined; - /** Keys metadata containing wrapped keys (required for v2) */ - keysMetadata: KeysMetadata | null | undefined; - /** Whether current user is the sender */ - isMe: boolean; - /** Media type */ - mediaType: 'image' | 'video'; - /** Whether media should be fetched (e.g., not hidden) */ - shouldFetch: boolean; -} - -export type UseDecryptedMediaResult = DecryptedMediaState & { - isEncrypted: boolean; - retry: () => void; -}; - -/** - * Hook to decrypt encrypted media files - */ -export function useDecryptedMedia({ - messageId, - mediaPath, - version, - encryptionIv, - keysMetadata, - isMe, - mediaType, - shouldFetch, -}: UseDecryptedMediaOptions): UseDecryptedMediaResult { - const [state, setState] = useState({ - uri: null, - isDecrypting: false, - error: null, - }); - - const { privateKeyJwk, hasKeys, isLoading: keysLoading } = useEncryptionKeys(); - const beginEncryptionRecovery = useAuthStore((s) => s.beginEncryptionRecovery); - const endEncryptionRecovery = useAuthStore((s) => s.endEncryptionRecovery); - const isMounted = useRef(true); - - const repairAttemptedByMessageId = useRef(new Set()); - const [retryNonce, setRetryNonce] = useState(0); - const autoRetryTimerRef = useRef | null>(null); - - const retry = useCallback(() => { - repairAttemptedByMessageId.current.delete(messageId); - setRetryNonce((n) => n + 1); - }, [messageId]); - - // Determine if this is encrypted media - const isEncrypted = version === MESSAGE_VERSION_E2EE && (mediaPath?.endsWith('.enc') ?? false); - - const decryptMedia = useCallback(async () => { - // No media path - nothing to do - if (!mediaPath || !shouldFetch) { - setState({ uri: null, isDecrypting: false, error: null, errorCode: undefined }); - return; - } - - console.log( - `[E2EE Media] Message ${messageId}: Starting decrypt - version=${version}, mediaPath=${mediaPath}, isEncrypted=${isEncrypted}`, - ); - - // Check cache first - const cacheKey = `${messageId}-${mediaPath}`; - const cachedUri = decryptedMediaCache.get(cacheKey); - if (cachedUri) { - try { - const fileInfo = await FileSystem.getInfoAsync(cachedUri); - if (fileInfo.exists) { - console.log(`[E2EE Media] Message ${messageId}: Using cached decrypted file`); - setState({ uri: cachedUri, isDecrypting: false, error: null, errorCode: undefined }); - return; - } - } catch { - decryptedMediaCache.delete(cacheKey); - } - } - - // v1 (plaintext) or non-.enc files: Use existing signed URL flow - if (!isEncrypted) { - console.log(`[E2EE Media] Message ${messageId}: Not encrypted, using signed URL flow`); - try { - const storagePath = getStoragePath(mediaPath); - const signedUrl = await getCachedSignedUrl(storagePath); - if (isMounted.current) { - setState({ - uri: signedUrl, - isDecrypting: false, - error: signedUrl ? null : new Error('Failed to get signed URL'), - errorCode: signedUrl ? undefined : 'E2EE_DECRYPT_FAILED', - }); - } - } catch (err) { - console.error(`[E2EE Media] Message ${messageId}: Failed to get signed URL:`, err); - if (isMounted.current) { - setState({ - uri: null, - isDecrypting: false, - error: err as Error, - errorCode: 'E2EE_DECRYPT_FAILED', - }); - } - } - return; - } - - // v2 (encrypted) media - requires decryption - console.log(`[E2EE Media] Message ${messageId}: Encrypted media, starting decryption`); - - if (Platform.OS === 'web') { - setState({ - uri: null, - isDecrypting: false, - error: new Error('Failed to load media'), - errorCode: 'E2EE_NOT_SUPPORTED', - }); - return; - } - - // Wait for keys to load - if (keysLoading) { - console.log(`[E2EE Media] Message ${messageId}: Keys still loading...`); - setState((prev) => ({ ...prev, isDecrypting: true })); - return; - } - - if (!hasKeys || !privateKeyJwk) { - console.log( - `[E2EE Media] Message ${messageId}: No keys available - hasKeys=${hasKeys}, hasPrivateKey=${!!privateKeyJwk}`, - ); - setState({ - uri: null, - isDecrypting: false, - error: new Error('Failed to load media'), - errorCode: 'E2EE_KEYS_UNAVAILABLE', - }); - return; - } - - // Validate required encryption fields - if (!encryptionIv || !keysMetadata) { - console.log( - `[E2EE Media] Message ${messageId}: Missing encryption metadata - iv=${!!encryptionIv}, keysMetadata=${!!keysMetadata}`, - ); - setState({ - uri: null, - isDecrypting: false, - error: new Error('Failed to load media'), - errorCode: 'E2EE_MISSING_FIELDS', - }); - return; - } - - // If the recipient key is missing, try server-assisted repair (admin recovery model). - let effectiveKeysMetadata: KeysMetadata | null = keysMetadata; - - const getWrappedKey = (metadata: KeysMetadata | null): string | undefined => - isMe ? metadata?.sender_wrapped_key : metadata?.recipient_wrapped_key; - - let wrappedKey = getWrappedKey(effectiveKeysMetadata); - - if (!wrappedKey) { - console.log( - `[E2EE Media] Message ${messageId}: No wrapped key for ${isMe ? 'sender' : 'recipient'} - pending_recipient=${(effectiveKeysMetadata as any)?.pending_recipient}`, - ); - - if (!isMe) { - beginEncryptionRecovery('pending-recipient'); - try { - setState({ - uri: null, - isDecrypting: true, - error: null, - errorCode: 'E2EE_PENDING_RECIPIENT_KEY', - }); - - if (!repairAttemptedByMessageId.current.has(messageId)) { - repairAttemptedByMessageId.current.add(messageId); - await reencryptPendingMessages(); - } - - const { data: refreshed } = await supabase - .from('messages') - .select('keys_metadata') - .eq('id', messageId) - .maybeSingle(); - - effectiveKeysMetadata = (refreshed?.keys_metadata ?? null) as KeysMetadata | null; - wrappedKey = getWrappedKey(effectiveKeysMetadata); - } finally { - endEncryptionRecovery(); - } - } - - if (!wrappedKey) { - setState({ - uri: null, - isDecrypting: false, - error: null, - errorCode: 'E2EE_PENDING_RECIPIENT_KEY', - }); - return; - } - } - - setState((prev) => ({ ...prev, isDecrypting: true, error: null, errorCode: undefined })); - - try { - // Get signed URL for the encrypted file - const storagePath = getStoragePath(mediaPath); - console.log(`[E2EE Media] Message ${messageId}: Getting signed URL for ${storagePath}`); - const encryptedUrl = await getCachedSignedUrl(storagePath); - - if (!encryptedUrl) { - throw new Error('Failed to load media'); - } - - console.log(`[E2EE Media] Message ${messageId}: Decrypting ${mediaType}...`); - - const decryptedUri = await decryptMediaFile( - encryptedUrl, - encryptionIv, - effectiveKeysMetadata as KeysMetadata, - privateKeyJwk as RSAPrivateKeyJWK, - !isMe, // isRecipient - mediaType, - ); - - console.log(`[E2EE Media] Message ${messageId}: Decryption successful - ${decryptedUri}`); - - decryptedMediaCache.set(cacheKey, decryptedUri); - - if (isMounted.current) { - setState({ - uri: decryptedUri, - isDecrypting: false, - error: null, - errorCode: undefined, - }); - } - } catch (err) { - const error = err instanceof Error ? err : new Error('Unknown error'); - console.error(`[E2EE Media] Message ${messageId}: Decryption failed:`, error); - - // Check if this is a stale key failure (message encrypted with old key) - const isStaleKeyFailure = - error.name === 'OperationError' || - error.message.includes('OperationError') || - error.message.includes('decryption failed') || - error.message.includes('decrypt error') || - error.message.includes('error in DoCipher'); - - // Attempt stale key repair if not already attempted - if (isStaleKeyFailure && !repairAttemptedByMessageId.current.has(messageId)) { - beginEncryptionRecovery('stale-key'); - const autoRotationPromise = triggerAutoKeyRotation(); - let didDecrypt = false; - - try { - console.log(`[E2EE Media] Message ${messageId}: Attempting stale key repair...`); - - if (isMounted.current) { - setState({ - uri: null, - isDecrypting: true, - error: null, - errorCode: undefined, - }); - } - - repairAttemptedByMessageId.current.add(messageId); - - try { - const repairResult = await repairStaleKey(messageId); - - if (repairResult.success) { - console.log(`[E2EE Media] Message ${messageId}: Stale key repaired, retrying decryption...`); - - // Fetch updated message and retry - const { data: refreshed } = await supabase - .from('messages') - .select('keys_metadata') - .eq('id', messageId) - .maybeSingle(); - - const refreshedMetadata = (refreshed?.keys_metadata ?? null) as KeysMetadata | null; - - if (refreshedMetadata && encryptionIv && mediaPath) { - const storagePath = getStoragePath(mediaPath); - const encryptedUrl = await getCachedSignedUrl(storagePath); - - if (encryptedUrl) { - const decryptedUri = await decryptMediaFile( - encryptedUrl, - encryptionIv, - refreshedMetadata, - privateKeyJwk as RSAPrivateKeyJWK, - !isMe, - mediaType, - ); - - const cacheKey = `${messageId}-${mediaPath}`; - decryptedMediaCache.set(cacheKey, decryptedUri); - - if (isMounted.current) { - setState({ - uri: decryptedUri, - isDecrypting: false, - error: null, - errorCode: undefined, - }); - } - didDecrypt = true; - return; - } - } - } else { - console.error(`[E2EE Media] Message ${messageId}: Stale key repair failed:`, repairResult.error); - } - } catch (repairErr) { - console.error(`[E2EE Media] Message ${messageId}: Stale key repair threw:`, repairErr); - } - } finally { - await autoRotationPromise; - if (autoRotationPromise && !didDecrypt) { - retry(); - } - endEncryptionRecovery(); - } - } - - if (isMounted.current) { - setState({ - uri: null, - isDecrypting: false, - error: new Error('Failed to load media'), - errorCode: 'E2EE_DECRYPT_FAILED', - }); - } - } - }, [ - messageId, - mediaPath, - version, - encryptionIv, - keysMetadata, - isMe, - mediaType, - shouldFetch, - isEncrypted, - privateKeyJwk, - hasKeys, - keysLoading, - retryNonce, - beginEncryptionRecovery, - endEncryptionRecovery, - retry, - ]); - - useEffect(() => { - isMounted.current = true; - decryptMedia(); - - return () => { - isMounted.current = false; - }; - }, [decryptMedia, retryNonce]); - - useEffect(() => { - return () => { - if (autoRetryTimerRef.current) { - clearTimeout(autoRetryTimerRef.current); - autoRetryTimerRef.current = null; - } - }; - }, [messageId, mediaPath]); - - useEffect(() => { - const autoRetryKey = `${messageId}:${mediaPath ?? 'none'}`; - - if (!state.errorCode) { - autoRetryCountsByMediaKey.delete(autoRetryKey); - if (autoRetryTimerRef.current) { - clearTimeout(autoRetryTimerRef.current); - autoRetryTimerRef.current = null; - } - return; - } - - const shouldRetry = - state.errorCode === 'E2EE_PENDING_RECIPIENT_KEY' || - state.errorCode === 'E2EE_KEYS_UNAVAILABLE'; - - if (!shouldRetry) { - return; - } - - const attempts = autoRetryCountsByMediaKey.get(autoRetryKey) ?? 0; - if (attempts >= MAX_AUTO_RETRIES) { - return; - } - - const nextAttempt = attempts + 1; - const delayMs = AUTO_RETRY_BASE_DELAY_MS * nextAttempt; - - autoRetryCountsByMediaKey.set(autoRetryKey, nextAttempt); - - autoRetryTimerRef.current = setTimeout(() => { - retry(); - }, delayMs); - - return () => { - if (autoRetryTimerRef.current) { - clearTimeout(autoRetryTimerRef.current); - autoRetryTimerRef.current = null; - } - }; - }, [messageId, mediaPath, state.errorCode, retry]); - - return { - ...state, - isEncrypted, - retry, - }; -} - diff --git a/apps/mobile/src/hooks/useDecryptedMessage.ts b/apps/mobile/src/hooks/useDecryptedMessage.ts deleted file mode 100644 index 2f61924..0000000 --- a/apps/mobile/src/hooks/useDecryptedMessage.ts +++ /dev/null @@ -1,466 +0,0 @@ -/** - * useDecryptedMessage Hook - * - * React hook for decrypting E2EE messages. - * Handles both v1 (plaintext) and v2 (encrypted) messages. - */ - -import { useState, useEffect, useCallback, useRef } from 'react'; -import { Platform } from 'react-native'; -import { - decryptTextMessage, - MESSAGE_VERSION_PLAINTEXT, - MESSAGE_VERSION_E2EE, - repairStaleKey, - triggerAutoKeyRotation, -} from '../lib/encryption'; -import type { - DecryptedMessageState, - KeysMetadata, - RSAPrivateKeyJWK, -} from '../lib/encryption'; -import { supabase } from '../lib/supabase'; -import { reencryptPendingMessages } from '../lib/encryption/reencryptPendingMessages'; -import { useEncryptionKeys } from './useEncryptionKeys'; -import { useAuthStore } from '../store/authStore'; - -const AUTO_RETRY_BASE_DELAY_MS = 3000; -const MAX_AUTO_RETRIES = 2; -const autoRetryCountsByMessageId = new Map(); - -interface Message { - id: string; - content: string | null; - version?: number | null; - encrypted_content?: string | null; - encryption_iv?: string | null; - keys_metadata?: KeysMetadata | null; - user_id: string; -} - -interface UseDecryptedMessageOptions { - /** The message to decrypt */ - message: Message; - /** Current user's ID to determine if sender or recipient */ - currentUserId: string; -} - -export type UseDecryptedMessageResult = DecryptedMessageState & { - /** Force a re-attempt (used by UI retry affordances) */ - retry: () => void; -}; - -/** - * Hook to decrypt a message - * - * Automatically handles: - * - v1 (plaintext) messages: returns content directly - * - v2 (encrypted) messages: decrypts using private key - * - Server-assisted re-wrap for pending recipient keys (admin recovery model) - */ -export function useDecryptedMessage({ - message, - currentUserId, -}: UseDecryptedMessageOptions): UseDecryptedMessageResult { - const [state, setState] = useState({ - content: null, - mediaUri: null, - isDecrypting: false, - error: null, - }); - - const { privateKeyJwk, hasKeys, isLoading: keysLoading, ensureKeysUploaded } = useEncryptionKeys(); - const beginEncryptionRecovery = useAuthStore((s) => s.beginEncryptionRecovery); - const endEncryptionRecovery = useAuthStore((s) => s.endEncryptionRecovery); - - // Track per-message repair attempts to avoid tight retry loops. - const repairAttemptedByMessageId = useRef(new Set()); - const [retryNonce, setRetryNonce] = useState(0); - const autoRetryTimerRef = useRef | null>(null); - - const retry = useCallback(() => { - repairAttemptedByMessageId.current.delete(message.id); - setRetryNonce((n) => n + 1); - }, [message.id]); - - const decrypt = useCallback(async () => { - // Version 1 or undefined: Legacy plaintext message - const version = message.version ?? MESSAGE_VERSION_PLAINTEXT; - - console.log( - `[E2EE Decrypt] Message ${message.id}: version=${version}, hasEncryptedContent=${!!message.encrypted_content}, hasIV=${!!message.encryption_iv}, hasKeysMetadata=${!!message.keys_metadata}`, - ); - - if (version === MESSAGE_VERSION_PLAINTEXT) { - console.log(`[E2EE Decrypt] Message ${message.id}: Using plaintext content`); - setState({ - content: message.content, - mediaUri: null, - isDecrypting: false, - error: null, - errorCode: undefined, - }); - return; - } - - // Version 2: E2EE - requires decryption - if (version === MESSAGE_VERSION_E2EE) { - console.log(`[E2EE Decrypt] Message ${message.id}: Attempting E2EE decryption`); - - // E2EE not supported on web - if (Platform.OS === 'web') { - console.log(`[E2EE Decrypt] Message ${message.id}: Web platform - E2EE not supported`); - setState({ - content: null, - mediaUri: null, - isDecrypting: false, - error: new Error('Encrypted message'), - errorCode: 'E2EE_NOT_SUPPORTED', - }); - return; - } - - // Wait for keys to load - if (keysLoading) { - console.log(`[E2EE Decrypt] Message ${message.id}: Keys still loading, waiting...`); - setState((prev) => ({ ...prev, isDecrypting: true })); - return; - } - - if (!hasKeys || !privateKeyJwk) { - console.log( - `[E2EE Decrypt] Message ${message.id}: No keys available - hasKeys=${hasKeys}, hasPrivateKey=${!!privateKeyJwk}`, - ); - setState({ - content: null, - mediaUri: null, - isDecrypting: false, - error: new Error('Waiting for keys...'), - errorCode: 'E2EE_KEYS_UNAVAILABLE', - }); - return; - } - - // Validate required encryption fields - if (!message.encrypted_content || !message.encryption_iv || !message.keys_metadata) { - console.log( - `[E2EE Decrypt] Message ${message.id}: Missing encryption fields - encrypted_content=${!!message.encrypted_content}, encryption_iv=${!!message.encryption_iv}, keys_metadata=${!!message.keys_metadata}`, - ); - setState({ - content: null, - mediaUri: null, - isDecrypting: false, - error: new Error('Message unavailable'), - errorCode: 'E2EE_MISSING_FIELDS', - }); - return; - } - - setState((prev) => ({ ...prev, isDecrypting: true, error: null, errorCode: undefined })); - - try { - const isMe = message.user_id === currentUserId; - console.log(`[E2EE Decrypt] Message ${message.id}: Decrypting as ${isMe ? 'sender' : 'recipient'}`); - console.log( - `[E2EE Decrypt] Message ${message.id}: keys_metadata=`, - JSON.stringify(message.keys_metadata, null, 2), - ); - - const decryptedContent = await decryptTextMessage( - message.encrypted_content, - message.encryption_iv, - message.keys_metadata as KeysMetadata, - privateKeyJwk as RSAPrivateKeyJWK, - !isMe, // isRecipient - ); - - console.log( - `[E2EE Decrypt] Message ${message.id}: Decryption successful, content length=${decryptedContent.length}`, - ); - setState({ - content: decryptedContent, - mediaUri: null, - isDecrypting: false, - error: null, - errorCode: undefined, - }); - } catch (err) { - const error = err instanceof Error ? err : new Error('Unknown error'); - console.error(`[E2EE Decrypt] Message ${message.id}: Decryption failed:`, error); - - const isMe = message.user_id === currentUserId; - const isMissingWrappedKey = error.message.includes('No wrapped key available for decryption'); - const metadata = message.keys_metadata as KeysMetadata; - - // Check if this is a stale key failure (message encrypted with old key) - // This happens when: message was composed offline, recipient regenerated keys before sync - const isStaleKeyFailure = - error.name === 'OperationError' || - error.message.includes('OperationError') || - error.message.includes('decryption failed') || - error.message.includes('decrypt error') || - // react-native-quick-crypto specific error for RSA decryption failure - error.message.includes('error in DoCipher'); - - // Case 1: Missing wrapped key (pending_recipient) - // - Partner sent message before recipient had keys - // - keys_metadata has no recipient_wrapped_key - const shouldAttemptPendingRepair = - !isMe && - isMissingWrappedKey && - (!!metadata?.pending_recipient || !metadata?.recipient_wrapped_key); - - // Case 2: Stale key failure - // - Message was encrypted with old public key - // - Need admin to re-wrap with current key - const shouldAttemptStaleKeyRepair = - isStaleKeyFailure && - !isMissingWrappedKey && - !repairAttemptedByMessageId.current.has(message.id); - - if (shouldAttemptPendingRepair) { - beginEncryptionRecovery('pending-recipient'); - try { - setState({ - content: null, - mediaUri: null, - isDecrypting: true, - error: null, - errorCode: 'E2EE_PENDING_RECIPIENT_KEY', - }); - - if (!repairAttemptedByMessageId.current.has(message.id)) { - repairAttemptedByMessageId.current.add(message.id); - await reencryptPendingMessages(); - } - - // Fetch the latest keys_metadata and retry once locally. - const { data: refreshed } = await supabase - .from('messages') - .select('encrypted_content, encryption_iv, keys_metadata, user_id') - .eq('id', message.id) - .maybeSingle(); - - const refreshedMetadata = (refreshed?.keys_metadata ?? null) as KeysMetadata | null; - const refreshedEncryptedContent = refreshed?.encrypted_content ?? null; - const refreshedIv = refreshed?.encryption_iv ?? null; - - if (refreshedMetadata && refreshedEncryptedContent && refreshedIv) { - try { - const decryptedContent = await decryptTextMessage( - refreshedEncryptedContent, - refreshedIv, - refreshedMetadata, - privateKeyJwk as RSAPrivateKeyJWK, - true, // isRecipient - ); - - setState({ - content: decryptedContent, - mediaUri: null, - isDecrypting: false, - error: null, - errorCode: undefined, - }); - return; - } catch { - // Still pending (or repair failed); show the placeholder instead of a hard error. - } - } - - setState({ - content: null, - mediaUri: null, - isDecrypting: false, - error: null, - errorCode: 'E2EE_PENDING_RECIPIENT_KEY', - }); - return; - } finally { - endEncryptionRecovery(); - } - } - - if (shouldAttemptStaleKeyRepair) { - beginEncryptionRecovery('stale-key'); - let didDecrypt = false; - - try { - console.log(`[E2EE Decrypt] Message ${message.id}: Attempting stale key repair...`); - setState({ - content: null, - mediaUri: null, - isDecrypting: true, - error: null, - errorCode: 'E2EE_REPAIRING_STALE_KEY', - }); - - repairAttemptedByMessageId.current.add(message.id); - - // CRITICAL: Ensure local keys are uploaded to database BEFORE repair. - // The repair edge function uses the database public key to re-wrap. - // If the database has a stale key, repair will "succeed" but decryption will fail. - console.log(`[E2EE Decrypt] Message ${message.id}: Ensuring keys are synced before repair...`); - const keysUploaded = await ensureKeysUploaded(); - console.log(`[E2EE Decrypt] Message ${message.id}: Keys sync result: ${keysUploaded}`); - - // Run auto key rotation to re-wrap recent messages BEFORE individual repair. - // This ensures handle-key-rotation uses the correct database key. - const autoRotationResult = await triggerAutoKeyRotation(); - if (autoRotationResult) { - console.log(`[E2EE Decrypt] Message ${message.id}: Auto rotation completed: ${autoRotationResult.updated} messages updated`); - } - - try { - const repairResult = await repairStaleKey(message.id); - - if (repairResult.success) { - console.log(`[E2EE Decrypt] Message ${message.id}: Stale key repaired, retrying decryption...`); - - // Fetch updated message and retry - const { data: refreshed } = await supabase - .from('messages') - .select('encrypted_content, encryption_iv, keys_metadata, user_id') - .eq('id', message.id) - .maybeSingle(); - - const refreshedMetadata = (refreshed?.keys_metadata ?? null) as KeysMetadata | null; - const refreshedEncryptedContent = refreshed?.encrypted_content ?? null; - const refreshedIv = refreshed?.encryption_iv ?? null; - - // Log key metadata for debugging - console.log(`[E2EE Decrypt] Message ${message.id}: Refreshed metadata:`, { - hasSenderKey: !!refreshedMetadata?.sender_wrapped_key, - hasRecipientKey: !!refreshedMetadata?.recipient_wrapped_key, - adminKeyId: refreshedMetadata?.admin_key_id, - isRecipient: !isMe, - }); - - if (refreshedMetadata && refreshedEncryptedContent && refreshedIv) { - const decryptedContent = await decryptTextMessage( - refreshedEncryptedContent, - refreshedIv, - refreshedMetadata, - privateKeyJwk as RSAPrivateKeyJWK, - !isMe, // isRecipient - ); - - setState({ - content: decryptedContent, - mediaUri: null, - isDecrypting: false, - error: null, - errorCode: undefined, - }); - didDecrypt = true; - return; - } - } else { - console.error(`[E2EE Decrypt] Message ${message.id}: Stale key repair failed:`, repairResult.error); - } - } catch (repairErr) { - // Note: This catch includes decryption errors after successful repair - console.error(`[E2EE Decrypt] Message ${message.id}: Decryption retry failed after repair:`, repairErr); - } - - // Repair failed or retry failed - setState({ - content: null, - mediaUri: null, - isDecrypting: false, - error: new Error('Waiting for message...'), - errorCode: 'E2EE_DECRYPT_FAILED', - }); - return; - } finally { - if (!didDecrypt) { - // Schedule another retry after a delay - keys may sync in the background - retry(); - } - endEncryptionRecovery(); - } - } - - setState({ - content: null, - mediaUri: null, - isDecrypting: false, - error: new Error('Waiting for message...'), - errorCode: 'E2EE_DECRYPT_FAILED', - }); - } - } - }, [ - message.id, - message.version, - message.content, - message.encrypted_content, - message.encryption_iv, - message.keys_metadata, - message.user_id, - currentUserId, - privateKeyJwk, - hasKeys, - keysLoading, - retryNonce, - beginEncryptionRecovery, - endEncryptionRecovery, - retry, - ensureKeysUploaded, - ]); - - useEffect(() => { - decrypt(); - }, [decrypt, retryNonce]); - - useEffect(() => { - return () => { - if (autoRetryTimerRef.current) { - clearTimeout(autoRetryTimerRef.current); - autoRetryTimerRef.current = null; - } - }; - }, [message.id]); - - useEffect(() => { - if (!state.errorCode) { - autoRetryCountsByMessageId.delete(message.id); - if (autoRetryTimerRef.current) { - clearTimeout(autoRetryTimerRef.current); - autoRetryTimerRef.current = null; - } - return; - } - - const shouldRetry = - state.errorCode === 'E2EE_PENDING_RECIPIENT_KEY' || - state.errorCode === 'E2EE_KEYS_UNAVAILABLE'; - - if (!shouldRetry) { - return; - } - - const attempts = autoRetryCountsByMessageId.get(message.id) ?? 0; - if (attempts >= MAX_AUTO_RETRIES) { - return; - } - - const nextAttempt = attempts + 1; - const delayMs = AUTO_RETRY_BASE_DELAY_MS * nextAttempt; - - autoRetryCountsByMessageId.set(message.id, nextAttempt); - - autoRetryTimerRef.current = setTimeout(() => { - retry(); - }, delayMs); - - return () => { - if (autoRetryTimerRef.current) { - clearTimeout(autoRetryTimerRef.current); - autoRetryTimerRef.current = null; - } - }; - }, [message.id, state.errorCode, retry]); - - return { ...state, retry }; -} diff --git a/apps/mobile/src/hooks/useEncryptedSend.ts b/apps/mobile/src/hooks/useEncryptedSend.ts deleted file mode 100644 index 11f0cce..0000000 --- a/apps/mobile/src/hooks/useEncryptedSend.ts +++ /dev/null @@ -1,349 +0,0 @@ -/** - * useEncryptedSend Hook - * - * Hook for sending encrypted messages via E2EE. - * Handles encryption with triple-wrapped keys (sender, recipient, admin). - * - * IMPORTANT: This hook reads keys from the global Zustand store to ensure - * consistency with all other encryption operations. - */ - -import { useCallback, useEffect, useRef, useState } from 'react'; -import { Platform } from 'react-native'; -import { - encryptTextMessage, - decryptTextMessage, - getAdminPublicKey, - getAdminKeyId, - isValidPublicKeyJwk, - sanitizePublicKeyJwk, - verifyKeyPair, -} from '../lib/encryption'; -import type { RSAPublicKeyJWK, EncryptedMessagePayload } from '../lib/encryption'; -import { useEncryptionKeys } from './useEncryptionKeys'; -import { useAuthStore } from '../store'; -import { captureError } from '../lib/sentry'; - -interface UseEncryptedSendReturn { - /** Encrypt a text message for sending */ - encryptMessage: (plaintext: string) => Promise; - /** Whether E2EE is available (keys loaded, not on web) */ - isE2EEAvailable: boolean; - /** Whether the admin key is available and valid */ - isAdminKeyReady: boolean; - /** Whether encryption is currently in progress */ - isEncrypting: boolean; - /** Last encryption error, if any */ - error: Error | null; -} - -/** - * Hook for encrypting messages before sending - * - * Throws if E2EE is not available or keys are not ready. - */ -export function useEncryptedSend(): UseEncryptedSendReturn { - const [isEncrypting, setIsEncrypting] = useState(false); - const [error, setError] = useState(null); - const [isAdminKeyReady, setIsAdminKeyReady] = useState(false); - - // Track the version of keys we have verified to handle key rotation/regeneration - const verifiedKeysVersionRef = useRef(null); - const partnerRefreshRef = useRef(0); - const adminKeyRetryRef = useRef(0); - const PARTNER_REFRESH_TTL_MS = 2 * 60 * 1000; - const ADMIN_KEY_RETRY_DELAYS = [500, 1000, 2000, 4000]; // Exponential backoff delays in ms - - const { publicKeyJwk, privateKeyJwk, hasKeys, isLoading } = useEncryptionKeys(); - const refreshPartner = useAuthStore((s) => s.refreshPartner); - const user = useAuthStore((s) => s.user); - - // E2EE is available if: - // - Not on web platform - // - Keys are loaded and available - const isE2EEAvailable = - Platform.OS !== 'web' && hasKeys && !isLoading && !!publicKeyJwk && !!privateKeyJwk; - - useEffect(() => { - let isMounted = true; - let retryTimeoutId: ReturnType | null = null; - - const checkAdminKey = async (retryCount = 0) => { - if (!isE2EEAvailable) { - if (isMounted) { - setIsAdminKeyReady(false); - } - return; - } - - try { - const adminPublicKey = await getAdminPublicKey(); - const adminKeyId = await getAdminKeyId(); - - if (!adminKeyId || !isValidPublicKeyJwk(adminPublicKey)) { - throw new Error('Admin public key is invalid'); - } - - if (isMounted) { - setIsAdminKeyReady(true); - adminKeyRetryRef.current = 0; // Reset retry count on success - } - } catch (adminKeyError) { - console.warn(`[E2EE Send] Admin key not ready (attempt ${retryCount + 1}):`, adminKeyError); - if (isMounted) { - setIsAdminKeyReady(false); - - // Retry with exponential backoff if we haven't exhausted retries - if (retryCount < ADMIN_KEY_RETRY_DELAYS.length) { - const delay = ADMIN_KEY_RETRY_DELAYS[retryCount]; - console.log(`[E2EE Send] Retrying admin key fetch in ${delay}ms...`); - retryTimeoutId = setTimeout(() => { - if (isMounted) { - checkAdminKey(retryCount + 1); - } - }, delay); - } else { - console.warn('[E2EE Send] Admin key fetch failed after all retries'); - } - } - } - }; - - checkAdminKey(); - - return () => { - isMounted = false; - if (retryTimeoutId) { - clearTimeout(retryTimeoutId); - } - }; - }, [isE2EEAvailable]); - - const encryptMessage = useCallback( - async (plaintext: string): Promise => { - // Block sending until E2EE is ready - if (!isE2EEAvailable) { - const readyError = new Error('Message security not ready. Please check your connection.'); - console.warn('[E2EE Send] E2EE not available'); - setError(readyError); - throw readyError; - } - - // CRITICAL: Read keys directly from the global store at encryption time - // This ensures we always use the most current keys, not potentially stale hook state - const currentKeys = useAuthStore.getState().encryptionKeys; - - if (!currentKeys.hasKeys || !currentKeys.publicKeyJwk || !currentKeys.privateKeyJwk) { - // User-friendly error - const keysError = new Error('Message security not ready. Please check your connection.'); - console.warn('[E2EE Send] Keys not fully available in global store'); - setError(keysError); - throw keysError; - } - - const senderPublicKey = currentKeys.publicKeyJwk; - const senderPrivateKey = currentKeys.privateKeyJwk; - - // SAFETY CHECK: Verify the key pair works together before encrypting - // This prevents creating unrecoverable messages if keys are mismatched. - // We check if the current keys version matches what we last verified. - if (verifiedKeysVersionRef.current !== currentKeys.keysVersion) { - console.log( - `[E2EE Send] Verifying sender key pair (version ${currentKeys.keysVersion})...` - ); - const isValidKeyPair = await verifyKeyPair( - senderPublicKey as RSAPublicKeyJWK, - senderPrivateKey - ); - - if (!isValidKeyPair) { - // User-friendly error - const keyError = new Error('Security check failed. Please restart the app.'); - console.error('[E2EE Send] CRITICAL: Sender key pair verification failed!'); - setError(keyError); - throw keyError; - } - - verifiedKeysVersionRef.current = currentKeys.keysVersion; - console.log('[E2EE Send] Sender key pair verified successfully'); - } - - console.log( - '[E2EE Send] Using sender public key from global store, version:', - currentKeys.keysVersion - ); - - setIsEncrypting(true); - setError(null); - - try { - // Refresh partner's profile only when key is missing/invalid or TTL expires - const resolvePartnerProfile = async () => { - const cachedPartner = useAuthStore.getState().partner; - const cachedKey = cachedPartner?.public_key_jwk as RSAPublicKeyJWK | null | undefined; - const hasValidKey = cachedKey ? isValidPublicKeyJwk(cachedKey) : false; - const now = Date.now(); - const shouldRefresh = !hasValidKey || (now - partnerRefreshRef.current) > PARTNER_REFRESH_TTL_MS; - - if (!shouldRefresh) { - return cachedPartner; - } - - console.log('[E2EE Send] Refreshing partner profile to get latest public key...'); - try { - const freshPartner = await refreshPartner(); - partnerRefreshRef.current = Date.now(); - return freshPartner ?? useAuthStore.getState().partner; - } catch (refreshError) { - console.warn('[E2EE Send] Partner refresh failed, using cached key:', refreshError); - partnerRefreshRef.current = Date.now(); - return cachedPartner; - } - }; - - const freshPartner = await resolvePartnerProfile(); - - // Get admin key for moderation access - // SAFETY: Validate the admin key before using it - let adminPublicKey: RSAPublicKeyJWK; - let adminKeyId: string; - - try { - adminPublicKey = await getAdminPublicKey(); - adminKeyId = await getAdminKeyId(); - - // Validate admin key structure - if (!isValidPublicKeyJwk(adminPublicKey)) { - const adminError = new Error('Connection issue. Please try again.'); - console.error('[E2EE Send] Admin public key is invalid'); - setIsEncrypting(false); - setError(adminError); - throw adminError; - } - } catch (adminKeyError) { - // Re-throw if already a user-facing error - if (adminKeyError instanceof Error && ( - adminKeyError.message.includes('Connection issue') || - adminKeyError.message.includes('Unable to secure') - )) { - throw adminKeyError; - } - const fetchError = new Error('Connection issue. Please try again.'); - console.error('[E2EE Send] Failed to fetch admin key:', adminKeyError); - setIsEncrypting(false); - setError(fetchError); - throw fetchError; - } - - // Get partner's public key from the freshly fetched profile - let partnerPublicKey = freshPartner?.public_key_jwk as - | RSAPublicKeyJWK - | null - | undefined; - - // Validate and sanitize partner's public key - if (partnerPublicKey) { - if (!isValidPublicKeyJwk(partnerPublicKey)) { - console.warn('[E2EE Send] Partner public key is invalid, treating as unavailable'); - partnerPublicKey = null; - } else { - // Sanitize to remove trailing dots from base64 fields (react-native-quick-crypto bug) - partnerPublicKey = sanitizePublicKeyJwk(partnerPublicKey); - } - } - - console.log('[E2EE Send] Partner public key available:', !!partnerPublicKey); - - let lastPayload: EncryptedMessagePayload | null = null; - - const encryptAndVerify = async (): Promise => { - const payload = await encryptTextMessage( - plaintext, - senderPublicKey as RSAPublicKeyJWK, - partnerPublicKey ?? null, - adminPublicKey, - adminKeyId - ); - - lastPayload = payload; - - const decrypted = await decryptTextMessage( - payload.encrypted_content, - payload.encryption_iv, - payload.keys_metadata, - senderPrivateKey, - false - ); - - if (decrypted !== plaintext) { - throw new Error('E2EE payload verification mismatch'); - } - - return payload; - }; - - const maxAttempts = 2; - let encryptedPayload: EncryptedMessagePayload | null = null; - - for (let attempt = 1; attempt <= maxAttempts; attempt++) { - try { - encryptedPayload = await encryptAndVerify(); - break; - } catch (verifyError) { - console.warn(`[E2EE Send] Payload verification failed (attempt ${attempt})`, verifyError); - - if (attempt === maxAttempts) { - const errorInstance = - verifyError instanceof Error - ? verifyError - : new Error('E2EE payload verification failed'); - - const lastPayloadData = lastPayload as EncryptedMessagePayload | null; - - captureError(errorInstance, { - stage: 'encrypt_verify', - attempt, - max_attempts: maxAttempts, - plaintext_length: plaintext.length, - encrypted_content_length: lastPayloadData?.encrypted_content.length ?? null, - encryption_iv_length: lastPayloadData?.encryption_iv.length ?? null, - admin_key_id: lastPayloadData?.keys_metadata?.admin_key_id ?? null, - pending_recipient: lastPayloadData?.keys_metadata?.pending_recipient ?? null, - has_partner_key: !!partnerPublicKey, - keys_version: currentKeys.keysVersion, - platform: Platform.OS, - user_id: user?.id ?? null, - }); - - throw new Error('Security check failed. Please try again.'); - } - } - } - - if (!encryptedPayload) { - throw new Error('Security check failed. Please try again.'); - } - - console.log('[E2EE Send] Message encrypted successfully'); - - setIsEncrypting(false); - return encryptedPayload; - } catch (err) { - console.error('[E2EE Send] Failed to encrypt message:', err); - setError(err as Error); - setIsEncrypting(false); - // Re-throw to block sending - never fall back to plaintext - throw err; - } - }, - [isE2EEAvailable, refreshPartner] - ); - - return { - encryptMessage, - isE2EEAvailable, - isAdminKeyReady, - isEncrypting, - error, - }; -} diff --git a/apps/mobile/src/hooks/useEncryptionKeys.ts b/apps/mobile/src/hooks/useEncryptionKeys.ts deleted file mode 100644 index c0b6360..0000000 --- a/apps/mobile/src/hooks/useEncryptionKeys.ts +++ /dev/null @@ -1,426 +0,0 @@ -/** - * useEncryptionKeys Hook - * - * React hook for managing E2EE encryption keys. - * Uses global Zustand store to ensure all components share the same key state. - * - * IMPORTANT: This hook reads from and writes to the global authStore.encryptionKeys - * to prevent race conditions where different hook instances have different state. - */ - -import { useCallback, useRef, useEffect } from 'react'; -import { Platform } from 'react-native'; -import { - generateAndStoreKeyPair, - getPrivateKey, - getLocalPublicKey, - hasKeyPair, - isPublicKeyUploaded, - markPublicKeyUploaded, - isValidPublicKeyJwk, - sanitizePublicKeyJwk, -} from '../lib/encryption'; -import type { RSAPublicKeyJWK } from '../lib/encryption'; -import { supabase } from '../lib/supabase'; -// Import directly from authStore to avoid circular dependency with store/index.ts -import { useAuthStore } from '../store/authStore'; - -interface UseEncryptionKeysReturn { - /** RSA private key in JWK format */ - privateKeyJwk: RSAPublicKeyJWK | null; - /** RSA public key in JWK format */ - publicKeyJwk: RSAPublicKeyJWK | null; - /** Whether keys are currently being loaded */ - isLoading: boolean; - /** Whether valid keys exist */ - hasKeys: boolean; - /** Any error that occurred */ - error: Error | null; - /** Initialize keys and upload to Supabase - does everything in one call */ - initializeAndUploadKeys: () => Promise<{ wasRegenerated: boolean }>; - /** Refresh the key state from storage */ - refresh: () => Promise; - /** Ensure local keys are uploaded to database. Blocks until complete. */ - ensureKeysUploaded: () => Promise; -} - -// Global promise to track in-flight key loading across all hook instances -let globalLoadKeysPromise: Promise | null = null; - -/** - * Hook for accessing and managing encryption keys. - * - * All key state is stored in the global Zustand store to ensure - * all components see the same keys at all times. - */ -export function useEncryptionKeys(): UseEncryptionKeysReturn { - // Get global state and actions from Zustand store - const encryptionKeys = useAuthStore((s) => s.encryptionKeys); - const setEncryptionKeys = useAuthStore((s) => s.setEncryptionKeys); - const user = useAuthStore((s) => s.user); - - // Track if we've already loaded keys in this session - const hasLoadedRef = useRef(false); - const isLoadingRef = useRef(false); - - /** - * Load existing keys from SecureStore into global state - */ - const loadKeys = useCallback(async () => { - // E2EE not supported on web - if (Platform.OS === 'web') { - setEncryptionKeys({ - privateKeyJwk: null, - publicKeyJwk: null, - isLoadingKeys: false, - hasKeys: false, - keysError: null, - }); - return null; - } - - // If keys are already loaded in global store, return them - if (encryptionKeys.hasKeys && encryptionKeys.publicKeyJwk) { - return encryptionKeys.publicKeyJwk; - } - - // If there's an in-flight global load, return that promise - if (globalLoadKeysPromise) { - console.log('[E2EE Global] Joining existing key load operation'); - return globalLoadKeysPromise; - } - - // Prevent concurrent loads (local check) - if (isLoadingRef.current) { - return encryptionKeys.publicKeyJwk; - } - - const task = async () => { - try { - isLoadingRef.current = true; - setEncryptionKeys({ isLoadingKeys: true, keysError: null }); - - const keysExist = await hasKeyPair(); - if (keysExist) { - const [privateKey, publicKey] = await Promise.all([ - getPrivateKey(), - getLocalPublicKey(), - ]); - - console.log('[E2EE Global] Keys loaded from storage'); - - setEncryptionKeys({ - privateKeyJwk: privateKey, - publicKeyJwk: publicKey, - isLoadingKeys: false, - hasKeys: true, - keysError: null, - }); - - hasLoadedRef.current = true; - return publicKey; - } else { - console.log('[E2EE Global] No keys in storage'); - setEncryptionKeys({ - privateKeyJwk: null, - publicKeyJwk: null, - isLoadingKeys: false, - hasKeys: false, - keysError: null, - }); - return null; - } - } catch (error) { - console.error('[E2EE Global] Failed to load encryption keys:', error); - setEncryptionKeys({ - privateKeyJwk: null, - publicKeyJwk: null, - isLoadingKeys: false, - hasKeys: false, - keysError: error as Error, - }); - return null; - } finally { - isLoadingRef.current = false; - } - }; - - // Assign to global promise - globalLoadKeysPromise = task().finally(() => { - globalLoadKeysPromise = null; - }); - - return globalLoadKeysPromise; - }, [encryptionKeys.publicKeyJwk, encryptionKeys.hasKeys, setEncryptionKeys]); - - /** - * Initialize encryption keys and upload to Supabase in one operation. - * This avoids race conditions between state updates and upload. - * - * @returns { wasRegenerated: boolean } - true if keys were newly generated or regenerated - */ - const initializeAndUploadKeys = useCallback(async (): Promise<{ - wasRegenerated: boolean; - }> => { - if (Platform.OS === 'web') { - console.warn('[E2EE Global] E2EE not supported on web'); - return { wasRegenerated: false }; - } - - if (!user?.id) { - console.warn('[E2EE Global] Cannot initialize keys: user not authenticated'); - return { wasRegenerated: false }; - } - - // Prevent concurrent initialization - if (isLoadingRef.current) { - console.log('[E2EE Global] Key initialization already in progress'); - return { wasRegenerated: false }; - } - - try { - isLoadingRef.current = true; - setEncryptionKeys({ isLoadingKeys: true, keysError: null }); - - let publicKey: RSAPublicKeyJWK | null = null; - let privateKey = null; - let wasRegenerated = false; - - const keysExist = await hasKeyPair(); - - if (!keysExist) { - // Generate new key pair - console.log('[E2EE Global] Generating new key pair...'); - publicKey = await generateAndStoreKeyPair(); - privateKey = await getPrivateKey(); - wasRegenerated = true; - - // Update global state IMMEDIATELY with new keys - setEncryptionKeys({ - privateKeyJwk: privateKey, - publicKeyJwk: publicKey, - isLoadingKeys: false, - hasKeys: true, - keysError: null, - }); - - console.log('[E2EE Global] Key pair generated and stored in global state'); - } else { - // Load existing keys - [privateKey, publicKey] = await Promise.all([ - getPrivateKey(), - getLocalPublicKey(), - ]); - - // Update global state with loaded keys - setEncryptionKeys({ - privateKeyJwk: privateKey, - publicKeyJwk: publicKey, - isLoadingKeys: false, - hasKeys: true, - keysError: null, - }); - } - - // Validate keys - if (!publicKey || !isValidPublicKeyJwk(publicKey)) { - if (publicKey) { - console.warn( - '[E2EE Global] Local public key invalid, regenerating...' - ); - } else { - console.warn( - '[E2EE Global] Local public key missing, regenerating...' - ); - } - - publicKey = await generateAndStoreKeyPair(); - privateKey = await getPrivateKey(); - wasRegenerated = true; - - // Update global state IMMEDIATELY with regenerated keys - setEncryptionKeys({ - privateKeyJwk: privateKey, - publicKeyJwk: publicKey, - isLoadingKeys: false, - hasKeys: true, - keysError: null, - }); - - console.log('[E2EE Global] Keys regenerated and stored in global state'); - } - - // Fetch the server copy to verify validity and avoid stale uploads - const { data: profile, error: profileError } = await supabase - .from('profiles') - .select('public_key_jwk') - .eq('id', user.id) - .maybeSingle(); - - if (profileError) { - throw profileError; - } - - const remoteKey = (profile?.public_key_jwk ?? null) as RSAPublicKeyJWK | null; - const remoteValid = isValidPublicKeyJwk(remoteKey); - const localValid = isValidPublicKeyJwk(publicKey); - - // Sanitize both keys before comparing (local key may have trailing dots) - const sanitizedLocal = sanitizePublicKeyJwk(publicKey!); - const sanitizedRemote = remoteKey ? sanitizePublicKeyJwk(remoteKey) : null; - const sameKey = - remoteValid && - localValid && - sanitizedRemote?.n === sanitizedLocal.n && - sanitizedRemote?.e === sanitizedLocal.e; - - // Upload if remote key is missing/invalid or doesn't match local. - // If we just regenerated the key, we MUST upload it regardless - if (publicKey && localValid && !sameKey) { - // Treat a mismatch as regeneration so we trigger key rotation later. - wasRegenerated = true; - } - - if ((publicKey && localValid && !sameKey) || (publicKey && wasRegenerated)) { - console.log('[E2EE Global] Uploading public key to profile...'); - - // Sanitize key before upload - const sanitizedKey = sanitizePublicKeyJwk(publicKey); - - const { error } = await supabase - .from('profiles') - .update({ - public_key_jwk: sanitizedKey as unknown as Record, - }) - .eq('id', user.id); - - if (error) { - throw error; - } - - await markPublicKeyUploaded(); - console.log('[E2EE Global] Public key uploaded successfully'); - } else if (sameKey) { - const alreadyUploaded = await isPublicKeyUploaded(); - if (!alreadyUploaded) { - await markPublicKeyUploaded(); - } - console.log('[E2EE Global] Public key already uploaded and valid'); - } - - hasLoadedRef.current = true; - return { wasRegenerated }; - } catch (error) { - console.error('[E2EE Global] Failed to initialize encryption keys:', error); - setEncryptionKeys({ - isLoadingKeys: false, - keysError: error as Error, - }); - throw error; - } finally { - isLoadingRef.current = false; - } - }, [user?.id, setEncryptionKeys]); - - /** - * Refresh keys from storage - */ - const refresh = useCallback(async () => { - hasLoadedRef.current = false; - await loadKeys(); - }, [loadKeys]); - - /** - * Ensure local keys are uploaded to database. - * Blocks until upload is complete or fails. - * This is critical for E2EE repair flows where the edge function needs - * the current public key to re-wrap message AES keys. - */ - const ensureKeysUploaded = useCallback(async (): Promise => { - if (Platform.OS === 'web') { - console.log('[E2EE] ensureKeysUploaded: Web platform, skipping'); - return false; - } - - if (!user?.id) { - console.log('[E2EE] ensureKeysUploaded: No user ID, skipping'); - return false; - } - - try { - // Check if local key matches database key - const { data: profile, error: profileError } = await supabase - .from('profiles') - .select('public_key_jwk') - .eq('id', user.id) - .maybeSingle(); - - if (profileError) { - console.error('[E2EE] ensureKeysUploaded: Failed to fetch profile:', profileError); - // Fall through to initializeAndUploadKeys which will handle this - } - - const remoteKey = (profile?.public_key_jwk ?? null) as RSAPublicKeyJWK | null; - const localKey = encryptionKeys.publicKeyJwk; - - if (!localKey) { - // No local key, need to initialize - console.log('[E2EE] ensureKeysUploaded: No local key, initializing...'); - await initializeAndUploadKeys(); - return true; - } - - // Compare keys (sanitize both for accurate comparison) - const sanitizedLocal = sanitizePublicKeyJwk(localKey); - const sanitizedRemote = remoteKey ? sanitizePublicKeyJwk(remoteKey) : null; - - const keysMatch = sanitizedRemote && - sanitizedLocal.n === sanitizedRemote.n && - sanitizedLocal.e === sanitizedRemote.e; - - if (!keysMatch) { - // Mismatch - upload local key - console.log('[E2EE] ensureKeysUploaded: Key mismatch detected, uploading local key...'); - await initializeAndUploadKeys(); - return true; - } - - console.log('[E2EE] ensureKeysUploaded: Keys already synced'); - return true; - } catch (error) { - console.error('[E2EE] ensureKeysUploaded: Error:', error); - // Try to initialize anyway as a fallback - try { - await initializeAndUploadKeys(); - return true; - } catch { - return false; - } - } - }, [user?.id, encryptionKeys.publicKeyJwk, initializeAndUploadKeys]); - - // Load keys on mount if not already loaded - useEffect(() => { - if (!hasLoadedRef.current && !isLoadingRef.current && !encryptionKeys.hasKeys) { - loadKeys(); - } - }, [loadKeys, encryptionKeys.hasKeys]); - - // Reset loaded flag when user changes - useEffect(() => { - if (!user?.id) { - hasLoadedRef.current = false; - } - }, [user?.id]); - - return { - privateKeyJwk: encryptionKeys.privateKeyJwk, - publicKeyJwk: encryptionKeys.publicKeyJwk, - isLoading: encryptionKeys.isLoadingKeys, - hasKeys: encryptionKeys.hasKeys, - error: encryptionKeys.keysError, - initializeAndUploadKeys, - refresh, - ensureKeysUploaded, - }; -} diff --git a/apps/mobile/src/lib/encryption/adminKeys.ts b/apps/mobile/src/lib/encryption/adminKeys.ts deleted file mode 100644 index 42c87b7..0000000 --- a/apps/mobile/src/lib/encryption/adminKeys.ts +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Admin Keys Management - * - * Fetches the active admin public key from the master_keys table. - */ - -import { supabase } from '../supabase'; -import type { MasterKey, RSAPublicKeyJWK } from './types'; - -// Cache for admin key to avoid repeated database calls -let cachedAdminKey: MasterKey | null = null; -let cacheTimestamp: number = 0; -const CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes - -/** - * Fetch the active admin public key from the database - * - * Results are cached for 5 minutes to reduce database calls. - * - * @param forceRefresh - Force a fresh fetch, bypassing cache - * @returns The active master key record - */ -export async function getActiveMasterKey(forceRefresh = false): Promise { - const now = Date.now(); - - // Return cached key if still valid - if (!forceRefresh && cachedAdminKey && (now - cacheTimestamp) < CACHE_TTL_MS) { - return cachedAdminKey; - } - - const { data, error } = await supabase - .from('master_keys') - .select('*') - .eq('is_active', true) - .limit(1) - .maybeSingle(); - - if (error) { - throw new Error(`Failed to fetch admin key: ${error.message}`); - } - - if (!data) { - throw new Error('No active admin key found. E2EE is not configured.'); - } - - // Validate the key structure - const publicKeyJwk = data.public_key_jwk as RSAPublicKeyJWK; - if (!publicKeyJwk || publicKeyJwk.kty !== 'RSA') { - throw new Error('Invalid admin public key format'); - } - - cachedAdminKey = { - id: data.id, - key_name: data.key_name, - public_key_jwk: publicKeyJwk, - is_active: data.is_active ?? true, - created_at: data.created_at ?? '', - rotated_at: data.rotated_at, - }; - cacheTimestamp = now; - - return cachedAdminKey; -} - -/** - * Get the admin public key JWK directly - */ -export async function getAdminPublicKey(): Promise { - const masterKey = await getActiveMasterKey(); - return masterKey.public_key_jwk; -} - -/** - * Get the admin key ID for storing in message metadata - */ -export async function getAdminKeyId(): Promise { - const masterKey = await getActiveMasterKey(); - return masterKey.id; -} - -/** - * Clear the admin key cache - * Called when keys might have been rotated - */ -export function clearAdminKeyCache(): void { - cachedAdminKey = null; - cacheTimestamp = 0; -} diff --git a/apps/mobile/src/lib/encryption/constants.ts b/apps/mobile/src/lib/encryption/constants.ts deleted file mode 100644 index 76b2a2b..0000000 --- a/apps/mobile/src/lib/encryption/constants.ts +++ /dev/null @@ -1,30 +0,0 @@ -/** - * E2EE Constants - * - * Algorithm identifiers and storage key names for encryption - */ - -// SecureStore key names for private key storage -export const PRIVATE_KEY_PREFIX = 'e2ee_private_key_chunk_'; -export const PUBLIC_KEY_UPLOADED = 'e2ee_public_key_uploaded'; -export const LOCAL_PUBLIC_KEY = 'e2ee_local_public_key'; - -// Encryption algorithms -export const SYMMETRIC_ALGORITHM = 'AES-GCM'; -export const SYMMETRIC_KEY_LENGTH = 256; -export const IV_LENGTH_BYTES = 12; // 96 bits for AES-GCM - -// Key wrapping -export const KEY_WRAP_ALGORITHM = 'RSA-OAEP'; -export const KEY_WRAP_HASH = 'SHA-256'; -export const RSA_KEY_SIZE = 2048; - -// SecureStore chunking (RSA-2048 JWK is ~1.7KB, SecureStore limit is 2KB) -export const SECURE_STORE_CHUNK_SIZE = 1900; - -// Default master key name -export const DEFAULT_MASTER_KEY_NAME = 'e2ee_admin_key_v1'; - -// Message version constants -export const MESSAGE_VERSION_PLAINTEXT = 1; -export const MESSAGE_VERSION_E2EE = 2; diff --git a/apps/mobile/src/lib/encryption/crypto.ts b/apps/mobile/src/lib/encryption/crypto.ts deleted file mode 100644 index 33550d1..0000000 --- a/apps/mobile/src/lib/encryption/crypto.ts +++ /dev/null @@ -1,226 +0,0 @@ -/** - * Low-level Crypto Operations - * - * AES-256-GCM encryption/decryption and RSA key wrapping operations. - */ - -import { - SYMMETRIC_ALGORITHM, - SYMMETRIC_KEY_LENGTH, - IV_LENGTH_BYTES, - KEY_WRAP_ALGORITHM -} from './constants'; -import { arrayBufferToBase64, base64ToArrayBuffer } from './utils'; -import type { RSAPublicKeyJWK, RSAPrivateKeyJWK } from './types'; -import { importPublicKey, importPrivateKey } from './keyManager'; - -/** - * Get the Web Crypto API - */ -function getSubtle(): SubtleCrypto { - if (typeof crypto !== 'undefined' && crypto.subtle) { - return crypto.subtle; - } - throw new Error('Web Crypto API not available'); -} - -/** - * Get crypto.getRandomValues - */ -function getRandomValues(array: Uint8Array): Uint8Array { - if (typeof crypto !== 'undefined' && crypto.getRandomValues) { - return crypto.getRandomValues(array); - } - throw new Error('Crypto random not available'); -} - -/** - * Generate a random AES-256 key - */ -export async function generateAESKey(): Promise { - const subtle = getSubtle(); - - return await subtle.generateKey( - { name: SYMMETRIC_ALGORITHM, length: SYMMETRIC_KEY_LENGTH }, - true, - ['encrypt', 'decrypt'] - ); -} - -/** - * Generate a random initialization vector for AES-GCM (12 bytes) - */ -export function generateIV(): Uint8Array { - return getRandomValues(new Uint8Array(IV_LENGTH_BYTES)); -} - -/** - * Encrypt data with AES-256-GCM - * - * @param plaintext - The data to encrypt (string or ArrayBuffer) - * @param key - The AES key - * @param iv - The initialization vector - * @returns The encrypted ciphertext as ArrayBuffer - */ -export async function encryptAES( - plaintext: string | ArrayBuffer, - key: CryptoKey, - iv: Uint8Array -): Promise { - const subtle = getSubtle(); - - const data = typeof plaintext === 'string' - ? new TextEncoder().encode(plaintext) - : plaintext; - - return await subtle.encrypt( - { name: SYMMETRIC_ALGORITHM, iv: iv as BufferSource }, - key, - data - ); -} - -/** - * Decrypt data with AES-256-GCM - * - * @param ciphertext - The encrypted data - * @param key - The AES key - * @param iv - The initialization vector - * @returns The decrypted plaintext as ArrayBuffer - */ -export async function decryptAES( - ciphertext: ArrayBuffer, - key: CryptoKey, - iv: Uint8Array -): Promise { - const subtle = getSubtle(); - - return await subtle.decrypt( - { name: SYMMETRIC_ALGORITHM, iv: iv as BufferSource }, - key, - ciphertext - ); -} - -/** - * Export an AES key to raw bytes - */ -export async function exportAESKey(key: CryptoKey): Promise { - const subtle = getSubtle(); - return await subtle.exportKey('raw', key); -} - -/** - * Import an AES key from raw bytes - */ -export async function importAESKey(rawKey: ArrayBuffer): Promise { - const subtle = getSubtle(); - - return await subtle.importKey( - 'raw', - rawKey, - { name: SYMMETRIC_ALGORITHM }, - false, - ['decrypt'] - ); -} - -/** - * Wrap (encrypt) an AES key with an RSA public key - * - * @param aesKeyRaw - The raw AES key bytes - * @param publicKeyJwk - The recipient's RSA public key - * @returns The wrapped key as base64 string - */ -export async function wrapAESKey( - aesKeyRaw: ArrayBuffer, - publicKeyJwk: RSAPublicKeyJWK -): Promise { - const subtle = getSubtle(); - const rsaKey = await importPublicKey(publicKeyJwk); - - const wrappedKey = await subtle.encrypt( - { name: KEY_WRAP_ALGORITHM }, - rsaKey, - aesKeyRaw - ); - - return arrayBufferToBase64(wrappedKey); -} - -/** - * Unwrap (decrypt) an AES key with an RSA private key - * - * @param wrappedKeyBase64 - The wrapped key as base64 string - * @param privateKeyJwk - The user's RSA private key - * @returns The unwrapped AES key as ArrayBuffer - */ -export async function unwrapAESKey( - wrappedKeyBase64: string, - privateKeyJwk: RSAPrivateKeyJWK -): Promise { - const subtle = getSubtle(); - const rsaKey = await importPrivateKey(privateKeyJwk); - const wrappedKey = base64ToArrayBuffer(wrappedKeyBase64); - - return await subtle.decrypt( - { name: KEY_WRAP_ALGORITHM }, - rsaKey, - wrappedKey - ); -} - -/** - * Verify that a public/private key pair actually work together. - * This catches key mismatches that could cause unrecoverable encrypted messages. - * - * @param publicKeyJwk - The RSA public key - * @param privateKeyJwk - The RSA private key - * @returns true if the keys work together, false otherwise - */ -export async function verifyKeyPair( - publicKeyJwk: RSAPublicKeyJWK, - privateKeyJwk: RSAPrivateKeyJWK -): Promise { - try { - const subtle = getSubtle(); - - // Create test data (32 bytes - same as AES-256 key) - const testData = getRandomValues(new Uint8Array(32)); - - // Import keys - const publicKey = await importPublicKey(publicKeyJwk); - const privateKey = await importPrivateKey(privateKeyJwk); - - // Encrypt with public key - const encrypted = await subtle.encrypt( - { name: KEY_WRAP_ALGORITHM }, - publicKey, - testData as BufferSource - ); - - // Decrypt with private key - const decrypted = await subtle.decrypt( - { name: KEY_WRAP_ALGORITHM }, - privateKey, - encrypted - ); - - // Verify the data matches - const decryptedArray = new Uint8Array(decrypted); - if (decryptedArray.length !== testData.length) { - return false; - } - - for (let i = 0; i < testData.length; i++) { - if (testData[i] !== decryptedArray[i]) { - return false; - } - } - - return true; - } catch (error) { - console.error('[E2EE] Key pair verification failed:', error); - return false; - } -} diff --git a/apps/mobile/src/lib/encryption/index.ts b/apps/mobile/src/lib/encryption/index.ts deleted file mode 100644 index 9f0ff63..0000000 --- a/apps/mobile/src/lib/encryption/index.ts +++ /dev/null @@ -1,70 +0,0 @@ -/** - * E2EE Encryption Library - * - * Public API exports for the Sauci E2EE implementation. - */ - -// Types -export type { - KeysMetadata, - EncryptedMessagePayload, - EncryptedMediaPayload, - DecryptedContent, - DecryptedMessageState, - RSAPublicKeyJWK, - RSAPrivateKeyJWK, - EncryptionKeysState, - MasterKey, - EncryptionContext, -} from './types'; - -// Constants -export { - MESSAGE_VERSION_PLAINTEXT, - MESSAGE_VERSION_E2EE, -} from './constants'; - -// Key Management -export { - generateAndStoreKeyPair, - getPrivateKey, - getLocalPublicKey, - hasKeyPair, - isPublicKeyUploaded, - markPublicKeyUploaded, - clearKeys, - isCryptoAvailable, - isValidPublicKeyJwk, - sanitizePublicKeyJwk, -} from './keyManager'; - -// Text Message Encryption/Decryption -export { encryptTextMessage } from './messageEncryption'; -export { decryptTextMessage } from './messageDecryption'; - -// Media Encryption/Decryption -export { encryptMediaFile, getEncryptedFileExtension } from './mediaEncryption'; -export { decryptMediaFile, cleanupDecryptedMedia } from './mediaDecryption'; - -// Admin Keys -export { - getActiveMasterKey, - getAdminPublicKey, - getAdminKeyId, - clearAdminKeyCache, -} from './adminKeys'; - -// Utilities -export { - arrayBufferToBase64, - base64ToArrayBuffer, -} from './utils'; - -// Key Rotation -export { triggerKeyRotation, triggerAutoKeyRotation } from './triggerKeyRotation'; - -// Stale Key Repair -export { repairStaleKey } from './repairStaleKey'; - -// Crypto Operations -export { verifyKeyPair } from './crypto'; diff --git a/apps/mobile/src/lib/encryption/keyManager.ts b/apps/mobile/src/lib/encryption/keyManager.ts deleted file mode 100644 index e3af8f1..0000000 --- a/apps/mobile/src/lib/encryption/keyManager.ts +++ /dev/null @@ -1,294 +0,0 @@ -/** - * E2EE Key Manager - * - * Handles RSA key pair generation and secure storage using expo-secure-store. - * Keys are stored in chunks due to SecureStore's 2KB limit. - */ - -import * as SecureStore from 'expo-secure-store'; -import { Platform } from 'react-native'; -import { - PRIVATE_KEY_PREFIX, - PUBLIC_KEY_UPLOADED, - LOCAL_PUBLIC_KEY, - SECURE_STORE_CHUNK_SIZE, - RSA_KEY_SIZE, - KEY_WRAP_ALGORITHM, - KEY_WRAP_HASH -} from './constants'; -import { chunkString } from './utils'; -import type { RSAPublicKeyJWK, RSAPrivateKeyJWK } from './types'; - -/** - * Check if we're running in a web environment - */ -function isWeb(): boolean { - return Platform.OS === 'web'; -} - -/** - * Check if crypto is available (polyfill installed and native modules built) - */ -export function isCryptoAvailable(): boolean { - if (isWeb()) return false; - return typeof crypto !== 'undefined' && crypto.subtle !== undefined; -} - -/** - * Sanitize a public key by removing trailing dots that may appear - * due to react-native-quick-crypto encoding issues. - */ -export function sanitizePublicKeyJwk(publicKeyJwk: RSAPublicKeyJWK): RSAPublicKeyJWK { - return { - ...publicKeyJwk, - n: publicKeyJwk.n.replace(/\.+$/, ''), - e: publicKeyJwk.e.replace(/\.+$/, ''), - }; -} - -/** - * Validate that a public key JWK looks well-formed for RSA import. - */ -export function isValidPublicKeyJwk(publicKeyJwk: RSAPublicKeyJWK | null): boolean { - if (!publicKeyJwk) return false; - if (publicKeyJwk.kty !== 'RSA') return false; - if (typeof publicKeyJwk.n !== 'string' || typeof publicKeyJwk.e !== 'string') return false; - - // Sanitize before validation (handle trailing dots from quick-crypto) - const sanitized = sanitizePublicKeyJwk(publicKeyJwk); - const base64UrlPattern = /^[A-Za-z0-9_\-+/=]+$/; - return base64UrlPattern.test(sanitized.n) && base64UrlPattern.test(sanitized.e); -} - -/** - * Get the Web Crypto API - * In React Native with react-native-quick-crypto, it's available globally - */ -function getSubtle(): SubtleCrypto { - // react-native-quick-crypto polyfills global.crypto - if (typeof crypto !== 'undefined' && crypto.subtle) { - return crypto.subtle; - } - throw new Error('Web Crypto API not available. Run: npx expo prebuild --clean'); -} - -/** - * Generate a new RSA-2048 key pair for E2EE - * - * @returns The public key in JWK format (private key is stored in SecureStore) - */ -export async function generateAndStoreKeyPair(): Promise { - if (isWeb()) { - console.warn('E2EE key generation not supported on web platform'); - throw new Error('E2EE is not supported on web'); - } - - const subtle = getSubtle(); - - // Generate RSA-2048 key pair - const keyPair = await subtle.generateKey( - { - name: KEY_WRAP_ALGORITHM, - modulusLength: RSA_KEY_SIZE, - publicExponent: new Uint8Array([1, 0, 1]), // 65537 - hash: KEY_WRAP_HASH, - }, - true, // extractable - ['encrypt', 'decrypt'] - ); - - // Export keys as JWK - const publicKeyJwk = await subtle.exportKey('jwk', keyPair.publicKey) as RSAPublicKeyJWK; - const privateKeyJwk = await subtle.exportKey('jwk', keyPair.privateKey) as RSAPrivateKeyJWK; - - // Store private key in SecureStore (chunked) - await storePrivateKey(privateKeyJwk); - - // Store public key locally for quick access - await storeLocalPublicKey(publicKeyJwk); - - return publicKeyJwk; -} - -/** - * Store private key in SecureStore using chunked storage - * RSA-2048 JWK is ~1.7KB, SecureStore limit is 2KB - */ -async function storePrivateKey(privateKeyJwk: RSAPrivateKeyJWK): Promise { - const json = JSON.stringify(privateKeyJwk); - const chunks = chunkString(json, SECURE_STORE_CHUNK_SIZE); - - // Store chunk count - await SecureStore.setItemAsync( - `${PRIVATE_KEY_PREFIX}count`, - chunks.length.toString() - ); - - // Store each chunk with high security settings - for (let i = 0; i < chunks.length; i++) { - await SecureStore.setItemAsync( - `${PRIVATE_KEY_PREFIX}${i}`, - chunks[i], - { - keychainAccessible: SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY - } - ); - } -} - -/** - * Store public key locally for quick access during encryption - */ -async function storeLocalPublicKey(publicKeyJwk: RSAPublicKeyJWK): Promise { - await SecureStore.setItemAsync( - LOCAL_PUBLIC_KEY, - JSON.stringify(publicKeyJwk) - ); -} - -/** - * Retrieve the private key from SecureStore - * - * @returns The private key in JWK format, or null if not found - */ -export async function getPrivateKey(): Promise { - if (isWeb()) { - return null; - } - - try { - const countStr = await SecureStore.getItemAsync(`${PRIVATE_KEY_PREFIX}count`); - if (!countStr) return null; - - const count = parseInt(countStr, 10); - const chunks: string[] = []; - - for (let i = 0; i < count; i++) { - const chunk = await SecureStore.getItemAsync(`${PRIVATE_KEY_PREFIX}${i}`); - if (!chunk) return null; - chunks.push(chunk); - } - - return JSON.parse(chunks.join('')) as RSAPrivateKeyJWK; - } catch (error) { - console.error('Failed to retrieve private key:', error); - return null; - } -} - -/** - * Retrieve the locally stored public key - * - * @returns The public key in JWK format, or null if not found - */ -export async function getLocalPublicKey(): Promise { - if (isWeb()) { - return null; - } - - try { - const json = await SecureStore.getItemAsync(LOCAL_PUBLIC_KEY); - if (!json) return null; - return JSON.parse(json) as RSAPublicKeyJWK; - } catch (error) { - console.error('Failed to retrieve local public key:', error); - return null; - } -} - -/** - * Check if a key pair exists in SecureStore - */ -export async function hasKeyPair(): Promise { - if (isWeb()) { - return false; - } - - try { - const countStr = await SecureStore.getItemAsync(`${PRIVATE_KEY_PREFIX}count`); - return countStr !== null; - } catch (error) { - console.error('Failed to check for key pair:', error); - return false; - } -} - -/** - * Check if public key has been uploaded to Supabase - */ -export async function isPublicKeyUploaded(): Promise { - if (isWeb()) { - return false; - } - - try { - const uploaded = await SecureStore.getItemAsync(PUBLIC_KEY_UPLOADED); - return uploaded === 'true'; - } catch (error) { - console.error('Failed to check public key upload status:', error); - return false; - } -} - -/** - * Mark public key as uploaded to Supabase - */ -export async function markPublicKeyUploaded(): Promise { - await SecureStore.setItemAsync(PUBLIC_KEY_UPLOADED, 'true'); -} - -/** - * Clear all encryption keys from SecureStore - * Used when user logs out or leaves a couple - */ -export async function clearKeys(): Promise { - if (isWeb()) { - return; - } - - try { - const countStr = await SecureStore.getItemAsync(`${PRIVATE_KEY_PREFIX}count`); - if (countStr) { - const count = parseInt(countStr, 10); - for (let i = 0; i < count; i++) { - await SecureStore.deleteItemAsync(`${PRIVATE_KEY_PREFIX}${i}`); - } - await SecureStore.deleteItemAsync(`${PRIVATE_KEY_PREFIX}count`); - } - - await SecureStore.deleteItemAsync(PUBLIC_KEY_UPLOADED); - await SecureStore.deleteItemAsync(LOCAL_PUBLIC_KEY); - } catch (error) { - console.error('Failed to clear encryption keys:', error); - } -} - -/** - * Import an RSA public key from JWK format for encryption operations - */ -export async function importPublicKey(publicKeyJwk: RSAPublicKeyJWK): Promise { - const subtle = getSubtle(); - - return await subtle.importKey( - 'jwk', - publicKeyJwk, - { name: KEY_WRAP_ALGORITHM, hash: KEY_WRAP_HASH }, - false, - ['encrypt'] - ); -} - -/** - * Import an RSA private key from JWK format for decryption operations - */ -export async function importPrivateKey(privateKeyJwk: RSAPrivateKeyJWK): Promise { - const subtle = getSubtle(); - - return await subtle.importKey( - 'jwk', - privateKeyJwk, - { name: KEY_WRAP_ALGORITHM, hash: KEY_WRAP_HASH }, - false, - ['decrypt'] - ); -} diff --git a/apps/mobile/src/lib/encryption/mediaDecryption.ts b/apps/mobile/src/lib/encryption/mediaDecryption.ts deleted file mode 100644 index 4c15584..0000000 --- a/apps/mobile/src/lib/encryption/mediaDecryption.ts +++ /dev/null @@ -1,100 +0,0 @@ -/** - * Media Decryption - * - * Decrypts E2EE images and videos using a download-first approach. - */ - -import * as FileSystem from 'expo-file-system'; -import { unwrapAESKey, importAESKey, decryptAES } from './crypto'; -import { base64ToArrayBuffer, base64ToUint8Array, arrayBufferToBase64 } from './utils'; -import type { KeysMetadata, RSAPrivateKeyJWK } from './types'; - -/** - * Decrypt an encrypted media file - * - * Downloads the encrypted file, decrypts it, and returns a local file URI. - * - * @param encryptedUrl - Signed URL to the .enc file in storage - * @param encryptionIv - Base64-encoded initialization vector - * @param keysMetadata - The wrapped keys metadata - * @param privateKeyJwk - User's RSA private key - * @param isRecipient - Whether the current user is the recipient - * @param mediaType - Type of media ('image' or 'video') - * @returns Local file URI to the decrypted media - */ -export async function decryptMediaFile( - encryptedUrl: string, - encryptionIv: string, - keysMetadata: KeysMetadata, - privateKeyJwk: RSAPrivateKeyJWK, - isRecipient: boolean, - mediaType: 'image' | 'video' -): Promise { - - // 1. Download entire encrypted file - const tempEncryptedPath = `${FileSystem.cacheDirectory}${Date.now()}_encrypted.enc`; - const downloadResult = await FileSystem.downloadAsync( - encryptedUrl, - tempEncryptedPath - ); - - if (downloadResult.status !== 200) { - throw new Error(`Failed to download encrypted file: ${downloadResult.status}`); - } - - // 2. Read encrypted data - const encryptedBase64 = await FileSystem.readAsStringAsync( - downloadResult.uri, - { encoding: FileSystem.EncodingType.Base64 } - ); - const encryptedData = base64ToArrayBuffer(encryptedBase64); - - // 3. Validate and decode IV (must be exactly 12 bytes for AES-GCM) - const iv = base64ToUint8Array(encryptionIv); - if (iv.length !== 12) { - throw new Error(`Invalid IV length: expected 12 bytes, got ${iv.length}`); - } - - // 4. Unwrap AES key - const wrappedKeyBase64 = isRecipient - ? keysMetadata.recipient_wrapped_key - : keysMetadata.sender_wrapped_key; - - if (!wrappedKeyBase64) { - throw new Error('No wrapped key available for media decryption'); - } - - const rawAesKey = await unwrapAESKey(wrappedKeyBase64, privateKeyJwk); - const aesKey = await importAESKey(rawAesKey); - - // 5. Decrypt file - const decryptedData = await decryptAES(encryptedData, aesKey, iv); - - // 6. Write decrypted file - const ext = mediaType === 'video' ? 'mp4' : 'jpg'; - const decryptedUri = `${FileSystem.cacheDirectory}${Date.now()}_decrypted.${ext}`; - - await FileSystem.writeAsStringAsync( - decryptedUri, - arrayBufferToBase64(decryptedData), - { encoding: FileSystem.EncodingType.Base64 } - ); - - // 6. Clean up encrypted temp file - await FileSystem.deleteAsync(downloadResult.uri, { idempotent: true }); - - return decryptedUri; -} - -/** - * Clean up a decrypted media file from cache - * - * @param uri - Local file URI to delete - */ -export async function cleanupDecryptedMedia(uri: string): Promise { - try { - await FileSystem.deleteAsync(uri, { idempotent: true }); - } catch (error) { - console.warn('Failed to clean up decrypted media:', error); - } -} diff --git a/apps/mobile/src/lib/encryption/mediaEncryption.ts b/apps/mobile/src/lib/encryption/mediaEncryption.ts deleted file mode 100644 index 4030720..0000000 --- a/apps/mobile/src/lib/encryption/mediaEncryption.ts +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Media Encryption - * - * Encrypts images and videos using AES-256-GCM with triple-wrapped keys. - * Uses a download-then-decrypt approach for simplicity. - */ - -import * as FileSystem from 'expo-file-system'; -import { generateAESKey, generateIV, encryptAES, exportAESKey, wrapAESKey } from './crypto'; -import { arrayBufferToBase64, base64ToArrayBuffer } from './utils'; -import type { KeysMetadata, EncryptedMediaPayload, RSAPublicKeyJWK } from './types'; - -/** - * Encrypt a media file (image or video) for E2EE - * - * @param sourceUri - Local file URI of the media to encrypt - * @param senderPublicKeyJwk - Sender's RSA public key - * @param recipientPublicKeyJwk - Recipient's RSA public key (may be null) - * @param adminPublicKeyJwk - Admin's RSA public key - * @param adminKeyId - UUID of the admin key record - * @returns Encrypted media payload with local file URI - */ -export async function encryptMediaFile( - sourceUri: string, - senderPublicKeyJwk: RSAPublicKeyJWK, - recipientPublicKeyJwk: RSAPublicKeyJWK | null, - adminPublicKeyJwk: RSAPublicKeyJWK, - adminKeyId: string -): Promise { - - // 1. Read entire file into memory as base64 - const fileBase64 = await FileSystem.readAsStringAsync(sourceUri, { - encoding: FileSystem.EncodingType.Base64, - }); - const fileBuffer = base64ToArrayBuffer(fileBase64); - - // 2. Generate AES key and IV - const aesKey = await generateAESKey(); - const iv = generateIV(); - - // 3. Encrypt entire file - const encryptedData = await encryptAES(fileBuffer, aesKey, iv); - - // 4. Write encrypted file to temp location - const encryptedUri = `${FileSystem.cacheDirectory}${Date.now()}.enc`; - await FileSystem.writeAsStringAsync( - encryptedUri, - arrayBufferToBase64(encryptedData), - { encoding: FileSystem.EncodingType.Base64 } - ); - - // 5. Wrap AES key for all parties - const rawAesKey = await exportAESKey(aesKey); - const senderWrappedKey = await wrapAESKey(rawAesKey, senderPublicKeyJwk); - const adminWrappedKey = await wrapAESKey(rawAesKey, adminPublicKeyJwk); - - let recipientWrappedKey: string | undefined; - if (recipientPublicKeyJwk) { - recipientWrappedKey = await wrapAESKey(rawAesKey, recipientPublicKeyJwk); - } - - return { - encryptedFileUri: encryptedUri, - encryption_iv: arrayBufferToBase64(iv.buffer as ArrayBuffer), - keys_metadata: { - sender_wrapped_key: senderWrappedKey, - recipient_wrapped_key: recipientWrappedKey, - admin_wrapped_key: adminWrappedKey, - admin_key_id: adminKeyId, - algorithm: 'AES-256-GCM', - key_wrap_algorithm: 'RSA-OAEP-SHA256', - pending_recipient: !recipientPublicKeyJwk, - }, - }; -} - -/** - * Get the file extension for encrypted media - */ -export function getEncryptedFileExtension(): string { - return '.enc'; -} diff --git a/apps/mobile/src/lib/encryption/messageDecryption.ts b/apps/mobile/src/lib/encryption/messageDecryption.ts deleted file mode 100644 index e52831b..0000000 --- a/apps/mobile/src/lib/encryption/messageDecryption.ts +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Text Message Decryption - * - * Decrypts E2EE text messages using the user's RSA private key. - */ - -import { unwrapAESKey, importAESKey, decryptAES } from './crypto'; -import { base64ToArrayBuffer, base64ToUint8Array } from './utils'; -import type { KeysMetadata, RSAPrivateKeyJWK } from './types'; - -/** - * Decrypt an E2EE text message - * - * @param encryptedContent - Base64-encoded ciphertext - * @param encryptionIv - Base64-encoded initialization vector - * @param keysMetadata - The wrapped keys metadata - * @param privateKeyJwk - User's RSA private key - * @param isRecipient - Whether the current user is the recipient (true) or sender (false) - * @returns The decrypted plaintext message - */ -export async function decryptTextMessage( - encryptedContent: string, - encryptionIv: string, - keysMetadata: KeysMetadata, - privateKeyJwk: RSAPrivateKeyJWK, - isRecipient: boolean -): Promise { - - // 1. Select the correct wrapped key - const wrappedKeyBase64 = isRecipient - ? keysMetadata.recipient_wrapped_key - : keysMetadata.sender_wrapped_key; - - if (!wrappedKeyBase64) { - throw new Error('No wrapped key available for decryption'); - } - - // 2. Validate and decode IV (must be exactly 12 bytes for AES-GCM) - const iv = base64ToUint8Array(encryptionIv); - if (iv.length !== 12) { - throw new Error(`Invalid IV length: expected 12 bytes, got ${iv.length}`); - } - - // 3. Unwrap AES key using RSA private key - const rawAesKey = await unwrapAESKey(wrappedKeyBase64, privateKeyJwk); - - // 4. Import AES key - const aesKey = await importAESKey(rawAesKey); - - // 5. Decrypt content - const ciphertext = base64ToArrayBuffer(encryptedContent); - - const plaintext = await decryptAES(ciphertext, aesKey, iv); - - // 6. Decode to string - return new TextDecoder().decode(plaintext); -} diff --git a/apps/mobile/src/lib/encryption/messageEncryption.ts b/apps/mobile/src/lib/encryption/messageEncryption.ts deleted file mode 100644 index c10d448..0000000 --- a/apps/mobile/src/lib/encryption/messageEncryption.ts +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Text Message Encryption - * - * Encrypts text messages using AES-256-GCM with triple-wrapped keys. - */ - -import { generateAESKey, generateIV, encryptAES, exportAESKey, wrapAESKey } from './crypto'; -import { arrayBufferToBase64 } from './utils'; -import type { KeysMetadata, EncryptedMessagePayload, RSAPublicKeyJWK } from './types'; - -/** - * Encrypt a text message for E2EE - * - * The message is encrypted with a random AES-256 key, and that key is - * wrapped (encrypted) separately for the sender, recipient, and admin. - * - * @param plaintext - The message text to encrypt - * @param senderPublicKeyJwk - Sender's RSA public key (for their own decryption) - * @param recipientPublicKeyJwk - Recipient's RSA public key (may be null if not yet generated) - * @param adminPublicKeyJwk - Admin's RSA public key (for moderation access) - * @param adminKeyId - UUID of the admin key record in master_keys table - * @returns The encrypted message payload - */ -export async function encryptTextMessage( - plaintext: string, - senderPublicKeyJwk: RSAPublicKeyJWK, - recipientPublicKeyJwk: RSAPublicKeyJWK | null, - adminPublicKeyJwk: RSAPublicKeyJWK, - adminKeyId: string -): Promise { - - // 1. Generate random AES-256 key - const aesKey = await generateAESKey(); - - // 2. Generate random 96-bit IV - const iv = generateIV(); - - // 3. Encrypt plaintext - const ciphertext = await encryptAES(plaintext, aesKey, iv); - - // 4. Export AES key for wrapping - const rawAesKey = await exportAESKey(aesKey); - - // 5. Wrap AES key for each party - const senderWrappedKey = await wrapAESKey(rawAesKey, senderPublicKeyJwk); - const adminWrappedKey = await wrapAESKey(rawAesKey, adminPublicKeyJwk); - - let recipientWrappedKey: string | undefined; - if (recipientPublicKeyJwk) { - recipientWrappedKey = await wrapAESKey(rawAesKey, recipientPublicKeyJwk); - } - - return { - version: 2, - encrypted_content: arrayBufferToBase64(ciphertext), - encryption_iv: arrayBufferToBase64(iv.buffer as ArrayBuffer), - keys_metadata: { - sender_wrapped_key: senderWrappedKey, - recipient_wrapped_key: recipientWrappedKey, - admin_wrapped_key: adminWrappedKey, - admin_key_id: adminKeyId, - algorithm: 'AES-256-GCM', - key_wrap_algorithm: 'RSA-OAEP-SHA256', - pending_recipient: !recipientPublicKeyJwk, - }, - }; -} diff --git a/apps/mobile/src/lib/encryption/reencryptPendingMessages.ts b/apps/mobile/src/lib/encryption/reencryptPendingMessages.ts deleted file mode 100644 index 128582f..0000000 --- a/apps/mobile/src/lib/encryption/reencryptPendingMessages.ts +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Pending Message Re-encryption (Server Assisted) - * - * Triggers the Supabase Edge Function `reencrypt-pending-messages` to re-wrap - * AES keys for messages that were sent before the current user had E2EE keys. - * - * This does NOT decrypt message content on the server. It only re-wraps the - * per-message AES key using the user's public key (admin recovery model). - */ - -import { supabase } from '../supabase'; - -export interface ReencryptPendingMessagesResult { - success: boolean; - updated: number; - reason?: string; - error?: string; -} - -let inFlight: Promise | null = null; -let lastRunAtMs = 0; - -const MIN_INTERVAL_MS = 15_000; - -export async function reencryptPendingMessages( - options: { force?: boolean } = {} -): Promise { - const now = Date.now(); - - if (inFlight) return inFlight; - - if (!options.force && now - lastRunAtMs < MIN_INTERVAL_MS) { - return null; - } - - inFlight = (async () => { - try { - const { data: { session } } = await supabase.auth.getSession(); - if (!session?.access_token) { - return null; - } - - const baseUrl = process.env.EXPO_PUBLIC_SUPABASE_URL; - if (!baseUrl) { - return { success: false, updated: 0, error: 'Missing EXPO_PUBLIC_SUPABASE_URL' }; - } - - const response = await fetch(`${baseUrl}/functions/v1/reencrypt-pending-messages`, { - method: 'POST', - headers: { - Authorization: `Bearer ${session.access_token}`, - 'Content-Type': 'application/json', - }, - body: JSON.stringify({}), - }); - - if (!response.ok) { - const text = await response.text(); - return { success: false, updated: 0, error: text || 'Failed to re-encrypt pending messages' }; - } - - const result = (await response.json()) as ReencryptPendingMessagesResult; - lastRunAtMs = Date.now(); - return result; - } catch (err) { - return { - success: false, - updated: 0, - error: err instanceof Error ? err.message : 'Unknown error', - }; - } finally { - inFlight = null; - } - })(); - - return inFlight; -} diff --git a/apps/mobile/src/lib/encryption/repairStaleKey.ts b/apps/mobile/src/lib/encryption/repairStaleKey.ts deleted file mode 100644 index d340791..0000000 --- a/apps/mobile/src/lib/encryption/repairStaleKey.ts +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Stale Key Repair (Server Assisted) - * - * When a message was encrypted offline with a recipient's old public key, - * and the recipient has since regenerated their keys, this function requests - * the server to re-wrap the AES key using the admin recovery model. - */ - -import { supabase } from '../supabase'; - -export interface RepairStaleKeyResult { - success: boolean; - message_id?: string; - error?: string; -} - -// Track in-flight repairs to avoid duplicate requests -const inFlightRepairs = new Map>(); - -/** - * Request the server to repair a message encrypted with a stale key. - * - * @param messageId - The ID of the message to repair - * @returns Result of the repair operation - */ -export async function repairStaleKey( - messageId: string -): Promise { - // Check if already in flight - const existing = inFlightRepairs.get(messageId); - if (existing) { - return existing; - } - - const promise = (async (): Promise => { - try { - const { data: { session } } = await supabase.auth.getSession(); - if (!session?.access_token) { - return { success: false, error: 'Not authenticated' }; - } - - const baseUrl = process.env.EXPO_PUBLIC_SUPABASE_URL; - if (!baseUrl) { - return { success: false, error: 'Missing EXPO_PUBLIC_SUPABASE_URL' }; - } - - const response = await fetch(`${baseUrl}/functions/v1/repair-stale-key`, { - method: 'POST', - headers: { - Authorization: `Bearer ${session.access_token}`, - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ message_id: messageId }), - }); - - if (!response.ok) { - const text = await response.text(); - let errorMessage = 'Failed to repair message key'; - try { - const json = JSON.parse(text); - errorMessage = json.error || errorMessage; - } catch { - // Use default error message - } - return { success: false, error: errorMessage }; - } - - const result = (await response.json()) as RepairStaleKeyResult; - return result; - } catch (err) { - return { - success: false, - error: err instanceof Error ? err.message : 'Unknown error', - }; - } finally { - inFlightRepairs.delete(messageId); - } - })(); - - inFlightRepairs.set(messageId, promise); - return promise; -} diff --git a/apps/mobile/src/lib/encryption/triggerKeyRotation.ts b/apps/mobile/src/lib/encryption/triggerKeyRotation.ts deleted file mode 100644 index e0bce94..0000000 --- a/apps/mobile/src/lib/encryption/triggerKeyRotation.ts +++ /dev/null @@ -1,102 +0,0 @@ -/** - * Trigger Key Rotation (Server Assisted) - * - * Calls the Supabase Edge Function `handle-key-rotation` to re-wrap - * all message AES keys with the user's current public key. - * - * This is needed when a user regenerates their keys (new device, app reinstall). - * The admin key is used to unwrap the message keys and re-wrap them for - * the user's new public key. - */ - -import { supabase } from '../supabase'; -import { reencryptPendingMessages } from './reencryptPendingMessages'; - - -export interface KeyRotationResult { - success: boolean; - updated: number; - reason?: string; - error?: string; -} - -let inFlight: Promise | null = null; -let autoRotationInFlight: Promise | null = null; -let lastAutoRotationAt = 0; - -const AUTO_ROTATION_MIN_INTERVAL_MS = 60_000; - - -export async function triggerKeyRotation(): Promise { - // Prevent concurrent calls - if (inFlight) return inFlight; - - inFlight = (async () => { - try { - const { data: { session } } = await supabase.auth.getSession(); - if (!session?.access_token) { - return null; - } - - const baseUrl = process.env.EXPO_PUBLIC_SUPABASE_URL; - if (!baseUrl) { - return { success: false, updated: 0, error: 'Missing EXPO_PUBLIC_SUPABASE_URL' }; - } - - console.log('[E2EE] Triggering key rotation for regenerated keys...'); - - const response = await fetch(`${baseUrl}/functions/v1/handle-key-rotation`, { - method: 'POST', - headers: { - Authorization: `Bearer ${session.access_token}`, - 'Content-Type': 'application/json', - }, - body: JSON.stringify({}), - }); - - if (!response.ok) { - const text = await response.text(); - console.error('[E2EE] Key rotation failed:', text); - return { success: false, updated: 0, error: text || 'Failed to rotate keys' }; - } - - const result = (await response.json()) as KeyRotationResult; - console.log(`[E2EE] Key rotation complete: ${result.updated} messages updated`); - return result; - } catch (err) { - console.error('[E2EE] Key rotation error:', err); - return { - success: false, - updated: 0, - error: err instanceof Error ? err.message : 'Unknown error', - }; - } finally { - inFlight = null; - } - })(); - - return inFlight; -} - -export function triggerAutoKeyRotation(): Promise | null { - const now = Date.now(); - - if (autoRotationInFlight) return autoRotationInFlight; - if (now - lastAutoRotationAt < AUTO_ROTATION_MIN_INTERVAL_MS) { - return null; - } - - lastAutoRotationAt = now; - - autoRotationInFlight = (async () => { - console.log('[E2EE] Auto key rotation triggered by decryption failure.'); - const result = await triggerKeyRotation(); - await reencryptPendingMessages({ force: true }); - return result; - })().finally(() => { - autoRotationInFlight = null; - }); - - return autoRotationInFlight; -} - diff --git a/apps/mobile/src/lib/encryption/types.ts b/apps/mobile/src/lib/encryption/types.ts deleted file mode 100644 index 9615bf4..0000000 --- a/apps/mobile/src/lib/encryption/types.ts +++ /dev/null @@ -1,133 +0,0 @@ -/** - * E2EE Types for Sauci Chat - * - * This file contains all TypeScript interfaces for the E2EE implementation. - */ - -/** - * Metadata about how message keys are wrapped for each party - */ -export interface KeysMetadata { - /** AES key encrypted with sender's RSA public key (base64) */ - sender_wrapped_key: string; - - /** AES key encrypted with recipient's RSA public key (base64). Null if recipient hasn't generated keys yet */ - recipient_wrapped_key?: string; - - /** AES key encrypted with admin's RSA public key (base64) */ - admin_wrapped_key: string; - - /** UUID of the master_keys record used */ - admin_key_id: string; - - /** Symmetric encryption algorithm */ - algorithm: 'AES-256-GCM'; - - /** Key wrapping algorithm */ - key_wrap_algorithm: 'RSA-OAEP-SHA256'; - - /** True if recipient key needs to be added when they generate their keys */ - pending_recipient?: boolean; -} - -/** - * Payload for an encrypted text message - */ -export interface EncryptedMessagePayload { - version: 2; - encrypted_content: string; - encryption_iv: string; - keys_metadata: KeysMetadata; -} - -/** - * Payload for encrypted media - */ -export interface EncryptedMediaPayload { - encryptedFileUri: string; - encryption_iv: string; - keys_metadata: KeysMetadata; -} - -/** - * Decrypted content result - */ -export interface DecryptedContent { - content: string | null; - mediaUrl: string | null; -} - -/** - * State for useDecryptedMessage hook - */ -export type DecryptedMessageErrorCode = - | 'E2EE_NOT_SUPPORTED' - | 'E2EE_KEYS_UNAVAILABLE' - | 'E2EE_MISSING_FIELDS' - | 'E2EE_PENDING_RECIPIENT_KEY' - | 'E2EE_REPAIRING_STALE_KEY' - | 'E2EE_DECRYPT_FAILED'; - -export interface DecryptedMessageState { - content: string | null; - mediaUri: string | null; - isDecrypting: boolean; - error: Error | null; - errorCode?: DecryptedMessageErrorCode; -} - -/** - * RSA public key in JWK format (JSON Web Key) - */ -export interface RSAPublicKeyJWK { - kty: 'RSA'; - n: string; // modulus - e: string; // exponent - alg?: string; - key_ops?: string[]; -} - -/** - * RSA private key in JWK format (includes public key components) - */ -export interface RSAPrivateKeyJWK extends RSAPublicKeyJWK { - d: string; // private exponent - p: string; // first prime factor - q: string; // second prime factor - dp: string; // first factor CRT exponent - dq: string; // second factor CRT exponent - qi: string; // first CRT coefficient -} - -/** - * State for useEncryptionKeys hook - */ -export interface EncryptionKeysState { - privateKeyJwk: RSAPrivateKeyJWK | null; - publicKeyJwk: RSAPublicKeyJWK | null; - isLoading: boolean; - hasKeys: boolean; - error: Error | null; -} - -/** - * Master key record from database - */ -export interface MasterKey { - id: string; - key_name: string; - public_key_jwk: RSAPublicKeyJWK; - is_active: boolean; - created_at: string; - rotated_at: string | null; -} - -/** - * Encryption context for sending messages - */ -export interface EncryptionContext { - senderPublicKeyJwk: RSAPublicKeyJWK; - recipientPublicKeyJwk: RSAPublicKeyJWK | null; - adminPublicKeyJwk: RSAPublicKeyJWK; - adminKeyId: string; -} diff --git a/apps/mobile/src/lib/encryption/utils.ts b/apps/mobile/src/lib/encryption/utils.ts deleted file mode 100644 index b37ce98..0000000 --- a/apps/mobile/src/lib/encryption/utils.ts +++ /dev/null @@ -1,72 +0,0 @@ -/** - * E2EE Utility Functions - * - * Base64 and ArrayBuffer conversion utilities for encryption operations. - */ - -/** - * Convert ArrayBuffer to base64 string - */ -export 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); -} - -/** - * Convert base64 string to ArrayBuffer - */ -export 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; -} - -/** - * Convert Uint8Array to base64 string - */ -export function uint8ArrayToBase64(array: Uint8Array): string { - let binary = ''; - for (let i = 0; i < array.length; i++) { - binary += String.fromCharCode(array[i]); - } - return btoa(binary); -} - -/** - * Convert base64 string to Uint8Array - */ -export function base64ToUint8Array(base64: string): Uint8Array { - 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; -} - -/** - * Split string into chunks of specified size - */ -export function chunkString(str: string, size: number): string[] { - const chunks: string[] = []; - for (let i = 0; i < str.length; i += size) { - chunks.push(str.slice(i, i + size)); - } - return chunks; -} - -/** - * Generate a random string for unique identifiers - */ -export function generateRandomId(): string { - const array = new Uint8Array(16); - crypto.getRandomValues(array); - return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join(''); -} diff --git a/apps/mobile/src/lib/mediaCache.ts b/apps/mobile/src/lib/mediaCache.ts deleted file mode 100644 index af57753..0000000 --- a/apps/mobile/src/lib/mediaCache.ts +++ /dev/null @@ -1,22 +0,0 @@ -/** - * Media Cache Utilities - * - * Extracted from useDecryptedMedia to avoid circular dependencies. - * This module handles caching of decrypted media files. - */ - -import { cleanupDecryptedMedia } from './encryption'; - -// In-memory cache to avoid re-decrypting the same media -export const decryptedMediaCache = new Map(); - -/** - * Clears all cached decrypted media files from disk and memory. - * Call this on sign out to free up storage. - */ -export async function clearDecryptedMediaCache(): Promise { - for (const uri of decryptedMediaCache.values()) { - await cleanupDecryptedMedia(uri); - } - decryptedMediaCache.clear(); -} diff --git a/apps/mobile/src/lib/packIcons.ts b/apps/mobile/src/lib/packIcons.ts index 2bc541a..ff06ec4 100644 --- a/apps/mobile/src/lib/packIcons.ts +++ b/apps/mobile/src/lib/packIcons.ts @@ -2,12 +2,8 @@ import type { Ionicons } from "@expo/vector-icons"; type IoniconsName = keyof typeof Ionicons.glyphMap; -/** - * Maps emoji icons to Ionicons for a more professional, consistent appearance. - * This eliminates the "AI slop" feel of heavy emoji usage while maintaining - * visual differentiation between packs. - */ -export const PACK_ICON_MAP: Record = { +// Legacy emoji mappings (for backwards compatibility with existing packs) +const EMOJI_TO_IONICON: Record = { // Career & Professional "💼": "briefcase-outline", @@ -49,13 +45,67 @@ export const PACK_ICON_MAP: Record = { "📁": "folder-outline", }; +export const PACK_ICON_MAP = EMOJI_TO_IONICON; + export const DEFAULT_PACK_ICON: IoniconsName = "layers-outline"; +// List of valid Ionicon names (subset we support) +const VALID_IONICONS = new Set([ + "heart-outline", + "heart-half-outline", + "heart-circle-outline", + "chatbubbles-outline", + "chatbox-outline", + "mail-outline", + "flower-outline", + "wine-outline", + "restaurant-outline", + "cafe-outline", + "airplane-outline", + "car-outline", + "compass-outline", + "map-outline", + "home-outline", + "people-outline", + "person-outline", + "eye-off-outline", + "key-outline", + "lock-closed-outline", + "dice-outline", + "gift-outline", + "sparkles-outline", + "star-outline", + "flame-outline", + "flash-outline", + "moon-outline", + "sunny-outline", + "flag-outline", + "calendar-outline", + "checkbox-outline", + "trophy-outline", + "layers-outline", + "cube-outline", + "folder-outline", + "bookmark-outline", + "bulb-outline", + "color-wand-outline", + "sync-outline", + "refresh-outline", + "briefcase-outline", +]); + /** - * Converts an emoji icon string to an Ionicons name. - * Falls back to DEFAULT_PACK_ICON if no mapping exists. + * Converts an icon value to an Ionicons name. + * Handles both: + * - Ionicon names directly (new packs): "briefcase-outline" -> "briefcase-outline" + * - Legacy emojis (existing packs): "💼" -> "briefcase-outline" */ -export function getPackIconName(emoji: string | null | undefined): IoniconsName { - if (!emoji) return DEFAULT_PACK_ICON; - return PACK_ICON_MAP[emoji] || DEFAULT_PACK_ICON; +export function getPackIconName(icon: string | null | undefined): IoniconsName { + if (!icon) return DEFAULT_PACK_ICON; + + if (VALID_IONICONS.has(icon)) { + return icon as IoniconsName; + } + + return EMOJI_TO_IONICON[icon] || DEFAULT_PACK_ICON; } diff --git a/apps/mobile/src/store/authStore.ts b/apps/mobile/src/store/authStore.ts index 4e35971..1b1cfaa 100644 --- a/apps/mobile/src/store/authStore.ts +++ b/apps/mobile/src/store/authStore.ts @@ -1,32 +1,8 @@ import { create } from "zustand"; import { supabase } from "../lib/supabase"; import { Events } from "../lib/analytics"; -import { clearKeys } from "../lib/encryption"; -import { clearDecryptedMediaCache } from "../lib/mediaCache"; import type { Profile, Couple } from "@/types"; -import type { RSAPublicKeyJWK, RSAPrivateKeyJWK } from "../lib/encryption/types"; -/** - * Encryption key state - stored globally to ensure all components - * share the same key state and avoid race conditions during encryption. - */ -type EncryptionRecoveryReason = 'stale-key' | 'pending-recipient' | 'rotation' | 'keys-unavailable'; - -interface EncryptionKeyState { - privateKeyJwk: RSAPrivateKeyJWK | null; - publicKeyJwk: RSAPublicKeyJWK | null; - hasKeys: boolean; - isLoadingKeys: boolean; - keysError: Error | null; - /** Incremented when keys change - consumers can use this to trigger re-renders */ - keysVersion: number; - /** Background recovery status for E2EE issues */ - isRecovering: boolean; - recoveryReason: EncryptionRecoveryReason | null; - recoveryCount: number; - recoveryUpdatedAt: number | null; -} - interface AuthState { user: Profile | null; @@ -35,22 +11,12 @@ interface AuthState { isLoading: boolean; isAuthenticated: boolean; - // Encryption key state (global to avoid hook instance sync issues) - encryptionKeys: EncryptionKeyState; - // Actions fetchUser: () => Promise; fetchCouple: () => Promise; refreshPartner: () => Promise; signOut: () => Promise; setUser: (user: Profile | null) => void; - - // Encryption key actions - setEncryptionKeys: (keys: Partial) => void; - clearEncryptionKeys: () => void; - beginEncryptionRecovery: (reason: EncryptionRecoveryReason) => void; - endEncryptionRecovery: () => void; - } // Import other stores lazily to avoid circular dependency issues @@ -62,19 +28,6 @@ const getOtherStores = () => { return { useMatchStore, usePacksStore, useMessageStore, useSubscriptionStore }; }; -const initialEncryptionKeyState: EncryptionKeyState = { - privateKeyJwk: null, - publicKeyJwk: null, - hasKeys: false, - isLoadingKeys: true, - keysError: null, - keysVersion: 0, - isRecovering: false, - recoveryReason: null, - recoveryCount: 0, - recoveryUpdatedAt: null, -}; - export const useAuthStore = create((set, get) => ({ user: null, @@ -82,7 +35,6 @@ export const useAuthStore = create((set, get) => ({ partner: null, isLoading: true, isAuthenticated: false, - encryptionKeys: initialEncryptionKeyState, fetchUser: async () => { try { @@ -100,13 +52,6 @@ export const useAuthStore = create((set, get) => ({ if (authError || !authUser) { console.log("[Auth] Session invalid, signing out:", authError?.message); - - // Clear E2EE keys - try { - await clearKeys(); - } catch (error) { - console.error("Failed to clear encryption keys:", error); - } // Session is invalid - clear everything set({ user: null, couple: null, partner: null, isAuthenticated: false, isLoading: false }); @@ -191,20 +136,6 @@ export const useAuthStore = create((set, get) => ({ signOut: async () => { Events.signOut(); - // Clear E2EE keys from storage - try { - await clearKeys(); - } catch (error) { - console.error("Failed to clear encryption keys:", error); - } - - // Clear decrypted media cache to free storage - try { - await clearDecryptedMediaCache(); - } catch (error) { - console.error("Failed to clear media cache:", error); - } - // Clear local state FIRST to ensure UI updates even if Supabase call fails set({ user: null, @@ -212,7 +143,6 @@ export const useAuthStore = create((set, get) => ({ partner: null, isAuthenticated: false, isLoading: false, - encryptionKeys: initialEncryptionKeyState, }); // Clear other stores const { useMatchStore, usePacksStore, useMessageStore, useSubscriptionStore } = getOtherStores(); @@ -246,60 +176,5 @@ export const useAuthStore = create((set, get) => ({ useSubscriptionStore.getState().clearSubscription(); } }, +})); - /** - * Update encryption key state. This is the ONLY way to update keys - * to ensure all consumers see the same state. - */ - setEncryptionKeys: (keys) => { - set((state) => ({ - encryptionKeys: { - ...state.encryptionKeys, - ...keys, - // Increment version when keys actually change - keysVersion: (keys.publicKeyJwk !== undefined || keys.privateKeyJwk !== undefined) - ? state.encryptionKeys.keysVersion + 1 - : state.encryptionKeys.keysVersion, - }, - })); - }, - - beginEncryptionRecovery: (reason) => { - set((state) => { - const nextCount = state.encryptionKeys.recoveryCount + 1; - return { - encryptionKeys: { - ...state.encryptionKeys, - recoveryCount: nextCount, - isRecovering: true, - recoveryReason: reason, - recoveryUpdatedAt: Date.now(), - }, - }; - }); - }, - - endEncryptionRecovery: () => { - set((state) => { - const nextCount = Math.max(0, state.encryptionKeys.recoveryCount - 1); - const isRecovering = nextCount > 0; - return { - encryptionKeys: { - ...state.encryptionKeys, - recoveryCount: nextCount, - isRecovering, - recoveryReason: isRecovering ? state.encryptionKeys.recoveryReason : null, - recoveryUpdatedAt: Date.now(), - }, - }; - }); - }, - - /** - * Clear encryption keys (called on sign out or when leaving couple) - */ - clearEncryptionKeys: () => { - set({ encryptionKeys: initialEncryptionKeyState }); - }, -})); - diff --git a/apps/supabase/functions/handle-key-rotation/index.ts b/apps/supabase/functions/handle-key-rotation/index.ts deleted file mode 100644 index 1c8dd7b..0000000 --- a/apps/supabase/functions/handle-key-rotation/index.ts +++ /dev/null @@ -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 { - 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 { - // 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); -} diff --git a/apps/supabase/functions/migrate-e2ee-to-plaintext/index.ts b/apps/supabase/functions/migrate-e2ee-to-plaintext/index.ts new file mode 100644 index 0000000..f802672 --- /dev/null +++ b/apps/supabase/functions/migrate-e2ee-to-plaintext/index.ts @@ -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 = { + 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 = {} +) { + 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, + 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, + 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"; + } +} diff --git a/apps/supabase/functions/reencrypt-pending-messages/index.ts b/apps/supabase/functions/reencrypt-pending-messages/index.ts deleted file mode 100644 index 1a3ac8b..0000000 --- a/apps/supabase/functions/reencrypt-pending-messages/index.ts +++ /dev/null @@ -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 { - 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 { - // 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); -} diff --git a/apps/supabase/functions/repair-stale-key/index.ts b/apps/supabase/functions/repair-stale-key/index.ts deleted file mode 100644 index 607d8bd..0000000 --- a/apps/supabase/functions/repair-stale-key/index.ts +++ /dev/null @@ -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 { - 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 { - // 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); -} diff --git a/docs/e2ee-implementation.md b/docs/e2ee-implementation.md deleted file mode 100644 index 0f916ff..0000000 --- a/docs/e2ee-implementation.md +++ /dev/null @@ -1,1458 +0,0 @@ -# E2EE Implementation Plan for Sauci Chat - -## Overview - -This document outlines the implementation of client-side **3-way End-to-End Encryption (E2EE)** for all chat content (text messages, images, and videos) in the Sauci mobile app. The design provides: - -- **Full encryption** of message content before it leaves the device -- **Triple-wrapped keys** allowing decryption by sender, recipient, and admin -- **Backwards compatibility** with existing plaintext (v1) messages -- **Admin moderation capability** for reported content review -- **Device change recovery** via admin re-encryption - ---- - -## Encryption Architecture - -``` -┌─────────────────────────────────────────────────────────────────────────┐ -│ Message Encryption Flow │ -├─────────────────────────────────────────────────────────────────────────┤ -│ │ -│ ┌──────────────┐ ┌──────────────────┐ │ -│ │ Text Message │ │ Media (Img/Video)│ │ -│ └──────┬───────┘ └────────┬─────────┘ │ -│ │ │ │ -│ ▼ ▼ │ -│ ┌──────────────────────────────────────────────────┐ │ -│ │ Generate Random AES-256-GCM Content Key │ │ -│ └──────────────────────────┬───────────────────────┘ │ -│ │ │ -│ ┌───────────────────┼───────────────────┐ │ -│ ▼ ▼ ▼ │ -│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ -│ │ Encrypt │ │ Encrypt │ │ Encrypt │ │ -│ │ AES Key │ │ AES Key │ │ AES Key │ │ -│ │ with │ │ with │ │ with │ │ -│ │ SENDER │ │ RECIPIENT │ │ ADMIN │ │ -│ │ RSA Pub │ │ RSA Pub │ │ RSA Pub │ │ -│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │ -│ │ │ │ │ -│ └──────────────────┼──────────────────┘ │ -│ ▼ │ -│ ┌─────────────────────────┐ │ -│ │ keys_metadata JSONB │ │ -│ │ { │ │ -│ │ sender_wrapped_key, │ │ -│ │ recipient_wrapped_key, │ │ -│ │ admin_wrapped_key, │ │ -│ │ admin_key_id │ │ -│ │ } │ │ -│ └─────────────────────────┘ │ -│ │ -└─────────────────────────────────────────────────────────────────────────┘ -``` - ---- - -## Key Decisions - -| Aspect | Decision | Rationale | -|--------|----------|-----------| -| **Crypto Library** | `react-native-quick-crypto@^0.7.x` | Works with old architecture (`newArchEnabled: false`), native performance | -| **Symmetric Cipher** | AES-256-GCM | Authenticated encryption, widely supported | -| **Asymmetric Cipher** | RSA-OAEP (SHA-256) | Secure key wrapping, PKCS#1 v2.1 | -| **RSA Key Size** | 2048-bit | Fits in SecureStore (~1.7KB), secure for 10+ years | -| **Key Format** | JWK (JSON Web Key) | Required - v0.x doesn't support PKCS8 import for RSA-OAEP | -| **Media Encryption** | Download-then-decrypt | Simpler than streaming, acceptable for compressed media | -| **Admin Key Storage** | Environment variable | Edge function accessible | -| **Key Rotation** | Archive old keys | Old messages remain decryptable | -| **Missing Partner Key** | Encrypt sender+admin only | Re-encrypt when partner generates keys | -| **Device Change** | Admin re-encryption | Recovers access when user gets new device | - ---- - -## Device Change / Key Loss Handling - -When a user loses their phone and reinstalls on a new device: - -### Problem -- New key pair generated on new device -- Old private key is lost (was in old device's SecureStore) -- User would lose access to all E2EE messages - -### Solution: Admin Re-encryption - -When a user's public key changes (detected via database trigger or Edge Function): - -1. System detects `profiles.public_key_jwk` was updated -2. Edge Function `handle-key-rotation` is triggered -3. For each v2 message where user is sender or recipient: - - Unwrap AES key using admin private key - - Re-wrap AES key with user's new public key - - Update `sender_wrapped_key` or `recipient_wrapped_key` -4. User regains access to all historical messages - -### Security Consideration -- Admin key becomes more powerful (can re-encrypt at will) -- This is acceptable since admin already has decryption access by design -- Audit logging recommended for accountability - ---- - -## Database Schema Changes - -### 1. Messages Table Updates - -Add columns to support encrypted messages: - -```sql --- Migration: add_e2ee_support_to_messages - --- Version indicator: 1 = plaintext (legacy), 2 = E2EE -ALTER TABLE messages ADD COLUMN version INTEGER DEFAULT 1; - --- Encrypted message content (base64 encoded ciphertext) -ALTER TABLE messages ADD COLUMN encrypted_content TEXT; - --- Initialization vector for AES-GCM (base64 encoded, 12 bytes) -ALTER TABLE messages ADD COLUMN encryption_iv TEXT; - --- Triple-wrapped encryption keys and metadata -ALTER TABLE messages ADD COLUMN keys_metadata JSONB; - --- Add comment for documentation -COMMENT ON COLUMN messages.version IS - 'Encryption version: 1 = plaintext (legacy), 2 = E2EE with triple-wrapped keys'; - --- Constraint: v2 messages must have encryption fields -ALTER TABLE messages ADD CONSTRAINT e2ee_fields_required - CHECK (version = 1 OR (version = 2 AND encryption_iv IS NOT NULL AND keys_metadata IS NOT NULL)); -``` - -### 2. Profiles Table Updates - -Store user's public key for E2EE: - -```sql --- Migration: add_public_key_to_profiles - --- RSA public key in JWK format -ALTER TABLE profiles ADD COLUMN public_key_jwk JSONB; - --- Index for efficient lookups when encrypting for partner -CREATE INDEX idx_profiles_couple_id_public_key ON profiles(couple_id) - WHERE public_key_jwk IS NOT NULL; -``` - -### 3. Master Keys Table - -Store admin public keys for moderation access: - -```sql --- Migration: create_master_keys_table - -CREATE TABLE master_keys ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - key_name TEXT UNIQUE NOT NULL, - public_key_jwk JSONB NOT NULL, - created_at TIMESTAMPTZ DEFAULT now(), - rotated_at TIMESTAMPTZ, - is_active BOOLEAN DEFAULT true -); - --- RLS: Only super admins can view/manage -ALTER TABLE master_keys ENABLE ROW LEVEL SECURITY; - -CREATE POLICY "Super admins can view master keys" - ON master_keys FOR SELECT - TO authenticated - USING (is_super_admin()); - -CREATE POLICY "Super admins can manage master keys" - ON master_keys FOR ALL - TO authenticated - USING (is_super_admin()); - --- Insert initial master key (public key only - private key in env) --- This will be done during deployment setup -``` - -### 4. Keys Metadata Structure - -```typescript -interface KeysMetadata { - // AES key encrypted with sender's RSA public key (base64) - sender_wrapped_key: string; - - // AES key encrypted with recipient's RSA public key (base64) - // Null/undefined if recipient hasn't generated keys yet - recipient_wrapped_key?: string; - - // AES key encrypted with admin's RSA public key (base64) - admin_wrapped_key: string; - - // UUID of the master_keys record used - admin_key_id: string; - - // Algorithm identifiers - algorithm: 'AES-256-GCM'; - key_wrap_algorithm: 'RSA-OAEP-SHA256'; - - // True if recipient key needs to be added when they join - pending_recipient?: boolean; -} -``` - ---- - -## Mobile App Implementation - -### File Structure - -``` -apps/mobile/src/lib/encryption/ -├── index.ts # Public API exports -├── types.ts # TypeScript interfaces -├── constants.ts # Algorithm constants, key names -├── utils.ts # Base64/ArrayBuffer conversions -├── keyManager.ts # Key generation, SecureStore storage -├── crypto.ts # Low-level RSA/AES operations -├── messageEncryption.ts # Encrypt text messages -├── messageDecryption.ts # Decrypt text messages -├── mediaEncryption.ts # Encrypt images/videos -├── mediaDecryption.ts # Decrypt images/videos (download-first) -└── adminKeys.ts # Fetch active admin public key - -apps/mobile/src/hooks/ -├── useEncryptionKeys.ts # Hook to access user's keypair -└── useDecryptedMessage.ts # Hook for message decryption - -apps/mobile/src/features/chat/ -├── hooks/ -│ └── useEncryptedMediaUpload.ts # Modified upload with encryption -└── components/ - └── EncryptedMessageContent.tsx # Version-aware message renderer -``` - -### Key Management - -#### Key Generation (on first launch or couple join) - -```typescript -// keyManager.ts - -import { subtle, getRandomValues } from 'react-native-quick-crypto'; -import * as SecureStore from 'expo-secure-store'; - -const PRIVATE_KEY_PREFIX = 'e2ee_private_key_chunk_'; -const PUBLIC_KEY_UPLOADED = 'e2ee_public_key_uploaded'; - -export async function generateAndStoreKeyPair(): Promise { - // Generate RSA-2048 key pair - const keyPair = await subtle.generateKey( - { - name: 'RSA-OAEP', - modulusLength: 2048, - publicExponent: new Uint8Array([1, 0, 1]), // 65537 - hash: 'SHA-256', - }, - true, // extractable - ['encrypt', 'decrypt'] - ); - - // Export keys as JWK - const publicKeyJwk = await subtle.exportKey('jwk', keyPair.publicKey); - const privateKeyJwk = await subtle.exportKey('jwk', keyPair.privateKey); - - // Store private key in SecureStore (chunked if needed) - await storePrivateKey(privateKeyJwk); - - return publicKeyJwk; -} - -async function storePrivateKey(privateKeyJwk: JsonWebKey): Promise { - const json = JSON.stringify(privateKeyJwk); - - // SecureStore has 2KB limit, RSA-2048 JWK is ~1.7KB - // Chunk to be safe - const chunks = chunkString(json, 1900); - - await SecureStore.setItemAsync( - `${PRIVATE_KEY_PREFIX}count`, - chunks.length.toString() - ); - - for (let i = 0; i < chunks.length; i++) { - await SecureStore.setItemAsync( - `${PRIVATE_KEY_PREFIX}${i}`, - chunks[i], - { keychainAccessible: SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY } - ); - } -} - -export async function getPrivateKey(): Promise { - const countStr = await SecureStore.getItemAsync(`${PRIVATE_KEY_PREFIX}count`); - if (!countStr) return null; - - const count = parseInt(countStr, 10); - const chunks: string[] = []; - - for (let i = 0; i < count; i++) { - const chunk = await SecureStore.getItemAsync(`${PRIVATE_KEY_PREFIX}${i}`); - if (!chunk) return null; - chunks.push(chunk); - } - - return JSON.parse(chunks.join('')); -} - -export async function hasKeyPair(): Promise { - const countStr = await SecureStore.getItemAsync(`${PRIVATE_KEY_PREFIX}count`); - return countStr !== null; -} - -export async function clearKeys(): Promise { - const countStr = await SecureStore.getItemAsync(`${PRIVATE_KEY_PREFIX}count`); - if (!countStr) return; - - const count = parseInt(countStr, 10); - for (let i = 0; i < count; i++) { - await SecureStore.deleteItemAsync(`${PRIVATE_KEY_PREFIX}${i}`); - } - await SecureStore.deleteItemAsync(`${PRIVATE_KEY_PREFIX}count`); - await SecureStore.deleteItemAsync(PUBLIC_KEY_UPLOADED); -} -``` - -#### Key Upload to Profile - -```typescript -// Called after key generation -export async function uploadPublicKey( - userId: string, - publicKeyJwk: JsonWebKey -): Promise { - const { error } = await supabase - .from('profiles') - .update({ public_key_jwk: publicKeyJwk }) - .eq('id', userId); - - if (error) throw error; - - await SecureStore.setItemAsync(PUBLIC_KEY_UPLOADED, 'true'); -} -``` - -### Text Message Encryption - -```typescript -// messageEncryption.ts - -import { subtle, getRandomValues } from 'react-native-quick-crypto'; -import { arrayBufferToBase64 } from './utils'; -import type { KeysMetadata, EncryptedMessagePayload } from './types'; - -export async function encryptTextMessage( - plaintext: string, - senderPublicKeyJwk: JsonWebKey, - recipientPublicKeyJwk: JsonWebKey | null, - adminPublicKeyJwk: JsonWebKey, - adminKeyId: string -): Promise { - - // 1. Generate random AES-256 key - const aesKey = await subtle.generateKey( - { name: 'AES-GCM', length: 256 }, - true, - ['encrypt', 'decrypt'] - ); - - // 2. Generate random 96-bit IV - const iv = getRandomValues(new Uint8Array(12)); - - // 3. Encrypt plaintext - const encoder = new TextEncoder(); - const plaintextBuffer = encoder.encode(plaintext); - - const ciphertext = await subtle.encrypt( - { name: 'AES-GCM', iv }, - aesKey, - plaintextBuffer - ); - - // 4. Export AES key for wrapping - const rawAesKey = await subtle.exportKey('raw', aesKey); - - // 5. Wrap AES key for each party - const senderWrappedKey = await wrapKeyForRecipient(rawAesKey, senderPublicKeyJwk); - const adminWrappedKey = await wrapKeyForRecipient(rawAesKey, adminPublicKeyJwk); - - let recipientWrappedKey: string | undefined; - if (recipientPublicKeyJwk) { - recipientWrappedKey = await wrapKeyForRecipient(rawAesKey, recipientPublicKeyJwk); - } - - return { - version: 2, - encrypted_content: arrayBufferToBase64(ciphertext), - encryption_iv: arrayBufferToBase64(iv), - keys_metadata: { - sender_wrapped_key: senderWrappedKey, - recipient_wrapped_key: recipientWrappedKey, - admin_wrapped_key: adminWrappedKey, - admin_key_id: adminKeyId, - algorithm: 'AES-256-GCM', - key_wrap_algorithm: 'RSA-OAEP-SHA256', - pending_recipient: !recipientPublicKeyJwk, - }, - }; -} - -async function wrapKeyForRecipient( - rawAesKey: ArrayBuffer, - recipientPublicKeyJwk: JsonWebKey -): Promise { - const rsaKey = await subtle.importKey( - 'jwk', - recipientPublicKeyJwk, - { name: 'RSA-OAEP', hash: 'SHA-256' }, - false, - ['encrypt'] - ); - - const wrappedKey = await subtle.encrypt( - { name: 'RSA-OAEP' }, - rsaKey, - rawAesKey - ); - - return arrayBufferToBase64(wrappedKey); -} -``` - -### Text Message Decryption - -```typescript -// messageDecryption.ts - -import { subtle } from 'react-native-quick-crypto'; -import { base64ToArrayBuffer } from './utils'; -import type { KeysMetadata } from './types'; - -export async function decryptTextMessage( - encryptedContent: string, - encryptionIv: string, - keysMetadata: KeysMetadata, - privateKeyJwk: JsonWebKey, - isRecipient: boolean -): Promise { - - // 1. Select the correct wrapped key - const wrappedKeyBase64 = isRecipient - ? keysMetadata.recipient_wrapped_key - : keysMetadata.sender_wrapped_key; - - if (!wrappedKeyBase64) { - throw new Error('No wrapped key available for decryption'); - } - - // 2. Import private key - const privateKey = await subtle.importKey( - 'jwk', - privateKeyJwk, - { name: 'RSA-OAEP', hash: 'SHA-256' }, - false, - ['decrypt'] - ); - - // 3. Unwrap AES key - const wrappedKey = base64ToArrayBuffer(wrappedKeyBase64); - const rawAesKey = await subtle.decrypt( - { name: 'RSA-OAEP' }, - privateKey, - wrappedKey - ); - - // 4. Import AES key - const aesKey = await subtle.importKey( - 'raw', - rawAesKey, - { name: 'AES-GCM' }, - false, - ['decrypt'] - ); - - // 5. Decrypt content - const iv = base64ToArrayBuffer(encryptionIv); - const ciphertext = base64ToArrayBuffer(encryptedContent); - - const plaintext = await subtle.decrypt( - { name: 'AES-GCM', iv }, - aesKey, - ciphertext - ); - - return new TextDecoder().decode(plaintext); -} -``` - -### Media Encryption (Download-First Approach) - -```typescript -// mediaEncryption.ts - -import { subtle, getRandomValues } from 'react-native-quick-crypto'; -import * as FileSystem from 'expo-file-system'; -import { arrayBufferToBase64, base64ToArrayBuffer } from './utils'; -import type { KeysMetadata, EncryptedMediaPayload } from './types'; - -export async function encryptMediaFile( - sourceUri: string, - senderPublicKeyJwk: JsonWebKey, - recipientPublicKeyJwk: JsonWebKey | null, - adminPublicKeyJwk: JsonWebKey, - adminKeyId: string -): Promise { - - // 1. Read entire file into memory - const fileBase64 = await FileSystem.readAsStringAsync(sourceUri, { - encoding: FileSystem.EncodingType.Base64, - }); - const fileBuffer = base64ToArrayBuffer(fileBase64); - - // 2. Generate AES key and IV - const aesKey = await subtle.generateKey( - { name: 'AES-GCM', length: 256 }, - true, - ['encrypt', 'decrypt'] - ); - const iv = getRandomValues(new Uint8Array(12)); - - // 3. Encrypt entire file - const encryptedData = await subtle.encrypt( - { name: 'AES-GCM', iv }, - aesKey, - fileBuffer - ); - - // 4. Write encrypted file to temp location - const encryptedUri = `${FileSystem.cacheDirectory}${Date.now()}.enc`; - await FileSystem.writeAsStringAsync( - encryptedUri, - arrayBufferToBase64(encryptedData), - { encoding: FileSystem.EncodingType.Base64 } - ); - - // 5. Wrap AES key for all parties - const rawAesKey = await subtle.exportKey('raw', aesKey); - const senderWrappedKey = await wrapKeyForRecipient(rawAesKey, senderPublicKeyJwk); - const adminWrappedKey = await wrapKeyForRecipient(rawAesKey, adminPublicKeyJwk); - - let recipientWrappedKey: string | undefined; - if (recipientPublicKeyJwk) { - recipientWrappedKey = await wrapKeyForRecipient(rawAesKey, recipientPublicKeyJwk); - } - - return { - encryptedFileUri: encryptedUri, - encryption_iv: arrayBufferToBase64(iv), - keys_metadata: { - sender_wrapped_key: senderWrappedKey, - recipient_wrapped_key: recipientWrappedKey, - admin_wrapped_key: adminWrappedKey, - admin_key_id: adminKeyId, - algorithm: 'AES-256-GCM', - key_wrap_algorithm: 'RSA-OAEP-SHA256', - pending_recipient: !recipientPublicKeyJwk, - }, - }; -} - -async function wrapKeyForRecipient( - rawAesKey: ArrayBuffer, - recipientPublicKeyJwk: JsonWebKey -): Promise { - const rsaKey = await subtle.importKey( - 'jwk', - recipientPublicKeyJwk, - { name: 'RSA-OAEP', hash: 'SHA-256' }, - false, - ['encrypt'] - ); - - const wrappedKey = await subtle.encrypt( - { name: 'RSA-OAEP' }, - rsaKey, - rawAesKey - ); - - return arrayBufferToBase64(wrappedKey); -} -``` - -### Media Decryption (Download-First Approach) - -```typescript -// mediaDecryption.ts - -import { subtle } from 'react-native-quick-crypto'; -import * as FileSystem from 'expo-file-system'; -import { base64ToArrayBuffer, arrayBufferToBase64 } from './utils'; -import type { KeysMetadata } from './types'; - -export async function decryptMediaFile( - encryptedUrl: string, // Signed URL to .enc file - encryptionIv: string, - keysMetadata: KeysMetadata, - privateKeyJwk: JsonWebKey, - isRecipient: boolean, - mediaType: 'image' | 'video' -): Promise { // Returns local file URI - - // 1. Download entire encrypted file - const tempEncryptedPath = `${FileSystem.cacheDirectory}${Date.now()}_encrypted.enc`; - const downloadResult = await FileSystem.downloadAsync( - encryptedUrl, - tempEncryptedPath - ); - - if (downloadResult.status !== 200) { - throw new Error(`Failed to download encrypted file: ${downloadResult.status}`); - } - - // 2. Read encrypted data - const encryptedBase64 = await FileSystem.readAsStringAsync( - downloadResult.uri, - { encoding: FileSystem.EncodingType.Base64 } - ); - const encryptedData = base64ToArrayBuffer(encryptedBase64); - - // 3. Unwrap AES key - const wrappedKeyBase64 = isRecipient - ? keysMetadata.recipient_wrapped_key - : keysMetadata.sender_wrapped_key; - - if (!wrappedKeyBase64) { - throw new Error('No wrapped key available'); - } - - const privateKey = await subtle.importKey( - 'jwk', - privateKeyJwk, - { name: 'RSA-OAEP', hash: 'SHA-256' }, - false, - ['decrypt'] - ); - - const rawAesKey = await subtle.decrypt( - { name: 'RSA-OAEP' }, - privateKey, - base64ToArrayBuffer(wrappedKeyBase64) - ); - - const aesKey = await subtle.importKey( - 'raw', - rawAesKey, - { name: 'AES-GCM' }, - false, - ['decrypt'] - ); - - // 4. Decrypt file - const iv = base64ToArrayBuffer(encryptionIv); - const decryptedData = await subtle.decrypt( - { name: 'AES-GCM', iv }, - aesKey, - encryptedData - ); - - // 5. Write decrypted file - const ext = mediaType === 'video' ? 'mp4' : 'jpg'; - const decryptedUri = `${FileSystem.cacheDirectory}${Date.now()}_decrypted.${ext}`; - - await FileSystem.writeAsStringAsync( - decryptedUri, - arrayBufferToBase64(decryptedData), - { encoding: FileSystem.EncodingType.Base64 } - ); - - // 6. Clean up encrypted temp file - await FileSystem.deleteAsync(downloadResult.uri, { idempotent: true }); - - return decryptedUri; -} -``` - -### Backwards Compatible Message Hook - -```typescript -// hooks/useDecryptedMessage.ts - -import { useState, useEffect } from 'react'; -import { decryptTextMessage } from '../lib/encryption/messageDecryption'; -import { useEncryptionKeys } from './useEncryptionKeys'; -import type { Message } from '../features/chat/types'; - -interface DecryptedMessageState { - content: string | null; - mediaUri: string | null; - isDecrypting: boolean; - error: Error | null; -} - -export function useDecryptedMessage( - message: Message, - isMe: boolean -): DecryptedMessageState { - const [state, setState] = useState({ - content: null, - mediaUri: null, - isDecrypting: false, - error: null, - }); - - const { privateKeyJwk } = useEncryptionKeys(); - - useEffect(() => { - async function decrypt() { - // Version 1 or undefined: Legacy plaintext - if (!message.version || message.version === 1) { - setState({ - content: message.content, - mediaUri: null, // Handle via existing signed URL flow - isDecrypting: false, - error: null, - }); - return; - } - - // Version 2: E2EE - requires decryption - if (message.version === 2) { - if (!privateKeyJwk) { - setState({ - content: null, - mediaUri: null, - isDecrypting: false, - error: new Error('Encryption keys not available'), - }); - return; - } - - setState(prev => ({ ...prev, isDecrypting: true })); - - try { - let content: string | null = null; - - if (message.encrypted_content) { - content = await decryptTextMessage( - message.encrypted_content, - message.encryption_iv!, - message.keys_metadata!, - privateKeyJwk, - !isMe - ); - } - - setState({ - content, - mediaUri: null, // Media handled separately via useDecryptedMedia - isDecrypting: false, - error: null, - }); - } catch (err) { - console.error('Failed to decrypt message:', err); - setState({ - content: '[Unable to decrypt]', - mediaUri: null, - isDecrypting: false, - error: err as Error, - }); - } - } - } - - decrypt(); - }, [message.id, message.version, privateKeyJwk, isMe]); - - return state; -} -``` - -### Encryption Keys Hook - -```typescript -// hooks/useEncryptionKeys.ts - -import { useState, useEffect } from 'react'; -import { getPrivateKey, hasKeyPair } from '../lib/encryption/keyManager'; - -interface EncryptionKeysState { - privateKeyJwk: JsonWebKey | null; - isLoading: boolean; - hasKeys: boolean; -} - -export function useEncryptionKeys(): EncryptionKeysState { - const [state, setState] = useState({ - privateKeyJwk: null, - isLoading: true, - hasKeys: false, - }); - - useEffect(() => { - async function loadKeys() { - try { - const hasKeys = await hasKeyPair(); - if (hasKeys) { - const privateKey = await getPrivateKey(); - setState({ - privateKeyJwk: privateKey, - isLoading: false, - hasKeys: true, - }); - } else { - setState({ - privateKeyJwk: null, - isLoading: false, - hasKeys: false, - }); - } - } catch (error) { - console.error('Failed to load encryption keys:', error); - setState({ - privateKeyJwk: null, - isLoading: false, - hasKeys: false, - }); - } - } - - loadKeys(); - }, []); - - return state; -} -``` - ---- - -## Edge Functions - -### Pending Recipient Re-encryption - -When a partner generates their keys after messages were already sent: - -```typescript -// supabase/functions/reencrypt-pending-messages/index.ts - -import "jsr:@supabase/functions-js/edge-runtime.d.ts"; -import { createClient } from "jsr:@supabase/supabase-js@2"; - -const supabaseAdmin = createClient( - Deno.env.get('SUPABASE_URL')!, - Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')! -); - -Deno.serve(async (req: Request) => { - try { - const { couple_id, new_recipient_user_id, new_recipient_public_key_jwk } = await req.json(); - - // Get admin private key from environment - const adminPrivateKeyJwk = JSON.parse( - Deno.env.get('ADMIN_PRIVATE_KEY_JWK')! - ); - - // Find messages with pending_recipient = true for this couple - const { data: matches } = await supabaseAdmin - .from('matches') - .select('id') - .eq('couple_id', couple_id); - - const matchIds = matches?.map(m => m.id) || []; - - const { data: messages } = await supabaseAdmin - .from('messages') - .select('id, user_id, keys_metadata') - .eq('version', 2) - .in('match_id', matchIds); - - let updatedCount = 0; - - for (const message of messages || []) { - const metadata = message.keys_metadata; - - // Only process if pending_recipient OR missing recipient key for this user - if (!metadata.pending_recipient && metadata.recipient_wrapped_key) { - continue; - } - - // Unwrap AES key using admin key - const rawAesKey = await unwrapWithAdminKey( - metadata.admin_wrapped_key, - adminPrivateKeyJwk - ); - - // Re-wrap for new recipient - const recipientWrappedKey = await wrapForRecipient( - rawAesKey, - new_recipient_public_key_jwk - ); - - // Update message - await supabaseAdmin - .from('messages') - .update({ - keys_metadata: { - ...metadata, - recipient_wrapped_key: recipientWrappedKey, - pending_recipient: false, - } - }) - .eq('id', message.id); - - updatedCount++; - } - - return new Response( - JSON.stringify({ success: true, updated: updatedCount }), - { headers: { 'Content-Type': 'application/json' } } - ); - } catch (error) { - console.error('Error re-encrypting messages:', error); - return new Response( - JSON.stringify({ success: false, error: error.message }), - { status: 500, headers: { 'Content-Type': 'application/json' } } - ); - } -}); - -async function unwrapWithAdminKey( - wrappedKeyBase64: string, - adminPrivateKeyJwk: JsonWebKey -): Promise { - 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 { - const publicKey = await crypto.subtle.importKey( - 'jwk', - recipientPublicKeyJwk, - { name: 'RSA-OAEP', hash: 'SHA-256' }, - false, - ['encrypt'] - ); - - const wrappedKey = await crypto.subtle.encrypt( - { name: 'RSA-OAEP' }, - publicKey, - rawAesKey - ); - - return arrayBufferToBase64(wrappedKey); -} - -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); -} -``` - -### Handle Key Rotation (Device Change) - -When a user's public key changes (new device): - -```typescript -// supabase/functions/handle-key-rotation/index.ts - -import "jsr:@supabase/functions-js/edge-runtime.d.ts"; -import { createClient } from "jsr:@supabase/supabase-js@2"; - -const supabaseAdmin = createClient( - Deno.env.get('SUPABASE_URL')!, - Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')! -); - -Deno.serve(async (req: Request) => { - try { - const { user_id, new_public_key_jwk } = await req.json(); - - // Get admin private key from environment - const adminPrivateKeyJwk = JSON.parse( - Deno.env.get('ADMIN_PRIVATE_KEY_JWK')! - ); - - // Get user's couple_id - const { data: profile } = await supabaseAdmin - .from('profiles') - .select('couple_id') - .eq('id', user_id) - .single(); - - if (!profile?.couple_id) { - return new Response( - JSON.stringify({ success: true, updated: 0, reason: 'No couple' }), - { headers: { '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) || []; - - // Find all v2 messages in these matches - const { data: messages } = await supabaseAdmin - .from('messages') - .select('id, user_id, keys_metadata') - .eq('version', 2) - .in('match_id', matchIds); - - let updatedCount = 0; - - for (const message of messages || []) { - const metadata = message.keys_metadata; - const isSender = message.user_id === user_id; - - // 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, - new_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; - } - - await supabaseAdmin - .from('messages') - .update({ keys_metadata: updatedMetadata }) - .eq('id', message.id); - - updatedCount++; - } - - return new Response( - JSON.stringify({ success: true, updated: updatedCount }), - { headers: { 'Content-Type': 'application/json' } } - ); - } catch (error) { - console.error('Error handling key rotation:', error); - return new Response( - JSON.stringify({ success: false, error: error.message }), - { status: 500, headers: { 'Content-Type': 'application/json' } } - ); - } -}); - -// ... include unwrapWithAdminKey, wrapForRecipient, base64 utils from above -``` - ---- - -## Admin Moderation Utility - -```typescript -// Admin dashboard utility or Edge Function - -export async function decryptForModeration( - messageId: string, - adminPrivateKeyJwk: JsonWebKey -): Promise { - - // 1. Fetch message with admin privileges - const { data: message } = await supabaseAdmin - .from('messages') - .select('*') - .eq('id', messageId) - .single(); - - if (!message) { - throw new Error('Message not found'); - } - - // 2. Version 1: Return plaintext directly - if (!message.version || message.version === 1) { - return { - content: message.content, - mediaUrl: message.media_path - ? await getAdminSignedUrl(message.media_path) - : null, - }; - } - - // 3. Version 2: Decrypt with admin key - const { admin_wrapped_key, admin_key_id } = message.keys_metadata; - - // Verify master key exists - const { data: masterKey } = await supabaseAdmin - .from('master_keys') - .select('id') - .eq('id', admin_key_id) - .single(); - - if (!masterKey) { - throw new Error(`Master key ${admin_key_id} not found - may have been rotated`); - } - - // Import admin private key - const privateKey = await crypto.subtle.importKey( - 'jwk', - adminPrivateKeyJwk, - { name: 'RSA-OAEP', hash: 'SHA-256' }, - false, - ['decrypt'] - ); - - // Unwrap AES key - const rawAesKey = await crypto.subtle.decrypt( - { name: 'RSA-OAEP' }, - privateKey, - base64ToArrayBuffer(admin_wrapped_key) - ); - - // Import AES key - const aesKey = await crypto.subtle.importKey( - 'raw', - rawAesKey, - { name: 'AES-GCM' }, - false, - ['decrypt'] - ); - - // Decrypt text content - let content: string | null = null; - if (message.encrypted_content) { - const plaintext = await crypto.subtle.decrypt( - { name: 'AES-GCM', iv: base64ToArrayBuffer(message.encryption_iv) }, - aesKey, - base64ToArrayBuffer(message.encrypted_content) - ); - content = new TextDecoder().decode(plaintext); - } - - // For media: download .enc file and decrypt similarly - let mediaUrl: string | null = null; - if (message.media_path && !message.media_expired) { - // Implementation would download and decrypt the .enc file - // Return a temporary signed URL or blob URL - } - - return { content, mediaUrl }; -} - -async function getAdminSignedUrl(mediaPath: string): Promise { - const { data } = await supabaseAdmin.storage - .from('chat-media') - .createSignedUrl(mediaPath, 3600); - return data?.signedUrl || ''; -} -``` - ---- - -## Implementation Tasks - -### Phase 1: Database & Infrastructure -| Task | Priority | Status | -|------|----------|--------| -| 1.1 Create migration: Add E2EE columns to `messages` table | High | ✅ | -| 1.2 Create migration: Add `public_key_jwk` to `profiles` table | High | ✅ | -| 1.3 Create migration: Create `master_keys` table with RLS policies | High | ✅ | -| 1.4 Generate master admin RSA-2048 key pair | High | ⬜ | -| 1.5 Insert master public key into `master_keys` table | High | ⬜ | -| 1.6 Store master private key in Supabase Edge Function secrets | High | ⬜ | -| 1.7 Update TypeScript types (`supabase.ts`) with new columns | High | ✅ | - -### Phase 2: Crypto Library Integration -| Task | Priority | Status | -|------|----------|--------| -| 2.1 Install `react-native-quick-crypto@^0.7.x` | High | ✅ | -| 2.2 Run `npx expo prebuild --clean` for iOS and Android | High | ⬜ | -| 2.3 Update `metro.config.js` to resolve `crypto` module | High | ✅ | -| 2.4 Create `src/lib/encryption/` directory structure | High | ✅ | -| 2.5 Implement utility functions (base64, ArrayBuffer) | High | ✅ | -| 2.6 Test basic crypto operations work on device | High | ⬜ | - -### Phase 3: Key Management -| Task | Priority | Status | -|------|----------|--------| -| 3.1 Implement `keyManager.ts` with key generation | High | ✅ | -| 3.2 Implement SecureStore chunked storage for private keys | High | ✅ | -| 3.3 Implement public key upload to Supabase profile | High | ✅ | -| 3.4 Create `useEncryptionKeys` hook | High | ✅ | -| 3.5 Add key initialization to app startup (auth flow) | High | ✅ | -| 3.6 Handle key generation when joining a couple | High | ✅ | - -### Phase 4: Text Message Encryption -| Task | Priority | Status | -|------|----------|--------| -| 4.1 Implement `messageEncryption.ts` | High | ✅ | -| 4.2 Implement `messageDecryption.ts` | High | ✅ | -| 4.3 Implement `adminKeys.ts` (fetch active admin public key) | High | ✅ | -| 4.4 Update `ChatScreen.tsx` `handleSend` to encrypt text | High | ✅ | -| 4.5 Create `useDecryptedMessage` hook | High | ✅ | -| 4.6 Update message insert to include encryption fields | High | ✅ | - -### Phase 5: Media Encryption -| Task | Priority | Status | -|------|----------|--------| -| 5.1 Implement `mediaEncryption.ts` (full file approach) | High | ✅ | -| 5.2 Implement `mediaDecryption.ts` (download-first) | High | ✅ | -| 5.3 Update `useMediaUpload.ts` to encrypt before upload | High | ✅ | -| 5.4 Update filename to use `.enc` extension | High | ✅ | -| 5.5 Update `MessageContent.tsx` for encrypted media handling | High | ✅ | -| 5.6 Implement decrypted media caching (avoid re-decrypting) | Medium | ✅ | - -### Phase 6: Backwards Compatibility -| Task | Priority | Status | -|------|----------|--------| -| 6.1 Update `MessageContent.tsx` to check `version` field | High | ✅ | -| 6.2 Render v1 messages with existing plaintext flow | High | ✅ | -| 6.3 Render v2 messages with decryption flow | High | ✅ | -| 6.4 Add loading state while decrypting | Medium | ✅ | -| 6.5 Add error state for decryption failures | Medium | ✅ | -| 6.6 Test mixed v1/v2 message thread | High | ⬜ | - -### Phase 7: Pending Recipient & Key Rotation -| Task | Priority | Status | -|------|----------|--------| -| 7.1 Handle sending when partner has no public key | Medium | ✅ | -| 7.2 Create `reencrypt-pending-messages` Edge Function | Medium | ✅ | -| 7.3 Trigger re-encryption when partner generates keys | Medium | ✅ | -| 7.4 Create `handle-key-rotation` Edge Function | Medium | ✅ | -| 7.5 Trigger key rotation when public_key_jwk changes | Medium | ⬜ | -| 7.6 Test end-to-end flow with new device | High | ⬜ | - -### Phase 8: Admin Moderation -| Task | Priority | Status | -|------|----------|--------| -| 8.1 Implement `decryptForModeration` utility | Medium | ⬜ | -| 8.2 Create admin UI for message decryption (if needed) | Low | ⬜ | -| 8.3 Add audit logging for admin decryptions | Medium | ⬜ | -| 8.4 Test admin decryption of v1 and v2 messages | Medium | ⬜ | - -### Phase 9: Testing & Polish -| Task | Priority | Status | -|------|----------|--------| -| 9.1 Unit tests for encryption/decryption functions | High | ⬜ | -| 9.2 Unit tests for key management | High | ⬜ | -| 9.3 Integration test: Send and receive encrypted text | High | ⬜ | -| 9.4 Integration test: Send and receive encrypted image | High | ⬜ | -| 9.5 Integration test: Send and receive encrypted video | High | ⬜ | -| 9.6 Test on low-end Android device (memory) | Medium | ⬜ | -| 9.7 Test key persistence across app restarts | High | ⬜ | -| 9.8 Test backward compatibility with existing messages | High | ⬜ | -| 9.9 Performance testing (encryption time for large videos) | Medium | ⬜ | - -### Phase 10: Documentation & Deployment -| Task | Priority | Status | -|------|----------|--------| -| 10.1 Update CLAUDE.md with E2EE architecture notes | Medium | ⬜ | -| 10.2 Document key rotation procedure | Medium | ⬜ | -| 10.3 Document admin moderation procedure | Medium | ⬜ | -| 10.4 Create deployment checklist | Medium | ⬜ | -| 10.5 Deploy migrations to non-prod first | High | ⬜ | -| 10.6 Test on non-prod thoroughly | High | ⬜ | -| 10.7 Deploy to production | High | ⬜ | - ---- - -## Utility Functions - -```typescript -// utils.ts - -export 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); -} - -export 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; -} - -export function chunkString(str: string, size: number): string[] { - const chunks: string[] = []; - for (let i = 0; i < str.length; i += size) { - chunks.push(str.slice(i, i + size)); - } - return chunks; -} -``` - ---- - -## TypeScript Types - -```typescript -// types.ts - -export interface KeysMetadata { - sender_wrapped_key: string; - recipient_wrapped_key?: string; - admin_wrapped_key: string; - admin_key_id: string; - algorithm: 'AES-256-GCM'; - key_wrap_algorithm: 'RSA-OAEP-SHA256'; - pending_recipient?: boolean; -} - -export interface EncryptedMessagePayload { - version: 2; - encrypted_content: string; - encryption_iv: string; - keys_metadata: KeysMetadata; -} - -export interface EncryptedMediaPayload { - encryptedFileUri: string; - encryption_iv: string; - keys_metadata: KeysMetadata; -} - -export interface DecryptedContent { - content: string | null; - mediaUrl: string | null; -} - -export interface DecryptedMessageState { - content: string | null; - mediaUri: string | null; - isDecrypting: boolean; - error: Error | null; -} -``` - ---- - -## Security Considerations - -### Key Storage -- Private keys stored in iOS Keychain / Android Keystore via SecureStore -- Keys accessible only when device is unlocked (`WHEN_UNLOCKED_THIS_DEVICE_ONLY`) -- Private keys never transmitted (except admin key stored in env) - -### Device Change Recovery -- When user gets new device, old private key is lost -- Admin key used to re-wrap all message AES keys with new public key -- User regains access to all historical messages automatically - -### Admin Access -- Admin can decrypt any message for moderation purposes -- Admin private key stored securely in environment variable -- Audit logging recommended for accountability - -### Key Rotation (Admin) -- Old master keys archived (remain in `master_keys` table with `is_active: false`) -- Messages encrypted with old admin keys remain decryptable -- New messages use active master key - -### Couple Breakup -- Both users retain their private keys -- Both can still decrypt their own sent/received messages -- No special handling required - ---- - -## Future Enhancements - -1. **Passphrase-based Key Backup**: Allow users to backup their private key encrypted with a passphrase to iCloud/Google Drive for manual recovery. - -2. **Key Fingerprint Verification**: Show key fingerprints so partners can verify each other's identity out-of-band. - -3. **Message Expiry**: Auto-delete decryption keys after a certain period for enhanced privacy. - -4. **Multi-device Support**: Sync private keys across user's devices (requires secure key transfer protocol). - ---- - -## Appendix: Admin Key Generation Script - -Run this once to generate the initial admin RSA key pair: - -```javascript -// scripts/generate-admin-keys.js -// Run with: node scripts/generate-admin-keys.js - -const crypto = require('crypto'); - -async function generateAdminKeyPair() { - const { publicKey, privateKey } = await crypto.subtle.generateKey( - { - name: 'RSA-OAEP', - modulusLength: 2048, - publicExponent: new Uint8Array([1, 0, 1]), - hash: 'SHA-256', - }, - true, - ['encrypt', 'decrypt'] - ); - - const publicKeyJwk = await crypto.subtle.exportKey('jwk', publicKey); - const privateKeyJwk = await crypto.subtle.exportKey('jwk', privateKey); - - console.log('=== PUBLIC KEY (store in master_keys table) ==='); - console.log(JSON.stringify(publicKeyJwk, null, 2)); - - console.log('\n=== PRIVATE KEY (store in ADMIN_PRIVATE_KEY_JWK env var) ==='); - console.log(JSON.stringify(privateKeyJwk)); -} - -generateAdminKeyPair().catch(console.error); -``` - -**Important:** Keep the private key secure. Never commit it to version control.