feat(swift-ios): add secure T3 Connect foundations
This commit is contained in:
13 files changed
+1971
No files matched your search
@@ -0,0 +1,93 @@
|
||||
import ClerkKit
|
||||
import Foundation
|
||||
|
||||
public enum T3ConnectSignInProvider: String, CaseIterable, Identifiable, Sendable {
|
||||
case google
|
||||
case github
|
||||
|
||||
public var id: String { rawValue }
|
||||
|
||||
public var title: String {
|
||||
switch self {
|
||||
case .google: "Continue with Google"
|
||||
case .github: "Continue with GitHub"
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate var clerkProvider: OAuthProvider {
|
||||
switch self {
|
||||
case .google: .google
|
||||
case .github: .github
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public struct T3ConnectAccount: Equatable, Sendable {
|
||||
public let id: String
|
||||
public let email: String?
|
||||
public let imageURL: URL?
|
||||
}
|
||||
|
||||
public enum T3ConnectAuthError: LocalizedError, Sendable {
|
||||
case noSession
|
||||
|
||||
public var errorDescription: String? {
|
||||
switch self {
|
||||
case .noSession:
|
||||
"Sign in to your T3 account to use T3 Connect."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Small ClerkKit boundary. Clerk owns encrypted session persistence and the
|
||||
/// ASWebAuthenticationSession callback; the app only asks for the relay JWT.
|
||||
@MainActor
|
||||
public final class T3ConnectClerkSession {
|
||||
private let clerk: Clerk
|
||||
private let jwtTemplate: String
|
||||
|
||||
public init(configuration: T3ConnectConfiguration) {
|
||||
jwtTemplate = configuration.clerkJWTTemplate
|
||||
clerk = Clerk.configure(
|
||||
publishableKey: configuration.clerkPublishableKey,
|
||||
options: .init(
|
||||
redirectConfig: .init(
|
||||
redirectUrl: "t3code://clerk-callback",
|
||||
callbackUrlScheme: "t3code"
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
public var account: T3ConnectAccount? {
|
||||
guard let user = clerk.user else { return nil }
|
||||
return T3ConnectAccount(
|
||||
id: user.id,
|
||||
email: user.primaryEmailAddress?.emailAddress,
|
||||
imageURL: URL(string: user.imageUrl)
|
||||
)
|
||||
}
|
||||
|
||||
public var isLoaded: Bool { clerk.isLoaded }
|
||||
|
||||
public func refresh() async throws {
|
||||
_ = try await clerk.refreshClient()
|
||||
}
|
||||
|
||||
public func signIn(with provider: T3ConnectSignInProvider) async throws {
|
||||
_ = try await clerk.auth.signInWithOAuth(provider: provider.clerkProvider)
|
||||
_ = try await clerk.refreshClient()
|
||||
}
|
||||
|
||||
public func signOut() async throws {
|
||||
try await clerk.auth.signOut()
|
||||
}
|
||||
|
||||
public func relayToken() async throws -> String {
|
||||
let token = try await clerk.auth.getToken(
|
||||
.init(template: jwtTemplate, expirationBuffer: 20)
|
||||
)
|
||||
guard let token, !token.isEmpty else { throw T3ConnectAuthError.noSession }
|
||||
return token
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
import Foundation
|
||||
import Observation
|
||||
|
||||
@MainActor
|
||||
public protocol T3ConnectCapable: AnyObject {
|
||||
var t3ConnectController: T3ConnectController { get }
|
||||
|
||||
/// Save and activate the relay-managed environment without treating its
|
||||
/// bootstrap credential as a bearer token. Implementations prepare the
|
||||
/// DPoP access token and socket ticket through `managedAuthorizer`.
|
||||
func connectT3Environment(
|
||||
_ credential: T3ConnectManagedEnvironmentCredential
|
||||
) async throws
|
||||
}
|
||||
|
||||
public struct T3ConnectCloudEnvironment: Identifiable, Equatable, Sendable {
|
||||
public var id: String { environment.environmentId }
|
||||
|
||||
public let environment: T3ConnectRelayEnvironment
|
||||
public let status: T3ConnectRelayEnvironmentStatus?
|
||||
public let statusError: String?
|
||||
|
||||
public init(
|
||||
environment: T3ConnectRelayEnvironment,
|
||||
status: T3ConnectRelayEnvironmentStatus? = nil,
|
||||
statusError: String? = nil
|
||||
) {
|
||||
self.environment = environment
|
||||
self.status = status
|
||||
self.statusError = statusError
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Observable
|
||||
public final class T3ConnectController {
|
||||
public let resolution: T3ConnectConfigurationResolution
|
||||
public let managedAuthorizer: T3ConnectManagedEnvironmentAuthorizer
|
||||
|
||||
public private(set) var account: T3ConnectAccount?
|
||||
public private(set) var environments: [T3ConnectCloudEnvironment] = []
|
||||
public private(set) var isRefreshing = false
|
||||
public private(set) var busyEnvironmentID: String?
|
||||
public var errorMessage: String?
|
||||
|
||||
private let auth: T3ConnectClerkSession?
|
||||
private let relay: T3ConnectRelayClient?
|
||||
|
||||
public init(
|
||||
resolution: T3ConnectConfigurationResolution = T3ConnectConfiguration.resolve(),
|
||||
transport: any HTTPTransport = URLSessionHTTPTransport(),
|
||||
signer: T3ConnectDPoPSigner = T3ConnectDPoPSigner()
|
||||
) {
|
||||
self.resolution = resolution
|
||||
managedAuthorizer = T3ConnectManagedEnvironmentAuthorizer(
|
||||
transport: transport,
|
||||
signer: signer
|
||||
)
|
||||
guard let configuration = resolution.configuration else {
|
||||
auth = nil
|
||||
relay = nil
|
||||
return
|
||||
}
|
||||
auth = T3ConnectClerkSession(configuration: configuration)
|
||||
relay = T3ConnectRelayClient(
|
||||
configuration: configuration,
|
||||
transport: transport,
|
||||
signer: signer
|
||||
)
|
||||
}
|
||||
|
||||
public var unavailableReason: String? {
|
||||
guard case let .unavailable(reason) = resolution else { return nil }
|
||||
return reason
|
||||
}
|
||||
|
||||
public func refresh() async {
|
||||
guard let auth, let relay else { return }
|
||||
isRefreshing = true
|
||||
defer { isRefreshing = false }
|
||||
do {
|
||||
if !auth.isLoaded { try await auth.refresh() }
|
||||
account = auth.account
|
||||
guard account != nil else {
|
||||
environments = []
|
||||
return
|
||||
}
|
||||
let token = try await auth.relayToken()
|
||||
let records = try await relay.listEnvironments(clerkToken: token)
|
||||
environments = records.map { T3ConnectCloudEnvironment(environment: $0) }
|
||||
environments = await withTaskGroup(
|
||||
of: T3ConnectCloudEnvironment.self,
|
||||
returning: [T3ConnectCloudEnvironment].self
|
||||
) { group in
|
||||
for record in records {
|
||||
group.addTask {
|
||||
do {
|
||||
let status = try await relay.status(for: record, clerkToken: token)
|
||||
return T3ConnectCloudEnvironment(
|
||||
environment: record,
|
||||
status: status
|
||||
)
|
||||
} catch {
|
||||
return T3ConnectCloudEnvironment(
|
||||
environment: record,
|
||||
statusError: error.localizedDescription
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
var loaded: [T3ConnectCloudEnvironment] = []
|
||||
for await environment in group { loaded.append(environment) }
|
||||
return loaded.sorted {
|
||||
$0.environment.linkedAt > $1.environment.linkedAt
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
public func signIn(with provider: T3ConnectSignInProvider) async {
|
||||
guard let auth else { return }
|
||||
isRefreshing = true
|
||||
defer { isRefreshing = false }
|
||||
do {
|
||||
try await auth.signIn(with: provider)
|
||||
account = auth.account
|
||||
await refresh()
|
||||
} catch {
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
public func signOut() async {
|
||||
guard let auth, let relay else { return }
|
||||
isRefreshing = true
|
||||
defer { isRefreshing = false }
|
||||
do {
|
||||
try await auth.signOut()
|
||||
await relay.clearTokenCache()
|
||||
account = nil
|
||||
environments = []
|
||||
} catch {
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
public func credential(
|
||||
for environment: T3ConnectRelayEnvironment,
|
||||
deviceID: String? = nil
|
||||
) async throws -> T3ConnectManagedEnvironmentCredential {
|
||||
guard let auth, let relay else {
|
||||
throw T3ConnectRelayError.invalidConfiguration(
|
||||
unavailableReason ?? "T3 Connect is unavailable in this build."
|
||||
)
|
||||
}
|
||||
busyEnvironmentID = environment.environmentId
|
||||
defer { busyEnvironmentID = nil }
|
||||
let token = try await auth.relayToken()
|
||||
return try await relay.connect(
|
||||
to: environment,
|
||||
clerkToken: token,
|
||||
deviceID: deviceID
|
||||
)
|
||||
}
|
||||
|
||||
public func unlink(_ environment: T3ConnectRelayEnvironment) async {
|
||||
guard let auth, let relay else { return }
|
||||
busyEnvironmentID = environment.environmentId
|
||||
defer { busyEnvironmentID = nil }
|
||||
do {
|
||||
let token = try await auth.relayToken()
|
||||
try await relay.unlinkEnvironment(
|
||||
environmentID: environment.environmentId,
|
||||
clerkToken: token
|
||||
)
|
||||
environments.removeAll { $0.id == environment.environmentId }
|
||||
} catch {
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
public func registerDevice(_ registration: T3ConnectDeviceRegistration) async throws {
|
||||
guard let auth, let relay else {
|
||||
throw T3ConnectRelayError.invalidConfiguration(
|
||||
unavailableReason ?? "T3 Connect is unavailable in this build."
|
||||
)
|
||||
}
|
||||
let token = try await auth.relayToken()
|
||||
try await relay.registerDevice(registration, clerkToken: token)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import Foundation
|
||||
|
||||
public struct T3ConnectConfiguration: Equatable, Sendable {
|
||||
public static let defaultClerkJWTTemplate = "t3-relay"
|
||||
|
||||
public let clerkPublishableKey: String
|
||||
public let clerkJWTTemplate: String
|
||||
public let relayHTTPURL: URL
|
||||
|
||||
public init(
|
||||
clerkPublishableKey: String,
|
||||
clerkJWTTemplate: String = Self.defaultClerkJWTTemplate,
|
||||
relayHTTPURL: URL
|
||||
) {
|
||||
self.clerkPublishableKey = clerkPublishableKey
|
||||
self.clerkJWTTemplate = clerkJWTTemplate
|
||||
self.relayHTTPURL = relayHTTPURL
|
||||
}
|
||||
|
||||
public static func resolve(bundle: Bundle = .main) -> T3ConnectConfigurationResolution {
|
||||
resolve(infoDictionary: bundle.infoDictionary ?? [:])
|
||||
}
|
||||
|
||||
public static func resolve(
|
||||
infoDictionary: [String: Any]
|
||||
) -> T3ConnectConfigurationResolution {
|
||||
let publishableKey = configuredString(
|
||||
infoDictionary["T3ConnectClerkPublishableKey"]
|
||||
)
|
||||
let relayHTTPValue = configuredString(infoDictionary["T3ConnectRelayHTTPURL"])
|
||||
let jwtTemplate = configuredString(infoDictionary["T3ConnectClerkJWTTemplate"])
|
||||
?? defaultClerkJWTTemplate
|
||||
|
||||
var missingKeys: [String] = []
|
||||
if publishableKey == nil { missingKeys.append("Clerk publishable key") }
|
||||
if relayHTTPValue == nil { missingKeys.append("relay HTTP URL") }
|
||||
guard missingKeys.isEmpty else {
|
||||
return .unavailable(
|
||||
reason: "This build is missing \(missingKeys.joined(separator: ", "))."
|
||||
)
|
||||
}
|
||||
|
||||
guard
|
||||
let relayHTTPValue,
|
||||
let relayHTTPURL = URL(string: relayHTTPValue),
|
||||
relayHTTPURL.scheme?.lowercased() == "https",
|
||||
relayHTTPURL.host != nil
|
||||
else {
|
||||
return .unavailable(reason: "The T3 Connect relay HTTP URL must use HTTPS.")
|
||||
}
|
||||
return .available(
|
||||
T3ConnectConfiguration(
|
||||
clerkPublishableKey: publishableKey!,
|
||||
clerkJWTTemplate: jwtTemplate,
|
||||
relayHTTPURL: normalizedBaseURL(relayHTTPURL)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
private static func configuredString(_ value: Any?) -> String? {
|
||||
guard let value = value as? String else { return nil }
|
||||
let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !trimmed.isEmpty, !trimmed.contains("$(") else { return nil }
|
||||
return trimmed
|
||||
}
|
||||
|
||||
private static func normalizedBaseURL(_ url: URL) -> URL {
|
||||
guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
|
||||
return url
|
||||
}
|
||||
components.query = nil
|
||||
components.fragment = nil
|
||||
if components.path != "/" {
|
||||
components.path = components.path.replacingOccurrences(
|
||||
of: #"/+$"#,
|
||||
with: "",
|
||||
options: .regularExpression
|
||||
)
|
||||
}
|
||||
return components.url ?? url
|
||||
}
|
||||
}
|
||||
|
||||
public enum T3ConnectConfigurationResolution: Equatable, Sendable {
|
||||
case available(T3ConnectConfiguration)
|
||||
case unavailable(reason: String)
|
||||
|
||||
public var configuration: T3ConnectConfiguration? {
|
||||
guard case let .available(configuration) = self else { return nil }
|
||||
return configuration
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
import CryptoKit
|
||||
import Foundation
|
||||
import Security
|
||||
|
||||
public struct T3ConnectDPoPPublicJWK: Codable, Equatable, Sendable {
|
||||
public let kty: String
|
||||
public let crv: String
|
||||
public let x: String
|
||||
public let y: String
|
||||
|
||||
fileprivate init(publicKey: P256.Signing.PublicKey) throws {
|
||||
let representation = publicKey.x963Representation
|
||||
guard representation.count == 65, representation.first == 0x04 else {
|
||||
throw T3ConnectDPoPError.invalidPublicKey
|
||||
}
|
||||
kty = "EC"
|
||||
crv = "P-256"
|
||||
x = Data(representation[1..<33]).base64URLEncodedString()
|
||||
y = Data(representation[33..<65]).base64URLEncodedString()
|
||||
}
|
||||
|
||||
public var canonicalThumbprintInput: String {
|
||||
"{\"crv\":\"\(crv)\",\"kty\":\"\(kty)\",\"x\":\"\(x)\",\"y\":\"\(y)\"}"
|
||||
}
|
||||
|
||||
public var thumbprint: String {
|
||||
Data(SHA256.hash(data: Data(canonicalThumbprintInput.utf8)))
|
||||
.base64URLEncodedString()
|
||||
}
|
||||
}
|
||||
|
||||
public struct T3ConnectDPoPProof: Equatable, Sendable {
|
||||
public let value: String
|
||||
public let thumbprint: String
|
||||
}
|
||||
|
||||
public enum T3ConnectDPoPError: LocalizedError, Sendable {
|
||||
case invalidURL
|
||||
case invalidPrivateKey
|
||||
case invalidPublicKey
|
||||
case invalidStoredKey
|
||||
case keychain(OSStatus)
|
||||
case encoding
|
||||
|
||||
public var errorDescription: String? {
|
||||
switch self {
|
||||
case .invalidURL:
|
||||
"The DPoP proof URL is invalid."
|
||||
case .invalidPrivateKey:
|
||||
"The DPoP private key is invalid."
|
||||
case .invalidPublicKey:
|
||||
"The DPoP public key is invalid."
|
||||
case .invalidStoredKey:
|
||||
"The saved DPoP identity is invalid."
|
||||
case let .keychain(status):
|
||||
SecCopyErrorMessageString(status, nil) as String? ?? "Keychain error \(status)."
|
||||
case .encoding:
|
||||
"The DPoP proof could not be encoded."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Owns the proof-of-possession identity used by both relay and environment requests.
|
||||
/// Rotating this key invalidates every token bound to its JWK thumbprint, so the
|
||||
/// production initializer persists it in the device-only Keychain.
|
||||
public actor T3ConnectDPoPSigner {
|
||||
private let service: String?
|
||||
private let account: String
|
||||
private var privateKey: P256.Signing.PrivateKey?
|
||||
|
||||
public init(
|
||||
service: String = "com.t3tools.t3code.swiftui.t3-connect-dpop",
|
||||
account: String = "device-proof-key"
|
||||
) {
|
||||
self.service = service
|
||||
self.account = account
|
||||
}
|
||||
|
||||
/// Deterministic in-memory identity for focused tests and previews.
|
||||
public init(privateKeyRawRepresentation: Data) throws {
|
||||
do {
|
||||
privateKey = try P256.Signing.PrivateKey(rawRepresentation: privateKeyRawRepresentation)
|
||||
} catch {
|
||||
throw T3ConnectDPoPError.invalidPrivateKey
|
||||
}
|
||||
service = nil
|
||||
account = "in-memory"
|
||||
}
|
||||
|
||||
public func publicJWK() throws -> T3ConnectDPoPPublicJWK {
|
||||
try T3ConnectDPoPPublicJWK(publicKey: try loadPrivateKey().publicKey)
|
||||
}
|
||||
|
||||
public func thumbprint() throws -> String {
|
||||
try publicJWK().thumbprint
|
||||
}
|
||||
|
||||
public func proof(
|
||||
method: String,
|
||||
url: URL,
|
||||
accessToken: String? = nil,
|
||||
issuedAt: Date = Date(),
|
||||
identifier: UUID = UUID()
|
||||
) throws -> T3ConnectDPoPProof {
|
||||
guard let normalizedURL = Self.normalizedHTU(url) else {
|
||||
throw T3ConnectDPoPError.invalidURL
|
||||
}
|
||||
|
||||
let key = try loadPrivateKey()
|
||||
let jwk = try T3ConnectDPoPPublicJWK(publicKey: key.publicKey)
|
||||
let header = Header(typ: "dpop+jwt", alg: "ES256", jwk: jwk)
|
||||
let payload = Payload(
|
||||
htm: method.uppercased(),
|
||||
htu: normalizedURL.absoluteString,
|
||||
jti: identifier.uuidString.lowercased(),
|
||||
iat: Int(issuedAt.timeIntervalSince1970.rounded(.down)),
|
||||
ath: accessToken.map(Self.accessTokenHash)
|
||||
)
|
||||
let encoder = JSONEncoder()
|
||||
encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]
|
||||
guard
|
||||
let headerPart = try? encoder.encode(header).base64URLEncodedString(),
|
||||
let payloadPart = try? encoder.encode(payload).base64URLEncodedString()
|
||||
else {
|
||||
throw T3ConnectDPoPError.encoding
|
||||
}
|
||||
let signingInput = "\(headerPart).\(payloadPart)"
|
||||
let signature = try key.signature(for: Data(signingInput.utf8))
|
||||
return T3ConnectDPoPProof(
|
||||
value: "\(signingInput).\(signature.rawRepresentation.base64URLEncodedString())",
|
||||
thumbprint: jwk.thumbprint
|
||||
)
|
||||
}
|
||||
|
||||
public static func normalizedHTU(_ url: URL) -> URL? {
|
||||
guard
|
||||
var components = URLComponents(url: url, resolvingAgainstBaseURL: false),
|
||||
components.scheme != nil,
|
||||
components.host != nil
|
||||
else { return nil }
|
||||
components.query = nil
|
||||
components.fragment = nil
|
||||
switch (components.scheme?.lowercased(), components.port) {
|
||||
case ("http", 80), ("https", 443), ("ws", 80), ("wss", 443):
|
||||
components.port = nil
|
||||
default:
|
||||
break
|
||||
}
|
||||
return components.url
|
||||
}
|
||||
|
||||
public static func accessTokenHash(_ accessToken: String) -> String {
|
||||
Data(SHA256.hash(data: Data(accessToken.utf8))).base64URLEncodedString()
|
||||
}
|
||||
|
||||
private func loadPrivateKey() throws -> P256.Signing.PrivateKey {
|
||||
if let privateKey { return privateKey }
|
||||
guard let service else { throw T3ConnectDPoPError.invalidStoredKey }
|
||||
|
||||
let query: [String: Any] = [
|
||||
kSecClass as String: kSecClassGenericPassword,
|
||||
kSecAttrService as String: service,
|
||||
kSecAttrAccount as String: account,
|
||||
kSecReturnData as String: true,
|
||||
kSecMatchLimit as String: kSecMatchLimitOne,
|
||||
]
|
||||
var item: CFTypeRef?
|
||||
let status = SecItemCopyMatching(query as CFDictionary, &item)
|
||||
if status == errSecSuccess {
|
||||
guard let data = item as? Data else { throw T3ConnectDPoPError.invalidStoredKey }
|
||||
do {
|
||||
let restored = try P256.Signing.PrivateKey(rawRepresentation: data)
|
||||
privateKey = restored
|
||||
return restored
|
||||
} catch {
|
||||
throw T3ConnectDPoPError.invalidStoredKey
|
||||
}
|
||||
}
|
||||
guard status == errSecItemNotFound else { throw T3ConnectDPoPError.keychain(status) }
|
||||
|
||||
let generated = P256.Signing.PrivateKey()
|
||||
var insertion = query
|
||||
insertion.removeValue(forKey: kSecReturnData as String)
|
||||
insertion.removeValue(forKey: kSecMatchLimit as String)
|
||||
insertion[kSecValueData as String] = generated.rawRepresentation
|
||||
insertion[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
|
||||
let insertionStatus = SecItemAdd(insertion as CFDictionary, nil)
|
||||
if insertionStatus == errSecDuplicateItem {
|
||||
// Another signer instance won the first-launch race. Preserve that
|
||||
// identity instead of rotating to this actor's generated key.
|
||||
return try readExistingPrivateKey(service: service)
|
||||
}
|
||||
guard insertionStatus == errSecSuccess else {
|
||||
throw T3ConnectDPoPError.keychain(insertionStatus)
|
||||
}
|
||||
privateKey = generated
|
||||
return generated
|
||||
}
|
||||
|
||||
private func readExistingPrivateKey(service: String) throws -> P256.Signing.PrivateKey {
|
||||
let query: [String: Any] = [
|
||||
kSecClass as String: kSecClassGenericPassword,
|
||||
kSecAttrService as String: service,
|
||||
kSecAttrAccount as String: account,
|
||||
kSecReturnData as String: true,
|
||||
kSecMatchLimit as String: kSecMatchLimitOne,
|
||||
]
|
||||
var item: CFTypeRef?
|
||||
let status = SecItemCopyMatching(query as CFDictionary, &item)
|
||||
guard status == errSecSuccess else { throw T3ConnectDPoPError.keychain(status) }
|
||||
guard let data = item as? Data else { throw T3ConnectDPoPError.invalidStoredKey }
|
||||
do {
|
||||
let restored = try P256.Signing.PrivateKey(rawRepresentation: data)
|
||||
privateKey = restored
|
||||
return restored
|
||||
} catch {
|
||||
throw T3ConnectDPoPError.invalidStoredKey
|
||||
}
|
||||
}
|
||||
|
||||
private struct Header: Encodable {
|
||||
let typ: String
|
||||
let alg: String
|
||||
let jwk: T3ConnectDPoPPublicJWK
|
||||
}
|
||||
|
||||
private struct Payload: Encodable {
|
||||
let htm: String
|
||||
let htu: String
|
||||
let jti: String
|
||||
let iat: Int
|
||||
let ath: String?
|
||||
}
|
||||
}
|
||||
|
||||
extension Data {
|
||||
fileprivate func base64URLEncodedString() -> String {
|
||||
base64EncodedString()
|
||||
.replacingOccurrences(of: "+", with: "-")
|
||||
.replacingOccurrences(of: "/", with: "_")
|
||||
.replacingOccurrences(of: "=", with: "")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
import Foundation
|
||||
|
||||
public struct T3ConnectPreparedEnvironmentConnection: Sendable {
|
||||
public let authorization: T3ConnectEnvironmentAccessToken
|
||||
public let webSocketURL: URL
|
||||
|
||||
public init(
|
||||
authorization: T3ConnectEnvironmentAccessToken,
|
||||
webSocketURL: URL
|
||||
) {
|
||||
self.authorization = authorization
|
||||
self.webSocketURL = webSocketURL
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts the relay's short-lived environment bootstrap credential into the
|
||||
/// DPoP access token and one-time WebSocket ticket understood by a T3 server.
|
||||
/// The same signer must authorize every later HTTP request for that token.
|
||||
public actor T3ConnectManagedEnvironmentAuthorizer {
|
||||
public static let standardScopes = [
|
||||
"orchestration:read",
|
||||
"orchestration:operate",
|
||||
"terminal:operate",
|
||||
"review:write",
|
||||
"relay:read",
|
||||
]
|
||||
|
||||
private struct AccessTokenResponse: Decodable, Sendable {
|
||||
let accessToken: String
|
||||
let issuedTokenType: String
|
||||
let tokenType: String
|
||||
let expiresIn: Double
|
||||
let scope: String
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case accessToken = "access_token"
|
||||
case issuedTokenType = "issued_token_type"
|
||||
case tokenType = "token_type"
|
||||
case expiresIn = "expires_in"
|
||||
case scope
|
||||
}
|
||||
}
|
||||
|
||||
private struct WebSocketTicketResponse: Decodable, Sendable {
|
||||
let ticket: String
|
||||
let expiresAt: String
|
||||
}
|
||||
|
||||
private struct ErrorBody: Decodable, Sendable {
|
||||
let message: String?
|
||||
let reason: String?
|
||||
let traceId: String?
|
||||
}
|
||||
|
||||
private let transport: any HTTPTransport
|
||||
private let signer: T3ConnectDPoPSigner
|
||||
|
||||
public init(
|
||||
transport: any HTTPTransport = URLSessionHTTPTransport(),
|
||||
signer: T3ConnectDPoPSigner = T3ConnectDPoPSigner()
|
||||
) {
|
||||
self.transport = transport
|
||||
self.signer = signer
|
||||
}
|
||||
|
||||
public func prepare(
|
||||
_ credential: T3ConnectManagedEnvironmentCredential,
|
||||
scopes: [String] = standardScopes,
|
||||
clientLabel: String? = nil
|
||||
) async throws -> T3ConnectPreparedEnvironmentConnection {
|
||||
let accessToken = try await exchange(
|
||||
credential,
|
||||
scopes: scopes,
|
||||
clientLabel: clientLabel
|
||||
)
|
||||
let webSocketURL = try await webSocketURL(using: accessToken)
|
||||
return T3ConnectPreparedEnvironmentConnection(
|
||||
authorization: accessToken,
|
||||
webSocketURL: webSocketURL
|
||||
)
|
||||
}
|
||||
|
||||
public func exchange(
|
||||
_ credential: T3ConnectManagedEnvironmentCredential,
|
||||
scopes: [String] = standardScopes,
|
||||
clientLabel: String? = nil
|
||||
) async throws -> T3ConnectEnvironmentAccessToken {
|
||||
guard let httpBaseURL = credential.endpoint.httpBaseURL else {
|
||||
throw T3ConnectRelayError.invalidConfiguration(
|
||||
"The managed environment HTTP URL is invalid."
|
||||
)
|
||||
}
|
||||
let target = endpoint(httpBaseURL, path: ["oauth", "token"])
|
||||
let proof = try await signer.proof(method: "POST", url: target)
|
||||
var fields = [
|
||||
"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
|
||||
"subject_token": credential.bootstrapCredential,
|
||||
"subject_token_type": "urn:t3:params:oauth:token-type:environment-bootstrap",
|
||||
"requested_token_type": "urn:ietf:params:oauth:token-type:access_token",
|
||||
"scope": scopes.joined(separator: " "),
|
||||
"client_device_type": "mobile",
|
||||
"client_os": ProcessInfo.processInfo.operatingSystemVersionString,
|
||||
]
|
||||
if let clientLabel, !clientLabel.isEmpty {
|
||||
fields["client_label"] = clientLabel
|
||||
}
|
||||
var request = URLRequest(url: target)
|
||||
request.httpMethod = "POST"
|
||||
request.httpBody = Self.formEncoded(fields)
|
||||
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
|
||||
request.setValue(proof.value, forHTTPHeaderField: "DPoP")
|
||||
let response = try await send(request, as: AccessTokenResponse.self)
|
||||
guard response.tokenType == "DPoP" else { throw T3ConnectRelayError.invalidResponse }
|
||||
let thumbprint = try await signer.thumbprint()
|
||||
guard thumbprint == credential.proofKeyThumbprint else {
|
||||
throw T3ConnectRelayError.invalidConfiguration(
|
||||
"The managed credential is bound to a different device identity."
|
||||
)
|
||||
}
|
||||
return T3ConnectEnvironmentAccessToken(
|
||||
environmentID: credential.environmentID,
|
||||
label: credential.label,
|
||||
endpoint: credential.endpoint,
|
||||
accessToken: response.accessToken,
|
||||
expiresAt: Date().addingTimeInterval(response.expiresIn),
|
||||
scopes: response.scope.split(separator: " ").map(String.init),
|
||||
proofKeyThumbprint: thumbprint
|
||||
)
|
||||
}
|
||||
|
||||
/// Adds a fresh request-bound proof. Call this immediately before sending;
|
||||
/// reusing a proof defeats replay protection and is rejected by the server.
|
||||
public func authorize(
|
||||
_ request: URLRequest,
|
||||
using authorization: T3ConnectEnvironmentAccessToken
|
||||
) async throws -> URLRequest {
|
||||
guard let url = request.url else { throw T3ConnectDPoPError.invalidURL }
|
||||
let proof = try await signer.proof(
|
||||
method: request.httpMethod ?? "GET",
|
||||
url: url,
|
||||
accessToken: authorization.accessToken
|
||||
)
|
||||
guard proof.thumbprint == authorization.proofKeyThumbprint else {
|
||||
throw T3ConnectRelayError.invalidConfiguration(
|
||||
"The environment token is bound to a different device identity."
|
||||
)
|
||||
}
|
||||
var authorized = request
|
||||
authorized.setValue(
|
||||
"DPoP \(authorization.accessToken)",
|
||||
forHTTPHeaderField: "Authorization"
|
||||
)
|
||||
authorized.setValue(proof.value, forHTTPHeaderField: "DPoP")
|
||||
return authorized
|
||||
}
|
||||
|
||||
public func webSocketURL(
|
||||
using authorization: T3ConnectEnvironmentAccessToken
|
||||
) async throws -> URL {
|
||||
guard
|
||||
let httpBaseURL = authorization.endpoint.httpBaseURL,
|
||||
let webSocketBaseURL = authorization.endpoint.webSocketBaseURL
|
||||
else {
|
||||
throw T3ConnectRelayError.invalidConfiguration(
|
||||
"The managed environment endpoint is invalid."
|
||||
)
|
||||
}
|
||||
let target = endpoint(
|
||||
httpBaseURL,
|
||||
path: ["api", "auth", "websocket-ticket"]
|
||||
)
|
||||
var ticketRequest = URLRequest(url: target)
|
||||
ticketRequest.httpMethod = "POST"
|
||||
ticketRequest = try await authorize(ticketRequest, using: authorization)
|
||||
let ticket = try await send(ticketRequest, as: WebSocketTicketResponse.self)
|
||||
|
||||
var components = URLComponents(
|
||||
url: webSocketBaseURL,
|
||||
resolvingAgainstBaseURL: false
|
||||
)
|
||||
if components?.path.isEmpty == true || components?.path == "/" {
|
||||
components?.path = "/ws"
|
||||
}
|
||||
var queryItems = components?.queryItems ?? []
|
||||
queryItems.removeAll { $0.name == "wsTicket" }
|
||||
queryItems.append(URLQueryItem(name: "wsTicket", value: ticket.ticket))
|
||||
components?.queryItems = queryItems
|
||||
guard let url = components?.url else { throw T3ConnectDPoPError.invalidURL }
|
||||
return url
|
||||
}
|
||||
|
||||
private func endpoint(_ baseURL: URL, path: [String]) -> URL {
|
||||
path.reduce(baseURL) { partial, component in
|
||||
partial.appendingPathComponent(component)
|
||||
}
|
||||
}
|
||||
|
||||
private func send<Response: Decodable & Sendable>(
|
||||
_ request: URLRequest,
|
||||
as type: Response.Type
|
||||
) async throws -> Response {
|
||||
let (data, response) = try await transport.data(for: HTTPRequestPolicy.prepare(request))
|
||||
guard (200..<300).contains(response.statusCode) else {
|
||||
let body = try? JSONDecoder.t3.decode(ErrorBody.self, from: data)
|
||||
throw T3ConnectRelayError.response(
|
||||
status: response.statusCode,
|
||||
message: body?.message ?? body?.reason ?? "Environment authorization failed.",
|
||||
traceID: body?.traceId
|
||||
)
|
||||
}
|
||||
do {
|
||||
return try JSONDecoder.t3.decode(type, from: data)
|
||||
} catch {
|
||||
throw T3ConnectRelayError.invalidResponse
|
||||
}
|
||||
}
|
||||
|
||||
private static func formEncoded(_ fields: [String: String]) -> Data {
|
||||
var components = URLComponents()
|
||||
components.queryItems = fields.keys.sorted().map {
|
||||
URLQueryItem(name: $0, value: fields[$0])
|
||||
}
|
||||
return Data((components.percentEncodedQuery ?? "").utf8)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,378 @@
|
||||
import Foundation
|
||||
|
||||
public enum T3ConnectRelayError: LocalizedError, Sendable {
|
||||
case invalidConfiguration(String)
|
||||
case invalidResponse
|
||||
case response(status: Int, message: String, traceID: String?)
|
||||
case unexpectedScope(requested: [String], granted: String)
|
||||
case environmentMismatch
|
||||
|
||||
public var errorDescription: String? {
|
||||
switch self {
|
||||
case let .invalidConfiguration(message):
|
||||
message
|
||||
case .invalidResponse:
|
||||
"T3 Connect returned an invalid response."
|
||||
case let .response(status, message, traceID):
|
||||
traceID.map { "\(message) (trace \($0))" } ?? "\(message) (HTTP \(status))"
|
||||
case let .unexpectedScope(requested, granted):
|
||||
"T3 Connect granted \(granted) instead of \(requested.joined(separator: " "))."
|
||||
case .environmentMismatch:
|
||||
"T3 Connect returned credentials for a different environment."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public actor T3ConnectRelayClient {
|
||||
private struct CachedToken: Sendable {
|
||||
let accessToken: String
|
||||
let expiresAt: Date
|
||||
let scopes: [T3ConnectRelayScope]
|
||||
let thumbprint: String
|
||||
}
|
||||
|
||||
private struct EnvironmentList: Decodable, Sendable {
|
||||
let environments: [T3ConnectRelayEnvironment]
|
||||
}
|
||||
|
||||
private struct DeviceList: Decodable, Sendable {
|
||||
let devices: [T3ConnectRelayDevice]
|
||||
}
|
||||
|
||||
private struct ConnectResponse: Decodable, Sendable {
|
||||
let environmentId: String
|
||||
let endpoint: T3ConnectManagedEndpoint
|
||||
let credential: String
|
||||
let expiresAt: String
|
||||
}
|
||||
|
||||
private struct OKResponse: Decodable, Sendable {
|
||||
let ok: Bool
|
||||
}
|
||||
|
||||
private struct RelayErrorBody: Decodable, Sendable {
|
||||
let message: String?
|
||||
let reason: String?
|
||||
let code: String?
|
||||
let traceId: String?
|
||||
}
|
||||
|
||||
private let configuration: T3ConnectConfiguration
|
||||
private let transport: any HTTPTransport
|
||||
private let signer: T3ConnectDPoPSigner
|
||||
private var cachedTokens: [String: CachedToken] = [:]
|
||||
|
||||
public init(
|
||||
configuration: T3ConnectConfiguration,
|
||||
transport: any HTTPTransport = URLSessionHTTPTransport(),
|
||||
signer: T3ConnectDPoPSigner = T3ConnectDPoPSigner()
|
||||
) {
|
||||
self.configuration = configuration
|
||||
self.transport = transport
|
||||
self.signer = signer
|
||||
}
|
||||
|
||||
public func listEnvironments(clerkToken: String) async throws
|
||||
-> [T3ConnectRelayEnvironment]
|
||||
{
|
||||
var request = request(path: ["v1", "environments"], method: "GET")
|
||||
request.setValue("Bearer \(clerkToken)", forHTTPHeaderField: "Authorization")
|
||||
return try await send(request, as: EnvironmentList.self).environments
|
||||
}
|
||||
|
||||
public func listDevices(clerkToken: String) async throws -> [T3ConnectRelayDevice] {
|
||||
var request = request(path: ["v1", "client", "devices"], method: "GET")
|
||||
request.setValue("Bearer \(clerkToken)", forHTTPHeaderField: "Authorization")
|
||||
return try await send(request, as: DeviceList.self).devices
|
||||
}
|
||||
|
||||
public func createEnvironmentLinkChallenge(
|
||||
clerkToken: String,
|
||||
request payload: T3ConnectEnvironmentLinkChallengeRequest
|
||||
) async throws -> T3ConnectEnvironmentLinkChallenge {
|
||||
var request = try jsonRequest(
|
||||
path: ["v1", "client", "environment-link-challenges"],
|
||||
method: "POST",
|
||||
payload: payload
|
||||
)
|
||||
request.setValue("Bearer \(clerkToken)", forHTTPHeaderField: "Authorization")
|
||||
return try await send(request, as: T3ConnectEnvironmentLinkChallenge.self)
|
||||
}
|
||||
|
||||
public func linkEnvironment(
|
||||
clerkToken: String,
|
||||
request payload: T3ConnectEnvironmentLinkRequest
|
||||
) async throws -> T3ConnectEnvironmentLinkResponse {
|
||||
var request = try jsonRequest(
|
||||
path: ["v1", "client", "environment-links"],
|
||||
method: "POST",
|
||||
payload: payload
|
||||
)
|
||||
request.setValue("Bearer \(clerkToken)", forHTTPHeaderField: "Authorization")
|
||||
return try await send(request, as: T3ConnectEnvironmentLinkResponse.self)
|
||||
}
|
||||
|
||||
public func unlinkEnvironment(environmentID: String, clerkToken: String) async throws {
|
||||
var request = request(
|
||||
path: ["v1", "client", "environment-links", environmentID],
|
||||
method: "DELETE"
|
||||
)
|
||||
request.setValue("Bearer \(clerkToken)", forHTTPHeaderField: "Authorization")
|
||||
_ = try await send(request, as: OKResponse.self)
|
||||
}
|
||||
|
||||
public func status(
|
||||
for environment: T3ConnectRelayEnvironment,
|
||||
clerkToken: String
|
||||
) async throws -> T3ConnectRelayEnvironmentStatus {
|
||||
let path = ["v1", "environments", environment.environmentId, "status"]
|
||||
let result: T3ConnectRelayEnvironmentStatus = try await sendDPoP(
|
||||
path: path,
|
||||
method: "POST",
|
||||
body: nil,
|
||||
clerkToken: clerkToken,
|
||||
scopes: [.environmentStatus]
|
||||
)
|
||||
guard
|
||||
result.environmentId == environment.environmentId,
|
||||
result.endpoint == environment.endpoint,
|
||||
result.descriptor?.environmentId == nil
|
||||
|| result.descriptor?.environmentId == environment.environmentId
|
||||
else { throw T3ConnectRelayError.environmentMismatch }
|
||||
return result
|
||||
}
|
||||
|
||||
public func connect(
|
||||
to environment: T3ConnectRelayEnvironment,
|
||||
clerkToken: String,
|
||||
deviceID: String? = nil
|
||||
) async throws -> T3ConnectManagedEnvironmentCredential {
|
||||
let thumbprint = try await signer.thumbprint()
|
||||
let payload = ConnectRequest(
|
||||
deviceId: deviceID,
|
||||
clientProofKeyThumbprint: thumbprint
|
||||
)
|
||||
let body = try JSONEncoder.t3.encode(payload)
|
||||
let response: ConnectResponse = try await sendDPoP(
|
||||
path: ["v1", "environments", environment.environmentId, "connect"],
|
||||
method: "POST",
|
||||
body: body,
|
||||
clerkToken: clerkToken,
|
||||
scopes: [.environmentConnect]
|
||||
)
|
||||
guard
|
||||
response.environmentId == environment.environmentId,
|
||||
response.endpoint == environment.endpoint
|
||||
else { throw T3ConnectRelayError.environmentMismatch }
|
||||
return T3ConnectManagedEnvironmentCredential(
|
||||
environmentID: response.environmentId,
|
||||
label: environment.label,
|
||||
endpoint: response.endpoint,
|
||||
bootstrapCredential: response.credential,
|
||||
bootstrapExpiresAt: response.expiresAt,
|
||||
proofKeyThumbprint: thumbprint
|
||||
)
|
||||
}
|
||||
|
||||
public func registerDevice(
|
||||
_ registration: T3ConnectDeviceRegistration,
|
||||
clerkToken: String
|
||||
) async throws {
|
||||
guard registration.iosMajorVersion >= 18 else {
|
||||
throw T3ConnectRelayError.invalidConfiguration(
|
||||
"T3 Connect device registration requires iOS 18 or newer."
|
||||
)
|
||||
}
|
||||
let body = try JSONEncoder.t3.encode(registration)
|
||||
let _: OKResponse = try await sendDPoP(
|
||||
path: ["v1", "mobile", "devices"],
|
||||
method: "POST",
|
||||
body: body,
|
||||
clerkToken: clerkToken,
|
||||
scopes: [.mobileRegistration]
|
||||
)
|
||||
}
|
||||
|
||||
public func clearTokenCache() {
|
||||
cachedTokens.removeAll()
|
||||
}
|
||||
|
||||
private func sendDPoP<Response: Decodable & Sendable>(
|
||||
path: [String],
|
||||
method: String,
|
||||
body: Data?,
|
||||
clerkToken: String,
|
||||
scopes: [T3ConnectRelayScope]
|
||||
) async throws -> Response {
|
||||
let target = endpoint(path)
|
||||
let authorization = try await authorize(
|
||||
clerkToken: clerkToken,
|
||||
scopes: scopes,
|
||||
method: method,
|
||||
url: target
|
||||
)
|
||||
var request = URLRequest(url: target)
|
||||
request.httpMethod = method
|
||||
request.httpBody = body
|
||||
request.setValue(
|
||||
"DPoP \(authorization.accessToken)",
|
||||
forHTTPHeaderField: "Authorization"
|
||||
)
|
||||
request.setValue(authorization.proof, forHTTPHeaderField: "DPoP")
|
||||
if body != nil {
|
||||
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||
}
|
||||
do {
|
||||
return try await send(request, as: Response.self)
|
||||
} catch let error as T3ConnectRelayError where error.isRejectedAuthorization {
|
||||
cachedTokens.removeValue(forKey: scopeCacheKey(scopes))
|
||||
let refreshed = try await authorize(
|
||||
clerkToken: clerkToken,
|
||||
scopes: scopes,
|
||||
method: method,
|
||||
url: target
|
||||
)
|
||||
request.setValue("DPoP \(refreshed.accessToken)", forHTTPHeaderField: "Authorization")
|
||||
request.setValue(refreshed.proof, forHTTPHeaderField: "DPoP")
|
||||
return try await send(request, as: Response.self)
|
||||
}
|
||||
}
|
||||
|
||||
private func authorize(
|
||||
clerkToken: String,
|
||||
scopes: [T3ConnectRelayScope],
|
||||
method: String,
|
||||
url: URL
|
||||
) async throws -> (accessToken: String, proof: String) {
|
||||
let thumbprint = try await signer.thumbprint()
|
||||
let cacheKey = scopeCacheKey(scopes)
|
||||
let token: CachedToken
|
||||
if let cached = cachedTokens[cacheKey],
|
||||
cached.thumbprint == thumbprint,
|
||||
cached.expiresAt.timeIntervalSinceNow > 5
|
||||
{
|
||||
token = cached
|
||||
} else {
|
||||
token = try await exchangeRelayAccessToken(
|
||||
clerkToken: clerkToken,
|
||||
scopes: scopes,
|
||||
thumbprint: thumbprint
|
||||
)
|
||||
cachedTokens[cacheKey] = token
|
||||
}
|
||||
let proof = try await signer.proof(
|
||||
method: method,
|
||||
url: url,
|
||||
accessToken: token.accessToken
|
||||
)
|
||||
return (token.accessToken, proof.value)
|
||||
}
|
||||
|
||||
private func exchangeRelayAccessToken(
|
||||
clerkToken: String,
|
||||
scopes: [T3ConnectRelayScope],
|
||||
thumbprint: String
|
||||
) async throws -> CachedToken {
|
||||
let target = endpoint(["v1", "client", "dpop-token"])
|
||||
let proof = try await signer.proof(method: "POST", url: target)
|
||||
let requestedScopes = scopes.map(\.rawValue).sorted()
|
||||
let fields = [
|
||||
"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
|
||||
"subject_token": clerkToken,
|
||||
"subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
|
||||
"requested_token_type": "urn:ietf:params:oauth:token-type:access_token",
|
||||
"resource": configuration.relayHTTPURL.absoluteString,
|
||||
"scope": requestedScopes.joined(separator: " "),
|
||||
"client_id": "t3-mobile",
|
||||
]
|
||||
var request = URLRequest(url: target)
|
||||
request.httpMethod = "POST"
|
||||
request.httpBody = Self.formEncoded(fields)
|
||||
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
|
||||
request.setValue(proof.value, forHTTPHeaderField: "DPoP")
|
||||
let response = try await send(request, as: T3ConnectRelayAccessToken.self)
|
||||
let granted = Set(response.scope.split(separator: " ").map(String.init))
|
||||
guard granted == Set(requestedScopes) else {
|
||||
throw T3ConnectRelayError.unexpectedScope(
|
||||
requested: requestedScopes,
|
||||
granted: response.scope
|
||||
)
|
||||
}
|
||||
guard response.tokenType == "DPoP" else {
|
||||
throw T3ConnectRelayError.invalidResponse
|
||||
}
|
||||
return CachedToken(
|
||||
accessToken: response.accessToken,
|
||||
expiresAt: Date().addingTimeInterval(TimeInterval(response.expiresIn)),
|
||||
scopes: scopes,
|
||||
thumbprint: thumbprint
|
||||
)
|
||||
}
|
||||
|
||||
private func request(path: [String], method: String) -> URLRequest {
|
||||
var request = URLRequest(url: endpoint(path))
|
||||
request.httpMethod = method
|
||||
return request
|
||||
}
|
||||
|
||||
private func jsonRequest<Payload: Encodable>(
|
||||
path: [String],
|
||||
method: String,
|
||||
payload: Payload
|
||||
) throws -> URLRequest {
|
||||
var request = request(path: path, method: method)
|
||||
request.httpBody = try JSONEncoder.t3.encode(payload)
|
||||
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||
return request
|
||||
}
|
||||
|
||||
private func endpoint(_ path: [String]) -> URL {
|
||||
path.reduce(configuration.relayHTTPURL) { partial, component in
|
||||
partial.appendingPathComponent(component)
|
||||
}
|
||||
}
|
||||
|
||||
private func send<Response: Decodable & Sendable>(
|
||||
_ request: URLRequest,
|
||||
as type: Response.Type
|
||||
) async throws -> Response {
|
||||
let (data, response) = try await transport.data(for: HTTPRequestPolicy.prepare(request))
|
||||
guard (200..<300).contains(response.statusCode) else {
|
||||
let body = try? JSONDecoder.t3.decode(RelayErrorBody.self, from: data)
|
||||
throw T3ConnectRelayError.response(
|
||||
status: response.statusCode,
|
||||
message: body?.message ?? body?.reason ?? body?.code ?? "T3 Connect request failed.",
|
||||
traceID: body?.traceId
|
||||
)
|
||||
}
|
||||
do {
|
||||
return try JSONDecoder.t3.decode(type, from: data)
|
||||
} catch {
|
||||
throw T3ConnectRelayError.invalidResponse
|
||||
}
|
||||
}
|
||||
|
||||
private func scopeCacheKey(_ scopes: [T3ConnectRelayScope]) -> String {
|
||||
scopes.map(\.rawValue).sorted().joined(separator: " ")
|
||||
}
|
||||
|
||||
private static func formEncoded(_ fields: [String: String]) -> Data {
|
||||
var components = URLComponents()
|
||||
components.queryItems = fields.keys.sorted().map {
|
||||
URLQueryItem(name: $0, value: fields[$0])
|
||||
}
|
||||
return Data((components.percentEncodedQuery ?? "").utf8)
|
||||
}
|
||||
|
||||
private struct ConnectRequest: Encodable {
|
||||
let deviceId: String?
|
||||
let clientProofKeyThumbprint: String
|
||||
}
|
||||
}
|
||||
|
||||
private extension T3ConnectRelayError {
|
||||
var isRejectedAuthorization: Bool {
|
||||
guard case let .response(status, _, _) = self else { return false }
|
||||
return status == 401
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
import Foundation
|
||||
|
||||
public enum T3ConnectRelayScope: String, Codable, CaseIterable, Sendable {
|
||||
case environmentConnect = "environment:connect"
|
||||
case environmentStatus = "environment:status"
|
||||
case mobileRegistration = "mobile:registration"
|
||||
}
|
||||
|
||||
public enum T3ConnectManagedEndpointProvider: String, Codable, Sendable {
|
||||
case manual
|
||||
case cloudflareTunnel = "cloudflare_tunnel"
|
||||
case t3Relay = "t3_relay"
|
||||
}
|
||||
|
||||
public struct T3ConnectManagedEndpoint: Codable, Equatable, Sendable {
|
||||
public let httpBaseUrl: String
|
||||
public let wsBaseUrl: String
|
||||
public let providerKind: T3ConnectManagedEndpointProvider
|
||||
|
||||
public var httpBaseURL: URL? { URL(string: httpBaseUrl) }
|
||||
public var webSocketBaseURL: URL? { URL(string: wsBaseUrl) }
|
||||
}
|
||||
|
||||
public struct T3ConnectRelayEnvironment: Codable, Identifiable, Equatable, Sendable {
|
||||
public var id: String { environmentId }
|
||||
|
||||
public let environmentId: String
|
||||
public let label: String
|
||||
public let endpoint: T3ConnectManagedEndpoint
|
||||
public let linkedAt: String
|
||||
}
|
||||
|
||||
public struct T3ConnectRelayEnvironmentStatus: Codable, Equatable, Sendable {
|
||||
public enum Value: String, Codable, Sendable {
|
||||
case online
|
||||
case offline
|
||||
}
|
||||
|
||||
public let environmentId: String
|
||||
public let endpoint: T3ConnectManagedEndpoint
|
||||
public let status: Value
|
||||
public let checkedAt: String
|
||||
public let descriptor: EnvironmentDescriptor?
|
||||
public let error: String?
|
||||
public let traceId: String?
|
||||
}
|
||||
|
||||
public struct T3ConnectManagedEnvironmentCredential: Codable, Equatable, Sendable {
|
||||
public let environmentID: String
|
||||
public let label: String
|
||||
public let endpoint: T3ConnectManagedEndpoint
|
||||
public let bootstrapCredential: String
|
||||
public let bootstrapExpiresAt: String
|
||||
public let proofKeyThumbprint: String
|
||||
}
|
||||
|
||||
public struct T3ConnectEnvironmentLinkChallengeRequest: Codable, Equatable, Sendable {
|
||||
public let notificationsEnabled: Bool
|
||||
public let liveActivitiesEnabled: Bool
|
||||
public let managedTunnelsEnabled: Bool
|
||||
|
||||
public init(
|
||||
notificationsEnabled: Bool,
|
||||
liveActivitiesEnabled: Bool,
|
||||
managedTunnelsEnabled: Bool = true
|
||||
) {
|
||||
self.notificationsEnabled = notificationsEnabled
|
||||
self.liveActivitiesEnabled = liveActivitiesEnabled
|
||||
self.managedTunnelsEnabled = managedTunnelsEnabled
|
||||
}
|
||||
}
|
||||
|
||||
public struct T3ConnectEnvironmentLinkChallenge: Codable, Equatable, Sendable {
|
||||
public let challenge: String
|
||||
public let expiresAt: String
|
||||
}
|
||||
|
||||
public struct T3ConnectEnvironmentLinkRequest: Codable, Equatable, Sendable {
|
||||
public let deviceId: String?
|
||||
public let proof: String
|
||||
public let notificationsEnabled: Bool
|
||||
public let liveActivitiesEnabled: Bool
|
||||
public let managedTunnelsEnabled: Bool
|
||||
|
||||
public init(
|
||||
deviceID: String? = nil,
|
||||
proof: String,
|
||||
notificationsEnabled: Bool,
|
||||
liveActivitiesEnabled: Bool,
|
||||
managedTunnelsEnabled: Bool = true
|
||||
) {
|
||||
deviceId = deviceID
|
||||
self.proof = proof
|
||||
self.notificationsEnabled = notificationsEnabled
|
||||
self.liveActivitiesEnabled = liveActivitiesEnabled
|
||||
self.managedTunnelsEnabled = managedTunnelsEnabled
|
||||
}
|
||||
}
|
||||
|
||||
public struct T3ConnectManagedEndpointRuntime: Codable, Equatable, Sendable {
|
||||
public let providerKind: T3ConnectManagedEndpointProvider
|
||||
public let connectorToken: String
|
||||
public let tunnelId: String?
|
||||
public let tunnelName: String?
|
||||
}
|
||||
|
||||
public struct T3ConnectEnvironmentLinkResponse: Codable, Equatable, Sendable {
|
||||
public let ok: Bool
|
||||
public let cloudUserId: String
|
||||
public let environmentId: String
|
||||
public let endpoint: T3ConnectManagedEndpoint
|
||||
public let endpointRuntime: T3ConnectManagedEndpointRuntime?
|
||||
public let relayIssuer: String
|
||||
public let environmentCredential: String
|
||||
public let cloudMintPublicKey: String
|
||||
}
|
||||
|
||||
public struct T3ConnectDevicePreferences: Codable, Equatable, Sendable {
|
||||
public let liveActivitiesEnabled: Bool
|
||||
public let notificationsEnabled: Bool
|
||||
public let notifyOnApproval: Bool
|
||||
public let notifyOnInput: Bool
|
||||
public let notifyOnCompletion: Bool
|
||||
public let notifyOnFailure: Bool
|
||||
|
||||
public init(
|
||||
liveActivitiesEnabled: Bool = true,
|
||||
notificationsEnabled: Bool = true,
|
||||
notifyOnApproval: Bool = true,
|
||||
notifyOnInput: Bool = true,
|
||||
notifyOnCompletion: Bool = true,
|
||||
notifyOnFailure: Bool = true
|
||||
) {
|
||||
self.liveActivitiesEnabled = liveActivitiesEnabled
|
||||
self.notificationsEnabled = notificationsEnabled
|
||||
self.notifyOnApproval = notifyOnApproval
|
||||
self.notifyOnInput = notifyOnInput
|
||||
self.notifyOnCompletion = notifyOnCompletion
|
||||
self.notifyOnFailure = notifyOnFailure
|
||||
}
|
||||
}
|
||||
|
||||
public struct T3ConnectDeviceRegistration: Codable, Equatable, Sendable {
|
||||
public enum APNSEnvironment: String, Codable, Sendable {
|
||||
case sandbox
|
||||
case production
|
||||
}
|
||||
|
||||
public let deviceId: String
|
||||
public let label: String
|
||||
public let platform: String
|
||||
public let iosMajorVersion: Int
|
||||
public let appVersion: String?
|
||||
public let bundleId: String?
|
||||
public let apsEnvironment: APNSEnvironment?
|
||||
public let pushToken: String?
|
||||
public let pushToStartToken: String?
|
||||
public let preferences: T3ConnectDevicePreferences
|
||||
|
||||
public init(
|
||||
deviceID: String,
|
||||
label: String,
|
||||
iosMajorVersion: Int,
|
||||
appVersion: String? = nil,
|
||||
bundleID: String? = nil,
|
||||
apsEnvironment: APNSEnvironment? = nil,
|
||||
pushToken: String? = nil,
|
||||
pushToStartToken: String? = nil,
|
||||
preferences: T3ConnectDevicePreferences = .init()
|
||||
) {
|
||||
deviceId = deviceID
|
||||
self.label = label
|
||||
platform = "ios"
|
||||
self.iosMajorVersion = iosMajorVersion
|
||||
self.appVersion = appVersion
|
||||
bundleId = bundleID
|
||||
self.apsEnvironment = apsEnvironment
|
||||
self.pushToken = pushToken
|
||||
self.pushToStartToken = pushToStartToken
|
||||
self.preferences = preferences
|
||||
}
|
||||
}
|
||||
|
||||
public struct T3ConnectRelayDevice: Codable, Identifiable, Equatable, Sendable {
|
||||
public struct Notifications: Codable, Equatable, Sendable {
|
||||
public let enabled: Bool
|
||||
public let notifyOnApproval: Bool
|
||||
public let notifyOnInput: Bool
|
||||
public let notifyOnCompletion: Bool
|
||||
public let notifyOnFailure: Bool
|
||||
}
|
||||
|
||||
public struct LiveActivities: Codable, Equatable, Sendable {
|
||||
public let enabled: Bool
|
||||
}
|
||||
|
||||
public var id: String { deviceId }
|
||||
|
||||
public let deviceId: String
|
||||
public let label: String
|
||||
public let platform: String
|
||||
public let iosMajorVersion: Int
|
||||
public let appVersion: String?
|
||||
public let notifications: Notifications
|
||||
public let liveActivities: LiveActivities
|
||||
public let updatedAt: String
|
||||
}
|
||||
|
||||
public struct T3ConnectRelayAccessToken: Codable, Equatable, Sendable {
|
||||
public let accessToken: String
|
||||
public let issuedTokenType: String
|
||||
public let tokenType: String
|
||||
public let expiresIn: Int
|
||||
public let scope: String
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case accessToken = "access_token"
|
||||
case issuedTokenType = "issued_token_type"
|
||||
case tokenType = "token_type"
|
||||
case expiresIn = "expires_in"
|
||||
case scope
|
||||
}
|
||||
}
|
||||
|
||||
public struct T3ConnectEnvironmentAccessToken: Codable, Equatable, Sendable {
|
||||
public let environmentID: String
|
||||
public let label: String
|
||||
public let endpoint: T3ConnectManagedEndpoint
|
||||
public let accessToken: String
|
||||
public let expiresAt: Date
|
||||
public let scopes: [String]
|
||||
public let proofKeyThumbprint: String
|
||||
|
||||
public init(
|
||||
environmentID: String,
|
||||
label: String,
|
||||
endpoint: T3ConnectManagedEndpoint,
|
||||
accessToken: String,
|
||||
expiresAt: Date,
|
||||
scopes: [String],
|
||||
proofKeyThumbprint: String
|
||||
) {
|
||||
self.environmentID = environmentID
|
||||
self.label = label
|
||||
self.endpoint = endpoint
|
||||
self.accessToken = accessToken
|
||||
self.expiresAt = expiresAt
|
||||
self.scopes = scopes
|
||||
self.proofKeyThumbprint = proofKeyThumbprint
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
import SwiftUI
|
||||
|
||||
public struct T3ConnectView: View {
|
||||
@Bindable private var controller: T3ConnectController
|
||||
private let connectEnvironment:
|
||||
@MainActor (T3ConnectManagedEnvironmentCredential) async throws -> Void
|
||||
|
||||
public init(capability: any T3ConnectCapable) {
|
||||
controller = capability.t3ConnectController
|
||||
connectEnvironment = capability.connectT3Environment
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
List {
|
||||
if let reason = controller.unavailableReason {
|
||||
unavailableSection(reason)
|
||||
} else if let account = controller.account {
|
||||
accountSection(account)
|
||||
environmentSection
|
||||
} else {
|
||||
signInSection
|
||||
}
|
||||
}
|
||||
.listStyle(.plain)
|
||||
.scrollContentBackground(.hidden)
|
||||
.background(Color.black)
|
||||
.navigationTitle("T3 Connect")
|
||||
.navigationBarTitleDisplayMode(.inline)
|
||||
.toolbar {
|
||||
if controller.account != nil {
|
||||
ToolbarItem(placement: .topBarTrailing) {
|
||||
Button("Sign out", role: .destructive) {
|
||||
Task { await controller.signOut() }
|
||||
}
|
||||
.disabled(controller.isRefreshing)
|
||||
}
|
||||
}
|
||||
}
|
||||
.refreshable {
|
||||
await controller.refresh()
|
||||
}
|
||||
.task {
|
||||
await controller.refresh()
|
||||
}
|
||||
.alert(
|
||||
"T3 Connect",
|
||||
isPresented: Binding(
|
||||
get: { controller.errorMessage != nil },
|
||||
set: { if !$0 { controller.errorMessage = nil } }
|
||||
)
|
||||
) {
|
||||
Button("OK") { controller.errorMessage = nil }
|
||||
} message: {
|
||||
Text(controller.errorMessage ?? "Something went wrong.")
|
||||
}
|
||||
.preferredColorScheme(.dark)
|
||||
}
|
||||
|
||||
private func unavailableSection(_ reason: String) -> some View {
|
||||
Section {
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
Label("Unavailable in this build", systemImage: "cloud.slash")
|
||||
.font(T3Typography.homeTitle)
|
||||
Text(reason)
|
||||
.font(T3Typography.threadBody)
|
||||
.foregroundStyle(T3Colors.textSecondary)
|
||||
Text("Direct and local connections still work without an account.")
|
||||
.font(T3Typography.supporting)
|
||||
.foregroundStyle(T3Colors.textTertiary)
|
||||
}
|
||||
.padding(.vertical, 8)
|
||||
.listRowBackground(Color.black)
|
||||
}
|
||||
}
|
||||
|
||||
private var signInSection: some View {
|
||||
Section {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Text("Your environments, on every device.")
|
||||
.font(T3Typography.homeTitle)
|
||||
Text("T3 Connect is optional. Sign in to reach environments linked to your T3 account.")
|
||||
.font(T3Typography.threadBody)
|
||||
.foregroundStyle(T3Colors.textSecondary)
|
||||
}
|
||||
.padding(.vertical, 8)
|
||||
.listRowBackground(Color.black)
|
||||
|
||||
ForEach(T3ConnectSignInProvider.allCases) { provider in
|
||||
Button {
|
||||
Task { await controller.signIn(with: provider) }
|
||||
} label: {
|
||||
HStack {
|
||||
Text(provider.title)
|
||||
.font(T3Typography.homeTitle)
|
||||
Spacer()
|
||||
Image(systemName: "arrow.up.right")
|
||||
.font(.body.weight(.semibold))
|
||||
}
|
||||
.foregroundStyle(.white)
|
||||
.padding(.vertical, 6)
|
||||
}
|
||||
.disabled(controller.isRefreshing)
|
||||
.listRowBackground(Color.black)
|
||||
}
|
||||
|
||||
if controller.isRefreshing {
|
||||
HStack(spacing: 10) {
|
||||
ProgressView()
|
||||
Text("Opening secure sign in…")
|
||||
.font(T3Typography.supporting)
|
||||
.foregroundStyle(T3Colors.textSecondary)
|
||||
}
|
||||
.listRowBackground(Color.black)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func accountSection(_ account: T3ConnectAccount) -> some View {
|
||||
Section("Account") {
|
||||
HStack(spacing: 12) {
|
||||
Image(systemName: "person.crop.circle.fill")
|
||||
.font(.title2)
|
||||
.foregroundStyle(T3Colors.textSecondary)
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text(account.email ?? "T3 account")
|
||||
.font(T3Typography.homeTitle)
|
||||
Text("Signed in")
|
||||
.font(T3Typography.supporting)
|
||||
.foregroundStyle(T3Colors.textSecondary)
|
||||
}
|
||||
}
|
||||
.padding(.vertical, 3)
|
||||
.listRowBackground(Color.black)
|
||||
}
|
||||
}
|
||||
|
||||
private var environmentSection: some View {
|
||||
Section("Cloud environments") {
|
||||
if controller.environments.isEmpty, !controller.isRefreshing {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
Text("No linked environments")
|
||||
.font(T3Typography.homeTitle)
|
||||
Text("Link an environment from T3 Code on desktop, then pull to refresh.")
|
||||
.font(T3Typography.supporting)
|
||||
.foregroundStyle(T3Colors.textSecondary)
|
||||
}
|
||||
.padding(.vertical, 8)
|
||||
.listRowBackground(Color.black)
|
||||
}
|
||||
|
||||
ForEach(controller.environments) { item in
|
||||
environmentRow(item)
|
||||
.listRowBackground(Color.black)
|
||||
.swipeActions {
|
||||
Button(role: .destructive) {
|
||||
Task { await controller.unlink(item.environment) }
|
||||
} label: {
|
||||
Label("Unlink", systemImage: "link.badge.minus")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if controller.isRefreshing {
|
||||
HStack(spacing: 10) {
|
||||
ProgressView()
|
||||
Text("Refreshing environments…")
|
||||
.font(T3Typography.supporting)
|
||||
.foregroundStyle(T3Colors.textSecondary)
|
||||
}
|
||||
.listRowBackground(Color.black)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func environmentRow(_ item: T3ConnectCloudEnvironment) -> some View {
|
||||
HStack(spacing: 12) {
|
||||
Circle()
|
||||
.fill(statusColor(item))
|
||||
.frame(width: 8, height: 8)
|
||||
.accessibilityHidden(true)
|
||||
|
||||
VStack(alignment: .leading, spacing: 3) {
|
||||
Text(item.environment.label)
|
||||
.font(T3Typography.homeTitle)
|
||||
.foregroundStyle(.white)
|
||||
.lineLimit(1)
|
||||
Text(statusText(item))
|
||||
.font(T3Typography.supporting)
|
||||
.foregroundStyle(T3Colors.textSecondary)
|
||||
.lineLimit(1)
|
||||
}
|
||||
|
||||
Spacer(minLength: 8)
|
||||
|
||||
Button {
|
||||
Task { await handleConnect(item.environment) }
|
||||
} label: {
|
||||
if controller.busyEnvironmentID == item.id {
|
||||
ProgressView()
|
||||
.frame(width: 54)
|
||||
} else {
|
||||
Text("Connect")
|
||||
.font(T3Typography.supportingStrong)
|
||||
}
|
||||
}
|
||||
.buttonStyle(.borderless)
|
||||
.disabled(controller.busyEnvironmentID != nil || item.status?.status == .offline)
|
||||
}
|
||||
.padding(.vertical, 5)
|
||||
}
|
||||
|
||||
private func handleConnect(_ environment: T3ConnectRelayEnvironment) async {
|
||||
do {
|
||||
let credential = try await controller.credential(for: environment)
|
||||
try await connectEnvironment(credential)
|
||||
} catch {
|
||||
controller.errorMessage = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
private func statusText(_ item: T3ConnectCloudEnvironment) -> String {
|
||||
if let error = item.statusError { return error }
|
||||
switch item.status?.status {
|
||||
case .online: return "Online"
|
||||
case .offline: return item.status?.error ?? "Offline"
|
||||
case nil: return "Checking…"
|
||||
}
|
||||
}
|
||||
|
||||
private func statusColor(_ item: T3ConnectCloudEnvironment) -> Color {
|
||||
switch item.status?.status {
|
||||
case .online: T3Colors.success
|
||||
case .offline: T3Colors.danger
|
||||
case nil: T3Colors.textTertiary
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ public struct SettingsView: View {
|
||||
NavigationStack {
|
||||
Form {
|
||||
connectionSection
|
||||
t3ConnectSection
|
||||
agentSection
|
||||
preferencesSection
|
||||
aboutSection
|
||||
@@ -187,6 +188,29 @@ public struct SettingsView: View {
|
||||
}
|
||||
}
|
||||
|
||||
private var t3ConnectSection: some View {
|
||||
Section("T3 Connect") {
|
||||
if let capability = model.client as? any T3ConnectCapable {
|
||||
NavigationLink {
|
||||
T3ConnectView(capability: capability)
|
||||
} label: {
|
||||
Label("Cloud environments", systemImage: "cloud")
|
||||
}
|
||||
} else {
|
||||
LabeledContent {
|
||||
Text("Unavailable")
|
||||
.foregroundStyle(T3Colors.textTertiary)
|
||||
} label: {
|
||||
Label("Cloud environments", systemImage: "cloud.slash")
|
||||
}
|
||||
}
|
||||
|
||||
Text("Optional account sync for relay-managed environments.")
|
||||
.font(T3Typography.supporting)
|
||||
.foregroundStyle(T3Colors.textSecondary)
|
||||
}
|
||||
}
|
||||
|
||||
private var preferencesSection: some View {
|
||||
Section("Preferences") {
|
||||
Picker("Theme", selection: $settings.appearance) {
|
||||
@@ -285,6 +309,19 @@ public struct SettingsView: View {
|
||||
private func save() {
|
||||
isSaving = true
|
||||
Task {
|
||||
if settings.notificationsEnabled,
|
||||
!model.snapshot.settings.notificationsEnabled
|
||||
{
|
||||
let authorized = await PlatformNotificationService.shared.requestAuthorization()
|
||||
if !authorized {
|
||||
settings.notificationsEnabled = false
|
||||
model.errorMessage = "Notifications are disabled in iOS Settings."
|
||||
}
|
||||
} else if !settings.notificationsEnabled,
|
||||
model.snapshot.settings.notificationsEnabled
|
||||
{
|
||||
_ = await PlatformNotificationService.shared.synchronize(enabled: false)
|
||||
}
|
||||
await model.saveSettings(settings)
|
||||
isSaving = false
|
||||
if model.snapshot.settings == settings {
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleURLTypes</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>CFBundleTypeRole</key>
|
||||
<string>Editor</string>
|
||||
<key>CFBundleURLName</key>
|
||||
<string>T3 Code SwiftUI Routes</string>
|
||||
<key>CFBundleURLSchemes</key>
|
||||
<array>
|
||||
<string>t3code</string>
|
||||
<string>t3</string>
|
||||
</array>
|
||||
</dict>
|
||||
</array>
|
||||
<key>T3ConnectClerkJWTTemplate</key>
|
||||
<string>$(T3CODE_CLERK_JWT_TEMPLATE)</string>
|
||||
<key>T3ConnectClerkPublishableKey</key>
|
||||
<string>$(T3CODE_CLERK_PUBLISHABLE_KEY)</string>
|
||||
<key>T3ConnectRelayHTTPURL</key>
|
||||
<string>$(T3CODE_RELAY_URL)</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -6,6 +6,20 @@
|
||||
objectVersion = 77;
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
B10000000000000000000001 /* ClerkKit in Frameworks */ = {isa = PBXBuildFile; productRef = B30000000000000000000001 /* ClerkKit */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */
|
||||
BE0000000000000000000001 /* Exceptions for "Resources" folder in "T3Code" target */ = {
|
||||
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
|
||||
membershipExceptions = (
|
||||
Info.plist,
|
||||
);
|
||||
target = A50000000000000000000001 /* T3Code */;
|
||||
};
|
||||
/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */
|
||||
|
||||
/* Begin PBXFileSystemSynchronizedRootGroup section */
|
||||
A10000000000000000000001 /* App */ = {
|
||||
isa = PBXFileSystemSynchronizedRootGroup;
|
||||
@@ -29,6 +43,9 @@
|
||||
};
|
||||
A10000000000000000000005 /* Resources */ = {
|
||||
isa = PBXFileSystemSynchronizedRootGroup;
|
||||
exceptions = (
|
||||
BE0000000000000000000001 /* Exceptions for "Resources" folder in "T3Code" target */,
|
||||
);
|
||||
path = Resources;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
@@ -44,6 +61,7 @@
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
B10000000000000000000001 /* ClerkKit in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -113,6 +131,7 @@
|
||||
);
|
||||
name = T3Code;
|
||||
packageProductDependencies = (
|
||||
B30000000000000000000001 /* ClerkKit */,
|
||||
);
|
||||
productName = T3Code;
|
||||
productReference = A40000000000000000000001 /* T3 Code.app */;
|
||||
@@ -172,6 +191,9 @@
|
||||
minimizedProjectReferenceProxies = 1;
|
||||
preferredProjectObjectVersion = 77;
|
||||
productRefGroup = A30000000000000000000002 /* Products */;
|
||||
packageReferences = (
|
||||
B20000000000000000000001 /* XCRemoteSwiftPackageReference "clerk-ios" */,
|
||||
);
|
||||
projectDirPath = "";
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
@@ -345,6 +367,7 @@
|
||||
CURRENT_PROJECT_VERSION = 1;
|
||||
ENABLE_PREVIEWS = YES;
|
||||
GENERATE_INFOPLIST_FILE = YES;
|
||||
INFOPLIST_FILE = Resources/Info.plist;
|
||||
INFOPLIST_KEY_CFBundleDisplayName = "T3 Code (SwiftUI)";
|
||||
INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO;
|
||||
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";
|
||||
@@ -382,6 +405,7 @@
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 1;
|
||||
GENERATE_INFOPLIST_FILE = YES;
|
||||
INFOPLIST_FILE = Resources/Info.plist;
|
||||
INFOPLIST_KEY_CFBundleDisplayName = "T3 Code (SwiftUI)";
|
||||
INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO;
|
||||
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";
|
||||
@@ -479,6 +503,25 @@
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
|
||||
/* Begin XCRemoteSwiftPackageReference section */
|
||||
B20000000000000000000001 /* XCRemoteSwiftPackageReference "clerk-ios" */ = {
|
||||
isa = XCRemoteSwiftPackageReference;
|
||||
repositoryURL = "https://github.com/clerk/clerk-ios.git";
|
||||
requirement = {
|
||||
kind = exactVersion;
|
||||
version = 1.2.0;
|
||||
};
|
||||
};
|
||||
/* End XCRemoteSwiftPackageReference section */
|
||||
|
||||
/* Begin XCSwiftPackageProductDependency section */
|
||||
B30000000000000000000001 /* ClerkKit */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
package = B20000000000000000000001 /* XCRemoteSwiftPackageReference "clerk-ios" */;
|
||||
productName = ClerkKit;
|
||||
};
|
||||
/* End XCSwiftPackageProductDependency section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
A40000000000000000000001 /* T3 Code.app */ = {
|
||||
isa = PBXFileReference;
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import CryptoKit
|
||||
import XCTest
|
||||
@testable import T3Code
|
||||
|
||||
final class T3ConnectDPoPTests: XCTestCase {
|
||||
func testCanonicalJWKThumbprintAndSignedProofMatchRFCShape() async throws {
|
||||
var scalar = Data(repeating: 0, count: 32)
|
||||
scalar[31] = 1
|
||||
let signer = try T3ConnectDPoPSigner(privateKeyRawRepresentation: scalar)
|
||||
let jwk = try await signer.publicJWK()
|
||||
|
||||
XCTAssertEqual(
|
||||
jwk.canonicalThumbprintInput,
|
||||
#"{"crv":"P-256","kty":"EC","x":"axfR8uEsQkf4vOblY6RA8ncDfYEt6zOg9KE5RdiYwpY","y":"T-NC4v4af5uO5-tKfA-eFivOM1drMV7Oy7ZAaDe_UfU"}"#
|
||||
)
|
||||
XCTAssertEqual(jwk.thumbprint, "xx0BcA-wMohw8atYDJOe6peGModklG2wRHBlXHMvl0M")
|
||||
|
||||
let token = "access-token"
|
||||
let proof = try await signer.proof(
|
||||
method: "post",
|
||||
url: URL(string: "https://relay.example/v1/connect?ignored=yes#fragment")!,
|
||||
accessToken: token,
|
||||
issuedAt: Date(timeIntervalSince1970: 1_800_000_000),
|
||||
identifier: UUID(uuidString: "12345678-1234-1234-1234-1234567890ab")!
|
||||
)
|
||||
let components = proof.value.split(separator: ".").map(String.init)
|
||||
XCTAssertEqual(components.count, 3)
|
||||
|
||||
let header = try jsonObject(components[0])
|
||||
XCTAssertEqual(header["typ"] as? String, "dpop+jwt")
|
||||
XCTAssertEqual(header["alg"] as? String, "ES256")
|
||||
XCTAssertNil((header["jwk"] as? [String: Any])?["d"])
|
||||
|
||||
let payload = try jsonObject(components[1])
|
||||
XCTAssertEqual(payload["htm"] as? String, "POST")
|
||||
XCTAssertEqual(payload["htu"] as? String, "https://relay.example/v1/connect")
|
||||
XCTAssertEqual(payload["iat"] as? Int, 1_800_000_000)
|
||||
XCTAssertEqual(
|
||||
payload["ath"] as? String,
|
||||
T3ConnectDPoPSigner.accessTokenHash(token)
|
||||
)
|
||||
|
||||
let x = try decodeBase64URL(jwk.x)
|
||||
let y = try decodeBase64URL(jwk.y)
|
||||
let publicKey = try P256.Signing.PublicKey(
|
||||
x963Representation: Data([0x04]) + x + y
|
||||
)
|
||||
let signature = try P256.Signing.ECDSASignature(
|
||||
rawRepresentation: decodeBase64URL(components[2])
|
||||
)
|
||||
XCTAssertTrue(
|
||||
publicKey.isValidSignature(
|
||||
signature,
|
||||
for: Data("\(components[0]).\(components[1])".utf8)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
func testHTUNormalizationDropsDefaultPortQueryAndFragment() {
|
||||
XCTAssertEqual(
|
||||
T3ConnectDPoPSigner.normalizedHTU(
|
||||
URL(string: "https://relay.example:443/path?query=one#fragment")!
|
||||
)?.absoluteString,
|
||||
"https://relay.example/path"
|
||||
)
|
||||
XCTAssertEqual(
|
||||
T3ConnectDPoPSigner.normalizedHTU(
|
||||
URL(string: "https://relay.example:8443/path")!
|
||||
)?.absoluteString,
|
||||
"https://relay.example:8443/path"
|
||||
)
|
||||
}
|
||||
|
||||
func testCloudConfigurationRequiresAllPublicEndpoints() {
|
||||
XCTAssertEqual(
|
||||
T3ConnectConfiguration.resolve(infoDictionary: [:]),
|
||||
.unavailable(
|
||||
reason: "This build is missing Clerk publishable key, relay HTTP URL."
|
||||
)
|
||||
)
|
||||
|
||||
let resolution = T3ConnectConfiguration.resolve(infoDictionary: [
|
||||
"T3ConnectClerkPublishableKey": "pk_test_example",
|
||||
"T3ConnectClerkJWTTemplate": "relay-template",
|
||||
"T3ConnectRelayHTTPURL": "https://relay.example/",
|
||||
])
|
||||
guard case let .available(configuration) = resolution else {
|
||||
return XCTFail("Expected available T3 Connect configuration")
|
||||
}
|
||||
XCTAssertEqual(configuration.clerkJWTTemplate, "relay-template")
|
||||
XCTAssertEqual(configuration.relayHTTPURL.absoluteString, "https://relay.example/")
|
||||
}
|
||||
|
||||
private func jsonObject(_ encoded: String) throws -> [String: Any] {
|
||||
let data = try decodeBase64URL(encoded)
|
||||
return try XCTUnwrap(
|
||||
JSONSerialization.jsonObject(with: data) as? [String: Any]
|
||||
)
|
||||
}
|
||||
|
||||
private func decodeBase64URL(_ value: String) throws -> Data {
|
||||
var base64 = value.replacingOccurrences(of: "-", with: "+")
|
||||
.replacingOccurrences(of: "_", with: "/")
|
||||
base64 += String(repeating: "=", count: (4 - base64.count % 4) % 4)
|
||||
return try XCTUnwrap(Data(base64Encoded: base64))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import XCTest
|
||||
@testable import T3Code
|
||||
|
||||
final class T3ConnectRelayDecodingTests: XCTestCase {
|
||||
func testRelayEnvironmentAndStatusDecodeCurrentContract() throws {
|
||||
let environment = try JSONDecoder.t3.decode(
|
||||
T3ConnectRelayEnvironment.self,
|
||||
from: Data(
|
||||
#"{"environmentId":"env-1","label":"Studio","endpoint":{"httpBaseUrl":"https://studio.example","wsBaseUrl":"wss://studio.example","providerKind":"cloudflare_tunnel"},"linkedAt":"2026-08-01T12:00:00.000Z"}"#.utf8
|
||||
)
|
||||
)
|
||||
XCTAssertEqual(environment.id, "env-1")
|
||||
XCTAssertEqual(environment.endpoint.providerKind, .cloudflareTunnel)
|
||||
|
||||
let status = try JSONDecoder.t3.decode(
|
||||
T3ConnectRelayEnvironmentStatus.self,
|
||||
from: Data(
|
||||
#"{"environmentId":"env-1","endpoint":{"httpBaseUrl":"https://studio.example","wsBaseUrl":"wss://studio.example","providerKind":"cloudflare_tunnel"},"status":"offline","checkedAt":"2026-08-01T12:01:00.000Z","error":"connector unavailable","traceId":"trace-1"}"#.utf8
|
||||
)
|
||||
)
|
||||
XCTAssertEqual(status.status, .offline)
|
||||
XCTAssertEqual(status.error, "connector unavailable")
|
||||
XCTAssertEqual(status.traceId, "trace-1")
|
||||
}
|
||||
|
||||
func testRelayTokensAndLinkResponsesDecodeSnakeCaseAndOptionalRuntime() throws {
|
||||
let token = try JSONDecoder.t3.decode(
|
||||
T3ConnectRelayAccessToken.self,
|
||||
from: Data(
|
||||
#"{"access_token":"relay-token","issued_token_type":"urn:ietf:params:oauth:token-type:access_token","token_type":"DPoP","expires_in":300,"scope":"environment:status environment:connect"}"#.utf8
|
||||
)
|
||||
)
|
||||
XCTAssertEqual(token.accessToken, "relay-token")
|
||||
XCTAssertEqual(token.expiresIn, 300)
|
||||
|
||||
let link = try JSONDecoder.t3.decode(
|
||||
T3ConnectEnvironmentLinkResponse.self,
|
||||
from: Data(
|
||||
#"{"ok":true,"cloudUserId":"user-1","environmentId":"env-1","endpoint":{"httpBaseUrl":"https://studio.example","wsBaseUrl":"wss://studio.example","providerKind":"t3_relay"},"endpointRuntime":null,"relayIssuer":"https://relay.example","environmentCredential":"credential","cloudMintPublicKey":"public-key"}"#.utf8
|
||||
)
|
||||
)
|
||||
XCTAssertTrue(link.ok)
|
||||
XCTAssertNil(link.endpointRuntime)
|
||||
XCTAssertEqual(link.endpoint.providerKind, .t3Relay)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user