Skip to content

Commit b5394cf

Browse files
authored
fix(client): escape a friend's avatar URL in the mentions stylesheet (#2648)
Written-by: Dev Fixes #2646 Owner: Dev Reviewer: Reviewer ## What `mentionCss` pasted `look.image` into `url("…")` in the page-wide mentions stylesheet, and the three entry points only rejected whitespace and `<>` — so a friend's Bot could close the `url()` and the rule and add CSS of its own (`body{…}`): page-wide overlays for UI spoofing, and a peer-chosen fetch from the operator's window. - `core/src/shared/look-image.js` (new): `safeLookImage()` keeps a plain `https?://` URL or a `data:image/(png|jpeg|webp|gif);base64,` string and answers `null` for `"`, `'`, `(`, `)`, `\`, whitespace, `<>` and control characters; `cssImageUrl()` writes the kept value as `url("…")`, `null` otherwise. - Sink: `core/src/client/mention-style.js` draws the colour/mask look when `cssImageUrl(look.image)` is `null`. - Entries: `core/src/host/hooks.js` `cleanRemoteLook`, `core/src/host/remote-chat.js` `applyPublishedLook` (now exported for the test) and `plugins/social/src/look.js` `lookFromServer` (via `lookImage`) drop a refused image and keep the rest of the look. - `plugins/social/test/look.test.js` holds the plugin predicate and the core one in step; the core copy alone allows a local gif, which `core/src/host/roster.js` stores. - Untouched: the string form's `DATA_IMAGE` branch, the chip `title=` escaping, `lookAvoidingLocals`. ## Red first Reverting the four source files turns both new test files red: ``` # core: SyntaxError: The requested module '../src/host/remote-chat.js' does not provide an export named 'applyPublishedLook' # plugins/social: SyntaxError: The requested module '../src/look.js' does not provide an export named 'lookImage' ``` With only the sink (`mention-style.js`) reverted, the payload case fails on the assertion, and the issue's own reproduction against the old sink prints the injected rule: ``` not ok 1 - a payload image cannot leave url("…") in the page-wide mention stylesheet (#2646) Expected values to be strictly equal: body{ present: true !== false …::before{background:center/cover url("data:image/png;base64,AA");}body{background:url(https://evil.example/beacon)}.z{");…} ``` Restored: 4/4 core cases and 4/4 plugin cases pass. ## Ran at 52f6742 - `node --import ./test/harness-resolve.mjs --test test/mention-style.test.js` → 4 pass - `TZ=UTC npm test` in `plugins/social` → 602 pass; `plugins/tree` 137, `plugins/timeline` 156, `plugins/workflow` 460 - core suite, `--test-concurrency=1` → 3042/3045. The three are this host, not the change: two `check-arch-docs` cases need `git` on `PATH` and an executable `/tmp` (both pass with `PATH=…/tools/git/bin` and `TMPDIR` on a real filesystem), and `usage-fields` spawns `python3`, absent here. - `node core/scripts/build-client.mjs --check`, `node scripts/ds-bot-patches.mjs check`, `… canonical`, `node .github/scripts/changelog.mjs check`, `node scripts/lint-plugins.mjs`, `npm --prefix core run lint` (0 errors), `node core/scripts/check-arch-docs.mjs` → green - `core/client.js` rebuilt with `npm run build`; `patches/ds-bot/` regenerated with `generate` Not run: the smoke bench and the Web/Desktop shots; CI runs the required checks. ## Checkpoint <!-- flybot:checkpoint --> { "pr": 2648, "claim": "Dev", "issue": 2646, "summary": "A friend's Bot could close the url() and the rule in the page-wide mention stylesheet and add CSS of its own. The image URL is now checked at the sink and at all three entries: only a plain https URL or a base64 raster image survives, and a refused image draws the colour/mask look. The social plugin carries the same predicate for its own threshold and a test keeps the two in step.", "files": ["core/src/client/mention-style.js", "core/src/host/remote-chat.js", "core/src/shared/look-image.js", "plugins/social/src/look.js", "core/test/mention-style.test.js"], "checks": { "ran": "core and plugin suites, build-client --check, ds-bot-patches check/canonical, changelog check, lint, arch-docs", "result": "green", "at": "52f6742ea91c61f4e4671753a840f4cc9ed1a689" }, "next": "none — ready for review" } <!-- /flybot:checkpoint -->
1 parent bfc652e commit b5394cf

