Repository Public License
1// SyncEngine — the `.orixcapsule` container: layout, limits, compression, encryption (docs/CAPSULE_FORMAT.md).2import CommonCrypto3import Compression4import CryptoKit5import Foundation67public enum CapsuleError: Error, Sendable, Equatable, CustomStringConvertible {8 case notACapsule9 case unsupportedVersion(Int)10 case malformed(String)11 case integrityCheckFailed12 case passwordRequired13 case wrongPasswordOrCorrupted14 case weakParameters(String)15 case limitExceeded(String)16 case unsafeName(String)17 case hashMismatch(String)18 case unsafeContent(String)19 case emptySelection20 case fileMissing(String)2122 public var description: String {23 switch self {24 case .notACapsule: return "This file is not an ORIX capsule."25 case .unsupportedVersion(let version): return "This capsule uses format version \(version), which this version of ORIX Navigator cannot read."26 case .malformed(let detail): return "The capsule is damaged or malformed (\(detail)). Nothing was imported."27 case .integrityCheckFailed: return "The capsule failed its integrity check: it was modified or damaged. Nothing was imported."28 case .passwordRequired: return "This capsule is protected by a password."29 case .wrongPasswordOrCorrupted: return "The password is wrong, or the capsule was modified. Nothing was imported."30 case .weakParameters(let detail): return "The capsule's encryption parameters are not acceptable (\(detail))."31 case .limitExceeded(let detail): return "The capsule exceeds a size limit (\(detail)). Nothing was imported."32 case .unsafeName(let name): return "The capsule contains an entry with an unsafe name (\(name.prefix(80))). Nothing was imported."33 case .hashMismatch(let name): return "The content of “\(name.prefix(80))” does not match the capsule's manifest. Nothing was imported."34 case .unsafeContent(let detail): return "The capsule contains content that cannot be imported safely (\(detail)). Nothing was imported."35 case .emptySelection: return "Nothing was selected for export."36 case .fileMissing(let name): return "A file to export is missing: \(name)."37 }38 }39}4041/// Bounds enforced when writing and, more importantly, when reading a capsule. Every claimed size is checked42/// against these before any allocation.43public struct CapsuleLimits: Sendable, Hashable {44 public var maximumFileBytes = 1024 * 1024 * 102445 public var maximumEntries = 20_00046 public var maximumEntryBytes = 256 * 1024 * 102447 /// Sum of the uncompressed sizes of all entries.48 public var maximumTotalBytes = 1024 * 1024 * 102449 public var maximumNameBytes = 24050 public var maximumHeaderBytes = 4_09651 /// Records per kind (bookmarks, notes, visits…).52 public var maximumItemsPerKind = 500_00053 public var maximumTextBytes = 4 * 1024 * 10245455 public init() {}56}5758/// What the manifest says a capsule entry holds.59public enum CapsuleItemKind: String, Sendable, Codable, CaseIterable, Hashable {60 case bookmarks, notes, canvases, workflows, spaces, history, archives61 /// The stored file of one archive.62 case archiveFile63 /// An image or PDF attached to a canvas.64 case canvasAttachment65}6667public struct CapsuleManifest: Codable, Sendable, Hashable {68 public static let formatIdentifier = "orix.capsule"69 public static let currentFormatVersion = 170 public static let entryName = "manifest.json"7172 public struct Item: Codable, Sendable, Hashable {73 /// Entry name inside the container.74 public var name: String75 public var kind: CapsuleItemKind76 /// Number of records in a JSON entry; 1 for a file.77 public var count: Int78 /// Uncompressed size in bytes.79 public var byteSize: Int80 /// Lowercase hex SHA-256 of the uncompressed payload.81 public var sha256: String82 }8384 public var format: String85 public var formatVersion: Int86 public var createdAt: Date87 public var appVersion: String88 /// `true` only when the user explicitly chose to export browsing history.89 public var includesHistory: Bool90 public var items: [Item]91}9293struct CapsuleEntry: Sendable, Hashable {94 var name: String95 var data: Data96}9798enum CapsuleCoding {99 static func encoder() -> JSONEncoder {100 let encoder = JSONEncoder()101 encoder.dateEncodingStrategy = .secondsSince1970102 encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]103 return encoder104 }105106 static func decoder() -> JSONDecoder {107 let decoder = JSONDecoder()108 decoder.dateDecodingStrategy = .secondsSince1970109 return decoder110 }111112 static func sha256(_ data: Data) -> String { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() }113}114115/// Reads and writes the container bytes. Pure: no file access, no database.116enum CapsuleContainer {117 static let magic = Data("ORIXCAPS".utf8)118 static let version: UInt16 = 1119 static let encryptedFlag: UInt16 = 0x0001120 static let knownFlags: UInt16 = 0x0001121 static let fixedPrefixLength = 16122 static let digestLength = 32123124 // MARK: Password-based encryption125126 struct EncryptionHeader: Codable, Equatable {127 var cipher: String128 var kdf: String129 var iterations: Int130 var salt: String131 var keyLength: Int132 }133134 static let cipherName = "AES-256-GCM"135 static let kdfName = "PBKDF2-HMAC-SHA256"136 /// OWASP's 2023 recommendation for PBKDF2-HMAC-SHA256.137 static let defaultIterations = 600_000138 static let minimumIterations = 100_000139 /// Upper bound accepted on reading, so a crafted header cannot stall the app for hours.140 static let maximumIterations = 10_000_000141 static let saltLength = 16142143 static func deriveKey(password: String, salt: Data, iterations: Int) throws -> SymmetricKey {144 // Unicode has several byte forms for the same visible text: normalise so the password typed on another145 // keyboard or OS derives the same key.146 let passwordBytes = Array(password.precomposedStringWithCanonicalMapping.utf8)147 var derived = [UInt8](repeating: 0, count: 32)148 let status = salt.withUnsafeBytes { saltBytes -> Int32 in149 passwordBytes.withUnsafeBufferPointer { passwordPointer in150 passwordPointer.withMemoryRebound(to: CChar.self) { chars in151 CCKeyDerivationPBKDF(CCPBKDFAlgorithm(kCCPBKDF2), chars.baseAddress, passwordBytes.count,152 saltBytes.bindMemory(to: UInt8.self).baseAddress, salt.count,153 CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA256), UInt32(iterations), &derived, derived.count)154 }155 }156 }157 guard status == kCCSuccess else { throw CapsuleError.malformed("key derivation failed") }158 defer { for index in derived.indices { derived[index] = 0 } }159 return SymmetricKey(data: derived)160 }161162 // MARK: Compression163164 /// Raw DEFLATE (RFC 1951) through Apple's Compression framework; `nil` when it does not make the data smaller.165 static func deflate(_ data: Data) -> Data? {166 guard data.count >= 64 else { return nil }167 let capacity = data.count168 var output = Data(count: capacity)169 let written = output.withUnsafeMutableBytes { destination -> Int in170 data.withUnsafeBytes { source -> Int in171 compression_encode_buffer(destination.bindMemory(to: UInt8.self).baseAddress!, capacity,172 source.bindMemory(to: UInt8.self).baseAddress!, data.count, nil, COMPRESSION_ZLIB)173 }174 }175 // 0 means "did not fit": the data is not compressible enough to be worth it.176 guard written > 0, written < data.count else { return nil }177 output.count = written178 return output179 }180181 /// Inflates into a buffer of exactly the claimed size plus one byte: anything longer than claimed is detected182 /// without ever allocating more than the (already bounded) claim.183 static func inflate(_ data: Data, expectedLength: Int, name: String) throws -> Data {184 guard expectedLength > 0, !data.isEmpty else { throw CapsuleError.malformed("empty compressed entry \(name)") }185 var output = Data(count: expectedLength + 1)186 let written = output.withUnsafeMutableBytes { destination -> Int in187 data.withUnsafeBytes { source -> Int in188 compression_decode_buffer(destination.bindMemory(to: UInt8.self).baseAddress!, expectedLength + 1,189 source.bindMemory(to: UInt8.self).baseAddress!, data.count, nil, COMPRESSION_ZLIB)190 }191 }192 guard written == expectedLength else { throw CapsuleError.malformed("entry \(name) does not inflate to its declared size") }193 output.count = expectedLength194 return output195 }196197 // MARK: Names198199 /// Entry names are relative paths of plain ASCII components. No absolute path, no `.`/`..`, no backslash,200 /// no control character, no component starting with a dot.201 static func isSafeName(_ name: String, limits: CapsuleLimits) -> Bool {202 guard !name.isEmpty, name.utf8.count <= limits.maximumNameBytes else { return false }203 let components = name.split(separator: "/", omittingEmptySubsequences: false)204 guard components.count <= 6 else { return false }205 for component in components {206 guard !component.isEmpty, component != ".", component != "..", component.first != ".", component.first != "-" else { return false }207 for byte in component.utf8 {208 let isAlphanumeric = (byte >= 48 && byte <= 57) || (byte >= 65 && byte <= 90) || (byte >= 97 && byte <= 122)209 guard isAlphanumeric || byte == 46 || byte == 45 || byte == 95 else { return false }210 }211 }212 return true213 }214215 /// Turns any file name into a safe single component (used for archive files, whose names come from pages).216 static func sanitisedFileName(_ name: String) -> String {217 var result = ""218 for scalar in (name as NSString).lastPathComponent.unicodeScalars {219 let value = scalar.value220 let isAlphanumeric = (value >= 48 && value <= 57) || (value >= 65 && value <= 90) || (value >= 97 && value <= 122)221 result.unicodeScalars.append(isAlphanumeric || scalar == "." || scalar == "-" || scalar == "_" ? scalar : "_")222 }223 while result.hasPrefix(".") || result.hasPrefix("-") { result.removeFirst() }224 if result.isEmpty { result = "file" }225 return String(result.prefix(80))226 }227228 // MARK: Writing229230 private static func append(_ value: UInt16, to data: inout Data) { withUnsafeBytes(of: value.bigEndian) { data.append(contentsOf: $0) } }231 private static func append(_ value: UInt32, to data: inout Data) { withUnsafeBytes(of: value.bigEndian) { data.append(contentsOf: $0) } }232 private static func append(_ value: UInt64, to data: inout Data) { withUnsafeBytes(of: value.bigEndian) { data.append(contentsOf: $0) } }233234 /// Serialises entries (the manifest must be first). The same entries always give the same bytes when235 /// there is no password; with a password the salt and nonce are random.236 static func write(_ entries: [CapsuleEntry], password: String?, limits: CapsuleLimits,237 iterations: Int = defaultIterations) throws -> Data {238 guard entries.count <= limits.maximumEntries else { throw CapsuleError.limitExceeded("\(entries.count) entries") }239 var body = Data()240 var total = 0241 var names = Set<String>()242 for entry in entries {243 guard isSafeName(entry.name, limits: limits), names.insert(entry.name).inserted else { throw CapsuleError.unsafeName(entry.name) }244 guard entry.data.count <= limits.maximumEntryBytes else { throw CapsuleError.limitExceeded("entry \(entry.name)") }245 total += entry.data.count246 guard total <= limits.maximumTotalBytes else { throw CapsuleError.limitExceeded("total size") }247 let compressed = deflate(entry.data)248 let nameBytes = Data(entry.name.utf8)249 append(UInt16(nameBytes.count), to: &body)250 body.append(nameBytes)251 body.append(compressed == nil ? 0 : 1)252 append(UInt64((compressed ?? entry.data).count), to: &body)253 append(UInt64(entry.data.count), to: &body)254 body.append(compressed ?? entry.data)255 }256 append(UInt16(0), to: &body)257 append(UInt32(entries.count), to: &body)258259 var header = Data("{}".utf8)260 var key: SymmetricKey?261 if let password {262 guard iterations >= minimumIterations, iterations <= maximumIterations else { throw CapsuleError.weakParameters("iterations") }263 var salt = Data(count: saltLength)264 let status = salt.withUnsafeMutableBytes { SecRandomCopyBytes(kSecRandomDefault, saltLength, $0.baseAddress!) }265 guard status == errSecSuccess else { throw CapsuleError.malformed("no random source") }266 header = try CapsuleCoding.encoder().encode(EncryptionHeader(cipher: cipherName, kdf: kdfName, iterations: iterations,267 salt: salt.base64EncodedString(), keyLength: 32))268 key = try deriveKey(password: password, salt: salt, iterations: iterations)269 }270 var output = magic271 append(version, to: &output)272 append(key == nil ? UInt16(0) : encryptedFlag, to: &output)273 append(UInt32(header.count), to: &output)274 output.append(header)275 if let key {276 // The prefix is authenticated as associated data: changing the header, the flags or the KDF277 // parameters breaks decryption.278 let sealed = try AES.GCM.seal(body, using: key, authenticating: output)279 guard let combined = sealed.combined else { throw CapsuleError.malformed("encryption failed") }280 output.append(combined)281 } else {282 output.append(body)283 output.append(contentsOf: SHA256.hash(data: output))284 }285 guard output.count <= limits.maximumFileBytes else { throw CapsuleError.limitExceeded("file size") }286 return output287 }288289 // MARK: Reading290291 /// A bounds-checked cursor: every read verifies the bytes exist.292 private struct Reader {293 let data: Data294 var offset: Int295296 var remaining: Int { data.count - offset }297298 mutating func bytes(_ count: Int, _ what: String) throws -> Data {299 guard count >= 0, count <= remaining else { throw CapsuleError.malformed("truncated \(what)") }300 defer { offset += count }301 return data.subdata(in: (data.startIndex + offset)..<(data.startIndex + offset + count))302 }303304 mutating func integer<T: FixedWidthInteger>(_ type: T.Type, _ what: String) throws -> T {305 let raw = try bytes(MemoryLayout<T>.size, what)306 return raw.reduce(T(0)) { ($0 << 8) | T($1) }307 }308 }309310 static func isEncrypted(_ file: Data) -> Bool {311 guard file.count >= fixedPrefixLength, file.prefix(magic.count) == magic else { return false }312 let flags = file.subdata(in: (file.startIndex + 10)..<(file.startIndex + 12)).reduce(UInt16(0)) { ($0 << 8) | UInt16($1) }313 return flags & encryptedFlag != 0314 }315316 /// Parses a container and returns its entries in file order, fully validated: structure, sizes, names,317 /// integrity (digest or authentication tag). Throws for anything unexpected; never returns partial content.318 static func read(_ file: Data, password: String?, limits: CapsuleLimits) throws -> [CapsuleEntry] {319 guard file.count <= limits.maximumFileBytes else { throw CapsuleError.limitExceeded("file size") }320 guard file.count >= fixedPrefixLength, file.prefix(magic.count) == magic else { throw CapsuleError.notACapsule }321 var reader = Reader(data: file, offset: magic.count)322 let fileVersion = try reader.integer(UInt16.self, "version")323 guard fileVersion == version else { throw CapsuleError.unsupportedVersion(Int(fileVersion)) }324 let flags = try reader.integer(UInt16.self, "flags")325 guard flags & ~knownFlags == 0 else { throw CapsuleError.malformed("unknown flags") }326 let headerLength = Int(try reader.integer(UInt32.self, "header length"))327 guard headerLength >= 2, headerLength <= limits.maximumHeaderBytes else { throw CapsuleError.malformed("header length") }328 let header = try reader.bytes(headerLength, "header")329 let prefix = file.prefix(fixedPrefixLength + headerLength)330331 let body: Data332 if flags & encryptedFlag != 0 {333 guard let parameters = try? JSONDecoder().decode(EncryptionHeader.self, from: header) else { throw CapsuleError.malformed("encryption header") }334 guard parameters.cipher == cipherName, parameters.kdf == kdfName, parameters.keyLength == 32 else {335 throw CapsuleError.weakParameters("unsupported cipher or key derivation")336 }337 guard parameters.iterations >= minimumIterations, parameters.iterations <= maximumIterations else {338 throw CapsuleError.weakParameters("\(parameters.iterations) iterations")339 }340 guard let salt = Data(base64Encoded: parameters.salt), salt.count >= saltLength, salt.count <= 64 else {341 throw CapsuleError.weakParameters("salt")342 }343 guard let password else { throw CapsuleError.passwordRequired }344 let sealedBytes = try reader.bytes(reader.remaining, "ciphertext")345 guard sealedBytes.count >= 12 + 16 else { throw CapsuleError.malformed("ciphertext") }346 let key = try deriveKey(password: password, salt: salt, iterations: parameters.iterations)347 guard let box = try? AES.GCM.SealedBox(combined: sealedBytes),348 let plain = try? AES.GCM.open(box, using: key, authenticating: prefix) else {349 throw CapsuleError.wrongPasswordOrCorrupted350 }351 body = plain352 } else {353 guard header == Data("{}".utf8) else { throw CapsuleError.malformed("header") }354 guard reader.remaining >= digestLength else { throw CapsuleError.malformed("truncated digest") }355 let digest = file.suffix(digestLength)356 let covered = file.prefix(file.count - digestLength)357 guard Data(SHA256.hash(data: covered)) == digest else { throw CapsuleError.integrityCheckFailed }358 body = try reader.bytes(reader.remaining - digestLength, "body")359 }360 return try parseEntries(body, limits: limits)361 }362363 private static func parseEntries(_ body: Data, limits: CapsuleLimits) throws -> [CapsuleEntry] {364 var reader = Reader(data: body, offset: 0)365 var entries: [CapsuleEntry] = []366 var names = Set<String>()367 var total = 0368 while true {369 let nameLength = Int(try reader.integer(UInt16.self, "entry name length"))370 if nameLength == 0 { break }371 guard entries.count < limits.maximumEntries else { throw CapsuleError.limitExceeded("number of entries") }372 guard nameLength <= limits.maximumNameBytes else { throw CapsuleError.unsafeName("name of \(nameLength) bytes") }373 guard let name = String(data: try reader.bytes(nameLength, "entry name"), encoding: .utf8) else { throw CapsuleError.unsafeName("not UTF-8") }374 guard isSafeName(name, limits: limits) else { throw CapsuleError.unsafeName(name) }375 guard names.insert(name).inserted else { throw CapsuleError.malformed("duplicate entry \(name)") }376 let compression = try reader.integer(UInt8.self, "compression")377 let storedLength = try reader.integer(UInt64.self, "stored length")378 let originalLength = try reader.integer(UInt64.self, "original length")379 // Claims are checked before a single byte is allocated for them.380 guard originalLength <= UInt64(limits.maximumEntryBytes) else { throw CapsuleError.limitExceeded("entry \(name) declares \(originalLength) bytes") }381 guard storedLength <= UInt64(reader.remaining) else { throw CapsuleError.malformed("entry \(name) is truncated") }382 total += Int(originalLength)383 guard total <= limits.maximumTotalBytes else { throw CapsuleError.limitExceeded("total uncompressed size") }384 let stored = try reader.bytes(Int(storedLength), "entry \(name)")385 let payload: Data386 switch compression {387 case 0:388 guard storedLength == originalLength else { throw CapsuleError.malformed("entry \(name) size mismatch") }389 payload = stored390 case 1:391 payload = try inflate(stored, expectedLength: Int(originalLength), name: name)392 default:393 throw CapsuleError.malformed("entry \(name) uses unknown compression \(compression)")394 }395 entries.append(CapsuleEntry(name: name, data: payload))396 }397 let declaredCount = Int(try reader.integer(UInt32.self, "entry count"))398 guard declaredCount == entries.count else { throw CapsuleError.malformed("entry count") }399 guard reader.remaining == 0 else { throw CapsuleError.malformed("trailing bytes") }400 return entries401 }402}403