Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions Helpers/AgentCatalogMCP.swift
Original file line number Diff line number Diff line change
Expand Up @@ -184,8 +184,8 @@ import Security
clientOverride = AgentPairing.clientName(arguments[flag + 1])
}
if arguments.contains("--forget-key") {
// Explicit reset from the same registered host. A revoked credential
// stays revoked until the host requests a reset and the user approves again.
// Explicit reset from the same registered host. Not needed after a
// revocation: a new session of the host asks the user again.
guard let registeredHost else { exit(1) }
exit(ClientKey.delete(host: registeredHost) ? 0 : 1)
}
Expand Down Expand Up @@ -421,7 +421,7 @@ import Security
("unproven", "The selected instruction changed or was not read by this helper. Read it again with \(reader), then resend with the returned profile and revision."),
("approval_required", "Ask the user to approve this pending connection in the app. Do not retry in a loop."),
("disabled", "Draft receipt is off for this app or globally. Ask the user to turn it on."),
("revoked", "This app's approval was revoked. It requires a credential reset and new approval."),
("revoked", "The user revoked this app's approval for this session. Stop. A new agent session asks the user for approval again."),
("locked", "The Mac is locked. Retry after the user unlocks it."),
("too_large", "A field is over its limit. Nothing was opened or shortened. Shorten it, or split the body into separate drafts with their own keys."),
("invalid", "A field is missing, misnamed or malformed. Fix the arguments; resending unchanged will not help."),
Expand Down Expand Up @@ -476,6 +476,18 @@ import Security
/// it yet, proves which client it is. Never needs the user unless the app
/// answers that an approval is required.
static func pairingStatus() -> String {
// Once the user revoked this app, this helper process stays revoked, also
// after the app restarts; a new session asks for approval again (#43).
if revokedHere { return "revoked" }
let status = queryPairingStatus()
if status == "revoked" { revokedHere = true }
return status
}

/// Set by the app's first "revoked" answer to this process.
static var revokedHere = false

