import '../../../core/transport/server_url.dart'; /// A validated artifact url plus whether it points outside the configured /// server origin. class ResolvedArtifactUrl { const ResolvedArtifactUrl({required this.uri, required this.external}); final Uri uri; /// True when the url's origin differs from the configured server origin (or /// the configured origin is unusable). A future authenticated fetch must send /// no cookies, authorization header or other server credentials for an /// external url. final bool external; String get url => uri.toString(); } const List _unsafePrefixes = ['//', r'\\', r'\/', '/\\']; /// Resolves a recorded artifact url for display and opening. /// /// A server-relative path (`/artifacts/...`, or a path without the leading /// slash) resolves against the configured websocket endpoint's http(s) origin, /// dropping the endpoint path and query. An absolute http(s) url is preserved, /// including its encoded path and query. Output is always http(s): protocol- /// relative (`//host`), hostless, credentialed, malformed and non-http(s) urls /// are rejected with null. A blank or invalid configured endpoint resolves no /// relative path; it never invents a host. ResolvedArtifactUrl? resolveArtifactUrl( String configuredEndpoint, String artifactUrl, ) { final raw = artifactUrl.trim(); if (raw.isEmpty) return null; for (final prefix in _unsafePrefixes) { if (raw.startsWith(prefix)) return null; } final parsed = Uri.tryParse(raw); if (parsed == null) return null; final configured = _httpOrigin(configuredEndpoint); if (parsed.hasScheme) { final scheme = parsed.scheme.toLowerCase(); if (scheme != 'http' && scheme != 'https') return null; if (!parsed.hasAuthority || parsed.host.isEmpty) return null; if (parsed.userInfo.isNotEmpty) return null; return ResolvedArtifactUrl( uri: parsed, external: configured == null || parsed.origin != configured.origin, ); } if (configured == null) return null; final relative = raw.startsWith('/') ? raw : '/$raw'; final resolved = Uri.tryParse('${configured.origin}$relative'); if (resolved == null) return null; final scheme = resolved.scheme.toLowerCase(); if (scheme != 'http' && scheme != 'https') return null; if (!resolved.hasAuthority || resolved.host.isEmpty) return null; if (resolved.userInfo.isNotEmpty) return null; return ResolvedArtifactUrl(uri: resolved, external: false); } /// The http(s) origin of a configured websocket endpoint, or null when the /// endpoint is blank, malformed, or not a ws/wss url. Uri? _httpOrigin(String configuredEndpoint) { try { final endpoint = ServerUrl.validate(configuredEndpoint); final http = Uri.parse(endpoint.httpUrl); final scheme = http.scheme.toLowerCase(); if (scheme != 'http' && scheme != 'https') return null; if (http.host.isEmpty) return null; return Uri.parse(http.origin); } on FormatException { return null; } }