The wire layer, recovery codes, share links, and a command-line client

Everything between the engine and an app: server discovery, the account
service, the file API, and a session that ties them together.

Recovery codes and share links move into the engine, and both agree with
the browser character for character — the vectors file now carries codes
generated by the JavaScript implementation, including one containing a Q,
because folding Q is the mistake that once corrupted a third of all codes.

`filesctl` exists so the cryptography can be exercised without an app, a
simulator, or a person tapping. `smoke` registers, signs in fresh so the
stored record has to actually open, uploads across four chunks, reads the
name back, compares bytes, and checks a password-protected link is refused
without its password. Verified against the Android engine as well: one
uploads, the other downloads, and the digests match.

Registration now sends the identity with the account rather than after it,
and a session with no identity for this product enrols one instead of
refusing — which is what an account created before Files existed needs.

MIT, matching the server. CI runs the suite on a Linux Swift image, which
is the point of keeping the crypto in a package rather than in app code.
This commit is contained in:
Paul Hitt
2026-08-21 18:17:26 -04:00
parent 7e2964a9ee
commit b88d638085
18 changed files with 1939 additions and 32 deletions
+10
View File
@@ -0,0 +1,10 @@
# The cryptography is a package, not app code, precisely so this can run without
# Xcode. A test suite that needs a Mac runner is a test suite that runs rarely.
default:
tags: [vps]
test:
image: swift:6.2-noble
script:
- swift build
- swift test
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Extant 2000 LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+8
View File
@@ -6,12 +6,20 @@ let package = Package(
platforms: [.iOS(.v16), .macOS(.v13)],
products: [
.library(name: "FilesEngine", targets: ["FilesEngine"]),
.library(name: "FilesClient", targets: ["FilesClient"]),
],
targets: [
// The engine is a package rather than app code so it can be tested with
// `swift test` on the command line. Requiring Xcode to run the crypto
// tests would mean they get run rarely.
.target(name: "FilesEngine"),
// The wire layer, kept out of the app target for the same reason: it
// can be exercised from the command line against a real server.
.target(name: "FilesClient", dependencies: ["FilesEngine"]),
// Not shipped in the app. It exercises the engine and the wire layer
// against a real server from the command line, which is the only way
// these paths get tested often enough to matter.
.executableTarget(name: "filesctl", dependencies: ["FilesEngine", "FilesClient"]),
.testTarget(
name: "FilesEngineTests",
dependencies: ["FilesEngine"],
+53 -32
View File
@@ -1,54 +1,75 @@
# flamenet-files-ios
The iOS client for [Flamenet Files](https://flamenetfiles.com).
The iOS client for [Flamenet Files](https://flamenetfiles.com) — private,
labelled file storage, encrypted on your device before it is uploaded.
**Private, deliberately.** The engine and its wire format are public at
[gitlab.com/paulhitt/flamenet-files](https://gitlab.com/paulhitt/flamenet-files);
the application is not. That split is only honest because the public half is a
full specification — anyone can verify this client speaks the same protocol
without reading its source.
MIT licensed, like [the server and web
client](https://gitlab.com/paulhitt/flamenet-files).
## What exists
## What is here
`Sources/FilesEngine` — the cryptographic engine in CryptoKit, implementing
[docs/SPEC.md](https://gitlab.com/paulhitt/flamenet-files/-/blob/main/docs/SPEC.md):
the lattice, key derivation, the key hierarchy, filename digests and chunked
content encryption.
| | |
|---|---|
| `Sources/FilesEngine` | The cryptography, in CryptoKit. Implements [docs/SPEC.md](https://gitlab.com/paulhitt/flamenet-files/-/blob/main/docs/SPEC.md) — the lattice, key derivation, the key hierarchy, recovery codes, filename digests, chunked content, share links. |
| `Sources/FilesClient` | The wire layer: server discovery, the account service, the file API, and a session that ties them together. |
| `Sources/filesctl` | A command-line client. Runs a full round trip against a real server without an app, a simulator, or a person tapping. |
| `Tests/FilesEngineTests` | Interop against vectors produced by the browser. |
It is a Swift package rather than app code so `swift test` runs it from the
command line. Requiring Xcode to run the crypto tests would mean they get run
rarely, and this is the part that must not be wrong.
The engine and the client are a Swift package rather than app code so that
`swift test` runs from the command line. Requiring Xcode to exercise the
cryptography would mean it gets exercised rarely, and this is the part that must
not be wrong.
## Interop is the test suite
`Tests/FilesEngineTests` runs against vectors produced by the JavaScript
reference implementation. They do not check that this code is self-consistent —
they check that it agrees with the implementation people actually use. Nine
tests currently pass, covering the label encoding, key derivation, unlocking an
identity written by the browser, the full key hierarchy, filename digests, and
chunked content.
The tests do not check that this code is self-consistent — they check that it
agrees with the implementation people actually use.
```bash
swift test
```
Refresh the vectors from the public repository when the spec moves.
The vectors are generated by the JavaScript engine in the public repository and
copied here verbatim. A file written in the browser must open on a phone, a code
printed on one device must work on another, and a divergence should fail here
rather than in somebody's hands.
## Trying it against a real server
```bash
swift run filesctl https://files.flamenet.io probe
```
One address is enough. The server names its own account service — `files.flamenet.io`
points at `accounts.flamenet.io`, a self-hosted box points at the service bundled
alongside it — so there are no build flags and no baked-in list of which
hostnames are "ours".
```bash
swift run filesctl http://127.0.0.1:8081 smoke myhandle 'a good passphrase'
```
`smoke` registers an account, signs in fresh, creates a folder, uploads 200 KB
across four chunks, decrypts the name back, downloads and compares byte for
byte, makes a password-protected share link, opens it, and checks that the same
link is refused without the password.
## Two things worth knowing
- **PKCS#8 versus raw.** WebCrypto exports an X25519 private key as PKCS#8;
CryptoKit uses raw 32-byte form. `Identity.rawFromPKCS8` converts. Without it
a record written in a browser cannot be opened here at all.
CryptoKit uses the raw 32-byte form. `Identity.rawFromPKCS8` converts. Without
it, a record written in a browser cannot be opened here at all.
- **PBKDF2 comes from CommonCrypto.** CryptoKit has no password-based KDF, and
the derivation must match WebCrypto byte for byte.
the derivation has to match WebCrypto byte for byte.
## Not built yet
## Status
The app itself: sign-in against `accounts.flamenet.io`, the file browser, upload
and download, the label picker. The engine is the foundation, and it is done and
verified.
The engine and the wire layer are complete and verified, including against the
Android engine: one uploads, the other downloads, and the bytes match.
⚠️ There is no release channel. No signing team is configured, and the
export-compliance key is unset — the same blockers that kept the Messenger app
from shipping. Those are worth resolving before more app code is written, not
after.
The SwiftUI app is in progress.
⚠️ **There is no release channel yet.** No signing team is configured and the
export-compliance key is unset. TestFlight needs an Apple Developer Program
membership; until there is one, this builds and runs in the simulator and
nowhere else.
+196
View File
@@ -0,0 +1,196 @@
import CryptoKit
import Foundation
import FilesEngine
/// The shared FlameNet account service.
///
/// One credential across products, with no shared key material. What this sends
/// is derived under an authentication context; the key that opens files comes
/// from an encryption context over the same passphrase. A fully compromised
/// account service can impersonate you to itself and decrypt nothing.
///
/// The passphrase never leaves the device.
public struct AccountsClient: Sendable {
public let baseURL: String
let http = HTTP()
public init(baseURL: String) { self.baseURL = baseURL }
func url(_ path: String) throws -> URL { try .endpoint(baseURL, path) }
func authHeaders(_ token: String?) -> [String: String] {
token.map { ["Authorization": "Bearer \($0)"] } ?? [:]
}
// MARK: credentials
/// Stretch parameters for a handle.
///
/// An unknown handle gets a deterministic fake, so this cannot be used to
/// discover who has an account — and this client cannot tell the
/// difference, which is the point. Do not add a "handle available?" check
/// on top of it.
public func params(handle: String) async throws -> Wire.KDFParams {
let lowered = handle.lowercased()
let escaped = lowered.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? lowered
let (data, _) = try await http.request("GET", try url("/accounts/" + escaped + "/params"))
return try http.decode(Wire.KDFParams.self, from: data)
}
struct RegisterBody: Encodable {
let handle: String
let authSecret: Data
let kdfSalt: Data
let kdfIterations: Int
let recoveryAuthSecret: Data?
let identity: Wire.NewIdentity?
}
/// Register an account and its first identity in one call.
///
/// The identity travels with the registration rather than after it, so both
/// land in a single transaction. Registering first and enrolling afterwards
/// left a window where an interrupted client stranded a handle that was
/// taken, unusable, and impossible to enrol into.
public func register(
handle: String, passphrase: String, recoveryEntropy: Data?, identity: Wire.NewIdentity?
) async throws {
let salt = Random.bytes(16)
let authSecret = try KDF.authSecret(passphrase: passphrase, salt: salt)
_ = try await http.request(
"POST", try url("/accounts"),
json: RegisterBody(
handle: handle.lowercased(),
authSecret: authSecret,
kdfSalt: salt,
kdfIterations: KDF.Parameters.v1.iterations,
recoveryAuthSecret: recoveryEntropy.map(KDF.recoveryAuthSecret(entropy:)),
identity: identity
))
}
struct SessionBody: Encodable {
let handle: String
let authSecret: Data
let product: String
}
/// Sign in. Returns the clearance token the file server verifies.
public func signIn(handle: String, passphrase: String, product: String = "files")
async throws -> Wire.Session {
let params = try await params(handle: handle)
let authSecret = try KDF.authSecret(
passphrase: passphrase, salt: params.kdfSalt,
parameters: .init(id: Int(params.kdfID), iterations: params.kdfIterations))
do {
let (data, _) = try await http.request(
"POST", try url("/sessions"),
json: SessionBody(
handle: handle.lowercased(), authSecret: authSecret, product: product))
return try http.decode(Wire.Session.self, from: data)
} catch ClientError.http(status: 401, _) {
throw ClientError.wrongPassphrase
}
}
struct RotateBody: Encodable {
let handle: String
let recoveryAuthSecret: Data
let newAuthSecret: Data
let newKdfSalt: Data
let newKdfIterations: Int
let newRecoveryAuthSecret: Data
}
/// Prove a recovery code and set a new passphrase.
///
/// The old code is retired and a fresh one issued: leaving a code in play
/// that somebody has already had cause to use is the wrong default.
public func rotate(
handle: String, entropy: Data, newPassphrase: String, nextEntropy: Data
) async throws {
let salt = Random.bytes(16)
let newAuthSecret = try KDF.authSecret(passphrase: newPassphrase, salt: salt)
_ = try await http.request(
"POST", try url("/accounts/rotate"),
json: RotateBody(
handle: handle.lowercased(),
recoveryAuthSecret: KDF.recoveryAuthSecret(entropy: entropy),
newAuthSecret: newAuthSecret,
newKdfSalt: salt,
newKdfIterations: KDF.Parameters.v1.iterations,
newRecoveryAuthSecret: KDF.recoveryAuthSecret(entropy: nextEntropy)
))
}
struct ChangePassphraseBody: Encodable {
let handle: String
let currentAuthSecret: Data
let newAuthSecret: Data
let newKdfSalt: Data
let newKdfIterations: Int
}
public func changePassphrase(
handle: String, currentPassphrase: String, newPassphrase: String
) async throws {
let params = try await params(handle: handle)
let current = try KDF.authSecret(
passphrase: currentPassphrase, salt: params.kdfSalt,
parameters: .init(id: Int(params.kdfID), iterations: params.kdfIterations))
let salt = Random.bytes(16)
let next = try KDF.authSecret(passphrase: newPassphrase, salt: salt)
do {
_ = try await http.request(
"POST", try url("/accounts/passphrase"),
json: ChangePassphraseBody(
handle: handle.lowercased(), currentAuthSecret: current,
newAuthSecret: next, newKdfSalt: salt,
newKdfIterations: KDF.Parameters.v1.iterations))
} catch ClientError.http(status: 401, _) {
throw ClientError.wrongPassphrase
}
}
// MARK: identities
//
// These live here rather than on the file server. An identity belongs to
// the account, not to one product's file tree — and holding them together
// is what lets registration be atomic.
public func identity(token: String) async throws -> Wire.Identity? {
let (data, response) = try await http.request(
"GET", try url("/identity"), headers: authHeaders(token))
// 204: the account exists but has no identity for this product yet,
// which is how the app decides between "unlock" and "create".
if response.statusCode == 204 { return nil }
return try http.decode(Wire.Identity.self, from: data)
}
struct EnrollBody: Encodable {
let publicKey: Data
let protectedRecord: String
let recoveryRecord: String?
}
public func enroll(
token: String, publicKey: Data, protectedRecord: String, recoveryRecord: String?
) async throws {
_ = try await http.request(
"POST", try url("/identity"), headers: authHeaders(token),
json: EnrollBody(publicKey: publicKey, protectedRecord: protectedRecord,
recoveryRecord: recoveryRecord))
}
struct RekeyBody: Encodable {
let protectedRecord: String
let recoveryRecord: String?
}
public func rekey(token: String, protectedRecord: String, recoveryRecord: String?)
async throws {
_ = try await http.request(
"POST", try url("/identity/rekey"), headers: authHeaders(token),
json: RekeyBody(protectedRecord: protectedRecord, recoveryRecord: recoveryRecord))
}
}
+157
View File
@@ -0,0 +1,157 @@
import Foundation
import FilesEngine
/// The file server.
///
/// Two headers carry the session label on every request. Omitting them makes
/// the server fall back to the clearance *minimum*, never the maximum, so a bug
/// here under-privileges rather than over-privileges.
public actor FilesAPI {
public let baseURL: String
public private(set) var token: String
private var label: Label?
private let http = HTTP()
public init(baseURL: String, token: String) {
self.baseURL = baseURL
self.token = token
}
public func setLabel(_ label: Label?) { self.label = label }
/// What a server says about itself. Unauthenticated, so it can be asked
/// before there is any credential to ask with.
public static func config(baseURL: String) async throws -> Wire.ServerConfig {
let http = HTTP()
let (data, _) = try await http.request("GET", try .endpoint(baseURL, "/api/config"))
return try http.decode(Wire.ServerConfig.self, from: data)
}
private var headers: [String: String] {
var headers = ["Authorization": "Bearer \(token)"]
if let label {
headers["X-Enclave-Classification"] = String(label.classification)
headers["X-Enclave-Compartments"] =
label.compartments.sorted().map(String.init).joined(separator: ",")
}
return headers
}
func get<T: Decodable>(_ type: T.Type, _ path: String) async throws -> T? {
let (data, response) = try await http.request(
"GET", try .endpoint(baseURL, path), headers: headers)
if response.statusCode == 204 { return nil }
return try http.decode(type, from: data)
}
@discardableResult
func post<T: Decodable>(_ type: T.Type, _ path: String, _ body: some Encodable & Sendable)
async throws -> T? {
let (data, response) = try await http.request(
"POST", try .endpoint(baseURL, path), headers: headers, json: body)
if response.statusCode == 204 || data.isEmpty { return nil }
return try? http.decode(type, from: data)
}
func delete(_ path: String) async throws {
_ = try await http.request("DELETE", try .endpoint(baseURL, path), headers: headers)
}
// MARK: nodes
public func roots() async throws -> [Wire.Node] {
try await get([Wire.Node].self, "/api/nodes/roots") ?? []
}
public func children(of folderID: UUID) async throws -> [Wire.Node] {
try await get([Wire.Node].self, "/api/nodes/\(folderID.uuidString)/children") ?? []
}
struct CreateNodeBody: Encodable {
let parentID: UUID?
let nameDigest: Data
let nameCiphertext: Data
let isFolder: Bool
let wrappedKey: Data
let contentKey: Data?
let blobID: UUID?
let sizeBytes: Int64
}
func create(_ body: CreateNodeBody) async throws -> Wire.Node? {
try await post(Wire.Node.self, "/api/nodes", body)
}
// MARK: keys
public func labelGrants() async throws -> [Wire.LabelGrant] {
try await get([Wire.LabelGrant].self, "/api/keys/labels") ?? []
}
struct GrantBody: Encodable {
let classification: Int16
let compartments: [Int]
let wrappedKey: Data
}
func storeGrant(label: Label, wrappedKey: Data) async throws {
_ = try await post(
Wire.LabelGrant.self, "/api/keys/labels",
GrantBody(classification: label.classification,
compartments: label.compartments.sorted(), wrappedKey: wrappedKey))
}
func nodeKey(_ nodeID: UUID) async throws -> Wire.NodeKey {
guard let key = try await get(Wire.NodeKey.self, "/api/keys/nodes/\(nodeID.uuidString)")
else { throw ClientError.http(status: 404, detail: "") }
return key
}
// MARK: blobs
func putBlob(_ ciphertext: Data) async throws -> UUID {
let (data, _) = try await http.request(
"POST", try .endpoint(baseURL, "/api/blobs"), headers: headers, body: ciphertext)
return try http.decode(Wire.BlobCreated.self, from: data).id
}
func getBlob(_ blobID: UUID) async throws -> Data {
let (data, _) = try await http.request(
"GET", try .endpoint(baseURL, "/api/blobs/\(blobID.uuidString)"), headers: headers)
return data
}
// MARK: vocabulary
public func vocabulary() async throws -> Wire.Vocabulary {
try await get(Wire.Vocabulary.self, "/api/vocabulary")
?? Wire.Vocabulary(levels: [], compartments: [], canEdit: false)
}
// MARK: shares
struct CreateShareBody: Encodable {
let nodeID: UUID
let wrappedContentKey: Data
let wrappedName: Data
let passwordSalt: Data?
let passwordIterations: Int?
let expiresInHours: Int
}
func createShare(_ body: CreateShareBody) async throws -> Wire.Share? {
try await post(Wire.Share.self, "/api/shares", body)
}
public func share(_ shareID: UUID) async throws -> Wire.Share? {
try await get(Wire.Share.self, "/api/shares/\(shareID.uuidString)")
}
public func shares(for nodeID: UUID) async throws -> [Wire.Share] {
try await get([Wire.Share].self, "/api/shares/for/\(nodeID.uuidString)") ?? []
}
public func revokeShare(_ shareID: UUID) async throws {
try await delete("/api/shares/\(shareID.uuidString)")
}
}
+392
View File
@@ -0,0 +1,392 @@
import CryptoKit
import Foundation
import FilesEngine
/// An unlocked working session.
///
/// Holds the identity private key and any unwrapped label keys in memory only.
/// Nothing is written to disk — not the passphrase, not the keys, not a cached
/// file listing. Closing the app forgets everything, which is the intended
/// behaviour and not an omission.
public actor FilesSession {
public struct Entry: Sendable, Identifiable, Hashable {
public let node: Wire.Node
/// `nil` when this session holds no key for the row's label: visible to
/// the database, unreadable here. Showing it as an unnamed row is more
/// honest than hiding it.
public let name: String?
public var id: UUID { node.id }
public var label: Label { node.label }
public var isFolder: Bool { node.isFolder }
}
public let api: FilesAPI
public let accounts: AccountsClient
public let token: String
public let clearance: Clearance
public private(set) var label: Label
/// Set only when a code was just issued, and never persisted. This is the
/// one moment it exists anywhere.
public private(set) var recoveryCode: String?
private let privateKey: Curve25519.KeyAgreement.PrivateKey
private let publicKey: Curve25519.KeyAgreement.PublicKey
private var labelKeys: [Label: Data] = [:]
init(api: FilesAPI, accounts: AccountsClient, token: String, clearance: Clearance,
privateKey: Curve25519.KeyAgreement.PrivateKey, recoveryCode: String? = nil) {
self.api = api
self.accounts = accounts
self.token = token
self.clearance = clearance
self.label = clearance.minimum
self.privateKey = privateKey
self.publicKey = privateKey.publicKey
self.recoveryCode = recoveryCode
}
public func clearRecoveryCode() { recoveryCode = nil }
// MARK: opening
/// Unlock an existing identity.
///
/// Identity records live on the account service, so this asks there rather
/// than the file server — the file server no longer holds anything about
/// who you are.
public static func open(
api: FilesAPI, accounts: AccountsClient, token: String,
passphrase: String, clearance: Clearance,
recoveryEntropy: Data? = nil
) async throws -> FilesSession {
await api.setLabel(clearance.minimum)
guard let record = try await accounts.identity(token: token),
let protectedRecord = record.protectedRecord
else {
// No identity for this product yet. That is an ordinary state, not
// an error: an account created before Files existed has one, and so
// does an account whose registration predates identities living
// here. Enrol rather than refusing.
//
// Safe because the server allows enrolment exactly once. If an
// identity did exist and simply would not unlock, this path is not
// reached — and if it somehow were, the server's 409 stops a second
// keypair from orphaning every label key wrapped to the first.
return try await enrol(
api: api, accounts: accounts, token: token,
passphrase: passphrase, clearance: clearance, recoveryEntropy: recoveryEntropy)
}
let decoded = try Identity.Record.parse(protectedRecord)
let privateKey: Curve25519.KeyAgreement.PrivateKey
do {
privateKey = try Identity.unlock(decoded, passphrase: passphrase)
} catch {
// The only realistic cause is a wrong passphrase: the record is
// authenticated, so tampering and a bad key look identical here.
throw ClientError.wrongPassphrase
}
return FilesSession(api: api, accounts: accounts, token: token,
clearance: clearance, privateKey: privateKey)
}
/// Create and enrol a keypair for an account that has none.
///
/// Returns the recovery code, which is the only moment it exists anywhere:
/// it is not stored, not derivable from the passphrase, and cannot be
/// reissued — only replaced by rekeying with a secret you already hold.
static func enrol(
api: FilesAPI, accounts: AccountsClient, token: String,
passphrase: String, clearance: Clearance, recoveryEntropy: Data?
) async throws -> FilesSession {
let entropy = recoveryEntropy ?? Recovery.generate().entropy
let key = Identity.generate()
try await accounts.enroll(
token: token,
publicKey: Identity.exportPublicKey(key.publicKey),
protectedRecord: try Identity.protect(key, passphrase: passphrase).json,
recoveryRecord: try Identity.protectWithRecovery(key, entropy: entropy).json)
return FilesSession(api: api, accounts: accounts, token: token, clearance: clearance,
privateKey: key, recoveryCode: try Recovery.encode(entropy))
}
/// Adopt a keypair this device just created during registration.
///
/// Registration writes the identity in the same transaction as the account,
/// so by the time there is a token the record already exists. Fetching and
/// unwrapping it again would be 650,000 wasted iterations.
public static func enrolled(
api: FilesAPI, accounts: AccountsClient, token: String,
privateKey: Curve25519.KeyAgreement.PrivateKey, clearance: Clearance,
recoveryCode: String?
) async -> FilesSession {
await api.setLabel(clearance.minimum)
return FilesSession(api: api, accounts: accounts, token: token, clearance: clearance,
privateKey: privateKey, recoveryCode: recoveryCode)
}
/// Unlock with a recovery code and set a new passphrase.
///
/// The keypair is unchanged, so every label key already wrapped to it stays
/// valid and nothing needs re-encrypting. A fresh code is issued and the old
/// one stops working.
public static func recover(
api: FilesAPI, accounts: AccountsClient, token: String,
code: String, newPassphrase: String, clearance: Clearance, nextEntropy: Data
) async throws -> FilesSession {
await api.setLabel(clearance.minimum)
guard let record = try await accounts.identity(token: token),
let recoveryRecord = record.recoveryRecord
else { throw ClientError.badServer("This account has no recovery code on file.") }
let entropy = try Recovery.decode(code)
let decoded = try Identity.Record.parse(recoveryRecord)
let privateKey = try Identity.unlockWithRecovery(decoded, entropy: entropy)
let next = try Identity.protect(privateKey, passphrase: newPassphrase)
let nextRecovery = try Identity.protectWithRecovery(privateKey, entropy: nextEntropy)
try await accounts.rekey(
token: token,
protectedRecord: next.json,
recoveryRecord: nextRecovery.json)
return FilesSession(api: api, accounts: accounts, token: token, clearance: clearance,
privateKey: privateKey,
recoveryCode: try Recovery.encode(nextEntropy))
}
// MARK: label keys
/// Load and unwrap every label key granted to this principal.
@discardableResult
public func loadLabelKeys() async throws -> [Label] {
for grant in try await api.labelGrants() {
do {
labelKeys[grant.label] = try Keys.acceptLabelKey(
grant.wrappedKey, label: grant.label, privateKey: privateKey)
} catch {
// A grant that will not unwrap is not fatal: it may have been
// wrapped to a superseded identity key. Skip it rather than
// failing the whole session.
continue
}
}
return Array(labelKeys.keys)
}
/// Ensure a label key exists for `label`, creating and self-granting one if
/// not.
///
/// The server's insert policy allows a self-grant at exactly the session
/// label and nothing else, so this cannot widen anyone's clearance — it only
/// materialises a key for a label the caller could already assert.
@discardableResult
func ensureLabelKey(_ wanted: Label) async throws -> Data {
guard clearance.permits(wanted) else { throw ClientError.notCleared }
if let existing = labelKeys[wanted] { return existing }
let key = Random.bytes(32)
let previous = label
await api.setLabel(wanted)
defer { Task { await api.setLabel(previous) } }
try await api.storeGrant(
label: wanted,
wrappedKey: try Keys.grantLabelKey(key, label: wanted, to: publicKey))
labelKeys[wanted] = key
return key
}
public func use(_ wanted: Label) async throws {
guard clearance.permits(wanted) else { throw ClientError.notCleared }
_ = try await ensureLabelKey(wanted)
label = wanted
await api.setLabel(wanted)
}
var currentLabelKey: Data {
get throws {
guard let key = labelKeys[label] else { throw ClientError.notCleared }
return key
}
}
/// The key that names a folder's children. Root entries use the label key.
func folderKey(_ folderID: UUID?) async throws -> Data {
guard let folderID else { return try currentLabelKey }
let record = try await api.nodeKey(folderID)
return try Keys.unwrapNodeKey(record.wrappedKey, labelKey: try currentLabelKey, label: label)
}
// MARK: browsing
/// List a folder, decrypting each visible child's name locally.
public func list(_ folderID: UUID?) async throws -> [Entry] {
let rows = folderID.map { id in { try await self.api.children(of: id) } }
?? { try await self.api.roots() }
let nodes = try await rows()
// Inside a folder every child is named under that folder's node key,
// which the caller necessarily holds to have got here at all.
//
// A root listing is different: it spans labels, and each entry was named
// under the key of its *own* label. Using the session's label key for
// all of them leaves a cleared user staring at rows they can see but
// cannot read, which is worse than not showing them at all.
let folderNodeKey = folderID == nil ? nil : try await folderKey(folderID)
return nodes.map { node in
let key = folderNodeKey ?? labelKeys[node.label]
var name: String?
if let key {
name = try? Names.decrypt(
folderKey: key, blob: node.nameCiphertext,
digest: node.nameDigest, label: node.label)
}
return Entry(node: node, name: name)
}
}
// MARK: writing
@discardableResult
public func createFolder(_ name: String, in parentID: UUID? = nil) async throws -> Wire.Node? {
let folderKey = try await folderKey(parentID)
let nodeKey = Random.bytes(32)
let named = try Names.encrypt(folderKey: folderKey, name: name, label: label)
return try await api.create(.init(
parentID: parentID,
nameDigest: named.digest, nameCiphertext: named.ciphertext,
isFolder: true,
wrappedKey: try Keys.wrapNodeKey(nodeKey, labelKey: try currentLabelKey, label: label),
contentKey: nil, blobID: nil, sizeBytes: 0))
}
/// Encrypt then upload.
///
/// The content key is wrapped to the *node* key, which is itself wrapped to
/// the label key — never to the parent folder's key. That is what keeps the
/// key hierarchy aligned with the lattice rather than with the tree.
@discardableResult
public func upload(_ bytes: Data, named name: String, in parentID: UUID? = nil)
async throws -> Wire.Node? {
let folderKey = try await folderKey(parentID)
let nodeKey = Random.bytes(32)
let contentKey = Random.bytes(32)
let ciphertext = try Content.encrypt(bytes, contentKey: contentKey, label: label)
let blobID = try await api.putBlob(ciphertext)
let named = try Names.encrypt(folderKey: folderKey, name: name, label: label)
return try await api.create(.init(
parentID: parentID,
nameDigest: named.digest, nameCiphertext: named.ciphertext,
isFolder: false,
wrappedKey: try Keys.wrapNodeKey(nodeKey, labelKey: try currentLabelKey, label: label),
contentKey: try Keys.wrapContentKey(contentKey, nodeKey: nodeKey, label: label),
blobID: blobID, sizeBytes: Int64(bytes.count)))
}
public func download(_ node: Wire.Node) async throws -> Data {
guard let blobID = node.blobID, let wrappedContentKey = node.contentKey else {
throw ClientError.badServer("That entry has no contents.")
}
let record = try await api.nodeKey(node.id)
let nodeKey = try Keys.unwrapNodeKey(
record.wrappedKey, labelKey: try currentLabelKey, label: node.label)
let contentKey = try Keys.unwrapContentKey(
wrappedContentKey, nodeKey: nodeKey, label: node.label)
return try Content.decrypt(try await api.getBlob(blobID),
contentKey: contentKey, label: node.label)
}
// MARK: shares
public struct CreatedShare: Sendable {
public let id: UUID
public let secret: String
public let expiresAt: Date?
/// The link. The secret goes in the fragment, which browsers never
/// transmit — so the server storing this share cannot open it.
public func url(site: String) -> String {
"\(site)/s/\(id.uuidString)#\(secret)"
}
}
public func createShare(
for entry: Entry, expiresInHours: Int = 168, password: String? = nil
) async throws -> CreatedShare {
guard let wrappedContentKey = entry.node.contentKey, let name = entry.name else {
throw ClientError.badServer("Only files you can read can be shared.")
}
let record = try await api.nodeKey(entry.node.id)
let nodeKey = try Keys.unwrapNodeKey(
record.wrappedKey, labelKey: try currentLabelKey, label: entry.label)
let contentKey = try Keys.unwrapContentKey(
wrappedContentKey, nodeKey: nodeKey, label: entry.label)
let secret = Shares.createSecret()
let sealed = try Shares.seal(
labelKey: try currentLabelKey, label: entry.label, secret: secret,
contentKey: contentKey, name: name, password: password)
guard let created = try await api.createShare(.init(
nodeID: entry.node.id,
wrappedContentKey: sealed.wrappedContentKey,
wrappedName: sealed.wrappedName,
passwordSalt: sealed.passwordSalt,
passwordIterations: sealed.passwordIterations,
expiresInHours: expiresInHours))
else { throw ClientError.badServer("The server did not return the new link.") }
return CreatedShare(id: created.id, secret: Shares.encodeSecret(secret),
expiresAt: created.expiresAt)
}
/// Open a shared file.
///
/// Fails for anyone not cleared for its label, twice over: the server will
/// not serve the wrapped material to an undominated session, and without the
/// label key the share key cannot be derived even if it did.
public func openShare(_ shareID: UUID, secret: String, password: String? = nil)
async throws -> (name: String, label: Label, bytes: Data) {
guard let row = try await api.share(shareID),
let classification = row.classification,
let wrappedContentKey = row.wrappedContentKey,
let wrappedName = row.wrappedName,
let blobID = row.blobID
else { throw ClientError.http(status: 404, detail: "") }
let shareLabel = Label(classification: classification,
compartments: Set(row.compartments ?? []))
guard let labelKey = labelKeys[shareLabel] else { throw ClientError.notCleared }
let opened = try Shares.open(
labelKey: labelKey, label: shareLabel,
secret: try Shares.decodeSecret(secret),
wrappedContentKey: wrappedContentKey, wrappedName: wrappedName,
password: password, passwordSalt: row.passwordSalt,
passwordIterations: row.passwordIterations ?? Shares.passwordIterations)
let bytes = try Content.decrypt(
try await api.getBlob(blobID), contentKey: opened.contentKey, label: shareLabel)
return (opened.name, shareLabel, bytes)
}
}
/// A clearance range. Mirrors the token's four claims.
public struct Clearance: Sendable, Hashable {
public let maximum: Label
public let minimum: Label
public init(maximum: Label, minimum: Label) {
self.maximum = maximum
self.minimum = minimum
}
/// Both bounds, always: a label must sit inside the range, not merely below
/// the top of it.
public func permits(_ label: Label) -> Bool {
maximum.dominates(label) && label.dominates(minimum)
}
}
+104
View File
@@ -0,0 +1,104 @@
import Foundation
/// A very small HTTP layer.
///
/// No third-party networking. This app moves ciphertext and bearer tokens, and
/// every dependency in that path is one more place a supply-chain compromise
/// reads plaintext — the browser client made the same call for the same reason.
struct HTTP: Sendable {
let session: URLSession
init() {
let configuration = URLSessionConfiguration.ephemeral
// Nothing here should be written to a shared cache: responses carry
// wrapped keys and, for the identity endpoint, the protected private
// key record.
configuration.urlCache = nil
configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
configuration.httpCookieStorage = nil
configuration.timeoutIntervalForRequest = 30
self.session = URLSession(configuration: configuration)
}
/// JSON in, JSON out. Dates are ISO-8601, matching Vapor's default.
static let decoder: JSONDecoder = {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
// Vapor encodes `Data` as base64, and `Data`'s synthesised Codable
// conformance expects an array of bytes. Say so explicitly rather than
// discovering it as a decode failure at sign-in.
decoder.dataDecodingStrategy = .base64
return decoder
}()
static let encoder: JSONEncoder = {
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
encoder.dataEncodingStrategy = .base64
return encoder
}()
func request(
_ method: String, _ url: URL, headers: [String: String] = [:],
json: (some Encodable & Sendable)? = Optional<String>.none, body: Data? = nil
) async throws -> (Data, HTTPURLResponse) {
var request = URLRequest(url: url)
request.httpMethod = method
for (key, value) in headers { request.setValue(value, forHTTPHeaderField: key) }
if let json {
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try Self.encoder.encode(json)
} else if let body {
request.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
request.httpBody = body
}
let (data, response) = try await session.data(for: request)
guard let http = response as? HTTPURLResponse else {
throw ClientError.badServer("That address did not answer as a web server.")
}
guard (200..<300).contains(http.statusCode) else {
throw ClientError.http(
status: http.statusCode,
detail: Self.reason(from: data))
}
return (data, http)
}
/// Vapor puts a human-readable message in `reason`. Fall back to the raw
/// body only if it is short — a stack trace in a toast helps nobody.
static func reason(from data: Data) -> String {
if let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let reason = object["reason"] as? String {
return reason
}
let text = String(data: data, encoding: .utf8) ?? ""
return text.count <= 200 ? text : ""
}
func decode<T: Decodable>(_ type: T.Type, from data: Data) throws -> T {
do { return try Self.decoder.decode(type, from: data) }
catch {
throw ClientError.badServer(
"The server sent something this version cannot read. It may be newer than the app.")
}
}
}
extension URL {
/// Joins a path onto a base that may or may not have a trailing slash, and
/// refuses anything that is not http(s) — a `file:` base would otherwise
/// silently "work" and read the device's own disk.
static func endpoint(_ base: String, _ path: String) throws -> URL {
var trimmed = base.trimmingCharacters(in: .whitespaces)
if trimmed.isEmpty { throw ClientError.badServer("Enter a server address.") }
if !trimmed.contains("://") { trimmed = "https://" + trimmed }
while trimmed.hasSuffix("/") { trimmed.removeLast() }
guard let url = URL(string: trimmed + path),
let scheme = url.scheme?.lowercased(),
scheme == "https" || scheme == "http"
else { throw ClientError.badServer("That doesn't look like a server address.") }
return url
}
}
+57
View File
@@ -0,0 +1,57 @@
import Foundation
import FilesEngine
/// The clearance claims, read out of the token the account service minted.
///
/// Deliberately *not* verified here. A client verifying its own token proves
/// nothing: it would be checking a signature against a key it was handed by the
/// same party. The file server verifies, and it is the only verification that
/// matters. This decode exists so the interface can grey out a level the server
/// would refuse anyway — a courtesy, never a control.
public struct TokenClaims: Sendable {
public let pseudonym: UUID?
public let tenant: String
public let clearance: Clearance
public let expiresAt: Date?
private struct Payload: Decodable {
let sub: String?
let exp: Double?
let ten: String?
let mxc: Int16?
let mxk: Int64?
let mnc: Int16?
let mnk: Int64?
}
public init(token: String) throws {
let parts = token.split(separator: ".", omittingEmptySubsequences: false)
guard parts.count == 3 else {
throw ClientError.badServer("The server issued a token this app cannot read.")
}
var body = String(parts[1])
.replacingOccurrences(of: "-", with: "+")
.replacingOccurrences(of: "_", with: "/")
body += String(repeating: "=", count: (4 - body.count % 4) % 4)
guard let data = Data(base64Encoded: body),
let payload = try? JSONDecoder().decode(Payload.self, from: data)
else { throw ClientError.badServer("The server issued a token this app cannot read.") }
self.pseudonym = payload.sub.flatMap(UUID.init(uuidString:))
self.tenant = payload.ten ?? "default"
self.expiresAt = payload.exp.map { Date(timeIntervalSince1970: $0) }
self.clearance = Clearance(
maximum: Label(classification: payload.mxc ?? 0,
compartments: Self.bits(payload.mxk ?? 0)),
minimum: Label(classification: payload.mnc ?? 0,
compartments: Self.bits(payload.mnk ?? 0)))
}
/// Postgres has no unsigned 64-bit integer, so the mask travels as a signed
/// one and bit 63 arrives negative. Reinterpreting the pattern rather than
/// converting the value is what keeps the top compartment usable.
static func bits(_ pattern: Int64) -> Set<Int> {
let mask = UInt64(bitPattern: pattern)
return Set((0..<64).filter { mask & (1 << UInt64($0)) != 0 })
}
}
+161
View File
@@ -0,0 +1,161 @@
import Foundation
import FilesEngine
/// The wire types, spelled out rather than decoded loosely.
///
/// Every field here crosses a trust boundary, so each one is named and typed:
/// a silently-missing key that becomes `nil` and then becomes a default is how
/// a client ends up encrypting under the wrong label.
public enum Wire {
/// What a server says about itself, before anyone has signed in.
///
/// This is how the app learns which account service to authenticate
/// against. Point it at `files.flamenet.io` and it is told
/// `accounts.flamenet.io`; point it at a self-hosted box and it is told
/// that box's own bundled service. No build flags, and no hardcoded list of
/// which hostnames are "ours" — which would be wrong the moment somebody
/// forks this.
public struct ServerConfig: Codable, Sendable {
public let accountsURL: String
public let tenant: String
public let siteURL: String
public let sourceURL: String
public let protocolVersion: Int
}
public struct KDFParams: Codable, Sendable {
public let kdfSalt: Data
public let kdfID: Int16
public let kdfIterations: Int
}
public struct Session: Codable, Sendable {
public let token: String
public let pseudonym: UUID
public let expiresAt: Date
}
public struct Identity: Codable, Sendable {
public let principalID: UUID
public let publicKey: Data
public let protectedRecord: String?
public let recoveryRecord: String?
}
public struct NewIdentity: Codable, Sendable {
public let product: String
public let publicKey: Data
public let protectedRecord: String
public let recoveryRecord: String?
public init(product: String = "files", publicKey: Data,
protectedRecord: String, recoveryRecord: String?) {
self.product = product
self.publicKey = publicKey
self.protectedRecord = protectedRecord
self.recoveryRecord = recoveryRecord
}
}
/// A node as the server sees it: a label, two opaque name blobs, and
/// nothing it can read.
public struct Node: Codable, Sendable, Identifiable, Hashable {
public let id: UUID
public let parentID: UUID?
public let classification: Int16
public let compartments: [Int]
public let nameDigest: Data
public let nameCiphertext: Data
public let isFolder: Bool
public let blobID: UUID?
public let contentKey: Data?
public let sizeBytes: Int64?
public var label: Label {
Label(classification: classification, compartments: Set(compartments))
}
}
public struct LabelGrant: Codable, Sendable {
public let classification: Int16
public let compartments: [Int]
public let wrappedKey: Data
public var label: Label {
Label(classification: classification, compartments: Set(compartments))
}
}
public struct NodeKey: Codable, Sendable {
public let wrappedKey: Data
}
public struct BlobCreated: Codable, Sendable {
public let id: UUID
}
/// What this deployment calls its levels and areas. Purely presentational:
/// nothing in the lattice depends on the words.
public struct Vocabulary: Codable, Sendable {
public struct Level: Codable, Sendable, Hashable {
public let ordinal: Int16
public let name: String
}
public struct Compartment: Codable, Sendable, Hashable {
public let bit: Int
public let name: String
}
public let levels: [Level]
public let compartments: [Compartment]
public let canEdit: Bool?
public func name(for label: Label) -> String {
let level = levels.first { $0.ordinal == label.classification }?.name
?? "Level \(label.classification)"
let areas = label.compartments.sorted().compactMap { bit in
compartments.first { $0.bit == bit }?.name ?? "Area \(bit)"
}
return areas.isEmpty ? level : "\(level) // \(areas.joined(separator: ", "))"
}
}
public struct Share: Codable, Sendable {
public let id: UUID
public let expiresAt: Date?
public let classification: Int16?
public let compartments: [Int]?
public let wrappedContentKey: Data?
public let wrappedName: Data?
public let passwordSalt: Data?
public let passwordIterations: Int?
public let needsPassword: Bool?
public let blobID: UUID?
}
}
/// What went wrong, in terms the interface can actually say out loud.
public enum ClientError: LocalizedError, Equatable {
case http(status: Int, detail: String)
case notCleared
case badServer(String)
case wrongPassphrase
public var errorDescription: String? {
switch self {
case .wrongPassphrase:
return "That handle and passphrase don't match."
case .notCleared:
return "You aren't cleared for this."
case .badServer(let why):
return why
case .http(let status, let detail):
// 404 is deliberate on this server: a row you are not cleared to
// see is missing, not forbidden. Saying "forbidden" would leak its
// existence, so the app does not say it either.
if status == 404 { return "Not found." }
if status == 401 { return "Your session has expired. Sign in again." }
if status == 403 { return "That's outside your clearance." }
return detail.isEmpty ? "The server returned \(status)." : detail
}
}
}
+8
View File
@@ -18,6 +18,14 @@ enum Bytes {
}
}
/// Random bytes, from the system CSPRNG.
///
/// Public because callers outside the engine need salts and link secrets, and
/// the alternative is each of them reaching for something weaker.
public enum Random {
public static func bytes(_ count: Int) -> Data { Bytes.random(count) }
}
public enum EngineError: Error, Equatable {
case unsupportedVersion(UInt8)
case malformed(String)
+92
View File
@@ -37,6 +37,98 @@ public enum Identity {
public let salt: String
public let nonce: String
public let privateKey: String
/// The stored form. Servers treat this as opaque text and have no
/// business parsing it, so the client is the only place that knows the
/// shape — including on the way out.
public var json: String {
String(decoding: (try? JSONEncoder().encode(self)) ?? Data(), as: UTF8.self)
}
public static func parse(_ text: String) throws -> Record {
guard let data = text.data(using: .utf8),
let record = try? JSONDecoder().decode(Record.self, from: data)
else { throw EngineError.malformed("identity record is not valid JSON") }
return record
}
public init(v: Int, kdf: Int, iterations: Int, context: String,
salt: String, nonce: String, privateKey: String) {
self.v = v
self.kdf = kdf
self.iterations = iterations
self.context = context
self.salt = salt
self.nonce = nonce
self.privateKey = privateKey
}
}
public static func generate() -> Curve25519.KeyAgreement.PrivateKey {
Curve25519.KeyAgreement.PrivateKey()
}
/// Raw 32 bytes, which is what every FlameNet server stores and what a
/// label key is wrapped to.
public static func exportPublicKey(_ key: Curve25519.KeyAgreement.PublicKey) -> Data {
key.rawRepresentation
}
/// Encrypt a private key for storage.
///
/// The context string is the authenticated data as well as the KDF domain
/// separator, so a record produced for one product cannot be unlocked as
/// another's even with the right passphrase.
///
/// The iteration count is written into the record rather than looked up
/// from a registry. Raising the default must not strand accounts whose
/// records were made under the old one, so the record has to say what
/// actually produced its key.
public static func protect(
_ privateKey: Curve25519.KeyAgreement.PrivateKey,
passphrase: String,
parameters: KDF.Parameters = .v1,
context: String = KDF.Context.filesIdentity
) throws -> Record {
let salt = Bytes.random(16)
let kek = try KDF.derive(
passphrase: passphrase, salt: salt, context: context, parameters: parameters)
let nonce = Bytes.random(12)
// PKCS#8, not raw: the browser writes this format and both must read
// each other's records.
let sealed = try AES.GCM.seal(
try pkcs8FromRaw(privateKey.rawRepresentation),
using: SymmetricKey(data: kek),
nonce: try AES.GCM.Nonce(data: nonce),
authenticating: Data(context.utf8)
)
return Record(
v: 1, kdf: parameters.id, iterations: parameters.iterations, context: context,
salt: salt.base64EncodedString(),
nonce: nonce.base64EncodedString(),
// Ciphertext and tag concatenated: WebCrypto's AES-GCM output is
// the two joined, while CryptoKit keeps them apart.
privateKey: (sealed.ciphertext + sealed.tag).base64EncodedString()
)
}
/// Wrap the same private key under a recovery code.
///
/// A different context, so neither secret reveals the other and changing
/// the passphrase does not invalidate the code. Rotating an identity fully
/// means replacing both records.
public static func protectWithRecovery(
_ privateKey: Curve25519.KeyAgreement.PrivateKey,
entropy: Data,
parameters: KDF.Parameters = .v1
) throws -> Record {
try protect(privateKey, passphrase: Recovery.kdfSecret(entropy),
parameters: parameters, context: KDF.Context.filesRecovery)
}
public static func unlockWithRecovery(_ record: Record, entropy: Data) throws
-> Curve25519.KeyAgreement.PrivateKey {
try unlock(record, passphrase: Recovery.kdfSecret(entropy))
}
/// Unlock a record produced by this engine or by the browser.
+19
View File
@@ -25,6 +25,10 @@ public enum KDF {
public enum Context {
public static let filesIdentity = "flamenet/files/identity/v1"
public static let filesAuth = "flamenet/files/auth/v1"
public static let filesRecovery = "flamenet/files/recovery/v1"
/// The account-side half of a recovery code. HKDF only: the code already
/// carries 128 bits of its own entropy, so stretching it buys nothing.
public static let filesAuthRecovery = "flamenet/files/auth-recovery/v1"
public static let messengerIdentity = "flamenet/messenger/identity/v1"
}
@@ -69,4 +73,19 @@ public enum KDF {
public static func authSecret(passphrase: String, salt: Data, parameters: Parameters = .v1) throws -> Data {
try derive(passphrase: passphrase, salt: salt, context: Context.filesAuth, parameters: parameters)
}
/// The account-side proof of a recovery code.
///
/// No PBKDF2 here, and that is not an oversight: the code is 128 random
/// bits, so there is nothing to stretch. HKDF over it is enough, and the
/// server keeps only a salted hash of the result.
public static func recoveryAuthSecret(entropy: Data) -> Data {
let key = HKDF<SHA256>.deriveKey(
inputKeyMaterial: SymmetricKey(data: Data(Recovery.kdfSecret(entropy).utf8)),
salt: Data(),
info: Data(Context.filesAuthRecovery.utf8),
outputByteCount: 32
)
return key.withUnsafeBytes { Data($0) }
}
}
+145
View File
@@ -0,0 +1,145 @@
import CryptoKit
import Foundation
/// Recovery codes. Specification §7.
///
/// Losing a passphrase otherwise loses the data outright: the server holds no
/// key that opens anything. A recovery code is a second, high-entropy secret
/// that wraps the *same* identity private key under a different context, so
/// either secret unlocks the account and neither reveals the other.
///
/// Crockford base32 rather than a word list. A twelve-word phrase transcribes
/// more kindly, but vendoring BIP-39 means carrying 2,048 words that have to be
/// byte-exact — one wrong entry silently produces codes that cannot be decoded.
/// Crockford needs no vendored data and is unambiguous by construction: `I`,
/// `L`, `O` and `U` are absent from the alphabet, and the glyphs people
/// actually confuse are folded on input.
///
/// 128 bits entropy || 12 bits checksum = 140 bits = 28 characters
/// grouped as XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX
///
/// The checksum catches a typo in microseconds, before the deliberately slow
/// key derivation runs.
public enum Recovery {
static let alphabet = Array("0123456789ABCDEFGHJKMNPQRSTVWXYZ")
public static let entropyBytes = 16
static let checksumBits = 12
static let codeLength = 28
static func checksum(_ entropy: Data) -> UInt16 {
let digest = Array(SHA256.hash(data: entropy))
// Top 12 bits.
return (UInt16(digest[0]) << 4) | (UInt16(digest[1]) >> 4)
}
/// Fold the ambiguous glyphs and drop formatting, so a code read off paper
/// as "O" for zero or "l" for one still decodes.
///
/// ⚠️ Only `O` and `I`/`L` fold. `Q` is a *valid* Crockford character —
/// folding it corrupts every code that contains one, which is a mistake
/// this codebase has made once already.
public static func normalize(_ text: String) -> String {
String(text.uppercased().compactMap { character -> Character? in
switch character {
case "O": return "0"
case "I", "L": return "1"
case "0"..."9", "A"..."Z": return character
default: return nil
}
})
}
public static func generate() -> (entropy: Data, code: String) {
let entropy = Bytes.random(entropyBytes)
return (entropy, try! encode(entropy))
}
public static func encode(_ entropy: Data) throws -> String {
guard entropy.count == entropyBytes else {
throw EngineError.malformed("entropy must be \(entropyBytes) bytes")
}
// 140 bits does not fit a fixed-width integer, so the value is carried
// as a little-endian digit array and shifted by hand.
var digits = [UInt8](repeating: 0, count: codeLength)
// Right-aligned in 18 bytes: 128 bits of entropy shifted up by the 12
// checksum bits is 140, which needs the extra two bytes of headroom.
// Padding on the wrong end shifts the entropy straight out of the top.
var accumulator = [UInt8](repeating: 0, count: 2) + [UInt8](entropy)
// Append the 12-bit checksum: shift the 128 bits left by 12 and or it in.
let check = checksum(entropy)
shiftLeft(&accumulator, bits: checksumBits)
accumulator[accumulator.count - 1] |= UInt8(check & 0xFF)
accumulator[accumulator.count - 2] |= UInt8((check >> 8) & 0x0F)
for index in stride(from: codeLength - 1, through: 0, by: -1) {
digits[index] = accumulator[accumulator.count - 1] & 31
shiftRight(&accumulator, bits: 5)
}
let raw = String(digits.map { alphabet[Int($0)] })
return stride(from: 0, to: raw.count, by: 4).map {
let start = raw.index(raw.startIndex, offsetBy: $0)
let end = raw.index(start, offsetBy: min(4, raw.count - $0))
return String(raw[start..<end])
}.joined(separator: "-")
}
public static func decode(_ text: String) throws -> Data {
let normalized = normalize(text)
guard normalized.count == codeLength else {
throw EngineError.malformed(
"recovery code must be \(codeLength) characters, got \(normalized.count)")
}
var accumulator = [UInt8](repeating: 0, count: entropyBytes + 2)
for character in normalized {
guard let index = alphabet.firstIndex(of: character) else {
throw EngineError.malformed("invalid character '\(character)' in recovery code")
}
shiftLeft(&accumulator, bits: 5)
accumulator[accumulator.count - 1] |= UInt8(index)
}
let provided = (UInt16(accumulator[accumulator.count - 2] & 0x0F) << 8)
| UInt16(accumulator[accumulator.count - 1])
shiftRight(&accumulator, bits: checksumBits)
let entropy = Data(accumulator.suffix(entropyBytes))
guard checksum(entropy) == provided else {
throw EngineError.malformed("recovery code checksum does not match — check for a typo")
}
return entropy
}
/// The string fed to the KDF.
///
/// Derived from the entropy rather than from the typed code, so formatting
/// differences — grouping, case, folded glyphs — cannot produce two
/// different keys from what is really one code.
public static func kdfSecret(_ entropy: Data) -> String {
entropy.map { String(format: "%02x", $0) }.joined()
}
// MARK: big-endian bit shifts over a byte array
private static func shiftLeft(_ bytes: inout [UInt8], bits: Int) {
for _ in 0..<bits {
var carry: UInt8 = 0
for index in stride(from: bytes.count - 1, through: 0, by: -1) {
let next = bytes[index] >> 7
bytes[index] = (bytes[index] << 1) | carry
carry = next
}
}
}
private static func shiftRight(_ bytes: inout [UInt8], bits: Int) {
for _ in 0..<bits {
var carry: UInt8 = 0
for index in 0..<bytes.count {
let next = bytes[index] & 1
bytes[index] = (bytes[index] >> 1) | (carry << 7)
carry = next
}
}
}
}
+131
View File
@@ -0,0 +1,131 @@
import CommonCrypto
import CryptoKit
import Foundation
/// Share links that still respect the lattice. Specification §8.
///
/// An ordinary "anyone with the link" share is incompatible with labels. A
/// label makes access depend on who you are; a bearer link makes it depend on
/// what you hold, and forwarding defeats it. So a share here needs *two* things:
///
/// - the link, whose fragment carries a secret the server never receives
/// - the label key, which only a cleared principal holds
///
/// shareKey = HKDF-SHA256(labelKey ‖ secret, info = "enclave/share/v1")
///
/// Forward the link to someone who is not cleared and they get nothing. The
/// server cannot read it either: the secret lives only in the URL fragment, and
/// fragments are never transmitted.
///
/// An optional password is a third factor, as DoD SAFE does it. It is stretched
/// hard, because a share password is chosen under time pressure and will be
/// short — and it is never sent anywhere, so no server can test a guess against
/// it. A wrong password simply produces a key that does not decrypt.
public enum Shares {
static let info = "enclave/share/v1"
static let infoPassword = "enclave/share/v2"
public static let passwordIterations = 250_000
public struct Sealed: Sendable {
public let wrappedContentKey: Data
public let wrappedName: Data
/// Public. A salt is not a secret and the recipient needs it.
public let passwordSalt: Data?
public let passwordIterations: Int?
}
public static func createSecret() -> Data { Bytes.random(32) }
static func passwordKey(_ password: String, salt: Data, iterations: Int) throws -> Data {
let passwordBytes = Array(password.utf8)
var derived = [UInt8](repeating: 0, count: 32)
let status = salt.withUnsafeBytes { saltBuffer -> Int32 in
CCKeyDerivationPBKDF(
CCPBKDFAlgorithm(kCCPBKDF2),
passwordBytes.map { Int8(bitPattern: $0) }, passwordBytes.count,
saltBuffer.bindMemory(to: UInt8.self).baseAddress, salt.count,
CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA256),
UInt32(iterations), &derived, derived.count
)
}
guard status == kCCSuccess else { throw EngineError.malformed("PBKDF2 failed") }
return Data(derived)
}
/// Two factors always; three when a password is set.
///
/// The info string differs between the two constructions, so a
/// password-protected share cannot be opened as though it had none.
static func shareKey(labelKey: Data, secret: Data, passwordKey: Data?) -> Data {
let material = passwordKey.map { labelKey + secret + $0 } ?? (labelKey + secret)
let key = HKDF<SHA256>.deriveKey(
inputKeyMaterial: SymmetricKey(data: material),
salt: Data(),
info: Data((passwordKey == nil ? info : infoPassword).utf8),
outputByteCount: 32
)
return key.withUnsafeBytes { Data($0) }
}
/// Both the key and the name carry the label as authenticated data, exactly
/// as everything else does, so a share cannot be replayed against a row the
/// server has since relabelled.
public static func seal(
labelKey: Data, label: Label, secret: Data,
contentKey: Data, name: String, password: String? = nil
) throws -> Sealed {
let salt = password == nil ? nil : Bytes.random(16)
let pwKey = try password.map {
try passwordKey($0, salt: salt!, iterations: passwordIterations)
}
let key = shareKey(labelKey: labelKey, secret: secret, passwordKey: pwKey)
let aad = label.bytes
return Sealed(
wrappedContentKey: try Wrap.withKey(key, key: contentKey, aad: aad),
wrappedName: try Wrap.withKey(key, key: Data(name.utf8), aad: aad),
passwordSalt: salt,
passwordIterations: password == nil ? nil : passwordIterations
)
}
public static func open(
labelKey: Data, label: Label, secret: Data,
wrappedContentKey: Data, wrappedName: Data,
password: String? = nil, passwordSalt: Data? = nil,
passwordIterations iterations: Int = passwordIterations
) throws -> (contentKey: Data, name: String) {
if passwordSalt != nil && password == nil {
throw EngineError.malformed("This link needs the password it was sent with.")
}
let pwKey = try passwordSalt.map {
try passwordKey(password!, salt: $0, iterations: iterations)
}
let key = shareKey(labelKey: labelKey, secret: secret, passwordKey: pwKey)
let aad = label.bytes
let contentKey = try Wrap.openWithKey(key, blob: wrappedContentKey, aad: aad)
let nameBytes = try Wrap.openWithKey(key, blob: wrappedName, aad: aad)
guard let name = String(data: nameBytes, encoding: .utf8) else {
throw EngineError.malformed("share name is not valid UTF-8")
}
return (contentKey, name)
}
/// The fragment form. Base64url, so it survives a URL untouched.
public static func encodeSecret(_ secret: Data) -> String {
secret.base64EncodedString()
.replacingOccurrences(of: "+", with: "-")
.replacingOccurrences(of: "/", with: "_")
.replacingOccurrences(of: "=", with: "")
}
public static func decodeSecret(_ text: String) throws -> Data {
var padded = text
.replacingOccurrences(of: "-", with: "+")
.replacingOccurrences(of: "_", with: "/")
padded += String(repeating: "=", count: (4 - padded.count % 4) % 4)
guard let data = Data(base64Encoded: padded) else {
throw EngineError.malformed("share secret is not valid base64url")
}
return data
}
}
+212
View File
@@ -0,0 +1,212 @@
import CryptoKit
import Foundation
import FilesEngine
import FilesClient
/// A command-line exercise of the same engine and wire layer the app uses.
///
/// The point is that this is not a mock: `filesctl smoke` runs the real
/// registration, the real key hierarchy and the real chunked content format
/// against a real server, from the command line, in seconds. Reaching the same
/// confidence through the simulator means a build, an install, and a person
/// tapping — which in practice means it gets done once and then not again.
///
/// It also answers the question the app has to answer on first launch: point it
/// at any server and it will tell you which account service that server trusts.
func fail(_ message: String) -> Never {
FileHandle.standardError.write(Data(("error: " + message + "\n").utf8))
exit(1)
}
func say(_ message: String) { print(message) }
let arguments = Array(CommandLine.arguments.dropFirst())
guard arguments.count >= 2 else {
say("""
usage: filesctl <server-url> <command> [arguments]
commands:
probe what this server says about itself
register <handle> <passphrase> create an account and its identity
signin <handle> <passphrase> sign in and list the root
smoke <handle> <passphrase> full round trip against a fresh account
put <handle> <passphrase> <file> upload, and print its sha256
get <handle> <passphrase> <name> download by name, and print its sha256
The server names its own account service, so one address is enough:
a self-hosted box points at its bundled service, files.flamenet.io
points at accounts.flamenet.io.
""")
exit(2)
}
let server = arguments[0]
let command = arguments[1]
func connect() async throws -> (Wire.ServerConfig, AccountsClient) {
let config = try await FilesAPI.config(baseURL: server)
return (config, AccountsClient(baseURL: config.accountsURL))
}
/// Sign in and open a working session, doing whichever of unlock/enrol applies.
func openSession(handle: String, passphrase: String)
async throws -> (FilesSession, Wire.ServerConfig) {
let (config, accounts) = try await connect()
let session = try await accounts.signIn(handle: handle, passphrase: passphrase)
let claims = try TokenClaims(token: session.token)
let api = FilesAPI(baseURL: server, token: session.token)
let files = try await FilesSession.open(
api: api, accounts: accounts, token: session.token,
passphrase: passphrase, clearance: claims.clearance)
try await files.loadLabelKeys()
return (files, config)
}
do {
switch command {
case "probe":
let config = try await FilesAPI.config(baseURL: server)
say("server: \(server)")
say("accounts: \(config.accountsURL)")
say("tenant: \(config.tenant)")
say("site: \(config.siteURL)")
say("source: \(config.sourceURL)")
say("protocol: v\(config.protocolVersion)")
case "register":
guard arguments.count >= 4 else { fail("register needs a handle and a passphrase") }
let (config, accounts) = try await connect()
let handle = arguments[2], passphrase = arguments[3]
// Built before the account exists, so both land in one transaction.
let (entropy, code) = Recovery.generate()
let key = Identity.generate()
let record = try Identity.protect(key, passphrase: passphrase)
let recovery = try Identity.protectWithRecovery(key, entropy: entropy)
try await accounts.register(
handle: handle, passphrase: passphrase, recoveryEntropy: entropy,
identity: Wire.NewIdentity(
product: "files",
publicKey: Identity.exportPublicKey(key.publicKey),
protectedRecord: record.json,
recoveryRecord: recovery.json))
say("registered \(handle) on \(config.accountsURL)")
say("recovery code: \(code)")
say(" This is shown once. Without it a lost passphrase loses the data.")
case "signin":
guard arguments.count >= 4 else { fail("signin needs a handle and a passphrase") }
let (files, _) = try await openSession(handle: arguments[2], passphrase: arguments[3])
let clearance = await files.clearance
say("signed in. clearance: classification \(clearance.maximum.classification)"
+ (clearance.maximum.compartments.isEmpty
? "" : ", compartments \(clearance.maximum.compartments.sorted())"))
let entries = try await files.list(nil)
if entries.isEmpty { say("(the root is empty)") }
for entry in entries {
let name = entry.name ?? "(no key for this area)"
say(" \(entry.isFolder ? "dir " : "file") \(name) [c\(entry.label.classification)"
+ (entry.label.compartments.isEmpty
? "" : "//\(entry.label.compartments.sorted().map(String.init).joined(separator: ","))")
+ "]")
}
// Cross-engine interop: one engine writes, the other reads. Neither the
// vectors file nor a self round-trip can catch a divergence that only shows
// up once two different implementations share an account.
case "put":
guard arguments.count >= 5 else { fail("put needs a handle, a passphrase and a file") }
let (files, _) = try await openSession(handle: arguments[2], passphrase: arguments[3])
let path = arguments[4]
let bytes = try Data(contentsOf: URL(fileURLWithPath: path))
try await files.use(await files.clearance.minimum)
_ = try await files.upload(bytes, named: (path as NSString).lastPathComponent)
say("uploaded \((path as NSString).lastPathComponent), \(bytes.count) bytes")
say("sha256: \(Data(SHA256.hash(data: bytes)).map { String(format: "%02x", $0) }.joined())")
case "get":
guard arguments.count >= 5 else { fail("get needs a handle, a passphrase and a name") }
let (files, _) = try await openSession(handle: arguments[2], passphrase: arguments[3])
try await files.use(await files.clearance.minimum)
let wanted = arguments[4]
guard let entry = try await files.list(nil).first(where: { $0.name == wanted }) else {
fail("no file named '\(wanted)' that this session can read")
}
let bytes = try await files.download(entry.node)
say("downloaded \(wanted), \(bytes.count) bytes")
say("sha256: \(Data(SHA256.hash(data: bytes)).map { String(format: "%02x", $0) }.joined())")
case "smoke":
guard arguments.count >= 4 else { fail("smoke needs a handle and a passphrase") }
let handle = arguments[2], passphrase = arguments[3]
let (config, accounts) = try await connect()
say("· server \(server) → accounts \(config.accountsURL)")
let (entropy, code) = Recovery.generate()
let key = Identity.generate()
try await accounts.register(
handle: handle, passphrase: passphrase, recoveryEntropy: entropy,
identity: Wire.NewIdentity(
product: "files",
publicKey: Identity.exportPublicKey(key.publicKey),
protectedRecord: try Identity.protect(key, passphrase: passphrase).json,
recoveryRecord: try Identity.protectWithRecovery(key, entropy: entropy).json))
say("· registered \(handle)")
// Signing in fresh, rather than reusing the keypair in memory, is the
// point: it proves the record the server stored actually opens.
let (files, _) = try await openSession(handle: handle, passphrase: passphrase)
let clearance = await files.clearance
say("· signed in, clearance c\(clearance.maximum.classification)")
try await files.use(clearance.minimum)
let folder = try await files.createFolder("smoke")
guard let folder else { fail("the server did not return the new folder") }
say("· created a folder")
let payload = Data((0..<200_000).map { UInt8($0 % 251) })
guard let uploaded = try await files.upload(payload, named: "sample.bin", in: folder.id)
else { fail("the server did not return the new file") }
say("· uploaded \(payload.count) bytes across \(payload.count / Content.defaultChunkSize + 1) chunks")
let listed = try await files.list(folder.id)
guard listed.contains(where: { $0.name == "sample.bin" }) else {
fail("the uploaded file did not come back with a readable name")
}
say("· listed it and decrypted its name")
let recovered = try await files.download(uploaded)
guard recovered == payload else { fail("the downloaded bytes do not match") }
say("· downloaded and the bytes match exactly")
let entry = listed.first { $0.name == "sample.bin" }!
let share = try await files.createShare(for: entry, password: "hunter2")
say("· made a password-protected link")
let opened = try await files.openShare(share.id, secret: share.secret, password: "hunter2")
guard opened.bytes == payload, opened.name == "sample.bin" else {
fail("the share did not open to the original file")
}
say("· opened it with the password")
do {
_ = try await files.openShare(share.id, secret: share.secret)
fail("the link opened WITHOUT its password — the third factor is not enforced")
} catch {
say("· refused it without the password")
}
say("")
say("all good. recovery code for \(handle): \(code)")
default:
fail("unknown command '\(command)'")
}
} catch let error as ClientError {
fail(error.errorDescription ?? String(describing: error))
} catch {
fail(String(describing: error))
}
+136
View File
@@ -138,3 +138,139 @@ final class InteropTests: XCTestCase {
contentKey: try b64(h.contentKey), label: wrong))
}
}
/// Recovery codes and identity protection.
///
/// The vectors file pins the wire formats the browser already produces. These
/// cover the two pieces this engine gained for the app, where the risk is not
/// interop with the browser but with *itself*: a code that encodes and does not
/// decode is worthless, and it fails silently at exactly the moment somebody
/// needs it.
final class RecoveryTests: XCTestCase {
private struct RecoveryVectors: Decodable {
struct Case: Decodable {
let entropy: String
let code: String
let kdfSecret: String
}
let recovery: [Case]
let recoveryWithQ: Case
}
private var vectors: RecoveryVectors!
override func setUpWithError() throws {
let url = try XCTUnwrap(Bundle.module.url(forResource: "vectors/v1", withExtension: "json"))
vectors = try JSONDecoder().decode(RecoveryVectors.self, from: try Data(contentsOf: url))
}
/// The one that matters: codes written by the browser must decode here, and
/// this engine must produce the identical string from the same entropy.
/// Anything else means a code printed on one device is useless on another.
func testAgreesWithTheBrowser() throws {
for expected in vectors.recovery + [vectors.recoveryWithQ] {
let entropy = try XCTUnwrap(Data(base64Encoded: expected.entropy))
XCTAssertEqual(try Recovery.encode(entropy), expected.code)
XCTAssertEqual(try Recovery.decode(expected.code), entropy)
XCTAssertEqual(Recovery.kdfSecret(entropy), expected.kdfSecret)
}
}
/// A code containing Q, decoded from paper: lower-cased, spaces instead of
/// dashes. Folding Q here is the bug that once corrupted a third of codes.
func testTheQCaseSurvivesTranscription() throws {
let expected = vectors.recoveryWithQ
XCTAssertTrue(expected.code.contains("Q"), "vector should contain a Q")
let mangled = expected.code.lowercased().replacingOccurrences(of: "-", with: " ")
XCTAssertEqual(try Recovery.decode(mangled),
try XCTUnwrap(Data(base64Encoded: expected.entropy)))
}
func testCodeRoundTrips() throws {
for _ in 0..<200 {
let (entropy, code) = Recovery.generate()
XCTAssertEqual(code.replacingOccurrences(of: "-", with: "").count, 28)
XCTAssertEqual(try Recovery.decode(code), entropy)
}
}
/// The failure that shipped once: `Q` is a valid Crockford character, and
/// folding it to `0` corrupted roughly a third of all codes.
func testQIsNotFolded() throws {
XCTAssertEqual(Recovery.normalize("Q"), "Q")
XCTAssertEqual(Recovery.normalize("O"), "0")
XCTAssertEqual(Recovery.normalize("I"), "1")
XCTAssertEqual(Recovery.normalize("L"), "1")
// A code containing Q must still decode after a round trip through
// normalisation, which is what the fold used to break.
var found = false
for _ in 0..<500 where !found {
let (entropy, code) = Recovery.generate()
if code.contains("Q") {
found = true
XCTAssertEqual(try Recovery.decode(code.lowercased()), entropy)
}
}
XCTAssertTrue(found, "expected at least one code containing Q in 500 draws")
}
func testFormattingDoesNotChangeTheKey() throws {
let (entropy, code) = Recovery.generate()
let mangled = code.lowercased().replacingOccurrences(of: "-", with: " ")
XCTAssertEqual(try Recovery.decode(mangled), entropy)
}
func testChecksumCatchesATypo() throws {
let (_, code) = Recovery.generate()
var characters = Array(Recovery.normalize(code))
// Change one character to a different valid one.
characters[3] = characters[3] == "7" ? "8" : "7"
XCTAssertThrowsError(try Recovery.decode(String(characters)))
}
func testIdentityRecordRoundTrips() throws {
// A low iteration count: this asserts the format, not the work factor,
// and 650,000 rounds per case would make the suite unbearable.
let fast = KDF.Parameters(id: 1, iterations: 1_000)
let key = Identity.generate()
let record = try Identity.protect(key, passphrase: "correct horse", parameters: fast)
let opened = try Identity.unlock(record, passphrase: "correct horse")
XCTAssertEqual(opened.rawRepresentation, key.rawRepresentation)
}
func testTheWrongPassphraseDoesNotOpenIt() throws {
let fast = KDF.Parameters(id: 1, iterations: 1_000)
let record = try Identity.protect(Identity.generate(), passphrase: "one", parameters: fast)
XCTAssertThrowsError(try Identity.unlock(record, passphrase: "two"))
}
/// The passphrase and the recovery code wrap the same key independently, so
/// changing one must not disturb the other.
func testRecoveryOpensTheSameKey() throws {
let fast = KDF.Parameters(id: 1, iterations: 1_000)
let key = Identity.generate()
let (entropy, _) = Recovery.generate()
let byRecovery = try Identity.protectWithRecovery(key, entropy: entropy, parameters: fast)
let opened = try Identity.unlockWithRecovery(byRecovery, entropy: entropy)
XCTAssertEqual(opened.rawRepresentation, key.rawRepresentation)
}
/// Different contexts, so a record made for one secret cannot be opened as
/// the other's even when the derived material would otherwise line up.
func testRecoveryRecordIsNotAPassphraseRecord() throws {
let fast = KDF.Parameters(id: 1, iterations: 1_000)
let key = Identity.generate()
let (entropy, _) = Recovery.generate()
let byRecovery = try Identity.protectWithRecovery(key, entropy: entropy, parameters: fast)
XCTAssertEqual(byRecovery.context, KDF.Context.filesRecovery)
// Same secret material, wrong context: must not open.
XCTAssertThrowsError(
try Identity.unlock(
Identity.Record(
v: 1, kdf: byRecovery.kdf, iterations: byRecovery.iterations,
context: KDF.Context.filesIdentity,
salt: byRecovery.salt, nonce: byRecovery.nonce,
privateKey: byRecovery.privateKey),
passphrase: Recovery.kdfSecret(entropy)))
}
}
+37
View File
@@ -95,5 +95,42 @@
"code": "BKKR-SJXB-E8M8-1A6B-CN47-WNM7-6RQN",
"entropy": "XOeMy6tyKICoy2VIflaHNg=="
}
},
"recovery": [
{
"entropy": "AEeO1RxjqvE4f8YNVJviKQ==",
"code": "013R-XN8W-CENF-2E3Z-RR6N-96Z2-57K9",
"kdfSecret": "00478ed51c63aaf1387fc60d549be229"
},
{
"entropy": "JWyz+kGIzxZdpOsyecAHTg==",
"code": "4NPB-7YJ1-H37H-CQD4-XCS7-KG07-9RBA",
"kdfSecret": "256cb3fa4188cf165da4eb3279c0074e"
},
{
"entropy": "SpHYH2at9DuCyRBXnuUscw==",
"code": "9A8X-G7V6-NQT3-Q0P9-21BS-XS9C-EE7C",
"kdfSecret": "4a91d81f66adf43b82c910579ee52c73"
},
{
"entropy": "b7b9RIvSGWCn7jV8wwpRmA==",
"code": "DYVF-TH4B-T8CP-19ZE-6NYC-62JH-K3JD",
"kdfSecret": "6fb6fd448bd21960a7ee357cc30a5198"
},
{
"entropy": "lNsiabD3PoXME1qh6C92vQ==",
"code": "JKDJ-4TDG-YWZ8-BK0K-BAGY-GBVP-QN2Y",
"kdfSecret": "94db2269b0f73e85cc135aa1e82f76bd"
},
{
"entropy": "uQBHjtUcY6rxOH/GDVSb4g==",
"code": "Q404-F3PN-3HHT-NW9R-FZ30-TN4V-W87R",
"kdfSecret": "b900478ed51c63aaf1387fc60d549be2"
}
],
"recoveryWithQ": {
"entropy": "AB06V3SRrsvoBSI/XHmWsw==",
"code": "00EK-MNVM-J6QC-QT05-48ZN-RYCP-PDSA",
"kdfSecret": "001d3a577491aecbe805223f5c7996b3"
}
}