From 410ef006445358218839ea1cb19e38c86feba827 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 22 Nov 2026 19:16:51 -0600 Subject: add CORS options --- src/slskd/Core/Options.cs | 67 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 1f6ceac2..100f612a 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -2092,6 +2092,12 @@ namespace slskd [Validate] public WebAuthenticationOptions Authentication { get; init; } = new WebAuthenticationOptions(); + /// + /// CORS options. + /// + [Validate] + public CorsOptions Cors { get; init; } = new CorsOptions(); + /// /// Authentication options. /// @@ -2385,6 +2391,67 @@ namespace slskd public string Password { get; init; } } } + + public class CorsOptions : IValidatableObject + { + [Argument(default, "cors-allowed-origins")] + [EnvironmentVariable("CORS_ALLOWED_ORIGINS")] + [Description("CORS allowed origins, comma separated")] + [RequiresRestart] + public string[] AllowedOrigins { get; init; } = null; + + [Argument(default, "cors-allow-credentials")] + [EnvironmentVariable("CORS_ALLOW_CREDENTIALS")] + [Description("CORS allow credentials (cookies, basic auth)")] + [RequiresRestart] + public bool AllowCredentials { get; init; } = false; + + public IEnumerable Validate(ValidationContext validationContext) + { + if (AllowedOrigins?.Count(x => x == "*") > 1) + { + yield return new ValidationResult("Specify only one wildcard origin (\"*\")"); + } + + foreach (var origin in (AllowedOrigins ?? []).Where(o => o != "*")) + { + if (origin.Contains('*')) + { + yield return new ValidationResult($"Origin {origin} must not contain a wildcard"); + } + + if (!Uri.TryCreate(origin, default(UriCreationOptions), out var o)) + { + yield return new ValidationResult($"Origin {origin} is not a valid URI"); + } + + if (!o.IsAbsoluteUri) + { + yield return new ValidationResult($"Origin {origin} must be an absolute URI"); + } + + string[] validSchemes = ["http", "https"]; + + if (!validSchemes.Contains(o.Scheme, StringComparer.OrdinalIgnoreCase)) + { + yield return new ValidationResult($"Origin {origin} must use the HTTP or HTTPS scheme"); + } + + var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicyBuilder().WithOrigins(origin).Build(); + var browserOrigin = $"{o.Scheme}://{o.IdnHost}{(o.IsDefaultPort ? string.Empty : $":{o.Port}")}"; + + if (!policy.IsOriginAllowed(browserOrigin)) + { + yield return new ValidationResult($"Origin {origin} is malformed and will never match a browser request; rewrite it as {browserOrigin}"); + } + } + + if ((AllowedOrigins is null || AllowedOrigins.Length == 0 || AllowedOrigins.Contains("*")) && AllowCredentials) + { + yield return new ValidationResult("Credentials can not be allowed while allowing all origins"); + } + } + } } /// -- cgit v1.2.3