Skip to content

Permissions-Policy Builder — Python source

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

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

"""permissions-policy — Permissions-Policy header builder / parser.

Language: Python 3 (standard library only).
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 text, so ``re`` plus ``str`` slicing reproduces
the TypeScript logic one-to-one. The 29-entry feature catalog is compressed to
the name -> weight mapping that ``privacy_score`` needs; the descriptive
metadata stays in the TypeScript lib.

display source — part of CosmoDev's polyglot tool pages.
"""

from __future__ import annotations

import math
import re

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

# feature name -> privacy weight, expanded once from the tiers above.
_FEATURE_WEIGHT: dict[str, int] = {
    name: weight for weight, names in _WEIGHT_TIERS.items() for name in names.split(" ")
}

# Same grammars as the lib: feature names are lowercase kebab tokens; origins
# are http(s) URLs (the ``https:`` shorthand allowed) with an optional port.
_FEATURE_NAME_RE = re.compile(r"^[a-z][a-z0-9-]*$")
_ORIGIN_RE = re.compile(r"^(https?://|https?:)[\w.-]+(:\d+)?$", re.IGNORECASE)


def _strip_header_name(header: str) -> str:
    """Trim, then drop an optional ``Permissions-Policy:`` prefix."""
    return re.sub(r"^permissions-policy\s*:\s*", "", header.strip(), count=1, flags=re.IGNORECASE)


def _format_allowlist(tokens: list[str]) -> str:
    if len(tokens) == 1 and tokens[0] == "*":
        return "*"
    return f"({' '.join(tokens)})"


def build_permissions_policy(features: dict[str, list[str]]) -> str:
    """Assemble a Permissions-Policy header value from a feature map."""
    return ", ".join(f"{name}={_format_allowlist(features[name])}" for name in sorted(features))


def parse_permissions_policy(header: str) -> dict[str, list[str]] | None:
    """Parse a header value back into a feature map; ``None`` if malformed.

    Accepts an optional ``Permissions-Policy:`` prefix.
    """
    cleaned = _strip_header_name(header)
    if not cleaned:
        return None
    mapping: dict[str, list[str]] = {}
    for raw_directive in cleaned.split(","):
        directive = raw_directive.strip()
        if not directive:
            return None
        eq = directive.find("=")
        if eq <= 0:
            return None
        name = directive[:eq].strip()
        value = directive[eq + 1:].strip()
        if not _FEATURE_NAME_RE.fullmatch(name):
            return None
        if value in ("*", "self"):
            mapping[name] = [value]
            continue
        if not (value.startswith("(") and value.endswith(")")):
            return None
        inner = value[1:-1].strip()
        if not inner:
            mapping[name] = []  # () = disabled
            continue
        tokens = [re.sub(r'^"(.*)"$', r"\1", t) for t in inner.split()]
        if any(t not in ("self", "*") and not _ORIGIN_RE.fullmatch(t) for t in tokens):
            return None
        mapping[name] = tokens
    return mapping


def validate_header_syntax(header: str) -> tuple[bool, list[str]]:
    """Syntax-check a header, collecting one message per bad directive.

    Returns ``(valid, errors)``; mirrors ``parse_permissions_policy``'s grammar.
    """
    errors: list[str] = []
    cleaned = _strip_header_name(header)
    if not cleaned:
        return False, ["Header is empty."]
    for i, raw_directive in enumerate(cleaned.split(",")):
        directive = raw_directive.strip()
        where = f"Directive {i + 1}"
        if not directive:
            errors.append(f"{where}: empty (stray comma?).")
            continue
        eq = directive.find("=")
        if eq <= 0:
            errors.append(f"{where}: expected `feature=allowlist`, got `{directive}`.")
            continue
        name = directive[:eq].strip()
        value = directive[eq + 1:].strip()
        if not _FEATURE_NAME_RE.fullmatch(name):
            errors.append(f"{where}: `{name}` is not a valid feature name.")
            continue
        if value in ("*", "self"):
            continue
        if not (value.startswith("(") and value.endswith(")")):
            errors.append(f"{where}: `{name}` allowlist must be `*`, `self`, or `(...)` — got `{value}`.")
            continue
        inner = value[1:-1].strip()
        if not inner:
            continue  # () = disabled, valid
        for raw in inner.split():
            token = re.sub(r'^"(.*)"$', r"\1", raw)
            if token not in ("self", "*") and not _ORIGIN_RE.fullmatch(token):
                errors.append(f"{where}: `{name}` has an invalid allowlist token `{raw}`.")
    return not errors, errors


def privacy_score(features: dict[str, list[str]]) -> int:
    """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``.
    """
    earned = 0.0
    possible = 0.0
    for name, weight in _FEATURE_WEIGHT.items():
        possible += weight
        allowlist = features.get(name)
        if allowlist is None:
            continue
        if len(allowlist) == 0:
            earned += weight  # () disabled
        elif not (len(allowlist) == 1 and allowlist[0] == "*"):
            earned += weight / 2  # self / origins
    return math.floor(earned / possible * 100 + 0.5)

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 →