Skip to content

Permissions-Policy Builder — Go source

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

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

// Package permissionspolicy ports src/lib/permissions-policy.ts (dual source:
// the web lib is TypeScript, the CLI lib is Go — kept in lock-step). Pure +
// deterministic, never panics. The table-driven tests in
// permissions_policy_test.go share vectors with
// src/lib/permissions-policy.test.ts so the two implementations are held to
// the same contract.
//
// The Permissions-Policy header is a comma-separated list of directives:
//
//	Permissions-Policy: geolocation=(self), camera=(), microphone=*, usb=(https://a.example)
//
// A policy is modeled as a map of feature -> allowlist tokens:
//
//	{ "geolocation": {"self"}, "camera": {}, "usb": {"https://a.example"} }
//	  - absent key    => feature stays absent from the header (browser default)
//	  - {}            => camera=()        (disabled)
//	  - {"*"}         => microphone=*     (every origin)
//	  - {"self"}      => geolocation=(self)
//	  - {origins...}  => usb=(https://a.example https://b.example)
package permissionspolicy

import (
	"errors"
	"fmt"
	"math"
	"regexp"
	"sort"
	"strings"
)

// PrivacyImpact grades how sensitive a browser feature is, mirroring the
// 'high' | 'medium' | 'low' union in the TS lib.
type PrivacyImpact string

const (
	PrivacyImpactHigh   PrivacyImpact = "high"
	PrivacyImpactMedium PrivacyImpact = "medium"
	PrivacyImpactLow    PrivacyImpact = "low"
)

// FeatureInfo describes one browser feature of the catalog.
type FeatureInfo struct {
	// Name is the directive token used in the header, e.g. `geolocation`.
	Name string
	// Description explains what the feature grants access to.
	Description string
	// PrivacyImpact grades the feature's fingerprinting / surveillance value.
	PrivacyImpact PrivacyImpact
	// DefaultBrowserBehavior says what browsers do when the feature is absent
	// from the policy.
	DefaultBrowserBehavior string
}

// FeatureMap maps a feature name to its allowlist tokens. An absent key means
// "not addressed by the policy"; an empty (non-nil) slice means "disabled"
// (`feature=()`); a single "*" means every origin.
type FeatureMap map[string][]string

