Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraVault/VaultFile.swift8// Module : Qyvora Vault9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0412// Last Modified : 2026-12-0413//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import QyvoraMath43import QyvoraStorage4445/// What a vault record holds. The raw value is the type byte of the file format.46public enum RecordType: UInt8, Sendable, Codable, CaseIterable {47 case recoveryPhrase = 148 case bip39Passphrase = 249 case identityKeys = 350 case watchOnlyAccount = 451 case setting = 552 case custom = 65354 public var name: String {55 switch self {56 case .recoveryPhrase: return "recoveryPhrase"57 case .bip39Passphrase: return "bip39Passphrase"58 case .identityKeys: return "identityKeys"59 case .watchOnlyAccount: return "watchOnlyAccount"60 case .setting: return "setting"61 case .custom: return "custom"62 }63 }64}6566/// A decrypted record.67public struct VaultRecord: Sendable, Equatable {68 public let id: UUID69 public let type: RecordType70 public let createdAt: Date71 public let updatedAt: Date72 /// The secret content. Wipe copies with `SecureMemory.zero` when done.73 public let payload: Bytes7475 public init(id: UUID, type: RecordType, createdAt: Date, updatedAt: Date, payload: Bytes) {76 self.id = id77 self.type = type78 self.createdAt = createdAt79 self.updatedAt = updatedAt80 self.payload = payload81 }82}8384/// The non-secret description of a record (readable while the vault is locked).85public struct RecordSummary: Sendable, Equatable, Codable {86 public let id: UUID87 public let type: RecordType88 public let createdAt: Date89 public let updatedAt: Date90 public let keyEpoch: UInt3291 public let sealedSize: Int92}9394/// QYVORA vault file, format version 1.95///96/// All integers are unsigned big-endian. Times are whole seconds since 1970-01-01 UTC.97///98/// file = magic ‖ version ‖ headerLength ‖ header ‖ bodyLength ‖ body ‖ mac ‖ checksum99/// magic = "QYVORAVF" 8 bytes (ASCII)100/// version = 0x0001 u16101/// headerLength, bodyLength u32 each102/// mac = HMAC-SHA256(fileMacKey, every byte before mac) 32 bytes103/// checksum = SHA-256(every byte before checksum, mac included) 32 bytes104///105/// header = vaultID (16) ‖ createdAt (u64) ‖ keyEpoch (u32) ‖ generation (u64) ‖ slotCount (u8) ‖ slot*106/// slot = slotType (u8) ‖ slotLength (u16) ‖ slotBody107/// slots appear in increasing slotType order, at most one of each type108///109/// slotType 1, password slot, and slotType 3, PIN slot (slotBody = 108 bytes):110/// argon2MemoryKiB (u32) ‖ argon2Iterations (u32) ‖ argon2Parallelism (u32) ‖ pbkdf2Iterations (u32)111/// ‖ argon2Salt (16) ‖ pbkdf2Salt (16) ‖ nonce (12) ‖ wrappedMasterKey (32 + 16-byte tag)112/// slotType 2, device slot:113/// flags (u8; bit 0 = wrapped again by the Secure Enclave key, other bits zero) ‖ blob114/// blob without Secure Enclave (60 bytes) = nonce (12) ‖ wrappedMasterKey (48)115/// blob with Secure Enclave (154 bytes) = SecureEnclaveKeyProvider.wrap(nonce ‖ wrappedMasterKey)116///117/// body = recordCount (u32) ‖ record*118/// record = recordID (16) ‖ recordType (u8) ‖ createdAt (u64) ‖ updatedAt (u64) ‖ keyEpoch (u32)119/// ‖ nonce (12) ‖ sealedLength (u32) ‖ sealed (ciphertext ‖ 16-byte tag)120///121/// Keys (all HKDF-SHA256, CryptoKit; `epoch` is the 4-byte key epoch):122///123/// recordsKey = HKDF(masterKey, salt = vaultID ‖ epoch, info = "qyvora/v1/records", 32)124/// fileMacKey = HKDF(masterKey, salt = vaultID ‖ epoch, info = "qyvora/v1/file-mac", 32)125/// password KEK = KeyStretching(NFKD-UTF-8(password), salts, parameters, info = "qyvora/v1/slot/password")126/// PIN KEK = KeyStretching(u16 length ‖ NFKD-UTF-8(PIN) ‖ device secret (32, Keychain), …, info = "qyvora/v1/slot/pin")127/// device key = 32 random bytes in the Keychain (biometryCurrentSet)128///129/// AEAD is AES-256-GCM with a fresh random 96-bit nonce for every seal.130///131/// record associated data = "qyvora/v1/record" ‖ version (u16) ‖ vaultID ‖ recordID ‖ recordType (u8)132/// ‖ createdAt (u64) ‖ keyEpoch (u32)133/// slot associated data = "qyvora/v1/slot" ‖ version (u16) ‖ vaultID ‖ slotType (u8) ‖ keyEpoch (u32)134///135/// Integrity. The checksum needs no key: it detects accidental damage as soon as the file is read and triggers the136/// fallback to `<name>.previous`. The header (slots included) must be readable before unlocking, so it cannot be137/// authenticated at that point; the HMAC covers header and body and is verified immediately after any slot yields138/// the master key, before any record is used. A modified slot therefore either fails to unwrap or fails the HMAC.139struct VaultFile: Sendable, Equatable {140 static let magic = Bytes("QYVORAVF".utf8)141 static let version: UInt16 = 1142 static let maximumFileSize = 64 << 20143 static let maximumRecordSize = 16 << 20144 static let macSize = 32145 static let checksumSize = 32146147 struct WrapSlot: Sendable, Equatable {148 var kdf: KDFParameters149 var argon2Salt: Bytes150 var pbkdf2Salt: Bytes151 var nonce: Bytes152 var wrapped: Bytes153 }154155 struct DeviceSlot: Sendable, Equatable {156 var usesSecureEnclave: Bool157 var blob: Bytes158 }159160 struct SealedRecord: Sendable, Equatable {161 var id: Bytes162 var type: RecordType163 var createdAt: UInt64164 var updatedAt: UInt64165 var epoch: UInt32166 var nonce: Bytes167 var sealed: Bytes168 }169170 var vaultID: Bytes171 var createdAt: UInt64172 var epoch: UInt32173 var generation: UInt64174 var password: WrapSlot?175 var device: DeviceSlot?176 var pin: WrapSlot?177 var records: [SealedRecord]178179 // MARK: Associated data and subkeys180181 static func slotAAD(vaultID: Bytes, slotType: UInt8, epoch: UInt32) -> Bytes {182 var w = ByteWriter()183 w.raw(Bytes(VaultLabels.slotAAD.utf8))184 w.u16(version)185 w.raw(vaultID)186 w.u8(slotType)187 w.u32(epoch)188 return w.bytes189 }190191 static func recordAAD(vaultID: Bytes, recordID: Bytes, type: RecordType, createdAt: UInt64, epoch: UInt32) -> Bytes {192 var w = ByteWriter()193 w.raw(Bytes(VaultLabels.recordAAD.utf8))194 w.u16(version)195 w.raw(vaultID)196 w.raw(recordID)197 w.u8(type.rawValue)198 w.u64(createdAt)199 w.u32(epoch)200 return w.bytes201 }202203 static func subkey(master: Bytes, vaultID: Bytes, epoch: UInt32, label: String) -> Bytes {204 SystemCrypto.hkdfSHA256(inputKeyMaterial: master, salt: vaultID + Endian.be32(epoch), info: Bytes(label.utf8), length: 32)205 }206207 // MARK: Encoding208209 /// Everything the HMAC covers (magic through body).210 func authenticatedBytes() -> Bytes {211 var h = ByteWriter()212 h.raw(vaultID)213 h.u64(createdAt)214 h.u32(epoch)215 h.u64(generation)216 h.u8(UInt8((password == nil ? 0 : 1) + (device == nil ? 0 : 1) + (pin == nil ? 0 : 1)))217 func wrapSlot(_ type: UInt8, _ s: WrapSlot) {218 var b = ByteWriter()219 s.kdf.encode(into: &b)220 b.raw(s.argon2Salt)221 b.raw(s.pbkdf2Salt)222 b.raw(s.nonce)223 b.raw(s.wrapped)224 h.u8(type)225 h.prefixed16(b.bytes)226 }227 if let password { wrapSlot(1, password) }228 if let device {229 h.u8(2)230 h.prefixed16([device.usesSecureEnclave ? 1 : 0] + device.blob)231 }232 if let pin { wrapSlot(3, pin) }233234 var b = ByteWriter()235 b.u32(UInt32(records.count))236 for r in records {237 b.raw(r.id)238 b.u8(r.type.rawValue)239 b.u64(r.createdAt)240 b.u64(r.updatedAt)241 b.u32(r.epoch)242 b.raw(r.nonce)243 b.prefixed32(r.sealed)244 }245246 var out = ByteWriter()247 out.raw(Self.magic)248 out.u16(Self.version)249 out.prefixed32(h.bytes)250 out.prefixed32(b.bytes)251 return out.bytes252 }253254 /// The complete file for the given file-MAC key.255 func encoded(macKey: Bytes) -> Bytes {256 var out = authenticatedBytes()257 out += SystemCrypto.hmacSHA256(key: macKey, message: out)258 out += SystemCrypto.sha256(out)259 return out260 }261262 // MARK: Parsing263264 struct Parsed: Sendable {265 var file: VaultFile266 /// The bytes the HMAC was computed over.267 var authenticated: Bytes268 var mac: Bytes269 }270271 static func parse(_ bytes: Bytes) throws(VaultError) -> Parsed {272 guard bytes.count <= maximumFileSize else { throw .corrupted(.malformed) }273 guard bytes.count >= magic.count + 2 else { throw .corrupted(.truncated) }274 guard Bytes(bytes[0..<magic.count]) == magic else { throw .corrupted(.badMagic) }275 let v = UInt16(bytes[8]) << 8 | UInt16(bytes[9])276 guard v == version else { throw .corrupted(.unsupportedVersion(v)) }277 guard bytes.count >= magic.count + 2 + 4 + 4 + macSize + checksumSize else { throw .corrupted(.truncated) }278 let checksumStart = bytes.count - checksumSize279 guard ConstantTime.equal(SystemCrypto.sha256(Bytes(bytes[0..<checksumStart])), Bytes(bytes[checksumStart...])) else {280 throw .corrupted(.checksumMismatch)281 }282 let macStart = checksumStart - macSize283 do {284 var r = ByteReader(Bytes(bytes[(magic.count + 2)..<macStart]))285 var h = ByteReader(try r.prefixed32(max: 1 << 16))286 var b = ByteReader(try r.prefixed32(max: maximumFileSize))287 try r.finish()288289 var file = VaultFile(290 vaultID: try h.raw(16), createdAt: try h.u64(), epoch: try h.u32(), generation: try h.u64(),291 password: nil, device: nil, pin: nil, records: [])292 let slotCount = try h.u8()293 var lastType: UInt8 = 0294 for _ in 0..<slotCount {295 let type = try h.u8()296 guard type > lastType else { throw VaultError.corrupted(.malformed) }297 lastType = type298 var s = ByteReader(try h.prefixed16())299 switch type {300 case 1, 3:301 let slot = WrapSlot(302 kdf: try KDFParameters(from: &s), argon2Salt: try s.raw(16), pbkdf2Salt: try s.raw(16),303 nonce: try s.raw(12), wrapped: try s.raw(48))304 try s.finish()305 guard slot.kdf.isWithinLimits else { throw VaultError.corrupted(.malformed) }306 if type == 1 { file.password = slot } else { file.pin = slot }307 case 2:308 let flags = try s.u8()309 guard flags <= 1 else { throw VaultError.corrupted(.malformed) }310 let blob = try s.raw(s.remaining)311 guard flags == 1 ? blob.count >= 60 : blob.count == 60 else { throw VaultError.corrupted(.malformed) }312 file.device = DeviceSlot(usesSecureEnclave: flags == 1, blob: blob)313 default:314 throw VaultError.corrupted(.malformed)315 }316 }317 try h.finish()318319 let count = try b.u32()320 // 69 bytes is the smallest possible record: a count beyond what the body can hold is malformed321 guard UInt64(count) * 69 <= UInt64(b.remaining) else { throw VaultError.corrupted(.malformed) }322 var seen = Set<Bytes>()323 for _ in 0..<count {324 let id = try b.raw(16)325 guard let type = RecordType(rawValue: try b.u8()) else { throw VaultError.corrupted(.malformed) }326 let record = SealedRecord(327 id: id, type: type, createdAt: try b.u64(), updatedAt: try b.u64(), epoch: try b.u32(),328 nonce: try b.raw(12), sealed: try b.prefixed32(max: maximumRecordSize + 16))329 guard record.sealed.count >= 16, seen.insert(id).inserted else { throw VaultError.corrupted(.malformed) }330 file.records.append(record)331 }332 try b.finish()333 return Parsed(file: file, authenticated: Bytes(bytes[0..<macStart]), mac: Bytes(bytes[macStart..<checksumStart]))334 } catch let error as VaultError {335 throw error336 } catch ByteReaderError.truncated {337 throw .corrupted(.truncated)338 } catch {339 throw .corrupted(.malformed)340 }341 }342}343344extension UUID {345 /// The 16 bytes of the identifier, in RFC 4122 order.346 public var bytes16: Bytes {347 withUnsafeBytes(of: uuid) { Bytes($0) }348 }349350 public init?(bytes16 b: Bytes) {351 guard b.count == 16 else { return nil }352 self.init(uuid: (b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]))353 }354}355