Skip to content
20 changes: 1 addition & 19 deletions Sources/Cloud/VMClientSocketCommands.swift
Original file line number Diff line number Diff line change
@@ -1,25 +1,7 @@
import Foundation

extension TerminalController {
nonisolated func socketWorkerCloudVMResponseIfNeeded(for command: String) -> String? {
guard command.hasPrefix("{"),
let data = command.data(using: .utf8),
let object = try? JSONSerialization.jsonObject(with: data, options: []),
let dict = object as? [String: Any] else {
return nil
}

let method = (dict["method"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
guard method.hasPrefix("vm.") else { return nil }

let id: Any? = dict["id"]
let params = dict["params"] as? [String: Any] ?? [:]
return withSocketCommandPolicy(commandKey: method, isV2: true) {
socketWorkerCloudVMResponse(method: method, id: id, params: params)
}
}

private nonisolated func socketWorkerCloudVMResponse(
nonisolated func socketWorkerCloudVMResponse(
method: String,
id: Any?,
params: [String: Any]
Expand Down
204 changes: 127 additions & 77 deletions Sources/TerminalController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1383,88 +1383,121 @@ class TerminalController {
return nil
}

private nonisolated func socketWorkerAuthResponseIfNeeded(for command: String) -> String? {
guard command.hasPrefix("{"),
let data = command.data(using: .utf8),
private enum SocketCommandExecutionPolicy: Equatable {
case mainActor
case socketWorker
}

private struct V2SocketRequest {
let id: Any?
let method: String
let params: [String: Any]
}

private nonisolated static let socketWorkerV2Methods: Set<String> = [
"auth.status",
"auth.begin_sign_in",
"auth.sign_out",
"feedback.submit",
"feed.push",
"feed.permission.reply",
"feed.question.reply",
"feed.exit_plan.reply",
]

private nonisolated static func executionPolicy(forV2Method method: String) -> SocketCommandExecutionPolicy {
if method.hasPrefix("vm.") || socketWorkerV2Methods.contains(method) {
return .socketWorker
}
return .mainActor
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

private nonisolated func parseV2SocketRequest(_ command: String) -> V2SocketRequest? {
let trimmedCommand = command.trimmingCharacters(in: .whitespacesAndNewlines)
guard trimmedCommand.hasPrefix("{"),
let data = trimmedCommand.data(using: .utf8),
let dict = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String: Any] else {
return nil
}

let method = (dict["method"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
guard method == "auth.status" || method == "auth.begin_sign_in" || method == "auth.sign_out" else {
guard !method.isEmpty else {
return nil
}

let id: Any? = dict["id"]
let params = dict["params"] as? [String: Any] ?? [:]

return withSocketCommandPolicy(commandKey: method, isV2: true) {
switch method {
case "auth.status":
let semaphore = DispatchSemaphore(value: 0)
Task { @MainActor in
await AuthManager.shared.awaitBootstrapped()
semaphore.signal()
}
semaphore.wait()
return v2Ok(id: id, result: v2AuthStatusPayload(timedOut: false))
case "auth.begin_sign_in":
let timeoutSeconds = (params["timeout_seconds"] as? Double) ?? 300
let semaphore = DispatchSemaphore(value: 0)
nonisolated(unsafe) var signedIn = false
Task { @MainActor in
signedIn = await AuthManager.shared.beginSignInAndAwait(
timeout: timeoutSeconds
)
semaphore.signal()
}
semaphore.wait()
return v2Ok(id: id, result: v2AuthStatusPayload(timedOut: !signedIn))
case "auth.sign_out":
let semaphore = DispatchSemaphore(value: 0)
Task { @MainActor in
_ = await AuthManager.shared.signOutAndAwait(timeout: 5)
semaphore.signal()
}
semaphore.wait()
return v2Ok(id: id, result: v2AuthStatusPayload(timedOut: false))
default:
return nil
}
}
return V2SocketRequest(
id: dict["id"],
method: method,
params: dict["params"] as? [String: Any] ?? [:]
)
}

private nonisolated func socketWorkerFeedbackResponseIfNeeded(for command: String) -> String? {
guard command.hasPrefix("{"),
let data = command.data(using: .utf8),
let dict = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String: Any] else {
private nonisolated func socketWorkerV2ResponseIfNeeded(for command: String) -> String? {
guard let request = parseV2SocketRequest(command),
Self.executionPolicy(forV2Method: request.method) == .socketWorker else {
return nil
}

let method = (dict["method"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
guard method == "feedback.submit" else { return nil }
return withSocketCommandPolicy(commandKey: request.method, isV2: true) {
socketWorkerV2Response(request)
}
}

let id: Any? = dict["id"]
let params = dict["params"] as? [String: Any] ?? [:]
return withSocketCommandPolicy(commandKey: method, isV2: true) {
v2Result(id: id, v2FeedbackSubmit(params: params))
private nonisolated func socketWorkerV2Response(_ request: V2SocketRequest) -> String {
switch request.method {
case "auth.status":
let semaphore = DispatchSemaphore(value: 0)
Task { @MainActor in
await AuthManager.shared.awaitBootstrapped()
semaphore.signal()
}
semaphore.wait()
return v2Ok(id: request.id, result: v2AuthStatusPayload(timedOut: false))
case "auth.begin_sign_in":
let timeoutSeconds = (request.params["timeout_seconds"] as? Double) ?? 300
let semaphore = DispatchSemaphore(value: 0)
nonisolated(unsafe) var signedIn = false
Task { @MainActor in
signedIn = await AuthManager.shared.beginSignInAndAwait(
timeout: timeoutSeconds
)
Comment on lines +1464 to +1470

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Reject non-positive timeout_seconds values.

A missing timeout falls back to 300, but a present 0 or negative value still gets passed into beginSignInAndAwait. For a socket-exposed timeout parameter, that should return invalid_params (or at least be clamped) instead of letting malformed input change auth behavior.

Suggested fix
-            let timeoutSeconds = (request.params["timeout_seconds"] as? Double) ?? 300
+            let timeoutSeconds: TimeInterval
+            if let rawTimeout = request.params["timeout_seconds"] {
+                guard let seconds = rawTimeout as? NSNumber, seconds.doubleValue > 0 else {
+                    return v2Error(
+                        id: request.id,
+                        code: "invalid_params",
+                        message: "auth.begin_sign_in requires `timeout_seconds` > 0"
+                    )
+                }
+                timeoutSeconds = seconds.doubleValue
+            } else {
+                timeoutSeconds = 300
+            }

Based on learnings: In Swift request/JSON handlers in Sources/TerminalController.swift, prefer the v2 numeric-parsing helpers and clamp/validate timeout inputs as appropriate.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Sources/TerminalController.swift` around lines 1458 - 1464, Validate and
reject non-positive timeout_seconds before calling
AuthManager.shared.beginSignInAndAwait: parse the incoming value from
request.params using the v2 numeric-parsing helper (instead of blindly casting
to Double into timeoutSeconds), check that the resulting timeout is > 0, and if
not return an invalid_params error (or clamp to a minimum positive value) rather
than passing it to beginSignInAndAwait; update the logic around timeoutSeconds
and the Task that calls beginSignInAndAwait to only run when the validated
timeout is positive.

semaphore.signal()
}
semaphore.wait()
return v2Ok(id: request.id, result: v2AuthStatusPayload(timedOut: !signedIn))
case "auth.sign_out":
let semaphore = DispatchSemaphore(value: 0)
Task { @MainActor in
_ = await AuthManager.shared.signOutAndAwait(timeout: 5)
semaphore.signal()
}
semaphore.wait()
return v2Ok(id: request.id, result: v2AuthStatusPayload(timedOut: false))
case "feedback.submit":
return v2Result(id: request.id, v2FeedbackSubmit(params: request.params))
case "feed.push":
return v2Result(id: request.id, v2FeedPush(params: request.params))
case "feed.permission.reply":
return v2Result(id: request.id, v2FeedPermissionReply(params: request.params))
case "feed.question.reply":
return v2Result(id: request.id, v2FeedQuestionReply(params: request.params))
case "feed.exit_plan.reply":
return v2Result(id: request.id, v2FeedExitPlanReply(params: request.params))
case let method where method.hasPrefix("vm."):
return socketWorkerCloudVMResponse(method: method, id: request.id, params: request.params)
default:
return v2Error(id: request.id, code: "method_not_found", message: "Unknown method")
}
}

private nonisolated func socketWorkerSystemTopResponseIfNeeded(for command: String) -> String? {
guard command.hasPrefix("{"),
let data = command.data(using: .utf8),
let dict = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String: Any] else {
guard let request = parseV2SocketRequest(command),
request.method == "system.top" else {
return nil
}

let method = (dict["method"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
guard method == "system.top" else { return nil }

let id: Any? = dict["id"]
let params = dict["params"] as? [String: Any] ?? [:]
return withSocketCommandPolicy(commandKey: method, isV2: true) {
v2Result(id: id, v2SystemTop(params: params))
return withSocketCommandPolicy(commandKey: request.method, isV2: true) {
v2Result(id: request.id, v2SystemTop(params: request.params))
}
}

Expand Down Expand Up @@ -1812,31 +1845,40 @@ class TerminalController {
if let response = authResponseIfNeeded(for: command, authenticated: &nextAuthenticated) {
return SocketLineProcessingResult(response: response, authenticated: nextAuthenticated)
}
if let response = socketWorkerAuthResponseIfNeeded(for: command) {
return SocketLineProcessingResult(response: response, authenticated: nextAuthenticated)
}
if let response = socketWorkerFeedbackResponseIfNeeded(for: command) {
return SocketLineProcessingResult(response: response, authenticated: nextAuthenticated)

let response = processCommandUsingSocketExecutionPolicy(command)
return SocketLineProcessingResult(response: response, authenticated: nextAuthenticated)
}

private nonisolated func processCommandUsingSocketExecutionPolicy(_ command: String) -> String {
if Thread.isMainThread,
let request = parseV2SocketRequest(command),
Self.executionPolicy(forV2Method: request.method) == .socketWorker {
return v2Error(
id: request.id,
code: "invalid_dispatch",
message: "\(request.method) must run off the main thread"
)
}
if let response = socketWorkerCloudVMResponseIfNeeded(for: command) {
return SocketLineProcessingResult(response: response, authenticated: nextAuthenticated)

if let response = socketWorkerV2ResponseIfNeeded(for: command) {
return response
}
if let response = socketWorkerSystemTopResponseIfNeeded(for: command) {
return SocketLineProcessingResult(response: response, authenticated: nextAuthenticated)
return response
}

let response = v2MainSync {
return v2MainSync {
self.processCommand(command)
}
return SocketLineProcessingResult(response: response, authenticated: nextAuthenticated)
}

/// Public entry point mirroring the socket's `processCommand` path so
/// in-process callers (e.g. the Feed coordinator's `feed.jump` focus
/// request) can reuse the full V1/V2 dispatcher without duplicating
/// its auth/policy wrappers.
func handleSocketLine(_ line: String) -> String {
return processCommand(line)
nonisolated func handleSocketLine(_ line: String) -> String {
return processCommandUsingSocketExecutionPolicy(line)
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

private func processCommand(_ command: String) -> String {
Expand Down Expand Up @@ -2228,6 +2270,14 @@ class TerminalController {
return v2Error(id: id, code: "invalid_request", message: "Missing method")
}

guard Self.executionPolicy(forV2Method: method) == .mainActor else {
return v2Error(
id: id,
code: "invalid_dispatch",
message: "\(method) must run on the socket worker"
)
}

v2MainSync { self.v2RefreshKnownRefs() }


Expand Down Expand Up @@ -7987,7 +8037,7 @@ class TerminalController {

// MARK: - V2 Feed (workstream) handlers

private func v2FeedPush(params: [String: Any]) -> V2CallResult {
private nonisolated func v2FeedPush(params: [String: Any]) -> V2CallResult {
let waitTimeout: TimeInterval
if let rawTimeout = params["wait_timeout_seconds"] {
let seconds: Double?
Expand Down Expand Up @@ -8052,7 +8102,7 @@ class TerminalController {
return .ok(FeedSocketEncoding.payload(for: result))
}

private func v2FeedPermissionReply(params: [String: Any]) -> V2CallResult {
private nonisolated func v2FeedPermissionReply(params: [String: Any]) -> V2CallResult {
guard let requestId = params["request_id"] as? String else {
return .err(
code: "invalid_params",
Expand All @@ -8076,7 +8126,7 @@ class TerminalController {
return .ok(["delivered": true])
}

private func v2FeedQuestionReply(params: [String: Any]) -> V2CallResult {
private nonisolated func v2FeedQuestionReply(params: [String: Any]) -> V2CallResult {
guard let requestId = params["request_id"] as? String else {
return .err(
code: "invalid_params",
Expand All @@ -8098,7 +8148,7 @@ class TerminalController {
return .ok(["delivered": true])
}

private func v2FeedExitPlanReply(params: [String: Any]) -> V2CallResult {
private nonisolated func v2FeedExitPlanReply(params: [String: Any]) -> V2CallResult {
guard let requestId = params["request_id"] as? String else {
return .err(
code: "invalid_params",
Expand Down
Loading