// Features is the catalog the privacy score is computed against. Mirrors the
// FEATURES array in src/lib/permissions-policy.ts (same order, same strings).
var Features = []FeatureInfo{
	// --- high privacy impact ---------------------------------------------------
	{Name: "camera", Description: "Access the device camera for photos / video calls.", PrivacyImpact: PrivacyImpactHigh, DefaultBrowserBehavior: "Same-origin only; prompts the user."},
	{Name: "microphone", Description: "Capture audio from the device microphone.", PrivacyImpact: PrivacyImpactHigh, DefaultBrowserBehavior: "Same-origin only; prompts the user."},
	{Name: "geolocation", Description: "Read the precise GPS location of the visitor.", PrivacyImpact: PrivacyImpactHigh, DefaultBrowserBehavior: "Same-origin only; prompts the user."},
	{Name: "display-capture", Description: "Screen / window sharing via getDisplayMedia.", PrivacyImpact: PrivacyImpactHigh, DefaultBrowserBehavior: "Same-origin only; prompts the user."},
	{Name: "idle-detection", Description: "Detects when the user is away from the device — reveals usage patterns.", PrivacyImpact: PrivacyImpactHigh, DefaultBrowserBehavior: "Disabled; prompts the user."},
	{Name: "serial", Description: "Talk to serial devices (Arduinos, POS terminals) over a physical port.", PrivacyImpact: PrivacyImpactHigh, DefaultBrowserBehavior: "Disabled; prompts the user."},
	{Name: "usb", Description: "WebUSB — direct access to connected USB devices.", PrivacyImpact: PrivacyImpactHigh, DefaultBrowserBehavior: "Disabled; prompts the user."},
	{Name: "hid", Description: "Human Interface Devices — raw access to unusual keyboards, gamepads, sensors.", PrivacyImpact: PrivacyImpactHigh, DefaultBrowserBehavior: "Disabled; prompts the user."},
	{Name: "xr-spatial-tracking", Description: "Tracks head / hand position in WebXR sessions.", PrivacyImpact: PrivacyImpactHigh, DefaultBrowserBehavior: "Same-origin only; prompts the user."},
	// --- medium privacy impact -------------------------------------------------
	{Name: "accelerometer", Description: "Device motion sensor — can fingerprint and infer behaviour.", PrivacyImpact: PrivacyImpactMedium, DefaultBrowserBehavior: "Same-origin only."},
	{Name: "ambient-light-sensor", Description: "Reads ambient light level around the device.", PrivacyImpact: PrivacyImpactMedium, DefaultBrowserBehavior: "Same-origin only."},
	{Name: "battery", Description: "Battery Status API — a classic fingerprinting vector.", PrivacyImpact: PrivacyImpactMedium, DefaultBrowserBehavior: "Same-origin only."},
	{Name: "gyroscope", Description: "Device orientation sensor — fingerprinting and behaviour inference.", PrivacyImpact: PrivacyImpactMedium, DefaultBrowserBehavior: "Same-origin only."},
	{Name: "magnetometer", Description: "Compass readings — can leak details of the user's surroundings.", PrivacyImpact: PrivacyImpactMedium, DefaultBrowserBehavior: "Same-origin only."},
	{Name: "keyboard-map", Description: "Reads the physical keyboard layout — a small but real fingerprint.", PrivacyImpact: PrivacyImpactMedium, DefaultBrowserBehavior: "Same-origin only."},
	{Name: "gamepad", Description: "Enumerates connected controllers and their button state.", PrivacyImpact: PrivacyImpactMedium, DefaultBrowserBehavior: "Same-origin only."},
	{Name: "midi", Description: "Web MIDI — access to attached music hardware.", PrivacyImpact: PrivacyImpactMedium, DefaultBrowserBehavior: "Same-origin only; prompts the user."},
	{Name: "payment", Description: "Payment Request API — can expose stored payment handles.", PrivacyImpact: PrivacyImpactMedium, DefaultBrowserBehavior: "Same-origin only."},
	{Name: "publickey-credentials-get", Description: "WebAuthn credential requests.", PrivacyImpact: PrivacyImpactMedium, DefaultBrowserBehavior: "Same-origin only."},
	{Name: "screen-wake-lock", Description: "Keeps the screen awake — drains battery and signals intent.", PrivacyImpact: PrivacyImpactMedium, DefaultBrowserBehavior: "Same-origin only."},
	{Name: "speaker-selection", Description: "Enumerates and switches audio output devices.", PrivacyImpact: PrivacyImpactMedium, DefaultBrowserBehavior: "Same-origin only."},
	{Name: "web-share", Description: "Invokes the OS share sheet with chosen content.", PrivacyImpact: PrivacyImpactMedium, DefaultBrowserBehavior: "Same-origin only."},
	{Name: "encrypted-media", Description: "DRM (EME) — playback identity can be correlated.", PrivacyImpact: PrivacyImpactMedium, DefaultBrowserBehavior: "Same-origin only."},
	{Name: "document-domain", Description: "Let frames relax the same-origin policy via document.domain.", PrivacyImpact: PrivacyImpactMedium, DefaultBrowserBehavior: "Allowed in same-origin pages; deprecated."},
	// --- low privacy impact ----------------------------------------------------
	{Name: "autoplay", Description: "Autoplay media with/without sound — not a data leak, an annoyance knob.", PrivacyImpact: PrivacyImpactLow, DefaultBrowserBehavior: "Muted autoplay allowed; audible blocked."},
	{Name: "cross-origin-isolated", Description: "COOP/COEP isolation for SharedArrayBuffer — hardens the page.", PrivacyImpact: PrivacyImpactLow, DefaultBrowserBehavior: "Not isolated."},
	{Name: "fullscreen", Description: "Element.requestFullscreen().", PrivacyImpact: PrivacyImpactLow, DefaultBrowserBehavior: "Same-origin only."},
	{Name: "navigation-override", Description: "Lets a frame intercept its own top-level navigations.", PrivacyImpact: PrivacyImpactLow, DefaultBrowserBehavior: "Disabled."},
	{Name: "picture-in-picture", Description: "Floating always-on-top video window.", PrivacyImpact: PrivacyImpactLow, DefaultBrowserBehavior: "Same-origin only."},
}

