Skip to content

feat(web_core): add URL security policy and plumb it to components and functions - #4104

Draft
nan-yu wants to merge 10 commits into
feat/url-security-specfrom
feat/url-security-web-core
Draft

nan-yu wants to merge 10 commits into
feat/url-security-specfrom
feat/url-security-web-core

Conversation

@nan-yu

@nan-yu nan-yu commented Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Implements the URL security policy from #4045 in @a2ui/web_core. A host sets one policy on the MessageProcessor, and component and function code reaches it through the context objects they already receive, so no existing signature changes. This is the first SDK implementation, so it's the place to review the API before the Python, Dart and Swift versions copy its shape.

Stacked on #4102, which adds the proposal and the shared conformance suite this PR runs.

Reviewer focus

  1. The public API below: names, the one-policy-per-processor setup, and sanitizeUrl on the contexts.
  2. GenericBinder: how x-a2ui-url-context marks travel through unions, intersections, nullable schemas, lists and records, and that every resolved value of a marked prop is checked once (generic-binder.ts).
  3. The baseline host rules in url_security_policy.ts, which keep URL parsers from disagreeing about a host.

Changes

  1. Host setup, once. MessageProcessorOptions gains urlSecurityPolicy and openUrlHandler. The processor passes both to every surface it creates (SurfaceModelOptions), where they are read-only. Leaving them unset keeps the permissive default.

    const processor = new MessageProcessor([basicCatalog, myCatalog], onAction, {
      urlSecurityPolicy: new AllowlistUrlSecurityPolicy({
        media: ['cdn.example.com'],
        navigation: ['*.example.com'],
        rewrite: {media: url => 'https://proxy.example.com/?u=' + encodeURIComponent(url)},
      }),
      openUrlHandler: url => confirmAndOpen(url),
    });
  2. Most components need no code. A catalog marks a URL prop with mediaUrl(), navigationUrl() or iframeUrl(). GenericBinder (and so NodeResolver) passes every resolved value through the policy, including data-bound, formatString, nested, list item and record values, and checks it again when it changes. The component gets the allowed or rewritten URL, or undefined if blocked, and the prop is typed string | undefined. A list bound to a marked prop is checked item by item.

    schema: z.object({
      title: DynamicStringSchema,
      imageUrl: mediaUrl('Product photo.'),
      productPageUrl: navigationUrl('Opened on tap.'),
    });

    Catalog.toJson() writes the mark as "x-a2ui-url-context" next to the property's $ref, and Catalog.fromJson() reads it back. fromJson() throws A2uiCatalogError for an unknown value, or for a mark under additionalProperties, unevaluatedProperties or patternProperties, which the resolver can't find by name.

  3. One call for URLs code builds itself. sanitizeUrl(url, context, info?) on ComponentContext, DataContext and SurfaceModel. The context fills in the surface, catalog and component details. A value that isn't a string resolves to undefined without a warning.

    const src = context.sanitizeUrl(`${props.base}/tile.png`, 'media');
  4. openUrl. The policy runs first. A blocked URL fails with URL_BLOCKED (A2uiUrlBlockedError, reported once as a surface error) and never reaches the handler or window.open. An allowed URL is resolved against globalThis.location when it exists, then goes to openUrlHandler if one is set, otherwise to window.open. The requiresUserActivation rule is unchanged.

  5. Policies. PermissiveUrlSecurityPolicy (the default) and AllowlistUrlSecurityPolicy: per-context ASCII host lists with *. subdomain wildcards, port-exact entries and IPv6 entries matched in any form, relative URL opt-in, rewrite hooks (whose output runs through the baseline again), allowSvgDataUrls, and a urlProperties map for catalogs the host can't edit. An entry that could never match (a URL, a path, userinfo, a percent-escape, non-ASCII, .example.com, 127.1, *.10.0.0.1, a bad port) throws a TypeError. Every policy runs the shared baseline before and after it, so a custom policy can't allow javascript:.

  6. Helpers for code outside a surface. applyUrlSecurityPolicy, redactUrl, urlContextOf, URL_CONTEXTS and BASIC_CATALOG_URL_PROPERTIES, for agent-side payload checks and for renderers that resolve props without GenericBinder. MarkdownRendererOptions.sanitizeUrl lets a markdown renderer check link and image URLs; the universal Text element fills it in.

  7. Reporting. A blocked URL emits one URL_BLOCKED warning on SurfaceModel.onWarning with context, the source (componentId, propertyName or functionName) and redactedUrl. The redacted form follows the proposal's "Reporting blocked URLs" rule (scheme and normalized host for an http(s) URL whose host passes the baseline, a data: media type, or the scheme alone), never the full URL. Reports are remembered per surface (256 entries, oldest forgotten first).

  8. Basic catalogs. Image.url, Video.url, Video.posterUrl, AudioPlayer.url and the basic theme's iconUrl are checked as media. The marks are on the code-defined Zod schemas, so they follow the components into catalogs with other IDs, and a built-in list covers the basic catalogs loaded from JSON. The published catalog documents are unchanged. A blocked theme iconUrl is removed and a rewritten one replaces it.

