Skip to content

Permissions-Policy Builder — Rust source

Build a Permissions-Policy header interactively. Control which browser features (camera, microphone, geolocation, etc.) your site can use.

This is the Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.

//! permissions-policy — Permissions-Policy header builder / parser.
//!
//! Language: Rust (std only — no external crates).
//! CosmoDev polyglot showcase port of the `permissions-policy` tool, ported
//! from src/lib/permissions-policy.ts (the canonical TypeScript implementation).
//!
//! The header grammar is plain ASCII text, so `str` slicing plus a small
//! hand-rolled origin check reproduces the lib's regexes exactly. The
//! 29-entry feature catalog is compressed to the name -> weight pairs that
//! `privacy_score` needs; descriptive metadata stays in the TypeScript lib.
//!
//! display source — part of CosmoDev's polyglot tool pages.

use std::collections::BTreeMap;

/// feature name -> allowlist tokens. `[]` = disabled, `["*"]` = all origins.
/// A BTreeMap iterates in sorted key order, which is what the builder needs.
pub type FeatureMap = BTreeMap<String, Vec<String>>;

/// Privacy weight per impact tier: high 3, medium 2, low 1 (name, weight).
const FEATURE_WEIGHTS: &[(&str, u32)] = &[
    ("camera", 3), ("microphone", 3), ("geolocation", 3), ("display-capture", 3),
    ("idle-detection", 3), ("serial", 3), ("usb", 3), ("hid", 3), ("xr-spatial-tracking", 3),
    ("accelerometer", 2), ("ambient-light-sensor", 2), ("battery", 2), ("gyroscope", 2),
    ("magnetometer", 2), ("keyboard-map", 2), ("gamepad", 2), ("midi", 2), ("payment", 2),
    ("publickey-credentials-get", 2), ("screen-wake-lock", 2), ("speaker-selection", 2),
    ("web-share", 2), ("encrypted-media", 2), ("document-domain", 2),
    ("autoplay", 1), ("cross-origin-isolated", 1), ("fullscreen", 1),
    ("navigation-override", 1), ("picture-in-picture", 1),
];

/// Strip one layer of matching double quotes, like the lib's `^"(.*)"$` sub.
fn unquote(token: &str) -> &str {
    token.strip_prefix('"').and_then(|t| t.strip_suffix('"')).unwrap_or(token)
}

/// `^[a-z][a-z0-9-]*$` without a regex crate: lowercase kebab tokens.
fn is_valid_feature_name(name: &str) -> bool {
    let mut chars = name.chars();
    match chars.next() {
        Some(first) if first.is_ascii_lowercase() => chars
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'),
        _ => false,
    }
}

/// Strip a prefix regardless of ASCII case. Compared at the byte level so a
/// non-ASCII `text` can never trip a multi-byte char-boundary panic.
fn strip_prefix_ignore_case<'a>(text: &'a str, prefix: &str) -> Option<&'a str> {
    let bytes = text.as_bytes();
    if bytes.len() >= prefix.len() && bytes[..prefix.len()].eq_ignore_ascii_case(prefix.as_bytes())
    {
        Some(&text[prefix.len()..])
    } else {
        None
    }
}

/// Trim, then drop an optional `Permissions-Policy:` prefix — the lib's
/// `^permissions-policy\s*:\s*` replacement. No colon, no match, no strip.
fn strip_header_name(raw: &str) -> &str {
    let trimmed = raw.trim();
    let Some(after_name) = strip_prefix_ignore_case(trimmed, "permissions-policy") else {
        return trimmed;
    };
    match after_name.trim_start().strip_prefix(':') {
        Some(after_colon) => after_colon.trim_start(),
        None => trimmed,
    }
}

/// `^(https?:\/\/|https?:)[\w.-]+(:\d+)?$` case-insensitively: an http(s)
/// scheme (the `https:` shorthand allowed), a non-empty host of `[\w.-]`
/// bytes, and an optional trailing `:<digits>` port.
fn is_valid_origin(token: &str) -> bool {
    let lower = token.to_ascii_lowercase();
    let rest = lower
        .strip_prefix("https://")
        .or_else(|| lower.strip_prefix("http://"))
        .or_else(|| lower.strip_prefix("https:"))
        .or_else(|| lower.strip_prefix("http:"));
    let Some(rest) = rest else { return false };
    let host = match rest.rsplit_once(':') {
        Some((host, port)) => {
            if port.is_empty() || !port.bytes().all(|b| b.is_ascii_digit()) {
                return false;
            }
            host
        }
        None => rest,
    };
    !host.is_empty()
        && host
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'.' || b == b'-')
}