19 files changed

Lines changed: 404 additions & 58 deletions

File tree

‎changelog.d/2646.fixed.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
A friend's Bot can no longer put its own CSS on your page: the image URL in its published look is checked where it enters and again in the page-wide mention stylesheet, so a value carrying a quote, a parenthesis, a backslash or a control character is dropped and the Bot is drawn with its colour and mask instead of its photo ([#2646](https://github.com/ThinkFlowLab/FlyBot/issues/2646)).

‎core/client.js‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4935,6 +4935,29 @@ function registerTheme(id, theme) {
49354935
}
49364936
var allThemes = () => ({ ...THEMES, ...customThemes });
49374937

4938+
// src/shared/look-image.js
4939+
var LOOK_IMAGE_MAX = 65536;
4940+
var DATA_IMAGE = /^data:image\/(png|jpeg|webp|gif);base64,[A-Za-z0-9+/]+=*$/i;
4941+
var HTTP = /^https?:\/\//i;
4942+
var UNSAFE = /["'()\\\u0000-\u001f\u007f\s<>]/;
4943+
function safeLookImage(value, max = LOOK_IMAGE_MAX) {
4944+
if (typeof value !== "string") return null;
4945+
const text2 = value.trim();
4946+
if (text2.length === 0 || text2.length > max || UNSAFE.test(text2)) return null;
4947+
if (DATA_IMAGE.test(text2)) return text2;
4948+
if (!HTTP.test(text2)) return null;
4949+
try {
4950+
new URL(text2);
4951+
} catch {
4952+
return null;
4953+
}
4954+
return text2;
4955+
}
4956+
function cssImageUrl(value) {
4957+
const image = safeLookImage(value);
4958+
return image === null ? null : `url("${image}")`;
4959+
}
4960+
49384961
// src/client/mention-style.js
49394962
function chipKey(bot) {
49404963
if (/\s/.test(bot?.name)) return null;
@@ -4956,7 +4979,8 @@ function mentionCss(bots) {
49564979
const chip = key !== null && owner.get(key) === bot ? `[class*="_userRow"] [data-ref-chip="file"][title="@${String(bot.name).replace(/["\\]/g, "\\$&")}" i]` : "";
49574980
const look = bot?.remote ? lookAvoidingLocals(bot) : lookOf(bot);
49584981
const marks = chip ? `${anchor}::before,${chip}::before` : `${anchor}::before`;
4959-
const mark = look.image ? `${marks}{background:center/cover url("${look.image}");-webkit-mask:none;mask:none;border-radius:50%}` : `${marks}{background:${paintCss(look.color)};-webkit-mask-image:${maskOf(look.shape)};mask-image:${maskOf(look.shape)}}`;
4982+
const image = cssImageUrl(look.image);
4983+
const mark = image ? `${marks}{background:center/cover ${image};-webkit-mask:none;mask:none;border-radius:50%}` : `${marks}{background:${paintCss(look.color)};-webkit-mask-image:${maskOf(look.shape)};mask-image:${maskOf(look.shape)}}`;
49604984
const chipBase = chip ? `${chip}{color:inherit;font-weight:600}${chip}>svg{display:none}${chip}::before{content:"";display:inline-block;flex:none;width:16px;height:16px;margin-right:3px;vertical-align:-3px;-webkit-mask:${DEFAULT_MASK} center/contain no-repeat;mask:${DEFAULT_MASK} center/contain no-repeat}` : "";
49614985
return `${anchor}{color:${inkText(look.color)}}${chipBase}${mark}`;
49624986
}).join("\n");

‎core/src/client/mention-style.js‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { lookAvoidingLocals, lookOf, maskOf, DEFAULT_MASK } from './characters.js'
22
import { inkText, paintCss } from './inks.js'
3+
import { cssImageUrl } from '../shared/look-image.js'
34
import { MENTION_ORIGIN } from './text.js'
45

56
// One @Name file chip per display name. A local Bot owns the chip when a
@@ -30,8 +31,11 @@ export function mentionCss(bots) {
3031
// sidebar has already stepped off (#1088). A local Bot still owns a shared @Name chip.
3132
const look = bot?.remote ? lookAvoidingLocals(bot) : lookOf(bot)
3233
const marks = chip ? `${anchor}::before,${chip}::before` : `${anchor}::before`
33-
const mark = look.image
34-
? `${marks}{background:center/cover url("${look.image}");-webkit-mask:none;mask:none;border-radius:50%}`
34+
// A friend's Bot publishes this URL, so the value is checked here as well as where it
35+
// enters; one that could leave url("…") draws the colour/mask look instead (#2646).
36+
const image = cssImageUrl(look.image)
37+
const mark = image
38+
? `${marks}{background:center/cover ${image};-webkit-mask:none;mask:none;border-radius:50%}`
3539
: `${marks}{background:${paintCss(look.color)};-webkit-mask-image:${maskOf(look.shape)};mask-image:${maskOf(look.shape)}}`
3640
const chipBase = chip ? `${chip}{color:inherit;font-weight:600}${chip}>svg{display:none}${chip}::before{content:"";display:inline-block;flex:none;width:16px;height:16px;margin-right:3px;vertical-align:-3px;-webkit-mask:${DEFAULT_MASK} center/contain no-repeat;mask:${DEFAULT_MASK} center/contain no-repeat}` : ''
3741
return `${anchor}{color:${inkText(look.color)}}${chipBase}${mark}`

‎core/src/host/hooks.js‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import { createHash, randomUUID } from 'node:crypto'
1313
import { createUserMessage } from '@deepseek-ai/dsh-llm'
1414
import { isApprovalWaiting } from '../shared/approval-waiting.js'
1515
import { canRetry } from '../shared/held-retry.js'
16+
import { safeLookImage } from '../shared/look-image.js'
1617
import { mentionSpans } from '../shared/mentions.js'
1718
import { isHomeLevelRemote, remoteMentionLabel } from '../shared/remote-label.js'
1819
import { cleanName, stripSessionChips } from './delivery.js'
@@ -937,8 +938,8 @@ export function install(rt) {
937938
const avatar = {}
938939
if (typeof src.shape === 'string' && /^[a-z0-9][a-z0-9_-]{0,31}$/.test(src.shape)) avatar.shape = src.shape
939940
if (typeof src.image === 'string') {
940-
const image = src.image.trim()
941-
if (image.length <= 65536 && /^(https?:\/\/|data:image\/)/i.test(image) && !/[\s<>]/.test(image)) avatar.image = image
941+
const image = safeLookImage(src.image)
942+
if (image) avatar.image = image
942943
}
943944
if (typeof src.emoji === 'string') {
944945
const emoji = src.emoji.trim()

‎core/src/host/remote-chat.js‎

Lines changed: 31 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import { createUserMessage, LlmAdapter } from '@deepseek-ai/dsh-llm'
1515
import { SOURCE_KIND } from './constants.js'
1616
import { cleanName, fenceUntrusted } from './delivery.js'
1717
import { isHomeLevelRemote, normRemoteHandle } from '../shared/remote-label.js'
18+
import { safeLookImage } from '../shared/look-image.js'
1819
import { cut } from './text.js'
1920

2021
export const REMOTE_PROVIDER = 'flybot-remote'
@@ -24,6 +25,36 @@ const SENT_KEPT = 500
2425
export const isRemoteChat = bot => typeof bot?.remote?.handle === 'string'
2526
const textOf = content => (Array.isArray(content) ? content.filter(block => block?.type === 'text').map(block => block.text).join('\n') : String(content ?? ''))
2627

28+
// A published look reaches the mention stylesheet, so its image is checked here as well as
29+
// at that sink: a value that could leave url("…") is dropped and the Bot keeps no photo (#2646).
30+
export function applyPublishedLook(bot, member) {
31+
if (!bot || !member) return false
32+
const at = typeof member.avatarUpdatedAt === 'string' ? member.avatarUpdatedAt : ''
33+
if (at && bot.avatarUpdatedAt === at) return false
34+
let changed = false
35+
if (typeof member.color === 'string' && member.color && bot.color !== member.color) {
36+
bot.color = member.color
37+
changed = true
38+
}
39+
if (member.avatar && typeof member.avatar === 'object') {
40+
const avatar = { ...member.avatar }
41+
if (avatar.image !== undefined) {
42+
const image = safeLookImage(avatar.image)
43+
if (image === null) delete avatar.image
44+
else avatar.image = image
45+
}
46+
if (JSON.stringify(bot.avatar) !== JSON.stringify(avatar)) {
47+
bot.avatar = avatar
48+
changed = true
49+
}
50+
}
51+
if (at && bot.avatarUpdatedAt !== at) {
52+
bot.avatarUpdatedAt = at
53+
changed = true
54+
}
55+
return changed
56+
}
57+
2758
// Sidebar / chat preview for a failed 1:1 send to a friend's Bot. Keep it one short
2859
// English line with a next step; never dump `Bot Social send_as_member: …`.
2960
export function notSentLine(error) {
@@ -193,27 +224,6 @@ export function install(rt) {
193224
}
194225

195226
let opening = Promise.resolve()
196-
function applyPublishedLook(bot, member) {
197-
if (!bot || !member) return false
198-
const at = typeof member.avatarUpdatedAt === 'string' ? member.avatarUpdatedAt : ''
199-
if (at && bot.avatarUpdatedAt === at) return false
200-
let changed = false
201-
if (typeof member.color === 'string' && member.color && bot.color !== member.color) {
202-
bot.color = member.color
203-
changed = true
204-
}
205-
if (member.avatar && typeof member.avatar === 'object') {
206-
if (JSON.stringify(bot.avatar) !== JSON.stringify(member.avatar)) {
207-
bot.avatar = { ...member.avatar }
208-
changed = true
209-
}
210-
}
211-
if (at && bot.avatarUpdatedAt !== at) {
212-
bot.avatarUpdatedAt = at
213-
changed = true
214-
}
215-
return changed
216-
}
217227
// Creates the chat for a remote Bot (once), or refreshes its name, home label, and look.
218228
function open({ handle, name, home, homeName, plugin, color, avatar, avatarUpdatedAt }) {
219229
if (isHomeLevelRemote({ handle, home })) return Promise.resolve(undefined)

‎core/src/shared/look-image.js‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// The image URL a Bot's look may carry. A friend's Bot publishes its own look, and the
2+
// page-wide mentions stylesheet pastes `avatar.image` into `url("…")` (client/mention-style.js),
3+
// so a value that can close the quote, the url() or the rule is dropped where it enters —
4+
// hooks.js `cleanRemoteLook` and remote-chat.js `applyPublishedLook` — and again at that sink.
5+
// A dropped image draws the colour/mask look instead. The social plugin carries the same test
6+
// for its own threshold (no gif there); plugins/social/test/look.test.js keeps the two in step.
7+
export const LOOK_IMAGE_MAX = 65536
8+
const DATA_IMAGE = /^data:image\/(png|jpeg|webp|gif);base64,[A-Za-z0-9+/]+=*$/i
9+
const HTTP = /^https?:\/\//i
10+
const UNSAFE = /["'()\\\u0000-\u001f\u007f\s<>]/
11+
12+
// The trimmed image URL, or null when it is not a plain https URL or a base64 raster image.
13+
export function safeLookImage(value, max = LOOK_IMAGE_MAX) {
14+
if (typeof value !== 'string') return null
15+
const text = value.trim()
16+
if (text.length === 0 || text.length > max || UNSAFE.test(text)) return null
17+
if (DATA_IMAGE.test(text)) return text
18+
if (!HTTP.test(text)) return null
19+
try { new URL(text) } catch { return null }
20+
return text
21+
}
22+
23+
// The same value, ready to sit inside a stylesheet as `url("…")`; null means draw the colour.
24+
export function cssImageUrl(value) {
25+
const image = safeLookImage(value)
26+
return image === null ? null : `url("${image}")`
27+
}

‎core/test/mention-style.test.js‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import assert from 'node:assert/strict'
2+
import { test } from 'node:test'
3+
import { mentionCss } from '../src/client/mention-style.js'
4+
import { applyPublishedLook } from '../src/host/remote-chat.js'
5+
import { cssImageUrl, safeLookImage } from '../src/shared/look-image.js'
6+
7+
// The payload from #2646: a friend's Bot publishes a look whose image closes url("…"),
8+
// closes the rule, and adds a page-wide `body{…}` rule to the mention stylesheet.
9+
const PAYLOAD = `data:image/png;base64,AA");}body{background:url(https://evil.example/beacon)}.z{'`
10+
const evil = {
11+
id: 'remote:evil.home',
12+
name: 'Evil',
13+
remote: { handle: 'evil.home' },
14+
avatar: { image: PAYLOAD },
15+
}
16+
17+
const urlQuotes = css => (css.match(/url\("/g) ?? []).length
18+
const urlCloses = css => (css.match(/"\)/g) ?? []).length
19+
20+
test('a payload image cannot leave url("…") in the page-wide mention stylesheet (#2646)', () => {
21+
const css = mentionCss([evil])
22+
assert.equal(css.includes('body{'), false)
23+
assert.equal(css.includes('evil.example'), false)
24+
assert.equal(urlQuotes(css), urlCloses(css))
25+
// The sink drops the photo and draws the colour/mask look instead.
26+
assert.match(css, /-webkit-mask-image:/)
27+
assert.equal(css.includes(PAYLOAD), false)
28+
})
29+
30+
test('a valid image still draws the photo in the mention stylesheet (#2646)', () => {
31+
// A display name with a space owns no @Name chip, so the DEFAULT_MASK url() stays out of the line.
32+
const friend = { id: 'remote:ok', name: 'Ok Friend', remote: { handle: 'ok.home' }, avatar: { image: 'https://ok.example/a.png' } }
33+
const css = mentionCss([friend])
34+
assert.match(css, /background:center\/cover url\("https:\/\/ok\.example\/a\.png"\)/)
35+
assert.equal(urlQuotes(css), 1)
36+
assert.equal(urlCloses(css), 1)
37+
// A local Bot's gif avatar is a stored form and keeps drawing (roster.js accepts it).
38+
const local = { id: 'local', name: 'Local Bot', avatar: { image: 'data:image/gif;base64,R0lGODlhAQABAAAAACw=' } }
39+
assert.match(mentionCss([local]), /url\("data:image\/gif;base64,R0lGODlhAQABAAAAACw="\)/)
40+
})
41+
42+
test('a published look drops an unsafe image and keeps a plain one (#2646)', () => {
43+
const dropped = {}
44+
applyPublishedLook(dropped, { avatar: { shape: 'moon', image: PAYLOAD }, avatarUpdatedAt: 't1' })
45+
assert.deepEqual(dropped.avatar, { shape: 'moon' })
46+
47+
const kept = {}
48+
applyPublishedLook(kept, { avatar: { image: 'https://ok.example/a.png' }, avatarUpdatedAt: 't2' })
49+
assert.deepEqual(kept.avatar, { image: 'https://ok.example/a.png' })
50+
})
51+
52+
test('cssImageUrl refuses every value that could close the url or the rule (#2646)', () => {
53+
for (const bad of [
54+
'https://ok.example/a".png',
55+
"https://ok.example/a'.png",
56+
'https://ok.example/a(.png',
57+
'https://ok.example/a).png',
58+
'https://ok.example/a\\.png',
59+
'https://ok.example/a\n.png',
60+
'https://ok.example/a\u0007.png',
61+
'javascript:alert(1)',
62+
'data:image/png;base64,AA");}body{background:red}',
63+
'',
64+
]) assert.equal(cssImageUrl(bad), null, bad)
65+
66+
assert.equal(cssImageUrl('https://ok.example/a.png'), 'url("https://ok.example/a.png")')
67+
assert.equal(safeLookImage('data:image/webp;base64,AAAA'), 'data:image/webp;base64,AAAA')
68+
assert.equal(safeLookImage('https://ok.example/a.png'), 'https://ok.example/a.png')
69+
})

0 commit comments

Comments
 (0)