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

HTTP.swift

500 lines17.1 KB

1import Foundation
2​
3public protocol HTTPTransport: Sendable {
4 func data(for request: URLRequest) async throws -> (Data, HTTPURLResponse)
5}
6​
7/// The Core transport deliberately knows nothing about Clerk or the relay.
8/// A managed-environment adapter supplies request-bound DPoP proofs and can
9/// reacquire a bound access token when the current one expires or is rejected.
10public protocol ManagedEnvironmentAuthorizing: Sendable {
11 func credentialRequiresRefresh(
12 _ credential: EnvironmentCredential,
13 environment: Environment
14 ) async throws -> Bool
15​
16 func authorize(
17 _ request: URLRequest,
18 environment: Environment,
19 credential: EnvironmentCredential
20 ) async throws -> URLRequest
21​
22 func refreshCredential(
23 for environment: Environment,
24 replacing credential: EnvironmentCredential
25 ) async throws -> EnvironmentCredential
27​
28public struct URLSessionHTTPTransport: HTTPTransport {
29 private let session: URLSession
30​
31 public init(session: URLSession? = nil) {
32 if let session {
33 self.session = session
34 } else {
35 let configuration = URLSessionConfiguration.default
36 configuration.httpAdditionalHeaders = [
37 "Accept-Encoding": HTTPRequestPolicy.acceptEncoding,
38 ]
39 self.session = URLSession(configuration: configuration)
40 }
41 }
42​
43 public func data(for request: URLRequest) async throws -> (Data, HTTPURLResponse) {
44 // URLSession transparently decodes gzip responses before returning
45 // their body. Applying the policy here is a final guard for requests
46 // constructed outside EnvironmentAPI.
47 let (data, response) = try await session.data(for: HTTPRequestPolicy.prepare(request))
48 guard let httpResponse = response as? HTTPURLResponse else {
49 throw HTTPError.invalidResponse
50 }
51 return (data, httpResponse)
52 }
54​
55/// Shared wire-level defaults for HTTP requests.
56///
57/// Foundation's URL loading system transparently decompresses gzip response
58/// bodies. The explicit offer matters because T3 only compresses JSON when the
59/// client advertises support.
60public enum HTTPRequestPolicy {
61 public static let acceptEncoding = "gzip"
62​
63 public static func prepare(_ request: URLRequest) -> URLRequest {
64 var prepared = request
65 if prepared.value(forHTTPHeaderField: "Accept-Encoding") == nil {
66 prepared.setValue(acceptEncoding, forHTTPHeaderField: "Accept-Encoding")
67 }
68 if prepared.value(forHTTPHeaderField: "Accept") == nil {
69 prepared.setValue("application/json", forHTTPHeaderField: "Accept")
70 }
71 return prepared
72 }
74​
75public enum HTTPError: LocalizedError, Sendable {
76 case invalidResponse
77 case status(Int, message: String, traceID: String?)
78 case missingCredential
79 case incompatibleCredential
80 case managedAuthorizationUnavailable
81​
82 public var errorDescription: String? {
83 switch self {
84 case .invalidResponse:
85 "The server returned an invalid response."
86 case let .status(status, message, traceID):
87 traceID.map { "\(message) (trace \($0))" } ?? "\(message) (HTTP \(status))"
88 case .missingCredential:
89 "This environment has no saved credential."
90 case .incompatibleCredential:
91 "This environment's saved authentication method is invalid. Connect it again."
92 case .managedAuthorizationUnavailable:
93 "This build cannot authorize a managed T3 Connect environment."
94 }
95 }
97​
98private struct ErrorBody: Decodable {
99 let message: String?
100 let reason: String?
101 let traceId: String?
103​
104public actor EnvironmentAPI {
105 private static let managedRefreshMargin: TimeInterval = 60
106​
107 private let transport: any HTTPTransport
108 private let credentials: any CredentialStore
109 private let managedAuthorization: (any ManagedEnvironmentAuthorizing)?
110​
111 public init(
112 transport: any HTTPTransport = URLSessionHTTPTransport(),
113 credentials: any CredentialStore,
114 managedAuthorization: (any ManagedEnvironmentAuthorizing)? = nil
115 ) {
116 self.transport = transport
117 self.credentials = credentials
118 self.managedAuthorization = managedAuthorization
119 }
120​
121 public func descriptor(at httpBaseURL: URL) async throws -> EnvironmentDescriptor {
122 try await send(
123 URLRequest(url: endpoint(httpBaseURL, path: "/.well-known/t3/environment")),
124 as: EnvironmentDescriptor.self
125 )
126 }
127​
128 public func shellSnapshot(
129 for environment: Environment,
130 timeoutInterval: TimeInterval? = nil
131 ) async throws
132 -> OrchestrationShellSnapshot
133 {
134 try await authorized(
135 environment: environment,
136 path: "/api/orchestration/shell",
137 method: "GET",
138 timeoutInterval: timeoutInterval,
139 as: OrchestrationShellSnapshot.self
140 )
141 }
142​
143 public func readModel(for environment: Environment) async throws -> OrchestrationReadModel {
144 try await authorized(
145 environment: environment,
146 path: "/api/orchestration/snapshot",
147 method: "GET",
148 as: OrchestrationReadModel.self
149 )
150 }
151​
152 public func threadSnapshot(
153 id: String,
154 environment: Environment,
155 turnLimit: Int? = nil,
156 beforeCursor: String? = nil
157 ) async throws -> OrchestrationThreadDetailSnapshot {
158 let encodedID = id.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? id
159 var queryItems: [URLQueryItem] = []
160 if let turnLimit {
161 queryItems.append(URLQueryItem(name: "turnLimit", value: String(turnLimit)))
162 }
163 if let beforeCursor {
164 queryItems.append(URLQueryItem(name: "beforeCursor", value: beforeCursor))
165 }
166 return try await authorized(
167 environment: environment,
168 path: "/api/orchestration/threads/\(encodedID)",
169 queryItems: queryItems,
170 method: "GET",
171 as: OrchestrationThreadDetailSnapshot.self
172 )
173 }
174​
175 public func dispatch(
176 _ command: JSONValue,
177 environment: Environment
178 ) async throws -> DispatchResult {
179 try await authorized(
180 environment: environment,
181 path: "/api/orchestration/dispatch",
182 method: "POST",
183 body: JSONEncoder.t3.encode(command),
184 as: DispatchResult.self
185 )
186 }
187​
188 public func pullRequestDiff(
189 _ input: PullRequestDiffInput,
190 environment: Environment
191 ) async throws -> PullRequestDiffResult {
192 try await authorized(
193 environment: environment,
194 path: "/api/pull-requests/diff",
195 method: "POST",
196 body: JSONEncoder.t3.encode(input),
197 timeoutInterval: 60,
198 as: PullRequestDiffResult.self
199 )
200 }
201​
202 public func webSocketTicket(for environment: Environment) async throws -> WebSocketTicket {
203 try await authorized(
204 environment: environment,
205 path: "/api/auth/websocket-ticket",
206 method: "POST",
207 as: WebSocketTicket.self
208 )
209 }
210​
211 public func session(for environment: Environment) async throws -> AuthSessionState {
212 try await authorized(
213 environment: environment,
214 path: "/api/auth/session",
215 method: "GET",
216 as: AuthSessionState.self
217 )
218 }
219​
220 public func clientSessions(for environment: Environment) async throws
221 -> [AuthClientSession]
222 {
223 try await authorized(
224 environment: environment,
225 path: "/api/auth/clients",
226 method: "GET",
227 as: [AuthClientSession].self
228 )
229 }
230​
231 public func revokeClientSession(
232 id: String,
233 environment: Environment
234 ) async throws -> AuthClientSessionRevokeResult {
235 try await authorized(
236 environment: environment,
237 path: "/api/auth/clients/revoke",
238 method: "POST",
239 body: JSONEncoder.t3.encode(["sessionId": id]),
240 as: AuthClientSessionRevokeResult.self
241 )
242 }
243​
244 public func revokeOtherClientSessions(
245 for environment: Environment
246 ) async throws -> AuthOtherClientSessionsRevokeResult {
247 try await authorized(
248 environment: environment,
249 path: "/api/auth/clients/revoke-others",
250 method: "POST",
251 as: AuthOtherClientSessionsRevokeResult.self
252 )
253 }
254​
255 private func authorized<Result: Decodable & Sendable>(
256 environment: Environment,
257 path: String,
258 queryItems: [URLQueryItem] = [],
259 method: String,
260 body: Data? = nil,
261 timeoutInterval: TimeInterval? = nil,
262 as type: Result.Type
263 ) async throws -> Result {
264 guard let credential = try await credentials.credential(for: environment.id) else {
265 throw HTTPError.missingCredential
266 }
267​
268 switch environment.kind {
269 case .bearer, .local:
270 guard credential.authorizationMethod == .bearer else {
271 throw HTTPError.incompatibleCredential
272 }
273 var request = makeRequest(
274 environment: environment,
275 path: path,
276 queryItems: queryItems,
277 method: method,
278 body: body
279 )
280 if let timeoutInterval {
281 request.timeoutInterval = timeoutInterval
282 }
283 request.setValue(
284 "Bearer \(credential.accessToken)",
285 forHTTPHeaderField: "Authorization"
286 )
287 return try await send(request, as: type)
288​
289 case .managedDPoP:
290 guard credential.authorizationMethod == .dpop,
291 credential.managedEnvironmentID == environment.id else {
292 throw HTTPError.incompatibleCredential
293 }
294 guard let managedAuthorization else {
295 throw HTTPError.managedAuthorizationUnavailable
296 }
297​
298 var current = credential
299 let bindingRequiresRefresh = try await managedAuthorization
300 .credentialRequiresRefresh(current, environment: environment)
301 if current.expiresAt?.timeIntervalSinceNow ?? 0 <= Self.managedRefreshMargin
302 || bindingRequiresRefresh {
303 current = try await refreshManagedCredential(
304 current,
305 environment: environment,
306 using: managedAuthorization
307 )
308 }
309 var request = try await managedAuthorization.authorize(
310 makeRequest(
311 environment: environment,
312 path: path,
313 queryItems: queryItems,
314 method: method,
315 body: body
316 ),
317 environment: environment,
318 credential: current
319 )
320 if let timeoutInterval {
321 request.timeoutInterval = timeoutInterval
322 }
323 do {
324 return try await send(request, as: type)
325 } catch let error as HTTPError where error.isRejectedAuthorization {
326 if let saved = try await newestUsableManagedCredential(
327 replacing: current,
328 environment: environment,
329 using: managedAuthorization
330 ) {
331 current = saved
332 } else {
333 current = try await refreshManagedCredential(
334 current,
335 environment: environment,
336 using: managedAuthorization
337 )
338 }
339 var retry = try await managedAuthorization.authorize(
340 makeRequest(
341 environment: environment,
342 path: path,
343 queryItems: queryItems,
344 method: method,
345 body: body
346 ),
347 environment: environment,
348 credential: current
349 )
350 if let timeoutInterval {
351 retry.timeoutInterval = timeoutInterval
352 }
353 return try await send(retry, as: type)
354 }
355 }
356 }
357​
358 private func makeRequest(
359 environment: Environment,
360 path: String,
361 queryItems: [URLQueryItem],
362 method: String,
363 body: Data?
364 ) -> URLRequest {
365 var request = URLRequest(
366 url: endpoint(environment.httpBaseURL, path: path, queryItems: queryItems)
367 )
368 request.httpMethod = method
369 request.httpBody = body
370 if body != nil {
371 request.setValue("application/json", forHTTPHeaderField: "Content-Type")
372 }
373 return request
374 }
375​
376 private func refreshManagedCredential(
377 _ credential: EnvironmentCredential,
378 environment: Environment,
379 using managedAuthorization: any ManagedEnvironmentAuthorizing
380 ) async throws -> EnvironmentCredential {
381 if let current = try await newestUsableManagedCredential(
382 replacing: credential,
383 environment: environment,
384 using: managedAuthorization
385 ) {
386 return current
387 }
388 let refreshed = try await managedAuthorization.refreshCredential(
389 for: environment,
390 replacing: credential
391 )
392 guard refreshed.authorizationMethod == .dpop,
393 refreshed.managedEnvironmentID == environment.id,
394 refreshed.proofKeyThumbprint?.isEmpty == false else {
395 throw HTTPError.incompatibleCredential
396 }
397 try await credentials.setCredential(refreshed, for: environment.id)
398 return refreshed
399 }
400​
401 private func newestUsableManagedCredential(
402 replacing credential: EnvironmentCredential,
403 environment: Environment,
404 using managedAuthorization: any ManagedEnvironmentAuthorizing
405 ) async throws -> EnvironmentCredential? {
406 guard let saved = try await credentials.credential(for: environment.id),
407 saved != credential,
408 saved.authorizationMethod == .dpop,
409 saved.managedEnvironmentID == environment.id,
410 saved.proofKeyThumbprint?.isEmpty == false,
411 saved.expiresAt?.timeIntervalSinceNow ?? 0 > Self.managedRefreshMargin else {
412 return nil
413 }
414 let requiresRefresh = try await managedAuthorization.credentialRequiresRefresh(
415 saved,
416 environment: environment
417 )
418 guard !requiresRefresh else { return nil }
419 return saved
420 }
421​
422 private func send<Result: Decodable & Sendable>(
423 _ request: URLRequest,
424 as type: Result.Type
425 ) async throws -> Result {
426 let (data, response) = try await transport.data(for: HTTPRequestPolicy.prepare(request))
427 guard (200..<300).contains(response.statusCode) else {
428 let body = try? JSONDecoder.t3.decode(ErrorBody.self, from: data)
429 throw HTTPError.status(
430 response.statusCode,
431 message: body?.message ?? body?.reason ?? "Environment request failed.",
432 traceID: body?.traceId
433 )
434 }
435 return try JSONDecoder.t3.decode(type, from: data)
436 }
438​
439private extension HTTPError {
440 var isRejectedAuthorization: Bool {
441 guard case let .status(status, _, _) = self else { return false }
442 return status == 401
443 }
445​
446public struct DispatchResult: Codable, Equatable, Sendable {
447 public let sequence: Int
449​
450public struct WebSocketTicket: Codable, Equatable, Sendable {
451 public let ticket: String
452 public let expiresAt: String
454​
455public struct AuthSessionState: Codable, Equatable, Sendable {
456 public let authenticated: Bool
457 public let scopes: [String]?
458 public let sessionMethod: String?
459 public let expiresAt: String?
461​
462public struct AuthClientMetadata: Codable, Equatable, Sendable {
463 public let label: String?
464 public let ipAddress: String?
465 public let userAgent: String?
466 public let deviceType: String
467 public let os: String?
468 public let browser: String?
470​
471public struct AuthClientSession: Codable, Identifiable, Equatable, Sendable {
472 public var id: String { sessionId }
473​
474 public let sessionId: String
475 public let subject: String
476 public let scopes: [String]
477 public let method: String
478 public let client: AuthClientMetadata
479 public let issuedAt: String
480 public let expiresAt: String
481 public let lastConnectedAt: String?
482 public let connected: Bool
483 public let current: Bool
485​
486public struct AuthClientSessionRevokeResult: Codable, Equatable, Sendable {
487 public let revoked: Bool
489​
490public struct AuthOtherClientSessionsRevokeResult: Codable, Equatable, Sendable {
491 public let revokedCount: Int
493​
494func endpoint(_ baseURL: URL, path: String, queryItems: [URLQueryItem] = []) -> URL {
495 var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: false)!
496 components.path = path
497 components.queryItems = queryItems.isEmpty ? nil : queryItems
498 components.fragment = nil
499 return components.url!