1+ import ClawdbotKit
12import ClawdbotProtocol
23import Darwin
34import Foundation
45
6+ private typealias ProtoAnyCodable = ClawdbotProtocol . AnyCodable
7+
58struct WizardCliOptions {
69 var url : String ?
710 var token : String ?
@@ -228,13 +231,18 @@ private func parseInt(_ value: Any?) -> Int? {
228231}
229232
230233actor 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
358429private 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}
0 commit comments