Skip to content

Permissions-Policy Builder — PHP source

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

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

<?php
/**
 * permissions-policy — Permissions-Policy header builder / parser.
 *
 * Language: PHP 7.4+ (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 preg_* plus substr/trim reproduce the
 * TypeScript logic one-to-one. The 29-entry feature catalog is compressed to
 * the name => weight pairs privacy_score() needs; descriptive metadata stays
 * in the TypeScript lib. Malformed headers parse to null, like the original.
 *
 * display source — part of CosmoDev's polyglot tool pages.
 */

declare(strict_types=1);

/** Privacy weight per impact tier: high 3, medium 2, low 1. */
const PP_FEATURE_WEIGHTS = [
    '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,
];

// Same grammars as the lib: feature names are lowercase kebab tokens; origins
// are http(s) URLs (the `https:` shorthand allowed) with an optional port.
const PP_FEATURE_NAME_RE = '/^[a-z][a-z0-9-]*$/';
const PP_ORIGIN_RE = '/^(https?:\/\/|https?:)[\w.-]+(:\d+)?$/i';

/** Trim, then drop an optional `Permissions-Policy:` prefix. */
function pp_strip_header_name(string $header): string
{
    $cleaned = trim($header);

    return (string) preg_replace('/^permissions-policy\s*:\s*/i', '', $cleaned, 1);
}

/** Strip one layer of matching double quotes, like the lib's `^"(.*)"$` sub. */
function pp_unquote(string $token): string
{
    if (strlen($token) >= 2 && $token[0] === '"' && substr($token, -1) === '"') {
        return substr($token, 1, -1);
    }

    return $token;
}

function pp_format_allowlist(array $tokens): string
{
    if (count($tokens) === 1 && $tokens[0] === '*') {
        return '*';
    }

    return '(' . implode(' ', $tokens) . ')';
}

/** Assemble a Permissions-Policy header value from a feature map. */
function pp_build_permissions_policy(array $features): string
{
    $names = array_keys($features);
    sort($names, SORT_STRING);
    $parts = [];
    foreach ($names as $name) {
        $parts[] = $name . '=' . pp_format_allowlist($features[$name]);
    }

    return implode(', ', $parts);
}

/**
 * Parse a Permissions-Policy header value back into a feature map. Accepts
 * an optional `Permissions-Policy:` prefix; returns null when the syntax is
 * malformed (bad directive, missing allowlist, bad token).
 *
 * @return array<string, list<string>>|null
 */
function pp_parse_permissions_policy(string $header): ?array
{
    $cleaned = pp_strip_header_name($header);
    if ($cleaned === '') {
        return null;
    }
    $map = [];
    foreach (explode(',', $cleaned) as $raw_directive) {
        $directive = trim($raw_directive);
        if ($directive === '') {
            return null;
        }
        $eq = strpos($directive, '=');
        if ($eq === false || $eq <= 0) {
            return null;
        }
        $name = trim(substr($directive, 0, $eq));
        $value = trim(substr($directive, $eq + 1));
        if (preg_match(PP_FEATURE_NAME_RE, $name) !== 1) {
            return null;
        }
        if ($value === '*' || $value === 'self') {
            $map[$name] = [$value];
            continue;
        }
        if (!(substr($value, 0, 1) === '(' && substr($value, -1) === ')')) {
            return null;
        }
        $inner = trim(substr($value, 1, -1));
        if ($inner === '') {
            $map[$name] = []; // () = disabled
            continue;
        }
        $tokens = [];
        foreach (preg_split('/\s+/', $inner) as $raw) {
            $token = pp_unquote($raw);
            if ($token !== 'self' && $token !== '*' && preg_match(PP_ORIGIN_RE, $token) !== 1) {
                return null;
            }
            $tokens[] = $token;
        }
        $map[$name] = $tokens;
    }

    return $map;
}

/**
 * Syntax-check a header the same way pp_parse_permissions_policy does, with
 * one message per bad directive instead of failing at the first one.
 *
 * @return array{valid: bool, errors: list<string>}
 */
function pp_validate_header_syntax(string $header): array
{
    $errors = [];
    $cleaned = pp_strip_header_name($header);
    if ($cleaned === '') {
        return ['valid' => false, 'errors' => ['Header is empty.']];
    }
    foreach (explode(',', $cleaned) as $i => $raw_directive) {
        $directive = trim($raw_directive);
        $where = 'Directive ' . ($i + 1);
        if ($directive === '') {
            $errors[] = "{$where}: empty (stray comma?).";
            continue;
        }
        $eq = strpos($directive, '=');
        if ($eq === false || $eq <= 0) {
            $errors[] = "{$where}: expected `feature=allowlist`, got `{$directive}`.";
            continue;
        }
        $name = trim(substr($directive, 0, $eq));
        $value = trim(substr($directive, $eq + 1));
        if (preg_match(PP_FEATURE_NAME_RE, $name) !== 1) {
            $errors[] = "{$where}: `{$name}` is not a valid feature name.";
            continue;
        }
        if ($value === '*' || $value === 'self') {
            continue;
        }
        if (!(substr($value, 0, 1) === '(' && substr($value, -1) === ')')) {
            $errors[] = "{$where}: `{$name}` allowlist must be `*`, `self`, or `(...)` — got `{$value}`.";
            continue;
        }
        $inner = trim(substr($value, 1, -1));
        if ($inner === '') {
            continue; // () = disabled, valid
        }
        foreach (preg_split('/\s+/', $inner) as $raw) {
            $token = pp_unquote($raw);
            if ($token !== 'self' && $token !== '*' && preg_match(PP_ORIGIN_RE, $token) !== 1) {
                $errors[] = "{$where}: `{$name}` has an invalid allowlist token `{$raw}`.";
            }
        }
    }

    return ['valid' => count($errors) === 0, 'errors' => $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.
 */
function pp_privacy_score(array $features): int
{
    $earned = 0.0;
    $possible = 0.0;
    foreach (PP_FEATURE_WEIGHTS as $name => $weight) {
        $possible += $weight;
        if (!array_key_exists($name, $features) || !is_array($features[$name])) {
            continue;
        }
        $allowlist = $features[$name];
        if (count($allowlist) === 0) {
            $earned += $weight; // () disabled
        } elseif (!(count($allowlist) === 1 && $allowlist[0] === '*')) {
            $earned += $weight / 2; // self / origins
        }
    }

    return (int) 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 →