File size: 12,895 Bytes
b8370f5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 | import Foundation
public struct OpenClawChatSourceContext: Hashable, Sendable {
public let gatewayURL: URL
/// Percent-encoded mount shared by resource routing and dedicated-link matching.
public let basePath: String
public let publicOrigin: URL?
public let automaticallyFetchFavicons: Bool
public init(
gatewayURL: URL,
basePath: String,
publicOrigin: URL? = nil,
automaticallyFetchFavicons: Bool = false)
{
self.gatewayURL = gatewayURL
self.basePath = basePath
self.publicOrigin = publicOrigin
self.automaticallyFetchFavicons = automaticallyFetchFavicons
}
}
/// One connected route owns bootstrap discovery and its preference snapshot.
/// Native adapters supply authenticated, bounded requests tied to that route.
public actor OpenClawChatSourceResources {
public typealias Request = @Sendable (URL, Int) async throws -> (Data, URLResponse)
public typealias ConfigLoader = @Sendable () async -> Data?
public typealias IsCurrent = @Sendable () async -> Bool
public static let maximumFaviconBytes = 64 * 1024
private let gatewayURL: URL
private let nativeControlPageURL: URL?
private let request: Request
private let loadConfig: ConfigLoader
private let isCurrent: IsCurrent
private var revision: UInt64 = 0
private struct ContextSnapshot: Sendable {
let context: OpenClawChatSourceContext
let resourceBaseURL: URL
}
private var contextTask: Task<ContextSnapshot?, Never>?
private var faviconTasks: [URL: Task<Data?, Never>] = [:]
private var faviconOrder: [URL] = []
private static let maximumCachedFavicons = 32
public init(
gatewayURL: URL,
nativeControlPageURL: URL? = nil,
request: @escaping Request,
loadConfig: @escaping ConfigLoader,
isCurrent: @escaping IsCurrent)
{
self.gatewayURL = gatewayURL
self.nativeControlPageURL = nativeControlPageURL
self.request = request
self.loadConfig = loadConfig
self.isCurrent = isCurrent
}
public func invalidate() {
self.revision &+= 1
self.contextTask?.cancel()
self.contextTask = nil
for task in self.faviconTasks.values {
task.cancel()
}
self.faviconTasks.removeAll()
self.faviconOrder.removeAll()
}
public func loadContext() async -> OpenClawChatSourceContext? {
await self.loadContextSnapshot()?.context
}
private func loadContextSnapshot() async -> ContextSnapshot? {
guard await self.isCurrent(), !Task.isCancelled else { return nil }
let revision = self.revision
let task: Task<ContextSnapshot?, Never>
if let existing = contextTask {
task = existing
} else {
task = Task { await self.discoverContext() }
self.contextTask = task
}
let context = await task.value
guard await self.isCurrent(), self.revision == revision, !Task.isCancelled else { return nil }
return context
}
public func loadFavicon(host: String) async -> Data? {
let revision = self.revision
guard let snapshot = await loadContextSnapshot(), snapshot.context.automaticallyFetchFavicons,
let url = Self.faviconURL(host: host, baseURL: snapshot.resourceBaseURL),
await isCurrent(), self.revision == revision, !Task.isCancelled
else { return nil }
let task: Task<Data?, Never>
if let cached = self.faviconTasks[url] {
task = cached
} else {
if self.faviconOrder.count >= Self.maximumCachedFavicons {
let oldest = self.faviconOrder.removeFirst()
self.faviconTasks.removeValue(forKey: oldest)?.cancel()
}
task = Task { await self.downloadFavicon(url: url, revision: revision) }
self.faviconTasks[url] = task
self.faviconOrder.append(url)
}
let data = await task.value
guard await self.isCurrent(), self.revision == revision, !Task.isCancelled else { return nil }
return data
}
private func downloadFavicon(url: URL, revision: UInt64) async -> Data? {
guard await self.isCurrent(), self.revision == revision, !Task.isCancelled,
let (data, response) = try? await self.request(url, Self.maximumFaviconBytes),
await self.isCurrent(), self.revision == revision, !Task.isCancelled,
let http = response as? HTTPURLResponse,
(200..<300).contains(http.statusCode),
http.mimeType?.lowercased().hasPrefix("image/") == true,
!data.isEmpty, data.count <= Self.maximumFaviconBytes
else { return nil }
return data
}
/// Proxy and Gateway credentials share one HTTP header. Preserve the proxy
/// attempt, then retry only an authentication rejection with the Gateway bearer.
public static func performAuthenticatedRequest(
_ request: URLRequest,
bearer: String?,
send: @Sendable (URLRequest) async throws -> (Data, URLResponse)) async throws -> (Data, URLResponse)
{
var request = request
let configuredAuthorization = request.value(forHTTPHeaderField: "Authorization")
let gatewayAuthorization = bearer.map { "Bearer " + $0 }
if configuredAuthorization == nil {
request.setValue(gatewayAuthorization, forHTTPHeaderField: "Authorization")
}
let result = try await send(request)
guard let configuredAuthorization,
let gatewayAuthorization, gatewayAuthorization != configuredAuthorization,
let response = result.1 as? HTTPURLResponse,
response.statusCode == 401 || response.statusCode == 403
else { return result }
try Task.checkCancellation()
request.setValue(gatewayAuthorization, forHTTPHeaderField: "Authorization")
return try await send(request)
}
private func discoverContext() async -> ContextSnapshot? {
guard let gatewayURL = Self.httpURL(self.gatewayURL) else { return nil }
let configData = await self.loadConfig()
guard await self.isCurrent() else { return nil }
let config = configData.flatMap { try? JSONDecoder().decode(ConfigSnapshot.self, from: $0) }
if let config {
let controlUI = config.runtimeConfig.gateway?.controlUi
return self.contextSnapshot(
gatewayURL: gatewayURL,
basePath: controlUI?.basePath ?? "",
publicOrigin: config.runtimeConfig.gateway?.publicOrigin.flatMap(Self.publicOrigin),
automaticallyFetchFavicons: controlUI?.automaticallyFetchFavicons != false)
}
let bootstrapBase = self.controlPageURL(gatewayURL: gatewayURL) ?? gatewayURL
guard let url = Self.appendResourcePath("/control-ui-config.json", to: bootstrapBase),
await self.isCurrent(), !Task.isCancelled
else { return nil }
if let (data, response) = try? await self.request(url, 64 * 1024),
let http = response as? HTTPURLResponse,
(200..<300).contains(http.statusCode), http.mimeType == "application/json",
let bootstrap = try? JSONDecoder().decode(Bootstrap.self, from: data)
{
guard await self.isCurrent(), !Task.isCancelled else { return nil }
if let snapshot = self.contextSnapshot(
gatewayURL: gatewayURL,
basePath: bootstrap.basePath,
automaticallyFetchFavicons: bootstrap.automaticallyFetchFavicons ?? false)
{
return snapshot
}
}
guard await self.isCurrent() else { return nil }
return self.contextSnapshot(gatewayURL: gatewayURL, basePath: "", automaticallyFetchFavicons: false)
}
private func contextSnapshot(
gatewayURL: URL,
basePath: String,
publicOrigin: URL? = nil,
automaticallyFetchFavicons: Bool) -> ContextSnapshot?
{
guard let basePath = Self.normalizedBasePath(basePath) else { return nil }
let resourceBaseURL: URL? = if basePath.isEmpty,
let controlPageURL = self.controlPageURL(gatewayURL: gatewayURL)
{
controlPageURL
} else {
Self.resourceURL(gatewayURL: gatewayURL, basePath: basePath, path: "")
}
guard let resourceBaseURL,
let components = URLComponents(url: resourceBaseURL, resolvingAgainstBaseURL: false)
else { return nil }
let mount = components.percentEncodedPath.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
return ContextSnapshot(
context: OpenClawChatSourceContext(
gatewayURL: gatewayURL,
basePath: mount.isEmpty ? "" : "/" + mount,
publicOrigin: publicOrigin,
automaticallyFetchFavicons: automaticallyFetchFavicons),
resourceBaseURL: resourceBaseURL)
}
private func controlPageURL(gatewayURL: URL) -> URL? {
guard let nativeControlPageURL, let url = Self.httpURL(nativeControlPageURL),
url.scheme == gatewayURL.scheme, url.host?.lowercased() == gatewayURL.host?.lowercased(),
(url.port ?? (url.scheme == "https" ? 443 : 80)) ==
(gatewayURL.port ?? (gatewayURL.scheme == "https" ? 443 : 80))
else { return nil }
return url
}
static func httpURL(_ url: URL) -> URL? {
guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false),
components.host?.isEmpty == false, components.user == nil, components.password == nil
else { return nil }
switch components.scheme?.lowercased() {
case "ws", "http": components.scheme = "http"
case "wss", "https": components.scheme = "https"
default: return nil
}
components.query = nil
components.fragment = nil
return components.url
}
private static func faviconURL(host: String, baseURL: URL) -> URL? {
let host = host.lowercased()
guard !host.isEmpty, host.utf8.count <= 253,
host.unicodeScalars.allSatisfy({
CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyz0123456789.-").contains($0)
}),
!host.hasPrefix("."), !host.hasSuffix("."), !host.contains("..")
else { return nil }
return Self.appendResourcePath("/__openclaw__/link-favicon/" + host, to: baseURL)
}
private static func appendResourcePath(_ path: String, to baseURL: URL) -> URL? {
guard var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: false) else { return nil }
while components.percentEncodedPath.hasSuffix("/") {
components.percentEncodedPath.removeLast()
}
components.percentEncodedPath += path
return components.url
}
private static func resourceURL(gatewayURL: URL, basePath: String, path: String) -> URL? {
guard let basePath = normalizedBasePath(basePath),
let url = httpURL(gatewayURL),
var components = URLComponents(url: url, resolvingAgainstBaseURL: false)
else { return nil }
components.path = basePath + path
return components.url
}
private static func normalizedBasePath(_ raw: String) -> String? {
let path = raw.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
guard !path.contains("\\"), !path.contains("?"), !path.contains("#"), !path.contains("%"),
!path.unicodeScalars.contains(where: { CharacterSet.controlCharacters.contains($0) }),
!path.split(separator: "/").contains(where: { $0 == "." || $0 == ".." })
else { return nil }
return path.isEmpty ? "" : "/" + path
}
private static func publicOrigin(_ raw: String) -> URL? {
guard let url = URL(string: raw), let http = httpURL(url),
["http", "https"].contains(url.scheme?.lowercased() ?? ""),
url.query == nil, url.fragment == nil
else { return nil }
return http
}
private struct Bootstrap: Decodable {
let basePath: String
let automaticallyFetchFavicons: Bool?
}
private struct ConfigSnapshot: Decodable {
let runtimeConfig: RuntimeConfig
}
private struct RuntimeConfig: Decodable {
let gateway: GatewayConfig?
}
private struct GatewayConfig: Decodable {
let publicOrigin: String?
let controlUi: ControlUIConfig?
}
private struct ControlUIConfig: Decodable {
let basePath: String?
let automaticallyFetchFavicons: Bool?
}
}
|