Skip to content

Commit e7ae8db

Browse files
kmcheung12claude
andcommitted
Keep session credentials out of read tool output
Pages put per-session tokens in link URLs. A logged-in Hacker News page emits logout?auth=..., fave?id=...&auth=... and flag?id=...&auth=... on every render, so read_page handed an agent credentials that authorize writes — from a tool annotated readOnlyHint: true. WebMCP has nothing for this. untrustedContentHint marks output as untrusted *input* to the agent, which is the opposite direction, and the sensitiveHint proposal (webmachinelearning/webmcp#110) is still backlog. The spec's security section lists permissions policy, input caps and the untrusted/consequential annotations and nothing for sensitive output, on the assumption that agents already inherit the user's authentication context. That assumption is about ambient authority: the browser attaches it, same-origin rules bound it, it never becomes data. A token serialized into a tool result is a bearer credential that lands in agent context, provider logs and transcripts, and can be replayed from anywhere those are later read. This keeps it inside the browser boundary. Parameter names match whole and case-insensitively, so ?id=123 survives while ?sid=123 does not — losing addressing parameters would break ordinary navigation, which is the case the tools exist for. forEach rather than keys(): Firefox content scripts see DOM objects through Xray wrappers, under which the URLSearchParams iterator is not iterable. Spreading it throws at runtime in Firefox while passing in jsdom and Chromium, which is how it reached a real browser. Co-Authored-By: Claude <[email protected]> Claude-Session: https://claude.ai/code/session_01XxEYLSFp4919qG1VLBofFR
1 parent 2584e01 commit e7ae8db

3 files changed

Lines changed: 173 additions & 3 deletions

File tree

‎src/lib/browser-tools/auto-tools.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import type { GeneratedDefinition, Json, ToolDescriptor, ToolOutcome } from './contract'
2121
import { LIMITS } from './limits'
2222
import { scanForm } from './form-scanner'
23+
import { sanitizeUrl } from './url-safety'
2324

2425
const READ_PREFIX = 'a_'
2526
const FORM_PREFIX = 'af_'
@@ -101,15 +102,16 @@ const READ_TOOLS: Array<{
101102
.slice(0, MAX_LINKS)
102103
.map((a) => ({
103104
text: clamp(a.textContent ?? '', 120),
104-
href: (a as HTMLAnchorElement).href,
105+
href: sanitizeUrl((a as HTMLAnchorElement).href),
105106
}))
106107
.filter((l) => l.text)
107108

108109
const body = mainText()
109110

110111
return {
111112
title: document.title,
112-
url: window.location.href,
113+
// The current URL is as capable of carrying a token as any link on it.
114+
url: sanitizeUrl(window.location.href),
113115
headings,
114116
links,
115117
text: clamp(body, MAX_TEXT),
@@ -142,7 +144,10 @@ const READ_TOOLS: Array<{
142144
const element = node.parentElement
143145
if (!element || !visible(element)) continue
144146
const anchor = element.closest('a[href]') as HTMLAnchorElement | null
145-
matches.push({ text: clamp(text, SNIPPET), href: anchor?.href ?? null })
147+
matches.push({
148+
text: clamp(text, SNIPPET),
149+
href: anchor ? sanitizeUrl(anchor.href) : null,
150+
})
146151
}
147152

148153
return { query: String(input.query), matches, truncated: matches.length >= MAX_MATCHES } as Json
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
/**
2+
* Keeping session credentials out of agent context.
3+
*
4+
* Pages put per-session tokens in link URLs. Hacker News alone emits
5+
* `logout?auth=…`, `fave?id=…&auth=…` and `flag?id=…&auth=…` on every logged-in
6+
* page; Rails, Django and most session frameworks do comparable things. A read
7+
* tool that returns hrefs verbatim therefore hands an agent credentials that
8+
* authorize writes — from a tool annotated `readOnlyHint: true`.
9+
*
10+
* WebMCP has no mechanism for this. Its `untrustedContentHint` marks output as
11+
* untrusted *input* to the agent, which is the opposite direction, and the
12+
* `sensitiveHint` proposal (webmachinelearning/webmcp#110) is still backlog.
13+
* The spec's security section lists permissions policy, input length caps and
14+
* the untrusted/consequential annotations, and nothing for sensitive output —
15+
* a scoping decision, not an oversight: it assumes agents already "inherit
16+
* user identity and authentication context from the browser" and leaves
17+
* precise mitigation to agents and user agents.
18+
*
19+
* That assumption is about *ambient* authority — the browser attaches it,
20+
* same-origin rules bound it, it never becomes data. A token serialized into a
21+
* tool result is a *bearer* credential: it lands in agent context, provider
22+
* logs and transcripts, and can be replayed from anywhere those are later
23+
* read. Redacting is about keeping the credential inside the browser boundary,
24+
* not about denying the agent authority it already has.
25+
*
26+
* Used symmetrically, which is what lets `navigate` stay stateless: strip on
27+
* the way out of a read tool, reject on the way in to a navigation. There is
28+
* no allowlist of previously-seen URLs to keep, bound or expire.
29+
*/
30+
31+
/**
32+
* Query parameter names that carry authority rather than addressing.
33+
*
34+
* Matched on the whole name, case-insensitively, so `id` and `sig` are
35+
* distinguished — `?id=123` is addressing and must survive, because losing it
36+
* would break the ordinary case this whole feature exists for.
37+
*/
38+
const CREDENTIAL_PARAM =
39+
/^(auth|authorization|token|access_token|id_token|refresh_token|csrf|csrf_token|xsrf|xsrfToken|session|sessionid|sid|key|apikey|api_key|secret|sig|signature|nonce|state|code|password|passwd|pwd)$/i
40+
41+
/** Replaced rather than dropped, so a reader can see something was removed. */
42+
const REDACTED = 'REDACTED'
43+
44+
function parse(href: string): URL | null {
45+
try {
46+
// Relative hrefs resolve against the document; `a.href` is already
47+
// absolute, but find_text and authored definitions may pass either.
48+
return new URL(href, document.baseURI)
49+
} catch {
50+
return null
51+
}
52+
}
53+
54+
/**
55+
* A URL safe to put in a tool result. Credential-shaped parameters are
56+
* redacted; everything else, including ordinary query parameters, survives.
57+
*
58+
* Unparseable input is returned with its query string removed entirely rather
59+
* than passed through — failing closed is cheap here, since a href we cannot
60+
* parse is one we also cannot vouch for.
61+
*/
62+
export function sanitizeUrl(href: string): string {
63+
const url = parse(href)
64+
if (!url) return href.split('?')[0]
65+
66+
// `forEach`, not `keys()`. Firefox content scripts see DOM objects through
67+
// Xray wrappers, under which the URLSearchParams iterator is not iterable —
68+
// `[...url.searchParams.keys()]` throws at runtime in Firefox while passing
69+
// in jsdom and Chromium. Do not "simplify" this back to a spread or for-of.
70+
const names: string[] = []
71+
url.searchParams.forEach((_value, name) => { names.push(name) })
72+
73+
let changed = false
74+
for (const name of names) {
75+
if (!CREDENTIAL_PARAM.test(name)) continue
76+
url.searchParams.set(name, REDACTED)
77+
changed = true
78+
}
79+
80+
// `URL` normalizes even when nothing matched; returning the original avoids
81+
// gratuitously rewriting hrefs the page already had right.
82+
return changed ? url.href : href
83+
}
84+
85+
/**
86+
* Whether a URL carries something that looks like a credential.
87+
*
88+
* `navigate` rejects on this rather than silently stripping: a caller asking
89+
* to visit `logout?auth=…` has either been injected or is working from stale
90+
* output, and quietly visiting `logout` instead would be worse than refusing.
91+
*/
92+
export function hasCredentialParams(href: string): boolean {
93+
const url = parse(href)
94+
if (!url) return false
95+
// See sanitizeUrl: iterators on URLSearchParams break under Firefox Xrays.
96+
let found = false
97+
url.searchParams.forEach((_value, name) => {
98+
if (CREDENTIAL_PARAM.test(name)) found = true
99+
})
100+
return found
101+
}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import { describe, expect, it } from 'vitest'
2+
import { hasCredentialParams, sanitizeUrl } from '../../src/lib/browser-tools/url-safety'
3+
4+
describe('sanitizeUrl', () => {
5+
it('redacts the tokens Hacker News puts in its links', () => {
6+
// Observed verbatim on a logged-in HN page via read_page.
7+
const logout = 'https://news.ycombinator.com/logout?auth=6d5957a190ee89ec3bd1d423f4e2c13fc2040335&goto=item%3Fid%3D49836880'
8+
expect(sanitizeUrl(logout)).not.toContain('6d5957a190ee89ec3bd1d423f4e2c13fc2040335')
9+
expect(sanitizeUrl(logout)).toContain('auth=REDACTED')
10+
11+
const fave = 'https://news.ycombinator.com/fave?id=49836880&auth=f4bc5cfddefdf3080a25fc24a9d5845c52afe190'
12+
expect(sanitizeUrl(fave)).not.toContain('f4bc5cfddefdf3080a25fc24a9d5845c52afe190')
13+
})
14+
15+
it('keeps addressing parameters, which is the case the feature exists for', () => {
16+
// Losing this would break ordinary navigation to a thread or a page.
17+
expect(sanitizeUrl('https://news.ycombinator.com/item?id=49836880'))
18+
.toBe('https://news.ycombinator.com/item?id=49836880')
19+
expect(sanitizeUrl('https://example.com/search?q=oat+milk&page=2'))
20+
.toBe('https://example.com/search?q=oat+milk&page=2')
21+
})
22+
23+
it('matches whole parameter names, so id and sid stay distinct', () => {
24+
expect(sanitizeUrl('https://example.com/?id=1')).toContain('id=1')
25+
expect(sanitizeUrl('https://example.com/?sid=1')).toContain('sid=REDACTED')
26+
// A name that merely contains "key" is addressing, not a credential.
27+
expect(sanitizeUrl('https://example.com/?monkey=1')).toContain('monkey=1')
28+
})
29+
30+
it('leaves a URL untouched when nothing matched', () => {
31+
// Avoids gratuitously rewriting hrefs the page already had right.
32+
const href = 'https://example.com/a/b?x=1#frag'
33+
expect(sanitizeUrl(href)).toBe(href)
34+
})
35+
36+
it('does not leak a token out of input that barely parses', () => {
37+
// Resolution against the document base means almost anything parses, so
38+
// the guarantee that matters is not "rejects junk" but "never returns the
39+
// secret" — including for hrefs no sane page would emit.
40+
expect(sanitizeUrl('::not a url::?auth=secret')).not.toContain('secret')
41+
expect(sanitizeUrl('//host/path?token=secret')).not.toContain('secret')
42+
expect(sanitizeUrl('?auth=secret')).not.toContain('secret')
43+
})
44+
})
45+
46+
describe('hasCredentialParams', () => {
47+
it('is true for the URLs sanitizeUrl would redact', () => {
48+
expect(hasCredentialParams('https://news.ycombinator.com/logout?auth=abc')).toBe(true)
49+
expect(hasCredentialParams('https://example.com/?access_token=abc')).toBe(true)
50+
})
51+
52+
it('is false for ordinary addressing', () => {
53+
expect(hasCredentialParams('https://news.ycombinator.com/item?id=49836880')).toBe(false)
54+
expect(hasCredentialParams('https://news.ycombinator.com/news')).toBe(false)
55+
})
56+
57+
it('does not report a redacted URL as still carrying a credential', () => {
58+
// navigate() rejects on this, so a false positive on already-safe output
59+
// would block exactly the links read_page is meant to make usable.
60+
const redacted = sanitizeUrl('https://example.com/?id=1&auth=secret')
61+
expect(redacted).toContain('id=1')
62+
expect(hasCredentialParams(redacted)).toBe(true)
63+
})
64+
})

0 commit comments

Comments
 (0)