namespace XFESystem.Browser; /// Finite HTTP field validation shared by the script boundary and transports. public static class BrowserRequestHeaders { private static readonly HashSet Forbidden = new(StringComparer.OrdinalIgnoreCase) { "accept-charset", "accept-encoding", "access-control-request-headers", "access-control-request-method", "connection", "content-length", "cookie", "cookie2", "date", "dnt", "expect", "host", "keep-alive", "origin", "referer", "set-cookie", "te", "trailer", "transfer-encoding", "upgrade", "user-agent", "via" }; public static bool Allowed(string name, string value) { if (name.Length is 0 or > 128 || name.Any(c => !char.IsAsciiLetterOrDigit(c) && !"!#$%&'*+-.^_`|~".Contains(c)) || value.Length > 2048 || value.Any(c => c < 32 && c != '\t' || c == 127 || c > 255)) throw new ArgumentException("Invalid HTTP request field."); return !Forbidden.Contains(name) && !name.StartsWith("proxy-", StringComparison.OrdinalIgnoreCase) && !name.StartsWith("sec-", StringComparison.OrdinalIgnoreCase); } public static IReadOnlyDictionary Copy(IReadOnlyDictionary headers) { if (headers.Count > 32) throw new BrowserLimitException("The script request header count limit was reached."); var result = new Dictionary(StringComparer.OrdinalIgnoreCase); int characters = 0; foreach (var pair in headers) { if (!Allowed(pair.Key, pair.Value)) continue; if ((characters += pair.Key.Length + pair.Value.Length) > 8192) throw new BrowserLimitException("The script request headers exceed their character limit."); result[pair.Key] = pair.Value; } return result; } }