var (
	featureNameRe  = regexp.MustCompile(`^[a-z][a-z0-9-]*$`)
	originRe       = regexp.MustCompile(`(?i)^(https?://|https?:)[\w.-]+(:\d+)?$`)
	headerPrefixRe = regexp.MustCompile(`(?i)^permissions-policy\s*:\s*`)
	quotedTokenRe  = regexp.MustCompile(`^"(.*)"$`)
)

var errEmptyHeader = errors.New("header is empty")

// formatAllowlist renders allowlist tokens as a directive value: a lone `*`
// stays bare, everything else joins space-separated inside parens.
func formatAllowlist(tokens []string) string {
	if len(tokens) == 1 && tokens[0] == "*" {
		return "*"
	}
	return "(" + strings.Join(tokens, " ") + ")"
}

// stripHeaderPrefix trims surrounding whitespace and drops an optional
// `Permissions-Policy:` prefix (case-insensitive), like the TS lib.
func stripHeaderPrefix(header string) string {
	return headerPrefixRe.ReplaceAllString(strings.TrimSpace(header), "")
}

// BuildPermissionsPolicy assembles a Permissions-Policy header value from a
// feature map, directives sorted by feature name. It is the Go twin of
// buildPermissionsPolicy() in src/lib/permissions-policy.ts and must agree
// with it on every shared vector.
func BuildPermissionsPolicy(features FeatureMap) string {
	names := make([]string, 0, len(features))
	for name := range features {
		names = append(names, name)
	}
	sort.Strings(names)
	parts := make([]string, 0, len(names))
	for _, name := range names {
		parts = append(parts, name+"="+formatAllowlist(features[name]))
	}
	return strings.Join(parts, ", ")
}

// ParsePermissionsPolicy parses a Permissions-Policy header value back into a
// feature map. It accepts an optional `Permissions-Policy:` prefix and
// fully-quoted origin tokens. It returns an error when the syntax is
// malformed (bad directive, missing allowlist, bad token). It is the Go twin
// of parsePermissionsPolicy() in src/lib/permissions-policy.ts (which returns
// null on the same inputs).
func ParsePermissionsPolicy(header string) (FeatureMap, error) {
	cleaned := stripHeaderPrefix(header)
	if cleaned == "" {
		return nil, errEmptyHeader
	}
	m := FeatureMap{}
	for _, rawDirective := range strings.Split(cleaned, ",") {
		directive := strings.TrimSpace(rawDirective)
		if directive == "" {
			return nil, fmt.Errorf("empty directive (stray comma?)")
		}
		eq := strings.Index(directive, "=")
		if eq <= 0 {
			return nil, fmt.Errorf("directive %q: expected feature=allowlist", directive)
		}
		name := strings.TrimSpace(directive[:eq])
		value := strings.TrimSpace(directive[eq+1:])
		if !featureNameRe.MatchString(name) {
			return nil, fmt.Errorf("%q is not a valid feature name", name)
		}
		if value == "*" || value == "self" {
			m[name] = []string{value}
			continue
		}
		if !strings.HasPrefix(value, "(") || !strings.HasSuffix(value, ")") {
			return nil, fmt.Errorf("feature %q: allowlist must be `*`, `self`, or `(...)` — got %q", name, value)
		}
		inner := strings.TrimSpace(value[1 : len(value)-1])
		if inner == "" {
			m[name] = []string{} // () = disabled
			continue
		}
		fields := strings.Fields(inner)
		tokens := make([]string, len(fields))
		for i, raw := range fields {
			tokens[i] = quotedTokenRe.ReplaceAllString(raw, "${1}")
		}
		for _, token := range tokens {
			if token != "self" && token != "*" && !originRe.MatchString(token) {
				return nil, fmt.Errorf("feature %q: invalid allowlist token %q", name, token)
			}
		}
		m[name] = tokens
	}
	return m, nil
}

