Repository navigation
Conversation
There was a problem hiding this comment.
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.
| (schema as {describe: (description: string) => z.ZodTypeAny}).describe = description => | ||
| keepRefOnDescribe( | ||
| rawDescribe.call( | ||
| schema, | ||
| description.startsWith('REF:') ? description : `REF:${ref}|${description}`, | ||
| ), | ||
| ); |
There was a problem hiding this comment.
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,
),
);There was a problem hiding this comment.
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
| // 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; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
| if (this.reportedBlockedUrls.size >= MAX_REPORTED_BLOCKED_URLS) { | ||
| this.reportedBlockedUrls.clear(); | ||
| } |
There was a problem hiding this comment.
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);
}
}There was a problem hiding this comment.
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
| 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; | ||
| } |
There was a problem hiding this comment.
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
- 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.
There was a problem hiding this comment.
Fixed in dfb824e. The test now lives in a nested describe that restores globalThis.location in an afterEach hook.
🤖 Agent-generated
65d6804 to
2a3a39a
Compare
b813633 to
e38ab5e
Compare
…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.
9ea092a to
eb519a5
Compare
Summary
Implements the URL security policy from #4045 in
@a2ui/web_core. A host sets one policy on theMessageProcessor, 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
sanitizeUrlon the contexts.GenericBinder: howx-a2ui-url-contextmarks travel through unions, intersections, nullable schemas, lists and records, and that every resolved value of a marked prop is checked once (generic-binder.ts).url_security_policy.ts, which keep URL parsers from disagreeing about a host.Changes
Host setup, once.
MessageProcessorOptionsgainsurlSecurityPolicyandopenUrlHandler. The processor passes both to every surface it creates (SurfaceModelOptions), where they are read-only. Leaving them unset keeps the permissive default.Most components need no code. A catalog marks a URL prop with
mediaUrl(),navigationUrl()oriframeUrl().GenericBinder(and soNodeResolver) 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, orundefinedif blocked, and the prop is typedstring | undefined. A list bound to a marked prop is checked item by item.Catalog.toJson()writes the mark as"x-a2ui-url-context"next to the property's$ref, andCatalog.fromJson()reads it back.fromJson()throwsA2uiCatalogErrorfor an unknown value, or for a mark underadditionalProperties,unevaluatedPropertiesorpatternProperties, which the resolver can't find by name.One call for URLs code builds itself.
sanitizeUrl(url, context, info?)onComponentContext,DataContextandSurfaceModel. The context fills in the surface, catalog and component details. A value that isn't a string resolves toundefinedwithout a warning.openUrl. The policy runs first. A blocked URL fails withURL_BLOCKED(A2uiUrlBlockedError, reported once as a surface error) and never reaches the handler orwindow.open. An allowed URL is resolved againstglobalThis.locationwhen it exists, then goes toopenUrlHandlerif one is set, otherwise towindow.open. TherequiresUserActivationrule is unchanged.Policies.
PermissiveUrlSecurityPolicy(the default) andAllowlistUrlSecurityPolicy: 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 aurlPropertiesmap 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 aTypeError. Every policy runs the shared baseline before and after it, so a custom policy can't allowjavascript:.Helpers for code outside a surface.
applyUrlSecurityPolicy,redactUrl,urlContextOf,URL_CONTEXTSandBASIC_CATALOG_URL_PROPERTIES, for agent-side payload checks and for renderers that resolve props withoutGenericBinder.MarkdownRendererOptions.sanitizeUrllets a markdown renderer check link and image URLs; the universalTextelement fills it in.Reporting. A blocked URL emits one
URL_BLOCKEDwarning onSurfaceModel.onWarningwithcontext, the source (componentId,propertyNameorfunctionName) andredactedUrl. The redacted form follows the proposal's "Reporting blocked URLs" rule (scheme and normalized host for anhttp(s)URL whose host passes the baseline, adata:media type, or the scheme alone), never the full URL. Reports are remembered per surface (256 entries, oldest forgotten first).Basic catalogs.
Image.url,Video.url,Video.posterUrl,AudioPlayer.urland the basic theme'siconUrlare checked asmedia. 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 themeiconUrlis removed and a rewritten one replaces it.Impact & risks
Breaking: the shared baseline is stricter than
sanitizeMediaUrlwas:data:image/svg+xmland non-mediadata:URLs are blocked.http(s)URLs without//and a host are blocked.127.1,0x7f.0.0.1), and non-ASCII hosts (also percent-encoded), are blocked.openUrlreportsURL_BLOCKEDinstead ofUnsupported URL scheme.The CHANGELOG has the migration notes.
Breaking:
Catalog.fromJson()rejects URL marks it couldn't apply (see Changes, item 2).sanitizeMediaUrlis deprecated and now runs the baseline. The universalImage,VideoandAudioPlayerelements use the already-checked resolved values and run the baseline on them again, for catalogs whose schemas don't mark them.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:
urlPropertiesoverrides apply to top-level component props only.sanitizeMediaUrl.@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
node scripts/copy-spec.js && npx tsc -p typescript/core/web_corebuilds cleanly, and every built test file passes, including 172 tests inurl_security_policy.test.ts,url_schema.test.tsandurl_resolution.test.ts, plus DOM tests forImage(an allowlisted, rewritten, then blocked bound URL) andText(markdown link checks).node typescript/core/web_core/tests/conformance/conformance_test.mjspasses, including every case ofcore/url_security_policy.yamlfrom feat(conformance): add URL security policy proposal and shared conformance suite #4102 (actionsurl_policy_check,url_policy_resolution,url_policy_entriesandurl_redact; the runner istests/conformance/url-security-policy.ts).Part of #4045.
🤖 Agent-generated