Impact & risks

  1. Breaking: the shared baseline is stricter than sanitizeMediaUrl was:

    1. URLs with a space, control character or backslash anywhere are blocked instead of trimmed.
    2. data:image/svg+xml and non-media data: URLs are blocked.
    3. http(s) URLs without // and a host are blocked.
    4. Hosts that end in a number but aren't dotted-decimal IPv4 (127.1, 0x7f.0.0.1), and non-ASCII hosts (also percent-encoded), are blocked.
    5. openUrl reports URL_BLOCKED instead of Unsupported URL scheme.

    The CHANGELOG has the migration notes.

  2. Breaking: Catalog.fromJson() rejects URL marks it couldn't apply (see Changes, item 2).

  3. sanitizeMediaUrl is deprecated and now runs the baseline. The universal Image, Video and AudioPlayer elements use the already-checked resolved values and run the baseline on them again, for catalogs whose schemas don't mark them.

  4. Cost: an allowlist check parses the URL a few times. Binding 5,000 marked list items with an allowlist and a rewrite takes about 145 ms against 72 ms without a policy, measured locally.

Not covered here:

  1. urlProperties overrides apply to top-level component props only.
  2. v0.8: the Lit 0.8 renderer still calls the deprecated sanitizeMediaUrl.
  3. Angular and React components, @a2ui/markdown-it, MCP app CSP and Vega-Lite are in the PRs stacked on this one, all part of core: configurable URL security policy and domain allowlists across SDKs to mitigate data exfiltration #4045.

Testing

  1. node scripts/copy-spec.js && npx tsc -p typescript/core/web_core builds cleanly, and every built test file passes, including 172 tests in url_security_policy.test.ts, url_schema.test.ts and url_resolution.test.ts, plus DOM tests for Image (an allowlisted, rewritten, then blocked bound URL) and Text (markdown link checks).
  2. node typescript/core/web_core/tests/conformance/conformance_test.mjs passes, including every case of core/url_security_policy.yaml from feat(conformance): add URL security policy proposal and shared conformance suite #4102 (actions url_policy_check, url_policy_resolution, url_policy_entries and url_redact; the runner is tests/conformance/url-security-policy.ts).
  3. eslint reports no errors, and prettier is clean on changed files.

Part of #4045.

🤖 Agent-generated

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a comprehensive URL security policy framework to validate, sanitize, and optionally rewrite URLs loaded, opened, or embedded by components and functions. It includes permissive and allowlist policies, integrates baseline checks across the core message processing and resolution pipeline, and updates basic components and functions to enforce these policies. The review feedback highlights several improvement opportunities: safely handling undefined descriptions in schema helpers to prevent runtime crashes, allowing rewritten URLs for theme icons rather than dropping them, implementing FIFO eviction for the blocked URL warning cache to avoid duplicate warning floods, and utilizing afterEach hooks in tests to clean up global state instead of try-finally blocks.

