Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

HTTP.swift

717 lines25.2 KB

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 }
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
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 }
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 }
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 case unauthenticatedSession
109​
110 public var errorDescription: String? {
111 switch self {
112 case .invalidResponse:
113 "The server returned an invalid response."
114 case let .status(status, message, traceID):
115 traceID.map { "\(message) (trace \($0))" } ?? "\(message) (HTTP \(status))"
116 case .missingCredential:
117 "This environment has no saved credential."
118 case .incompatibleCredential:
119 "This environment's saved authentication method is invalid. Connect it again."
120 case .managedAuthorizationUnavailable:
121 "This build cannot authorize a managed T3 Connect environment."
122 case .unauthenticatedSession:
123 "The environment rejected the session authorization."
124 }
125 }
127​
128struct T3ConnectNetworkError: LocalizedError, Sendable {
129 static let hint =
130 "Your DNS or firewall may be blocking T3 Connect. Try another network, such as a phone hotspot."
131​
132 let message: String
133​
134 var errorDescription: String? { "\(message) \(Self.hint)" }
135​
136 // A failed transport can be an outage or filtering. Keep protocol and
137 // authentication errors unchanged because they have a server response.
138 static func wrapping(_ error: any Error) -> any Error {
139 guard let error = error as? URLError else { return error }
140 switch error.code {
141 case .timedOut, .cannotFindHost, .cannotConnectToHost, .dnsLookupFailed,
142 .networkConnectionLost, .notConnectedToInternet:
143 return Self(message: error.localizedDescription)
144 default:
145 return error
146 }
147 }
149​
150enum DPoPFailureReason: Decodable, Equatable, Sendable {
151 case timeWindow
152 case keyMismatch
153 case requestMismatch
154 case tokenMismatch
155 case replay
156 case invalidProof
157 case unknown
158​
159 init(from decoder: any Decoder) throws {
160 switch try decoder.singleValueContainer().decode(String.self) {
161 case "time_window": self = .timeWindow
162 case "key_mismatch": self = .keyMismatch
163 case "request_mismatch": self = .requestMismatch
164 case "token_mismatch": self = .tokenMismatch
165 case "replay": self = .replay
166 case "invalid_proof": self = .invalidProof
167 default: self = .unknown
168 }
169 }
171​
172enum DPoPFailurePresentation {
173 static let clockHint =
174 "Hint: Check that automatic date and time is enabled on both devices, then try again."
175 static let unknownHint =
176 "Hint: Try again. If it still fails, clock skew may be the cause; check that automatic date and time is enabled on both devices."
177 static let retryHint = "Hint: Try again. If the problem continues, copy the trace ID."
178​
179 static func message(_ message: String, reason: DPoPFailureReason?) -> String {
180 let hint = if reason == .timeWindow {
181 clockHint
182 } else if reason == nil {
183 unknownHint
184 } else {
185 retryHint
186 }
187 return "\(message) \(hint)"
188 }
190​
191struct EnvironmentErrorBody: Decodable {
192 let message: String?
193 let reason: String?
194 let dpopFailureReason: DPoPFailureReason?
195 let traceId: String?
197​
198public actor EnvironmentAPI {
199 private static let managedRefreshMargin: TimeInterval = 60
200​
201 private let transport: any HTTPTransport
202 private let credentials: any CredentialStore
203 private let managedAuthorization: (any ManagedEnvironmentAuthorizing)?
204​
205 public init(
206 transport: any HTTPTransport = URLSessionHTTPTransport(),
207 credentials: any CredentialStore,
208 managedAuthorization: (any ManagedEnvironmentAuthorizing)? = nil
209 ) {
210 self.transport = transport
211 self.credentials = credentials
212 self.managedAuthorization = managedAuthorization
213 }
214​
215 public func descriptor(at httpBaseURL: URL) async throws -> EnvironmentDescriptor {
216 try await send(
217 URLRequest(url: endpoint(httpBaseURL, path: "/.well-known/t3/environment")),
218 as: EnvironmentDescriptor.self
219 )
220 }
221​
222 public func shellSnapshot(
223 for environment: Environment,
224 timeoutInterval: TimeInterval? = nil
225 ) async throws
226 -> OrchestrationShellSnapshot
227 {
228 try await authorized(
229 environment: environment,
230 path: "/api/orchestration/shell",
231 method: "GET",
232 timeoutInterval: timeoutInterval,
233 as: OrchestrationShellSnapshot.self
234 )
235 }
236​
237 public func readModel(for environment: Environment) async throws -> OrchestrationReadModel {
238 try await authorized(
239 environment: environment,
240 path: "/api/orchestration/snapshot",
241 method: "GET",
242 as: OrchestrationReadModel.self
243 )
244 }
245​
246 public func threadSnapshot(
247 id: String,
248 environment: Environment,
249 turnLimit: Int? = nil,
250 beforeCursor: String? = nil,
251 timeoutInterval: TimeInterval? = nil
252 ) async throws -> OrchestrationThreadDetailSnapshot {
253 let encodedID = id.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? id
254 var queryItems: [URLQueryItem] = []
255 if let turnLimit {
256 queryItems.append(URLQueryItem(name: "turnLimit", value: String(turnLimit)))
257 }
258 if let beforeCursor {
259 queryItems.append(URLQueryItem(name: "beforeCursor", value: beforeCursor))
260 }
261 return try await authorized(
262 environment: environment,
263 path: "/api/orchestration/threads/\(encodedID)",
264 queryItems: queryItems,
265 method: "GET",
266 timeoutInterval: timeoutInterval,
267 as: OrchestrationThreadDetailSnapshot.self
268 )
269 }
270​
271 public func dispatch(
272 _ command: JSONValue,
273 environment: Environment
274 ) async throws -> DispatchResult {
275 try await authorized(
276 environment: environment,
277 path: "/api/orchestration/dispatch",
278 method: "POST",
279 body: JSONEncoder.t3.encode(command),
280 as: DispatchResult.self
281 )
282 }
283​
284 public func pullRequestDiff(
285 _ input: PullRequestDiffInput,
286 environment: Environment
287 ) async throws -> PullRequestDiffResult {
288 try await authorized(
289 environment: environment,
290 path: "/api/pull-requests/diff",
291 method: "POST",
292 body: JSONEncoder.t3.encode(input),
293 timeoutInterval: 60,
294 as: PullRequestDiffResult.self
295 )
296 }
297​
298 /// Upload URLs carry their own short-lived signature and do not need the
299 /// environment's bearer token or DPoP authorization headers.
300 public func uploadAttachment(
301 _ data: Data,
302 mimeType: String,
303 to url: URL
304 ) async throws {
305 var request = URLRequest(url: url, timeoutInterval: 60)
306 request.httpMethod = "POST"
307 request.httpBody = data
308 request.setValue(mimeType, forHTTPHeaderField: "Content-Type")
309 request.setValue(String(data.count), forHTTPHeaderField: "Content-Length")
310​
311 let (responseData, response) = try await transport.data(
312 for: HTTPRequestPolicy.prepare(request)
313 )
314 guard (200...299).contains(response.statusCode) else {
315 let detail = String(data: responseData, encoding: .utf8)?
316 .trimmingCharacters(in: .whitespacesAndNewlines)
317 throw HTTPError.status(
318 response.statusCode,
319 message: detail.flatMap { $0.isEmpty ? nil : $0 } ?? "Image upload failed.",
320 traceID: nil
321 )
322 }
323 }
324​
325 /// Production uses URLSession's file upload API so large attachments never
326 /// become one in-memory Data value.
327 public func uploadAttachment(
328 fileURL: URL,
329 byteCount: Int,
330 mimeType: String,
331 to url: URL
332 ) async throws {
333 var request = URLRequest(url: url, timeoutInterval: 60)
334 request.httpMethod = "POST"
335 request.setValue(mimeType, forHTTPHeaderField: "Content-Type")
336 request.setValue(String(byteCount), forHTTPHeaderField: "Content-Length")
337​
338 let (responseData, response) = try await transport.upload(
339 for: HTTPRequestPolicy.prepare(request),
340 fromFile: fileURL
341 )
342 guard (200...299).contains(response.statusCode) else {
343 let detail = String(data: responseData, encoding: .utf8)?
344 .trimmingCharacters(in: .whitespacesAndNewlines)
345 throw HTTPError.status(
346 response.statusCode,
347 message: detail.flatMap { $0.isEmpty ? nil : $0 } ?? "File upload failed.",
348 traceID: nil
349 )
350 }
351 }
352​
353 public func webSocketTicket(for environment: Environment) async throws -> WebSocketTicket {
354 try await authorized(
355 environment: environment,
356 path: "/api/auth/websocket-ticket",
357 method: "POST",
358 as: WebSocketTicket.self
359 )
360 }
361​
362 public func session(for environment: Environment) async throws -> AuthSessionState {
363 try await authorized(
364 environment: environment,
365 path: "/api/auth/session",
366 method: "GET",
367 isUnauthorizedResponse: { !$0.authenticated },
368 as: AuthSessionState.self
369 )
370 }
371​
372 public func clientSessions(for environment: Environment) async throws
373 -> [AuthClientSession]
374 {
375 try await authorized(
376 environment: environment,
377 path: "/api/auth/clients",
378 method: "GET",
379 as: [AuthClientSession].self
380 )
381 }
382​
383 public func revokeClientSession(
384 id: String,
385 environment: Environment
386 ) async throws -> AuthClientSessionRevokeResult {
387 try await authorized(
388 environment: environment,
389 path: "/api/auth/clients/revoke",
390 method: "POST",
391 body: JSONEncoder.t3.encode(["sessionId": id]),
392 as: AuthClientSessionRevokeResult.self
393 )
394 }
395​
396 public func revokeOtherClientSessions(
397 for environment: Environment
398 ) async throws -> AuthOtherClientSessionsRevokeResult {
399 try await authorized(
400 environment: environment,
401 path: "/api/auth/clients/revoke-others",
402 method: "POST",
403 as: AuthOtherClientSessionsRevokeResult.self
404 )
405 }
406​
407 private func authorized<Result: Decodable & Sendable>(
408 environment: Environment,
409 path: String,
410 queryItems: [URLQueryItem] = [],
411 method: String,
412 body: Data? = nil,
413 timeoutInterval: TimeInterval? = nil,
414 isUnauthorizedResponse: (@Sendable (Result) -> Bool)? = nil,
415 as type: Result.Type
416 ) async throws -> Result {
417 let credential = try await credentials.credential(for: environment.id)
418​
419 switch environment.kind {
420 case .bearer, .local:
421 guard let credential else { throw HTTPError.missingCredential }
422 guard credential.authorizationMethod == .bearer else {
423 throw HTTPError.incompatibleCredential
424 }
425 var request = makeRequest(
426 environment: environment,
427 path: path,
428 queryItems: queryItems,
429 method: method,
430 body: body
431 )
432 if let timeoutInterval {
433 request.timeoutInterval = timeoutInterval
434 }
435 request.setValue(
436 "Bearer \(credential.accessToken)",
437 forHTTPHeaderField: "Authorization"
438 )
439 return try await send(request, as: type)
440​
441 case .managedDPoP:
442 guard let managedAuthorization else {
443 throw HTTPError.managedAuthorizationUnavailable
444 }
445​
446 // Device-only Keychain entries do not transfer to a new iPhone.
447 // The restored catalog can still use the signed-in relay account.
448 var current: EnvironmentCredential
449 if let credential,
450 credential.authorizationMethod == .dpop,
451 credential.managedEnvironmentID == environment.id {
452 current = credential
453 } else {
454 current = try await refreshManagedCredential(
455 credential, environment: environment, using: managedAuthorization
456 )
457 }
458 let bindingRequiresRefresh = try await managedAuthorization
459 .credentialRequiresRefresh(current, environment: environment)
460 if current.expiresAt?.timeIntervalSinceNow ?? 0 <= Self.managedRefreshMargin
461 || bindingRequiresRefresh {
462 current = try await refreshManagedCredential(
463 current,
464 environment: environment,
465 using: managedAuthorization
466 )
467 }
468 var request = try await managedAuthorization.authorize(
469 makeRequest(
470 environment: environment,
471 path: path,
472 queryItems: queryItems,
473 method: method,
474 body: body
475 ),
476 environment: environment,
477 credential: current
478 )
479 if let timeoutInterval {
480 request.timeoutInterval = timeoutInterval
481 }
482 do {
483 return try await send(
484 request,
485 isManagedRequest: true,
486 isUnauthorizedResponse: isUnauthorizedResponse,
487 as: type
488 )
489 } catch let error as HTTPError where error.isRejectedAuthorization {
490 if let saved = try await newestUsableManagedCredential(
491 replacing: current,
492 environment: environment,
493 using: managedAuthorization
494 ) {
495 current = saved
496 } else {
497 current = try await refreshManagedCredential(
498 current,
499 environment: environment,
500 using: managedAuthorization
501 )
502 }
503 var retry = try await managedAuthorization.authorize(
504 makeRequest(
505 environment: environment,
506 path: path,
507 queryItems: queryItems,
508 method: method,
509 body: body
510 ),
511 environment: environment,
512 credential: current
513 )
514 if let timeoutInterval {
515 retry.timeoutInterval = timeoutInterval
516 }
517 return try await send(
518 retry,
519 isManagedRequest: true,
520 isUnauthorizedResponse: isUnauthorizedResponse,
521 as: type
522 )
523 }
524 }
525 }
526​
527 private func makeRequest(
528 environment: Environment,
529 path: String,
530 queryItems: [URLQueryItem],
531 method: String,
532 body: Data?
533 ) -> URLRequest {
534 var request = URLRequest(
535 url: endpoint(environment.httpBaseURL, path: path, queryItems: queryItems)
536 )
537 request.httpMethod = method
538 request.httpBody = body
539 if body != nil {
540 request.setValue("application/json", forHTTPHeaderField: "Content-Type")
541 }
542 return request
543 }
544​
545 private func refreshManagedCredential(
546 _ credential: EnvironmentCredential?,
547 environment: Environment,
548 using managedAuthorization: any ManagedEnvironmentAuthorizing
549 ) async throws -> EnvironmentCredential {
550 if let current = try await newestUsableManagedCredential(
551 replacing: credential,
552 environment: environment,
553 using: managedAuthorization
554 ) {
555 return current
556 }
557 let refreshed = try await managedAuthorization.refreshCredential(
558 for: environment,
559 replacing: credential
560 )
561 guard refreshed.authorizationMethod == .dpop,
562 refreshed.managedEnvironmentID == environment.id,
563 refreshed.proofKeyThumbprint?.isEmpty == false else {
564 throw HTTPError.incompatibleCredential
565 }
566 guard try await credentials.replaceCredential(
567 refreshed,
568 ifMatching: credential,
569 for: environment.id
570 ) else {
571 if let current = try await newestUsableManagedCredential(
572 replacing: credential,
573 environment: environment,
574 using: managedAuthorization
575 ) {
576 return current
577 }
578 throw HTTPError.missingCredential
579 }
580 return refreshed
581 }
582​
583 private func newestUsableManagedCredential(
584 replacing credential: EnvironmentCredential?,
585 environment: Environment,
586 using managedAuthorization: any ManagedEnvironmentAuthorizing
587 ) async throws -> EnvironmentCredential? {
588 guard let saved = try await credentials.credential(for: environment.id),
589 saved != credential,
590 saved.authorizationMethod == .dpop,
591 saved.managedEnvironmentID == environment.id,
592 saved.proofKeyThumbprint?.isEmpty == false,
593 saved.expiresAt?.timeIntervalSinceNow ?? 0 > Self.managedRefreshMargin else {
594 return nil
595 }
596 let requiresRefresh = try await managedAuthorization.credentialRequiresRefresh(
597 saved,
598 environment: environment
599 )
600 guard !requiresRefresh else { return nil }
601 return saved
602 }
603​
604 private func send<Result: Decodable & Sendable>(
605 _ request: URLRequest,
606 isManagedRequest: Bool = false,
607 isUnauthorizedResponse: (@Sendable (Result) -> Bool)? = nil,
608 as type: Result.Type
609 ) async throws -> Result {
610 let data: Data
611 let response: HTTPURLResponse
612 do {
613 (data, response) = try await transport.data(for: HTTPRequestPolicy.prepare(request))
614 } catch {
615 throw isManagedRequest ? T3ConnectNetworkError.wrapping(error) : error
616 }
617 guard (200..<300).contains(response.statusCode) else {
618 let body = try? JSONDecoder.t3.decode(EnvironmentErrorBody.self, from: data)
619 let message: String
620 if response.statusCode == 401,
621 request.value(forHTTPHeaderField: "DPoP") != nil,
622 body?.reason == "invalid_credential"
623 {
624 message = DPoPFailurePresentation.message(
625 "The environment credential is invalid.",
626 reason: body?.dpopFailureReason
627 )
628 } else {
629 message = body?.message ?? body?.reason ?? "Environment request failed."
630 }
631 throw HTTPError.status(
632 response.statusCode,
633 message: message,
634 traceID: body?.traceId
635 )
636 }
637 let result = try JSONDecoder.t3.decode(type, from: data)
638 if isUnauthorizedResponse?(result) == true {
639 throw HTTPError.unauthenticatedSession
640 }
641 return result
642 }
644​
645public extension HTTPError {
646 /// The server refused the saved credential. Callers stop retrying and ask
647 /// the user to pair again instead of reporting the server as unreachable.
648 var isRejectedAuthorization: Bool {
649 switch self {
650 case .unauthenticatedSession, .missingCredential, .incompatibleCredential: return true
651 case let .status(status, _, _): return status == 401
652 default: return false
653 }
654 }
656​
657public extension Error {
658 var isRejectedAuthorization: Bool {
659 (self as? HTTPError)?.isRejectedAuthorization == true
660 }
662​
663public struct DispatchResult: Codable, Equatable, Sendable {
664 public let sequence: Int
666​
667public struct WebSocketTicket: Codable, Equatable, Sendable {
668 public let ticket: String
669 public let expiresAt: String
671​
672public struct AuthSessionState: Codable, Equatable, Sendable {
673 public let authenticated: Bool
674 public let scopes: [String]?
675 public let sessionMethod: String?
676 public let expiresAt: String?
678​
679public struct AuthClientMetadata: Codable, Equatable, Sendable {
680 public let label: String?
681 public let ipAddress: String?
682 public let userAgent: String?
683 public let deviceType: String
684 public let os: String?
685 public let browser: String?
687​
688public struct AuthClientSession: Codable, Identifiable, Equatable, Sendable {
689 public var id: String { sessionId }
690​
691 public let sessionId: String
692 public let subject: String
693 public let scopes: [String]
694 public let method: String
695 public let client: AuthClientMetadata
696 public let issuedAt: String
697 public let expiresAt: String
698 public let lastConnectedAt: String?
699 public let connected: Bool
700 public let current: Bool
702​
703public struct AuthClientSessionRevokeResult: Codable, Equatable, Sendable {
704 public let revoked: Bool
706​
707public struct AuthOtherClientSessionsRevokeResult: Codable, Equatable, Sendable {
708 public let revokedCount: Int
710​
711func endpoint(_ baseURL: URL, path: String, queryItems: [URLQueryItem] = []) -> URL {
712 var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: false)!
713 components.path = path
714 components.queryItems = queryItems.isEmpty ? nil : queryItems
715 components.fragment = nil
716 return components.url!