// ValidationResult is the outcome of ValidatePermissionsPolicy.
type ValidationResult struct {
	Valid  bool
	Errors []string
}

// ValidatePermissionsPolicy syntax-checks a header the same way
// ParsePermissionsPolicy does, but collects one message per problem instead of
// stopping at the first. Message texts mirror validatePermissionsPolicy() in
// src/lib/permissions-policy.ts. It is that function's Go twin.
func ValidatePermissionsPolicy(header string) ValidationResult {
	var errs []string
	cleaned := stripHeaderPrefix(header)
	if cleaned == "" {
		return ValidationResult{Valid: false, Errors: []string{"Header is empty."}}
	}
	for i, rawDirective := range strings.Split(cleaned, ",") {
		directive := strings.TrimSpace(rawDirective)
		where := fmt.Sprintf("Directive %d", i+1)
		if directive == "" {
			errs = append(errs, where+": empty (stray comma?).")
			continue
		}
		eq := strings.Index(directive, "=")
		if eq <= 0 {
			errs = append(errs, fmt.Sprintf("%s: expected `feature=allowlist`, got `%s`.", where, directive))
			continue
		}
		name := strings.TrimSpace(directive[:eq])
		value := strings.TrimSpace(directive[eq+1:])
		if !featureNameRe.MatchString(name) {
			errs = append(errs, fmt.Sprintf("%s: `%s` is not a valid feature name.", where, name))
			continue
		}
		if value == "*" || value == "self" {
			continue
		}
		if !strings.HasPrefix(value, "(") || !strings.HasSuffix(value, ")") {
			errs = append(errs, fmt.Sprintf("%s: `%s` allowlist must be `*`, `self`, or `(...)` — got `%s`.", where, name, value))
			continue
		}
		inner := strings.TrimSpace(value[1 : len(value)-1])
		if inner == "" {
			continue // () = disabled, valid
		}
		for _, raw := range strings.Fields(inner) {
			token := quotedTokenRe.ReplaceAllString(raw, "${1}")
			if token != "self" && token != "*" && !originRe.MatchString(token) {
				errs = append(errs, fmt.Sprintf("%s: `%s` has an invalid allowlist token `%s`.", where, name, raw))
			}
		}
	}
	return ValidationResult{Valid: len(errs) == 0, Errors: errs}
}

// PrivacyScore returns a 0-100 privacy score for a policy: how much it locks
// down the catalog. Each feature is weighted by privacy impact (high 3, medium
// 2, low 1). Disabled `()` earns full credit, `self` or an origin list half,
// `*` or "absent from the policy" none (the browser default stays in force).
// It is the Go twin of privacyScore() in src/lib/permissions-policy.ts.
func PrivacyScore(features FeatureMap) int {
	weight := map[PrivacyImpact]float64{
		PrivacyImpactHigh:   3,
		PrivacyImpactMedium: 2,
		PrivacyImpactLow:    1,
	}
	var earned, possible float64
	for _, feature := range Features {
		w := weight[feature.PrivacyImpact]
		possible += w
		allowlist := features[feature.Name]
		if allowlist == nil {
			continue // absent from the policy
		}
		if len(allowlist) == 0 {
			earned += w // () disabled
		} else if !(len(allowlist) == 1 && allowlist[0] == "*") {
			earned += w / 2 // self / origins
		}
	}
	return int(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 →