Open History to see the last commit
1import Foundation
2
3public protocol HTTPTransport: Sendable {
4 func data(for request: URLRequest) async throws -> (Data, HTTPURLResponse)
5 func upload(for request: URLRequest, fromFile fileURL: URL) async throws
6 -> (Data, HTTPURLResponse)
7}
8
9public extension HTTPTransport {
10 /// Test transports can keep recording URLRequest bodies without providing
11 /// a second transport implementation. Production overrides this method.
12 func upload(for request: URLRequest, fromFile fileURL: URL) async throws
13 -> (Data, HTTPURLResponse)
14 {
15 var request = request
16 request.httpBody = try Data(contentsOf: fileURL)
17 return try await data(for: request)
18 }
19}
20
21/// The Core transport deliberately knows nothing about Clerk or the relay.
22/// A managed-environment adapter supplies request-bound DPoP proofs and can
23/// reacquire a bound access token when the current one expires or is rejected.
24public protocol ManagedEnvironmentAuthorizing: Sendable {
25 func credentialRequiresRefresh(
26 _ credential: EnvironmentCredential,
27 environment: Environment
28 ) async throws -> Bool
29
30 func authorize(
31 _ request: URLRequest,
32 environment: Environment,
33 credential: EnvironmentCredential
34 ) async throws -> URLRequest
35
36 func refreshCredential(
37 for environment: Environment,
38 replacing credential: EnvironmentCredential
39 ) async throws -> EnvironmentCredential
40}
41
42public struct URLSessionHTTPTransport: HTTPTransport {
43 private let session: URLSession
44
45 public init(session: URLSession? = nil) {
46 if let session {
47 self.session = session
48 } else {
49 let configuration = URLSessionConfiguration.default
50 configuration.httpAdditionalHeaders = [
51 "Accept-Encoding": HTTPRequestPolicy.acceptEncoding,
52 ]
53 self.session = URLSession(configuration: configuration)
54 }
55 }
56
57 public func data(for request: URLRequest) async throws -> (Data, HTTPURLResponse) {
58 // URLSession transparently decodes gzip responses before returning
59 // their body. Applying the policy here is a final guard for requests
60 // constructed outside EnvironmentAPI.
61 let (data, response) = try await session.data(for: HTTPRequestPolicy.prepare(request))
62 guard let httpResponse = response as? HTTPURLResponse else {
63 throw HTTPError.invalidResponse
64 }
65 return (data, httpResponse)
66 }
67
68 public func upload(for request: URLRequest, fromFile fileURL: URL) async throws
69 -> (Data, HTTPURLResponse)
70 {
71 let (data, response) = try await session.upload(
72 for: HTTPRequestPolicy.prepare(request),
73 fromFile: fileURL
74 )
75 guard let httpResponse = response as? HTTPURLResponse else {
76 throw HTTPError.invalidResponse
77 }
78 return (data, httpResponse)
79 }
80}
81
82/// Shared wire-level defaults for HTTP requests.
83///
84/// Foundation's URL loading system transparently decompresses gzip response
85/// bodies. The explicit offer matters because T3 only compresses JSON when the
86/// client advertises support.
87public enum HTTPRequestPolicy {
88 public static let acceptEncoding = "gzip"
89
90 public static func prepare(_ request: URLRequest) -> URLRequest {
91 var prepared = request
92 if prepared.value(forHTTPHeaderField: "Accept-Encoding") == nil {
93 prepared.setValue(acceptEncoding, forHTTPHeaderField: "Accept-Encoding")
94 }
95 if prepared.value(forHTTPHeaderField: "Accept") == nil {
96 prepared.setValue("application/json", forHTTPHeaderField: "Accept")
97 }
98 return prepared
99 }
100}
101
102public enum HTTPError: LocalizedError, Sendable {
103 case invalidResponse
104 case status(Int, message: String, traceID: String?)
105 case missingCredential
106 case incompatibleCredential
107 case managedAuthorizationUnavailable
108
109 public var errorDescription: String? {
110 switch self {
111 case .invalidResponse:
112 "The server returned an invalid response."
113 case let .status(status, message, traceID):
114 traceID.map { "\(message) (trace \($0))" } ?? "\(message) (HTTP \(status))"
115 case .missingCredential:
116 "This environment has no saved credential."
117 case .incompatibleCredential:
118 "This environment's saved authentication method is invalid. Connect it again."
119 case .managedAuthorizationUnavailable:
120 "This build cannot authorize a managed T3 Connect environment."
121 }
122 }
123}
124
125enum DPoPFailureReason: Decodable, Equatable, Sendable {
126 case timeWindow
127 case keyMismatch
128 case requestMismatch
129 case tokenMismatch
130 case replay
131 case invalidProof
132 case unknown
133
134 init(from decoder: any Decoder) throws {
135 switch try decoder.singleValueContainer().decode(String.self) {
136 case "time_window": self = .timeWindow
137 case "key_mismatch": self = .keyMismatch
138 case "request_mismatch": self = .requestMismatch
139 case "token_mismatch": self = .tokenMismatch
140 case "replay": self = .replay
141 case "invalid_proof": self = .invalidProof
142 default: self = .unknown
143 }
144 }
145}
146
147enum DPoPFailurePresentation {
148 static let clockHint =
149 "Hint: Check that automatic date and time is enabled on both devices, then try again."
150 static let unknownHint =
151 "Hint: Try again. If it still fails, clock skew may be the cause; check that automatic date and time is enabled on both devices."
152 static let retryHint = "Hint: Try again. If the problem continues, copy the trace ID."
153
154 static func message(_ message: String, reason: DPoPFailureReason?) -> String {
155 let hint = if reason == .timeWindow {
156 clockHint
157 } else if reason == nil {
158 unknownHint
159 } else {
160 retryHint
161 }
162 return "\(message) \(hint)"
163 }
164}
165
166struct EnvironmentErrorBody: Decodable {
167 let message: String?
168 let reason: String?
169 let dpopFailureReason: DPoPFailureReason?
170 let traceId: String?
171}
172
173public actor EnvironmentAPI {
174 private static let managedRefreshMargin: TimeInterval = 60
175
176 private let transport: any HTTPTransport
177 private let credentials: any CredentialStore
178 private let managedAuthorization: (any ManagedEnvironmentAuthorizing)?
179
180 public init(
181 transport: any HTTPTransport = URLSessionHTTPTransport(),
182 credentials: any CredentialStore,
183 managedAuthorization: (any ManagedEnvironmentAuthorizing)? = nil
184 ) {
185 self.transport = transport
186 self.credentials = credentials
187 self.managedAuthorization = managedAuthorization
188 }
189
190 public func descriptor(at httpBaseURL: URL) async throws -> EnvironmentDescriptor {
191 try await send(
192 URLRequest(url: endpoint(httpBaseURL, path: "/.well-known/t3/environment")),
193 as: EnvironmentDescriptor.self
194 )
195 }
196
197 public func shellSnapshot(
198 for environment: Environment,
199 timeoutInterval: TimeInterval? = nil
200 ) async throws
201 -> OrchestrationShellSnapshot
202 {
203 try await authorized(
204 environment: environment,
205 path: "/api/orchestration/shell",
206 method: "GET",
207 timeoutInterval: timeoutInterval,
208 as: OrchestrationShellSnapshot.self
209 )
210 }
211
212 public func readModel(for environment: Environment) async throws -> OrchestrationReadModel {
213 try await authorized(
214 environment: environment,
215 path: "/api/orchestration/snapshot",
216 method: "GET",
217 as: OrchestrationReadModel.self
218 )
219 }
220
221 public func threadSnapshot(
222 id: String,
223 environment: Environment,
224 turnLimit: Int? = nil,
225 beforeCursor: String? = nil,
226 timeoutInterval: TimeInterval? = nil
227 ) async throws -> OrchestrationThreadDetailSnapshot {
228 let encodedID = id.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? id
229 var queryItems: [URLQueryItem] = []
230 if let turnLimit {
231 queryItems.append(URLQueryItem(name: "turnLimit", value: String(turnLimit)))
232 }
233 if let beforeCursor {
234 queryItems.append(URLQueryItem(name: "beforeCursor", value: beforeCursor))
235 }
236 return try await authorized(
237 environment: environment,
238 path: "/api/orchestration/threads/\(encodedID)",
239 queryItems: queryItems,
240 method: "GET",
241 timeoutInterval: timeoutInterval,
242 as: OrchestrationThreadDetailSnapshot.self
243 )
244 }
245
246 public func dispatch(
247 _ command: JSONValue,
248 environment: Environment
249 ) async throws -> DispatchResult {
250 try await authorized(
251 environment: environment,
252 path: "/api/orchestration/dispatch",
253 method: "POST",
254 body: JSONEncoder.t3.encode(command),
255 as: DispatchResult.self
256 )
257 }
258
259 public func pullRequestDiff(
260 _ input: PullRequestDiffInput,
261 environment: Environment
262 ) async throws -> PullRequestDiffResult {
263 try await authorized(
264 environment: environment,
265 path: "/api/pull-requests/diff",
266 method: "POST",
267 body: JSONEncoder.t3.encode(input),
268 timeoutInterval: 60,
269 as: PullRequestDiffResult.self
270 )
271 }
272
273 /// Upload URLs carry their own short-lived signature and do not need the
274 /// environment's bearer token or DPoP authorization headers.
275 public func uploadAttachment(
276 _ data: Data,
277 mimeType: String,
278 to url: URL
279 ) async throws {
280 var request = URLRequest(url: url, timeoutInterval: 60)
281 request.httpMethod = "POST"
282 request.httpBody = data
283 request.setValue(mimeType, forHTTPHeaderField: "Content-Type")
284 request.setValue(String(data.count), forHTTPHeaderField: "Content-Length")
285
286 let (responseData, response) = try await transport.data(
287 for: HTTPRequestPolicy.prepare(request)
288 )
289 guard (200...299).contains(response.statusCode) else {
290 let detail = String(data: responseData, encoding: .utf8)?
291 .trimmingCharacters(in: .whitespacesAndNewlines)
292 throw HTTPError.status(
293 response.statusCode,
294 message: detail.flatMap { $0.isEmpty ? nil : $0 } ?? "Image upload failed.",
295 traceID: nil
296 )
297 }
298 }
299
300 /// Production uses URLSession's file upload API so large attachments never
301 /// become one in-memory Data value.
302 public func uploadAttachment(
303 fileURL: URL,
304 byteCount: Int,
305 mimeType: String,
306 to url: URL
307 ) async throws {
308 var request = URLRequest(url: url, timeoutInterval: 60)
309 request.httpMethod = "POST"
310 request.setValue(mimeType, forHTTPHeaderField: "Content-Type")
311 request.setValue(String(byteCount), forHTTPHeaderField: "Content-Length")
312
313 let (responseData, response) = try await transport.upload(
314 for: HTTPRequestPolicy.prepare(request),
315 fromFile: fileURL
316 )
317 guard (200...299).contains(response.statusCode) else {
318 let detail = String(data: responseData, encoding: .utf8)?
319 .trimmingCharacters(in: .whitespacesAndNewlines)
320 throw HTTPError.status(
321 response.statusCode,
322 message: detail.flatMap { $0.isEmpty ? nil : $0 } ?? "File upload failed.",
323 traceID: nil
324 )
325 }
326 }
327
328 public func webSocketTicket(for environment: Environment) async throws -> WebSocketTicket {
329 try await authorized(
330 environment: environment,
331 path: "/api/auth/websocket-ticket",
332 method: "POST",
333 as: WebSocketTicket.self
334 )
335 }
336
337 public func session(for environment: Environment) async throws -> AuthSessionState {
338 try await authorized(
339 environment: environment,
340 path: "/api/auth/session",
341 method: "GET",
342 as: AuthSessionState.self
343 )
344 }
345
346 public func clientSessions(for environment: Environment) async throws
347 -> [AuthClientSession]
348 {
349 try await authorized(
350 environment: environment,
351 path: "/api/auth/clients",
352 method: "GET",
353 as: [AuthClientSession].self
354 )
355 }
356
357 public func revokeClientSession(
358 id: String,
359 environment: Environment
360 ) async throws -> AuthClientSessionRevokeResult {
361 try await authorized(
362 environment: environment,
363 path: "/api/auth/clients/revoke",
364 method: "POST",
365 body: JSONEncoder.t3.encode(["sessionId": id]),
366 as: AuthClientSessionRevokeResult.self
367 )
368 }
369
370 public func revokeOtherClientSessions(
371 for environment: Environment
372 ) async throws -> AuthOtherClientSessionsRevokeResult {
373 try await authorized(
374 environment: environment,
375 path: "/api/auth/clients/revoke-others",
376 method: "POST",
377 as: AuthOtherClientSessionsRevokeResult.self
378 )
379 }
380
381 private func authorized<Result: Decodable & Sendable>(
382 environment: Environment,
383 path: String,
384 queryItems: [URLQueryItem] = [],
385 method: String,
386 body: Data? = nil,
387 timeoutInterval: TimeInterval? = nil,
388 as type: Result.Type
389 ) async throws -> Result {
390 guard let credential = try await credentials.credential(for: environment.id) else {
391 throw HTTPError.missingCredential
392 }
393
394 switch environment.kind {
395 case .bearer, .local:
396 guard credential.authorizationMethod == .bearer else {
397 throw HTTPError.incompatibleCredential
398 }
399 var request = makeRequest(
400 environment: environment,
401 path: path,
402 queryItems: queryItems,
403 method: method,
404 body: body
405 )
406 if let timeoutInterval {
407 request.timeoutInterval = timeoutInterval
408 }
409 request.setValue(
410 "Bearer \(credential.accessToken)",
411 forHTTPHeaderField: "Authorization"
412 )
413 return try await send(request, as: type)
414
415 case .managedDPoP:
416 guard credential.authorizationMethod == .dpop,
417 credential.managedEnvironmentID == environment.id else {
418 throw HTTPError.incompatibleCredential
419 }
420 guard let managedAuthorization else {
421 throw HTTPError.managedAuthorizationUnavailable
422 }
423
424 var current = credential
425 let bindingRequiresRefresh = try await managedAuthorization
426 .credentialRequiresRefresh(current, environment: environment)
427 if current.expiresAt?.timeIntervalSinceNow ?? 0 <= Self.managedRefreshMargin
428 || bindingRequiresRefresh {
429 current = try await refreshManagedCredential(
430 current,
431 environment: environment,
432 using: managedAuthorization
433 )
434 }
435 var request = try await managedAuthorization.authorize(
436 makeRequest(
437 environment: environment,
438 path: path,
439 queryItems: queryItems,
440 method: method,
441 body: body
442 ),
443 environment: environment,
444 credential: current
445 )
446 if let timeoutInterval {
447 request.timeoutInterval = timeoutInterval
448 }
449 do {
450 return try await send(request, as: type)
451 } catch let error as HTTPError where error.isRejectedAuthorization {
452 if let saved = try await newestUsableManagedCredential(
453 replacing: current,
454 environment: environment,
455 using: managedAuthorization
456 ) {
457 current = saved
458 } else {
459 current = try await refreshManagedCredential(
460 current,
461 environment: environment,
462 using: managedAuthorization
463 )
464 }
465 var retry = try await managedAuthorization.authorize(
466 makeRequest(
467 environment: environment,
468 path: path,
469 queryItems: queryItems,
470 method: method,
471 body: body
472 ),
473 environment: environment,
474 credential: current
475 )
476 if let timeoutInterval {
477 retry.timeoutInterval = timeoutInterval
478 }
479 return try await send(retry, as: type)
480 }
481 }
482 }
483
484 private func makeRequest(
485 environment: Environment,
486 path: String,
487 queryItems: [URLQueryItem],
488 method: String,
489 body: Data?
490 ) -> URLRequest {
491 var request = URLRequest(
492 url: endpoint(environment.httpBaseURL, path: path, queryItems: queryItems)
493 )
494 request.httpMethod = method
495 request.httpBody = body
496 if body != nil {
497 request.setValue("application/json", forHTTPHeaderField: "Content-Type")
498 }
499 return request
500 }
501
502 private func refreshManagedCredential(
503 _ credential: EnvironmentCredential,
504 environment: Environment,
505 using managedAuthorization: any ManagedEnvironmentAuthorizing
506 ) async throws -> EnvironmentCredential {
507 if let current = try await newestUsableManagedCredential(
508 replacing: credential,
509 environment: environment,
510 using: managedAuthorization
511 ) {
512 return current
513 }
514 let refreshed = try await managedAuthorization.refreshCredential(
515 for: environment,
516 replacing: credential
517 )
518 guard refreshed.authorizationMethod == .dpop,
519 refreshed.managedEnvironmentID == environment.id,
520 refreshed.proofKeyThumbprint?.isEmpty == false else {
521 throw HTTPError.incompatibleCredential
522 }
523 guard try await credentials.replaceCredential(
524 refreshed,
525 ifMatching: credential,
526 for: environment.id
527 ) else {
528 if let current = try await newestUsableManagedCredential(
529 replacing: credential,
530 environment: environment,
531 using: managedAuthorization
532 ) {
533 return current
534 }
535 throw HTTPError.missingCredential
536 }
537 return refreshed
538 }
539
540 private func newestUsableManagedCredential(
541 replacing credential: EnvironmentCredential,
542 environment: Environment,
543 using managedAuthorization: any ManagedEnvironmentAuthorizing
544 ) async throws -> EnvironmentCredential? {
545 guard let saved = try await credentials.credential(for: environment.id),
546 saved != credential,
547 saved.authorizationMethod == .dpop,
548 saved.managedEnvironmentID == environment.id,
549 saved.proofKeyThumbprint?.isEmpty == false,
550 saved.expiresAt?.timeIntervalSinceNow ?? 0 > Self.managedRefreshMargin else {
551 return nil
552 }
553 let requiresRefresh = try await managedAuthorization.credentialRequiresRefresh(
554 saved,
555 environment: environment
556 )
557 guard !requiresRefresh else { return nil }
558 return saved
559 }
560
561 private func send<Result: Decodable & Sendable>(
562 _ request: URLRequest,
563 as type: Result.Type
564 ) async throws -> Result {
565 let (data, response) = try await transport.data(for: HTTPRequestPolicy.prepare(request))
566 guard (200..<300).contains(response.statusCode) else {
567 let body = try? JSONDecoder.t3.decode(EnvironmentErrorBody.self, from: data)
568 let message: String
569 if response.statusCode == 401,
570 request.value(forHTTPHeaderField: "DPoP") != nil,
571 body?.reason == "invalid_credential"
572 {
573 message = DPoPFailurePresentation.message(
574 "The environment credential is invalid.",
575 reason: body?.dpopFailureReason
576 )
577 } else {
578 message = body?.message ?? body?.reason ?? "Environment request failed."
579 }
580 throw HTTPError.status(
581 response.statusCode,
582 message: message,
583 traceID: body?.traceId
584 )
585 }
586 return try JSONDecoder.t3.decode(type, from: data)
587 }
588}
589
590private extension HTTPError {
591 var isRejectedAuthorization: Bool {
592 guard case let .status(status, _, _) = self else { return false }
593 return status == 401
594 }
595}
596
597public struct DispatchResult: Codable, Equatable, Sendable {
598 public let sequence: Int
599}
600
601public struct WebSocketTicket: Codable, Equatable, Sendable {
602 public let ticket: String
603 public let expiresAt: String
604}
605
606public struct AuthSessionState: Codable, Equatable, Sendable {
607 public let authenticated: Bool
608 public let scopes: [String]?
609 public let sessionMethod: String?
610 public let expiresAt: String?
611}
612
613public struct AuthClientMetadata: Codable, Equatable, Sendable {
614 public let label: String?
615 public let ipAddress: String?
616 public let userAgent: String?
617 public let deviceType: String
618 public let os: String?
619 public let browser: String?
620}
621
622public struct AuthClientSession: Codable, Identifiable, Equatable, Sendable {
623 public var id: String { sessionId }
624
625 public let sessionId: String
626 public let subject: String
627 public let scopes: [String]
628 public let method: String
629 public let client: AuthClientMetadata
630 public let issuedAt: String
631 public let expiresAt: String
632 public let lastConnectedAt: String?
633 public let connected: Bool
634 public let current: Bool
635}
636
637public struct AuthClientSessionRevokeResult: Codable, Equatable, Sendable {
638 public let revoked: Bool
639}
640
641public struct AuthOtherClientSessionsRevokeResult: Codable, Equatable, Sendable {
642 public let revokedCount: Int
643}
644
645func endpoint(_ baseURL: URL, path: String, queryItems: [URLQueryItem] = []) -> URL {
646 var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: false)!
647 components.path = path
648 components.queryItems = queryItems.isEmpty ? nil : queryItems
649 components.fragment = nil
650 return components.url!
651}