SPB Git

Repository Public

BackupArchive.swift 9.6 KB 218 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP ID & Card Vault7// File             : SPVault/Engines/Backup/BackupArchive.swift8// Module           : SPVault9// Repository       : https://git.spboucher.ai/sp-id-card-vault10// Project Website  : Not specified11// Created          : 2026-12-0212// Last Modified    : 2026-12-0213//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 CryptoKit42import Foundation4344enum BackupError: Error, Equatable {45    case notABackup46    case unsupportedVersion(UInt16)47    case wrongPassphrase48    /// A record failed authentication, is missing, duplicated or out of order.49    case corrupted50    case weakPassphrase51}5253/// One card inside a backup: the record and its photographs, exactly as stored.54struct BackupCard: Codable, Sendable, Equatable {55    var card: Card56    var front: Data57    var frontThumbnail: Data58    var back: Data?59    var backThumbnail: Data?60}6162struct BackupContents: Sendable, Equatable {63    var createdAt: Date64    var manifest: VaultManifest65    var cards: [BackupCard]66}6768/// `.spvault` — SP Vault encrypted backup, format version 1.69///70/// ```71/// "SPVAULT\0"                8 bytes  magic72/// version                    u16 BE73/// header length              u32 BE74/// header                     JSON, clear: KDF parameters, creation date, app version75/// repeat:76///   record length            u32 BE77///   record                   SPV1 sealed blob (AES-256-GCM, kind backupRecord)78/// ```79///80/// Key: PBKDF2-HMAC-SHA256(passphrase, salt, iterations) → HKDF-SHA256 with the81/// SHA-256 of the clear header as salt. Each record authenticates82/// `header hash | record index | final flag`, so tampering with the header,83/// reordering, dropping or truncating records is detected. Record 0 is the84/// summary (counts + vault manifest); each following record is one card.85/// The file holds no clear-text card data, not even the number of cards.86enum BackupArchive {87    static let magic = Data("SPVAULT\0".utf8)88    static let version: UInt16 = 189    static let fileExtension = "spvault"9091    struct Header: Codable, Equatable {92        var format = "spvault"93        var kdf: KDFParameters94        var createdAt: Date95        var appVersion: String96    }9798    private struct Summary: Codable {99        var cardCount: Int100        var manifest: VaultManifest101        var createdAt: Date102    }103104    private static func recordContext(_ headerHash: Data, index: Int, isFinal: Bool) -> Data {105        var data = headerHash106        withUnsafeBytes(of: UInt32(index).bigEndian) { data.append(contentsOf: $0) }107        data.append(isFinal ? 1 : 0)108        return data109    }110111    private static func appendLength(_ value: Int, to data: inout Data) {112        withUnsafeBytes(of: UInt32(value).bigEndian) { data.append(contentsOf: $0) }113    }114115    static func encode(_ contents: BackupContents, passphrase: String,116                       iterations: UInt32 = KDFParameters.defaultIterations,117                       appVersion: String = "1.0.0", enforcePolicy: Bool = true) throws -> Data {118        if enforcePolicy, !PassphrasePolicy.isAcceptable(passphrase) { throw BackupError.weakPassphrase }119        let header = Header(kdf: try KDFParameters.fresh(iterations: iterations), createdAt: contents.createdAt,120                            appVersion: appVersion)121        let headerData = try JSONEncoder.vault.encode(header)122        let headerHash = Data(SHA256.hash(data: headerData))123        let key = VaultCrypto.subkey(try header.kdf.key(for: passphrase, allowWeakParameters: true),124                                     salt: headerHash, purpose: "spvault/backup/v1")125126        var out = magic127        withUnsafeBytes(of: version.bigEndian) { out.append(contentsOf: $0) }128        appendLength(headerData.count, to: &out)129        out.append(headerData)130131        let summary = Summary(cardCount: contents.cards.count, manifest: contents.manifest, createdAt: contents.createdAt)132        var plaintexts = [try JSONEncoder.vault.encode(summary)]133        for card in contents.cards { plaintexts.append(try JSONEncoder.vault.encode(card)) }134        for (index, plaintext) in plaintexts.enumerated() {135            let sealed = try SealedBlob.seal(plaintext, key: key, kind: .backupRecord,136                                             context: recordContext(headerHash, index: index,137                                                                    isFinal: index == plaintexts.count - 1))138            appendLength(sealed.count, to: &out)139            out.append(sealed)140        }141        return out142    }143144    /// Clear header of a backup file, without the passphrase.145    static func readHeader(_ file: Data) throws -> Header {146        try split(file).header147    }148149    private static func split(_ file: Data) throws -> (header: Header, headerData: Data, records: [Data]) {150        let data = Data(file)151        guard data.count >= magic.count + 6, data.prefix(magic.count) == magic else { throw BackupError.notABackup }152        var offset = magic.count153        func readU32() throws -> Int {154            guard offset + 4 <= data.count else { throw BackupError.corrupted }155            let value = data.subdata(in: offset..<(offset + 4)).reduce(0) { ($0 << 8) | Int($1) }156            offset += 4157            return value158        }159        let fileVersion = UInt16(data[offset]) << 8 | UInt16(data[offset + 1])160        offset += 2161        guard fileVersion == version else { throw BackupError.unsupportedVersion(fileVersion) }162        let headerLength = try readU32()163        guard headerLength > 0, offset + headerLength <= data.count else { throw BackupError.corrupted }164        let headerData = data.subdata(in: offset..<(offset + headerLength))165        offset += headerLength166        guard let header = try? JSONDecoder.vault.decode(Header.self, from: headerData) else { throw BackupError.corrupted }167        var records: [Data] = []168        while offset < data.count {169            let length = try readU32()170            guard length >= SealedBlob.overhead, offset + length <= data.count else { throw BackupError.corrupted }171            records.append(data.subdata(in: offset..<(offset + length)))172            offset += length173        }174        guard !records.isEmpty else { throw BackupError.corrupted }175        return (header, headerData, records)176    }177178    /// Decrypts and fully verifies a backup. Nothing is returned unless every179    /// record authenticates and the card count matches the summary.180    static func decode(_ file: Data, passphrase: String) throws -> BackupContents {181        let (header, headerData, records) = try split(file)182        let headerHash = Data(SHA256.hash(data: headerData))183        guard let base = try? header.kdf.key(for: passphrase) else { throw BackupError.corrupted }184        let key = VaultCrypto.subkey(base, salt: headerHash, purpose: "spvault/backup/v1")185186        func open(_ index: Int) throws -> Data {187            try SealedBlob.open(records[index], key: key, kind: .backupRecord,188                                context: recordContext(headerHash, index: index, isFinal: index == records.count - 1))189        }190        let summaryData: Data191        do { summaryData = try open(0) } catch {192            // The first record failing means the key is wrong (or the header was193            // altered, which changes the key): both read as "wrong passphrase"194            // unless a later structural check says otherwise.195            if records.count == 1, (try? SealedBlob.open(records[0], key: key, kind: .backupRecord,196                                                         context: recordContext(headerHash, index: 0, isFinal: false))) != nil {197                throw BackupError.corrupted   // truncated: record 0 was not final198            }199            throw BackupError.wrongPassphrase200        }201        do {202            let summary = try JSONDecoder.vault.decode(Summary.self, from: summaryData)203            guard summary.cardCount == records.count - 1 else { throw BackupError.corrupted }204            var cards: [BackupCard] = []205            for index in 1..<records.count {206                let card = try JSONDecoder.vault.decode(BackupCard.self, from: try open(index))207                cards.append(card)208            }209            guard Set(cards.map(\.card.id)).count == cards.count else { throw BackupError.corrupted }210            return BackupContents(createdAt: summary.createdAt, manifest: summary.manifest, cards: cards)211        } catch let error as BackupError {212            throw error213        } catch {214            throw BackupError.corrupted215        }216    }217}218
Files main
Menu

Theme