From 93fa1a1622a55002f351065163a1fa78c4a01288 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 08:47:58 +0000 Subject: [PATCH 1/7] Sync the dictionary and snippets with iPhone, Android and other Macs End-to-end encrypted sync with no accounts: one device makes a secret, others pair by scanning its QR code or typing the code. HushtypeCore gets the shared format (SyncVocabulary with per-item merge and tombstones), the keys and AES-GCM sealing (SyncKeys) and the client (SyncClient). The Mac app adds a Your devices section in Settings > General. sync-server/ is the Cloudflare Worker + D1 server with tests and the protocol spec. iCloud sync leaves the dictionary and snippets alone while this is on. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01H6HfURkfdoEWCjjJLphzQX --- Sources/Hushtype/CloudSync.swift | 10 +- Sources/Hushtype/DeviceSync.swift | 188 ++++++++++++++++ Sources/Hushtype/DeviceSyncViews.swift | 210 ++++++++++++++++++ Sources/Hushtype/HushtypeApp.swift | 5 +- Sources/Hushtype/SettingsWindow.swift | 20 +- Sources/HushtypeCore/SyncClient.swift | 108 +++++++++ Sources/HushtypeCore/SyncCrypto.swift | 160 ++++++++++++++ Sources/HushtypeCore/SyncVocabulary.swift | 209 ++++++++++++++++++ Tests/HushtypeCoreTests/SyncTests.swift | 256 ++++++++++++++++++++++ sync-server/README.md | 89 ++++++++ sync-server/reference.mjs | 68 ++++++ sync-server/schema.sql | 9 + sync-server/src/index.js | 130 +++++++++++ sync-server/test.mjs | 80 +++++++ sync-server/wrangler.toml | 8 + 15 files changed, 1541 insertions(+), 9 deletions(-) create mode 100644 Sources/Hushtype/DeviceSync.swift create mode 100644 Sources/Hushtype/DeviceSyncViews.swift create mode 100644 Sources/HushtypeCore/SyncClient.swift create mode 100644 Sources/HushtypeCore/SyncCrypto.swift create mode 100644 Sources/HushtypeCore/SyncVocabulary.swift create mode 100644 Tests/HushtypeCoreTests/SyncTests.swift create mode 100644 sync-server/README.md create mode 100644 sync-server/reference.mjs create mode 100644 sync-server/schema.sql create mode 100644 sync-server/src/index.js create mode 100644 sync-server/test.mjs create mode 100644 sync-server/wrangler.toml diff --git a/Sources/Hushtype/CloudSync.swift b/Sources/Hushtype/CloudSync.swift index 8c24656..c9d9f59 100644 --- a/Sources/Hushtype/CloudSync.swift +++ b/Sources/Hushtype/CloudSync.swift @@ -100,11 +100,17 @@ final class CloudSync { private func push(_ value: Bool, _ key: String) { store.set(value, forKey: key) } private func push(_ value: String, _ key: String) { store.set(value, forKey: key) } + /// Hushtype device sync carries the dictionary and snippets when it's on. iCloud copies them + /// only by replacing the whole list, which would undo that sync's per-word merging. + private var deviceSyncOn: Bool { UserDefaults.standard.bool(forKey: DeviceSync.enabledKey) } + private func pushDictionary() { + guard !deviceSyncOn else { return } store.set(settings.dictionaryText, forKey: Key.dictionary) } private func pushSnippets() { + guard !deviceSyncOn else { return } if let data = try? JSONEncoder().encode(settings.snippets) { store.set(data, forKey: Key.snippets) } } @@ -120,14 +126,14 @@ final class CloudSync { DispatchQueue.main.async { [weak self] in self?.applyingRemote = false } } - if let remote = store.string(forKey: Key.dictionary) { + if !deviceSyncOn, let remote = store.string(forKey: Key.dictionary) { if merging { settings.addToDictionary(DictationPipeline.vocabulary(from: remote)) } else if remote != settings.dictionaryText { settings.dictionaryText = remote } } - if let data = store.data(forKey: Key.snippets), + if !deviceSyncOn, let data = store.data(forKey: Key.snippets), let remote = try? JSONDecoder().decode([Snippet].self, from: data) { let updated = merging ? SnippetSync.merge(settings.snippets, remote) : remote if updated != settings.snippets { settings.snippets = updated } diff --git a/Sources/Hushtype/DeviceSync.swift b/Sources/Hushtype/DeviceSync.swift new file mode 100644 index 0000000..4ce0989 --- /dev/null +++ b/Sources/Hushtype/DeviceSync.swift @@ -0,0 +1,188 @@ +import AppKit +import Combine +import HushtypeCore +import os + +/// Keeps the dictionary and snippets in step with the person's other devices (Macs, iPhone, +/// Android) through the Hushtype sync server. Everything is encrypted on this Mac with a secret +/// only the paired devices know; pairing hands that secret over as a QR code or a typed code. +@MainActor +final class DeviceSync: ObservableObject { + enum Status: Equatable { + case off + case syncing + case upToDate(Date) + case failed(String) + } + + /// Read by iCloud sync, which leaves the dictionary and snippets alone while this is on. + static let enabledKey = "deviceSyncEnabled" + private static let ledgerKey = "deviceSyncLedger" + private static let lastSyncKey = "deviceSyncLast" + private static let keychainAccount = "device-sync-secret" + private static let interval: Duration = .seconds(10 * 60) + + @Published private(set) var status: Status = .off + @Published private(set) var keys: SyncKeys? + + private let settings: SettingsStore + private let defaults = UserDefaults.standard + private let log = Logger(subsystem: "app.hushtype.Hushtype", category: "sync") + private var subscriptions: Set = [] + private var timer: Task? + private var wakeObserver: NSObjectProtocol? + private var running = false + private var runAgain = false + /// True while synced words are written into Settings, so that write doesn't start a sync. + private var applying = false + + init(settings: SettingsStore) { + self.settings = settings + if let secret = Keychain.read(account: Self.keychainAccount).flatMap({ Data(base64Encoded: $0) }) { + keys = SyncKeys(secret: secret) + } + if keys != nil, let last = defaults.object(forKey: Self.lastSyncKey) as? Date { status = .upToDate(last) } + defaults.set(keys != nil, forKey: Self.enabledKey) + + // Edits sync a couple of seconds after they settle. + settings.$dictionaryText.map { _ in () } + .merge(with: settings.$snippets.map { _ in () }) + .dropFirst(2) + .filter { [weak self] in self?.applying == false } + .debounce(for: .seconds(2), scheduler: DispatchQueue.main) + .sink { [weak self] in self?.syncNow() } + .store(in: &subscriptions) + wakeObserver = NSWorkspace.shared.notificationCenter.addObserver( + forName: NSWorkspace.didWakeNotification, object: nil, queue: .main + ) { [weak self] _ in + MainActor.assumeIsolated { self?.syncNow() } + } + startTimer() + syncNow() + } + + var isOn: Bool { keys != nil } + + // MARK: Turning it on and off + + /// Starts a new group with this Mac's words. Other devices join by scanning its code. + func turnOn() { + guard keys == nil else { return } + save(SyncKeys.generate()) + syncNow() + } + + /// Joins the group another device started. Throws, leaving sync off, when the code is wrong or + /// the server can't be reached. + func join(code: String) async throws { + guard let joined = SyncKeys(pairingCode: code) else { + throw PairingError.notACode + } + status = .syncing + let ledger = loadLedger().reconciled(terms: settings.vocabulary, snippets: settings.snippets) + do { + let merged = try await SyncClient(keys: joined).sync(ledger, joining: true) + save(joined) + apply(merged, startedFrom: ledger) + finished() + } catch { + status = keys == nil ? .off : status + throw error + } + } + + /// Stops syncing on this Mac. Its words stay; the other devices keep syncing with each other. + func turnOff() { + Keychain.delete(account: Self.keychainAccount) + defaults.removeObject(forKey: Self.ledgerKey) + defaults.removeObject(forKey: Self.lastSyncKey) + defaults.set(false, forKey: Self.enabledKey) + keys = nil + status = .off + } + + enum PairingError: LocalizedError { + case notACode + var errorDescription: String? { + "That isn't a Hushtype pairing code. It starts with HT1 and has 13 groups of four." + } + } + + private func save(_ new: SyncKeys) { + Keychain.write(new.secret.base64EncodedString(), account: Self.keychainAccount) + keys = new + defaults.set(true, forKey: Self.enabledKey) + } + + // MARK: Syncing + + func syncNow() { + guard let keys else { return } + if running { + runAgain = true + return + } + running = true + status = .syncing + let ledger = loadLedger().reconciled(terms: settings.vocabulary, snippets: settings.snippets) + Task { + defer { + running = false + if runAgain { + runAgain = false + syncNow() + } + } + do { + let merged = try await SyncClient(keys: keys).sync(ledger) + guard self.keys == keys else { return } + apply(merged, startedFrom: ledger) + finished() + } catch { + guard self.keys == keys else { return } + log.error("Sync failed: \(error.localizedDescription, privacy: .public)") + status = .failed(error.localizedDescription) + } + } + } + + /// Writes the merged words into Settings without losing edits made while the request was out: + /// those are folded in with newer timestamps and go up on the next round. + private func apply(_ merged: SyncVocabulary, startedFrom ledger: SyncVocabulary) { + let current = ledger.reconciled(terms: settings.vocabulary, snippets: settings.snippets) + let final = SyncVocabulary.merge(local: current, remote: merged) + saveLedger(final) + + let words = final.dictionary(keepingOrderOf: settings.vocabulary) + let snippets = final.snippetList(keepingOrderOf: settings.snippets) + applying = true + if words != settings.vocabulary { settings.dictionaryText = words.joined(separator: "\n") } + if snippets != settings.snippets { settings.snippets = snippets } + DispatchQueue.main.async { [weak self] in self?.applying = false } + if final != merged { runAgain = true } + } + + private func finished() { + let now = Date() + defaults.set(now, forKey: Self.lastSyncKey) + status = .upToDate(now) + } + + private func startTimer() { + timer = Task { [weak self] in + while !Task.isCancelled { + try? await Task.sleep(for: Self.interval) + self?.syncNow() + } + } + } + + private func loadLedger() -> SyncVocabulary { + defaults.data(forKey: Self.ledgerKey).flatMap { try? JSONDecoder().decode(SyncVocabulary.self, from: $0) } + ?? SyncVocabulary() + } + + private func saveLedger(_ ledger: SyncVocabulary) { + defaults.set(try? JSONEncoder().encode(ledger), forKey: Self.ledgerKey) + } +} diff --git a/Sources/Hushtype/DeviceSyncViews.swift b/Sources/Hushtype/DeviceSyncViews.swift new file mode 100644 index 0000000..2dccf45 --- /dev/null +++ b/Sources/Hushtype/DeviceSyncViews.swift @@ -0,0 +1,210 @@ +import AppKit +import CoreImage.CIFilterBuiltins +import HushtypeCore +import SwiftUI + +/// The "Your devices" section in Settings › General: turn sync on, show the pairing code to the +/// iPhone or Android app, or join with a code from another device. +struct DeviceSyncSection: View { + @ObservedObject var sync: DeviceSync + @State private var showingCode = false + @State private var joining = false + + var body: some View { + SectionLabel("Your devices") + SettingsCard { + if sync.isOn { + SettingsRow(title: "Dictionary and snippets sync", + subtitle: statusText, + symbol: "arrow.clockwise", + info: Self.privacyNote) { + if case .syncing = sync.status { + ProgressView().controlSize(.small) + } else { + Button("Sync Now") { sync.syncNow() } + } + } + SettingsRow(title: "Add a device", + subtitle: "Scan the code with Hushtype on your iPhone or Android, or type it on another Mac.", + symbol: "plus") { + Button("Show Pairing Code…") { showingCode = true } + .buttonStyle(.borderedProminent) + } + SettingsRow(title: "Stop syncing on this Mac", + subtitle: "Your words stay here. Your other devices keep syncing with each other.", + symbol: "power") { + Button("Turn Off") { sync.turnOff() } + } + } else { + SettingsRow(title: "Sync with your iPhone and Android", + subtitle: "Your dictionary and snippets, end-to-end encrypted. No account needed.", + symbol: "arrow.clockwise", + info: Self.privacyNote) { + HStack(spacing: 8) { + Button("Enter Code…") { joining = true } + Button("Turn On") { + sync.turnOn() + showingCode = true + } + .buttonStyle(.borderedProminent) + } + } + } + } + .sheet(isPresented: $showingCode) { + if let keys = sync.keys { PairingCodeSheet(keys: keys) } + } + .sheet(isPresented: $joining) { + JoinSheet(sync: sync) + } + } + + static let privacyNote = """ + Words are encrypted on your device with a key only your paired devices have, then stored on \ + Hushtype's sync server, which can't read them. Pairing hands that key over through the QR \ + code, so keep the code private. Your dictation key, history and Claude key never leave this Mac. + """ + + private var statusText: String { + switch sync.status { + case .off: return "Off" + case .syncing: return "Syncing…" + case .upToDate(let date): + if Date().timeIntervalSince(date) < 60 { return "Up to date" } + return "Up to date · synced \(date.formatted(.relative(presentation: .named)))" + case .failed(let message): return message + } + } +} + +/// The QR code and the typed code for adding another device. +private struct PairingCodeSheet: View { + let keys: SyncKeys + @Environment(\.dismiss) private var dismiss + @State private var copied = false + + var body: some View { + VStack(spacing: 18) { + VStack(spacing: 6) { + Text("Add a device").font(.title2.weight(.semibold)) + Text("In Hushtype on your iPhone or Android, open Settings › Sync and scan this code.") + .font(.callout) + .foregroundStyle(.secondary) + .multilineTextAlignment(.center) + .fixedSize(horizontal: false, vertical: true) + } + if let image = QRCode.image(for: keys.pairingCode) { + Image(nsImage: image) + .interpolation(.none) + .resizable() + .frame(width: 200, height: 200) + .padding(14) + .background(RoundedRectangle(cornerRadius: 16, style: .continuous).fill(.white)) + .overlay(RoundedRectangle(cornerRadius: 16, style: .continuous) + .strokeBorder(Color.hushViolet.opacity(0.5), lineWidth: 1)) + .shadow(color: Color.hushViolet.opacity(0.2), radius: 12, y: 4) + .accessibilityLabel("Pairing QR code") + } + VStack(spacing: 6) { + Text("On another Mac, type this code instead") + .font(.caption) + .foregroundStyle(.secondary) + Text(keys.pairingCode) + .font(.system(.callout, design: .monospaced)) + .textSelection(.enabled) + .multilineTextAlignment(.center) + .frame(width: 340) + .fixedSize(horizontal: false, vertical: true) + } + HStack { + Button(copied ? "Copied" : "Copy Code") { + NSPasteboard.general.clearContents() + NSPasteboard.general.setString(keys.pairingCode, forType: .string) + copied = true + } + Spacer() + Button("Done") { dismiss() } + .keyboardShortcut(.defaultAction) + .buttonStyle(.borderedProminent) + } + Text("Anyone with this code can read and change your dictionary. Only share it with your own devices.") + .font(.caption2) + .foregroundStyle(.tertiary) + .multilineTextAlignment(.center) + } + .padding(24) + .frame(width: 420) + .tint(.hushViolet) + } +} + +/// Typing a code from another Mac (or reading it off a phone). +private struct JoinSheet: View { + @ObservedObject var sync: DeviceSync + @Environment(\.dismiss) private var dismiss + @State private var code = "" + @State private var error: String? + @State private var working = false + + var body: some View { + VStack(alignment: .leading, spacing: 14) { + Text("Join your other devices").font(.title2.weight(.semibold)) + Text("On a device that already syncs, open Hushtype's sync settings, choose to show the pairing code, and type or paste it here. Your words here are merged with theirs.") + .font(.callout) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + TextField("HT1-XXXX-XXXX-…", text: $code, axis: .vertical) + .font(.system(.body, design: .monospaced)) + .textFieldStyle(.roundedBorder) + .lineLimit(2...3) + .onSubmit(join) + if let error { + Label(error, systemImage: "exclamationmark.triangle.fill") + .font(.caption) + .foregroundStyle(.orange) + .fixedSize(horizontal: false, vertical: true) + } + HStack { + Spacer() + Button("Cancel") { dismiss() } + .keyboardShortcut(.cancelAction) + Button(action: join) { + if working { ProgressView().controlSize(.small) } else { Text("Join") } + } + .keyboardShortcut(.defaultAction) + .buttonStyle(.borderedProminent) + .disabled(working || code.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + } + } + .padding(24) + .frame(width: 440) + .tint(.hushViolet) + } + + private func join() { + guard !working else { return } + working = true + error = nil + Task { + do { + try await sync.join(code: code) + dismiss() + } catch { + self.error = error.localizedDescription + } + working = false + } + } +} + +enum QRCode { + /// A crisp black-on-white QR code, one point per module (scale it up with `.interpolation(.none)`). + static func image(for text: String) -> NSImage? { + let filter = CIFilter.qrCodeGenerator() + filter.message = Data(text.utf8) + filter.correctionLevel = "M" + guard let output = filter.outputImage, + let cgImage = CIContext().createCGImage(output, from: output.extent) else { return nil } + return NSImage(cgImage: cgImage, size: output.extent.size) + } +} diff --git a/Sources/Hushtype/HushtypeApp.swift b/Sources/Hushtype/HushtypeApp.swift index 5b78c69..3c4619f 100644 --- a/Sources/Hushtype/HushtypeApp.swift +++ b/Sources/Hushtype/HushtypeApp.swift @@ -33,14 +33,17 @@ final class AppDelegate: NSObject, NSApplicationDelegate { private var permissionWatch: AnyCancellable? private var windowObservers: [NSObjectProtocol] = [] private lazy var cloudSync = CloudSync(settings: settings, controller: controller) + /// Dictionary and snippets with the person's iPhone, Android and other Macs. + lazy var deviceSync = DeviceSync(settings: settings) private lazy var onboardingWindow = OnboardingWindowController(settings: settings, controller: controller) private lazy var settingsWindow = SettingsWindowController(settings: settings, controller: controller, - updater: updater) { [weak self] in + updater: updater, deviceSync: deviceSync) { [weak self] in self?.showOnboarding() } func applicationDidFinishLaunching(_ notification: Notification) { _ = cloudSync + _ = deviceSync watchWindowsForDockIcon() controller.start() permissions.start(every: 2) diff --git a/Sources/Hushtype/SettingsWindow.swift b/Sources/Hushtype/SettingsWindow.swift index b56f5a7..05052fd 100644 --- a/Sources/Hushtype/SettingsWindow.swift +++ b/Sources/Hushtype/SettingsWindow.swift @@ -32,7 +32,7 @@ enum SettingsPane: String, CaseIterable, Identifiable { case .snippets: return "Say a phrase, and Hushtype types your saved text exactly as written." case .history: return "Your recent dictations, saved only on this Mac." case .permissions: return "Hushtype needs these to hear you and type for you." - case .general: return "Startup, setup and updates." + case .general: return "Startup, syncing with your devices, and updates." } } @@ -68,7 +68,7 @@ enum SettingsPane: String, CaseIterable, Identifiable { case .snippets: return ["shortcut", "expand", "text", "phrase"] case .history: return ["recent", "copy", "paste last", "search"] case .permissions: return ["accessibility", "input monitoring", "microphone", "privacy"] - case .general: return ["login", "startup", "setup", "updates", "version"] + case .general: return ["login", "startup", "setup", "updates", "version", "sync", "iphone", "android", "devices", "pair", "qr"] } } @@ -103,6 +103,7 @@ final class SettingsWindowController { private let settings: SettingsStore private let controller: DictationController private let updater: Updater + private let deviceSync: DeviceSync private let runSetup: () -> Void private let navigation = SettingsNavigation() private var window: NSWindow? @@ -110,10 +111,12 @@ final class SettingsWindowController { private var windowObservers: [NSObjectProtocol] = [] private var windowButtons: NSHostingView? - init(settings: SettingsStore, controller: DictationController, updater: Updater, runSetup: @escaping () -> Void) { + init(settings: SettingsStore, controller: DictationController, updater: Updater, deviceSync: DeviceSync, + runSetup: @escaping () -> Void) { self.settings = settings self.controller = controller self.updater = updater + self.deviceSync = deviceSync self.runSetup = runSetup } @@ -121,7 +124,7 @@ final class SettingsWindowController { func show(tab: String? = nil) { if window == nil { let root = SettingsRoot(navigation: navigation, settings: settings, controller: controller, - updater: updater, runSetup: runSetup) + updater: updater, deviceSync: deviceSync, runSetup: runSetup) let host = NSHostingController(rootView: root) host.sizingOptions = [] let window = NSWindow(contentViewController: host) @@ -234,6 +237,7 @@ private struct SettingsRoot: View { @ObservedObject var settings: SettingsStore @ObservedObject var controller: DictationController @ObservedObject var updater: Updater + let deviceSync: DeviceSync let runSetup: () -> Void @StateObject private var permissions = PermissionMonitor() @@ -273,7 +277,7 @@ private struct SettingsRoot: View { case .snippets: SnippetsPane(settings: settings) case .history: HistoryPane(settings: settings, controller: controller) case .permissions: PermissionsPane(controller: controller, permissions: permissions) - case .general: GeneralPane(settings: settings, updater: updater, runSetup: runSetup) + case .general: GeneralPane(settings: settings, updater: updater, deviceSync: deviceSync, runSetup: runSetup) } } } @@ -1348,6 +1352,7 @@ private struct PermissionsPane: View { private struct GeneralPane: View { @ObservedObject var settings: SettingsStore @ObservedObject var updater: Updater + @ObservedObject var deviceSync: DeviceSync let runSetup: () -> Void @State private var launchAtLogin = LaunchAtLogin.isEnabled @State private var keySyncError: String? @@ -1361,10 +1366,13 @@ private struct GeneralPane: View { Button("Run Setup Again…", action: runSetup) } } + DeviceSyncSection(sync: deviceSync) SectionLabel("iCloud") SettingsCard { ToggleRow(title: "Sync with iCloud", - subtitle: "Your dictionary, snippets and style settings follow you to your other Macs. The dictation key, microphone and history stay on this Mac.", + subtitle: deviceSync.isOn + ? "Your style settings follow you to your other Macs. Your dictionary and snippets sync with your devices above." + : "Your dictionary, snippets and style settings follow you to your other Macs. The dictation key, microphone and history stay on this Mac.", symbol: "icloud", isOn: $settings.iCloudSync) SettingsRow(title: "Include Anthropic API key", subtitle: keySyncError ?? "Kept in iCloud Keychain, end-to-end encrypted, so you only paste it once.", diff --git a/Sources/HushtypeCore/SyncClient.swift b/Sources/HushtypeCore/SyncClient.swift new file mode 100644 index 0000000..c27fc1b --- /dev/null +++ b/Sources/HushtypeCore/SyncClient.swift @@ -0,0 +1,108 @@ +import Foundation + +/// Talks to the Hushtype sync server: fetches the group's encrypted copy, merges it with this +/// device's, and writes the result back when it changed. Writes are compare-and-swap on the +/// server's version, so two devices syncing at once can't overwrite each other. +public struct SyncClient: Sendable { + /// The public server. Self-hosters can point the apps at their own copy of sync-server/. + public static let defaultServer = URL(string: "https://hushtype-sync.chiranjeeb.workers.dev")! + /// Matches the server's limit. + public static let maxBlobBytes = 512 * 1024 + + public let server: URL + public let keys: SyncKeys + private let session: URLSession + + public init(keys: SyncKeys, server: URL = SyncClient.defaultServer, session: URLSession = .shared) { + self.keys = keys + self.server = server + self.session = session + } + + private var groupURL: URL { server.appendingPathComponent("v1/groups/\(keys.groupID)") } + + /// One round: pull, merge, push if anything is new to the server. + /// - Parameters: + /// - local: this device's copy, already `reconciled` with its current words and snippets. + /// - joining: true when pairing with an existing group, which then has to exist. + /// - Returns: the merged copy, for the device to apply and keep. + public func sync(_ local: SyncVocabulary, joining: Bool = false) async throws -> SyncVocabulary { + var attempt = 0 + while true { + attempt += 1 + let remote = try await fetch() + if remote == nil, joining { throw SyncError.noSuchGroup } + let merged = (remote.map { SyncVocabulary.merge(local: local, remote: $0.vocabulary) } ?? local).compacted() + if let remote, remote.vocabulary == merged { return merged } + do { + try await store(merged, replacing: remote?.version) + return merged + } catch SyncError.server(412) where attempt < 4 { + // Another device wrote first; merge with its copy and try again. + continue + } + } + } + + struct Remote { + let vocabulary: SyncVocabulary + let version: String + } + + func fetch() async throws -> Remote? { + let (data, response) = try await send(authorized(groupURL)) + switch response.statusCode { + case 200: + guard let version = response.value(forHTTPHeaderField: "ETag") else { throw SyncError.badData } + return Remote(vocabulary: try keys.open(data), version: version) + case 404: + return nil + default: + throw Self.error(for: response.statusCode) + } + } + + func store(_ vocabulary: SyncVocabulary, replacing version: String?) async throws { + let blob = try keys.seal(vocabulary) + guard blob.count <= Self.maxBlobBytes else { throw SyncError.tooLarge } + var request = authorized(groupURL) + request.httpMethod = "PUT" + request.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type") + if let version { + request.setValue(version, forHTTPHeaderField: "If-Match") + } else { + request.setValue("*", forHTTPHeaderField: "If-None-Match") + } + request.httpBody = blob + let (_, response) = try await send(request) + guard (200..<300).contains(response.statusCode) else { throw Self.error(for: response.statusCode) } + } + + private func authorized(_ url: URL) -> URLRequest { + var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 20) + request.setValue("Bearer \(keys.authToken)", forHTTPHeaderField: "Authorization") + return request + } + + private func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) { + do { + let (data, response) = try await session.data(for: request) + guard let http = response as? HTTPURLResponse else { throw SyncError.offline } + return (data, http) + } catch let error as SyncError { + throw error + } catch is CancellationError { + throw CancellationError() + } catch { + throw SyncError.offline + } + } + + static func error(for status: Int) -> SyncError { + switch status { + case 401, 403: return .unauthorized + case 413: return .tooLarge + default: return .server(status) + } + } +} diff --git a/Sources/HushtypeCore/SyncCrypto.swift b/Sources/HushtypeCore/SyncCrypto.swift new file mode 100644 index 0000000..4318cda --- /dev/null +++ b/Sources/HushtypeCore/SyncCrypto.swift @@ -0,0 +1,160 @@ +import CryptoKit +import Foundation + +/// The secret a group of devices shares, and everything derived from it. One device makes the +/// secret; the others get it by scanning its QR code or typing its pairing code. The server only +/// ever sees the group id, a token that lets it check writes, and data it can't decrypt. +/// +/// sync-server/README.md describes the format for the Android app; keep the two in step. +public struct SyncKeys: Equatable, Sendable { + /// 32 random bytes. + public let secret: Data + + public init?(secret: Data) { + guard secret.count == 32 else { return nil } + self.secret = secret + } + + public static func generate() -> SyncKeys { + var bytes = [UInt8](repeating: 0, count: 32) + var generator = SystemRandomNumberGenerator() + for i in bytes.indices { bytes[i] = generator.next() } + return SyncKeys(secret: Data(bytes))! + } + + private func derive(_ label: String) -> SymmetricKey { + HKDF.deriveKey(inputKeyMaterial: SymmetricKey(data: secret), + salt: Data("hushtype-sync-v1".utf8), + info: Data(label.utf8), + outputByteCount: 32) + } + + private static func bytes(_ key: SymmetricKey) -> Data { key.withUnsafeBytes { Data($0) } } + + /// Names the group on the server: 32 lowercase hex characters. + public var groupID: String { + Self.bytes(derive("group-id")).prefix(16).map { String(format: "%02x", $0) }.joined() + } + + /// Sent as a bearer token. The server keeps only its SHA-256, set by the first write. + public var authToken: String { Self.base64URL(Self.bytes(derive("auth"))) } + + private var encryptionKey: SymmetricKey { derive("encryption") } + + // MARK: Pairing code + + /// What the QR code holds and what people type on a Mac: "HT1-" and the secret in Crockford + /// base32, in groups of four. + public var pairingCode: String { + let body = Self.crockford(secret) + var groups: [String] = [] + var rest = Substring(body) + while !rest.isEmpty { + groups.append(String(rest.prefix(4))) + rest = rest.dropFirst(4) + } + return "HT1-" + groups.joined(separator: "-") + } + + /// Reads a pairing code, forgiving case, spaces, dashes and look-alike letters (O for 0, I and L + /// for 1). Nil when it isn't one. + public init?(pairingCode: String) { + var cleaned = pairingCode.uppercased().filter { $0.isLetter || $0.isNumber } + guard cleaned.hasPrefix("HT1") else { return nil } + cleaned.removeFirst(3) + guard let data = Self.decodeCrockford(cleaned), data.count == 32 else { return nil } + self.init(secret: data) + } + + private static let alphabet = Array("0123456789ABCDEFGHJKMNPQRSTVWXYZ") + + static func crockford(_ data: Data) -> String { + var output = "" + var buffer: UInt32 = 0 + var bits = 0 + for byte in data { + buffer = (buffer << 8) | UInt32(byte) + bits += 8 + while bits >= 5 { + output.append(alphabet[Int((buffer >> UInt32(bits - 5)) & 31)]) + bits -= 5 + } + } + if bits > 0 { output.append(alphabet[Int((buffer << UInt32(5 - bits)) & 31)]) } + return output + } + + static func decodeCrockford(_ text: String) -> Data? { + var bytes: [UInt8] = [] + var buffer: UInt32 = 0 + var bits = 0 + for character in text { + let normalized: Character + switch character { + case "O": normalized = "0" + case "I", "L": normalized = "1" + default: normalized = character + } + guard let value = alphabet.firstIndex(of: normalized) else { return nil } + buffer = (buffer << 5) | UInt32(value) + bits += 5 + if bits >= 8 { + bytes.append(UInt8((buffer >> UInt32(bits - 8)) & 0xFF)) + bits -= 8 + } + } + return Data(bytes) + } + + static func base64URL(_ data: Data) -> String { + data.base64EncodedString() + .replacingOccurrences(of: "+", with: "-") + .replacingOccurrences(of: "/", with: "_") + .replacingOccurrences(of: "=", with: "") + } + + // MARK: Sealing + + /// Format version 1: one byte 0x01, the 12-byte nonce, the ciphertext, the 16-byte tag. The + /// group id is bound in as associated data, so a blob can't be moved to another group. + public func seal(_ vocabulary: SyncVocabulary) throws -> Data { + let plain = try JSONEncoder().encode(vocabulary) + let box = try AES.GCM.seal(plain, using: encryptionKey, authenticating: Data(groupID.utf8)) + guard let combined = box.combined else { throw SyncError.badData } + return Data([1]) + combined + } + + public func open(_ blob: Data) throws -> SyncVocabulary { + guard blob.count > 1 + 12 + 16, blob.first == 1 else { throw SyncError.badData } + do { + let box = try AES.GCM.SealedBox(combined: blob.dropFirst()) + let plain = try AES.GCM.open(box, using: encryptionKey, authenticating: Data(groupID.utf8)) + return try JSONDecoder().decode(SyncVocabulary.self, from: plain) + } catch { + throw SyncError.badData + } + } +} + +public enum SyncError: LocalizedError, Equatable, Sendable { + /// The pairing code doesn't match any devices yet. + case noSuchGroup + /// The server refused the token. + case unauthorized + /// Couldn't decrypt or read what the server sent. + case badData + case tooLarge + case server(Int) + case offline + + public var errorDescription: String? { + switch self { + case .noSuchGroup: return "No device is using that pairing code. Check it, or start sync on the other device first." + case .unauthorized: return "The sync server didn't accept this device. Pair it again." + case .badData: return "The synced data couldn't be read. Pair this device again." + case .tooLarge: return "Your dictionary and snippets are too large to sync." + case .server(let status): return "The sync server had a problem (\(status)). Hushtype will try again." + case .offline: return "Couldn't reach the sync server. Hushtype will try again." + } + } +} diff --git a/Sources/HushtypeCore/SyncVocabulary.swift b/Sources/HushtypeCore/SyncVocabulary.swift new file mode 100644 index 0000000..97775d3 --- /dev/null +++ b/Sources/HushtypeCore/SyncVocabulary.swift @@ -0,0 +1,209 @@ +import Foundation + +/// The dictionary and snippets as they travel between devices (Mac, iPhone, Android). Every item +/// carries its own timestamps and a removal is kept as a tombstone, so two devices can merge their +/// copies item by item and a word removed on one stays removed on the others. +/// +/// The JSON shape is shared with the Android app; see sync-server/README.md before changing a field name. +public struct SyncVocabulary: Codable, Equatable, Sendable { + public struct Term: Codable, Equatable, Sendable { + public var text: String + /// Epoch milliseconds. + public var createdAt: Int64 + public var updatedAt: Int64 + public var deleted: Bool + /// Added by learning from a correction, not typed in by hand. + public var learned: Bool + + public init(text: String, createdAt: Int64, updatedAt: Int64, deleted: Bool = false, learned: Bool = false) { + self.text = text + self.createdAt = createdAt + self.updatedAt = updatedAt + self.deleted = deleted + self.learned = learned + } + + /// Two devices that add the same word agree on this. + public var key: String { Self.key(text) } + public static func key(_ text: String) -> String { text.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() } + } + + public struct SyncSnippet: Codable, Equatable, Sendable { + /// A UUID string. Upper or lower case both match. + public var id: String + public var trigger: String + public var expansion: String + public var createdAt: Int64 + public var updatedAt: Int64 + public var deleted: Bool + + public init(id: String, trigger: String, expansion: String, createdAt: Int64, updatedAt: Int64, + deleted: Bool = false) { + self.id = id + self.trigger = trigger + self.expansion = expansion + self.createdAt = createdAt + self.updatedAt = updatedAt + self.deleted = deleted + } + + public var key: String { id.lowercased() } + } + + public var terms: [Term] + public var snippets: [SyncSnippet] + + public init(terms: [Term] = [], snippets: [SyncSnippet] = []) { + self.terms = terms + self.snippets = snippets + } + + /// Tombstones older than this are dropped. A device offline for longer may bring a removed + /// word back, which beats keeping every removal forever. + public static let tombstoneLifetime: Int64 = 30 * 24 * 60 * 60 * 1000 + + public static func now() -> Int64 { Int64((Date().timeIntervalSince1970 * 1000).rounded()) } + + public var liveTerms: [Term] { terms.filter { !$0.deleted } } + public var liveSnippets: [SyncSnippet] { snippets.filter { !$0.deleted } } + + // MARK: Merge + + /// Combines two copies item by item: the newer `updatedAt` wins, and on a tie `local` wins. + /// Items keep the order they have in `local`, with items only `remote` has after them. + public static func merge(local: SyncVocabulary, remote: SyncVocabulary) -> SyncVocabulary { + SyncVocabulary(terms: mergeItems(local.terms, remote.terms, key: \.key, updated: \.updatedAt), + snippets: mergeItems(local.snippets, remote.snippets, key: \.key, updated: \.updatedAt)) + } + + private static func mergeItems(_ local: [Item], _ remote: [Item], key: (Item) -> String, + updated: (Item) -> Int64) -> [Item] { + var remoteByKey: [String: Item] = [:] + for item in remote { + let k = key(item) + if let existing = remoteByKey[k], updated(existing) >= updated(item) { continue } + remoteByKey[k] = item + } + var result: [Item] = [] + var seen = Set() + for item in local { + let k = key(item) + guard seen.insert(k).inserted else { continue } + if let theirs = remoteByKey[k], updated(theirs) > updated(item) { + result.append(theirs) + } else { + result.append(item) + } + } + for item in remote { + let k = key(item) + guard seen.insert(k).inserted, let best = remoteByKey[k] else { continue } + result.append(best) + } + return result + } + + /// Drops tombstones older than `tombstoneLifetime`. + public func compacted(now: Int64 = SyncVocabulary.now()) -> SyncVocabulary { + let cutoff = now - Self.tombstoneLifetime + return SyncVocabulary(terms: terms.filter { !$0.deleted || $0.updatedAt >= cutoff }, + snippets: snippets.filter { !$0.deleted || $0.updatedAt >= cutoff }) + } + + // MARK: Following local edits + + /// Brings this record up to date with the device's current dictionary and snippets: new items + /// are added, changed ones get a new `updatedAt`, and items that are gone become tombstones. + /// Call it before every merge, so edits made while sync was off still count. + public func reconciled(terms current: [String], snippets currentSnippets: [Snippet], + learned: Set = [], now: Int64 = SyncVocabulary.now()) -> SyncVocabulary { + var result = self + + var index: [String: Int] = [:] + for (i, term) in result.terms.enumerated() where index[term.key] == nil { index[term.key] = i } + var present = Set() + for text in current { + let clean = text.trimmingCharacters(in: .whitespacesAndNewlines) + let key = Term.key(clean) + guard !key.isEmpty, present.insert(key).inserted else { continue } + if let i = index[key] { + if result.terms[i].deleted || result.terms[i].text != clean { + result.terms[i].text = clean + result.terms[i].deleted = false + result.terms[i].updatedAt = max(now, result.terms[i].updatedAt + 1) + } + } else { + index[key] = result.terms.count + result.terms.append(Term(text: clean, createdAt: now, updatedAt: now, learned: learned.contains(key))) + } + } + for i in result.terms.indices where !result.terms[i].deleted && !present.contains(result.terms[i].key) { + result.terms[i].deleted = true + result.terms[i].updatedAt = max(now, result.terms[i].updatedAt + 1) + } + + var snippetIndex: [String: Int] = [:] + for (i, snippet) in result.snippets.enumerated() where snippetIndex[snippet.key] == nil { + snippetIndex[snippet.key] = i + } + var presentSnippets = Set() + for snippet in currentSnippets { + let key = snippet.id.uuidString.lowercased() + guard presentSnippets.insert(key).inserted else { continue } + if let i = snippetIndex[key] { + let old = result.snippets[i] + if old.deleted || old.trigger != snippet.trigger || old.expansion != snippet.expansion { + result.snippets[i].trigger = snippet.trigger + result.snippets[i].expansion = snippet.expansion + result.snippets[i].deleted = false + result.snippets[i].updatedAt = max(now, old.updatedAt + 1) + } + } else { + snippetIndex[key] = result.snippets.count + result.snippets.append(SyncSnippet(id: key, trigger: snippet.trigger, expansion: snippet.expansion, + createdAt: now, updatedAt: now)) + } + } + for i in result.snippets.indices + where !result.snippets[i].deleted && !presentSnippets.contains(result.snippets[i].key) { + result.snippets[i].deleted = true + result.snippets[i].updatedAt = max(now, result.snippets[i].updatedAt + 1) + } + return result + } + + /// The device's dictionary after a merge: the words it already had, in their order, minus + /// removed ones, then new words. Spelling follows the merged copy. + public func dictionary(keepingOrderOf current: [String]) -> [String] { + var live: [String: String] = [:] + for term in liveTerms where live[term.key] == nil { live[term.key] = term.text } + var result: [String] = [] + var used = Set() + for text in current { + let key = Term.key(text) + guard let spelled = live[key], used.insert(key).inserted else { continue } + result.append(spelled) + } + for term in liveTerms where used.insert(term.key).inserted { result.append(term.text) } + return result + } + + /// The device's snippets after a merge, in the same spirit as `dictionary(keepingOrderOf:)`. + /// Snippets whose id isn't a UUID (never written by Hushtype) are skipped. + public func snippetList(keepingOrderOf current: [Snippet]) -> [Snippet] { + var live: [String: SyncSnippet] = [:] + for snippet in liveSnippets where live[snippet.key] == nil { live[snippet.key] = snippet } + var result: [Snippet] = [] + var used = Set() + for snippet in current { + let key = snippet.id.uuidString.lowercased() + guard let synced = live[key], used.insert(key).inserted else { continue } + result.append(Snippet(id: snippet.id, trigger: synced.trigger, expansion: synced.expansion)) + } + for synced in liveSnippets where used.insert(synced.key).inserted { + guard let id = UUID(uuidString: synced.id) else { continue } + result.append(Snippet(id: id, trigger: synced.trigger, expansion: synced.expansion)) + } + return result + } +} diff --git a/Tests/HushtypeCoreTests/SyncTests.swift b/Tests/HushtypeCoreTests/SyncTests.swift new file mode 100644 index 0000000..487c76f --- /dev/null +++ b/Tests/HushtypeCoreTests/SyncTests.swift @@ -0,0 +1,256 @@ +import Foundation +import XCTest +@testable import HushtypeCore + +final class SyncFormatTests: XCTestCase { + /// Test vector from `node sync-server/reference.mjs`. Android checks the same values. + let secret = Data(0..<32) + + func testDerivedValuesMatchReference() throws { + let keys = try XCTUnwrap(SyncKeys(secret: secret)) + XCTAssertEqual(keys.groupID, "8187ad2336c78c03a3802eb930117608") + XCTAssertEqual(keys.authToken, "5ZN7bna256_f6Ck-1W9euZAu54gAfn1DpAFt9HDKQzU") + XCTAssertEqual(keys.pairingCode, + "HT1-000G-40R4-0M30-E209-185G-R38E-1W81-24GK-2GAH-C5RR-34D1-P70X-3RFG") + } + + func testOpensBlobSealedByReference() throws { + let keys = try XCTUnwrap(SyncKeys(secret: secret)) + let blob = try XCTUnwrap(Data(base64Encoded: "AaChoqOkpaanqKmqq+w8k+U+nxPol7F8T1tCZASQ3/wy82AKchj2R7iDTY3TQIs69xlgRBb1L4rvJ9CKbwB2oHzinE3YmwlvqkSy4Br2oO6oUcsrrfBFr4jElm2vJ+0h+N48uLG4htgtB4jJ+bO+d2k7FNX8HiQnMoCsb4g4ikGQ5MZ6kEwYrIsRrHUWko0gnGbMoV7RK/YwS7/FBd/lMCINf7y4FK623S9TPlSEY0BvqR0NmnKx76YEuUWi1fB4ZNsBC6HPqsWebIvCnldejMu0i92FFo8Fq2GF5c95NXZ+C73lyK3166w0ObXGZZvNXxmnn7/nY2SxMF8RXzo4JGojx+gebk227qUz0jDx56mPtqcdNtzp6s7jXkzpG+DTHTA20TAkLmmeTipmAMH+VRILGTozFnPhkEk2EobL1nqEtpif")) + let vocabulary = try keys.open(blob) + XCTAssertEqual(vocabulary.terms, [SyncVocabulary.Term(text: "Kubernetes", createdAt: 1763100000000, + updatedAt: 1763100000000, learned: true)]) + XCTAssertEqual(vocabulary.snippets.first?.trigger, "my link") + XCTAssertEqual(vocabulary.snippets.first?.updatedAt, 1763100000001) + } + + func testSealRoundTripAndTamperDetection() throws { + let keys = SyncKeys.generate() + let vocabulary = SyncVocabulary(terms: [.init(text: "Hushtype", createdAt: 1, updatedAt: 2)]) + var blob = try keys.seal(vocabulary) + XCTAssertEqual(try keys.open(blob), vocabulary) + XCTAssertThrowsError(try SyncKeys.generate().open(blob)) + blob[blob.count - 1] ^= 1 + XCTAssertThrowsError(try keys.open(blob)) + } + + func testPairingCodeIsForgiving() throws { + let keys = SyncKeys.generate() + let code = keys.pairingCode + XCTAssertEqual(SyncKeys(pairingCode: code), keys) + XCTAssertEqual(SyncKeys(pairingCode: code.lowercased().replacingOccurrences(of: "-", with: " ")), keys) + let lookAlike = "HT1" + code.dropFirst(3).replacingOccurrences(of: "0", with: "O").replacingOccurrences(of: "1", with: "l") + XCTAssertEqual(SyncKeys(pairingCode: lookAlike), keys) + XCTAssertNil(SyncKeys(pairingCode: "HT1-1234")) + XCTAssertNil(SyncKeys(pairingCode: "hello")) + } +} + +final class SyncVocabularyTests: XCTestCase { + typealias Term = SyncVocabulary.Term + + func testNewerEditWinsAndTieKeepsLocal() { + let local = SyncVocabulary(terms: [Term(text: "kubernetes", createdAt: 1, updatedAt: 5), + Term(text: "Jena", createdAt: 1, updatedAt: 3)]) + let remote = SyncVocabulary(terms: [Term(text: "Kubernetes", createdAt: 1, updatedAt: 6), + Term(text: "jena", createdAt: 1, updatedAt: 3), + Term(text: "Swift", createdAt: 2, updatedAt: 2)]) + let merged = SyncVocabulary.merge(local: local, remote: remote) + XCTAssertEqual(merged.terms.map(\.text), ["Kubernetes", "Jena", "Swift"]) + } + + func testRemovalSticksUntilReAdded() { + let local = SyncVocabulary(terms: [Term(text: "Foo", createdAt: 1, updatedAt: 1)]) + let remote = SyncVocabulary(terms: [Term(text: "Foo", createdAt: 1, updatedAt: 4, deleted: true)]) + let merged = SyncVocabulary.merge(local: local, remote: remote) + XCTAssertEqual(merged.dictionary(keepingOrderOf: ["Foo", "Bar"]), []) + + let readded = merged.reconciled(terms: ["Foo"], snippets: [], now: 10) + XCTAssertEqual(readded.liveTerms.map(\.text), ["Foo"]) + XCTAssertEqual(SyncVocabulary.merge(local: remote, remote: readded).liveTerms.map(\.text), ["Foo"]) + } + + func testReconcileFollowsLocalEdits() { + let id = UUID() + let start = SyncVocabulary().reconciled(terms: ["Alpha", "Beta", "beta"], + snippets: [Snippet(id: id, trigger: "sig", expansion: "Thanks")], + learned: ["beta"], now: 100) + XCTAssertEqual(start.terms.map(\.text), ["Alpha", "Beta"]) + XCTAssertEqual(start.terms.map(\.learned), [false, true]) + XCTAssertEqual(start.snippets.first?.id, id.uuidString.lowercased()) + + let unchanged = start.reconciled(terms: ["Alpha", "Beta"], + snippets: [Snippet(id: id, trigger: "sig", expansion: "Thanks")], now: 200) + XCTAssertEqual(unchanged, start) + + let edited = start.reconciled(terms: ["Beta"], snippets: [Snippet(id: id, trigger: "sig", expansion: "Cheers")], + now: 300) + XCTAssertEqual(edited.terms.first { $0.text == "Alpha" }?.deleted, true) + XCTAssertEqual(edited.terms.first { $0.text == "Alpha" }?.updatedAt, 300) + XCTAssertEqual(edited.snippets.first?.expansion, "Cheers") + XCTAssertEqual(edited.snippets.first?.updatedAt, 300) + } + + func testApplyingKeepsLocalOrder() { + let id = UUID() + let vocabulary = SyncVocabulary( + terms: [Term(text: "New", createdAt: 1, updatedAt: 1), Term(text: "kept", createdAt: 1, updatedAt: 1), + Term(text: "Gone", createdAt: 1, updatedAt: 2, deleted: true)], + snippets: [.init(id: id.uuidString.lowercased(), trigger: "t", expansion: "e", createdAt: 1, updatedAt: 1)]) + XCTAssertEqual(vocabulary.dictionary(keepingOrderOf: ["Gone", "Kept"]), ["kept", "New"]) + XCTAssertEqual(vocabulary.snippetList(keepingOrderOf: []).map(\.id), [id]) + } + + func testCompactionDropsOldTombstones() { + let now: Int64 = SyncVocabulary.tombstoneLifetime + 1000 + let vocabulary = SyncVocabulary(terms: [Term(text: "old", createdAt: 0, updatedAt: 1, deleted: true), + Term(text: "recent", createdAt: 0, updatedAt: now, deleted: true), + Term(text: "live", createdAt: 0, updatedAt: 1)]) + XCTAssertEqual(vocabulary.compacted(now: now).terms.map(\.text), ["recent", "live"]) + } + + func testJSONFieldNamesMatchAndroid() throws { + let vocabulary = SyncVocabulary(terms: [Term(text: "a", createdAt: 1, updatedAt: 2)], + snippets: [.init(id: "x", trigger: "t", expansion: "e", createdAt: 1, updatedAt: 2)]) + let json = try XCTUnwrap(JSONSerialization.jsonObject(with: JSONEncoder().encode(vocabulary)) as? [String: Any]) + let term = try XCTUnwrap((json["terms"] as? [[String: Any]])?.first) + XCTAssertEqual(Set(term.keys), ["text", "createdAt", "updatedAt", "deleted", "learned"]) + let snippet = try XCTUnwrap((json["snippets"] as? [[String: Any]])?.first) + XCTAssertEqual(Set(snippet.keys), ["id", "trigger", "expansion", "createdAt", "updatedAt", "deleted"]) + } +} + +/// A stand-in for the sync server, with the same compare-and-swap rules. +final class FakeSyncServer: URLProtocol, @unchecked Sendable { + nonisolated(unsafe) static var blob: Data? + nonisolated(unsafe) static var version = 0 + nonisolated(unsafe) static var token: String? + /// Writes another device's copy right before the next PUT lands, to force a conflict. + nonisolated(unsafe) static var interleave: (() -> Void)? + static let lock = NSLock() + + static func reset() { + lock.withLock { blob = nil; version = 0; token = nil; interleave = nil } + } + + override class func canInit(with request: URLRequest) -> Bool { true } + override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } + override func stopLoading() {} + + override func startLoading() { + let (status, body, etag) = Self.lock.withLock { () -> (Int, Data?, String?) in + let auth = request.value(forHTTPHeaderField: "Authorization") + if let token = Self.token, auth != token { return (401, nil, nil) } + switch request.httpMethod { + case "GET": + guard let blob = Self.blob else { return (404, nil, nil) } + return (200, blob, "\"\(Self.version)\"") + case "PUT": + if let interleave = Self.interleave { + Self.interleave = nil + interleave() + } + let data = request.httpBody ?? Self.read(request.httpBodyStream) + if request.value(forHTTPHeaderField: "If-None-Match") == "*" { + guard Self.blob == nil else { return (412, nil, nil) } + } else if request.value(forHTTPHeaderField: "If-Match") != "\"\(Self.version)\"" { + return (412, nil, nil) + } + Self.blob = data + Self.version += 1 + Self.token = auth + return (204, nil, "\"\(Self.version)\"") + default: + return (405, nil, nil) + } + } + var headers: [String: String] = [:] + if let etag { headers["ETag"] = etag } + let response = HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: nil, headerFields: headers)! + client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + client?.urlProtocol(self, didLoad: body ?? Data()) + client?.urlProtocolDidFinishLoading(self) + } + + private static func read(_ stream: InputStream?) -> Data { + guard let stream else { return Data() } + stream.open() + defer { stream.close() } + var data = Data() + var buffer = [UInt8](repeating: 0, count: 4096) + while stream.hasBytesAvailable { + let count = stream.read(&buffer, maxLength: buffer.count) + if count <= 0 { break } + data.append(buffer, count: count) + } + return data + } +} + +final class SyncClientTests: XCTestCase { + var session: URLSession! + + override func setUp() { + FakeSyncServer.reset() + let configuration = URLSessionConfiguration.ephemeral + configuration.protocolClasses = [FakeSyncServer.self] + session = URLSession(configuration: configuration) + } + + func client(_ keys: SyncKeys) -> SyncClient { + SyncClient(keys: keys, server: URL(string: "https://sync.test")!, session: session) + } + + func testTwoDevicesConverge() async throws { + let keys = SyncKeys.generate() + let mac = SyncVocabulary().reconciled(terms: ["Kubernetes"], snippets: [], now: 10) + let phone = SyncVocabulary().reconciled(terms: ["Chiranjeeb"], snippets: [], now: 20) + + let afterMac = try await client(keys).sync(mac) + XCTAssertEqual(afterMac.liveTerms.map(\.text), ["Kubernetes"]) + + let afterPhone = try await client(keys).sync(phone, joining: true) + XCTAssertEqual(Set(afterPhone.liveTerms.map(\.text)), ["Kubernetes", "Chiranjeeb"]) + + let macAgain = try await client(keys).sync(afterMac) + XCTAssertEqual(Set(macAgain.liveTerms.map(\.text)), ["Kubernetes", "Chiranjeeb"]) + } + + func testJoiningUnknownGroupFails() async { + do { + _ = try await client(SyncKeys.generate()).sync(SyncVocabulary(), joining: true) + XCTFail("Expected noSuchGroup") + } catch { + XCTAssertEqual(error as? SyncError, .noSuchGroup) + } + } + + func testRetriesAfterConflict() async throws { + let keys = SyncKeys.generate() + let other = SyncVocabulary().reconciled(terms: ["Other"], snippets: [], now: 5) + _ = try await client(keys).sync(SyncVocabulary().reconciled(terms: ["First"], snippets: [], now: 1)) + let otherBlob = try keys.seal(SyncVocabulary.merge( + local: other, remote: SyncVocabulary().reconciled(terms: ["First"], snippets: [], now: 1))) + FakeSyncServer.interleave = { + FakeSyncServer.blob = otherBlob + FakeSyncServer.version += 1 + } + let mine = SyncVocabulary().reconciled(terms: ["First", "Mine"], snippets: [], now: 9) + let merged = try await client(keys).sync(mine) + XCTAssertEqual(Set(merged.liveTerms.map(\.text)), ["First", "Other", "Mine"]) + let stored = try keys.open(try XCTUnwrap(FakeSyncServer.blob)) + XCTAssertEqual(Set(stored.liveTerms.map(\.text)), ["First", "Other", "Mine"]) + } + + func testWrongTokenIsUnauthorized() async throws { + let keys = SyncKeys.generate() + _ = try await client(keys).sync(SyncVocabulary().reconciled(terms: ["A"], snippets: [], now: 1)) + FakeSyncServer.lock.withLock { FakeSyncServer.token = "Bearer something-else" } + do { + _ = try await client(keys).sync(SyncVocabulary()) + XCTFail("Expected unauthorized") + } catch { + XCTAssertEqual(error as? SyncError, .unauthorized) + } + } +} diff --git a/sync-server/README.md b/sync-server/README.md new file mode 100644 index 0000000..836e9f6 --- /dev/null +++ b/sync-server/README.md @@ -0,0 +1,89 @@ +# Hushtype sync + +Keeps the dictionary and snippets in step across a person's Macs, iPhone and Android phone. There are no +accounts. One device makes a random secret and the others get it by scanning a QR code (or typing the +code on a Mac). Everything is encrypted on the device with keys derived from that secret, so this server +only ever stores data it can't read. + +The Swift side lives in `Sources/HushtypeCore/Sync*.swift` and the Android side in hushtype-android's +`data/VocabularyRepository.kt`. **Change all of them together.** `reference.mjs` prints the test +vectors that both test suites check. + +## Pairing code + +- The secret is 32 random bytes. +- The pairing code is `HT1-` followed by the secret in [Crockford base32](https://www.crockford.com/base32.html) + (alphabet `0123456789ABCDEFGHJKMNPQRSTVWXYZ`, no padding, 52 characters), in dash-separated groups of four. + The QR code holds exactly this text. +- When reading a code, ignore case and anything that isn't a letter or digit, and read `O` as `0` and + `I`/`L` as `1`. It must start with `HT1` and decode to 32 bytes. + +## Keys + +All three come from HKDF-SHA256 with the secret as input key material, the salt `hushtype-sync-v1` (UTF-8) +and 32 bytes of output. Only the `info` label differs: + +| info | use | +| --- | --- | +| `group-id` | first 16 bytes, lowercase hex (32 characters): the group's id on the server | +| `auth` | base64url without padding (43 characters): sent as `Authorization: Bearer …` | +| `encryption` | the AES-256-GCM key | + +## Blob + +The server stores one blob per group: byte `0x01`, then a random 12-byte nonce, the AES-256-GCM ciphertext +and the 16-byte tag. The associated data is the group id (its 32 hex characters, UTF-8). The plaintext is +UTF-8 JSON: + +```json +{ + "terms": [ + {"text": "Kubernetes", "createdAt": 1763100000000, "updatedAt": 1763100000000, "deleted": false, "learned": true} + ], + "snippets": [ + {"id": "6f1c2b8e-1d5a-4c1e-9a77-1b2c3d4e5f60", "trigger": "my link", "expansion": "https://cal.com/x", + "createdAt": 1763100000000, "updatedAt": 1763100000001, "deleted": false} + ] +} +``` + +Times are epoch milliseconds. Ignore unknown fields so later versions can add some. + +## Merging + +- A term's key is its text, trimmed and lowercased. A snippet's key is its id, lowercased. +- For each key, the item with the larger `updatedAt` wins. On a tie, the device's own copy wins. +- A removal is a tombstone (`deleted: true` with a new `updatedAt`), never a missing item. +- Tombstones older than 30 days are dropped before uploading. +- Every local add, edit or removal sets `updatedAt` to now (and always to more than the old value). + +## Server API + +`GET /v1/groups/{groupId}`, with the bearer token: +- `200` with the blob and `ETag: ""` +- `404` when no device has written yet +- `401` when the token doesn't match the one that created the group + +`PUT /v1/groups/{groupId}`, with the bearer token and the blob as the body (at most 512 KB): +- With `If-None-Match: *`, it creates the group. The token's SHA-256 is stored, and later requests must use the same token. +- With `If-Match: ""`, it replaces the blob only if nothing changed since that version. +- Returns `204` with the new `ETag`, `412` if someone else wrote first (fetch, merge and try again), + `401`, `413` or `428` (no condition header). + +A device syncs like this. Fetch the blob. Merge it with the device's own copy and apply the result locally. +If the result differs from what the server had, `PUT` it with the version you read. If that returns `412`, +start over. Sync on launch, a couple of seconds after a local edit, and every few minutes while the app runs. + +## Running the server + +It's a Cloudflare Worker with a D1 database. + +```sh +cd sync-server +npx wrangler d1 create hushtype-sync # put the database_id in wrangler.toml +npx wrangler d1 execute hushtype-sync --remote --file=schema.sql +npx wrangler deploy +node --test test.mjs # tests, with SQLite standing in for D1 +``` + +To use your own server, point `SyncClient.defaultServer` (and the Android equivalent) at it. diff --git a/sync-server/reference.mjs b/sync-server/reference.mjs new file mode 100644 index 0000000..bcd4ce6 --- /dev/null +++ b/sync-server/reference.mjs @@ -0,0 +1,68 @@ +// A small reference of the sync format in plain JavaScript, used to make test vectors that the +// Swift and Kotlin tests check against: node sync-server/reference.mjs +import { hkdfSync, createCipheriv, createDecipheriv } from "node:crypto"; + +const ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; + +export function derive(secret, label) { + return Buffer.from(hkdfSync("sha256", secret, Buffer.from("hushtype-sync-v1"), Buffer.from(label), 32)); +} + +export function groupID(secret) { + return derive(secret, "group-id").subarray(0, 16).toString("hex"); +} + +export function authToken(secret) { + return derive(secret, "auth").toString("base64url"); +} + +export function crockford(bytes) { + let out = "", buffer = 0, bits = 0; + for (const byte of bytes) { + buffer = ((buffer << 8) | byte) & 0xffff; + bits += 8; + while (bits >= 5) { out += ALPHABET[(buffer >> (bits - 5)) & 31]; bits -= 5; } + } + if (bits > 0) out += ALPHABET[(buffer << (5 - bits)) & 31]; + return out; +} + +export function pairingCode(secret) { + return "HT1-" + crockford(secret).match(/.{1,4}/g).join("-"); +} + +export function seal(secret, json, nonce) { + const key = derive(secret, "encryption"); + const cipher = createCipheriv("aes-256-gcm", key, nonce); + cipher.setAAD(Buffer.from(groupID(secret))); + const body = Buffer.concat([cipher.update(Buffer.from(json)), cipher.final()]); + return Buffer.concat([Buffer.from([1]), nonce, body, cipher.getAuthTag()]); +} + +export function open(secret, blob) { + const key = derive(secret, "encryption"); + const decipher = createDecipheriv("aes-256-gcm", key, blob.subarray(1, 13)); + decipher.setAAD(Buffer.from(groupID(secret))); + decipher.setAuthTag(blob.subarray(blob.length - 16)); + return Buffer.concat([decipher.update(blob.subarray(13, blob.length - 16)), decipher.final()]).toString(); +} + +if (import.meta.url === `file://${process.argv[1]}`) { + const secret = Buffer.from([...Array(32).keys()]); + const nonce = Buffer.from([...Array(12).keys()].map((i) => 0xa0 + i)); + const json = JSON.stringify({ + terms: [{ text: "Kubernetes", createdAt: 1763100000000, updatedAt: 1763100000000, deleted: false, learned: true }], + snippets: [{ id: "6f1c2b8e-1d5a-4c1e-9a77-1b2c3d4e5f60", trigger: "my link", expansion: "https://cal.com/x", + createdAt: 1763100000000, updatedAt: 1763100000001, deleted: false }], + }); + const blob = seal(secret, json, nonce); + console.log(JSON.stringify({ + secretHex: secret.toString("hex"), + groupID: groupID(secret), + authToken: authToken(secret), + pairingCode: pairingCode(secret), + plaintext: json, + blobBase64: blob.toString("base64"), + }, null, 2)); + if (open(secret, blob) !== json) throw new Error("round trip failed"); +} diff --git a/sync-server/schema.sql b/sync-server/schema.sql new file mode 100644 index 0000000..c6105e0 --- /dev/null +++ b/sync-server/schema.sql @@ -0,0 +1,9 @@ +-- One row per sync group. `blob` is the group's encrypted dictionary and snippets (base64); the +-- server can't read it. `auth_hash` is the SHA-256 of the token the first writer used. +CREATE TABLE IF NOT EXISTS groups ( + id TEXT PRIMARY KEY, + auth_hash TEXT NOT NULL, + version INTEGER NOT NULL, + blob TEXT NOT NULL, + updated_at INTEGER NOT NULL +); diff --git a/sync-server/src/index.js b/sync-server/src/index.js new file mode 100644 index 0000000..7e5e34a --- /dev/null +++ b/sync-server/src/index.js @@ -0,0 +1,130 @@ +// Hushtype sync server. Stores one encrypted blob per group of paired devices and hands it back. +// It never sees the pairing secret, so it can't read anyone's dictionary. See README.md. + +export const MAX_BLOB_BYTES = 512 * 1024; +const GROUP_PATH = /^\/v1\/groups\/([0-9a-f]{32})$/; +const TOKEN = /^Bearer ([A-Za-z0-9_-]{43})$/; + +export default { + async fetch(request, env) { + try { + return await handle(request, env); + } catch (error) { + console.error(error); + return text(500, "Server error"); + } + }, +}; + +async function handle(request, env) { + const url = new URL(request.url); + if (url.pathname === "/" && request.method === "GET") { + return text(200, "Hushtype sync server"); + } + const match = GROUP_PATH.exec(url.pathname); + if (!match) return text(404, "Not found"); + const id = match[1]; + + const token = TOKEN.exec(request.headers.get("Authorization") ?? ""); + if (!token) return text(401, "Missing token"); + const authHash = await sha256Hex(token[1]); + + switch (request.method) { + case "GET": + return get(env.DB, id, authHash); + case "PUT": + return put(env.DB, id, authHash, request); + default: + return text(405, "Method not allowed"); + } +} + +async function get(db, id, authHash) { + const row = await db.prepare("SELECT auth_hash, version, blob FROM groups WHERE id = ?").bind(id).first(); + if (!row) return text(404, "No such group"); + if (row.auth_hash !== authHash) return text(401, "Wrong token"); + return new Response(fromBase64(row.blob), { + status: 200, + headers: { "Content-Type": "application/octet-stream", ETag: etag(row.version), "Cache-Control": "no-store" }, + }); +} + +async function put(db, id, authHash, request) { + const declared = Number(request.headers.get("Content-Length") ?? "0"); + if (declared > MAX_BLOB_BYTES) return text(413, "Too large"); + const body = new Uint8Array(await request.arrayBuffer()); + if (body.length > MAX_BLOB_BYTES) return text(413, "Too large"); + if (body.length < 30 || body[0] !== 1) return text(400, "Not a Hushtype blob"); + const blob = toBase64(body); + const now = Date.now(); + + const ifNoneMatch = request.headers.get("If-None-Match"); + const ifMatch = request.headers.get("If-Match"); + if (ifNoneMatch === "*") { + const result = await db + .prepare( + "INSERT INTO groups (id, auth_hash, version, blob, updated_at) VALUES (?, ?, 1, ?, ?) ON CONFLICT(id) DO NOTHING", + ) + .bind(id, authHash, blob, now) + .run(); + if (result.meta.changes === 0) return conflictOrUnauthorized(db, id, authHash); + return saved(1); + } + if (ifMatch) { + const version = parseEtag(ifMatch); + if (version === null) return text(400, "Bad If-Match"); + const result = await db + .prepare( + "UPDATE groups SET blob = ?, version = version + 1, updated_at = ? WHERE id = ? AND version = ? AND auth_hash = ?", + ) + .bind(blob, now, id, version, authHash) + .run(); + if (result.meta.changes === 0) return conflictOrUnauthorized(db, id, authHash); + return saved(version + 1); + } + return text(428, "Send If-Match or If-None-Match: *"); +} + +/// A write that changed nothing: someone else wrote first (412), or the token is wrong (401). +async function conflictOrUnauthorized(db, id, authHash) { + const row = await db.prepare("SELECT auth_hash FROM groups WHERE id = ?").bind(id).first(); + if (row && row.auth_hash !== authHash) return text(401, "Wrong token"); + return text(412, "Changed since you read it"); +} + +function saved(version) { + return new Response(null, { status: 204, headers: { ETag: etag(version) } }); +} + +function etag(version) { + return `"${version}"`; +} + +function parseEtag(value) { + const match = /^(?:W\/)?"(\d+)"$/.exec(value.trim()); + return match ? Number(match[1]) : null; +} + +function text(status, body) { + return new Response(body, { status, headers: { "Content-Type": "text/plain; charset=utf-8" } }); +} + +async function sha256Hex(value) { + const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value)); + return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join(""); +} + +function toBase64(bytes) { + let binary = ""; + for (let i = 0; i < bytes.length; i += 0x8000) { + binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); + } + return btoa(binary); +} + +function fromBase64(value) { + const binary = atob(value); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); + return bytes; +} diff --git a/sync-server/test.mjs b/sync-server/test.mjs new file mode 100644 index 0000000..41e86ce --- /dev/null +++ b/sync-server/test.mjs @@ -0,0 +1,80 @@ +// Runs the worker against an in-memory SQLite stand-in for D1: node --test sync-server/test.mjs +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { DatabaseSync } from "node:sqlite"; +import worker, { MAX_BLOB_BYTES } from "./src/index.js"; + +function fakeD1() { + const sqlite = new DatabaseSync(":memory:"); + sqlite.exec(readFileSync(new URL("./schema.sql", import.meta.url), "utf8")); + return { + prepare(sql) { + let params = []; + const statement = { + bind(...values) { params = values; return statement; }, + async first() { return sqlite.prepare(sql).get(...params) ?? null; }, + async run() { const r = sqlite.prepare(sql).run(...params); return { meta: { changes: Number(r.changes) } }; }, + }; + return statement; + }, + }; +} + +const id = "0123456789abcdef0123456789abcdef"; +const token = "A".repeat(43); +const other = "B".repeat(43); +const blob = (n) => new Uint8Array([1, ...new Array(40).fill(n)]); + +function call(env, method, { auth = token, headers = {}, body, path = `/v1/groups/${id}` } = {}) { + const h = { ...headers }; + if (auth) h.Authorization = `Bearer ${auth}`; + return worker.fetch(new Request(`https://sync.test${path}`, { method, headers: h, body }), env); +} + +test("create, read, update with compare-and-swap", async () => { + const env = { DB: fakeD1() }; + assert.equal((await call(env, "GET")).status, 404); + + const created = await call(env, "PUT", { headers: { "If-None-Match": "*" }, body: blob(7) }); + assert.equal(created.status, 204); + assert.equal(created.headers.get("ETag"), '"1"'); + + const again = await call(env, "PUT", { headers: { "If-None-Match": "*" }, body: blob(8) }); + assert.equal(again.status, 412); + + const read = await call(env, "GET"); + assert.equal(read.status, 200); + assert.equal(read.headers.get("ETag"), '"1"'); + assert.deepEqual(new Uint8Array(await read.arrayBuffer()), blob(7)); + + const updated = await call(env, "PUT", { headers: { "If-Match": '"1"' }, body: blob(9) }); + assert.equal(updated.status, 204); + assert.equal(updated.headers.get("ETag"), '"2"'); + + const stale = await call(env, "PUT", { headers: { "If-Match": '"1"' }, body: blob(10) }); + assert.equal(stale.status, 412); + + const latest = await call(env, "GET"); + assert.deepEqual(new Uint8Array(await latest.arrayBuffer()), blob(9)); +}); + +test("a different token can't read or write", async () => { + const env = { DB: fakeD1() }; + await call(env, "PUT", { headers: { "If-None-Match": "*" }, body: blob(1) }); + assert.equal((await call(env, "GET", { auth: other })).status, 401); + assert.equal((await call(env, "PUT", { auth: other, headers: { "If-Match": '"1"' }, body: blob(2) })).status, 401); + assert.equal((await call(env, "PUT", { auth: other, headers: { "If-None-Match": "*" }, body: blob(2) })).status, 401); + assert.equal((await call(env, "GET", { auth: null })).status, 401); +}); + +test("rejects bad requests", async () => { + const env = { DB: fakeD1() }; + assert.equal((await call(env, "PUT", { body: blob(1) })).status, 428); + assert.equal((await call(env, "PUT", { headers: { "If-None-Match": "*" }, body: new Uint8Array([2, 3]) })).status, 400); + const big = new Uint8Array(MAX_BLOB_BYTES + 1); + big[0] = 1; + assert.equal((await call(env, "PUT", { headers: { "If-None-Match": "*" }, body: big })).status, 413); + assert.equal((await call(env, "GET", { path: "/v1/groups/xyz" })).status, 404); + assert.equal((await call(env, "DELETE")).status, 405); +}); diff --git a/sync-server/wrangler.toml b/sync-server/wrangler.toml new file mode 100644 index 0000000..f58d2ef --- /dev/null +++ b/sync-server/wrangler.toml @@ -0,0 +1,8 @@ +name = "hushtype-sync" +main = "src/index.js" +compatibility_date = "2026-10-01" + +[[d1_databases]] +binding = "DB" +database_name = "hushtype-sync" +database_id = "REPLACE_WITH_DATABASE_ID" From 3a6f3f20d8e439f3deba0d36e9798ee20bf990e4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 08:49:38 +0000 Subject: [PATCH 2/7] Point the sync server at its D1 database Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01H6HfURkfdoEWCjjJLphzQX --- sync-server/wrangler.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sync-server/wrangler.toml b/sync-server/wrangler.toml index f58d2ef..a17216c 100644 --- a/sync-server/wrangler.toml +++ b/sync-server/wrangler.toml @@ -5,4 +5,4 @@ compatibility_date = "2026-10-01" [[d1_databases]] binding = "DB" database_name = "hushtype-sync" -database_id = "REPLACE_WITH_DATABASE_ID" +database_id = "a5d1f455-ceb3-4bc0-9e6c-4b659a9e1f58" From 7c93409dabebf9a523a8d55089ee9f9b6c79b5f4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 08:49:51 +0000 Subject: [PATCH 3/7] Add a live sync test against the real server Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01H6HfURkfdoEWCjjJLphzQX --- Tests/HushtypeCoreTests/SyncTests.swift | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/Tests/HushtypeCoreTests/SyncTests.swift b/Tests/HushtypeCoreTests/SyncTests.swift index 487c76f..bdf7d46 100644 --- a/Tests/HushtypeCoreTests/SyncTests.swift +++ b/Tests/HushtypeCoreTests/SyncTests.swift @@ -254,3 +254,23 @@ final class SyncClientTests: XCTestCase { } } } + +/// Runs against the real server: HUSHTYPE_SYNC_LIVE=1 swift test --filter LiveSyncTests +final class LiveSyncTests: XCTestCase { + func testTwoDevicesThroughRealServer() async throws { + try XCTSkipUnless(ProcessInfo.processInfo.environment["HUSHTYPE_SYNC_LIVE"] == "1", "Set HUSHTYPE_SYNC_LIVE=1") + let keys = SyncKeys.generate() + let mac = SyncVocabulary().reconciled(terms: ["Kubernetes"], snippets: [], now: 10) + _ = try await SyncClient(keys: keys).sync(mac) + let phone = SyncVocabulary().reconciled(terms: ["Chiranjeeb"], snippets: [], now: 20) + let merged = try await SyncClient(keys: try XCTUnwrap(SyncKeys(pairingCode: keys.pairingCode))) + .sync(phone, joining: true) + XCTAssertEqual(Set(merged.liveTerms.map(\.text)), ["Kubernetes", "Chiranjeeb"]) + do { + _ = try await SyncClient(keys: SyncKeys.generate()).sync(SyncVocabulary(), joining: true) + XCTFail("Expected noSuchGroup") + } catch { + XCTAssertEqual(error as? SyncError, .noSuchGroup) + } + } +} From 046bdb017f6c8ddb46b75263d2c6eaf397adae5c Mon Sep 17 00:00:00 2001 From: Chiranjeeb Jena Date: Sat, 14 Nov 2026 14:24:44 +0530 Subject: [PATCH 4/7] Point the apps at the deployed sync server Co-Authored-By: Claude Opus 5.5 --- Sources/HushtypeCore/SyncClient.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/HushtypeCore/SyncClient.swift b/Sources/HushtypeCore/SyncClient.swift index c27fc1b..80b9422 100644 --- a/Sources/HushtypeCore/SyncClient.swift +++ b/Sources/HushtypeCore/SyncClient.swift @@ -5,7 +5,7 @@ import Foundation /// server's version, so two devices syncing at once can't overwrite each other. public struct SyncClient: Sendable { /// The public server. Self-hosters can point the apps at their own copy of sync-server/. - public static let defaultServer = URL(string: "https://hushtype-sync.chiranjeeb.workers.dev")! + public static let defaultServer = URL(string: "https://hushtype-sync.chiranjib-jena.workers.dev")! /// Matches the server's limit. public static let maxBlobBytes = 512 * 1024 From 0dfa7dfcb6b74217f166614d6b9755bb85ed21e3 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 05:31:37 +0000 Subject: [PATCH 5/7] Sync the dictionary and snippets with the iPhone through iCloud With Sync with iCloud on, DeviceSync keeps a per-word SyncVocabulary in iCloud key-value storage (key vocabulary.v1) and merges it the same way as the sync server, so Macs and iPhones on one Apple ID sync with no pairing and iCloud and the server can both be on. CloudSync now only carries the style settings; the old whole-list dictionary and snippets values are merged in once and no longer written. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01H6HfURkfdoEWCjjJLphzQX --- Sources/Hushtype/CloudSync.swift | 44 +------ Sources/Hushtype/DeviceSync.swift | 134 +++++++++++++++------ Sources/Hushtype/DeviceSyncViews.swift | 6 +- Sources/Hushtype/SettingsWindow.swift | 4 +- Sources/HushtypeCore/CloudVocabulary.swift | 39 ++++++ 5 files changed, 144 insertions(+), 83 deletions(-) create mode 100644 Sources/HushtypeCore/CloudVocabulary.swift diff --git a/Sources/Hushtype/CloudSync.swift b/Sources/Hushtype/CloudSync.swift index c9d9f59..29410ca 100644 --- a/Sources/Hushtype/CloudSync.swift +++ b/Sources/Hushtype/CloudSync.swift @@ -2,9 +2,9 @@ import Combine import Foundation import HushtypeCore -/// Mirrors the settings that follow a person, not a Mac, through iCloud key-value storage: the -/// dictionary, snippets and style choices. The dictation key, microphone, login item and history -/// stay on each Mac, and so does "keep history", since turning it off erases that Mac's history. +/// Mirrors the style choices, which follow a person rather than a Mac, through iCloud key-value +/// storage. DeviceSync carries the dictionary and snippets (through iCloud too, merged word by +/// word with the iPhone). The dictation key, microphone, login item and history stay on each Mac, and so does "keep history", since turning it off erases that Mac's history. /// This Mac's copy stays the source of truth; iCloud carries changes between Macs. @MainActor final class CloudSync { @@ -18,8 +18,6 @@ final class CloudSync { private var applyingRemote = false private enum Key { - static let dictionary = "dictionary" - static let snippets = "snippets" static let cleanupEnabled = "cleanupEnabled" static let useContext = "useContext" static let language = "language" @@ -61,8 +59,6 @@ final class CloudSync { pull(merging: true) pushAll() - watch(settings.$dictionaryText) { [weak self] _ in self?.pushDictionary() } - watch(settings.$snippets) { [weak self] _ in self?.pushSnippets() } watch(settings.$cleanupEnabled) { [weak self] in self?.push($0, Key.cleanupEnabled) } watch(settings.$useContext) { [weak self] in self?.push($0, Key.useContext) } watch(settings.$language) { [weak self] in self?.push($0, Key.language) } @@ -87,8 +83,6 @@ final class CloudSync { // MARK: Sending private func pushAll() { - pushDictionary() - pushSnippets() push(settings.cleanupEnabled, Key.cleanupEnabled) push(settings.useContext, Key.useContext) push(settings.language, Key.language) @@ -100,25 +94,10 @@ final class CloudSync { private func push(_ value: Bool, _ key: String) { store.set(value, forKey: key) } private func push(_ value: String, _ key: String) { store.set(value, forKey: key) } - /// Hushtype device sync carries the dictionary and snippets when it's on. iCloud copies them - /// only by replacing the whole list, which would undo that sync's per-word merging. - private var deviceSyncOn: Bool { UserDefaults.standard.bool(forKey: DeviceSync.enabledKey) } - - private func pushDictionary() { - guard !deviceSyncOn else { return } - store.set(settings.dictionaryText, forKey: Key.dictionary) - } - - private func pushSnippets() { - guard !deviceSyncOn else { return } - if let data = try? JSONEncoder().encode(settings.snippets) { store.set(data, forKey: Key.snippets) } - } - // MARK: Receiving - /// Applies what's in iCloud. When sync is first turned on, words and snippets are merged so - /// nothing on either side is lost; after that iCloud's copy replaces this Mac's, so a word - /// removed on one Mac is removed on the others too. + /// Applies the style choices in iCloud. The dictionary and snippets go through DeviceSync, + /// which merges them word by word with the iPhone and the sync server. private func pull(merging: Bool) { applyingRemote = true defer { @@ -126,19 +105,6 @@ final class CloudSync { DispatchQueue.main.async { [weak self] in self?.applyingRemote = false } } - if !deviceSyncOn, let remote = store.string(forKey: Key.dictionary) { - if merging { - settings.addToDictionary(DictationPipeline.vocabulary(from: remote)) - } else if remote != settings.dictionaryText { - settings.dictionaryText = remote - } - } - if !deviceSyncOn, let data = store.data(forKey: Key.snippets), - let remote = try? JSONDecoder().decode([Snippet].self, from: data) { - let updated = merging ? SnippetSync.merge(settings.snippets, remote) : remote - if updated != settings.snippets { settings.snippets = updated } - } - // Simple choices take the latest value from iCloud. if let value = bool(Key.cleanupEnabled), value != settings.cleanupEnabled { settings.cleanupEnabled = value } if let value = bool(Key.useContext), value != settings.useContext { settings.useContext = value } diff --git a/Sources/Hushtype/DeviceSync.swift b/Sources/Hushtype/DeviceSync.swift index 4ce0989..8760ba3 100644 --- a/Sources/Hushtype/DeviceSync.swift +++ b/Sources/Hushtype/DeviceSync.swift @@ -3,9 +3,11 @@ import Combine import HushtypeCore import os -/// Keeps the dictionary and snippets in step with the person's other devices (Macs, iPhone, -/// Android) through the Hushtype sync server. Everything is encrypted on this Mac with a secret -/// only the paired devices know; pairing hands that secret over as a QR code or a typed code. +/// Keeps the dictionary and snippets in step with the person's other devices, two ways at once: +/// - iCloud, when "Sync with iCloud" is on: Macs and iPhones on the same Apple ID, no pairing. +/// - The Hushtype sync server, once paired: any device, Android too. Everything is encrypted on +/// this Mac with a secret only the paired devices know; pairing hands it over as a QR code. +/// Both hold the same per-word record (`SyncVocabulary`), so each round merges whatever both say. @MainActor final class DeviceSync: ObservableObject { enum Status: Equatable { @@ -15,10 +17,9 @@ final class DeviceSync: ObservableObject { case failed(String) } - /// Read by iCloud sync, which leaves the dictionary and snippets alone while this is on. - static let enabledKey = "deviceSyncEnabled" private static let ledgerKey = "deviceSyncLedger" private static let lastSyncKey = "deviceSyncLast" + private static let legacyImportedKey = "deviceSyncImportedLegacyICloud" private static let keychainAccount = "device-sync-secret" private static let interval: Duration = .seconds(10 * 60) @@ -27,10 +28,11 @@ final class DeviceSync: ObservableObject { private let settings: SettingsStore private let defaults = UserDefaults.standard + private let cloud = NSUbiquitousKeyValueStore.default private let log = Logger(subsystem: "app.hushtype.Hushtype", category: "sync") private var subscriptions: Set = [] private var timer: Task? - private var wakeObserver: NSObjectProtocol? + private var observers: [NSObjectProtocol] = [] private var running = false private var runAgain = false /// True while synced words are written into Settings, so that write doesn't start a sync. @@ -41,8 +43,7 @@ final class DeviceSync: ObservableObject { if let secret = Keychain.read(account: Self.keychainAccount).flatMap({ Data(base64Encoded: $0) }) { keys = SyncKeys(secret: secret) } - if keys != nil, let last = defaults.object(forKey: Self.lastSyncKey) as? Date { status = .upToDate(last) } - defaults.set(keys != nil, forKey: Self.enabledKey) + if isOn, let last = defaults.object(forKey: Self.lastSyncKey) as? Date { status = .upToDate(last) } // Edits sync a couple of seconds after they settle. settings.$dictionaryText.map { _ in () } @@ -52,18 +53,39 @@ final class DeviceSync: ObservableObject { .debounce(for: .seconds(2), scheduler: DispatchQueue.main) .sink { [weak self] in self?.syncNow() } .store(in: &subscriptions) - wakeObserver = NSWorkspace.shared.notificationCenter.addObserver( - forName: NSWorkspace.didWakeNotification, object: nil, queue: .main - ) { [weak self] _ in - MainActor.assumeIsolated { self?.syncNow() } - } + settings.$iCloudSync + .dropFirst() + .receive(on: DispatchQueue.main) + .sink { [weak self] _ in + guard let self else { return } + if !self.isOn { self.status = .off } + self.syncNow() + } + .store(in: &subscriptions) + observers = [ + NSWorkspace.shared.notificationCenter.addObserver( + forName: NSWorkspace.didWakeNotification, object: nil, queue: .main + ) { [weak self] _ in + MainActor.assumeIsolated { self?.syncNow() } + }, + NotificationCenter.default.addObserver( + forName: NSUbiquitousKeyValueStore.didChangeExternallyNotification, object: cloud, queue: .main + ) { [weak self] _ in + MainActor.assumeIsolated { self?.syncNow() } + }, + ] + cloud.synchronize() startTimer() syncNow() } - var isOn: Bool { keys != nil } + /// Paired through the sync server. + var isPaired: Bool { keys != nil } + /// Syncing words through iCloud. + var usesICloud: Bool { settings.iCloudSync } + var isOn: Bool { isPaired || usesICloud } - // MARK: Turning it on and off + // MARK: Pairing /// Starts a new group with this Mac's words. Other devices join by scanning its code. func turnOn() { @@ -72,33 +94,35 @@ final class DeviceSync: ObservableObject { syncNow() } - /// Joins the group another device started. Throws, leaving sync off, when the code is wrong or - /// the server can't be reached. + /// Joins the group another device started. Throws, leaving pairing off, when the code is + /// wrong or the server can't be reached. func join(code: String) async throws { guard let joined = SyncKeys(pairingCode: code) else { throw PairingError.notACode } status = .syncing - let ledger = loadLedger().reconciled(terms: settings.vocabulary, snippets: settings.snippets) + let ledger = localLedger() do { let merged = try await SyncClient(keys: joined).sync(ledger, joining: true) save(joined) apply(merged, startedFrom: ledger) finished() } catch { - status = keys == nil ? .off : status + status = isOn ? .failed(error.localizedDescription) : .off throw error } } - /// Stops syncing on this Mac. Its words stay; the other devices keep syncing with each other. + /// Unpairs this Mac. Its words stay; the other devices keep syncing with each other, and + /// iCloud keeps syncing if it's on. func turnOff() { Keychain.delete(account: Self.keychainAccount) - defaults.removeObject(forKey: Self.ledgerKey) - defaults.removeObject(forKey: Self.lastSyncKey) - defaults.set(false, forKey: Self.enabledKey) keys = nil - status = .off + if !usesICloud { + defaults.removeObject(forKey: Self.ledgerKey) + defaults.removeObject(forKey: Self.lastSyncKey) + status = .off + } } enum PairingError: LocalizedError { @@ -111,20 +135,26 @@ final class DeviceSync: ObservableObject { private func save(_ new: SyncKeys) { Keychain.write(new.secret.base64EncodedString(), account: Self.keychainAccount) keys = new - defaults.set(true, forKey: Self.enabledKey) } // MARK: Syncing func syncNow() { - guard let keys else { return } + guard isOn else { return } if running { runAgain = true return } running = true status = .syncing - let ledger = loadLedger().reconciled(terms: settings.vocabulary, snippets: settings.snippets) + let keys = self.keys + let iCloud = usesICloud + if iCloud { importLegacyICloudOnce() } + var ledger = localLedger() + if iCloud, let remote = CloudVocabulary.read(from: cloud) { + ledger = SyncVocabulary.merge(local: ledger, remote: remote) + } + let start = ledger Task { defer { running = false @@ -133,25 +163,39 @@ final class DeviceSync: ObservableObject { syncNow() } } - do { - let merged = try await SyncClient(keys: keys).sync(ledger) - guard self.keys == keys else { return } - apply(merged, startedFrom: ledger) + var merged = start + var failure: Error? + if let keys { + do { + merged = try await SyncClient(keys: keys).sync(start) + } catch { + failure = error + } + } + guard self.keys == keys, usesICloud == iCloud else { return } + apply(merged, startedFrom: start) + if let failure { + log.error("Sync failed: \(failure.localizedDescription, privacy: .public)") + status = .failed(failure.localizedDescription) + } else { finished() - } catch { - guard self.keys == keys else { return } - log.error("Sync failed: \(error.localizedDescription, privacy: .public)") - status = .failed(error.localizedDescription) } } } + /// This Mac's record, updated with edits made since the last round. + private func localLedger() -> SyncVocabulary { + loadLedger().reconciled(terms: settings.vocabulary, snippets: settings.snippets) + } + /// Writes the merged words into Settings without losing edits made while the request was out: - /// those are folded in with newer timestamps and go up on the next round. + /// those are folded in with newer timestamps and go up on the next round. Then iCloud gets the + /// result. private func apply(_ merged: SyncVocabulary, startedFrom ledger: SyncVocabulary) { let current = ledger.reconciled(terms: settings.vocabulary, snippets: settings.snippets) - let final = SyncVocabulary.merge(local: current, remote: merged) + let final = SyncVocabulary.merge(local: current, remote: merged).compacted() saveLedger(final) + if usesICloud { CloudVocabulary.write(final, to: cloud) } let words = final.dictionary(keepingOrderOf: settings.vocabulary) let snippets = final.snippetList(keepingOrderOf: settings.snippets) @@ -159,7 +203,21 @@ final class DeviceSync: ObservableObject { if words != settings.vocabulary { settings.dictionaryText = words.joined(separator: "\n") } if snippets != settings.snippets { settings.snippets = snippets } DispatchQueue.main.async { [weak self] in self?.applying = false } - if final != merged { runAgain = true } + if isPaired, final != merged { runAgain = true } + } + + /// Hushtype 0.3.7 and earlier kept the whole dictionary as one iCloud value. Its words are + /// added here once, so nothing an older Mac synced is lost. + private func importLegacyICloudOnce() { + guard !defaults.bool(forKey: Self.legacyImportedKey) else { return } + defaults.set(true, forKey: Self.legacyImportedKey) + let legacy = CloudVocabulary.legacy(from: cloud) + applying = true + if !legacy.terms.isEmpty { settings.addToDictionary(legacy.terms) } + let known = Set(settings.snippets.map(\.id)) + let missing = legacy.snippets.filter { !known.contains($0.id) } + if !missing.isEmpty { settings.snippets += missing } + DispatchQueue.main.async { [weak self] in self?.applying = false } } private func finished() { diff --git a/Sources/Hushtype/DeviceSyncViews.swift b/Sources/Hushtype/DeviceSyncViews.swift index 2dccf45..13a90c2 100644 --- a/Sources/Hushtype/DeviceSyncViews.swift +++ b/Sources/Hushtype/DeviceSyncViews.swift @@ -13,7 +13,7 @@ struct DeviceSyncSection: View { var body: some View { SectionLabel("Your devices") SettingsCard { - if sync.isOn { + if sync.isPaired { SettingsRow(title: "Dictionary and snippets sync", subtitle: statusText, symbol: "arrow.clockwise", @@ -36,8 +36,8 @@ struct DeviceSyncSection: View { Button("Turn Off") { sync.turnOff() } } } else { - SettingsRow(title: "Sync with your iPhone and Android", - subtitle: "Your dictionary and snippets, end-to-end encrypted. No account needed.", + SettingsRow(title: "Sync with Android and other devices", + subtitle: "For devices that aren't on your Apple ID. End-to-end encrypted, no account needed.", symbol: "arrow.clockwise", info: Self.privacyNote) { HStack(spacing: 8) { diff --git a/Sources/Hushtype/SettingsWindow.swift b/Sources/Hushtype/SettingsWindow.swift index 05052fd..e2a7215 100644 --- a/Sources/Hushtype/SettingsWindow.swift +++ b/Sources/Hushtype/SettingsWindow.swift @@ -1370,9 +1370,7 @@ private struct GeneralPane: View { SectionLabel("iCloud") SettingsCard { ToggleRow(title: "Sync with iCloud", - subtitle: deviceSync.isOn - ? "Your style settings follow you to your other Macs. Your dictionary and snippets sync with your devices above." - : "Your dictionary, snippets and style settings follow you to your other Macs. The dictation key, microphone and history stay on this Mac.", + subtitle: "Your dictionary, snippets and style settings follow you to your iPhone and other Macs on this Apple ID, with no pairing. The dictation key, microphone and history stay on this Mac.", symbol: "icloud", isOn: $settings.iCloudSync) SettingsRow(title: "Include Anthropic API key", subtitle: keySyncError ?? "Kept in iCloud Keychain, end-to-end encrypted, so you only paste it once.", diff --git a/Sources/HushtypeCore/CloudVocabulary.swift b/Sources/HushtypeCore/CloudVocabulary.swift new file mode 100644 index 0000000..4696a36 --- /dev/null +++ b/Sources/HushtypeCore/CloudVocabulary.swift @@ -0,0 +1,39 @@ +import Foundation + +/// The dictionary and snippets in iCloud key-value storage, so a Mac and an iPhone on the same +/// Apple ID sync with no pairing. It holds the same `SyncVocabulary` as the sync server and merges +/// the same way, item by item, so iCloud and the server can both be on without fighting: each +/// device merges whatever it finds in both places. +/// +/// The Mac app and the iPhone app share one store: both apps' entitlements set +/// `com.apple.developer.ubiquity-kvstore-identifier` to `.app.hushtype.Hushtype`. +public enum CloudVocabulary { + static let key = "vocabulary.v1" + /// What Hushtype 0.3.7 and earlier wrote on the Mac: the whole dictionary as text, and the + /// snippets as JSON. Read once and merged in, never written any more. + static let legacyDictionaryKey = "dictionary" + static let legacySnippetsKey = "snippets" + + public static func read(from store: NSUbiquitousKeyValueStore = .default) -> SyncVocabulary? { + store.data(forKey: key).flatMap { try? JSONDecoder().decode(SyncVocabulary.self, from: $0) } + } + + /// Writes only when something changed, since iCloud rate-limits writes. + public static func write(_ vocabulary: SyncVocabulary, to store: NSUbiquitousKeyValueStore = .default) { + guard read(from: store) != vocabulary, let data = try? JSONEncoder().encode(vocabulary) else { return } + store.set(data, forKey: key) + store.synchronize() + } + + /// The words and snippets an older Mac left in iCloud, for a one-time merge. + public static func legacy(from store: NSUbiquitousKeyValueStore = .default) -> (terms: [String], snippets: [Snippet]) { + let terms = store.string(forKey: legacyDictionaryKey).map(DictationPipeline.vocabulary(from:)) ?? [] + let snippets = store.data(forKey: legacySnippetsKey) + .flatMap { try? JSONDecoder().decode([Snippet].self, from: $0) } ?? [] + return (terms, snippets) + } + + /// True when this device is signed in to iCloud. Doesn't say whether this build has the + /// iCloud entitlement; without it, reads come back empty and writes go nowhere. + public static var isSignedIn: Bool { FileManager.default.ubiquityIdentityToken != nil } +} From b32c878bc32b85c2b0df1f9f8bd690dd2d62ae1f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 05:31:58 +0000 Subject: [PATCH 6/7] Reflow a comment Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01H6HfURkfdoEWCjjJLphzQX --- Sources/Hushtype/CloudSync.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Sources/Hushtype/CloudSync.swift b/Sources/Hushtype/CloudSync.swift index 29410ca..3c3990b 100644 --- a/Sources/Hushtype/CloudSync.swift +++ b/Sources/Hushtype/CloudSync.swift @@ -4,7 +4,8 @@ import HushtypeCore /// Mirrors the style choices, which follow a person rather than a Mac, through iCloud key-value /// storage. DeviceSync carries the dictionary and snippets (through iCloud too, merged word by -/// word with the iPhone). The dictation key, microphone, login item and history stay on each Mac, and so does "keep history", since turning it off erases that Mac's history. +/// word with the iPhone). The dictation key, microphone, login item and history stay on each +/// Mac, and so does "keep history", since turning it off erases that Mac's history. /// This Mac's copy stays the source of truth; iCloud carries changes between Macs. @MainActor final class CloudSync { From e66755788999a22e7c7dbf6768c5ae39eb7d3d66 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 05:56:57 +0000 Subject: [PATCH 7/7] Fix iCloud sync deleting words that arrive from another device syncNow reconciled Settings against the ledger after merging iCloud in, so every word that had just arrived looked removed and was tombstoned and written back. Reconcile against this device's own ledger instead. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01H6HfURkfdoEWCjjJLphzQX --- Sources/Hushtype/DeviceSync.swift | 13 +++++++------ Tests/HushtypeCoreTests/SyncTests.swift | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/Sources/Hushtype/DeviceSync.swift b/Sources/Hushtype/DeviceSync.swift index 8760ba3..6c3eb19 100644 --- a/Sources/Hushtype/DeviceSync.swift +++ b/Sources/Hushtype/DeviceSync.swift @@ -150,11 +150,12 @@ final class DeviceSync: ObservableObject { let keys = self.keys let iCloud = usesICloud if iCloud { importLegacyICloudOnce() } - var ledger = localLedger() - if iCloud, let remote = CloudVocabulary.read(from: cloud) { - ledger = SyncVocabulary.merge(local: ledger, remote: remote) - } - let start = ledger + // `local` is what this device's words say. `start` adds what iCloud holds, and goes to the + // server. Applying has to reconcile against `local`: against `start`, words that just came + // from iCloud aren't in Settings yet and would look removed here, and be deleted everywhere. + let local = localLedger() + let fromICloud = iCloud ? CloudVocabulary.read(from: cloud) : nil + let start = fromICloud.map { SyncVocabulary.merge(local: local, remote: $0) } ?? local Task { defer { running = false @@ -173,7 +174,7 @@ final class DeviceSync: ObservableObject { } } guard self.keys == keys, usesICloud == iCloud else { return } - apply(merged, startedFrom: start) + apply(merged, startedFrom: local) if let failure { log.error("Sync failed: \(failure.localizedDescription, privacy: .public)") status = .failed(failure.localizedDescription) diff --git a/Tests/HushtypeCoreTests/SyncTests.swift b/Tests/HushtypeCoreTests/SyncTests.swift index bdf7d46..c9d45ef 100644 --- a/Tests/HushtypeCoreTests/SyncTests.swift +++ b/Tests/HushtypeCoreTests/SyncTests.swift @@ -274,3 +274,21 @@ final class LiveSyncTests: XCTestCase { } } } + +final class SyncApplyTests: XCTestCase { + /// Words arriving from iCloud aren't in the device's dictionary yet. Reconciling against the + /// merged copy would read them as removed and delete them everywhere; DeviceSync reconciles + /// against the device's own record instead. + func testWordsFromAnotherDeviceSurviveApplying() { + let local = SyncVocabulary().reconciled(terms: ["Alpha"], snippets: [], now: 10) + let remote = SyncVocabulary().reconciled(terms: ["Beta"], snippets: [], now: 20) + let merged = SyncVocabulary.merge(local: local, remote: remote) + + let current = local.reconciled(terms: ["Alpha"], snippets: [], now: 30) + let final = SyncVocabulary.merge(local: current, remote: merged) + XCTAssertEqual(final.dictionary(keepingOrderOf: ["Alpha"]), ["Alpha", "Beta"]) + + let wrong = merged.reconciled(terms: ["Alpha"], snippets: [], now: 30) + XCTAssertEqual(wrong.liveTerms.map(\.text), ["Alpha"], "the bug this guards against") + } +}