Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Vault9// File : apple/SharedVaultKit/Tests/SharedVaultKitTests/ItemsTransferTests.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 XCTest89@testable import SharedVaultKit9091final class ItemsTransferTests: XCTestCase {92 // ── items ──9394 func testNewItemAndJsonShape() throws {95 let item = SPV1.newItem(.login, title: "Site")96 XCTAssertEqual(item.createdAt, item.updatedAt)97 XCTAssertNotNil(try? Date.ISO8601FormatStyle(includingFractionalSeconds: true).parse(item.createdAt))98 XCTAssertEqual(item.createdAt.count, 24, "same shape as Date.toISOString(): 2026-11-19T00:00:00.000Z")99 XCTAssertTrue(item.createdAt.hasSuffix("Z"))100 // exactly the keys newItem() produces in TypeScript, in the same order101 XCTAssertEqual(item.jsonValue.objectValue?.keys, ["type", "title", "fields", "urls", "custom", "notes", "tags", "favorite", "attachments", "passwordHistory", "createdAt", "updatedAt"])102 var full = item103 full.collection = "c"; full.expiresAt = "2027-01-01"; full.rotateEveryDays = 30; full.conflictOf = "r"; full.trashedAt = "t"; full.deleted = true104 XCTAssertEqual(full.jsonValue.objectValue?.keys, ["type", "title", "fields", "urls", "custom", "notes", "tags", "favorite", "collection", "attachments", "passwordHistory",105 "expiresAt", "rotateEveryDays", "createdAt", "updatedAt", "conflictOf", "deleted", "trashedAt"])106 XCTAssertEqual(ItemType.allCases.map(\.rawValue), ["login", "passkey", "card", "identity", "note", "wifi", "license", "document", "ssh-key", "api-token", "certificate", "database", "env"])107 XCTAssertEqual(TEMPLATES.count, 13)108 }109110 func testLenientDecoding() throws {111 // missing keys → defaults, unknown keys ignored, unknown type → note112 let minimal = try JSONDecoder().decode(Item.self, from: Data("{}".utf8))113 XCTAssertEqual(minimal.type, .note); XCTAssertEqual(minimal.title, ""); XCTAssertEqual(minimal.createdAt, "1970-01-01T00:00:00.000Z"); XCTAssertFalse(minimal.favorite)114 let odd = try Item(json: Data(#"{"type":"hologram","title":"T","future":{"x":[1,2]},"fields":{"a":"b","n":1},"favorite":1,"tags":["x","x"," x "]}"#.utf8))115 XCTAssertEqual(odd.type, .note); XCTAssertEqual(odd.title, "T"); XCTAssertEqual(odd.fields, ["a": "b"]); XCTAssertFalse(odd.favorite); XCTAssertEqual(odd.tags, ["x"])116 // prototype-chain names are not item types (they are accepted by `x.type in TEMPLATES` in the TypeScript reference)117 for name in ["toString", "constructor", "__proto__", "hasOwnProperty"] { XCTAssertEqual(try Item(json: Data("{\"type\":\"\(name)\"}".utf8)).type, .note) }118 // tombstone119 let tomb = try Item(json: Item.tombstoneJSON)120 XCTAssertTrue(tomb.deleted); XCTAssertEqual(tomb.type, .note)121 XCTAssertEqual(tomb.jsonValue["deleted"], .bool(true))122 XCTAssertThrowsError(try Item(json: Data("5".utf8)))123 XCTAssertThrowsError(try Item(json: Data("\"x\"".utf8)))124 XCTAssertThrowsError(try Item(json: Data("null".utf8)))125 XCTAssertThrowsError(try Item(json: Data("{".utf8)))126 // limits127 let big = try Item(json: JSONValue.object(JSONObject([("type", "login"), ("title", .string(String(repeating: "x", count: 600))), ("notes", .string(String(repeating: "n", count: 500_010)))])).serialized())128 XCTAssertEqual(big.title.count, 500); XCTAssertEqual(big.notes.count, 500_000)129 }130131 func testPrimarySecretAndApplyEdit() throws {132 var login = SPV1.newItem(.login, title: "L")133 XCTAssertNil(SPV1.primarySecret(login))134 login.fields = ["username": "u", "password": "p1"]135 XCTAssertEqual(SPV1.primarySecret(login), "p1")136 var card = SPV1.newItem(.card); card.fields = ["number": "4111", "cvv": "123"]137 XCTAssertEqual(SPV1.primarySecret(card), "4111")138 XCTAssertNil(SPV1.primarySecret(SPV1.newItem(.note)))139 var token = SPV1.newItem(.apiToken); token.fields["token"] = "tok"140 XCTAssertEqual(SPV1.primarySecret(token), "tok")141142 var prev = login; prev.createdAt = "2026-01-01T00:00:00.000Z"; prev.updatedAt = "2026-01-01T00:00:00.000Z"143 var next = prev; next.fields["password"] = "p2"; next.createdAt = "1999-01-01T00:00:00.000Z"144 let edited = SPV1.applyEdit(prev: prev, next: next)145 XCTAssertEqual(edited.createdAt, prev.createdAt, "createdAt cannot be changed by an edit")146 XCTAssertNotEqual(edited.updatedAt, prev.updatedAt)147 XCTAssertEqual(edited.passwordHistory, [PasswordHistoryEntry(value: "p1", at: edited.updatedAt)])148 XCTAssertEqual(edited.fields["password"], "p2")149 // unchanged password: no history entry150 var titleOnly = prev; titleOnly.title = "New"151 XCTAssertTrue(SPV1.applyEdit(prev: prev, next: titleOnly).passwordHistory.isEmpty)152 // history is capped at 20, oldest dropped153 var cur = prev154 for i in 0..<25 { var n = cur; n.fields["password"] = "pw\(i)"; cur = SPV1.applyEdit(prev: cur, next: n) }155 XCTAssertEqual(cur.passwordHistory.count, 20)156 XCTAssertEqual(cur.passwordHistory.last?.value, "pw23")157 XCTAssertEqual(cur.passwordHistory.first?.value, "pw4")158 }159160 func testVaultMetaAndSearch() throws {161 let meta = VaultMeta(name: "Perso", kind: .personal, icon: "🔐", retentionDays: 30)162 XCTAssertEqual(meta.jsonValue.serializedString(), #"{"name":"Perso","kind":"personal","icon":"🔐","retentionDays":30}"#)163 XCTAssertEqual(try JSONDecoder().decode(VaultMeta.self, from: meta.jsonData), meta)164 XCTAssertEqual(try JSONDecoder().decode(VaultMeta.self, from: Data(#"{"name":"W","kind":"spaceship","extra":1}"#.utf8)), VaultMeta(name: "W", kind: .personal))165 XCTAssertEqual(VaultMeta(name: "n", kind: .work).jsonValue.serializedString(), #"{"name":"n","kind":"work"}"#)166167 var item = SPV1.newItem(.login, title: "Crème Brûlée")168 item.fields = ["username": "ÉLODIE", "password": "TopSecret"]169 item.custom = [CustomField(label: "pin", value: "9999", kind: .secret), CustomField(label: "hint", value: "blue", kind: .text)]170 let text = SPV1.searchText(item)171 XCTAssertTrue(SPV1.matchesQuery(haystack: text, query: "creme BRULEE"))172 XCTAssertTrue(SPV1.matchesQuery(haystack: text, query: "élodie"))173 XCTAssertTrue(SPV1.matchesQuery(haystack: text, query: "hint blue"))174 XCTAssertTrue(SPV1.matchesQuery(haystack: text, query: " "))175 XCTAssertFalse(SPV1.matchesQuery(haystack: text, query: "topsecret"), "passwords are never searchable")176 XCTAssertFalse(SPV1.matchesQuery(haystack: text, query: "9999"), "secret custom fields are never searchable")177 }178179 // ── JSON value ──180181 func testJSONValueParserStrictness() throws {182 XCTAssertEqual(try JSONValue.parse(#" {"a":[1,2.5,-3e2,true,false,null,"x\u00e9\ud83d\ude00\n"],"b":{}} "#),183 ["a": [1, 2.5, -300, true, false, nil, "xé😀\n"], "b": [:]])184 for bad in ["", "{", "[1,]", "{\"a\":1,}", "{'a':1}", "01", "1.", "+1", "nul", "\"\u{01}\"", "\"\\x\"", "[1] x", "{\"a\" 1}", "NaN", "\"unterminated"] {185 XCTAssertThrowsError(try JSONValue.parse(bad), bad)186 }187 XCTAssertThrowsError(try JSONValue.parse(Data([0x22, 0xc3, 0x28, 0x22])), "invalid UTF-8")188 XCTAssertThrowsError(try JSONValue.parse(String(repeating: "[", count: 5000) + String(repeating: "]", count: 5000)), "nesting bomb")189 // order preserved, duplicates: last value wins, equality ignores order190 let o = try JSONValue.parse(#"{"z":1,"a":2,"z":3}"#)191 XCTAssertEqual(o.objectValue?.keys, ["z", "a"])192 XCTAssertEqual(o["z"], 3)193 XCTAssertEqual(o.serializedString(), #"{"z":3,"a":2}"#)194 XCTAssertEqual(try JSONValue.parse(#"{"a":2,"z":3}"#), o)195 XCTAssertEqual(JSONValue.number(1e15).serializedString(), "1000000000000000")196 XCTAssertEqual(JSONValue.number(-0.0).serializedString(), "0")197 XCTAssertEqual(JSONValue.number(.nan).serializedString(), "null")198 XCTAssertEqual((["a": [1, ["b": []]], "c": [:]] as JSONValue).serializedString(indent: 1), "{\n \"a\": [\n 1,\n {\n \"b\": []\n }\n ],\n \"c\": {}\n}")199 }200201 // ── import / export / backup round trips ──202203 func sampleItems() -> [Item] {204 var a = SPV1.newItem(.login, title: "Exemple, \"quoted\"")205 a.fields = ["username": "alice", "password": "p,\"w\"\nline2", "totp": "otpauth://totp/x?secret=JBSWY3DPEHPK3PXP"]206 a.urls = [ItemUrl(url: "https://example.com/login")]207 a.notes = "note with, comma\r\nand newline"208 var b = SPV1.newItem(.login, title: "Été 🔐")209 b.fields = ["username": "bob@example.org", "password": " leading and trailing "]210 b.urls = [ItemUrl(url: "https://sub.example.co.uk")]211 var c = SPV1.newItem(.login, title: "No URL")212 c.fields = ["username": "carol", "password": "x"]213 return [a, b, c]214 }215216 func testCsvExportImportRoundTrip() throws {217 let items = sampleItems()218 var note = SPV1.newItem(.note, title: "not exported"); note.notes = "secret"219 let csv = SPV1.exportCsv(items + [note])220 XCTAssertTrue(csv.hasPrefix("Title,URL,Username,Password,Notes,OTPAuth\r\n"))221 XCTAssertTrue(csv.hasSuffix("\r\n"))222 XCTAssertFalse(csv.contains("not exported"))223 let rows = try SPV1.parseCsv(csv)224 XCTAssertEqual(rows.count, 4)225 XCTAssertEqual(rows[1][3], "p,\"w\"\nline2")226 let result = try SPV1.importCsv(csv)227 XCTAssertEqual(result.format, .apple)228 XCTAssertEqual(result.skipped, 0)229 XCTAssertEqual(result.items.count, 3)230 for (orig, got) in zip(items, result.items) {231 XCTAssertEqual(got.type, .login)232 XCTAssertEqual(got.title, orig.title)233 XCTAssertEqual(got.fields["username"], orig.fields["username"])234 XCTAssertEqual(got.fields["password"], orig.fields["password"], "passwords survive byte for byte, including spaces")235 XCTAssertEqual(got.fields["totp"], orig.fields["totp"])236 XCTAssertEqual(got.urls, orig.urls)237 }238 XCTAssertEqual(result.items[0].notes, "note with, comma\r\nand newline")239 // second generation is stable240 XCTAssertEqual(SPV1.exportCsv(result.items), csv)241 XCTAssertThrowsError(try SPV1.importCsv(""))242 XCTAssertThrowsError(try SPV1.importCsv("foo,bar\n1,2\n"), "no password column")243 XCTAssertThrowsError(try SPV1.importBitwardenJson(#"{"encrypted":true,"items":[]}"#))244 XCTAssertThrowsError(try SPV1.importBitwardenJson(#"{"nothing":1}"#))245 XCTAssertThrowsError(try SPV1.importAny(fileName: "x.json", text: "not json"))246 }247248 func testBackupRoundTripWithArkAndRecoveryKey() throws {249 let ark = SPV1.random(32), rk = SPV1.generateRecoveryKey(), accountId = SPV1.uuid(), account = SPV1.generateAccountKeys()250 let keyset = try SPV1.sealKeyset(ark: ark, accountId: accountId, keys: account)251 let envelope = try SPV1.sealRecoveryEnvelope(rk: rk, accountId: accountId, epoch: 3, ark: ark)252 var card = SPV1.newItem(.card, title: "Visa"); card.fields = ["number": "4111111111111111"]; card.tags = ["bank"]253 let payload = BackupPayload(vaults: [254 BackupVault(id: SPV1.uuid(), meta: VaultMeta(name: "Personnel", kind: .personal, icon: "🏠"), items: sampleItems().map { BackupItem(id: SPV1.uuid(), item: $0) }),255 BackupVault(id: SPV1.uuid(), meta: VaultMeta(name: "Work", kind: .work, retentionDays: 90), items: [BackupItem(id: SPV1.uuid(), item: card)]),256 BackupVault(id: SPV1.uuid(), meta: VaultMeta(name: "Empty", kind: .shared), items: []),257 ])258 let file = try SPV1.createBackup(ark: ark, accountId: accountId, recoveryEpoch: 3, recoveryEnvelope: envelope, keyset: keyset, payload: payload)259 XCTAssertEqual(file.format, "spvault-backup"); XCTAssertEqual(file.v, 1); XCTAssertTrue(SPV1.isUuid(file.backupId))260 let text = String(decoding: file.jsonData, as: UTF8.self)261 XCTAssertFalse(text.contains("4111111111111111")); XCTAssertFalse(text.contains("Personnel"))262 XCTAssertEqual(try JSONValue.parse(text).objectValue?.keys, ["format", "v", "backupId", "accountId", "createdAt", "recoveryEpoch", "recoveryEnvelope", "keyset", "nonce", "ct"])263 let parsed = try SPV1.parseBackup(text)264 XCTAssertEqual(parsed, file)265 XCTAssertEqual(try JSONDecoder().decode(BackupFile.self, from: file.jsonData), file)266267 let withArk = try SPV1.openBackup(parsed, secret: .ark(ark))268 XCTAssertEqual(withArk.payload, payload)269 let withRk = try SPV1.openBackup(parsed, secret: .recoveryKey(rk))270 XCTAssertEqual(withRk.ark, ark)271 XCTAssertEqual(withRk.payload, payload)272 // the restored ARK opens the keyset carried by the file273 XCTAssertEqual(try SPV1.openKeyset(ark: withRk.ark, accountId: parsed.accountId, blob: parsed.keyset).sigPub, account.sigPub)274275 assertThrows(.authenticationFailed, try SPV1.openBackup(parsed, secret: .ark(SPV1.random(32))))276 assertThrows(.authenticationFailed, try SPV1.openBackup(parsed, secret: .recoveryKey(SPV1.random(32))))277 for mutate in [{ (f: inout BackupFile) in f.backupId = SPV1.uuid() }, { $0.accountId = SPV1.uuid() }, { $0.createdAt = "2020-01-01T00:00:00.000Z" }] as [(inout BackupFile) -> Void] {278 var m = parsed; mutate(&m)279 assertThrows(.authenticationFailed, try SPV1.openBackup(m, secret: .ark(ark)))280 }281 var epoch = parsed; epoch.recoveryEpoch = 4282 XCTAssertNoThrow(try SPV1.openBackup(epoch, secret: .ark(ark)))283 assertThrows(.authenticationFailed, try SPV1.openBackup(epoch, secret: .recoveryKey(rk)))284 var ct = parsed; var raw = try SPV1.unb64u(ct.ct); raw[raw.count / 2] ^= 1; ct.ct = SPV1.b64u(raw)285 assertThrows(.authenticationFailed, try SPV1.openBackup(ct, secret: .ark(ark)))286 XCTAssertThrowsError(try SPV1.parseBackup("{}"))287 XCTAssertThrowsError(try SPV1.parseBackup(text.replacingOccurrences(of: "\"v\":1", with: "\"v\":2")))288 XCTAssertThrowsError(try SPV1.parseBackup(text.replacingOccurrences(of: "spvault-backup", with: "other")))289 XCTAssertThrowsError(try SPV1.parseBackup("not json"))290 }291292 /// `isoString(ms:)` is `new Date(ms).toISOString()` for every millisecond (no binary-fraction truncation).293 func testIsoStringIsExactToTheMillisecond() {294 XCTAssertEqual(isoString(ms: 0), "1970-01-01T00:00:00.000Z")295 XCTAssertEqual(isoString(ms: 1_795_080_155_001), "2026-11-19T09:22:35.001Z")296 XCTAssertEqual(isoString(ms: -1), "1969-12-31T23:59:59.999Z")297 for i in 0..<1000 {298 let s = isoString(ms: 1_795_080_155_000 + Double(i)), m = String(i)299 XCTAssertTrue(s.hasSuffix("." + String(repeating: "0", count: 3 - m.count) + m + "Z"), s)300 XCTAssertEqual(parseDateMs(s), 1_795_080_155_000 + Double(i))301 }302 XCTAssertNotNil(isoNow().range(of: #"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$"#, options: .regularExpression))303 }304}305