Permissions-Policy Builder — JavaScript source
Build a Permissions-Policy header interactively. Control which browser features (camera, microphone, geolocation, etc.) your site can use.
This is the JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.
/**
* permissions-policy - Permissions-Policy header builder / parser.
*
* Language: JavaScript (ES module; runs in browsers, Node >= 16, Bun, Deno).
* CosmoDev polyglot showcase port of the `permissions-policy` tool.
* Ported from src/lib/permissions-policy.ts (the canonical TypeScript implementation).
*
* Why this file exists: the Permissions-Policy grammar is plain text - no
* platform APIs involved - so the port transcribes the lib one-to-one. Only
* the 29-entry feature catalog is compressed to the name -> weight pairs that
* privacyScore() needs; the descriptive metadata stays in the TypeScript lib.
*
* display source - part of CosmoDev's polyglot tool pages.
*/
// Privacy weight per impact tier: high 3, medium 2, low 1.
const WEIGHT_TIERS = {
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. */
const FEATURE_WEIGHT = {};
for (const [weight, names] of Object.entries(WEIGHT_TIERS)) {
for (const name of names.split(' ')) FEATURE_WEIGHT[name] = Number(weight);
}
// 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 FEATURE_NAME_RE = /^[a-z][a-z0-9-]*$/;
const ORIGIN_RE = /^(https?:\/\/|https?:)[\w.-]+(:\d+)?$/i;
function formatAllowlist(tokens) {
if (tokens.length === 1 && tokens[0] === '*') return '*';
return `(${tokens.join(' ')})`;
}
/** Assemble a Permissions-Policy header value from a feature map. */
export function buildPermissionsPolicy(features) {
return Object.keys(features)
.sort()
.map((name) => `${name}=${formatAllowlist(features[name])}`)
.join(', ');
}
/**
* 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).
*/
export function parsePermissionsPolicy(header) {
const cleaned = header.trim().replace(/^permissions-policy\s*:\s*/i, '');
if (!cleaned) return null;
const map = {};
for (const rawDirective of cleaned.split(',')) {
const directive = rawDirective.trim();
if (!directive) return null;
const eq = directive.indexOf('=');
if (eq <= 0) return null;
const name = directive.slice(0, eq).trim();
const value = directive.slice(eq + 1).trim();
if (!FEATURE_NAME_RE.test(name)) return null;
if (value === '*' || value === 'self') { map[name] = [value]; continue; }
if (!value.startsWith('(') || !value.endsWith(')')) return null;
const inner = value.slice(1, -1).trim();
if (!inner) { map[name] = []; continue; } // () = disabled
const tokens = inner.split(/\s+/).map((t) => t.replace(/^"(.*)"$/, '$1'));
for (const token of tokens) {
if (token !== 'self' && token !== '*' && !ORIGIN_RE.test(token)) return null;
}
map[name] = tokens;
}
return map;
}
/**
* Syntax-check a header the same way parsePermissionsPolicy does, but with
* one message per bad directive instead of failing at the first one.
*/
export function validateHeaderSyntax(header) {
const errors = [];
const cleaned = header.trim().replace(/^permissions-policy\s*:\s*/i, '');
if (!cleaned) return { valid: false, errors: ['Header is empty.'] };
cleaned.split(',').forEach((rawDirective, i) => {
const directive = rawDirective.trim();
const where = `Directive ${i + 1}`;
if (!directive) return void errors.push(`${where}: empty (stray comma?).`);
const eq = directive.indexOf('=');
if (eq <= 0) return void errors.push(`${where}: expected \`feature=allowlist\`, got \`${directive}\`.`);
const name = directive.slice(0, eq).trim();
const value = directive.slice(eq + 1).trim();
if (!FEATURE_NAME_RE.test(name)) return void errors.push(`${where}: \`${name}\` is not a valid feature name.`);
if (value === '*' || value === 'self') return;
if (!value.startsWith('(') || !value.endsWith(')')) {
errors.push(`${where}: \`${name}\` allowlist must be \`*\`, \`self\`, or \`(...)\` - got \`${value}\`.`);
return;
}
const inner = value.slice(1, -1).trim();
if (!inner) return; // () = disabled, valid
for (const raw of inner.split(/\s+/)) {
const token = raw.replace(/^"(.*)"$/, '$1');
if (token !== 'self' && token !== '*' && !ORIGIN_RE.test(token)) {
errors.push(`${where}: \`${name}\` has an invalid allowlist token \`${raw}\`.`);
}
}
});
return { valid: errors.length === 0, errors };
}
/**
* Privacy score 0-100 for a policy: disabled `()` earns a feature's full
* weight, `self`/origins half, `*` or absent none. Math.round matches the lib.
*/
export function privacyScore(features) {
let earned = 0;
let possible = 0;
for (const [name, weight] of Object.entries(FEATURE_WEIGHT)) {
possible += weight;
const allowlist = features[name];
if (allowlist && allowlist.length === 0) earned += weight; // () disabled
else if (allowlist && !(allowlist.length === 1 && allowlist[0] === '*')) earned += weight / 2; // self / origins
}
return Math.round((earned / possible) * 100);
}
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 →