#!/usr/bin/env swift
// Decrypts a Vaultbook encrypted journal without Vaultbook, on any Mac.
//
//   swift vaultbook-decrypt.swift <vault folder> <output folder>
//
// Asks for the passphrase, or the recovery code if you no longer have it. Writes every
// decrypted file into the output folder under its original name; the vault is only read.
// Written from docs/ENCRYPTION-FORMAT.md alone, so it shares no code with the app.

import Foundation
import CryptoKit
import CommonCrypto

struct Wrap: Decodable { let salt: Data; let iterations: Int; let sealedKey: Data }
struct KeyFile: Decodable { let format: Int; let keyID: Data; let passphrase: Wrap; let recovery: Wrap }

func fail(_ message: String) -> Never {
    FileHandle.standardError.write(Data((message + "\n").utf8))
    exit(1)
}

func pbkdf2(_ secret: String, _ salt: Data, _ iterations: Int) -> SymmetricKey {
    let password = Array(secret.precomposedStringWithCanonicalMapping.utf8).map { Int8(bitPattern: $0) }
    var out = [UInt8](repeating: 0, count: 32)
    _ = salt.withUnsafeBytes {
        CCKeyDerivationPBKDF(CCPBKDFAlgorithm(kCCPBKDF2), password, password.count,
                             $0.bindMemory(to: UInt8.self).baseAddress, salt.count,
                             CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA256), UInt32(iterations), &out, 32)
    }
    return SymmetricKey(data: out)
}

func canonicalCode(_ typed: String) -> String? {
    let alphabet = Array("0123456789ABCDEFGHJKMNPQRSTVWXYZ")
    let chars: [Character] = typed.uppercased().compactMap {
        switch $0 { case "O": return "0"; case "I", "L": return "1"; case " ", "-", "\n", "\t": return nil; default: return $0 }
    }
    guard chars.count == 30, chars.allSatisfy(alphabet.contains) else { return nil }
    var s = 0
    for (i, c) in chars.prefix(28).enumerated() { s = (s + (i + 1) * alphabet.firstIndex(of: c)!) % 1021 }
    guard chars[28] == alphabet[s / 32 % 32], chars[29] == alphabet[s % 32] else { return nil }
    return stride(from: 0, to: 30, by: 5).map { String(chars[$0 ..< $0 + 5]) }.joined(separator: "-")
}

func unwrap(_ wrap: Wrap, _ secret: String) -> SymmetricKey? {
    guard let box = try? ChaChaPoly.SealedBox(combined: wrap.sealedKey),
          let raw = try? ChaChaPoly.open(box, using: pbkdf2(secret, wrap.salt, wrap.iterations),
                                         authenticating: Data("vaultbook key".utf8)) else { return nil }
    return SymmetricKey(data: raw)
}

func decrypt(_ file: Data, key: SymmetricKey, keyID: Data) -> Data? {
    guard file.count >= 29 + 16, file.prefix(4) == Data("VBE1".utf8), file[file.startIndex + 4] == 1 else { return nil }
    let header = Data(file.prefix(29))
    guard header[5..<13] == keyID else { return nil }
    let h = [UInt8](header)
    let chunk = Int(h[13]) | Int(h[14]) << 8 | Int(h[15]) << 16 | Int(h[16]) << 24
    let base = Array(h[17..<29])
    let body = Data(file.dropFirst(29))
    var out = Data(), offset = 0, n: UInt64 = 0
    while true {
        let remaining = body.count - offset, take = min(chunk + 16, remaining), last = take == remaining
        guard take >= 16 else { return nil }
        var nonce = base
        for i in 0..<8 { nonce[4 + i] ^= UInt8(n >> (8 * UInt64(7 - i)) & 0xFF) }
        var aad = header
        for i in (0..<8).reversed() { aad.append(UInt8(n >> (8 * UInt64(i)) & 0xFF)) }
        aad.append(last ? 1 : 0)
        let piece = body[offset ..< offset + take]
        guard let box = try? ChaChaPoly.SealedBox(nonce: ChaChaPoly.Nonce(data: nonce), ciphertext: piece.dropLast(16), tag: piece.suffix(16)),
              let plain = try? ChaChaPoly.open(box, using: key, authenticating: aad) else { return nil }
        out.append(plain)
        offset += take; n += 1
        if last { return out }
    }
}

let arguments = CommandLine.arguments
guard arguments.count >= 3 else { fail("usage: swift vaultbook-decrypt.swift <vault folder> <output folder> [passphrase or recovery code]") }
// Symlinks resolved, so a folder reached through one (as /var is, through /private/var) still
// gives each file its right place under the output folder.
let vault = URL(fileURLWithPath: arguments[1]).resolvingSymlinksInPath(), output = URL(fileURLWithPath: arguments[2])
guard let keyData = try? Data(contentsOf: vault.appendingPathComponent(".vaultbook/encryption.json")),
      let keyFile = try? JSONDecoder().decode(KeyFile.self, from: keyData) else { fail("No .vaultbook/encryption.json in \(vault.path).") }
let secret = arguments.count > 3 ? arguments[3] : String(cString: getpass("Passphrase or recovery code: "))
guard let key = unwrap(keyFile.passphrase, secret) ?? canonicalCode(secret).flatMap({ unwrap(keyFile.recovery, $0) }) else {
    fail("That isn't the passphrase or the recovery code for this vault.")
}

var written = 0, refused: [String] = []
let walker = FileManager.default.enumerator(at: vault, includingPropertiesForKeys: nil)
while let url = walker?.nextObject() as? URL {
    guard url.pathExtension == "vbe", let data = try? Data(contentsOf: url) else { continue }
    let full = url.resolvingSymlinksInPath().path
    guard full.hasPrefix(vault.path + "/") else { refused.append(full); continue }
    let relative = String(full.dropFirst(vault.path.count + 1).dropLast(4))
    guard let plain = decrypt(data, key: key, keyID: keyFile.keyID), plain.count >= 4 else { refused.append(relative); continue }
    // Inside: the name's length (4 bytes, little-endian), the name, then the file. The name is
    // the file's path inside its journal folder, which is the folder the encrypted file is in.
    let b = [UInt8](plain.prefix(4))
    let length = Int(b[0]) | Int(b[1]) << 8 | Int(b[2]) << 16 | Int(b[3]) << 24
    guard plain.count >= 4 + length, let name = String(data: plain.dropFirst(4).prefix(length), encoding: .utf8),
          !name.hasPrefix("/"), !name.split(separator: "/").contains("..") else { refused.append(relative); continue }
    let folder = (relative as NSString).deletingLastPathComponent
    let target = output.appendingPathComponent(folder).appendingPathComponent(name)
    let content = plain.dropFirst(4 + length)
    try? FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
    do { try content.write(to: target); written += 1 } catch { refused.append(relative) }
}
print("Decrypted \(written) files into \(output.path).")
if !refused.isEmpty { fail("Couldn't decrypt \(refused.count): \(refused.prefix(10).joined(separator: ", "))") }
