Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.
Swift apple-siliconcustom-formathomebrewiosipaipadipadosiphonemetalnative-portnintendo-switchnxnativeromfsswitch-games
Launcher: check prod.keys against the game files before the build (issue #63)
v0lumehie62a5035ac46
diff --git a/frontend/README.md b/frontend/README.mdindex 8fc1ad06..0461c610 100644--- a/frontend/README.md+++ b/frontend/README.md@@ -20,6 +20,13 @@ writes them as PNG (from a copy of your library, with example paths), and2. Add an update or DLC under **Updates & add-on content** when needed.3. Choose **This Mac** or **iPhone / iPad**, then **Build game**.+As soon as the base game and `prod.keys` are chosen, the line under `prod.keys` says+whether the keys open the game files: it decrypts the NCA headers of the NSP or NSZ+(base game, update, DLC) with `header_key` and checks that the keys of each one's key+generation are in the file, so keys that are too old for an update show up before the+build, not in its extraction step. An XCI cannot be checked this way and says so. No+key value is shown or logged.+Setup lives under **Settings**: the games folder, the repository and its updates,the dependency checks and installers, and app updates. Missing setup is linkedfrom the build screen. The progress shows each of the script's steps with itsdiff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swiftindex 2c9aff77..b39df59b 100644--- a/frontend/Sources/NSPortBuilder/ContentView.swift+++ b/frontend/Sources/NSPortBuilder/ContentView.swift@@ -2007,6 +2007,7 @@ struct BuilderView: View {var controlChanges = 0@State private var extrasOpen = false@State private var logOpen = false+ @State private var keyCheck: KeyCheck.Outcome? // prod.keys against the chosen files (KeyCheck.swift)@EnvironmentObject private var padFocus: PadFocusvar body: some View {@@ -2157,7 +2158,10 @@ struct BuilderView: View {.contentShape(Rectangle())}.buttonStyle(.plain)- ForEach(m.slots.filter { !$0.optional }, id: \.id) { s in divider; slotRow(s) }+ ForEach(m.slots.filter { !$0.optional }, id: \.id) { s in+ divider; slotRow(s)+ if s.id == "keys", let keyCheck { KeyCheckLine(outcome: keyCheck, t: m.t) }+ }dividerdisclosure(m.t("build.options"), isOpen: extrasOpen) { extrasOpen.toggle() }if extrasOpen {@@ -2171,6 +2175,9 @@ struct BuilderView: View {}}}+ .task(id: KeyCheck.Inputs(keys: m.keysPath, files: [m.basePath, m.updatePath] + m.dlcPaths)) {+ keyCheck = await KeyCheck.runDetached(KeyCheck.Inputs(keys: m.keysPath, files: [m.basePath, m.updatePath] + m.dlcPaths))+ }}private func slotRow(_ s: Slot) -> some View {diff --git a/frontend/Sources/NSPortBuilder/KeyCheck.swift b/frontend/Sources/NSPortBuilder/KeyCheck.swiftnew file mode 100644index 00000000..4cd9b786--- /dev/null+++ b/frontend/Sources/NSPortBuilder/KeyCheck.swift@@ -0,0 +1,264 @@+import SwiftUI+import CommonCrypto++// Checks prod.keys against the chosen game files before a build starts (issue #63). A build with keys+// that are too old for the game, or a header_key that does not open it, used to fail minutes in, in+// the extraction step, with LibHac's message in the log. The same answer is in the first kilobyte of+// each NCA: its header, encrypted with header_key, names the key generation the content needs.+//+// What is read: the PFS0 table of an NSP or NSZ and the first 0x400 bytes of each NCA (an NCZ keeps+// its NCA header as it was, uncompressed). An XCI's NCAs sit in nested HFS0 partitions behind a card+// header, so it is reported as not checkable here rather than guessed at. Key values are never+// printed, logged or shown: only key names appear in the messages.++enum KeyCheck {+ enum Part: String, Sendable { case base, update, dlc }++ enum Outcome: Equatable, Sendable {+ case fits+ case unreadableKeys+ case noHeaderKey+ /// header_key decrypts none of the file's NCA headers to an NCA magic.+ case wrongHeaderKey(file: String)+ /// The newest generation a file needs and a key of it the file lacks (its name, never its value).+ case tooOld(part: Part, generation: Int, missing: String)+ case cannotCheck(file: String)+ }++ /// What the check depends on: it runs again whenever one of these changes.+ struct Inputs: Hashable, Sendable {+ var keys: String+ var files: [String] // base, update, then the add-on content; "" for an empty slot+ }++ /// The firmware that brought each master key revision (hactool's table), for telling someone what to dump the keys from.+ static let firmware = ["1.0.0", "3.0.0", "3.0.1", "4.0.0", "5.0.0", "6.0.0", "6.2.0", "7.0.0", "8.1.0", "9.0.0",+ "9.1.0", "12.1.0", "13.0.0", "14.0.0", "15.0.0", "16.0.0", "17.0.0", "18.0.0", "19.0.0", "20.0.0"]++ // MARK: prod.keys++ /// `name = hex` lines, names lowercased; anything else (comments, blank lines, a value that is not hex) is skipped.+ static func parseKeys(_ text: String) -> [String: [UInt8]] {+ var keys: [String: [UInt8]] = [:]+ for line in text.split(whereSeparator: \.isNewline) {+ let parts = line.split(separator: "=", maxSplits: 1)+ guard parts.count == 2 else { continue }+ let name = parts[0].trimmingCharacters(in: .whitespaces).lowercased()+ if let value = hex(parts[1].trimmingCharacters(in: .whitespaces)), !name.isEmpty { keys[name] = value }+ }+ return keys+ }++ static func hex(_ s: String) -> [UInt8]? {+ let chars = Array(s.utf8)+ guard !chars.isEmpty, chars.count % 2 == 0 else { return nil }+ var out: [UInt8] = []+ out.reserveCapacity(chars.count / 2)+ for i in stride(from: 0, to: chars.count, by: 2) {+ guard let hi = nibble(chars[i]), let lo = nibble(chars[i + 1]) else { return nil }+ out.append(hi << 4 | lo)+ }+ return out+ }++ private static func nibble(_ c: UInt8) -> UInt8? {+ switch c {+ case 0x30...0x39: return c - 0x30+ case 0x41...0x46: return c - 0x41 + 10+ case 0x61...0x66: return c - 0x61 + 10+ default: return nil+ }+ }++ // MARK: AES-XTS++ /// AES-128-XTS over whole sectors, as Nintendo uses it for NCA headers: the 32-byte key is the data key then the+ /// tweak key, and the tweak is the sector number big-endian (IEEE 1619 has it little-endian). CommonCrypto has no+ /// XTS mode, so it is built on ECB: the blocks of a sector are independent once each is masked with its tweak.+ static func xts(_ data: [UInt8], key: [UInt8], sector: UInt64 = 0, sectorSize: Int = 0x200, encrypt: Bool) -> [UInt8]? {+ guard key.count == 32, sectorSize > 0, sectorSize % 16 == 0, data.count % sectorSize == 0 else { return nil }+ var out: [UInt8] = []+ out.reserveCapacity(data.count)+ for (i, start) in stride(from: 0, to: data.count, by: sectorSize).enumerated() {+ var tweak = [UInt8](repeating: 0, count: 16)+ var n = sector + UInt64(i)+ for b in (8..<16).reversed() { tweak[b] = UInt8(n & 0xFF); n >>= 8 }+ guard let s = xtsSector(Array(data[start..<start + sectorSize]), dataKey: Array(key[0..<16]), tweakKey: Array(key[16..<32]),+ tweak: tweak, encrypt: encrypt) else { return nil }+ out += s+ }+ return out+ }++ /// One sector with a given 16-byte tweak block (the tests feed it IEEE 1619's own vectors).+ static func xtsSector(_ data: [UInt8], dataKey: [UInt8], tweakKey: [UInt8], tweak: [UInt8], encrypt: Bool) -> [UInt8]? {+ guard data.count % 16 == 0, var t = ecb(tweak, key: tweakKey, encrypt: true) else { return nil }+ var masks: [UInt8] = []+ masks.reserveCapacity(data.count)+ for _ in 0..<(data.count / 16) {+ masks += t+ // multiply by x in GF(2^128), the bytes little-endian+ var carry: UInt8 = 0+ for j in 0..<16 { let c = t[j] >> 7; t[j] = t[j] << 1 | carry; carry = c }+ if carry != 0 { t[0] ^= 0x87 }+ }+ guard let y = ecb(zip(data, masks).map { $0 ^ $1 }, key: dataKey, encrypt: encrypt) else { return nil }+ return zip(y, masks).map { $0 ^ $1 }+ }++ private static func ecb(_ data: [UInt8], key: [UInt8], encrypt: Bool) -> [UInt8]? {+ var out = [UInt8](repeating: 0, count: data.count)+ var moved = 0+ let status = CCCrypt(CCOperation(encrypt ? kCCEncrypt : kCCDecrypt), CCAlgorithm(kCCAlgorithmAES), CCOptions(kCCOptionECBMode),+ key, key.count, nil, data, data.count, &out, out.count, &moved)+ return status == kCCSuccess && moved == data.count ? out : nil+ }++ // MARK: NCA headers++ /// The bytes of the header that matter here: the magic at 0x200, both key generation fields and the rights ID+ /// (0x200...0x23F, sector 1). Two sectors are decrypted because XTS needs whole ones.+ static let headerBytes = 0x400++ /// The key a decrypted NCA header needs, and its master key revision. nil when it is not an NCA header (wrong key).+ /// The revision is the larger of the two key generation fields (0x206 for the oldest firmware, 0x220 since 3.0.1),+ /// minus one when not zero, as LibHac (which the build's extractor uses) and hactool derive it. Content with a+ /// rights ID is opened through its ticket's title key, which titlekek_XX decrypts; content without one carries its+ /// keys in the key area, under key_area_key_<application|ocean|system>_XX (the index at 0x207).+ static func needs(header h: [UInt8]) -> (revision: Int, key: String)? {+ guard h.count >= headerBytes else { return nil }+ let magic = String(bytes: h[0x200..<0x204], encoding: .ascii) ?? ""+ guard ["NCA3", "NCA2"].contains(magic) else { return nil }+ let generation = Int(max(h[0x206], h[0x220]))+ let revision = generation == 0 ? 0 : generation - 1+ let suffix = String(format: "%02x", revision)+ if h[0x230..<0x240].contains(where: { $0 != 0 }) { return (revision, "titlekek_" + suffix) }+ let area = ["application", "ocean", "system"]+ guard Int(h[0x207]) < area.count else { return nil }+ return (revision, "key_area_key_\(area[Int(h[0x207])])_" + suffix)+ }++ /// A derived key counts when it is in the file or its master key is: LibHac derives titlekek and the key area+ /// keys from master_key_XX with the sources it carries, and some key dumps list only the master keys.+ static func has(_ key: String, in keys: [String: [UInt8]]) -> Bool {+ if keys[key]?.count == 16 { return true }+ guard let suffix = key.split(separator: "_").last else { return false }+ return keys["master_key_" + suffix]?.count == 16+ }++ enum Container {+ /// The encrypted headers of the package's NCAs, each with whether it is an NCZ (whose layout is taken on trust).+ case pfs0([(header: [UInt8], ncz: Bool)])+ case unsupported+ }++ /// The NCA headers of an NSP or NSZ (a PFS0); anything else, an XCI among them, is `unsupported`.+ static func readContainer(_ path: String) -> Container {+ guard let f = FileHandle(forReadingAtPath: path) else { return .unsupported }+ defer { try? f.close() }+ func read(_ offset: UInt64, _ count: Int) -> [UInt8]? {+ guard (try? f.seek(toOffset: offset)) != nil, let d = try? f.read(upToCount: count), d.count == count else { return nil }+ return [UInt8](d)+ }+ func u32(_ b: [UInt8], _ o: Int) -> Int { Int(b[o]) | Int(b[o + 1]) << 8 | Int(b[o + 2]) << 16 | Int(b[o + 3]) << 24 }+ func u64(_ b: [UInt8], _ o: Int) -> UInt64 { (0..<8).reduce(UInt64(0)) { $0 | UInt64(b[o + $1]) << (8 * $1) } }+ guard let head = read(0, 0x10), head[0..<4].elementsEqual("PFS0".utf8) else { return .unsupported }+ let count = u32(head, 4), names = u32(head, 8)+ guard count > 0, count <= 4096, names <= 1 << 20, let table = read(0x10, count * 0x18 + names) else { return .unsupported }+ let dataStart = UInt64(0x10 + count * 0x18 + names)+ var headers: [(header: [UInt8], ncz: Bool)] = []+ for i in 0..<count {+ let e = i * 0x18+ let offset = u64(table, e), size = u64(table, e + 8), nameAt = count * 0x18 + u32(table, e + 0x10)+ guard nameAt < table.count else { continue }+ let name = String(decoding: table[nameAt...].prefix { $0 != 0 }, as: UTF8.self).lowercased()+ let ncz = name.hasSuffix(".ncz")+ guard name.hasSuffix(".nca") || ncz, size >= UInt64(headerBytes), let h = read(dataStart + offset, headerBytes) else { continue }+ headers.append((h, ncz))+ }+ return .pfs0(headers)+ }++ // MARK: The check++ /// The check for the Builds page, off the main thread; nil (no line) until both the base game and prod.keys are chosen.+ static func runDetached(_ inputs: Inputs) async -> Outcome? {+ guard !inputs.keys.isEmpty, inputs.files.first.map({ !$0.isEmpty }) == true else { return nil }+ return await Task.detached(priority: .userInitiated) { run(inputs) }.value+ }++ /// Every chosen file against the keys; the worst finding wins (a key that opens nothing, then the newest missing+ /// generation, then a file that cannot be checked). Reads a few kilobytes per file, so it is quick, but it reads+ /// files: run it off the main thread.+ static func run(_ inputs: Inputs) -> Outcome {+ guard let data = FileManager.default.contents(atPath: inputs.keys),+ let text = String(data: data, encoding: .utf8) ?? String(data: data, encoding: .isoLatin1) else { return .unreadableKeys }+ let parts: [Part] = [.base, .update] + Array(repeating: .dlc, count: max(0, inputs.files.count - 2))+ let files = zip(parts, inputs.files).filter { !$0.1.isEmpty }.map { (part: $0.0, path: $0.1, container: readContainer($0.1)) }+ return check(keys: parseKeys(text), files: files.map { ($0.part, ($0.path as NSString).lastPathComponent, $0.container) })+ }++ static func check(keys: [String: [UInt8]], files: [(part: Part, name: String, container: Container)]) -> Outcome {+ guard let headerKey = keys["header_key"] else { return .noHeaderKey }+ var tooOld: (part: Part, revision: Int, key: String)?+ var unchecked: String?+ for file in files {+ guard case let .pfs0(ncas) = file.container, !ncas.isEmpty else { unchecked = unchecked ?? file.name; continue }+ // A damaged NCA among good ones is the file's problem, not the keys': only a key that opens none is wrong.+ let opened = ncas.compactMap { nca -> (revision: Int, key: String)? in+ guard headerKey.count == 32, let plain = xts(nca.header, key: headerKey, encrypt: false) else { return nil }+ return needs(header: plain)+ }+ if opened.isEmpty {+ // An NCZ's header is expected to be the NCA's own, still encrypted; if it is not, that is not the key's fault.+ if ncas.allSatisfy(\.ncz) { unchecked = unchecked ?? file.name; continue }+ return .wrongHeaderKey(file: file.name)+ }+ for need in opened where !has(need.key, in: keys) && need.revision > (tooOld?.revision ?? -1) {+ tooOld = (file.part, need.revision, need.key)+ }+ }+ if let tooOld { return .tooOld(part: tooOld.part, generation: tooOld.revision + 1, missing: tooOld.key) }+ if let unchecked { return .cannotCheck(file: unchecked) }+ return .fits+ }++ /// The line under the prod.keys row.+ static func message(_ o: Outcome, _ t: (String) -> String) -> String {+ switch o {+ case .fits: return t("keycheck.fits")+ case .unreadableKeys: return t("keycheck.unreadable")+ case .noHeaderKey: return t("keycheck.noHeaderKey")+ case .wrongHeaderKey(let file): return String(format: t("keycheck.wrongHeaderKey"), file)+ case .cannotCheck(let file): return String(format: t("keycheck.cannotCheck"), file)+ case let .tooOld(part, generation, missing):+ var s = String(format: t("keycheck.tooOld"), t("keycheck.part." + part.rawValue), generation, missing)+ if generation - 1 < firmware.count { s += " " + String(format: t("keycheck.firmware"), firmware[generation - 1]) }+ return s+ }+ }+}++/// The key check's result, set in under the prod.keys row it is about.+struct KeyCheckLine: View {+ let outcome: KeyCheck.Outcome+ let t: (String) -> String++ var body: some View {+ let (symbol, color): (String, Color) = {+ switch outcome {+ case .fits: return ("checkmark.circle.fill", LauncherPalette.ready)+ case .cannotCheck: return ("questionmark.circle", .secondary)+ default: return ("exclamationmark.triangle.fill", LauncherPalette.building)+ }+ }()+ HStack(alignment: .firstTextBaseline, spacing: 7) {+ Image(systemName: symbol).font(.system(size: 11, weight: .semibold)).foregroundStyle(color)+ Text(KeyCheck.message(outcome, t)).font(.manrope(12.5)).foregroundStyle(outcome == .fits ? Color.secondary : color)+ .fixedSize(horizontal: false, vertical: true)+ Spacer(minLength: 0)+ }+ // under the row's title: past its padding and its dot's place+ .padding(.leading, 37).padding(.trailing, 18).padding(.top, -6).padding(.bottom, 13)+ }+}diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swiftindex 03ebf7f7..aec5abf4 100644--- a/frontend/Sources/NSPortBuilder/Localization.swift+++ b/frontend/Sources/NSPortBuilder/Localization.swift@@ -143,6 +143,16 @@ enum L10n {"build.heading": ("\u{6784}\u{5efa}\u{6e38}\u{620f}", "Build game"),"build.intro": ("\u{9009}\u{62e9}\u{6e38}\u{620f}\u{6587}\u{4ef6}\u{548c}\u{8fd0}\u{884c}\u{8bbe}\u{5907}\u{3002}", "Choose game files and an output."),"build.files": ("1. \u{9009}\u{62e9}\u{6e38}\u{620f}\u{6587}\u{4ef6}", "1. Choose your game files"),+ "keycheck.fits": ("密钥匹配:可以打开这些游戏文件", "Keys fit: they open these game files"),+ "keycheck.unreadable": ("无法读取 prod.keys", "prod.keys can’t be read"),+ "keycheck.noHeaderKey": ("prod.keys 中缺少 header_key", "header_key is missing from prod.keys"),+ "keycheck.wrongHeaderKey": ("prod.keys 中的 header_key 打不开 %@", "The header_key in prod.keys doesn’t open %@"),+ "keycheck.cannotCheck": ("构建前无法检查这种格式:%@", "Can’t check this format before building: %@"),+ "keycheck.tooOld": ("这些密钥比%1$@所需的旧:需要密钥世代 %2$ld(缺少 %3$@)。", "These keys are older than %1$@ needs: key generation %2$ld (%3$@ is missing)."),+ "keycheck.firmware": ("请从系统版本 %@ 或更新的 Switch 重新导出 prod.keys。", "Dump prod.keys again from a Switch on firmware %@ or newer."),+ "keycheck.part.base": ("游戏本体", "the base game"),+ "keycheck.part.update": ("更新包", "the update"),+ "keycheck.part.dlc": ("追加内容", "the add-on content"),"build.folderNote": ("\u{9009}\u{62e9}\u{5305}\u{542b}\u{6e38}\u{620f}\u{7684}\u{6587}\u{4ef6}\u{5939}\u{ff0c}\u{6216}\u{9010}\u{4e2a}\u{9009}\u{62e9}\u{6587}\u{4ef6}\u{3002}", "Choose the folder containing your game, or select the files below."),"build.options": ("\u{66f4}\u{65b0}\u{548c}\u{9644}\u{52a0}\u{5185}\u{5bb9}\u{ff08}\u{53ef}\u{9009}\u{ff09}", "Updates & add-on content (optional)"),"build.details": ("\u{6784}\u{5efa}\u{8be6}\u{60c5}", "Build details"),diff --git a/frontend/Tests/NSPortBuilderTests/KeyCheckTests.swift b/frontend/Tests/NSPortBuilderTests/KeyCheckTests.swiftnew file mode 100644index 00000000..43e29e08--- /dev/null+++ b/frontend/Tests/NSPortBuilderTests/KeyCheckTests.swift@@ -0,0 +1,197 @@+import XCTest+import SwiftUI+@testable import NSPortBuilder++/// prod.keys against the game files before a build (issue #63). Every key here is made up for the test.+final class KeyCheckTests: XCTestCase {+ private var temporary: URL!+ private let headerKey = (0..<32).map { UInt8(0xA0 ^ $0) }++ override func setUpWithError() throws {+ temporary = FileManager.default.temporaryDirectory.appendingPathComponent("nxnative-keycheck-" + UUID().uuidString)+ try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true)+ }++ override func tearDownWithError() throws { try FileManager.default.removeItem(at: temporary) }++ private func hex(_ b: [UInt8]) -> String { b.map { String(format: "%02x", $0) }.joined() }++ /// An NCA header as a game's has it, encrypted with `key`: NCA3, the key generation in the newer field, a rights ID or the key area index.+ private func ncaHeader(generation: UInt8, rightsID: Bool = true, keyArea: UInt8 = 0, key: [UInt8]? = nil) -> [UInt8] {+ var h = [UInt8](repeating: 0, count: 0xC00)+ h.replaceSubrange(0x200..<0x204, with: Array("NCA3".utf8))+ h[0x206] = 2; h[0x207] = keyArea; h[0x220] = generation+ if rightsID { h[0x230] = 0x01; h[0x23F] = generation }+ return KeyCheck.xts(h, key: key ?? headerKey, encrypt: true)!+ }++ /// A PFS0 (an NSP) of the given files.+ private func pfs0(_ files: [(String, [UInt8])], name: String = "Game [0100000000010800][v65536].nsp") throws -> String {+ var names: [UInt8] = [], entries: [UInt8] = [], data: [UInt8] = []+ func le(_ v: Int, _ n: Int) -> [UInt8] { (0..<n).map { UInt8(v >> (8 * $0) & 0xFF) } }+ for (file, bytes) in files {+ entries += le(data.count, 8) + le(bytes.count, 8) + le(names.count, 4) + le(0, 4)+ names += Array(file.utf8) + [0]+ data += bytes+ }+ while names.count % 0x20 != 0 { names.append(0) }+ let out = Array("PFS0".utf8) + le(files.count, 4) + le(names.count, 4) + le(0, 4) + entries + names + data+ let path = temporary.appendingPathComponent(name).path+ FileManager.default.createFile(atPath: path, contents: Data(out))+ return path+ }++ private func keysFile(_ lines: [String]) throws -> String {+ let path = temporary.appendingPathComponent("prod.keys").path+ try lines.joined(separator: "\n").write(toFile: path, atomically: true, encoding: .utf8)+ return path+ }++ private func key(_ name: String, _ byte: UInt8 = 0x5A) -> String { name + " = " + hex([UInt8](repeating: byte, count: 16)) }++ // MARK: AES-XTS++ func testXTSMatchesTheIEEE1619Vectors() {+ // Vector 1: both keys zero, data unit 0, 32 zero bytes+ XCTAssertEqual(KeyCheck.xtsSector([UInt8](repeating: 0, count: 32), dataKey: [UInt8](repeating: 0, count: 16), tweakKey: [UInt8](repeating: 0, count: 16),+ tweak: [UInt8](repeating: 0, count: 16), encrypt: true).map(hex),+ "917cf69ebd68b2ec9b9fe9a3eadda692cd43d2f59598ed858c02c2652fbf922e")+ // Vector 2: keys 11… and 22…, data unit 0x3333333333 (little-endian in the standard's tweak), 32 bytes of 0x44+ let tweak: [UInt8] = [0x33, 0x33, 0x33, 0x33, 0x33] + [UInt8](repeating: 0, count: 11)+ let cipher = KeyCheck.xtsSector([UInt8](repeating: 0x44, count: 32), dataKey: [UInt8](repeating: 0x11, count: 16),+ tweakKey: [UInt8](repeating: 0x22, count: 16), tweak: tweak, encrypt: true)+ XCTAssertEqual(cipher.map(hex), "c454185e6a16936e39334038acef838bfb186fff7480adc4289382ecd6d394f0")+ XCTAssertEqual(KeyCheck.xtsSector(cipher!, dataKey: [UInt8](repeating: 0x11, count: 16), tweakKey: [UInt8](repeating: 0x22, count: 16),+ tweak: tweak, encrypt: false), [UInt8](repeating: 0x44, count: 32))+ }++ func testXTSTakesTheSectorNumberBigEndianAsNintendoDoes() throws {+ // Reference from Python's cryptography (AES-XTS with the tweak 1 and 2 as 16 big-endian bytes)+ let key = (0..<32).map { UInt8($0) }+ let plain = (0..<1024).map { UInt8($0 & 0xFF) }+ let cipher = try XCTUnwrap(KeyCheck.xts(plain, key: key, sector: 1, encrypt: true))+ XCTAssertEqual(hex(Array(cipher[0..<32])), "b3a5829f75001e33a3e33d96293537271839b0f42b2193fe6b6639f25fce3dc9")+ XCTAssertEqual(hex(Array(cipher[512..<544])), "e6c87ee3b2bf1279e40ce226185a4e4b65d1b98ecc430fc229f63e1f75705f2c")+ XCTAssertEqual(hex(Array(cipher[992...])), "82142b94e8152ad255c70f932fd60e476bf7d1e01ec121147c775085bcb4bdc9")+ XCTAssertEqual(KeyCheck.xts(cipher, key: key, sector: 1, encrypt: false), plain)+ XCTAssertNil(KeyCheck.xts(plain, key: Array(key[0..<16]), encrypt: true), "a 16-byte key is not an XTS key")+ }++ // MARK: NCA headers++ func testASyntheticHeaderDecryptsWithTheTestHeaderKey() throws {+ let plain = try XCTUnwrap(KeyCheck.xts(Array(ncaHeader(generation: 0x13)[0..<KeyCheck.headerBytes]), key: headerKey, encrypt: false))+ XCTAssertEqual(KeyCheck.needs(header: plain)?.revision, 0x12, "the larger generation field, minus one")+ XCTAssertEqual(KeyCheck.needs(header: plain)?.key, "titlekek_12")+ let area = try XCTUnwrap(KeyCheck.xts(Array(ncaHeader(generation: 0, rightsID: false, keyArea: 1)[0..<KeyCheck.headerBytes]), key: headerKey, encrypt: false))+ XCTAssertEqual(KeyCheck.needs(header: area)?.key, "key_area_key_ocean_01", "the old field (2) when the new one is 0; no rights ID: the key area")++ let nsp = try pfs0([("0123.nca", ncaHeader(generation: 0x13)), ("0123.tik", [UInt8](repeating: 0, count: 0x2C0))])+ let keys = try keysFile(["; a comment", "header_key = " + hex(headerKey), key("titlekek_12"), "", "not a key line"])+ XCTAssertEqual(KeyCheck.run(.init(keys: keys, files: ["", nsp])), .fits)+ }++ func testMissingGenerationKeysAreDetected() throws {+ let base = try pfs0([("a.nca", ncaHeader(generation: 0x0C)), ("b.cnmt.nca", ncaHeader(generation: 0x0C, rightsID: false))], name: "Game [0100000000010000].nsp")+ let update = try pfs0([("c.nca", ncaHeader(generation: 0x13)), ("d.nca", ncaHeader(generation: 0x11))])+ let keys = try keysFile(["header_key = " + hex(headerKey), key("titlekek_0b"), key("key_area_key_application_0b"), key("titlekek_10")])+ let outcome = KeyCheck.run(.init(keys: keys, files: [base, update]))+ XCTAssertEqual(outcome, .tooOld(part: .update, generation: 0x13, missing: "titlekek_12"), "the newest generation that is missing")+ let text = KeyCheck.message(outcome) { L10n.string($0, .en) }+ XCTAssertTrue(text.contains("the update") && text.contains("key generation 19") && text.contains("titlekek_12") && text.contains("19.0.0"), text)+ XCTAssertFalse(text.contains(hex(headerKey)) || text.contains("5a5a"), "never a key value")+ XCTAssertEqual(KeyCheck.run(.init(keys: keys, files: [base, ""])), .fits)++ // a dump that lists only the master keys: the extractor derives the rest from them+ let master = try keysFile(["header_key = " + hex(headerKey), key("master_key_0b"), key("master_key_10"), key("master_key_12")])+ XCTAssertEqual(KeyCheck.run(.init(keys: master, files: [base, update])), .fits)+ }++ func testAWrongHeaderKeyIsRejected() throws {+ let nsp = try pfs0([("a.nca", ncaHeader(generation: 0x13))])+ let other = (0..<32).map { UInt8(0x30 + $0) }+ let keys = try keysFile(["header_key = " + hex(other), key("titlekek_12")])+ XCTAssertEqual(KeyCheck.run(.init(keys: keys, files: [nsp])), .wrongHeaderKey(file: (nsp as NSString).lastPathComponent))+ let short = try keysFile(["header_key = " + hex(Array(headerKey[0..<16])), key("titlekek_12")])+ XCTAssertEqual(KeyCheck.run(.init(keys: short, files: [nsp])), .wrongHeaderKey(file: (nsp as NSString).lastPathComponent))+ let none = try keysFile([key("titlekek_12")])+ XCTAssertEqual(KeyCheck.run(.init(keys: none, files: [nsp])), .noHeaderKey)+ XCTAssertEqual(KeyCheck.run(.init(keys: temporary.appendingPathComponent("absent.keys").path, files: [nsp])), .unreadableKeys)+ }++ func testFormatsThatCannotBeCheckedSaySo() throws {+ var card = [UInt8](repeating: 0, count: 0x200)+ card.replaceSubrange(0x100..<0x104, with: Array("HEAD".utf8))+ let xci = temporary.appendingPathComponent("Game [0100000000010000].xci").path+ FileManager.default.createFile(atPath: xci, contents: Data(card))+ let keys = try keysFile(["header_key = " + hex(headerKey), key("titlekek_12")])+ XCTAssertEqual(KeyCheck.run(.init(keys: keys, files: [xci])), .cannotCheck(file: "Game [0100000000010000].xci"))+ // an NCZ whose first bytes are not the NCA's header is not taken as a wrong key+ let nsz = try pfs0([("a.ncz", [UInt8](repeating: 0x77, count: 0x4000))], name: "Game [0100000000010000].nsz")+ XCTAssertEqual(KeyCheck.run(.init(keys: keys, files: [nsz])), .cannotCheck(file: "Game [0100000000010000].nsz"))+ // one whose header is the NCA's own is checked like an NSP+ let good = try pfs0([("a.ncz", ncaHeader(generation: 0x13) + [UInt8](repeating: 0, count: 0x3400))], name: "Good [0100000000010000].nsz")+ XCTAssertEqual(KeyCheck.run(.init(keys: keys, files: [good])), .fits)+ // a problem with the keys outranks a file that could not be checked+ let old = try pfs0([("a.nca", ncaHeader(generation: 0x13))], name: "Update [0100000000010800].nsp")+ let olderKeys = try keysFile(["header_key = " + hex(headerKey)])+ XCTAssertEqual(KeyCheck.run(.init(keys: olderKeys, files: [xci, old])), .tooOld(part: .update, generation: 0x13, missing: "titlekek_12"))+ }++ func testNoLineUntilTheBaseGameAndTheKeysAreChosen() async {+ let none = await KeyCheck.runDetached(.init(keys: "", files: ["/x.nsp"]))+ XCTAssertNil(none)+ let noBase = await KeyCheck.runDetached(.init(keys: "/prod.keys", files: ["", "/update.nsp"]))+ XCTAssertNil(noBase)+ }++ func testEveryMessageHasBothLanguages() {+ let outcomes: [KeyCheck.Outcome] = [.fits, .unreadableKeys, .noHeaderKey, .wrongHeaderKey(file: "a.nsp"), .cannotCheck(file: "a.xci"),+ .tooOld(part: .base, generation: 0x13, missing: "titlekek_12"), .tooOld(part: .dlc, generation: 0x30, missing: "titlekek_2f")]+ for lang in [Lang.zh, .en] {+ for o in outcomes {+ let text = KeyCheck.message(o) { L10n.string($0, lang) }+ XCTAssertFalse(text.contains("keycheck."), text)+ }+ }+ XCTAssertTrue(KeyCheck.message(.tooOld(part: .base, generation: 0x13, missing: "titlekek_12")) { L10n.string($0, .zh) }.contains("titlekek_12"))+ XCTAssertFalse(KeyCheck.message(.tooOld(part: .dlc, generation: 0x30, missing: "titlekek_2f")) { L10n.string($0, .en) }.contains("firmware"),+ "no firmware named past the table")+ }++ // MARK: Visual QA (matched by --filter testRenderLauncherForVisualQA)++ @MainActor func testRenderLauncherForVisualQAKeyCheck() throws {+ guard let directory = ProcessInfo.processInfo.environment["NX_LAUNCHER_CAPTURE_DIR"] else { throw XCTSkip("Set NX_LAUNCHER_CAPTURE_DIR to capture native views") }+ let output = URL(fileURLWithPath: directory)+ try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)+ NSApplication.shared.setActivationPolicy(.accessory)+ let oldOutput = UserDefaults.standard.object(forKey: "buildOutputDirectory")+ defer { UserDefaults.standard.set(oldOutput, forKey: "buildOutputDirectory") }+ let model = BuildModel()+ model.lang = .en+ model.outDir = temporary.path+ model.depsChecked = true+ model.deps = [BuildModel.Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])]+ let library = GameLibrary(file: temporary.appendingPathComponent("preview.json"))+ let base = try pfs0([("a.nca", ncaHeader(generation: 0x0C))], name: "Metroid Dread [010093801237C000].nsp")+ let update = try pfs0([("b.nca", ncaHeader(generation: 0x13))], name: "Metroid Dread [010093801237C800][v327680].nsp")+ func capture(_ name: String, keys: [String], withUpdate: Bool) throws {+ model.slots[0].paths = [base]+ model.slots[1].paths = withUpdate ? [update] : []+ model.slots[3].paths = [try keysFile(keys)]+ let host = NSHostingView(rootView: ContentView(model: model, library: library, initialPage: .builds, performStartupChecks: false))+ let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1440, height: 1024), styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false)+ window.contentView = host+ window.orderFront(nil)+ RunLoop.main.run(until: Date().addingTimeInterval(0.8))+ host.layoutSubtreeIfNeeded()+ let rep = try XCTUnwrap(host.bitmapImageRepForCachingDisplay(in: host.bounds))+ host.cacheDisplay(in: host.bounds, to: rep)+ try XCTUnwrap(rep.representation(using: .png, properties: [:])).write(to: output.appendingPathComponent(name + ".png"))+ window.orderOut(nil)+ }+ try capture("build-keys-fit", keys: ["header_key = " + hex(headerKey), key("titlekek_0b")], withUpdate: false)+ try capture("build-keys-old", keys: ["header_key = " + hex(headerKey), key("titlekek_0b")], withUpdate: true)+ }+}