Skip to main content

Module csp

Module csp 

Source
Expand description

§CSP — Declarative Content Security Policy for widgets

This module owns the config types and the merge function that together decide which domains appear in a widget’s CSP when mcpr rewrites an MCP response.

§Model

A widget’s CSP has three independent directive arrays:

  • connectDomains — allowed targets for fetch, WebSocket, EventSource.
  • resourceDomains — allowed sources for scripts, styles, images, fonts, media.
  • frameDomains — allowed sources for nested <iframe> content.

Each directive carries its own DirectivePolicy — a list of domains and a Mode (extend or replace) that decides how to combine declared domains with whatever the upstream MCP server already returned.

A top-level CspConfig holds one policy per directive plus an optional list of WidgetScoped entries. Widget entries match resource URIs with glob patterns (e.g. ui://widget/payment*) and layer on top of the global policy.

§Merge

effective_domains computes the final domain list for one directive, given upstream domains, a resource URI, and the config. The rules are:

  1. If the global directive’s mode is replace, discard upstream entirely; otherwise start from upstream minus localhost and the upstream host itself.
  2. Append the global directive’s declared domains.
  3. For each widget entry whose match glob matches the resource URI, in config order, either extend (append) or replace (overwrite) the working list with the widget’s domains for this directive.
  4. Prepend the proxy URL and dedupe.

Replace semantics are scoped: a global replace only ignores upstream; a widget replace wipes everything accumulated above it.

§Example

[csp.connectDomains]
domains = ["api.example.com"]
mode    = "extend"

[csp.resourceDomains]
domains = ["cdn.example.com"]
mode    = "extend"

[csp.frameDomains]
domains = []
mode    = "replace"

[[csp.widget]]
match              = "ui://widget/payment*"
connectDomains     = ["api.stripe.com"]
connectDomainsMode = "extend"

Structs§

CspConfig
Complete CSP configuration: three global directives plus widget overrides.
DirectivePolicy
A domain list paired with a merge mode.
WidgetScoped
Per-widget override matched by glob on resource URI.

Enums§

Directive
Which of the three CSP directive arrays a policy targets.
Mode
Merge mode for a single CSP directive.

Functions§

effective_domains
Compute the effective domain list for one directive.
glob_match
Minimal glob matcher over bytes. Supports * (any sequence) and ? (single character). Everything else matches literally.