diff --git a/CHANGELOG.md b/CHANGELOG.md index bb252d14..9cf4196b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,6 +44,7 @@ Anything that changes what the dashboard, the admin or a widget can do gets a li sessions after 30 minutes (on by default), and group the board by application. ### Fixed +- **Application icon access.** Widgets that subscribe to `dock` receive icons through the dashboard host; cross-site requests to the icon route are refused, so other widget frames cannot probe installed applications. - **Widgets load on the native dashboard again.** WebKit can now load the bridge and a widget's own script, style, image, font and media files inside the sandboxed frame. - Shortcut buttons draw the real icon of an application that is not in the Dock again. The widget diff --git a/docs/writing-widgets.md b/docs/writing-widgets.md index 38a1a168..c34beec7 100644 --- a/docs/writing-widgets.md +++ b/docs/writing-widgets.md @@ -226,7 +226,8 @@ Fremkit.whenReady(() => { | `fetch(url, init)` | GET through the server's proxy. Only the host in `permissions.network` is reachable; `body` and `credentials` are ignored | | `favicon(url)` | The icon of the site `url` is on, as a `data:` URL for an ``; rejects when there is none. Ask this rather than loading `/api/favicon` in an ``: a widget's frame has an opaque origin, so the server sees that request as cross-site and refuses it | | `image(url)` | The image at exactly `url`, as a `data:` URL, under the rules of `favicon` (no SVG, no private address). Fetched only when `url` is a value the user typed into this widget's settings; rejects otherwise — the whole address leaves the machine, so a widget cannot pick it | -| `installedApps()` | The applications installed on this Mac, as `{ name, bundleId, file }` — enough to match a name the user typed and ask for its icon at `/api/apps/icon/`, and no filesystem path. Ask this rather than `fetch('/api/apps/installed')`: a widget's frame is served with `connect-src 'none'`, so its own request never leaves the page. Answered only to a widget that subscribes to `dock`, which the consent dialog shows; anything else is refused | +| `installedApps()` | The applications installed on this Mac, as `{ name, bundleId, file }` — enough to match a name the user typed and ask for its icon with `appIcon(bundleId)`, and no filesystem path. Ask this rather than `fetch('/api/apps/installed')`: a widget's frame is served with `connect-src 'none'`, so its own request never leaves the page. Answered only to a widget that subscribes to `dock`, which the consent dialog shows; anything else is refused | +| `appIcon(bundleId)` | A local application icon as a `data:` URL for an ``. Requires a `dock` subscription, like `installedApps()`. The host fetches it because the opaque widget frame cannot load `/api/apps/icon/` directly | | `t(dict, params)` | Resolves a `{ fr, en }` table entry and interpolates `{name}` placeholders | | `onSettings(cb)` | Fires when the admin edits the settings, without a reload. Returns an off function | | `onLocale(cb)` | Fires when the language changes. Returns an off function | diff --git a/server/src/bridge/fremkit.js b/server/src/bridge/fremkit.js index 2fbae784..1d5bbd67 100644 --- a/server/src/bridge/fremkit.js +++ b/server/src/bridge/fremkit.js @@ -222,7 +222,7 @@ }, /** * The applications installed on this Mac, as `{ name, bundleId, file }` — enough to name one - * and to ask for its icon at `/api/apps/icon/`, and nothing about where it lives. + * and to ask for its icon with `appIcon(bundleId)`, and nothing about where it lives. * * Asked of the host for the same reason as a favicon, one step earlier: a widget's frame is * served with `connect-src 'none'`, so a `fetch` from here never leaves the page at all. The @@ -231,6 +231,10 @@ installedApps: function () { return request({ type: 'fremkit:apps' }) }, + /** A local application's icon as a data URL. Requires a Dock subscription. */ + appIcon: function (bundleId) { + return request({ type: 'fremkit:app-icon', bundleId: bundleId }) + }, /** * Escapes a string for HTML. * diff --git a/server/src/dock/routes.ts b/server/src/dock/routes.ts index db4dc4e7..a9c64448 100644 --- a/server/src/dock/routes.ts +++ b/server/src/dock/routes.ts @@ -2,6 +2,7 @@ import type { FastifyInstance, FastifyRequest } from 'fastify' import { BUNDLE_ID_RE, isPng, MAX_ICON_BYTES, MAX_ICONS, type DockState } from './state.js' import { isLoopbackAddress } from '../net/loopback.js' import { tr } from '../i18n.js' +import { isCrossSiteFetch } from '../http/guard.js' /** * Twice the base64 of the largest accepted PNG, plus the small JSON envelope around it: an icon @@ -52,6 +53,7 @@ export async function dockRoutes(app: FastifyInstance, opts: { state: DockState; }) app.get<{ Params: { bundleId: string } }>('/api/apps/icon/:bundleId', async (req, reply) => { + if (isCrossSiteFetch(req.headers)) return reply.code(403).send() const { bundleId } = req.params if (!BUNDLE_ID_RE.test(bundleId)) return reply.code(400).send({ error: 'identifiant de bundle invalide' }) // The helper uploads one icon per Dock slot; an application that is merely installed — the diff --git a/server/test/apps-installed.test.ts b/server/test/apps-installed.test.ts index db47b5c5..d405384a 100644 --- a/server/test/apps-installed.test.ts +++ b/server/test/apps-installed.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect } from 'vitest' +import { describe, it, expect, vi } from 'vitest' import { mkdtemp, readFile, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -233,6 +233,21 @@ describe('GET /api/apps/installed', () => { }) describe('GET /api/apps/icon/:bundleId with an extraction fallback', () => { + it('refuses cross-site image probes before looking up an installed app', async () => { + const app = Fastify() + const get = vi.fn(async () => PNG) + await app.register(dockRoutes, { + state: new DockState({ iconsDir: join(tmpdir(), 'fremkit-icon-probe-test') }), + appIcons: { get }, + }) + const res = await app.inject({ + url: '/api/apps/icon/com.example.a', + headers: { 'sec-fetch-site': 'cross-site' }, + }) + expect(res.statusCode).toBe(403) + expect(get).not.toHaveBeenCalled() + await app.close() + }) it('serves the extracted icon when the helper never uploaded one', async () => { const dir = await mkdtemp(join(tmpdir(), 'fremkit-iconroute-')) const app = Fastify() diff --git a/server/test/bridge.test.ts b/server/test/bridge.test.ts index bc18f06f..08ce853e 100644 --- a/server/test/bridge.test.ts +++ b/server/test/bridge.test.ts @@ -9,6 +9,7 @@ import { SDK_VERSION } from '../src/bridge/sdk.js' * widget now relies on for escaping can be exercised without a DOM. */ interface Bridge { + appIcon(bundleId: string): Promise sdk: number esc(value: unknown): string el(tag: string, className?: string, text?: unknown): { tagName: string; className: string; textContent: string } @@ -17,6 +18,7 @@ interface Bridge { /** What the loaded bridge did to its document, for the kiosk-behaviour tests. */ interface LoadResult { + posted: Record[] bridge: Bridge listeners: string[] styles: { attrs: Record; textContent: string }[] @@ -29,8 +31,9 @@ interface LoadResult { async function loadBridge(): Promise { const src = await readFile(fileURLToPath(new URL('../src/bridge/fremkit.js', import.meta.url)), 'utf8') let onMessage: ((event: { source: unknown; data: unknown }) => void) | null = null + const posted: Record[] = [] const window: Record = { - parent: { postMessage: () => {} }, + parent: { postMessage: (message: Record) => { posted.push(message) } }, addEventListener: (type: string, cb: (event: { source: unknown; data: unknown }) => void) => { if (type === 'message') onMessage = cb }, @@ -71,6 +74,7 @@ async function loadBridge(): Promise { } new Function('window', 'document', 'console', src)(window, document, console) return { + posted, bridge: window.Fremkit as Bridge, listeners, styles, @@ -230,3 +234,14 @@ describe('a widget under a theme', () => { expect(loaded.properties.has('--text')).toBe(false) }) }) + +describe('Fremkit.appIcon', () => { + it('requests a bundle id from the host and returns its image data', async () => { + const loaded = await loadBridge() + const promise = loaded.bridge.appIcon('com.apple.mail') + const message = loaded.posted.at(-1)! + expect(message).toMatchObject({ type: 'fremkit:app-icon', bundleId: 'com.apple.mail' }) + loaded.send({ type: 'fremkit:result', id: message.id, result: 'data:image/png;base64,aWNvbg==' }) + await expect(promise).resolves.toBe('data:image/png;base64,aWNvbg==') + }) +}) diff --git a/server/test/shortcuts-widget.test.ts b/server/test/shortcuts-widget.test.ts index dfc91de8..14cff3f3 100644 --- a/server/test/shortcuts-widget.test.ts +++ b/server/test/shortcuts-widget.test.ts @@ -14,6 +14,8 @@ import { fileURLToPath } from 'node:url' interface StubNode { tag: string; className: string; textContent: string; src: string children: StubNode[] + parentNode: StubNode | null + isConnected: boolean retryTimer?: unknown } @@ -24,6 +26,7 @@ interface Loaded { artwork(): StubNode | undefined /** Hands the widget one answer from the dock channel, as the host delivers it. */ publishDock(data: unknown): void + iconRequests(): string[] } async function loadWidget(installed: unknown, settings: Record): Promise { @@ -33,15 +36,15 @@ async function loadWidget(installed: unknown, settings: Record) const node = (tag = 'div'): StubNode => { const self = { tag, className: '', textContent: '', src: '', alt: '', hidden: false, clientHeight: 300, - children: [] as StubNode[], + children: [] as StubNode[], parentNode: null, isConnected: true, style: { setProperty: () => {} }, classList: { add: () => {}, remove: () => {}, toggle: () => {} }, - appendChild: (child: StubNode) => { self.children.push(child) }, - replaceChild: (next: StubNode, old: StubNode) => { self.children.splice(self.children.indexOf(old), 1, next) }, + appendChild: (child: StubNode) => { child.parentNode = self; self.children.push(child) }, + replaceChild: (next: StubNode, old: StubNode) => { old.parentNode = null; next.parentNode = self; self.children.splice(self.children.indexOf(old), 1, next) }, addEventListener: () => {}, onclick: null, // The widget empties the grid this way before rebuilding it. - set innerHTML(_v: string) { self.children.length = 0 }, + set innerHTML(_v: string) { self.children.forEach((child) => { child.parentNode = null; child.isConnected = false }); self.children.length = 0 }, get innerHTML() { return '' }, } as unknown as StubNode return self @@ -52,6 +55,7 @@ async function loadWidget(installed: unknown, settings: Record) return nodes.get(id)! } const dockSubscribers: ((data: unknown) => void)[] = [] + const iconRequests: string[] = [] const document = { documentElement: node('html'), getElementById: byId, @@ -77,6 +81,7 @@ async function loadWidget(installed: unknown, settings: Record) esc: (value: unknown) => String(value ?? ''), color: (_value: unknown, fallback: string) => fallback, installedApps: () => (installed === REFUSED ? Promise.reject(new Error('unavailable')) : Promise.resolve(installed)), + appIcon: (bundleId: string) => { iconRequests.push(bundleId); return Promise.resolve('data:image/png;base64,aWNvbg==') }, } // The widget refreshes the list on a timer; a test wants the one call it makes on startup. new Function('document', 'Fremkit', 'setInterval', script)(document, Fremkit, () => 0) @@ -85,6 +90,7 @@ async function loadWidget(installed: unknown, settings: Record) buttons: () => grid().children, artwork: () => grid().children[0]?.children[0], publishDock: (data) => dockSubscribers.forEach((cb) => cb(data)), + iconRequests: () => iconRequests, } } @@ -98,7 +104,8 @@ describe('the shortcuts widget application icons', () => { await Promise.resolve() await Promise.resolve() expect(loaded.artwork()?.tag).toBe('img') - expect(loaded.artwork()?.src).toBe('/api/apps/icon/com.apple.Terminal') + expect(loaded.artwork()?.src).toBe('data:image/png;base64,aWNvbg==') + expect(loaded.iconRequests()).toContain('com.apple.Terminal') }) it('matches the bundle a name is filed under, not only its own name', async () => { @@ -107,7 +114,8 @@ describe('the shortcuts widget application icons', () => { }) await Promise.resolve() await Promise.resolve() - expect(loaded.artwork()?.src).toBe('/api/apps/icon/com.microsoft.VSCode') + expect(loaded.artwork()?.src).toBe('data:image/png;base64,aWNvbg==') + expect(loaded.iconRequests()).toContain('com.microsoft.VSCode') }) it('keeps the glyph while the host has not answered, and when it never does', async () => { @@ -122,6 +130,8 @@ describe('the shortcuts widget application icons', () => { await Promise.resolve() await Promise.resolve() loaded.publishDock({ available: true, apps: [{ name: 'Terminal', bundleId: 'com.apple.Terminal', badge: null, running: true }] }) - expect(loaded.artwork()?.src).toBe('/api/apps/icon/com.apple.Terminal') + await Promise.resolve() + expect(loaded.artwork()?.src).toBe('data:image/png;base64,aWNvbg==') + expect(loaded.iconRequests()).toContain('com.apple.Terminal') }) }) diff --git a/ui/src/shared/locales/en.ts b/ui/src/shared/locales/en.ts index e385747e..cc7fb1b6 100644 --- a/ui/src/shared/locales/en.ts +++ b/ui/src/shared/locales/en.ts @@ -268,6 +268,7 @@ export const en: Record = { 'bridge.badRequest': 'invalid widget request', 'bridge.noIcon': 'no icon for this site', + 'bridge.noAppIcon': 'no icon for this application', 'bridge.noApps': 'installed applications unavailable', 'bridge.channelNotAllowed': 'channel not allowed: {channel}', diff --git a/ui/src/shared/locales/fr.ts b/ui/src/shared/locales/fr.ts index 5f2f9e7b..d67c239c 100644 --- a/ui/src/shared/locales/fr.ts +++ b/ui/src/shared/locales/fr.ts @@ -268,6 +268,7 @@ export const fr: Record = { 'bridge.badRequest': 'requête du widget invalide', 'bridge.noIcon': 'pas d’icône pour ce site', + 'bridge.noAppIcon': 'pas d’icône pour cette application', 'bridge.noApps': 'liste des applications indisponible', 'bridge.channelNotAllowed': 'canal non autorisé : {channel}', diff --git a/ui/src/shared/useWidgetBridge.ts b/ui/src/shared/useWidgetBridge.ts index 43cbe7d8..b7fcd849 100644 --- a/ui/src/shared/useWidgetBridge.ts +++ b/ui/src/shared/useWidgetBridge.ts @@ -4,7 +4,7 @@ import { t, useI18n } from './i18n' import { isHexColor, tileText } from './color' import { useAppliedTheme, useThemeColors } from './theme' import { channelAllowed, mergeSettings, type AccentMode, type NavSlot, type WidgetInstance, type WidgetManifest, type WidgetSize } from './types' -import { FrameTrust, connRequest, faviconTarget, fetchTarget, imageTarget, mayListApps, nonEmptyString, stampInstance } from './widgetMessages' +import { FrameTrust, appIconTarget, connRequest, faviconTarget, fetchTarget, imageTarget, mayListApps, nonEmptyString, stampInstance } from './widgetMessages' export type BridgeState = 'loading' | 'ready' | 'error' @@ -209,6 +209,21 @@ export function useWidgetBridge( .catch((e: Error) => reply(id, undefined, e.message)) break } + case 'fremkit:app-icon': { + const id = str(m.id) + if (!id) break + if (!mayListApps(manifest()?.subscriptions)) { reply(id, undefined, t('bridge.channelNotAllowed', { channel: 'dock' })); break } + const bundleId = appIconTarget(m) + if (!bundleId) { reply(id, undefined, t('bridge.badRequest')); break } + // Fetch from the host origin. An opaque widget cannot load this route directly. + fetch(`/api/apps/icon/${encodeURIComponent(bundleId)}`, { cache: 'no-store' }) + .then(async (r) => { + if (!r.ok) { reply(id, undefined, t('bridge.noAppIcon')); return } + reply(id, await dataUrl(await r.blob())) + }) + .catch((e: Error) => reply(id, undefined, e.message)) + break + } case 'fremkit:apps': { // Same reason as the favicon above, one step earlier: the widget's frame is served with // `connect-src 'none'`, so its own fetch never leaves the page. The route answers the diff --git a/ui/src/shared/widgetMessages.ts b/ui/src/shared/widgetMessages.ts index 0e7f4dab..a69cb20a 100644 --- a/ui/src/shared/widgetMessages.ts +++ b/ui/src/shared/widgetMessages.ts @@ -13,6 +13,12 @@ export function nonEmptyString(value: unknown): string | null { return typeof value === 'string' && value !== '' ? value : null } +/** The bundle id whose local icon the host may retrieve, never a path or URL. */ +export function appIconTarget(message: { bundleId?: unknown }): string | null { + const id = nonEmptyString(message.bundleId) + return id && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(id) ? id : null +} + /** * The origin a `fremkit:favicon` request is about, or null. * diff --git a/ui/test/app-icon-host.test.ts b/ui/test/app-icon-host.test.ts new file mode 100644 index 00000000..d357d2a6 --- /dev/null +++ b/ui/test/app-icon-host.test.ts @@ -0,0 +1,62 @@ +// @vitest-environment jsdom +import { afterEach, describe, expect, it, vi } from 'vitest' +import { mount, type VueWrapper } from '@vue/test-utils' +import { defineComponent, h, ref } from 'vue' +import { readFileSync } from 'node:fs' +import { URL as NodeURL } from 'node:url' +import { useWidgetBridge } from '../src/shared/useWidgetBridge' +import type { WidgetManifest } from '../src/shared/types' + +vi.mock('../src/shared/socket', () => ({ useSocket: () => ({ subscribe: vi.fn(), command: vi.fn() }) })) +const manifest = JSON.parse(readFileSync(new NodeURL('../../widgets/notifications/manifest.json', import.meta.url), 'utf8')) as WidgetManifest +let wrapper: VueWrapper | undefined +let frame: HTMLIFrameElement +function load(subscriptions = ['dock']) { + frame = document.createElement('iframe') + document.body.appendChild(frame) + const reply = vi.spyOn(frame.contentWindow!, 'postMessage').mockImplementation(() => {}) + wrapper = mount(defineComponent({ + setup() { + useWidgetBridge(ref(frame), () => ({ instanceId: 'n-1', widgetId: 'notifications', x: 0, y: 0, w: 10, h: 10, showTitle: true, settings: {} }), + () => ({ ...manifest, subscriptions }), () => 40) + return () => h('div') + }, + })) + return reply +} +function request(bundleId: unknown, source: Window | null = frame.contentWindow) { + window.dispatchEvent(new MessageEvent('message', { source, data: {type: 'fremkit:app-icon', id: 'icon-1', bundleId} })) +} +afterEach(() => { wrapper?.unmount(); frame?.remove(); vi.unstubAllGlobals(); vi.restoreAllMocks() }) +describe('host application icon requests', () => { + it('fetches the local PNG for a Dock widget and replies with image data', async () => { + const fetcher = vi.fn().mockResolvedValue({ok: true, blob: async () => new Blob(['icon'], {type: 'image/png'})}) + vi.stubGlobal('fetch', fetcher) + const reply = load() + request('com.apple.mail') + await vi.waitFor(() => expect(reply).toHaveBeenCalledWith({type: 'fremkit:result', id: 'icon-1', result: 'data:image/png;base64,aWNvbg=='}, '*')) + expect(fetcher).toHaveBeenCalledWith('/api/apps/icon/com.apple.mail', {cache: 'no-store'}) + }) + it('explains when a local application icon is unavailable', async () => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ok: false})) + const reply = load() + request('com.apple.mail') + await vi.waitFor(() => expect(reply).toHaveBeenCalledWith({type: 'fremkit:result', id: 'icon-1', error: 'pas d’icône pour cette application'}, '*')) + }) + it('refuses widgets without a Dock subscription before fetching', () => { + const fetcher = vi.fn(); vi.stubGlobal('fetch', fetcher) + const reply = load([]) + request('com.apple.mail') + expect(fetcher).not.toHaveBeenCalled() + expect(reply.mock.calls.at(-1)?.[0]).toMatchObject({type: 'fremkit:result', id: 'icon-1', error: expect.any(String)}) + }) + it('refuses a path and ignores messages outside the widget frame', () => { + const fetcher = vi.fn(); vi.stubGlobal('fetch', fetcher) + const reply = load() + request('../config') + expect(reply).toHaveBeenCalledTimes(1) + request('com.apple.mail', null) + expect(reply).toHaveBeenCalledTimes(1) + expect(fetcher).not.toHaveBeenCalled() + }) +}) diff --git a/ui/test/bridge.test.ts b/ui/test/bridge.test.ts index 67e09b14..7c2cc1b2 100644 --- a/ui/test/bridge.test.ts +++ b/ui/test/bridge.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { FrameTrust, faviconTarget, fetchTarget, imageTarget, mayListApps, nonEmptyString, stampInstance } from '../src/shared/widgetMessages' +import { FrameTrust, appIconTarget, faviconTarget, fetchTarget, imageTarget, mayListApps, nonEmptyString, stampInstance } from '../src/shared/widgetMessages' describe('nonEmptyString', () => { it('accepts a non-empty string and nothing else', () => { @@ -150,3 +150,13 @@ describe('FrameTrust', () => { expect(trust.trusted).toBe(false) }) }) + +describe('appIconTarget', () => { + it('accepts bundle ids and refuses paths, URLs and other values', () => { + expect(appIconTarget({ bundleId: 'com.apple.mail' })).toBe('com.apple.mail') + expect(appIconTarget({ bundleId: 'com.example.app-2_1' })).toBe('com.example.app-2_1') + for (const bundleId of ['', '../config', 'https://evil.example/', '/com.apple.mail', 'a'.repeat(129), 42, null]) { + expect(appIconTarget({ bundleId })).toBeNull() + } + }) +}) diff --git a/ui/test/notifications-widget.test.ts b/ui/test/notifications-widget.test.ts new file mode 100644 index 00000000..3d856806 --- /dev/null +++ b/ui/test/notifications-widget.test.ts @@ -0,0 +1,41 @@ +// @vitest-environment jsdom +import { afterEach, describe, expect, it, vi } from 'vitest' +import { readFileSync } from 'node:fs' +import { URL as NodeURL } from 'node:url' + +const html = readFileSync(new NodeURL('../../widgets/notifications/index.html', import.meta.url), 'utf8') +function load(appIcon: (id: string) => Promise) { + document.body.innerHTML = html.match(/([\s\S]*?)