fn format_allowlist(tokens: &[String]) -> String {
    if tokens.len() == 1 && tokens[0] == "*" {
        return "*".to_string();
    }
    format!("({})", tokens.join(" "))
}

/// Assemble a Permissions-Policy header value from a feature map.
pub fn build_permissions_policy(features: &FeatureMap) -> String {
    features
        .iter()
        .map(|(name, tokens)| format!("{}={}", name, format_allowlist(tokens)))
        .collect::<Vec<_>>()
        .join(", ")
}

/// Parse a Permissions-Policy header value back into a feature map. Accepts
/// an optional `Permissions-Policy:` prefix; returns `None` when the syntax
/// is malformed (bad directive, missing allowlist, bad token).
pub fn parse_permissions_policy(header: &str) -> Option<FeatureMap> {
    let cleaned = strip_header_name(header);
    if cleaned.is_empty() {
        return None;
    }
    let mut map = FeatureMap::new();
    for raw_directive in cleaned.split(',') {
        let directive = raw_directive.trim();
        if directive.is_empty() {
            return None;
        }
        let eq = directive.find('=')?;
        if eq == 0 {
            return None;
        }
        let name = directive[..eq].trim();
        let value = directive[eq + 1..].trim();
        if !is_valid_feature_name(name) {
            return None;
        }
        if value == "*" || value == "self" {
            map.insert(name.to_string(), vec![value.to_string()]);
            continue;
        }
        if !(value.starts_with('(') && value.ends_with(')')) {
            return None;
        }
        let inner = value[1..value.len() - 1].trim();
        if inner.is_empty() {
            map.insert(name.to_string(), Vec::new()); // () = disabled
            continue;
        }
        let mut tokens = Vec::new();
        for raw in inner.split_whitespace() {
            let token = unquote(raw);
            if token != "self" && token != "*" && !is_valid_origin(token) {
                return None;
            }
            tokens.push(token.to_string());
        }
        map.insert(name.to_string(), tokens);
    }
    Some(map)
}

/// Syntax-check a header the same way `parse_permissions_policy` does, with
/// one message per bad directive instead of failing at the first one.
pub fn validate_header_syntax(header: &str) -> (bool, Vec<String>) {
    let mut errors = Vec::new();
    let cleaned = strip_header_name(header);
    if cleaned.is_empty() {
        return (false, vec!["Header is empty.".to_string()]);
    }
    for (i, raw_directive) in cleaned.split(',').enumerate() {
        let directive = raw_directive.trim();
        let where_ = format!("Directive {}", i + 1);
        if directive.is_empty() {
            errors.push(format!("{}: empty (stray comma?).", where_));
            continue;
        }
        let bad_eq = format!("{}: expected `feature=allowlist`, got `{}`.", where_, directive);
        let Some(eq) = directive.find('=') else {
            errors.push(bad_eq);
            continue;
        };
        if eq == 0 {
            errors.push(bad_eq);
            continue;
        }
        let name = directive[..eq].trim();
        let value = directive[eq + 1..].trim();
        if !is_valid_feature_name(name) {
            errors.push(format!("{}: `{}` is not a valid feature name.", where_, name));
            continue;
        }
        if value == "*" || value == "self" {
            continue;
        }
        if !(value.starts_with('(') && value.ends_with(')')) {
            errors.push(format!(
                "{}: `{}` allowlist must be `*`, `self`, or `(...)` — got `{}`.",
                where_, name, value
            ));
            continue;
        }
        let inner = value[1..value.len() - 1].trim();
        if inner.is_empty() {
            continue; // () = disabled, valid
        }
        for raw in inner.split_whitespace() {
            let token = unquote(raw);
            if token != "self" && token != "*" && !is_valid_origin(token) {
                errors.push(format!(
                    "{}: `{}` has an invalid allowlist token `{}`.",
                    where_, name, raw
                ));
            }
        }
    }
    (errors.is_empty(), errors)
}

/// Privacy score 0-100, weighted by impact (high 3, medium 2, low 1).
/// Disabled `()` earns the full weight, `self`/origins half, `*` or absent
/// none. `floor(x + 0.5)` reproduces the lib's `Math.round`.
pub fn privacy_score(features: &FeatureMap) -> u32 {
    let mut earned = 0.0_f64;
    let mut possible = 0.0_f64;
    for &(name, weight) in FEATURE_WEIGHTS {
        possible += f64::from(weight);
        if let Some(allowlist) = features.get(name) {
            if allowlist.is_empty() {
                earned += f64::from(weight); // () disabled
            } else if !(allowlist.len() == 1 && allowlist[0] == "*") {
                earned += f64::from(weight) / 2.0; // self / origins
            }
        }
    }
    (earned / possible * 100.0 + 0.5).floor() as u32
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →