Modern Apps git

← Modern-Apps.git

findfamily: shorten share links via a seeded ML-KEM link key

Commit
898a90db932bd684887900b84cace2be5340d9ac
Author
Vayun Mathur <[email protected]>
When
2026-08-20 20:06 UTC (3 months ago)
Parents
638fd15

Diff

FindFamilyiOS/Crypto/PQCCrypto.swift
diff --git a/FindFamilyiOS/Crypto/PQCCrypto.swift b/FindFamilyiOS/Crypto/PQCCrypto.swiftindex a14f50408d..dc8712094e 100644--- a/FindFamilyiOS/Crypto/PQCCrypto.swift+++ b/FindFamilyiOS/Crypto/PQCCrypto.swift@@ -169,6 +169,21 @@ func pqc_identity_keygen(     _ priv_bundle_len_out: UnsafeMutablePointer<Int> ) -> Int32 +@_silgen_name("pqc_link_keygen")+func pqc_link_keygen(+    _ seed_out: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>,+    _ seed_len_out: UnsafeMutablePointer<Int>,+    _ pub_bundle_out: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>,+    _ pub_bundle_len_out: UnsafeMutablePointer<Int>+) -> Int32++@_silgen_name("pqc_link_pub_from_seed")+func pqc_link_pub_from_seed(+    _ seed: UnsafePointer<UInt8>?, _ seed_len: Int,+    _ pub_bundle_out: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>,+    _ pub_bundle_len_out: UnsafeMutablePointer<Int>+) -> Int32+ @_silgen_name("pqc_kem_encaps") func pqc_kem_encaps(     _ kem_pub: UnsafePointer<UInt8>?, _ kem_pub_len: Int,@@ -311,4 +326,41 @@ enum PQCCrypto {         pqc_free(pr, privLen)         return (pubData, privData)     }++    /// Generates a share-link key: a 32-byte ML-KEM seed plus the ML-KEM-only public bundle+    /// it derives. The seed is the link's whole secret — it is what goes in the URL fragment,+    /// and the recipient's browser expands it back into the keypair.+    static func generateLinkKey() throws -> (seed: Data, publicBundle: Data) {+        var seedPtr: UnsafeMutablePointer<UInt8>? = nil+        var seedLen: Int = 0+        var pubPtr: UnsafeMutablePointer<UInt8>? = nil+        var pubLen: Int = 0+        let ok = pqc_link_keygen(&seedPtr, &seedLen, &pubPtr, &pubLen)+        guard ok == 1, let sp = seedPtr, let pb = pubPtr else {+            throw NSError(domain: "pqc", code: -7, userInfo: [NSLocalizedDescriptionKey: "link keygen failed (native not linked?)"])+        }+        defer {+            pqc_secure_zero(sp, seedLen)+            pqc_free(sp, seedLen)+            pqc_free(pb, pubLen)+        }+        return (Data(bytes: sp, count: seedLen), Data(bytes: pb, count: pubLen))+    }++    /// Re-derives a share-link public bundle from a stored 32-byte seed.+    static func linkPublicFromSeed(_ seed: Data) throws -> Data {+        var pubPtr: UnsafeMutablePointer<UInt8>? = nil+        var pubLen: Int = 0+        let ok: Int32 = seed.withUnsafeBytes { seedBuf in+            pqc_link_pub_from_seed(+                seedBuf.baseAddress?.assumingMemoryBound(to: UInt8.self), seedBuf.count,+                &pubPtr, &pubLen+            )+        }+        guard ok == 1, let pb = pubPtr else {+            throw NSError(domain: "pqc", code: -8, userInfo: [NSLocalizedDescriptionKey: "link key derivation failed"])+        }+        defer { pqc_free(pb, pubLen) }+        return Data(bytes: pb, count: pubLen)+    } }
FindFamilyiOS/Crypto/PQCKeyManager.swift
diff --git a/FindFamilyiOS/Crypto/PQCKeyManager.swift b/FindFamilyiOS/Crypto/PQCKeyManager.swiftindex cdb0253d18..bf9f0f86be 100644--- a/FindFamilyiOS/Crypto/PQCKeyManager.swift+++ b/FindFamilyiOS/Crypto/PQCKeyManager.swift@@ -142,13 +142,18 @@ final class PQCKeyManager {         try identity().publicBundle.base64EncodedString()     } -    // MARK: - Ephemeral (TemporaryLink)--    /// Generate a fresh ephemeral PQC bundle for a TemporaryLink, same crypto as device identity.-    /// Returns (publicBundleB64, privateBundleB64).-    func generateEphemeralBundle() throws -> (publicB64: String, privateB64: String) {-        let (pubBundle, privBundle) = try PQCCrypto.generateIdentity()-        return (pubBundle.base64EncodedString(), privBundle.base64EncodedString())+    // MARK: - Share links (TemporaryLink)++    /// Generate a fresh share-link key. The link is ML-KEM only and derived from a 32-byte+    /// seed; the seed (base64url, unpadded) is what goes in the URL fragment, and the public+    /// bundle is what locations get encrypted to.+    func generateLinkKey() throws -> (seedB64Url: String, publicB64: String) {+        let (seed, pubBundle) = try PQCCrypto.generateLinkKey()+        let seedB64Url = seed.base64EncodedString()+            .replacingOccurrences(of: "+", with: "-")+            .replacingOccurrences(of: "/", with: "_")+            .replacingOccurrences(of: "=", with: "")+        return (seedB64Url, pubBundle.base64EncodedString())     }      // MARK: - Encrypt / Decrypt helpers (mirror Pqc.encryptTo / decrypt)
FindFamilyiOS/Crypto/PQCStubs.c
diff --git a/FindFamilyiOS/Crypto/PQCStubs.c b/FindFamilyiOS/Crypto/PQCStubs.cindex c62860cd82..cd8b4df239 100644--- a/FindFamilyiOS/Crypto/PQCStubs.c+++ b/FindFamilyiOS/Crypto/PQCStubs.c@@ -2,7 +2,8 @@ // // Purpose: allows the iOS app to build and link even when libe2ee_pqc.a XCFramework // is not present. Each function returns failure (0) / no-op, so PQC is reported as-// unavailable and Networking falls back to RSA-only — no crash, no link error.+// unavailable — no crash, no link error. There is no classic fallback: sharing simply+// does not work until the real library is linked. // // When the real Rust lib (src/main/rust) is built for iOS and added as // e2ee_pqc.xcframework (static lib), its strong symbols override these weak ones@@ -54,6 +55,22 @@ __attribute__((weak)) int32_t pqc_identity_keygen(     return 0; } +__attribute__((weak)) int32_t pqc_link_keygen(+    uint8_t **seed_out, size_t *seed_len_out,+    uint8_t **pub_bundle_out, size_t *pub_bundle_len_out) {+    (void)seed_out; (void)seed_len_out;+    (void)pub_bundle_out; (void)pub_bundle_len_out;+    return 0;+}++__attribute__((weak)) int32_t pqc_link_pub_from_seed(+    const uint8_t *seed, size_t seed_len,+    uint8_t **pub_bundle_out, size_t *pub_bundle_len_out) {+    (void)seed; (void)seed_len;+    (void)pub_bundle_out; (void)pub_bundle_len_out;+    return 0;+}+ __attribute__((weak)) int32_t pqc_kem_encaps(     const uint8_t *kem_pub, size_t kem_pub_len,     uint8_t **ct_out, size_t *ct_len_out,
FindFamilyiOS/Model/Models.swift
diff --git a/FindFamilyiOS/Model/Models.swift b/FindFamilyiOS/Model/Models.swiftindex 238e7386c4..e0f1d95fbe 100644--- a/FindFamilyiOS/Model/Models.swift+++ b/FindFamilyiOS/Model/Models.swift@@ -162,6 +162,10 @@ struct TemporaryLink: Identifiable, Codable, Hashable, Equatable {     var deleteAt: Date     /// PQC ephemeral public bundle (base64 [4B kemLen][kemPub][dsaPub]), nullable for migration.     var pqcPublicKey: String? = nil-    /// PQC ephemeral private bundle (base64 [4B kemPrivLen][kemPriv][dsaPriv]), nullable. Fragment `#pqc_key=` contains this.+    /// Legacy: the full PQC private bundle (base64 [4B kemPrivLen][kemPriv][dsaPriv]) that older+    /// builds put in the fragment as `#pqc_key=`. Only set on links created before [pqcSeed].     var pqcKey: String? = nil+    /// The 32-byte ML-KEM link seed (base64url, unpadded) — what goes in the fragment as `#s=`.+    /// This is the link's entire secret; the recipient's browser expands it into the keypair.+    var pqcSeed: String? = nil }
FindFamilyiOS/Persistence/Database.swift
diff --git a/FindFamilyiOS/Persistence/Database.swift b/FindFamilyiOS/Persistence/Database.swiftindex db396f7fb8..b8d8c56c9b 100644--- a/FindFamilyiOS/Persistence/Database.swift+++ b/FindFamilyiOS/Persistence/Database.swift@@ -109,6 +109,9 @@ final class Database {         if !columnExists(table: "temporaryLinks", column: "pqcKey") {             exec("ALTER TABLE temporaryLinks ADD COLUMN pqcKey TEXT;")         }+        if !columnExists(table: "temporaryLinks", column: "pqcSeed") {+            exec("ALTER TABLE temporaryLinks ADD COLUMN pqcSeed TEXT;")+        }     }      // MARK: - Reload helpers@@ -462,7 +465,7 @@ final class Database {         var result = link         queue.sync {             if link.id == 0 {-                let sql = "INSERT INTO temporaryLinks (name, key, publicKey, deleteAt, pqcPublicKey, pqcKey) VALUES (?, ?, ?, ?, ?, ?);"+                let sql = "INSERT INTO temporaryLinks (name, key, publicKey, deleteAt, pqcPublicKey, pqcKey, pqcSeed) VALUES (?, ?, ?, ?, ?, ?, ?);"                 var stmt: OpaquePointer?                 sqlite3_prepare_v2(db, sql, -1, &stmt, nil)                 bindText(stmt, 1, link.name)@@ -471,11 +474,12 @@ final class Database {                 sqlite3_bind_int64(stmt, 4, Int64(link.deleteAt.timeIntervalSince1970))                 bindOptionalText(stmt, 5, link.pqcPublicKey)                 bindOptionalText(stmt, 6, link.pqcKey)+                bindOptionalText(stmt, 7, link.pqcSeed)                 sqlite3_step(stmt)                 sqlite3_finalize(stmt)                 result.id = sqlite3_last_insert_rowid(db)             } else {-                let sql = "INSERT OR REPLACE INTO temporaryLinks (id, name, key, publicKey, deleteAt, pqcPublicKey, pqcKey) VALUES (?, ?, ?, ?, ?, ?, ?);"+                let sql = "INSERT OR REPLACE INTO temporaryLinks (id, name, key, publicKey, deleteAt, pqcPublicKey, pqcKey, pqcSeed) VALUES (?, ?, ?, ?, ?, ?, ?, ?);"                 var stmt: OpaquePointer?                 sqlite3_prepare_v2(db, sql, -1, &stmt, nil)                 sqlite3_bind_int64(stmt, 1, link.id)@@ -485,6 +489,7 @@ final class Database {                 sqlite3_bind_int64(stmt, 5, Int64(link.deleteAt.timeIntervalSince1970))                 bindOptionalText(stmt, 6, link.pqcPublicKey)                 bindOptionalText(stmt, 7, link.pqcKey)+                bindOptionalText(stmt, 8, link.pqcSeed)                 sqlite3_step(stmt)                 sqlite3_finalize(stmt)             }@@ -503,7 +508,7 @@ final class Database {     private func loadTemporaryLinks() -> [TemporaryLink] {         var out: [TemporaryLink] = []         // Try new schema first; fallback to old if column missing.-        let sql = "SELECT id, name, key, publicKey, deleteAt, pqcPublicKey, pqcKey FROM temporaryLinks;"+        let sql = "SELECT id, name, key, publicKey, deleteAt, pqcPublicKey, pqcKey, pqcSeed FROM temporaryLinks;"         var stmt: OpaquePointer?         let rc = sqlite3_prepare_v2(db, sql, -1, &stmt, nil)         if rc != SQLITE_OK {@@ -518,7 +523,8 @@ final class Database {                     publicKey: text(stmt, 3) ?? "",                     deleteAt: Date(timeIntervalSince1970: TimeInterval(sqlite3_column_int64(stmt, 4))),                     pqcPublicKey: nil,-                    pqcKey: nil+                    pqcKey: nil,+                    pqcSeed: nil                 ))             }             sqlite3_finalize(stmt)@@ -532,7 +538,8 @@ final class Database {                 publicKey: text(stmt, 3) ?? "",                 deleteAt: Date(timeIntervalSince1970: TimeInterval(sqlite3_column_int64(stmt, 4))),                 pqcPublicKey: text(stmt, 5),-                pqcKey: text(stmt, 6)+                pqcKey: text(stmt, 6),+                pqcSeed: text(stmt, 7)             ))         }         sqlite3_finalize(stmt)
FindFamilyiOS/UI/Cards.swift
diff --git a/FindFamilyiOS/UI/Cards.swift b/FindFamilyiOS/UI/Cards.swiftindex aa69747b34..2cc9661261 100644--- a/FindFamilyiOS/UI/Cards.swift+++ b/FindFamilyiOS/UI/Cards.swift@@ -198,10 +198,14 @@ struct TemporaryLinkCard: View {             }             Spacer()             Button {-                // Links are post-quantum only, matching Android: the fragment carries just-                // the PQC private bundle — no classic `#key=`. The fragment never hits the server.-                guard let pqcKey = link.pqcKey else { return }-                Platform.copy("https://findfamily.cc/view/\(UInt64(bitPattern: link.id))#pqc_key=\(pqcKey)")+                // The fragment carries the link's secret and never hits the server. New links+                // send just the 32-byte ML-KEM seed (`#s=`) with a Base26 id, which fits in an+                // SMS; links minted before that still carry their full private bundle.+                if let seed = link.pqcSeed {+                    Platform.copy("https://findfamily.cc/view/\(Base26.encode(link.id))#s=\(seed)")+                } else if let pqcKey = link.pqcKey {+                    Platform.copy("https://findfamily.cc/view/\(UInt64(bitPattern: link.id))#pqc_key=\(pqcKey)")+                }             } label: { Image(systemName: "doc.on.doc") }             Button(role: .destructive) {                 Database.shared.deleteTemporaryLink(link)
FindFamilyiOS/UI/Dialogs.swift
diff --git a/FindFamilyiOS/UI/Dialogs.swift b/FindFamilyiOS/UI/Dialogs.swiftindex 5f12d800c6..a00acf07d9 100644--- a/FindFamilyiOS/UI/Dialogs.swift+++ b/FindFamilyiOS/UI/Dialogs.swift@@ -280,9 +280,9 @@ struct AddLinkDialog: View {         working = true         Task {             do {-                // Links are post-quantum only: generate a PQC ephemeral bundle. There is no RSA+                // Links are post-quantum only: generate an ML-KEM link key. There is no RSA                 // fallback, so this fails the creation rather than downgrading to classic crypto.-                let ep = try PQCKeyManager.shared.generateEphemeralBundle()+                let linkKey = try PQCKeyManager.shared.generateLinkKey()                 let link = TemporaryLink(                     // A link id is the server-side recipient id (what `/view/<id>` resolves to)                     // and shares the random 64-bit namespace of userids. Room-style autoincrement@@ -294,12 +294,13 @@ struct AddLinkDialog: View {                     key: "",                     publicKey: "",                     deleteAt: Date().addingTimeInterval(expirySeconds),-                    pqcPublicKey: ep.publicB64,-                    pqcKey: ep.privateB64+                    pqcPublicKey: linkKey.publicB64,+                    pqcKey: nil,+                    pqcSeed: linkKey.seedB64Url                 )                 _ = Database.shared.upsertTemporaryLink(link)             } catch {-                print("AddLink: PQC ephemeral unavailable (native not linked?): \(error.localizedDescription)")+                print("AddLink: PQC link key unavailable (native not linked?): \(error.localizedDescription)")             }             working = false             isPresented = false