SPB Git

Repository Public

CryptoNegativeTests.swift 42.1 KB 583 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Vault9// File             : apple/SharedVaultKit/Tests/SharedVaultKitTests/CryptoNegativeTests.swift10// Module           : SharedVaultKitTests11// Repository       : https://git.spboucher.ai/sp-vault12// Project Website  : https://vault.spboucher.ai13// Created          : 2026-11-1914// Last Modified    : 2026-11-1915//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author           : Simon-Pierre Boucher21// Position         : Professor of Finance22// Institution      : Université du Québec en Outaouais (UQO)23// Department       : Département des sciences administratives24// Organization     : SP Boucher25//26// Website          : https://spboucher.ai27// Git              : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General          : info@spboucher.ai34// Professional     : contact@spboucher.ai35// Direct           : simon@spboucher.ai36// Research         : research@spboucher.ai37// Development      : dev@spboucher.ai38// Support          : support@spboucher.ai39// Security/Admin   : admin@spboucher.ai40// Notifications    : notifications@spboucher.ai41//42// Preferred Contact: support@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification   : Public67// Distribution     : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License          : None specified (no license file in this repository)81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import CryptoKit89import XCTest90@testable import SharedVaultKit9192final class CryptoNegativeTests: XCTestCase {93    let vk = pattern(32, 3)94    let ref = RecordRef(vaultId: "33333333-3333-4333-8333-333333333333", recordId: "44444444-4444-4444-8444-444444444444", type: .item, rev: 3)95    let json = Data("{\"type\":\"note\",\"title\":\"n\"}".utf8)9697    func flip(_ b64: String, at index: Int = 0) throws -> String {98        var d = try SPV1.unb64u(b64)99        d[d.startIndex + index] ^= 0x01100        return SPV1.b64u(d)101    }102103    // ── encodings ──104105    func testBase64urlStrictness() throws {106        XCTAssertEqual(SPV1.b64u(Data([0xfb, 0xff, 0xfe])), "-__-")107        XCTAssertEqual(try SPV1.unb64u("-__-"), Data([0xfb, 0xff, 0xfe]))108        XCTAssertEqual(try SPV1.unb64u(""), Data())109        for n in 0..<70 { let d = pattern(n, n); XCTAssertEqual(try SPV1.unb64u(SPV1.b64u(d)), d); XCTAssertFalse(SPV1.b64u(d).contains("=")) }110        for bad in ["A", "AAAAA", "AA==", "AA=", "A A", "AA\n", "+/+/", "é", "AA.A", " AAAA"] { assertThrows(.invalidBase64url, try SPV1.unb64u(bad)) }111    }112113    func testHexAndContext() throws {114        XCTAssertEqual(SPV1.hex(Data([0, 1, 0xab, 0xff])), "0001abff")115        XCTAssertEqual(try SPV1.unhex("0001ABff"), Data([0, 1, 0xab, 0xff]))116        assertThrows(.invalidHex, try SPV1.unhex("abc"))117        assertThrows(.invalidHex, try SPV1.unhex("zz"))118        XCTAssertEqual(SPV1.hex(try SPV1.ctx("é", "", "ü")), "535056310002c3a900000002c3bc")119        // no two field splits collide120        XCTAssertNotEqual(try SPV1.ctx("a", "bc", "d"), try SPV1.ctx("a", "b", "cd"))121        XCTAssertNotEqual(try SPV1.ctx("a", "b"), try SPV1.ctx("a", "b", ""))122        XCTAssertNoThrow(try SPV1.ctx("l", String(repeating: "x", count: 0xffff)))123        assertThrows(.contextFieldTooLong, try SPV1.ctx("l", String(repeating: "x", count: 0x10000)))124    }125126    func testConstantTimeEqualAndRandom() {127        XCTAssertTrue(SPV1.ctEqual(Data([1, 2, 3]), Data([1, 2, 3])))128        XCTAssertFalse(SPV1.ctEqual(Data([1, 2, 3]), Data([1, 2, 4])))129        XCTAssertFalse(SPV1.ctEqual(Data([1, 2, 3]), Data([1, 2])))130        XCTAssertTrue(SPV1.ctEqual(Data(), Data()))131        let slice = Data([9, 1, 2, 3]).dropFirst() // non-zero startIndex132        XCTAssertTrue(SPV1.ctEqual(slice, Data([1, 2, 3])))133        XCTAssertEqual(SPV1.random(32).count, 32)134        XCTAssertNotEqual(SPV1.random(32), SPV1.random(32))135        XCTAssertTrue(SPV1.isUuid(SPV1.uuid()))136        XCTAssertFalse(SPV1.isUuid("11111111-1111-1111-8111-111111111111"))137        XCTAssertFalse(SPV1.isUuid("11111111-1111-4111-8111-11111111111G"))138    }139140    // ── AEAD / HKDF / signatures / HPKE ──141142    func testAead() throws {143        let key = pattern(32, 1), nonce = pattern(12, 2), aad = Data("aad".utf8), pt = Data("hello".utf8)144        let ct = try SPV1.aeadSeal(key: key, nonce: nonce, plaintext: pt, aad: aad)145        XCTAssertEqual(ct.count, pt.count + 16)146        XCTAssertEqual(try SPV1.aeadOpen(key: key, nonce: nonce, ciphertext: ct, aad: aad), pt)147        for i in 0..<ct.count { var t = ct; t[i] ^= 0x80; assertThrows(.authenticationFailed, try SPV1.aeadOpen(key: key, nonce: nonce, ciphertext: t, aad: aad)) }148        assertThrows(.authenticationFailed, try SPV1.aeadOpen(key: pattern(32, 9), nonce: nonce, ciphertext: ct, aad: aad))149        assertThrows(.authenticationFailed, try SPV1.aeadOpen(key: key, nonce: pattern(12, 3), ciphertext: ct, aad: aad))150        assertThrows(.authenticationFailed, try SPV1.aeadOpen(key: key, nonce: nonce, ciphertext: ct, aad: Data("aae".utf8)))151        assertThrows(.authenticationFailed, try SPV1.aeadOpen(key: key, nonce: nonce, ciphertext: ct.dropLast(), aad: aad))152        assertThrows(.ciphertextTooShort, try SPV1.aeadOpen(key: key, nonce: nonce, ciphertext: Data(count: 15), aad: aad))153        assertThrows(.invalidNonce, try SPV1.aeadSeal(key: key, nonce: pattern(11, 0), plaintext: pt, aad: aad))154        assertThrows(.invalidNonce, try SPV1.aeadOpen(key: key, nonce: pattern(16, 0), ciphertext: ct, aad: aad))155        assertThrows(.invalidKeyLength, try SPV1.aeadSeal(key: pattern(16, 0), nonce: nonce, plaintext: pt, aad: aad))156        assertThrows(.invalidKeyLength, try SPV1.aeadOpen(key: pattern(31, 0), nonce: nonce, ciphertext: ct, aad: aad))157        // empty plaintext and data slices with non-zero start index158        let empty = try SPV1.aeadSeal(key: key, nonce: nonce, plaintext: Data(), aad: Data())159        XCTAssertEqual(empty.count, 16)160        XCTAssertEqual(try SPV1.aeadOpen(key: key, nonce: nonce, ciphertext: (Data([0]) + ct).dropFirst(), aad: aad), pt)161    }162163    func testHkdfRfc5869Vector() throws {164        // RFC 5869 test case 1165        let okm = SPV1.hkdf(ikm: try SPV1.unhex("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"), salt: try SPV1.unhex("000102030405060708090a0b0c"),166                            info: try SPV1.unhex("f0f1f2f3f4f5f6f7f8f9"), length: 42)167        XCTAssertEqual(SPV1.hex(okm), "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865")168        // RFC 5869 test case 3 (empty salt and info)169        let okm3 = SPV1.hkdf(ikm: try SPV1.unhex("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"), salt: Data(), info: Data(), length: 42)170        XCTAssertEqual(SPV1.hex(okm3), "8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d201395faa4b61a96c8")171        // RFC 4231 test case 2 (HMAC-SHA256)172        XCTAssertEqual(SPV1.hex(SPV1.hmac(key: Data("Jefe".utf8), message: Data("what do ya want for nothing?".utf8))), "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843")173        XCTAssertEqual(SPV1.hex(SPV1.sha256(Data("abc".utf8))), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")174    }175176    func testSignatures() throws {177        let key = SPV1.generateSigKey(), msg = Data("message".utf8)178        let sig = try SPV1.sign(key: key, message: msg)179        XCTAssertEqual(sig.count, 64)180        let pub = key.publicKey.x963Representation181        XCTAssertEqual(pub.count, 65)182        XCTAssertTrue(try SPV1.verify(publicKey: pub, message: msg, signature: sig))183        XCTAssertFalse(try SPV1.verify(publicKey: pub, message: Data("messagf".utf8), signature: sig))184        var bad = sig; bad[10] ^= 1185        XCTAssertFalse(try SPV1.verify(publicKey: pub, message: msg, signature: bad))186        XCTAssertFalse(try SPV1.verify(publicKey: pub, message: msg, signature: sig.dropLast()))187        XCTAssertFalse(try SPV1.verify(publicKey: pub, message: msg, signature: Data(count: 64)))188        XCTAssertFalse(try SPV1.verify(publicKey: SPV1.generateSigKey().publicKey.x963Representation, message: msg, signature: sig))189        assertThrows(.invalidPublicKey, try SPV1.verify(publicKey: pub.dropLast(), message: msg, signature: sig))190        assertThrows(.invalidPublicKey, try SPV1.verify(publicKey: Data([4]) + Data(count: 64), message: msg, signature: sig)) // not on the curve191        assertThrows(.invalidPublicKey, try SPV1.verify(publicKey: key.publicKey.compressedRepresentation, message: msg, signature: sig))192    }193194    func testPrivateKeyImport() throws {195        let k = SPV1.generateKemKey(), s = SPV1.generateSigKey()196        XCTAssertEqual(k.x963Representation.count, 97)197        XCTAssertEqual(try SPV1.importKemPrivateX963(k.x963Representation).publicKey.x963Representation, k.publicKey.x963Representation)198        XCTAssertEqual(try SPV1.importSigPrivateX963(s.x963Representation).publicKey.x963Representation, s.publicKey.x963Representation)199        assertThrows(.invalidPrivateKey, try SPV1.importKemPrivateX963(k.x963Representation.dropLast()))200        assertThrows(.invalidPrivateKey, try SPV1.importSigPrivateX963(k.rawRepresentation))201        // public part that does not belong to the private scalar must be rejected202        let mismatched = SPV1.generateKemKey().publicKey.x963Representation + k.x963Representation.suffix(32)203        assertThrows(.invalidPrivateKey, try SPV1.importKemPrivateX963(mismatched))204        assertThrows(.invalidPrivateKey, try SPV1.importSigPrivateX963(SPV1.generateSigKey().publicKey.x963Representation + s.x963Representation.suffix(32)))205    }206207    func testHpke() throws {208        let k = SoftwareKEMKey(), info = Data("info".utf8), pt = Data("secret".utf8)209        let sealed = try SPV1.hpkeSeal(recipientPublicKey: k.publicKey, info: info, plaintext: pt)210        XCTAssertEqual(sealed.count, 65 + pt.count + 16)211        XCTAssertEqual(sealed.first, 4)212        XCTAssertEqual(try k.hpkeOpen(info: info, sealed: sealed), pt)213        XCTAssertNotEqual(try SPV1.hpkeSeal(recipientPublicKey: k.publicKey, info: info, plaintext: pt), sealed, "HPKE is randomized")214        assertThrows(.authenticationFailed, try k.hpkeOpen(info: Data("inf0".utf8), sealed: sealed))215        assertThrows(.authenticationFailed, try SoftwareKEMKey().hpkeOpen(info: info, sealed: sealed))216        for i in [0, 1, 40, 64, 65, 70, sealed.count - 1] { var t = sealed; t[i] ^= 1; assertThrows(.authenticationFailed, try k.hpkeOpen(info: info, sealed: t)) }217        assertThrows(.sealedBoxTooShort, try k.hpkeOpen(info: info, sealed: sealed.prefix(80)))218        assertThrows(.invalidPublicKey, try SPV1.hpkeSeal(recipientPublicKey: k.publicKey.dropFirst(), info: info, plaintext: pt))219        assertThrows(.invalidPublicKey, try SPV1.hpkeSeal(recipientPublicKey: Data([4]) + Data(repeating: 1, count: 64), info: info, plaintext: pt))220    }221222    // ── keys ──223224    func testKeysetRoundTripRewrapAndTamper() throws {225        let ark = SPV1.random(32), account = SPV1.generateAccountKeys(), id = SPV1.uuid()226        let blob = try SPV1.sealKeyset(ark: ark, accountId: id, keys: account)227        let opened = try SPV1.openKeyset(ark: ark, accountId: id, blob: blob)228        XCTAssertEqual(opened.sigPub, account.sigPub)229        XCTAssertEqual(opened.encPub, account.encPub)230        assertThrows(.authenticationFailed, try SPV1.openKeyset(ark: SPV1.random(32), accountId: id, blob: blob))231        assertThrows(.authenticationFailed, try SPV1.openKeyset(ark: ark, accountId: SPV1.uuid(), blob: blob))232        assertThrows(.authenticationFailed, try SPV1.openKeyset(ark: ark, accountId: id, blob: KeysetBlob(nonce: blob.nonce, ct: try flip(blob.ct, at: 5))))233        assertThrows(.authenticationFailed, try SPV1.openKeyset(ark: ark, accountId: id, blob: KeysetBlob(nonce: try flip(blob.nonce), ct: blob.ct)))234        assertThrows(.invalidBase64url, try SPV1.openKeyset(ark: ark, accountId: id, blob: KeysetBlob(nonce: "***", ct: blob.ct)))235        let newArk = SPV1.random(32)236        let rewrapped = try SPV1.rewrapKeyset(oldArk: ark, newArk: newArk, accountId: id, blob: blob)237        XCTAssertEqual(try SPV1.openKeyset(ark: newArk, accountId: id, blob: rewrapped).sigPub, account.sigPub)238        assertThrows(.authenticationFailed, try SPV1.openKeyset(ark: ark, accountId: id, blob: rewrapped))239        assertThrows(.authenticationFailed, try SPV1.rewrapKeyset(oldArk: newArk, newArk: ark, accountId: id, blob: blob))240        // authenticated but not a keyset241        let junk = try SPV1.sealKeysetRaw(ark: ark, accountId: id, plaintext: Data("{\"sig\":1}".utf8), nonce: SPV1.random(12))242        assertThrows(.invalidKeyset, try SPV1.openKeyset(ark: ark, accountId: id, blob: junk))243        XCTAssertEqual(try JSONValue.parse(SPV1.keysetPlaintext(account)).objectValue?.keys, ["sig", "enc"])244    }245246    func testDeviceCertAndArkEnvelope() throws {247        let account = SPV1.generateAccountKeys(), accountId = SPV1.uuid(), deviceId = SPV1.uuid(), dev = SPV1.generateDeviceKeys(), ark = SPV1.random(32)248        XCTAssertFalse(dev.isHardwareBound)249        let cert = try SPV1.signDeviceCert(account: account, accountId: accountId, deviceId: deviceId, encPub: dev.encPub, sigPub: dev.sigPub, createdAt: "2026-11-19T00:00:00.000Z")250        let d = DevicePublic(deviceId: deviceId, encPub: dev.encPub, sigPub: dev.sigPub, createdAt: "2026-11-19T00:00:00.000Z", cert: cert)251        XCTAssertTrue(SPV1.verifyDeviceCert(accountSigPub: account.sigPub, accountId: accountId, device: d))252        XCTAssertFalse(SPV1.verifyDeviceCert(accountSigPub: account.sigPub, accountId: SPV1.uuid(), device: d))253        XCTAssertFalse(SPV1.verifyDeviceCert(accountSigPub: SPV1.generateAccountKeys().sigPub, accountId: accountId, device: d))254        for mutate in [{ (x: inout DevicePublic) in x.encPub = x.sigPub }, { $0.sigPub = $0.encPub }, { $0.createdAt = "2026-11-19T00:00:00.001Z" }, { $0.cert = "!!" }, { $0.cert = "" }, { $0.deviceId += "x" }] as [(inout DevicePublic) -> Void] {255            var m = d; mutate(&m)256            XCTAssertFalse(SPV1.verifyDeviceCert(accountSigPub: account.sigPub, accountId: accountId, device: m))257        }258        XCTAssertFalse(SPV1.verifyDeviceCert(accountSigPub: Data(count: 65), accountId: accountId, device: d), "invalid account key must not throw")259        // a device signature made by the device key verifies with the generic verifier260        let sig = try dev.sig.sign(Data("challenge".utf8))261        XCTAssertTrue(try SPV1.verify(publicKey: dev.sig.publicKey, message: Data("challenge".utf8), signature: sig))262263        let env = try SPV1.wrapArkForDevice(ark: ark, accountId: accountId, deviceId: deviceId, devEncPub: dev.enc.publicKey)264        XCTAssertEqual(try SPV1.unwrapArk(device: dev, accountId: accountId, deviceId: deviceId, envelope: env), ark)265        assertThrows(.authenticationFailed, try SPV1.unwrapArk(device: dev, accountId: deviceId, deviceId: deviceId, envelope: env))266        assertThrows(.authenticationFailed, try SPV1.unwrapArk(device: SPV1.generateDeviceKeys(), accountId: accountId, deviceId: deviceId, envelope: env))267        assertThrows(.authenticationFailed, try SPV1.unwrapArk(device: dev, accountId: accountId, deviceId: deviceId, envelope: try flip(env, at: 80)))268        let short = try SPV1.wrapArkForDevice(ark: SPV1.random(31), accountId: accountId, deviceId: deviceId, devEncPub: dev.enc.publicKey)269        assertThrows(.invalidARK, try SPV1.unwrapArk(device: dev, accountId: accountId, deviceId: deviceId, envelope: short))270    }271272    func testRecoveryKeyEncoding() throws {273        let rk = pattern(32, 2)274        let text = try SPV1.encodeRecoveryKey(rk)275        XCTAssertTrue(text.hasPrefix("SPV1-"))276        XCTAssertEqual(text.count, 5 + 56 + 13)277        XCTAssertEqual(try SPV1.decodeRecoveryKey(text), rk)278        // tolerance: case, separators, whitespace, optional prefix, O→0, I/L→1279        XCTAssertEqual(try SPV1.decodeRecoveryKey(text.lowercased()), rk)280        XCTAssertEqual(try SPV1.decodeRecoveryKey("  " + text.replacingOccurrences(of: "-", with: " ") + "\n"), rk)281        XCTAssertEqual(try SPV1.decodeRecoveryKey(String(text.dropFirst(5)).replacingOccurrences(of: "-", with: "")), rk)282        let zeroOne = try SPV1.encodeRecoveryKey(Data(repeating: 0, count: 31) + Data([0x21])) // contains many 0 and at least one 1283        XCTAssertTrue(zeroOne.contains("0") && zeroOne.contains("1"))284        let original = try SPV1.decodeRecoveryKey(zeroOne)285        let body = String(zeroOne.dropFirst(5))286        XCTAssertEqual(try SPV1.decodeRecoveryKey("SPV1-" + body.replacingOccurrences(of: "0", with: "O")), original)287        XCTAssertEqual(try SPV1.decodeRecoveryKey("SPV1-" + body.replacingOccurrences(of: "0", with: "o")), original)288        XCTAssertEqual(try SPV1.decodeRecoveryKey("SPV1-" + body.replacingOccurrences(of: "1", with: "I")), original)289        XCTAssertEqual(try SPV1.decodeRecoveryKey("SPV1-" + body.replacingOccurrences(of: "1", with: "l")), original)290        XCTAssertEqual(try SPV1.decodeRecoveryKey("SPV1-" + body.replacingOccurrences(of: "1", with: "L").replacingOccurrences(of: "0", with: "O")), original)291        // typos: every single-character substitution is caught by the checksum (or the alphabet)292        let chars = Array(text)293        let alphabet = Array("0123456789ABCDEFGHJKMNPQRSTVWXYZ")294        var rejected = 0, total = 0295        for i in 5..<chars.count where chars[i] != "-" {296            for repl in [alphabet[(alphabet.firstIndex(of: chars[i])! + 1) % 32], alphabet[(alphabet.firstIndex(of: chars[i])! + 17) % 32]] {297                var c = chars; c[i] = repl298                total += 1299                do { _ = try SPV1.decodeRecoveryKey(String(c)) } catch VaultError.recoveryKeyChecksum { rejected += 1 } catch { XCTFail("unexpected error \(error)") }300            }301        }302        XCTAssertEqual(rejected, total, "single-character typos must fail the checksum")303        // transposition of two different adjacent characters304        var swapped = chars305        if let i = (5..<chars.count - 1).first(where: { chars[$0] != "-" && chars[$0 + 1] != "-" && chars[$0] != chars[$0 + 1] }) { swapped.swapAt(i, i + 1) }306        assertThrows(.recoveryKeyChecksum, try SPV1.decodeRecoveryKey(String(swapped)))307        assertThrows(.recoveryKeyMalformed, try SPV1.decodeRecoveryKey(String(text.dropLast())))308        assertThrows(.recoveryKeyMalformed, try SPV1.decodeRecoveryKey(text + "A"))309        assertThrows(.recoveryKeyMalformed, try SPV1.decodeRecoveryKey("SPV1-" + String(repeating: "U", count: 56)))310        assertThrows(.recoveryKeyMalformed, try SPV1.decodeRecoveryKey(""))311        assertThrows(.recoveryKeyMalformed, try SPV1.decodeRecoveryKey(text.replacingOccurrences(of: "A", with: "É")))312        assertThrows(.recoveryKeyLength, try SPV1.encodeRecoveryKey(Data(count: 31)))313        XCTAssertEqual(SPV1.generateRecoveryKey().count, 32)314    }315316    func testRecoveryEnvelope() throws {317        let rk = SPV1.random(32), ark = SPV1.random(32), id = SPV1.uuid()318        let env = try SPV1.sealRecoveryEnvelope(rk: rk, accountId: id, epoch: 2, ark: ark)319        XCTAssertEqual(try SPV1.unb64u(env).count, 12 + 32 + 16)320        XCTAssertEqual(try SPV1.openRecoveryEnvelope(rk: rk, accountId: id, epoch: 2, envelope: env), ark)321        assertThrows(.authenticationFailed, try SPV1.openRecoveryEnvelope(rk: rk, accountId: id, epoch: 1, envelope: env))322        assertThrows(.authenticationFailed, try SPV1.openRecoveryEnvelope(rk: rk, accountId: SPV1.uuid(), epoch: 2, envelope: env))323        assertThrows(.authenticationFailed, try SPV1.openRecoveryEnvelope(rk: SPV1.random(32), accountId: id, epoch: 2, envelope: env))324        assertThrows(.authenticationFailed, try SPV1.openRecoveryEnvelope(rk: rk, accountId: id, epoch: 2, envelope: try flip(env, at: 20)))325        assertThrows(.authenticationFailed, try SPV1.openRecoveryEnvelope(rk: rk, accountId: id, epoch: 2, envelope: try flip(env, at: 0)))326        XCTAssertThrowsError(try SPV1.openRecoveryEnvelope(rk: rk, accountId: id, epoch: 2, envelope: "AAAA"))327        XCTAssertNotEqual(try SPV1.recoveryAuth(rk: rk, accountId: id), try SPV1.recoveryAuth(rk: rk, accountId: SPV1.uuid()))328        XCTAssertEqual(try SPV1.unb64u(try SPV1.recoveryAuthHash(rk: rk, accountId: id)).count, 32)329    }330331    func testVaultGrant() throws {332        let owner = SPV1.generateAccountKeys(), member = SPV1.generateAccountKeys(), vk = SPV1.random(32)333        let vaultId = SPV1.uuid(), ownerId = SPV1.uuid(), memberId = SPV1.uuid()334        let g = try SPV1.grantVaultKey(granter: owner, granterAccountId: ownerId, vk: vk, vaultId: vaultId, epoch: 4, memberAccountId: memberId, memberEncPub: member.encPub, role: .editor)335        XCTAssertEqual(try SPV1.acceptVaultGrant(member: member, grant: g, granterSigPub: owner.sigPub), vk)336        assertThrows(.vaultGrantSignatureInvalid, try SPV1.acceptVaultGrant(member: member, grant: g, granterSigPub: member.sigPub))337        for mutate in [{ (x: inout VaultGrant) in x.epoch = 5 }, { $0.role = .owner }, { $0.vaultId = SPV1.uuid() }, { $0.memberAccountId = SPV1.uuid() }] as [(inout VaultGrant) -> Void] {338            var m = g; mutate(&m)339            assertThrows(.vaultGrantSignatureInvalid, try SPV1.acceptVaultGrant(member: member, grant: m, granterSigPub: owner.sigPub))340        }341        var tampered = g; tampered.envelope = try flip(g.envelope, at: 70)342        assertThrows(.vaultGrantSignatureInvalid, try SPV1.acceptVaultGrant(member: member, grant: tampered, granterSigPub: owner.sigPub))343        // valid signature, wrong recipient344        assertThrows(.authenticationFailed, try SPV1.acceptVaultGrant(member: owner, grant: g, granterSigPub: owner.sigPub))345        assertThrows(.invalidVaultKey, try SPV1.grantVaultKey(granter: owner, granterAccountId: ownerId, vk: SPV1.random(16), vaultId: vaultId, epoch: 1, memberAccountId: memberId, memberEncPub: member.encPub, role: .reader))346        // Codable round trip keeps the TypeScript key names347        let j = try JSONValue.from(g)348        XCTAssertEqual(Set(j.objectValue?.keys ?? []), ["vaultId", "epoch", "memberAccountId", "role", "envelope", "granterAccountId", "sig"])349        XCTAssertEqual(try j.decode(VaultGrant.self), g)350    }351352    func testPairing() throws {353        let secret = SPV1.random(16), id = SPV1.uuid(), dev = SPV1.generateDeviceKeys()354        let tag = try SPV1.pairingTag(secret: secret, pairingId: id, encPub: dev.encPub, sigPub: dev.sigPub)355        XCTAssertTrue(SPV1.verifyPairingTag(secret: secret, pairingId: id, encPub: dev.encPub, sigPub: dev.sigPub, tag: tag))356        XCTAssertFalse(SPV1.verifyPairingTag(secret: SPV1.random(16), pairingId: id, encPub: dev.encPub, sigPub: dev.sigPub, tag: tag))357        XCTAssertFalse(SPV1.verifyPairingTag(secret: secret, pairingId: SPV1.uuid(), encPub: dev.encPub, sigPub: dev.sigPub, tag: tag))358        XCTAssertFalse(SPV1.verifyPairingTag(secret: secret, pairingId: id, encPub: dev.sigPub, sigPub: dev.encPub, tag: tag), "server-substituted keys must fail")359        XCTAssertFalse(SPV1.verifyPairingTag(secret: secret, pairingId: id, encPub: dev.encPub, sigPub: dev.sigPub, tag: "not base64!"))360        XCTAssertFalse(SPV1.verifyPairingTag(secret: secret, pairingId: id, encPub: dev.encPub, sigPub: dev.sigPub, tag: String(tag.dropLast(2))))361        let sas = try SPV1.pairingSas(pairingId: id, encPub: dev.encPub, sigPub: dev.sigPub)362        XCTAssertEqual(sas.count, 6)363        XCTAssertTrue(sas.allSatisfy(\.isNumber))364        let code = SPV1.encodePairingCode(pairingId: id, secret: secret)365        let decoded = try SPV1.decodePairingCode("  \(code)\n")366        XCTAssertEqual(decoded.pairingId, id)367        XCTAssertEqual(decoded.secret, secret)368        for bad in ["", "spvault-pair:\(id)", "spvault-pair:\(id):short", "spvault:\(id):\(SPV1.b64u(secret))", "spvault-pair:\(id.uppercased()):\(SPV1.b64u(secret))", code + ":x", code + "A", "x" + code] {369            assertThrows(.notPairingCode, try SPV1.decodePairingCode(bad))370        }371        let account = SPV1.generateAccountKeys()372        let fp = try SPV1.accountFingerprint(sigPub: account.sigPub, encPub: account.encPub)373        XCTAssertEqual(fp.count, 24)374        XCTAssertEqual(fp.split(separator: " ").count, 5)375        XCTAssertNotEqual(fp, try SPV1.accountFingerprint(sigPub: account.encPub, encPub: account.sigPub))376    }377378    // ── records ──379380    func testRecordRoundTripAndPadding() throws {381        for n in [0, 1, 200, 255, 256, 257, 511, 512, 5000] {382            let body = "{\"notes\":\"" + String(repeating: "x", count: n) + "\"}"383            let e = try SPV1.sealRecord(vk: vk, kid: 2, ref: ref, json: Data(body.utf8))384            let ctLen = try SPV1.unb64u(e.ct).count385            XCTAssertEqual((ctLen - 16) % 256, 0)386            XCTAssertGreaterThanOrEqual(ctLen - 16, body.utf8.count)387            XCTAssertLessThan(ctLen - 16 - body.utf8.count, 256 + (body.utf8.count == 0 ? 1 : 0))388            XCTAssertEqual(try SPV1.openRecordData(keyFor: { $0 == 2 ? self.vk : nil }, ref: ref, envelope: e), Data(body.utf8))389        }390        XCTAssertEqual(try SPV1.pad(Data()).count, 256)391        XCTAssertEqual(try SPV1.pad(Data(count: 256)).count, 256)392        XCTAssertEqual(try SPV1.pad(Data(count: 257)).count, 512)393        XCTAssertEqual(try SPV1.pad(Data("ab".utf8)).suffix(254), Data(repeating: 0x20, count: 254))394        assertThrows(.recordTooLarge, try SPV1.pad(Data(count: SPV1.maxRecordPlaintext + 1)))395        XCTAssertNoThrow(try SPV1.sealRecord(vk: vk, kid: 1, ref: ref, json: Data("\"".utf8) + Data(repeating: 0x61, count: SPV1.maxRecordPlaintext - 2) + Data("\"".utf8)))396        // fresh salt and nonce per seal397        let a = try SPV1.sealRecord(vk: vk, kid: 1, ref: ref, json: json), b = try SPV1.sealRecord(vk: vk, kid: 1, ref: ref, json: json)398        XCTAssertNotEqual(a.salt, b.salt); XCTAssertNotEqual(a.nonce, b.nonce); XCTAssertNotEqual(a.ct, b.ct)399        // typed and Encodable entry points400        struct Note: Codable, Equatable { var title: String; var n: Int }401        let e = try SPV1.sealRecord(vk: vk, kid: 1, ref: ref, encoding: Note(title: "été / 🔐", n: 7))402        XCTAssertEqual(try SPV1.openRecord(Note.self, keyFor: { _ in self.vk }, ref: ref, envelope: e), Note(title: "été / 🔐", n: 7))403        XCTAssertEqual(try SPV1.openRecordJSON(keyFor: { _ in self.vk }, ref: ref, envelope: e), ["n": 7, "title": "été / 🔐"])404        var item = SPV1.newItem(.login, title: "Site"); item.fields["password"] = "pw"405        let ie = try SPV1.sealRecord(vk: vk, kid: 1, ref: ref, encoding: item)406        XCTAssertEqual(try SPV1.openRecord(Item.self, keyFor: { _ in self.vk }, ref: ref, envelope: ie), item)407        XCTAssertEqual(try SPV1.openRecordData(keyFor: { _ in self.vk }, ref: ref, envelope: ie), item.jsonData)408        // tombstone409        let t = try SPV1.sealRecord(vk: vk, kid: 1, ref: ref, json: Item.tombstoneJSON)410        XCTAssertTrue(try SPV1.openRecord(Item.self, keyFor: { _ in self.vk }, ref: ref, envelope: t).deleted)411        var zero = ref; zero.rev = 0412        assertThrows(.invalidRevision, try SPV1.sealRecord(vk: vk, kid: 1, ref: zero, json: json))413    }414415    func testRecordWrongKeyAadAndTamper() throws {416        let e = try SPV1.sealRecord(vk: vk, kid: 1, ref: ref, json: json)417        let key: (Int) -> Data? = { _ in self.vk }418        XCTAssertNoThrow(try SPV1.openRecordData(keyFor: key, ref: ref, envelope: e))419        // wrong key420        assertThrows(.authenticationFailed, try SPV1.openRecordData(keyFor: { _ in pattern(32, 4) }, ref: ref, envelope: e))421        assertThrows(.vaultKeyUnavailable(1), try SPV1.openRecordData(keyFor: { _ in nil }, ref: ref, envelope: e))422        // each AAD field423        var r = ref; r.vaultId = ref.recordId424        assertThrows(.authenticationFailed, try SPV1.openRecordData(keyFor: key, ref: r, envelope: e))425        r = ref; r.recordId = ref.vaultId426        assertThrows(.authenticationFailed, try SPV1.openRecordData(keyFor: key, ref: r, envelope: e))427        for other in [RecordType.vaultMeta, .collection] { r = ref; r.type = other; assertThrows(.authenticationFailed, try SPV1.openRecordData(keyFor: key, ref: r, envelope: e)) }428        for rev in [1, 2, 4, 30] { r = ref; r.rev = rev; assertThrows(.authenticationFailed, try SPV1.openRecordData(keyFor: key, ref: r, envelope: e), "replay as rev \(rev)") }429        var k = e; k.kid = 2430        assertThrows(.authenticationFailed, try SPV1.openRecordData(keyFor: key, ref: ref, envelope: k), "kid is bound by the AAD")431        // tampering432        var t = e; t.ct = try flip(e.ct, at: 0)433        assertThrows(.authenticationFailed, try SPV1.openRecordData(keyFor: key, ref: ref, envelope: t))434        t = e; t.ct = try flip(e.ct, at: try SPV1.unb64u(e.ct).count - 1)435        assertThrows(.authenticationFailed, try SPV1.openRecordData(keyFor: key, ref: ref, envelope: t))436        t = e; t.salt = try flip(e.salt)437        assertThrows(.authenticationFailed, try SPV1.openRecordData(keyFor: key, ref: ref, envelope: t))438        t = e; t.nonce = try flip(e.nonce)439        assertThrows(.authenticationFailed, try SPV1.openRecordData(keyFor: key, ref: ref, envelope: t))440        // authenticated plaintext that is not JSON is rejected441        let notJson = try SPV1.sealRecord(vk: vk, kid: 1, ref: ref, json: Data("not json".utf8))442        XCTAssertThrowsError(try SPV1.openRecordData(keyFor: key, ref: ref, envelope: notJson)) { if case VaultError.invalidJSON = $0 {} else { XCTFail("\($0)") } }443        let badUtf8 = try SPV1.sealRecord(vk: vk, kid: 1, ref: ref, json: Data([0x22, 0xff, 0x22]))444        XCTAssertThrowsError(try SPV1.openRecordData(keyFor: key, ref: ref, envelope: badUtf8))445    }446447    func testMalformedEnvelopes() throws {448        let e = try SPV1.sealRecord(vk: vk, kid: 1, ref: ref, json: json)449        XCTAssertNoThrow(try SPV1.checkEnvelope(e))450        var x = e; x.v = 2; assertThrows(.unsupportedEnvelopeVersion, try SPV1.checkEnvelope(x))451        x = e; x.v = 0; assertThrows(.unsupportedEnvelopeVersion, try SPV1.checkEnvelope(x))452        x = e; x.alg = 2; assertThrows(.unsupportedEnvelopeVersion, try SPV1.checkEnvelope(x))453        x = e; x.kid = 0; assertThrows(.invalidKeyId, try SPV1.checkEnvelope(x))454        x = e; x.kid = -1; assertThrows(.invalidKeyId, try SPV1.checkEnvelope(x))455        x = e; x.salt = SPV1.b64u(Data(count: 31)); assertThrows(.invalidEnvelopeSizes, try SPV1.checkEnvelope(x))456        x = e; x.salt = SPV1.b64u(Data(count: 33)); assertThrows(.invalidEnvelopeSizes, try SPV1.checkEnvelope(x))457        x = e; x.nonce = SPV1.b64u(Data(count: 11)); assertThrows(.invalidEnvelopeSizes, try SPV1.checkEnvelope(x))458        x = e; x.nonce = SPV1.b64u(Data(count: 16)); assertThrows(.invalidEnvelopeSizes, try SPV1.checkEnvelope(x))459        x = e; x.salt = e.salt + "="; assertThrows(.invalidBase64url, try SPV1.checkEnvelope(x))460        x = e; x.nonce = "@@@@"; assertThrows(.invalidBase64url, try SPV1.checkEnvelope(x))461        x = e; x.ct = e.ct + "+"; assertThrows(.invalidBase64url, try SPV1.checkEnvelope(x))462        for n in [0, 15, 16, 271, 273, 16 + 255, 16 + 257, SPV1.maxRecordPlaintext + 16 + 512] {463            x = e; x.ct = SPV1.b64u(Data(count: n)); assertThrows(.invalidCiphertextSize, try SPV1.checkEnvelope(x), "ct of \(n) bytes")464        }465        x = e; x.ct = SPV1.b64u(Data(count: 272)); XCTAssertNoThrow(try SPV1.checkEnvelope(x))466        assertThrows(.authenticationFailed, try SPV1.openRecordData(keyFor: { _ in self.vk }, ref: ref, envelope: x))467        // open refuses malformed envelopes before touching keys468        x = e; x.v = 2469        assertThrows(.unsupportedEnvelopeVersion, try SPV1.openRecordData(keyFor: { _ in XCTFail("key requested"); return nil }, ref: ref, envelope: x))470471        // untrusted JSON form472        let good = e.jsonValue.serializedString()473        XCTAssertEqual(try Envelope(json: Data(good.utf8)), e)474        func mutated(_ key: String, _ value: JSONValue?) -> Data { var o = e.jsonValue.objectValue!; o[key] = value; return JSONValue.object(o).serialized() }475        assertThrows(.unsupportedEnvelopeVersion, try Envelope(json: mutated("v", 2)))476        assertThrows(.unsupportedEnvelopeVersion, try Envelope(json: mutated("v", "1")))477        assertThrows(.unsupportedEnvelopeVersion, try Envelope(json: mutated("v", nil)))478        assertThrows(.unsupportedEnvelopeVersion, try Envelope(json: mutated("alg", 0)))479        assertThrows(.unsupportedEnvelopeVersion, try Envelope(json: Data("[]".utf8)))480        assertThrows(.unsupportedEnvelopeVersion, try Envelope(json: Data("null".utf8)))481        assertThrows(.unsupportedEnvelopeVersion, try Envelope(json: Data("{".utf8)))482        assertThrows(.invalidKeyId, try Envelope(json: mutated("kid", 1.5)))483        assertThrows(.invalidKeyId, try Envelope(json: mutated("kid", "1")))484        assertThrows(.invalidKeyId, try Envelope(json: mutated("kid", 0)))485        assertThrows(.invalidBase64url, try Envelope(json: mutated("salt", 5)))486        assertThrows(.invalidBase64url, try Envelope(json: mutated("ct", nil)))487        assertThrows(.invalidEnvelopeSizes, try Envelope(json: mutated("nonce", "AAAA")))488        XCTAssertEqual(try JSONValue.from(e), e.jsonValue)489        XCTAssertEqual(RecordType.vaultMeta.rawValue, "vault-meta")490    }491492    // ── attachments ──493494    func testAttachmentRoundTrip() throws {495        for size in [0, 1, 1000, SPV1.chunkSize - 1, SPV1.chunkSize, SPV1.chunkSize + 1, 2 * SPV1.chunkSize + 17] {496            let pt = Data((0..<size).map { UInt8(truncatingIfNeeded: $0 &* 31 &+ size) })497            let att = try SPV1.newAttachment(id: SPV1.uuid(), name: "f.bin", mime: "application/octet-stream", plaintext: pt)498            XCTAssertEqual(att.ref.chunks, SPV1.chunkCount(size: size))499            XCTAssertEqual(att.chunks.count, att.ref.chunks)500            XCTAssertEqual(att.ref.size, size)501            XCTAssertEqual(try SPV1.openAttachment(ref: att.ref, chunks: att.chunks), pt)502        }503        XCTAssertEqual(SPV1.chunkCount(size: 0), 1)504        XCTAssertEqual(SPV1.chunkCount(size: SPV1.chunkSize), 1)505        XCTAssertEqual(SPV1.chunkCount(size: SPV1.chunkSize + 1), 2)506    }507508    func testAttachmentTruncationReorderSubstitution() throws {509        let pt = SPV1.random(3 * SPV1.chunkSize + 5)510        let att = try SPV1.newAttachment(id: SPV1.uuid(), name: "f", mime: "m", plaintext: pt)511        XCTAssertEqual(att.chunks.count, 4)512        // truncated (drop last chunk): count mismatch; with a forged count the "final" flag and total in the AAD fail513        assertThrows(.attachmentChunkCountMismatch, try SPV1.openAttachment(ref: att.ref, chunks: Array(att.chunks.dropLast())))514        var forged = att.ref; forged.chunks = 3; forged.size = 3 * SPV1.chunkSize515        assertThrows(.authenticationFailed, try SPV1.openAttachment(ref: forged, chunks: Array(att.chunks.dropLast())))516        // extended517        assertThrows(.attachmentChunkCountMismatch, try SPV1.openAttachment(ref: att.ref, chunks: att.chunks + [att.chunks[0]]))518        // reordered519        var reordered = att.chunks; reordered.swapAt(0, 1)520        assertThrows(.authenticationFailed, try SPV1.openAttachment(ref: att.ref, chunks: reordered))521        // duplicated522        var dup = att.chunks; dup[2] = dup[1]523        assertThrows(.authenticationFailed, try SPV1.openAttachment(ref: att.ref, chunks: dup))524        // truncated chunk body / tampered525        var cut = att.chunks; cut[3] = cut[3].dropLast()526        assertThrows(.authenticationFailed, try SPV1.openAttachment(ref: att.ref, chunks: cut))527        var bit = att.chunks; bit[1][100] ^= 1528        assertThrows(.authenticationFailed, try SPV1.openAttachment(ref: att.ref, chunks: bit))529        // cross-file substitution: same key and prefix, different attachment id530        var other = att.ref; other.id = SPV1.uuid()531        assertThrows(.authenticationFailed, try SPV1.openAttachment(ref: other, chunks: att.chunks))532        // manifest integrity533        var wrongHash = att.ref; wrongHash.sha256 = SPV1.b64u(SPV1.sha256(Data("x".utf8)))534        assertThrows(.attachmentIntegrity, try SPV1.openAttachment(ref: wrongHash, chunks: att.chunks))535        var wrongSize = att.ref; wrongSize.size += 1536        assertThrows(.attachmentIntegrity, try SPV1.openAttachment(ref: wrongSize, chunks: att.chunks))537        // chunk-level API538        let key = SPV1.random(32), prefix = SPV1.random(8), id = SPV1.uuid()539        let c0 = try SPV1.sealChunk(key: key, prefix: prefix, id: id, index: 0, total: 2, data: Data(count: SPV1.chunkSize))540        assertThrows(.authenticationFailed, try SPV1.openChunk(key: key, prefix: prefix, id: id, index: 1, total: 2, data: c0))541        assertThrows(.authenticationFailed, try SPV1.openChunk(key: key, prefix: prefix, id: id, index: 0, total: 1, data: c0), "a non-final chunk cannot be passed off as final")542        assertThrows(.authenticationFailed, try SPV1.openChunk(key: key, prefix: prefix, id: id, index: 0, total: 3, data: c0))543        XCTAssertThrowsError(try SPV1.sealChunk(key: key, prefix: Data(count: 7), id: id, index: 0, total: 1, data: Data()))544        XCTAssertThrowsError(try SPV1.sealChunk(key: key, prefix: prefix, id: id, index: 0, total: 2, data: Data(count: 10)), "non-final chunk must be full")545        XCTAssertThrowsError(try SPV1.sealChunk(key: key, prefix: prefix, id: id, index: 0, total: 1, data: Data(count: SPV1.chunkSize + 1)))546    }547548    // ── relay and link ──549550    func testRelay() throws {551        let alice = SPV1.generateAccountKeys(), bob = SPV1.generateAccountKeys(), share = SPV1.uuid(), aId = SPV1.uuid(), bId = SPV1.uuid()552        let value: JSONValue = ["type": "note", "title": "shared"]553        let box = try SPV1.sealRelay(sender: alice, shareId: share, senderId: aId, recipientId: bId, recipientEncPub: bob.encPub, value: value)554        XCTAssertEqual(try SPV1.openRelayJSON(recipient: bob, shareId: share, senderId: aId, recipientId: bId, senderSigPub: alice.sigPub, box: box), value)555        XCTAssertEqual(try SPV1.openRelayData(recipient: bob, shareId: share, senderId: aId, recipientId: bId, senderSigPub: alice.sigPub, box: box), value.serialized())556        XCTAssertEqual(try SPV1.openRelay(Item.self, recipient: bob, shareId: share, senderId: aId, recipientId: bId, senderSigPub: alice.sigPub, box: box).title, "shared")557        XCTAssertEqual((try SPV1.unb64u(box.ct).count - 65 - 16) % 256, 0)558        assertThrows(.shareSignatureInvalid, try SPV1.openRelayData(recipient: bob, shareId: share, senderId: aId, recipientId: bId, senderSigPub: bob.sigPub, box: box))559        assertThrows(.shareSignatureInvalid, try SPV1.openRelayData(recipient: bob, shareId: SPV1.uuid(), senderId: aId, recipientId: bId, senderSigPub: alice.sigPub, box: box))560        assertThrows(.shareSignatureInvalid, try SPV1.openRelayData(recipient: bob, shareId: share, senderId: aId, recipientId: bId, senderSigPub: alice.sigPub, box: RelayBox(ct: try flip(box.ct, at: 90), sig: box.sig)))561        assertThrows(.authenticationFailed, try SPV1.openRelayData(recipient: bob, shareId: share, senderId: bId, recipientId: bId, senderSigPub: alice.sigPub, box: box))562        assertThrows(.authenticationFailed, try SPV1.openRelayData(recipient: bob, shareId: share, senderId: aId, recipientId: aId, senderSigPub: alice.sigPub, box: box))563        assertThrows(.authenticationFailed, try SPV1.openRelayData(recipient: alice, shareId: share, senderId: aId, recipientId: bId, senderSigPub: alice.sigPub, box: box))564    }565566    func testLink() throws {567        let secret = SPV1.random(32), share = SPV1.uuid()568        let value: JSONValue = ["hello": "link"]569        let box = try SPV1.sealLink(secret: secret, shareId: share, value: value)570        XCTAssertEqual(try SPV1.openLinkJSON(secret: secret, shareId: share, box: box), value)571        XCTAssertEqual(try SPV1.openLinkData(secret: secret, shareId: share, box: box), Data("{\"hello\":\"link\"}".utf8))572        struct Hello: Decodable, Equatable { var hello: String }573        XCTAssertEqual(try SPV1.openLink(Hello.self, secret: secret, shareId: share, box: box), Hello(hello: "link"))574        assertThrows(.authenticationFailed, try SPV1.openLinkData(secret: SPV1.random(32), shareId: share, box: box))575        assertThrows(.authenticationFailed, try SPV1.openLinkData(secret: secret, shareId: SPV1.uuid(), box: box))576        assertThrows(.authenticationFailed, try SPV1.openLinkData(secret: secret, shareId: share, box: try flip(box, at: 30)))577        assertThrows(.invalidLinkSecret, try SPV1.linkKeys(secret: SPV1.random(31), shareId: share))578        let k = try SPV1.linkKeys(secret: secret, shareId: share)579        XCTAssertEqual(k.authHash, SPV1.b64u(SPV1.sha256(try SPV1.unb64u(k.auth))))580        XCTAssertNotEqual(SPV1.b64u(k.key), k.auth, "the download authenticator must not be the content key")581    }582}583
Files main
Menu

Theme