Comment on lines +155 to +161
(schema as {describe: (description: string) => z.ZodTypeAny}).describe = description =>
keepRefOnDescribe(
rawDescribe.call(
schema,
description.startsWith('REF:') ? description : `REF:${ref}|${description}`,
),
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

If describe is called with undefined (or if result.description is undefined when cloning), description.startsWith will throw a TypeError at runtime. We should handle undefined descriptions safely to prevent potential crashes.

  (schema as {describe: (description?: string) => z.ZodTypeAny}).describe = description =>
    keepRefOnDescribe(
      rawDescribe.call(
        schema,
        description === undefined
          ? undefined
          : description.startsWith('REF:')
            ? description
            : 'REF:' + ref + '|' + description,
      ),
    );

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in dfb824e. The describe override now handles an undefined description by keeping just the REF: pointer, so the catalog document still writes the $ref. Added a test in url_schema.test.ts.

🤖 Agent-generated

Comment on lines +1074 to +1076
// The theme is applied as given, so an allowed but rewritten URL can't be
// used; it is dropped like a blocked one.
return allowed === iconUrl ? undefined : iconUrl;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Dropping rewritten URLs completely for the theme's iconUrl means that if a host configures a rewriting policy (such as a media proxy), the theme icon will be silently removed even though the policy technically allowed it. Consider allowing rewritten URLs to be applied to the theme rather than dropping them.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in dfb824e. A rewritten theme iconUrl (for example, through a media proxy) now replaces the original in the surface theme, and only a blocked one is removed and reported. Added a test and updated the CHANGELOG entry.

🤖 Agent-generated

Comment on lines +894 to +896
if (this.reportedBlockedUrls.size >= MAX_REPORTED_BLOCKED_URLS) {
this.reportedBlockedUrls.clear();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Clearing the entire reportedBlockedUrls set when it reaches the limit can lead to a sudden flood of duplicate warnings if the limit is exceeded. Since JavaScript Set preserves insertion order, we can implement a simple FIFO eviction by deleting the oldest entry instead of clearing the entire set.

    if (this.reportedBlockedUrls.size >= MAX_REPORTED_BLOCKED_URLS) {
      const oldest = this.reportedBlockedUrls.values().next().value;
      if (oldest !== undefined) {
        this.reportedBlockedUrls.delete(oldest);
      }
    }

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in dfb824e. When the memory is full, the surface now forgets only the oldest reported URL (a Set iterates in insertion order). Added a test showing the second URL is still remembered after the first one is evicted.

🤖 Agent-generated

Comment on lines +626 to +634
try {
g.location = {href: 'https://host.example/app/page'};
executeOpenUrl('../help?x=1', ctx);
executeOpenUrl('mailto:help@example.com', ctx);
g.location = undefined;
executeOpenUrl('/help', ctx);
} finally {
g.location = original;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Instead of wrapping individual test assertions or operations in try...finally blocks to restore global state like globalThis.location, use an afterEach hook to clean up and reset global state. This guarantees cleanup even if assertions fail and prevents test pollution, adhering to the repository's best practices.

References
  1. Use an afterEach hook to clean up the DOM (e.g., clearing document.body.innerHTML) and reset global state (like document.adoptedStyleSheets) after each test, rather than wrapping individual test assertions in try...finally blocks. This guarantees cleanup even if assertions fail and prevents test pollution.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in dfb824e. The test now lives in a nested describe that restores globalThis.location in an afterEach hook.

🤖 Agent-generated

…4045)

Adds a URL security policy to @a2ui/web_core: a UrlSecurityPolicy
contract, a built-in baseline that runs before and after every policy,
PermissiveUrlSecurityPolicy (the default) and AllowlistUrlSecurityPolicy
(per-context host lists, subdomain wildcards, port-exact entries,
relative URL opt-in, rewrite hooks, and a urlProperties map for catalogs
the host can't edit).

1. Hosts set the policy and an optional openUrlHandler once in
   MessageProcessorOptions. The processor passes both to every surface it
   creates through the SurfaceModelOptions constructor argument, so code
   holding a surface can't swap the policy. ComponentContext, DataContext
   and SurfaceModel gain sanitizeUrl(url, context, info?).
2. Catalog authors mark URL props with mediaUrl(), navigationUrl() and
   iframeUrl(). Catalog.toJson() writes "x-a2ui-url-context",
   Catalog.fromJson() reads it back, and GenericBinder passes every
   resolved value of a marked prop (data-bound, formatString, nested)
   through the policy. A blocked value resolves to undefined and is
   reported once per surface as a redacted URL_BLOCKED warning. Marked
   props resolve to string | undefined in ResolveA2uiProp.
3. The basic catalogs' Image, Video and AudioPlayer media props and the
   v0.9 theme iconUrl are checked without changing the published catalog
   documents; the generator emits the markUrlContext wrappers.
4. openUrl checks its URL as navigation, resolves relative URLs against
   the page location, reports a blocked URL as URL_BLOCKED, and hands
   allowed URLs to openUrlHandler when set. MarkdownRendererOptions gains
   sanitizeUrl, which the universal Text element fills in.
5. Exports applyUrlSecurityPolicy, redactUrl, urlContextOf and
   BASIC_CATALOG_URL_PROPERTIES; deprecates sanitizeMediaUrl.
6. Runs the url_security_policy conformance suite in the web_core
   harness and claims F-CORE-46 for ts-web-core.

Rebased onto main as one commit (the eight earlier commits of this PR
touched the same files that main rewrote).
…st hosts only (#4045)

1. The baseline blocks an http(s) URL whose host ends in a number unless
   the host is a dotted-decimal IPv4 address, so 127.1, 0x7f.0.0.1,
   0177.0.0.1, 2130706433 and 256.0.0.1 are blocked. The check reads the
   host as written (percent-decoded), not URL.hostname, which rewrites
   these forms.
2. AllowlistUrlSecurityPolicy never matches a host written with non-ASCII
   characters and rejects non-ASCII entries; internationalized names are
   listed in punycode. IPv6 entries match any form of the address.
… check (#4045)

127.0.0.1. is the same address to the URL parser, so it passes like
127.0.0.1, as in the Dart SDK. 127.1. stays blocked.
…nd rewrites (#4045)

1. The baseline blocks an http(s) URL whose host has a non-ASCII character
   after percent-decoding. Browsers map fullwidth digits and dots, the
   ideographic full stop, and soft hyphens to a numeric IPv4 host, which
   got past the dotted-decimal check.
2. AllowlistUrlSecurityPolicy rejects entries that could never match: a
   leading dot, percent escapes, an IP address after '*.', and numeric
   hosts the baseline blocks, such as 127.1.
3. AllowlistUrlSecurityPolicy.sanitizeUrl runs the baseline on what a
   rewrite hook returns, for hosts that call the policy directly.
…e binder can't reach (#4045)

1. GenericBinder keeps a URL mark when behavior trees merge (union and
   oneOf/anyOf variants, intersections, nullable values, records and
   catchalls), reads marks from union branches, pushes a mark on a list
   down to its items, and keeps a marked catchall. Two different contexts
   merge to the stricter one (iframe, then navigation, then media).
2. Catalog.fromJson rejects an x-a2ui-url-context value it doesn't know,
   and one under additionalProperties, unevaluatedProperties or
   patternProperties, whose values the binder can't find by name.
3. The universal Image, Video and AudioPlayer elements run the baseline
   on the resolved URL again, for catalogs whose schemas don't mark it.
4. A host urlProperties entry on a catchall prop keeps its binding.
5. A blocked theme iconUrl asks the policy once, and a blocked openUrl is
   reported once, as the URL_BLOCKED error.
6. v1.0 URL props resolve to string | undefined (not any), the v1_0 and
   v0_9 entry points export the URL policy API, URL_BLOCKED warnings type
   redactedUrl and context, and the report memory keys only the first
   2048 characters of a URL.
…nstead of throwing (#4045)

A custom component that passed a missing optional prop or a number from
the data model to sanitizeUrl crashed while reporting the blocked value.
Also add a DOM test for an allowlisted, rewritten, and blocked Image src.
…es (#4045)

redactUrl now writes the host only for an http(s) URL whose host passes the
baseline, normalized as allowlists compare it (no trailing dot), so every
SDK reports the same redactedUrl. Also export URL_CONTEXTS and say "an
iframe URL" in the warning message.
…d pass (#4045)

Bound marked lists, union context strictness, schema marks over the
built-in list, host urlProperties for undeclared props, nested and $defs
URL marks, rewritten openUrl targets, handler rejections, report dedupe
keys, multi-@ userinfo, and allowlist hosts with a trailing dot.
@nan-yu
nan-yu force-pushed the feat/url-security-web-core branch from 9ea092a to eb519a5 Compare December 3, 2026 19:29

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant