Skip to content

Commit dfbf6ac

Browse files
committed
feat: enforce device-bound connect challenge
1 parent 121ae60 commit dfbf6ac

21 files changed

Lines changed: 953 additions & 129 deletions

File tree

‎apps/macos/Package.swift‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ let package = Package(
7878
.executableTarget(
7979
name: "ClawdbotWizardCLI",
8080
dependencies: [
81+
.product(name: "ClawdbotKit", package: "ClawdbotKit"),
8182
.product(name: "ClawdbotProtocol", package: "ClawdbotKit"),
8283
],
8384
path: "Sources/ClawdbotWizardCLI",

‎apps/macos/Sources/ClawdbotProtocol/GatewayModels.swift‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ public struct ConnectParams: Codable, Sendable {
2020
public let permissions: [String: AnyCodable]?
2121
public let role: String?
2222
public let scopes: [String]?
23-
public let device: [String: AnyCodable]
23+
public let device: [String: AnyCodable]?
2424
public let auth: [String: AnyCodable]?
2525
public let locale: String?
2626
public let useragent: String?
@@ -34,7 +34,7 @@ public struct ConnectParams: Codable, Sendable {
3434
permissions: [String: AnyCodable]?,
3535
role: String?,
3636
scopes: [String]?,
37-
device: [String: AnyCodable],
37+
device: [String: AnyCodable]?,
3838
auth: [String: AnyCodable]?,
3939
locale: String?,
4040
useragent: String?

‎apps/macos/Sources/ClawdbotWizardCLI/main.swift‎

Lines changed: 109 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
1+
import ClawdbotKit
12
import ClawdbotProtocol
23
import Darwin
34
import Foundation
45

6+
private typealias ProtoAnyCodable = ClawdbotProtocol.AnyCodable
7+
58
struct WizardCliOptions {
69
var url: String?
710
var token: String?
@@ -228,13 +231,18 @@ private func parseInt(_ value: Any?) -> Int? {
228231
}
229232

230233
actor GatewayWizardClient {
234+
private enum ConnectChallengeError: Error {
235+
case timeout
236+
}
237+
231238
private let url: URL
232239
private let token: String?
233240
private let password: String?
234241
private let json: Bool
235242
private let encoder = JSONEncoder()
236243
private let decoder = JSONDecoder()
237244
private let session = URLSession(configuration: .default)
245+
private let connectChallengeTimeoutSeconds: Double = 0.75
238246
private var task: URLSessionWebSocketTask?
239247

240248
init(url: URL, token: String?, password: String?, json: Bool) {
@@ -257,7 +265,7 @@ actor GatewayWizardClient {
257265
self.task = nil
258266
}
259267

260-
func request(method: String, params: [String: AnyCodable]?) async throws -> ResponseFrame {
268+
func request(method: String, params: [String: ProtoAnyCodable]?) async throws -> ResponseFrame {
261269
guard let task = self.task else {
262270
throw WizardCliError.gatewayError("gateway not connected")
263271
}
@@ -266,7 +274,7 @@ actor GatewayWizardClient {
266274
type: "req",
267275
id: id,
268276
method: method,
269-
params: params.map { AnyCodable($0) })
277+
params: params.map { ProtoAnyCodable($0) })
270278
let data = try self.encoder.encode(frame)
271279
try await task.send(.data(data))
272280

@@ -309,60 +317,123 @@ actor GatewayWizardClient {
309317
}
310318
let osVersion = ProcessInfo.processInfo.operatingSystemVersion
311319
let platform = "macos \(osVersion.majorVersion).\(osVersion.minorVersion).\(osVersion.patchVersion)"
312-
let client: [String: AnyCodable] = [
313-
"id": AnyCodable("clawdbot-macos"),
314-
"displayName": AnyCodable(Host.current().localizedName ?? "Clawdbot macOS Wizard CLI"),
315-
"version": AnyCodable("dev"),
316-
"platform": AnyCodable(platform),
317-
"deviceFamily": AnyCodable("Mac"),
318-
"mode": AnyCodable("ui"),
319-
"instanceId": AnyCodable(UUID().uuidString),
320+
let clientId = "clawdbot-macos"
321+
let clientMode = "ui"
322+
let role = "operator"
323+
let scopes: [String] = []
324+
let client: [String: ProtoAnyCodable] = [
325+
"id": ProtoAnyCodable(clientId),
326+
"displayName": ProtoAnyCodable(Host.current().localizedName ?? "Clawdbot macOS Wizard CLI"),
327+
"version": ProtoAnyCodable("dev"),
328+
"platform": ProtoAnyCodable(platform),
329+
"deviceFamily": ProtoAnyCodable("Mac"),
330+
"mode": ProtoAnyCodable(clientMode),
331+
"instanceId": ProtoAnyCodable(UUID().uuidString),
320332
]
321333

322-
var params: [String: AnyCodable] = [
323-
"minProtocol": AnyCodable(GATEWAY_PROTOCOL_VERSION),
324-
"maxProtocol": AnyCodable(GATEWAY_PROTOCOL_VERSION),
325-
"client": AnyCodable(client),
326-
"caps": AnyCodable([String]()),
327-
"locale": AnyCodable(Locale.preferredLanguages.first ?? Locale.current.identifier),
328-
"userAgent": AnyCodable(ProcessInfo.processInfo.operatingSystemVersionString),
334+
var params: [String: ProtoAnyCodable] = [
335+
"minProtocol": ProtoAnyCodable(GATEWAY_PROTOCOL_VERSION),
336+
"maxProtocol": ProtoAnyCodable(GATEWAY_PROTOCOL_VERSION),
337+
"client": ProtoAnyCodable(client),
338+
"caps": ProtoAnyCodable([String]()),
339+
"locale": ProtoAnyCodable(Locale.preferredLanguages.first ?? Locale.current.identifier),
340+
"userAgent": ProtoAnyCodable(ProcessInfo.processInfo.operatingSystemVersionString),
341+
"role": ProtoAnyCodable(role),
342+
"scopes": ProtoAnyCodable(scopes),
329343
]
330344
if let token = self.token {
331-
params["auth"] = AnyCodable(["token": AnyCodable(token)])
345+
params["auth"] = ProtoAnyCodable(["token": ProtoAnyCodable(token)])
332346
} else if let password = self.password {
333-
params["auth"] = AnyCodable(["password": AnyCodable(password)])
347+
params["auth"] = ProtoAnyCodable(["password": ProtoAnyCodable(password)])
348+
}
349+
let connectNonce = try await self.waitForConnectChallenge()
350+
let identity = DeviceIdentityStore.loadOrCreate()
351+
let signedAtMs = Int(Date().timeIntervalSince1970 * 1000)
352+
let scopesValue = scopes.joined(separator: ",")
353+
var payloadParts = [
354+
connectNonce == nil ? "v1" : "v2",
355+
identity.deviceId,
356+
clientId,
357+
clientMode,
358+
role,
359+
scopesValue,
360+
String(signedAtMs),
361+
self.token ?? "",
362+
]
363+
if let connectNonce {
364+
payloadParts.append(connectNonce)
365+
}
366+
let payload = payloadParts.joined(separator: "|")
367+
if let signature = DeviceIdentityStore.signPayload(payload, identity: identity),
368+
let publicKey = DeviceIdentityStore.publicKeyBase64Url(identity) {
369+
var device: [String: ProtoAnyCodable] = [
370+
"id": ProtoAnyCodable(identity.deviceId),
371+
"publicKey": ProtoAnyCodable(publicKey),
372+
"signature": ProtoAnyCodable(signature),
373+
"signedAt": ProtoAnyCodable(signedAtMs),
374+
]
375+
if let connectNonce {
376+
device["nonce"] = ProtoAnyCodable(connectNonce)
377+
}
378+
params["device"] = ProtoAnyCodable(device)
334379
}
335380

336381
let reqId = UUID().uuidString
337382
let frame = RequestFrame(
338383
type: "req",
339384
id: reqId,
340385
method: "connect",
341-
params: AnyCodable(params))
386+
params: ProtoAnyCodable(params))
342387
let data = try self.encoder.encode(frame)
343388
try await task.send(.data(data))
344389

345-
let message = try await task.receive()
346-
let frameResponse = try decodeFrame(message)
347-
guard case let .res(res) = frameResponse, res.id == reqId else {
348-
throw WizardCliError.gatewayError("connect failed (unexpected response)")
390+
while true {
391+
let message = try await task.receive()
392+
let frameResponse = try decodeFrame(message)
393+
if case let .res(res) = frameResponse, res.id == reqId {
394+
if res.ok == false {
395+
let msg = (res.error?["message"]?.value as? String) ?? "gateway connect failed"
396+
throw WizardCliError.gatewayError(msg)
397+
}
398+
_ = try self.decodePayload(res, as: HelloOk.self)
399+
return
400+
}
349401
}
350-
if res.ok == false {
351-
let msg = (res.error?["message"]?.value as? String) ?? "gateway connect failed"
352-
throw WizardCliError.gatewayError(msg)
402+
}
403+
404+
private func waitForConnectChallenge() async throws -> String? {
405+
guard let task = self.task else { return nil }
406+
do {
407+
return try await AsyncTimeout.withTimeout(
408+
seconds: self.connectChallengeTimeoutSeconds,
409+
onTimeout: { ConnectChallengeError.timeout },
410+
operation: {
411+
while true {
412+
let message = try await task.receive()
413+
let frame = try decodeFrame(message)
414+
if case let .event(evt) = frame, evt.event == "connect.challenge" {
415+
if let payload = evt.payload?.value as? [String: ProtoAnyCodable],
416+
let nonce = payload["nonce"]?.value as? String {
417+
return nonce
418+
}
419+
}
420+
}
421+
})
422+
} catch {
423+
if error is ConnectChallengeError { return nil }
424+
throw error
353425
}
354-
_ = try self.decodePayload(res, as: HelloOk.self)
355426
}
356427
}
357428

358429
private func runWizard(client: GatewayWizardClient, opts: WizardCliOptions) async throws {
359-
var params: [String: AnyCodable] = [:]
430+
var params: [String: ProtoAnyCodable] = [:]
360431
let mode = opts.mode.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
361432
if mode == "local" || mode == "remote" {
362-
params["mode"] = AnyCodable(mode)
433+
params["mode"] = ProtoAnyCodable(mode)
363434
}
364435
if let workspace = opts.workspace?.trimmingCharacters(in: .whitespacesAndNewlines), !workspace.isEmpty {
365-
params["workspace"] = AnyCodable(workspace)
436+
params["workspace"] = ProtoAnyCodable(workspace)
366437
}
367438

368439
let startResponse = try await client.request(method: "wizard.start", params: params)
@@ -395,17 +466,17 @@ private func runWizard(client: GatewayWizardClient, opts: WizardCliOptions) asyn
395466

396467
if let step = decodeWizardStep(nextResult.step) {
397468
let answer = try promptAnswer(for: step)
398-
var answerPayload: [String: AnyCodable] = [
399-
"stepId": AnyCodable(step.id),
469+
var answerPayload: [String: ProtoAnyCodable] = [
470+
"stepId": ProtoAnyCodable(step.id),
400471
]
401472
if !(answer is NSNull) {
402-
answerPayload["value"] = AnyCodable(answer)
473+
answerPayload["value"] = ProtoAnyCodable(answer)
403474
}
404475
let response = try await client.request(
405476
method: "wizard.next",
406477
params: [
407-
"sessionId": AnyCodable(sessionId),
408-
"answer": AnyCodable(answerPayload),
478+
"sessionId": ProtoAnyCodable(sessionId),
479+
"answer": ProtoAnyCodable(answerPayload),
409480
])
410481
nextResult = try await client.decodePayload(response, as: WizardNextResult.self)
411482
if opts.json {
@@ -414,7 +485,7 @@ private func runWizard(client: GatewayWizardClient, opts: WizardCliOptions) asyn
414485
} else {
415486
let response = try await client.request(
416487
method: "wizard.next",
417-
params: ["sessionId": AnyCodable(sessionId)])
488+
params: ["sessionId": ProtoAnyCodable(sessionId)])
418489
nextResult = try await client.decodePayload(response, as: WizardNextResult.self)
419490
if opts.json {
420491
dumpResult(response)
@@ -424,7 +495,7 @@ private func runWizard(client: GatewayWizardClient, opts: WizardCliOptions) asyn
424495
} catch WizardCliError.cancelled {
425496
_ = try? await client.request(
426497
method: "wizard.cancel",
427-
params: ["sessionId": AnyCodable(sessionId)])
498+
params: ["sessionId": ProtoAnyCodable(sessionId)])
428499
throw WizardCliError.cancelled
429500
}
430501
}

‎apps/shared/ClawdbotKit/Sources/ClawdbotKit/DeviceIdentity.swift‎

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,18 @@
11
import CryptoKit
22
import Foundation
33

4-
struct DeviceIdentity: Codable, Sendable {
5-
var deviceId: String
6-
var publicKey: String
7-
var privateKey: String
8-
var createdAtMs: Int
4+
public struct DeviceIdentity: Codable, Sendable {
5+
public var deviceId: String
6+
public var publicKey: String
7+
public var privateKey: String
8+
public var createdAtMs: Int
9+
10+
public init(deviceId: String, publicKey: String, privateKey: String, createdAtMs: Int) {
11+
self.deviceId = deviceId
12+
self.publicKey = publicKey
13+
self.privateKey = privateKey
14+
self.createdAtMs = createdAtMs
15+
}
916
}
1017

1118
enum DeviceIdentityPaths {
@@ -27,10 +34,10 @@ enum DeviceIdentityPaths {
2734
}
2835
}
2936

30-
enum DeviceIdentityStore {
37+
public enum DeviceIdentityStore {
3138
private static let fileName = "device.json"
3239

33-
static func loadOrCreate() -> DeviceIdentity {
40+
public static func loadOrCreate() -> DeviceIdentity {
3441
let url = self.fileURL()
3542
if let data = try? Data(contentsOf: url),
3643
let decoded = try? JSONDecoder().decode(DeviceIdentity.self, from: data),
@@ -44,7 +51,7 @@ enum DeviceIdentityStore {
4451
return identity
4552
}
4653

47-
static func signPayload(_ payload: String, identity: DeviceIdentity) -> String? {
54+
public static func signPayload(_ payload: String, identity: DeviceIdentity) -> String? {
4855
guard let privateKeyData = Data(base64Encoded: identity.privateKey) else { return nil }
4956
do {
5057
let privateKey = try Curve25519.Signing.PrivateKey(rawRepresentation: privateKeyData)
@@ -76,7 +83,7 @@ enum DeviceIdentityStore {
7683
.replacingOccurrences(of: "=", with: "")
7784
}
7885

79-
static func publicKeyBase64Url(_ identity: DeviceIdentity) -> String? {
86+
public static func publicKeyBase64Url(_ identity: DeviceIdentity) -> String? {
8087
guard let data = Data(base64Encoded: identity.publicKey) else { return nil }
8188
return self.base64UrlEncode(data)
8289
}

0 commit comments

Comments
 (0)