Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
feat(ios): prove the account when pairing and join unowned computers
leepokai57a21f960d52
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreLinks.kt b/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreLinks.ktindex 7195f7c2..665b2b10 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreLinks.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreLinks.kt@@ -37,9 +37,12 @@ internal fun AccountStore.pair(text: String, via: PairedVia) {Analytics.completeOnboarding(OnboardingVia.Paired)// The computer joined this account: the account takes it in (or it stays paired, outside the account).val signed = paired.claim+ // In the background, as on iOS: the computer is already paired.if (client != null && claim != null && signed != null) {- bestEffort("complete the claim") { client.completeClaim(claim.claimId, signed) }- refreshCloud()+ contextScope.launch {+ bestEffort("complete the claim") { client.completeClaim(claim.claimId, signed) }+ refreshCloud()+ }}} catch (error: CancellationException) { throw error }catch (error: Exception) {diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsEvent.kt b/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsEvent.ktindex 619f9250..e1974f05 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsEvent.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsEvent.kt@@ -122,8 +122,14 @@ internal enum class PairingFailure(override val wire: String) : CatalogValue {PairingProblem.Kind.OutdatedHost -> OutdatedHostPairingProblem.Kind.Invalid -> Invalid}- // 400: a host from before Android phones turns the platform down; 403: the code expired or was used.- error is HostError -> when (error.status) { 400 -> OutdatedHost; 403 -> Expired; 426 -> UpgradeRequired; else -> Other }+ // 400: a host from before Android phones turns the platform down. 403: the code expired or was used, or the+ // computer turned this phone away (another account, declined, an account it couldn't confirm), as on iOS.+ error is HostError -> when (error.status) {+ 400 -> OutdatedHost+ 403 -> if (error.message.startsWith("This pairing code expired")) Expired else Unauthorized+ 426 -> UpgradeRequired+ else -> Other+ }// The computer's keys don't match the code's.error is SecurityException -> Unauthorizederror.isTimeout -> Timeoutdiff --git a/apps/android/app/src/test/kotlin/com/codync/android/AnalyticsTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/AnalyticsTest.ktindex 06ed8bda..0b4db8da 100644--- a/apps/android/app/src/test/kotlin/com/codync/android/AnalyticsTest.kt+++ b/apps/android/app/src/test/kotlin/com/codync/android/AnalyticsTest.kt@@ -35,7 +35,8 @@ class AnalyticsTest {@Test fun `pairing failures map to the catalog's reasons`() {assertEquals(PairingFailure.NotPairingLink, PairingFailure.of(PairingProblem(PairingProblem.Kind.NotPairingLink)))assertEquals(PairingFailure.UpgradeRequired, PairingFailure.of(HostError(426, "Update")))- assertEquals(PairingFailure.Expired, PairingFailure.of(HostError(403, "Expired code")))+ assertEquals(PairingFailure.Expired, PairingFailure.of(HostError(403, "This pairing code expired. Show a new one on the computer.")))+ assertEquals(PairingFailure.Unauthorized, PairingFailure.of(HostError(403, "The computer didn't let this phone in.")))assertEquals(PairingFailure.Timeout, PairingFailure.of(IOException("Late", java.net.SocketTimeoutException())))assertEquals(PairingFailure.Unreachable, PairingFailure.of(IOException("Offline")))assertEquals(PairingFailure.Other, PairingFailure.of(IllegalArgumentException("Use Start over")))diff --git a/apps/ios/Kit/Sources/CodyncKit/Analytics/AnalyticsEvent.swift b/apps/ios/Kit/Sources/CodyncKit/Analytics/AnalyticsEvent.swiftindex 6d5f66f3..232eafd0 100644--- a/apps/ios/Kit/Sources/CodyncKit/Analytics/AnalyticsEvent.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Analytics/AnalyticsEvent.swift@@ -83,8 +83,9 @@ public enum AnalyticsEvent: Equatable, Sendable {case let host as HostError:self = switch host {case .upgradeRequired: .upgradeRequired- // The host turns down a pairing code that expired or was already used.- case .http(403, _): .expired+ // The host turns down a pairing code that expired or was already used, and a phone it doesn't+ // let in: another account's, one it can't confirm, or one its user declined.+ case let .http(403, message): message.hasPrefix("This pairing code expired") ? .expired : .unauthorizedcase .unauthorized, .http(401, _): .unauthorizedcase .unreachable, .computerOffline: .unreachablecase .http: .otherdiff --git a/apps/ios/Kit/Sources/CodyncKit/Client/CloudClient.swift b/apps/ios/Kit/Sources/CodyncKit/Client/CloudClient.swiftindex 07435672..05df85fd 100644--- a/apps/ios/Kit/Sources/CodyncKit/Client/CloudClient.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Client/CloudClient.swift@@ -58,6 +58,13 @@ public struct CloudClient: Sendable {let _: Res = try await request("POST", "v1/devices", body: ["name": name, "platform": platform], signed: true)}+ /// What pairing shows a computer to prove this device's account. 403: the key isn't registered (or was revoked).+ public func deviceCertificate() async throws -> DeviceCertificate {+ struct Res: Decodable { var certificate: DeviceCertificate }+ let res: Res = try await request("POST", "v1/devices/certificate", signed: true)+ return res.certificate+ }+public func devices() async throws -> [CloudDevice] {struct Res: Decodable { var devices: [CloudDevice] }let res: Res = try await request("GET", "v1/devices")@@ -151,6 +158,15 @@ public struct CloudClient: Sendable {// MARK: claims (§4.2 A)+ public func createClaim() async throws -> CloudClaim {+ try await request("POST", "v1/claims")+ }++ /// `claim`: the JSON object the computer signed while pairing, sent as it came.+ public func completeClaim(claimId: String, claim: Data) async throws {+ let _: Ignored = try await request("POST", "v1/claims/\(claimId)/complete", json: claim, signed: false)+ }+// MARK: plumbingprivate struct NoBody: Encodable {}@@ -165,11 +181,15 @@ public struct CloudClient: Sendable {}func request<T: Decodable>(_ method: String, _ path: String, body: (some Encodable)? = NoBody?.none, signed: Bool = false) async throws -> T {+ try await request(method, path, json: try body.map { try JSONEncoder().encode($0) }, signed: signed)+ }++ private func request<T: Decodable>(_ method: String, _ path: String, json: Data?, signed: Bool) async throws -> T {let url = baseURL.appending(path: path)var req = URLRequest(url: url, timeoutInterval: 20)req.httpMethod = method- let data = try body.map { try JSONEncoder().encode($0) } ?? Data()- if body != nil {+ let data = json ?? Data()+ if json != nil {req.httpBody = datareq.setValue("application/json", forHTTPHeaderField: "Content-Type")}diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/HostConnector.swift b/apps/ios/Kit/Sources/CodyncKit/Client/HostConnector.swiftindex 7fd09dad..6ff4f522 100644--- a/apps/ios/Kit/Sources/CodyncKit/Client/HostConnector.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Client/HostConnector.swift@@ -16,21 +16,39 @@ public enum HostConnector {throw HostError.unreachable}- /// Proves the QR's one-time code inside a channel to the QR's host key; the host- /// then authorizes this device and closes with `4100 paired`.- public static func pair(_ pairing: Pairing, identity: DeviceIdentity, deviceName: String, platform: String) async throws -> Computer {- let transport = ChannelTransport(computer: pairing.computer, identity: identity, pairingCode: pairing.code)+ /// Proves the QR's one-time code inside a channel to the QR's host key, with the account's `certificate`;+ /// the host then authorizes this device and closes with `4100 paired`. A computer in no account asks its+ /// user first, then signs `claim` and returns it (as JSON) for the phone to complete with the cloud.+ public static func pair(_ pairing: Pairing, identity: DeviceIdentity, deviceName: String, platform: String,+ certificate: DeviceCertificate, claim: CloudClaim?) async throws -> (computer: Computer, claim: Data?) {+ try await pair(pairing, identity: identity, deviceName: deviceName, platform: platform,+ certificate: certificate, claim: claim, dial: URLSessionSocket.dial)+ }++ static func pair(_ pairing: Pairing, identity: DeviceIdentity, deviceName: String, platform: String,+ certificate: DeviceCertificate, claim: CloudClaim?, dial: @escaping Dialer) async throws -> (computer: Computer, claim: Data?) {+ let transport = ChannelTransport(computer: pairing.computer, identity: identity, pairingCode: pairing.code, dial: dial)await transport.start()do {- struct Body: Encodable { var code: String; var name: String; var platform: String }+ struct Body: Encodable {+ var code: String+ var name: String+ var platform: String+ var certificate: DeviceCertificate+ var claim: CloudClaim?+ }struct Res: Decodable { var computerId: ComputerID; var name: String? }- let data = try await transport.call("pair", body: JSONEncoder().encode(Body(code: pairing.code, name: deviceName, platform: platform)), timeout: 30)+ let body = try JSONEncoder().encode(Body(code: pairing.code, name: deviceName, platform: platform, certificate: certificate, claim: claim))+ try await transport.ready(within: 30)+ // The computer may be waiting for its user to let this phone in (up to 2 minutes).+ let data = try await transport.call("pair", body: body, timeout: 150)await transport.shutdown()let res = try JSONDecoder().decode(Res.self, from: data)guard res.computerId == pairing.computer.id else { throw HostError.unauthorized(ChannelTransport.identityChanged) }var computer = pairing.computerif let name = res.name, !name.isEmpty { computer.name = name }- return computer+ let signed = (try JSONSerialization.jsonObject(with: data) as? [String: Any])?["claim"] as? [String: Any]+ return (computer, try signed.map { try JSONSerialization.data(withJSONObject: $0) })} catch {await transport.shutdown()throw await transport.needsUpgrade ? HostError.upgradeRequired : errordiff --git a/apps/ios/Kit/Sources/CodyncKit/Client/Pairing.swift b/apps/ios/Kit/Sources/CodyncKit/Client/Pairing.swiftindex f27337b9..c4ca5982 100644--- a/apps/ios/Kit/Sources/CodyncKit/Client/Pairing.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Client/Pairing.swift@@ -62,6 +62,11 @@ public struct Pairing: Hashable, Sendable {self.code = code}+ /// The 6 digits the computer shows if it asks whether to let `identity` in.+ public func checkCode(for identity: DeviceIdentity) -> String {+ RelayCrypto.pairCheck(deviceKey: identity.deviceKey, hostSignKey: Data(base64URL: computer.signKey) ?? Data())+ }+/// The relay's pairing socket parameter.var offerId: String? { Data(base64URL: code).map(RelayCrypto.offerId(code:)) }diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/RelayCrypto.swift b/apps/ios/Kit/Sources/CodyncKit/Client/RelayCrypto.swiftindex 55aed0f1..41faaa3c 100644--- a/apps/ios/Kit/Sources/CodyncKit/Client/RelayCrypto.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Client/RelayCrypto.swift@@ -258,7 +258,17 @@ public enum RelayCrypto {}static func sasCode(hostSignKey: Data, deviceKey dk: Data, deviceNonce nD: Data, hostNonce nH: Data) -> String {- let h = sha256(label("codync/sas/v2"), hostSignKey, dk, nD, nH)+ sixDigits(sha256(label("codync/sas/v2"), hostSignKey, dk, nD, nH))+ }++ /// The code a computer in no account shows while it asks whether to let this phone in (pairing, phase 2):+ /// a phone that isn't the one in the user's hand shows another one.+ static func pairCheck(deviceKey dk: Data, hostSignKey: Data) -> String {+ sixDigits(sha256(label("codync/pair-check/v1"), dk, hostSignKey))+ }++ /// The hash's first 4 bytes, big-endian, as 6 zero-padded digits.+ private static func sixDigits(_ h: Data) -> String {let v = h.prefix(4).reduce(UInt32(0)) { $0 << 8 | UInt32($1) }let s = String(v % 1_000_000)return String(repeating: "0", count: 6 - s.count) + sdiff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Cloud.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Cloud.swiftindex 49115200..050e6a06 100644--- a/apps/ios/Kit/Sources/CodyncKit/Models/Cloud.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Cloud.swift@@ -76,6 +76,35 @@ public struct CloudDevice: Codable, Hashable, Sendable, Identifiable {public var id: String { deviceId }}+/// The cloud's word that this device key is in the account (`POST /v1/devices/certificate`), shown to a computer+/// when pairing; it checks the signature offline. `payload` is the signed JSON text, passed on unchanged.+public struct DeviceCertificate: Codable, Hashable, Sendable {+ public var payload: String+ public var sig: String++ public init(payload: String, sig: String) {+ self.payload = payload+ self.sig = sig+ }++ /// When computers stop taking it; 0 when the payload can't be read.+ public var exp: Int64 {+ struct Claims: Decodable { var exp: Int64 }+ return (try? JSONDecoder().decode(Claims.self, from: Data(payload.utf8)))?.exp ?? 0+ }++ /// Valid for more than another day: reused rather than asked for again.+ public func isFresh(at now: Date = .now) -> Bool { isValid(at: now.addingTimeInterval(86_400)) }++ public func isValid(at now: Date = .now) -> Bool { exp > Int64(now.timeIntervalSince1970 * 1000) }+}++/// A claim the account opened (`POST /v1/claims`), for a computer in no account to sign while pairing.+public struct CloudClaim: Codable, Hashable, Sendable {+ public var claimId: String+ public var nonce: String+}+/// `GET /v1/computers/{id}/grants`.public struct CloudGrant: Codable, Hashable, Sendable, Identifiable {public var grantId: Stringdiff --git a/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swiftindex 13751a28..1bef5982 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift@@ -34,6 +34,8 @@ public final class AccountStore {/// The actual request approved most recently, distinct from a previously paired computer.public private(set) var approvedAccess: [ComputerID: String] = [:]public var lastError: String?+ /// While pairing: the code the computer shows if it asks whether to let this phone in.+ public private(set) var pairingCheck: String?public var selection: BotReference? {didSet {guard !retired else { return }@@ -60,6 +62,8 @@ public final class AccountStore {private var cloudListVersion = 0/// Access requests still waiting for their code, joined by a second ask.private var asks: [ComputerID: Task<AccessTicket, any Error>] = [:]+ /// The account's word for this device's key, kept in memory for this context.+ private var certificate: DeviceCertificate?private var isActive = trueprivate var retired = false@@ -97,17 +101,71 @@ public final class AccountStore {// MARK: computers- /// QR pairing (§4.1); the computer is saved in this context and connected.+ /// QR pairing (§4.1) with this account's certificate: a computer in another account turns the phone away,+ /// one in none asks its user, then joins this account. The computer is saved in this context and connected.public func pair(_ pairing: Pairing, deviceName: String, platform: String) async throws -> Computer {let identity = try DeviceIdentity.load(context: storage)- var computer = try await HostConnector.pair(pairing, identity: identity, deviceName: deviceName, platform: platform)+ guard let cloud else { throw Self.noCertificate }+ let certificate = try await pairingCertificate(cloud, deviceName: deviceName, platform: platform)+ // Without a claim the computer still pairs; it just doesn't join the account.+ let claim: CloudClaim?+ do { claim = try await cloud.createClaim() } catch {+ log.info("pairing without a claim: \(error.localizedDescription, privacy: .public)")+ claim = nil+ }+ pairingCheck = pairing.checkCode(for: identity)+ defer { pairingCheck = nil }+ let paired = try await HostConnector.pair(pairing, identity: identity, deviceName: deviceName, platform: platform,+ certificate: certificate, claim: claim)guard !retired else { throw CancellationError() }+ var computer = paired.computerif let previous = saved.first(where: { $0.id == computer.id }) { computer.keepDevicePicks(from: previous) }save(computer)open(computer)+ if let claim, let signed = paired.claim {+ Task { await joinAccount(claimId: claim.claimId, signed: signed, cloud: cloud) }+ }return computer}+ static let noCertificate = CloudError(status: 0, code: "noCertificate",+ message: "Connect to the internet to pair, so Codync can confirm your account.")++ /// This device's certificate: the one held while more than a day is left, else a new one, registering+ /// the device again if the cloud doesn't know it. Offline, one that is still valid will do.+ func pairingCertificate(_ cloud: CloudClient, deviceName: String, platform: String) async throws -> DeviceCertificate {+ if let certificate, certificate.isFresh() { return certificate }+ do {+ let fresh: DeviceCertificate+ do {+ fresh = try await cloud.deviceCertificate()+ } catch let error as CloudError where error.status == 403 {+ try await cloud.registerDevice(name: deviceName, platform: platform)+ fresh = try await cloud.deviceCertificate()+ }+ certificate = fresh+ return fresh+ } catch let error as CloudError where !error.isTransient {+ throw error+ } catch {+ if let certificate, certificate.isValid() { return certificate }+ log.info("no device certificate: \(error.localizedDescription, privacy: .public)")+ throw Self.noCertificate+ }+ }++ /// The computer signed this account's claim while letting this phone in: the phone, which holds the+ /// account's session, completes it. Best effort: without it the computer stays paired, outside the account.+ private func joinAccount(claimId: String, signed: Data, cloud: CloudClient) async {+ do {+ try await cloud.completeClaim(claimId: claimId, claim: signed)+ } catch {+ log.error("paired computer didn't join the account: \(error.localizedDescription, privacy: .public)")+ return+ }+ await refreshCloud()+ }+public func forget(_ id: ComputerID) {saved.removeAll { $0.id == id }persist()diff --git a/apps/ios/Kit/Tests/CodyncKitTests/AnalyticsTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/AnalyticsTests.swiftindex 5eec738a..b8c1d8d5 100644--- a/apps/ios/Kit/Tests/CodyncKitTests/AnalyticsTests.swift+++ b/apps/ios/Kit/Tests/CodyncKitTests/AnalyticsTests.swift@@ -76,6 +76,7 @@ import Testing#expect(AnalyticsEvent.PairingFailure(Pairing.Problem.outdatedHost) == .outdatedHost)#expect(AnalyticsEvent.PairingFailure(HostError.http(401, "secret")) == .unauthorized)#expect(AnalyticsEvent.PairingFailure(HostError.http(403, "This pairing code expired.")) == .expired)+ #expect(AnalyticsEvent.PairingFailure(HostError.http(403, "The computer didn't let this phone in.")) == .unauthorized)#expect(AnalyticsEvent.PairingFailure(HostError.computerOffline(lastSeen: nil)) == .unreachable)#expect(AnalyticsEvent.PairingFailure(URLError(.timedOut)) == .timeout)#expect(AnalyticsEvent.PairingFailure(CocoaError(.fileNoSuchFile)) == .other)diff --git a/apps/ios/Kit/Tests/CodyncKitTests/ChannelTransportTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/ChannelTransportTests.swiftindex db2d1e80..a38faadd 100644--- a/apps/ios/Kit/Tests/CodyncKitTests/ChannelTransportTests.swift+++ b/apps/ios/Kit/Tests/CodyncKitTests/ChannelTransportTests.swift@@ -413,6 +413,31 @@ private func waitFor(_ states: AsyncStream<LinkState>, _ match: (LinkState) -> Bawait t.shutdown()}+/// Pairing shows the account's certificate and claim; a computer in no account answers with the claim it+/// signed, which comes back as it was sent, for the cloud.+@Test(.timeLimit(.minutes(1))) func pairCarriesTheAccountProofAndReturnsTheSignedClaim() async throws {+ let (dial, sockets) = fakeDialer()+ var direct = v.computer+ direct.urls = ["http://127.0.0.1:1"]+ let computer = direct+ let certificate = DeviceCertificate(payload: #"{"v":1,"exp":1}"#, sig: "c2ln")+ async let paired = HostConnector.pair(Pairing(computer: computer, code: v.str("pairing", "code")), identity: v.identity,+ deviceName: "iPhone", platform: "ios", certificate: certificate,+ claim: CloudClaim(claimId: "clm_1", nonce: "n1"), dial: dial)+ var it = sockets.makeAsyncIterator()+ var host = HostSide(try #require(await it.next()))+ try await host.accept()+ let request = try await host.receive()+ let body = try #require(request["b"] as? [String: Any])+ #expect(body["certificate"] as? [String: String] == ["payload": certificate.payload, "sig": certificate.sig])+ #expect(body["claim"] as? [String: String] == ["claimId": "clm_1", "nonce": "n1"])+ let signed = ["computerId": computer.id, "signKey": computer.signKey, "version": "2.36.0", "sig": "s"]+ try await host.send(["id": request["id"] ?? 0, "ok": ["computerId": computer.id, "name": "Studio", "claim": signed]])+ let result = try await paired+ #expect(result.computer.name == "Studio")+ #expect(try JSONSerialization.jsonObject(with: try #require(result.claim)) as? [String: String] == signed)+}+@Test func lapsedLeaseIsRetriedNotARevocation() throws {let reject = { (code: String) in ChannelTransport.rejection(try ChannelTransport.decodeWire(#"{"t":"reject","code":"\#(code)"}"#)) }// The computer couldn't confirm the account's approval lately: the channel keeps trying.diff --git a/apps/ios/Kit/Tests/CodyncKitTests/RelayVectorsTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/RelayVectorsTests.swiftindex 72cd45cf..0453deca 100644--- a/apps/ios/Kit/Tests/CodyncKitTests/RelayVectorsTests.swift+++ b/apps/ios/Kit/Tests/CodyncKitTests/RelayVectorsTests.swift@@ -136,6 +136,11 @@ private func raw(_ key: SymmetricKey) -> Data { key.withUnsafeBytes { Data($0) }hostNonce: v.b64("sas", "hostNonce")) == v.str("sas", "code"))}+/// The same digits the host shows (host/src/remote/pairing_requests.rs `check_code`).+@Test func pairCheckMatchesTheHost() {+ #expect(RelayCrypto.pairCheck(deviceKey: Data(repeating: 1, count: 32), hostSignKey: Data(repeating: 2, count: 32)) == "855066")+}+@Test func claimAndACLSignaturesVerify() {let host = v.hostSign.publicKey#expect(host.isValidSignature(v.b64("claim", "sig"), for: Data(v.str("claim", "canonical").utf8)))diff --git a/apps/ios/Kit/Tests/CodyncUITests/PairingCertificateTests.swift b/apps/ios/Kit/Tests/CodyncUITests/PairingCertificateTests.swiftnew file mode 100644index 00000000..3d2061d2--- /dev/null+++ b/apps/ios/Kit/Tests/CodyncUITests/PairingCertificateTests.swift@@ -0,0 +1,86 @@+import Foundation+import os+import Testing+@testable import CodyncKit+@testable import CodyncUI++/// The cloud's certificate route: 403 until this device registers, then certificates expiring at `exp`.+private final class CertificateCloudStub: URLProtocol {+ struct State {+ var registered = false+ var offline = false+ var exp: Int64 = 0+ var issued = 0+ }++ static let state = OSAllocatedUnfairLock(initialState: State())++ 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 path = request.url?.path ?? ""+ let answer: (status: Int, json: String)? = Self.state.withLock { s in+ if s.offline { return nil }+ if path.hasSuffix("/v1/devices") {+ s.registered = true+ return (200, "{}")+ }+ guard s.registered else { return (403, #"{"error":{"code":"forbidden"}}"#) }+ s.issued += 1+ return (200, #"{"certificate":{"payload":"{\"v\":1,\"exp\":\#(s.exp)}","sig":"s"}}"#)+ }+ guard let answer else {+ client?.urlProtocol(self, didFailWithError: URLError(.notConnectedToInternet))+ return+ }+ let response = HTTPURLResponse(url: request.url!, statusCode: answer.status, httpVersion: nil, headerFields: nil)!+ client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)+ client?.urlProtocol(self, didLoad: Data(answer.json.utf8))+ client?.urlProtocolDidFinishLoading(self)+ }+}++/// Pairing's certificate: an unregistered device registers once and gets one; it's held while more than a+/// day is left, renewed after, and offline a still valid one will do. Offline with none, pairing can't start.+@MainActor @Test func pairingCertificateIsRegisteredForHeldAndRenewed() async throws {+ let suite = "PairingCertificate.\(UUID().uuidString)"+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }+ let config = URLSessionConfiguration.ephemeral+ config.protocolClasses = [CertificateCloudStub.self]+ let cloud = CloudClient(baseURL: URL(string: "https://cloud.test")!, identity: DeviceIdentity(signing: .init(), push: .init()),+ session: URLSession(configuration: config)) { "token" }+ let storage = SharedStore.Context(accountID: "account", suite: suite)+ let accounts = AccountStore(storage: storage, cloud: cloud)+ defer { accounts.retire() }+ func certificate(_ store: AccountStore) async throws -> DeviceCertificate {+ try await store.pairingCertificate(cloud, deviceName: "iPhone", platform: "ios")+ }+ func set(_ change: @escaping @Sendable (inout CertificateCloudStub.State) -> Void) { CertificateCloudStub.state.withLock(change) }+ let hour: Int64 = 3_600_000+ let now = Int64(Date.now.timeIntervalSince1970 * 1000)++ set { $0.exp = now + 12 * hour }+ let short = try await certificate(accounts)+ #expect(short.exp == now + 12 * hour)+ #expect(CertificateCloudStub.state.withLock { $0.registered })++ // Less than a day left: offline, it still does; online, a new one replaces it.+ set { $0.offline = true }+ #expect(try await certificate(accounts) == short)+ set {+ $0.offline = false+ $0.exp = now + 7 * 24 * hour+ }+ let long = try await certificate(accounts)+ #expect(long.exp == now + 7 * 24 * hour)+ #expect(try await certificate(accounts) == long)+ #expect(CertificateCloudStub.state.withLock { $0.issued } == 2)++ set { $0.offline = true }+ let fresh = AccountStore(storage: storage, cloud: cloud)+ defer { fresh.retire() }+ await #expect(throws: AccountStore.noCertificate) { try await certificate(fresh) }+ #expect(AccountStore.noCertificate.localizedDescription == "Connect to the internet to pair, so Codync can confirm your account.")+}diff --git a/apps/ios/Views/PairingView.swift b/apps/ios/Views/PairingView.swiftindex a793d32e..38619b3b 100644--- a/apps/ios/Views/PairingView.swift+++ b/apps/ios/Views/PairingView.swift@@ -250,7 +250,7 @@ private struct ScanPage: View {if let error {VStack(alignment: .leading, spacing: 6) {- Text(error).font(.footnote).foregroundStyle(Palette.danger)+ Text(L10n.tr(error)).font(.footnote).foregroundStyle(Palette.danger)// The usual cause: the phone has no road to the computer yet.Label(L10n.tr("Check that this iPhone and the computer are on the same Wi-Fi or both on Tailscale, or that “Reach from anywhere” is on in Codync on the computer."),systemImage: "wifi.exclamationmark")@@ -316,12 +316,25 @@ private struct ScanPage: View {}if pairing {Palette.background.opacity(0.7)- Spinner(size: 28)+ VStack(spacing: 16) {+ Spinner(size: 28)+ // A computer in no account asks its user first, showing the same code.+ if let code = app.accounts.pairingCheck {+ Text(L10n.tr("If the computer asks, check it shows {code}.")+ .replacingOccurrences(of: "{code}", with: "\(code.prefix(3)) \(code.suffix(3))"))+ .font(.subheadline.monospacedDigit())+ .foregroundStyle(Palette.text)+ .multilineTextAlignment(.center)+ .padding(.horizontal, 24)+ .transition(.opacity)+ }+ }}}.aspectRatio(1, contentMode: .fit).clipShape(RoundedRectangle(cornerRadius: 24, style: .continuous)).animation(Motion.fade, value: pairing)+ .animation(Motion.fade, value: app.accounts.pairingCheck)}private func pair(_ text: String) {