The iOS app: a SwiftUI shell over the tested client

Sign in, register with a recovery code shown once, browse, switch area,
upload, download through a share sheet, and create password-protected
links. All of it sits on FilesClient, which filesctl already exercises end
to end against both a self-hosted stack and files.flamenet.io.

The area banner is always on screen rather than tucked into a menu. Which
area you are working in decides where a new file lands and who can ever
read it, and finding that out afterwards is too late. Rows this session
cannot decrypt are shown, and say so — hiding them would be a lie about
what the server knows.

The project file is generated by XcodeGen and not committed, so it cannot
become a merge hazard.

UI tests drive the real app, which is how the first real bug here was
found: the mode picker and the submit button carry the same three words,
so matching on the visible label tapped the picker and the form never
submitted. Both are addressed by identifier now, which VoiceOver benefits
from as much as the tests do.
This commit is contained in:
Paul Hitt
2026-08-21 18:39:41 -04:00
parent b88d638085
commit d729a2d9af
11 changed files with 1015 additions and 2 deletions
+3 -2
View File
@@ -1,5 +1,6 @@
.build/
.swiftpm/
*.xcodeproj/
*.xcworkspace/
DerivedData/
*.xcuserstate
xcuserdata/
.DS_Store
+37
View File
@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key>
<string>Flamenet Files</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>0.1</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>ITSAppUsesNonExemptEncryption</key>
<false/>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsLocalNetworking</key>
<true/>
</dict>
<key>UILaunchScreen</key>
<dict/>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
</array>
</dict>
</plist>
+286
View File
@@ -0,0 +1,286 @@
import CryptoKit
import Foundation
import SwiftUI
import FilesEngine
import FilesClient
/// SwiftUI has a `Label` of its own, and the collision is silent in the worst
/// way: it type-checks in some positions and not others. Spelling ours out also
/// reads better in interface code — "security label" is what it is.
typealias SecurityLabel = FilesEngine.Label
/// Everything the interface needs, in one observable place.
///
/// Deliberately holds no persistence. The session keeps the identity key and
/// the label keys in memory; closing the app forgets them, and the next launch
/// asks for the passphrase again. That is the intended behaviour, not an
/// omission — a key cached in the keychain is a key an unlocked phone hands to
/// whoever is holding it.
///
/// The one thing that *is* remembered is the server address and the handle,
/// because typing a URL on a phone every time is how people end up choosing a
/// worse product.
@MainActor
final class AppState: ObservableObject {
enum Phase: Equatable {
case signedOut
case working(String)
case showingRecoveryCode(String)
case browsing
}
@Published var phase: Phase = .signedOut
@Published var error: String?
@AppStorage("server") var server: String = "https://files.flamenet.io"
@AppStorage("handle") var handle: String = ""
@Published private(set) var config: Wire.ServerConfig?
@Published private(set) var vocabulary = Wire.Vocabulary(levels: [], compartments: [], canEdit: false)
@Published private(set) var clearance: Clearance?
@Published private(set) var label: SecurityLabel?
/// Breadcrumb of the folders walked into, so the title bar can say where
/// you are and Back knows where to return to.
@Published private(set) var path: [(id: UUID, name: String)] = []
@Published private(set) var entries: [FilesSession.Entry] = []
private var session: FilesSession?
var isSignedIn: Bool { session != nil }
var folderID: UUID? { path.last?.id }
/// Every label this clearance permits, as the picker offers them.
///
/// Built from the vocabulary rather than from the whole lattice: 2^64
/// compartment combinations is not a menu. Only named areas appear, which
/// is also the only set anybody can reason about.
var selectableLabels: [SecurityLabel] {
guard let clearance else { return [] }
let levels = vocabulary.levels.map(\.ordinal).sorted()
let bits = vocabulary.compartments.map(\.bit).sorted()
var out: [SecurityLabel] = []
for level in levels {
// Areas are offered one at a time plus the empty set. Every
// combination is correct in the lattice and useless in a list.
for subset in [[]] + bits.map { [$0] } {
let candidate = SecurityLabel(classification: level, compartments: Set(subset))
if clearance.permits(candidate) { out.append(candidate) }
}
}
return out
}
func name(for label: SecurityLabel) -> String { vocabulary.name(for: label) }
// MARK: connecting
func probe() async {
error = nil
do { config = try await FilesAPI.config(baseURL: server) }
catch { self.error = message(error) }
}
func signIn(passphrase: String, mode: SignInMode, recoveryCode: String = "") async {
error = nil
phase = .working(mode == .register ? "Creating your account…" : "Deriving keys…")
do {
let config = try await FilesAPI.config(baseURL: server)
self.config = config
let accounts = AccountsClient(baseURL: config.accountsURL)
var freshCode: String?
var enrolledKey: Curve25519.KeyAgreement.PrivateKey?
switch mode {
case .register:
// Built before the account exists so both land in one
// transaction. Registering first and enrolling after left a
// window where a backgrounded app stranded a handle that was
// taken, unusable, and impossible to enrol into.
let (entropy, code) = Recovery.generate()
let key = Identity.generate()
try await accounts.register(
handle: handle, passphrase: passphrase, recoveryEntropy: entropy,
identity: Wire.NewIdentity(
publicKey: Identity.exportPublicKey(key.publicKey),
protectedRecord: try Identity.protect(key, passphrase: passphrase).json,
recoveryRecord: try Identity.protectWithRecovery(key, entropy: entropy).json))
freshCode = code
enrolledKey = key
case .recover:
let entropy = try Recovery.decode(recoveryCode)
let (nextEntropy, _) = Recovery.generate()
try await accounts.rotate(
handle: handle, entropy: entropy,
newPassphrase: passphrase, nextEntropy: nextEntropy)
case .signIn:
break
}
let token = try await accounts.signIn(handle: handle, passphrase: passphrase).token
let claims = try TokenClaims(token: token)
let api = FilesAPI(baseURL: server, token: token)
let opened: FilesSession
switch mode {
case .register:
opened = await FilesSession.enrolled(
api: api, accounts: accounts, token: token,
privateKey: enrolledKey!, clearance: claims.clearance, recoveryCode: freshCode)
case .recover:
let (nextEntropy, _) = Recovery.generate()
opened = try await FilesSession.recover(
api: api, accounts: accounts, token: token, code: recoveryCode,
newPassphrase: passphrase, clearance: claims.clearance,
nextEntropy: nextEntropy)
case .signIn:
opened = try await FilesSession.open(
api: api, accounts: accounts, token: token,
passphrase: passphrase, clearance: claims.clearance)
}
session = opened
clearance = claims.clearance
try await opened.loadLabelKeys()
vocabulary = try await api.vocabulary()
let startingLabel = claims.clearance.minimum
try await opened.use(startingLabel)
label = startingLabel
if let code = await opened.recoveryCode {
phase = .showingRecoveryCode(code)
} else {
phase = .browsing
await refresh()
}
} catch {
session = nil
phase = .signedOut
self.error = message(error)
}
}
func signOut() {
session = nil
clearance = nil
label = nil
path = []
entries = []
phase = .signedOut
}
func acknowledgeRecoveryCode() async {
await session?.clearRecoveryCode()
phase = .browsing
await refresh()
}
// MARK: browsing
func refresh() async {
guard let session else { return }
do { entries = try await session.list(folderID) }
catch { self.error = message(error) }
}
func open(_ entry: FilesSession.Entry) async {
guard entry.isFolder else { return }
path.append((entry.id, entry.name ?? "Folder"))
await refresh()
}
func goBack() async {
guard !path.isEmpty else { return }
path.removeLast()
await refresh()
}
func use(_ label: SecurityLabel) async {
guard let session else { return }
do {
try await session.use(label)
self.label = label
// Changing area changes what exists, so the breadcrumb cannot
// survive it: a folder id from one label may be invisible in
// another, and 404 is the correct answer rather than an error.
path = []
await refresh()
} catch { self.error = message(error) }
}
func createFolder(named name: String) async {
guard let session else { return }
do {
_ = try await session.createFolder(name, in: folderID)
await refresh()
} catch { self.error = message(error) }
}
func upload(_ data: Data, named name: String) async {
guard let session else { return }
phase = .working("Encrypting \(name)…")
do {
_ = try await session.upload(data, named: name, in: folderID)
phase = .browsing
await refresh()
} catch {
phase = .browsing
self.error = message(error)
}
}
func download(_ entry: FilesSession.Entry) async -> URL? {
guard let session else { return nil }
do {
let bytes = try await session.download(entry.node)
// A temporary file, so the share sheet has something to hand to
// another app. It is plaintext on disk for as long as it exists,
// which is why it goes in the caches directory and is named after
// the file rather than after anything identifying.
let url = FileManager.default.temporaryDirectory
.appendingPathComponent(entry.name ?? "file")
try bytes.write(to: url, options: .atomic)
return url
} catch {
self.error = message(error)
return nil
}
}
func createShare(for entry: FilesSession.Entry, password: String?) async -> String? {
guard let session, let config else { return nil }
do {
let share = try await session.createShare(
for: entry, password: password?.isEmpty == false ? password : nil)
return share.url(site: config.siteURL)
} catch {
self.error = message(error)
return nil
}
}
private func message(_ error: any Error) -> String {
(error as? LocalizedError)?.errorDescription ?? error.localizedDescription
}
}
enum SignInMode: String, CaseIterable {
case signIn = "Unlock"
case register = "Create account"
case recover = "Recover"
/// A stable handle for tests and accessibility, separate from the visible
/// wording. Changing a button's text should not break either.
var identifier: String {
switch self {
case .signIn: return "signin"
case .register: return "register"
case .recover: return "recover"
}
}
}
+196
View File
@@ -0,0 +1,196 @@
import SwiftUI
import UniformTypeIdentifiers
import FilesEngine
import FilesClient
struct BrowseView: View {
@EnvironmentObject private var state: AppState
@State private var importing = false
@State private var newFolder = false
@State private var folderName = ""
@State private var sharing: FilesSession.Entry?
@State private var exportedFile: URL?
var body: some View {
NavigationStack {
List {
if state.entries.isEmpty {
ContentUnavailableView(
"Nothing here yet",
systemImage: "folder",
description: Text("Files you add are encrypted on this device before they leave it.")
)
}
ForEach(state.entries) { entry in
Row(entry: entry)
.contentShape(Rectangle())
.onTapGesture { Task { await open(entry) } }
.swipeActions(edge: .trailing) {
if !entry.isFolder && entry.name != nil {
Button {
sharing = entry
} label: {
Label("Link", systemImage: "link")
}
.tint(.indigo)
}
}
}
}
.listStyle(.plain)
.refreshable { await state.refresh() }
.navigationTitle(state.path.last?.name ?? "All files")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .topBarLeading) {
if !state.path.isEmpty {
Button { Task { await state.goBack() } } label: {
Label("Back", systemImage: "chevron.left")
}
} else {
LabelMenu()
}
}
ToolbarItem(placement: .topBarTrailing) {
Menu {
Button { importing = true } label: {
Label("Upload a file", systemImage: "arrow.up.doc")
}
Button { newFolder = true } label: {
Label("New folder", systemImage: "folder.badge.plus")
}
Divider()
if !state.path.isEmpty { LabelMenu() }
Button(role: .destructive) { state.signOut() } label: {
Label("Sign out", systemImage: "lock")
}
} label: {
Image(systemName: "ellipsis.circle")
}
}
}
.safeAreaInset(edge: .top) {
if let label = state.label {
// Always visible, never a hidden mode. Which area you are
// working in decides where a new file lands and who can
// ever read it, and finding that out afterwards is too late.
Text("Working at \(state.name(for: label)). New files are filed here.")
.font(.footnote)
.foregroundStyle(.secondary)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal, 16)
.padding(.vertical, 8)
.background(.bar)
}
}
}
.fileImporter(isPresented: $importing, allowedContentTypes: [.item]) { result in
guard case .success(let url) = result else { return }
Task {
// A security-scoped URL: the file lives outside the app's
// sandbox and access has to be claimed and released explicitly.
guard url.startAccessingSecurityScopedResource() else {
state.error = "Could not read that file."
return
}
defer { url.stopAccessingSecurityScopedResource() }
do {
let data = try Data(contentsOf: url)
await state.upload(data, named: url.lastPathComponent)
} catch {
state.error = "Could not read that file."
}
}
}
.alert("New folder", isPresented: $newFolder) {
TextField("Name", text: $folderName)
Button("Cancel", role: .cancel) { folderName = "" }
Button("Create") {
let name = folderName
folderName = ""
Task { await state.createFolder(named: name) }
}
}
.sheet(item: $sharing) { entry in
ShareSheet(entry: entry)
}
.sheet(isPresented: Binding(get: { exportedFile != nil },
set: { if !$0 { exportedFile = nil } })) {
if let exportedFile { SystemShareSheet(items: [exportedFile]) }
}
}
private func open(_ entry: FilesSession.Entry) async {
if entry.isFolder {
await state.open(entry)
} else if entry.name != nil {
exportedFile = await state.download(entry)
}
}
}
/// One row. A file this session cannot decrypt still appears, and says so.
struct Row: View {
@EnvironmentObject private var state: AppState
let entry: FilesSession.Entry
var body: some View {
HStack(spacing: 12) {
Image(systemName: entry.isFolder ? "folder.fill" : "doc.fill")
.foregroundStyle(entry.name == nil ? AnyShapeStyle(.secondary) : AnyShapeStyle(.tint))
.frame(width: 22)
VStack(alignment: .leading, spacing: 2) {
if let name = entry.name {
Text(name).lineLimit(1)
} else {
// Visible to the database, unreadable here. Saying so is
// more honest than hiding the row, and hiding it would be a
// lie about what the server knows.
Text("Encrypted for another key")
.italic()
.foregroundStyle(.secondary)
}
Text(state.name(for: entry.label))
.font(.caption2)
.foregroundStyle(.secondary)
}
Spacer()
if let size = entry.node.sizeBytes, size > 0 {
Text(ByteCountFormatter.string(fromByteCount: size, countStyle: .file))
.font(.caption)
.foregroundStyle(.secondary)
}
}
.padding(.vertical, 4)
}
}
/// Switching area. Only labels the clearance permits are offered, so nobody
/// discovers the limit by being refused.
struct LabelMenu: View {
@EnvironmentObject private var state: AppState
var body: some View {
Menu {
ForEach(state.selectableLabels, id: \.self) { label in
Button {
Task { await state.use(label) }
} label: {
if label == state.label {
Label(state.name(for: label), systemImage: "checkmark")
} else {
Text(state.name(for: label))
}
}
}
} label: {
Label(state.label.map(state.name(for:)) ?? "Area", systemImage: "shield.lefthalf.filled")
.labelStyle(.titleAndIcon)
.font(.footnote)
}
}
}
+59
View File
@@ -0,0 +1,59 @@
import SwiftUI
@main
struct FlamenetFilesApp: App {
@StateObject private var state = AppState()
var body: some Scene {
WindowGroup {
RootView().environmentObject(state)
}
}
}
struct RootView: View {
@EnvironmentObject private var state: AppState
var body: some View {
Group {
switch state.phase {
case .signedOut:
SignInView()
case .working(let what):
WorkingView(what: what)
case .showingRecoveryCode(let code):
RecoveryCodeView(code: code)
case .browsing:
BrowseView()
}
}
.animation(.default, value: state.phase)
.alert("Something went wrong",
isPresented: Binding(get: { state.error != nil },
set: { if !$0 { state.error = nil } })) {
Button("OK", role: .cancel) { state.error = nil }
} message: {
Text(state.error ?? "")
}
}
}
/// Deliberately says what is slow and why.
///
/// The stretch takes several seconds on a phone, on purpose. Without a reason
/// on screen, a deliberate cost reads as a broken app.
struct WorkingView: View {
let what: String
var body: some View {
VStack(spacing: 16) {
ProgressView().controlSize(.large)
Text(what).font(.headline)
Text("This takes a few seconds on purpose — it's what makes a short passphrase hard to attack.")
.font(.footnote)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
.padding(.horizontal, 40)
}
}
}
+90
View File
@@ -0,0 +1,90 @@
import SwiftUI
import UIKit
import FilesClient
/// Making a link.
///
/// The copy here matters more than the controls. A share link on this system is
/// not what people expect a share link to be: it is useless to anyone who is
/// not cleared for the file's area, which is a feature and a surprise.
struct ShareSheet: View {
@EnvironmentObject private var state: AppState
@Environment(\.dismiss) private var dismiss
let entry: FilesSession.Entry
@State private var usePassword = false
@State private var password = ""
@State private var link: String?
@State private var busy = false
var body: some View {
NavigationStack {
Form {
if let link {
Section {
Text(link)
.font(.system(.footnote, design: .monospaced))
.textSelection(.enabled)
Button {
UIPasteboard.general.string = link
} label: {
Label("Copy link", systemImage: "doc.on.doc")
}
} footer: {
Text("The part after # never leaves the recipient's browser, so the server storing this link cannot open it.")
}
} else {
Section {
Toggle("Require a password", isOn: $usePassword)
if usePassword {
SecureField("Password", text: $password)
}
} footer: {
Text(usePassword
? "Send it separately from the link — a password in the same message is not a second factor. It is never sent to the server, so nobody can test a guess against it."
: "Anyone cleared for this area who has the link can open the file.")
}
Section {
Button {
busy = true
Task {
link = await state.createShare(
for: entry, password: usePassword ? password : nil)
busy = false
}
} label: {
if busy {
ProgressView().frame(maxWidth: .infinity)
} else {
Text("Create link").frame(maxWidth: .infinity)
}
}
.buttonStyle(.borderedProminent)
.disabled(busy || (usePassword && password.isEmpty))
} footer: {
Text("This link only works for people cleared for \(state.name(for: entry.label)). Forwarding it to anyone else gives them nothing.")
}
}
}
.navigationTitle(entry.name ?? "Share")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .topBarTrailing) {
Button("Done") { dismiss() }
}
}
}
}
}
/// The system share sheet, for handing a decrypted file to another app.
struct SystemShareSheet: UIViewControllerRepresentable {
let items: [Any]
func makeUIViewController(context: Context) -> UIActivityViewController {
UIActivityViewController(activityItems: items, applicationActivities: nil)
}
func updateUIViewController(_ controller: UIActivityViewController, context: Context) {}
}
+149
View File
@@ -0,0 +1,149 @@
import SwiftUI
struct SignInView: View {
@EnvironmentObject private var state: AppState
@State private var mode: SignInMode = .signIn
@State private var passphrase = ""
@State private var recoveryCode = ""
@State private var showingServer = false
var body: some View {
NavigationStack {
Form {
Section {
TextField("Handle", text: $state.handle)
.accessibilityIdentifier("handle")
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.textContentType(.username)
SecureField(mode == .recover ? "New passphrase" : "Passphrase",
text: $passphrase)
.accessibilityIdentifier("passphrase")
.textContentType(mode == .signIn ? .password : .newPassword)
if mode == .recover {
TextField("Recovery code", text: $recoveryCode)
.textInputAutocapitalization(.characters)
.autocorrectionDisabled()
.font(.system(.body, design: .monospaced))
}
} footer: {
Text(footer)
}
Section {
Button {
Task {
await state.signIn(
passphrase: passphrase, mode: mode, recoveryCode: recoveryCode)
}
} label: {
Text(mode.rawValue).frame(maxWidth: .infinity)
}
.buttonStyle(.borderedProminent)
.disabled(!isReady)
// The mode picker below carries the same three words, so
// the submit button and the mode it submits are otherwise
// indistinguishable — to a UI test and to VoiceOver alike.
.accessibilityIdentifier("submit")
}
Section {
Picker("", selection: $mode) {
ForEach(SignInMode.allCases, id: \.self) {
Text($0.rawValue)
.tag($0)
.accessibilityIdentifier("mode-\($0.identifier)")
}
}
.pickerStyle(.segmented)
.accessibilityIdentifier("mode")
}
Section {
// Behind a disclosure: almost nobody changes it, and a URL
// field at the top of a sign-in screen is a good way to
// make a simple product look like an administrative one.
DisclosureGroup("Server", isExpanded: $showingServer) {
TextField("https://files.flamenet.io", text: $state.server)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.keyboardType(.URL)
if let config = state.config {
LabeledContent("Accounts", value: shortHost(config.accountsURL))
.font(.footnote)
}
Button("Check") { Task { await state.probe() } }
}
} footer: {
Text("Your server decides which account service to trust. Self-hosted deployments use their own.")
}
}
.navigationTitle("Flamenet Files")
.task { await state.probe() }
}
}
private var isReady: Bool {
!state.handle.trimmingCharacters(in: .whitespaces).isEmpty
&& !passphrase.isEmpty
&& (mode != .recover || !recoveryCode.isEmpty)
}
private var footer: String {
switch mode {
case .signIn:
return "Your passphrase never leaves this device. It builds your keys here."
case .register:
return "Choose something long. There is no way to reset it — you'll get a recovery code once, and that is the only way back in."
case .recover:
return "Your recovery code unlocks the same keys your passphrase did, so nothing needs re-encrypting. A fresh code is issued and the old one stops working."
}
}
private func shortHost(_ url: String) -> String {
URL(string: url)?.host ?? url
}
}
/// Shown once, and it says so.
struct RecoveryCodeView: View {
@EnvironmentObject private var state: AppState
let code: String
var body: some View {
VStack(spacing: 22) {
Image(systemName: "key.horizontal.fill")
.font(.system(size: 40))
.foregroundStyle(.tint)
Text("Write this down now").font(.title2.bold())
Text("This is the only way back in if you forget your passphrase. It is not stored anywhere, this is the only time it will ever be shown, and we cannot send it again.")
.font(.callout)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
// Monospaced and generously spaced, because this gets copied onto
// paper by hand and a wrapped group is a transcription error.
Text(code)
.font(.system(.title3, design: .monospaced).weight(.semibold))
.multilineTextAlignment(.center)
.textSelection(.enabled)
.padding(18)
.frame(maxWidth: .infinity)
.background(.quaternary, in: RoundedRectangle(cornerRadius: 12))
HStack(spacing: 12) {
Button("Copy") { UIPasteboard.general.string = code }
.buttonStyle(.bordered)
Button("I've written it down") {
Task { await state.acknowledgeRecoveryCode() }
}
.buttonStyle(.borderedProminent)
}
}
.padding(28)
}
}
+92
View File
@@ -0,0 +1,92 @@
import XCTest
/// Drives the real app against a real server.
///
/// This exists because the interesting failures in this app are wiring, not
/// cryptography — the engine and the wire layer are already covered by `swift
/// test` and by `filesctl` running full round trips. What is left is whether a
/// button is connected to the thing it claims to do, and the only way to find
/// that out is to press it.
///
/// Needs a stack on `http://127.0.0.1:8081`. The simulator shares the host's
/// network, so `docker compose up` on the development machine is enough.
final class SignInFlowTests: XCTestCase {
private var app: XCUIApplication!
override func setUp() {
continueAfterFailure = false
app = XCUIApplication()
// The handle is remembered between launches, deliberately — typing a
// username on a phone every time is a small cruelty. That makes it
// shared state between tests, so each run starts from a clean slate.
app.launchArguments = ["-server", "http://127.0.0.1:8081", "-handle", ""]
app.launch()
}
/// A unique handle per run. Registration is once per name, and a test that
/// only passes on a fresh database is a test that gets ignored.
private var handle: String {
"uitest\(Int(Date().timeIntervalSince1970))"
}
/// The picker and the submit button carry the same three words, so both are
/// addressed by identifier. Matching on the visible label picks whichever
/// XCTest finds first, which is the picker — and the form never submits.
private func register(as name: String) {
app.buttons["mode-register"].tap()
let handleField = app.textFields["handle"]
XCTAssertTrue(handleField.waitForExistence(timeout: 5))
handleField.tap()
handleField.typeText(name)
let passphrase = app.secureTextFields["passphrase"]
passphrase.tap()
passphrase.typeText("correct horse battery staple")
app.buttons["submit"].tap()
}
func testRegisterThenBrowse() throws {
let name = handle
register(as: name)
// The stretch is deliberately slow, and slower again in a simulator.
let recovery = app.staticTexts["Write this down now"]
XCTAssertTrue(recovery.waitForExistence(timeout: 90),
"registration did not reach the recovery code")
app.buttons["I've written it down"].tap()
// An empty account, said plainly rather than shown as a blank screen.
XCTAssertTrue(app.staticTexts["Nothing here yet"].waitForExistence(timeout: 20))
// The area banner is not decoration: it says where a new file will be
// filed, and it must be visible without looking for it.
XCTAssertTrue(app.staticTexts.containing(
NSPredicate(format: "label BEGINSWITH 'Working at'")).firstMatch.exists)
}
func testAFolderSurvivesARoundTrip() throws {
let name = handle
register(as: name)
XCTAssertTrue(app.staticTexts["Write this down now"].waitForExistence(timeout: 90))
app.buttons["I've written it down"].tap()
XCTAssertTrue(app.staticTexts["Nothing here yet"].waitForExistence(timeout: 20))
app.buttons["ellipsis.circle"].firstMatch.tap()
app.buttons["New folder"].tap()
let field = app.alerts.textFields.firstMatch
XCTAssertTrue(field.waitForExistence(timeout: 5))
field.typeText("Reports")
app.alerts.buttons["Create"].tap()
// The name comes back only if it encrypted, uploaded, listed and
// decrypted — the whole hierarchy, exercised by one tap.
XCTAssertTrue(app.staticTexts["Reports"].waitForExistence(timeout: 20))
}
}
+18
View File
@@ -73,3 +73,21 @@ The SwiftUI app is in progress.
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.
## Building the app
```bash
xcodegen generate # the .xcodeproj is generated, not committed
open FlamenetFiles.xcodeproj
```
`AppTests/` drives the real app against a real server, because the interesting
failures up here are wiring rather than cryptography — whether a button is
connected to the thing it claims to do. It expects a stack on
`http://127.0.0.1:8081`; the simulator shares the host's network, so
`docker compose up` in the public repository is enough.
```bash
xcodebuild -project FlamenetFiles.xcodeproj -scheme FlamenetFiles \
-destination 'platform=iOS Simulator,name=iPhone 17 Pro' test
```
+14
View File
@@ -100,15 +100,29 @@ public enum Wire {
public struct Level: Codable, Sendable, Hashable {
public let ordinal: Int16
public let name: String
public init(ordinal: Int16, name: String) {
self.ordinal = ordinal
self.name = name
}
}
public struct Compartment: Codable, Sendable, Hashable {
public let bit: Int
public let name: String
public init(bit: Int, name: String) {
self.bit = bit
self.name = name
}
}
public let levels: [Level]
public let compartments: [Compartment]
public let canEdit: Bool?
public init(levels: [Level] = [], compartments: [Compartment] = [], canEdit: Bool? = nil) {
self.levels = levels
self.compartments = compartments
self.canEdit = canEdit
}
public func name(for label: Label) -> String {
let level = levels.first { $0.ordinal == label.classification }?.name
?? "Level \(label.classification)"
+71
View File
@@ -0,0 +1,71 @@
# Generated with XcodeGen so the project file is not a merge hazard.
# `xcodegen generate` rebuilds it; the .xcodeproj is not committed.
name: FlamenetFiles
options:
bundleIdPrefix: io.flamenet
deploymentTarget:
iOS: "17.0"
createIntermediateGroups: true
packages:
FlamenetFiles:
path: .
targets:
FlamenetFiles:
type: application
platform: iOS
sources:
- path: App/Sources
- path: App/Resources
dependencies:
- package: FlamenetFiles
product: FilesEngine
- package: FlamenetFiles
product: FilesClient
info:
path: App/Info.plist
properties:
CFBundleDisplayName: Flamenet Files
CFBundleShortVersionString: "0.1"
CFBundleVersion: "1"
UILaunchScreen: {}
UISupportedInterfaceOrientations:
- UIInterfaceOrientationPortrait
# Declares that the app uses only encryption exempt under the standard
# note. Without it, every TestFlight build stops for a compliance
# questionnaire.
ITSAppUsesNonExemptEncryption: false
# HTTPS everywhere by default. The exception is localhost, so a
# developer can point the app at a stack running on their own machine
# without weakening anything that ships.
NSAppTransportSecurity:
NSAllowsLocalNetworking: true
settings:
base:
PRODUCT_BUNDLE_IDENTIFIER: io.flamenet.files
SWIFT_VERSION: "6.0"
TARGETED_DEVICE_FAMILY: "1,2"
ENABLE_USER_SCRIPT_SANDBOXING: YES
FlamenetFilesUITests:
type: bundle.ui-testing
platform: iOS
sources: [AppTests]
dependencies:
- target: FlamenetFiles
settings:
base:
PRODUCT_BUNDLE_IDENTIFIER: io.flamenet.files.uitests
schemes:
FlamenetFiles:
build:
targets:
FlamenetFiles: all
FlamenetFilesUITests: [test]
run:
config: Debug
test:
config: Debug
targets: [FlamenetFilesUITests]