private static func queryPairingStatus() -> String {
guard pin != nil else { return "signing_required" }
slot = nil
let schema = AgentPairing.schema
Expand Down Expand Up @@ -517,7 +529,7 @@ import Security
case "approval_required": return "Ask the user to approve this specific pending connection in \(TTSRuntime.displayName) → Agent (에이전트), then check again."
case "disabled": return "Draft receipt is off globally or for this agent app. Ask the user to enable it in \(TTSRuntime.displayName) → Agent (에이전트)."
case "locked": return "The Mac's screen is locked, so nothing is received. Retry after the user unlocks it; no new approval is needed."
case "revoked": return "The user removed this client in \(TTSRuntime.displayName). An explicit host credential reset and a new approval are required for this registered agent."
case "revoked": return "The user revoked this app's approval in \(TTSRuntime.displayName). This session stays disconnected; start a new agent session to ask the user for approval again."
case "upgrade_required": return "The running app and this helper are different versions. Use the helper bundled with the running app."
case "reading_only": return "Connected. One instruction revision is approved. Draft receipt is off."
case "receiving_only": return "Connected. Send with submit_tts_draft; there is no selected instruction."
Expand Down
15 changes: 11 additions & 4 deletions Sources/App/AgentSessionController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,8 @@ import Security
if blockedPeers.contains(peer) { return ["status": "revoked"] }
guard let keyID = AgentPairingProof.keyID(publicKey) else { return ["status": "invalid"] }
let host = persistent ? AgentPeerSigning.registeredHost(pid: peer.pid) : nil
if trust.lookup(keyID: keyID, host: host ?? "") == .revoked { return ["status": "revoked"] }
// A revoked key gets a challenge like an unknown one: a new helper
// process may ask the user again (the revoked live helper stays blocked).
var bytes = [UInt8](repeating: 0, count: 32)
guard SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) == errSecSuccess else { return ["status": "unavailable"] }
let nonce = Data(bytes).base64EncodedString()
Expand Down Expand Up @@ -400,7 +401,6 @@ import Security
let lookup = trust.lookup(keyID: claim.keyID, host: claim.host ?? "")
let outcome: [String: String]
switch lookup {
case .revoked: outcome = ["status": "revoked"]
case .trusted(let record) where claim.host != nil:
if !autoReceive || !record.receiptEnabled { outcome = ["status": "disabled"] }
else if bindings[record.id] != nil { outcome = ["status": "other_agent"] }
Expand Down Expand Up @@ -483,8 +483,7 @@ import Security
removeApproval(id)
let claim = request.claim
guard ContinuousClock.now < request.deadline, Self.sameHost(as: claim),
!blockedPeers.contains(claim.peer), binding(for: claim.peer) == nil,
trust.lookup(keyID: claim.keyID, host: claim.host ?? "") != .revoked else { return false }
!blockedPeers.contains(claim.peer), binding(for: claim.peer) == nil else { return false }
var client = UUID()
if let host = claim.host {
switch trust.lookup(keyID: claim.keyID, host: host) {
Expand Down Expand Up @@ -820,8 +819,16 @@ import Security
private func adoptStoreAfterTakeover() {
let wasFailed = trust.readFailed
let priorKeys = Dictionary(trust.clients.map { ($0.id, $0.keyID) }, uniquingKeysWith: { first, _ in first })
let priorRevoked = Set(trust.file.revoked)
// Only the socket holder writes the file; another instance only reads it.
trust.adoptDisk(writeBack: pairingSocket != nil)
// A request raised before its key was revoked elsewhere cannot lift that
// revocation; a new session of the app asks again (#43).
let newlyRevoked = Set(trust.file.revoked).subtracting(priorRevoked)
if !newlyRevoked.isEmpty {
for request in approvalRequests where newlyRevoked.contains(request.claim.keyID) { removeApproval(request.id) }
challenges.removeAll { newlyRevoked.contains($0.keyID) }
}
// A remembered instruction choice belongs to the key that was approved
// when it was made; a removed or replaced key does not inherit it.
let keys = Dictionary(trust.clients.map { ($0.id, $0.keyID) }, uniquingKeysWith: { first, _ in first })
Expand Down
11 changes: 11 additions & 0 deletions Sources/Core/AgentMCPConfiguration.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,15 @@ struct AgentMCPConfiguration {
let quoted = "'" + entry.replacingOccurrences(of: "'", with: "'\\''") + "'"
return "claude mcp add-json \(serverName) \(quoted) --scope user"
}

/// The common `mcpServers` JSON entry that the Claude desktop app
/// (claude_desktop_config.json) and most other stdio MCP clients read (#43).
/// Copied only: the user merges it into the client's file and restarts it.
var mcpServersJSON: String? {
guard let json = try? JSONSerialization.data(
withJSONObject: ["mcpServers": [serverName: ["command": command, "args": [String]()]]],
options: [.sortedKeys, .withoutEscapingSlashes, .prettyPrinted]),
let text = String(data: json, encoding: .utf8) else { return nil }
return text + "\n"
}
}
17 changes: 12 additions & 5 deletions Sources/Core/AgentTrustStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ final class AgentTrustStore {
lastGood = loaded
savedRevoked.formUnion(loaded.revoked)
needsAdopt = false
// Revocations are never undone (a revoked key cannot be approved again),
// Revocations are undone only by the user's new approval of that key,
// so every revocation this run knows is kept, also over a restored older
// copy that predates it. Receipt choices are not merged this way: the user
// may have turned receipt back on through another instance in between.
Expand Down Expand Up @@ -330,10 +330,12 @@ final class AgentTrustStore {

/// Explicit approval can renew or rotate the credential for one registered
/// host. Other hosts keep their records even when the labels match.
/// A revoked key can be approved again only by the user's new approval
/// (#33 manual check 6/7): the approval lifts its revocation.
func trust(publicKey: Data, label: String, host: String) throws -> AgentTrustedClient {
guard let keyID = AgentPairingProof.keyID(publicKey) else { throw Failure.invalid }
guard !file.revoked.contains(keyID) else { throw Failure.revoked }
var next = file
next.revoked.removeAll { $0 == keyID }
let time = now()
let client: AgentTrustedClient
var replaced: String?
Expand All @@ -357,7 +359,12 @@ final class AgentTrustStore {
next.clients.append(client)
}
if let replaced, !pending.contains(.revoke(replaced)) { pending.append(.revoke(replaced)) }
// An unsaved revocation of this key must not undo the new approval later.
let hadPendingRevoke = pending.contains(.revoke(keyID))
pending.removeAll { $0 == .revoke(keyID) }
guard grant(next, byUser: false) else {
// Not approved: the key stays revoked as before.
if hadPendingRevoke, !pending.contains(.revoke(keyID)) { pending.append(.revoke(keyID)) }
// The new key is not approved, but the replaced one stays revoked.
if let replaced {
Self.apply(.revoke(replaced), to: &file)
Expand Down Expand Up @@ -397,9 +404,9 @@ final class AgentTrustStore {
_ = commit(next, byUser: false, denial: false)
}

/// Forgetting tombstones the key, so the same credential cannot come back
/// even inside a later approval window. Fails closed in memory if the disk
/// write fails.
/// Forgetting revokes the key: it is refused until the user approves a new
/// request from it, and a restored older copy does not bring it back. Fails
/// closed in memory if the disk write fails.
@discardableResult
func forget(_ id: UUID) -> Bool {
guard let client = file.clients.first(where: { $0.id == id }) else { return false }
Expand Down
18 changes: 16 additions & 2 deletions Sources/UI/ExplainWorkspace.swift
Original file line number Diff line number Diff line change
Expand Up @@ -575,15 +575,20 @@ struct ExplainWorkspace: View {
copyMCP(command, client: "Claude Code")
}
}
if let desktop = setup.mcpServersJSON {
Button("JSON · mcpServers (Claude 데스크톱 앱 등)") {
copyMCP(desktop, client: "JSON")
}
}
}
.accessibilityLabel("MCP 설정 복사")
.accessibilityHint("Codex 또는 Claude Code 설정을 클립보드에 복사합니다.")
.accessibilityHint("Codex, Claude Code 또는 mcpServers JSON 형식(Claude 데스크톱 앱 등) 설정을 클립보드에 복사합니다.")
if let copiedMCPClient {
Text("\(copiedMCPClient) 설정 복사됨").font(.caption).foregroundStyle(.secondary)
}
}
if let copiedMCPClient {
Text(copiedMCPClient == "Codex" ? "config.toml에 붙여넣으세요." : "터미널에 붙여넣고 실행하세요.")
Text(Self.pasteHint(for: copiedMCPClient))
.font(.caption).foregroundStyle(.secondary)
}
} else {
Expand All @@ -593,6 +598,15 @@ struct ExplainWorkspace: View {
}
}

private static func pasteHint(for client: String) -> String {
switch client {
case "Codex": return "config.toml에 붙여넣으세요."
case "JSON":
return "설정 파일이 비어 있으면 그대로 붙여넣으세요. 이미 mcpServers가 있으면 복사한 내용 중 서버 이름과 그 중괄호 묶음 전체를 기존 mcpServers 안에 쉼표로 이어 넣으세요. 그다음 그 앱을 완전히 종료하고 다시 여세요. Claude 데스크톱 앱은 설정 › 개발자 › 구성 편집으로 claude_desktop_config.json을 엽니다."
default: return "터미널에 붙여넣고 실행하세요."
}
}

private func copyMCP(_ text: String, client: String) {
let clipboard = NSPasteboard.general
clipboard.clearContents()
Expand Down
29 changes: 25 additions & 4 deletions Tests/AgentCatalogTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -441,10 +441,15 @@ enum CodeExplanation { static let noChange = "변경 없음" }
precondition(store.forget(renewed.id))
store = open()
precondition(store.lookup(keyID: keyID, host: "h") == .revoked && store.clients.count == AgentTrustStore.maxClients - 1)
do {
_ = try store.trust(publicKey: publicKey, label: "claude", host: "h")
preconditionFailure("a forgotten key must not be approved again")
} catch AgentTrustStore.Failure.revoked {}
// The user's new approval of a forgotten key lifts its revocation (#33 manual
// check 6/7), also after a restart; forgetting it again revokes it again.
let reapproved = try store.trust(publicKey: publicKey, label: "claude", host: "h")
precondition(store.lookup(keyID: keyID, host: "h") == .trusted(reapproved) && !store.file.revoked.contains(keyID))
store = open()
precondition(store.lookup(keyID: keyID, host: "h") == .trusted(reapproved))
precondition(store.forget(reapproved.id))
store = open()
precondition(store.lookup(keyID: keyID, host: "h") == .revoked)

let retryURL = directory.appendingPathComponent("agent-denial.json")
var writesFail = false
Expand All @@ -464,6 +469,22 @@ enum CodeExplanation { static let noChange = "변경 없음" }
precondition(retry.setReceiptEnabled(false, for: rotated.id))
let restarted = AgentTrustStore(url: retryURL)
precondition(!restarted.autoReceive && restarted.clients.count == 1 && !restarted.clients[0].receiptEnabled)
// A revocation not saved yet does not undo a later approval of the same key,
// and a failed approval leaves it revoked and pending.
writesFail = true
precondition(!retry.forget(rotated.id) && retry.hasUnsavedDenials)
let otherKey = other.publicKey.x963Representation
let otherID = AgentPairingProof.keyID(otherKey)!
do {
_ = try retry.trust(publicKey: otherKey, label: "same", host: registeredHost)
preconditionFailure("an approval that cannot be saved must fail")
} catch AgentTrustStore.Failure.unwritable {}
precondition(retry.lookup(keyID: otherID, host: registeredHost) == .revoked && retry.hasUnsavedDenials)
writesFail = false
let back = try retry.trust(publicKey: otherKey, label: "same", host: registeredHost)
retry.adoptDisk()
precondition(retry.lookup(keyID: otherID, host: registeredHost) == .trusted(back) && !retry.hasUnsavedDenials)
precondition(AgentTrustStore(url: retryURL).lookup(keyID: otherID, host: registeredHost) == .trusted(back))

// Anything but our own private, intact file is no trust at all.
precondition(chmod(url.path, 0o644) == 0 && open().clients.isEmpty && !open().autoReceive)
Expand Down
5 changes: 5 additions & 0 deletions Tests/AgentMCPConfigurationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ import Foundation
precondition(AgentMCPConfiguration(command: "/invalid\0path", bundleID: productionID) == nil)
precondition(config.codexTOML.contains("O'Brian"))
precondition(config.claudeCodeCommand!.contains("O'\\''Brian"))
// The desktop entry is JSON that parses back to the exact path (#43).
let desktop = try JSONSerialization.jsonObject(with: Data(config.mcpServersJSON!.utf8)) as! [String: Any]
let servers = desktop["mcpServers"] as! [String: Any]
let entry = servers["codebasic_tts_agent"] as! [String: Any]
precondition(servers.count == 1 && entry["command"] as? String == path && (entry["args"] as? [String]) == [])
precondition(AgentMCPConfiguration.bundled(in: .main) == nil)

let tested: AgentMCPConfiguration
Expand Down
8 changes: 6 additions & 2 deletions Tests/Fixtures/run_agent_app_connections.py
Original file line number Diff line number Diff line change
Expand Up @@ -295,11 +295,15 @@ def connect(host, helper="helper", key_dir=keys):
expect_status(a, "revoked")
assert a.send("after-revoke", "철회 뒤 차단되는 원고")["outcome"] == "rejected"
a.close()
# A new session of the revoked app asks the user again (#33 manual check 6/7).
a = connect("A")
expect_status(a, "revoked")
expect_status(a, "approval_required")
request_again, = requests(server)
expect_status(b, "receiving_only")
assert b.send("after-other-revoke", "다른 앱 철회 뒤의 B 원고")["status"] == "accepted"
check("master off survives restart; revocation clears A's pending approvals and blocks its old key")
approve(server, a, request_again)
check("master off survives restart; revocation clears A's pending approvals and blocks its live helper; "
"a new A session asks again")

other = connect("B", helper="other-helper")
expect_status(other, "app_unavailable")
Expand Down
26 changes: 17 additions & 9 deletions Tests/Fixtures/run_persistent_pairing.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,21 +304,29 @@ def client_id():
assert server.snapshot()["trusted"] == [slot_a]
ok("lost or replaced client key: blocked until a new approval, which supersedes the old record")

# forget <id> revokes the app's key (#13): a late request and a restart with the
# same key are refused for good; only a key reset and a new approval connect again.
# forget <id> revokes the app's key (#13): a late request is refused and that
# helper stays revoked. A new session with the same key asks the user again and
# connects only after a new approval (#33 manual check 6/7).
assert server("forget " + client_id()) == "ok"
late = a.send("late", "잊은 뒤 늦은 요청")
assert late["outcome"] == "rejected" and server.documents() == []
assert a.status() == "revoked" and server.snapshot()["trusted"] == []
a.close()
revoked_helper = a
a = client()
assert a.status() == "revoked" and not server.snapshot()["paired"]
a.close()
assert forget_key(slot_a) == 0
a = client()
assert a.status() == "approval_required"
assert a.status() == "approval_required" and not server.snapshot()["paired"]
assert server.snapshot()["trusted"] == []
assert fs.approve(server, a) == "receiving_only"; clicks += 1
ok("forget: late request and restart are refused; only a new approval with a new key connects again")
assert server.snapshot()["trusted"] == [slot_a]
# The revoked helper stays revoked, also once its key is approved again and
# after the app restarts, and raises no request.
assert revoked_helper.status() == "revoked"
server.end()
server = app()
assert revoked_helper.status() == "revoked" and a.status() == "receiving_only"
assert json.loads(server("requests")) == []
revoked_helper.close()
ok("forget: late request refused, that helper stays revoked across re-approval and app restart; "
"a new session asks again and connects after approval")

# disconnect <id> is this app's receipt off (#13): it keeps the approval and stays
# off across client and app restarts; resume turns it back on with no new pairing.
Expand Down
Loading