Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion docs/writing-widgets.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<img>`; rejects when there is none. Ask this rather than loading `/api/favicon` in an `<img>`: 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/<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 |
| `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 `<img>`. Requires a `dock` subscription, like `installedApps()`. The host fetches it because the opaque widget frame cannot load `/api/apps/icon/<bundleId>` 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 |
Expand Down
6 changes: 5 additions & 1 deletion server/src/bridge/fremkit.js
Original file line number Diff line number Diff line change
Expand Up @@ -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/<bundleId>`, 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
Expand All @@ -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.
*
Expand Down
2 changes: 2 additions & 0 deletions server/src/dock/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
17 changes: 16 additions & 1 deletion server/test/apps-installed.test.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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()
Expand Down
17 changes: 16 additions & 1 deletion server/test/bridge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>
sdk: number
esc(value: unknown): string
el(tag: string, className?: string, text?: unknown): { tagName: string; className: string; textContent: string }
Expand All @@ -17,6 +18,7 @@ interface Bridge {

/** What the loaded bridge did to its document, for the kiosk-behaviour tests. */
interface LoadResult {
posted: Record<string, unknown>[]
bridge: Bridge
listeners: string[]
styles: { attrs: Record<string, string>; textContent: string }[]
Expand All @@ -29,8 +31,9 @@ interface LoadResult {
async function loadBridge(): Promise<LoadResult> {
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<string, unknown>[] = []
const window: Record<string, unknown> = {
parent: { postMessage: () => {} },
parent: { postMessage: (message: Record<string, unknown>) => { posted.push(message) } },
addEventListener: (type: string, cb: (event: { source: unknown; data: unknown }) => void) => {
if (type === 'message') onMessage = cb
},
Expand Down Expand Up @@ -71,6 +74,7 @@ async function loadBridge(): Promise<LoadResult> {
}
new Function('window', 'document', 'console', src)(window, document, console)
return {
posted,
bridge: window.Fremkit as Bridge,
listeners,
styles,
Expand Down Expand Up @@ -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==')
})
})
24 changes: 17 additions & 7 deletions server/test/shortcuts-widget.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand All @@ -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<string, unknown>): Promise<Loaded> {
Expand All @@ -33,15 +36,15 @@ async function loadWidget(installed: unknown, settings: Record<string, unknown>)
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
Expand All @@ -52,6 +55,7 @@ async function loadWidget(installed: unknown, settings: Record<string, unknown>)
return nodes.get(id)!
}
const dockSubscribers: ((data: unknown) => void)[] = []
const iconRequests: string[] = []
const document = {
documentElement: node('html'),
getElementById: byId,
Expand All @@ -77,6 +81,7 @@ async function loadWidget(installed: unknown, settings: Record<string, unknown>)
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)
Expand All @@ -85,6 +90,7 @@ async function loadWidget(installed: unknown, settings: Record<string, unknown>)
buttons: () => grid().children,
artwork: () => grid().children[0]?.children[0],
publishDock: (data) => dockSubscribers.forEach((cb) => cb(data)),
iconRequests: () => iconRequests,
}
}

Expand All @@ -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 () => {
Expand All @@ -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 () => {
Expand All @@ -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')
})
})
1 change: 1 addition & 0 deletions ui/src/shared/locales/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,7 @@ export const en: Record<string, string> = {

'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}',

Expand Down
1 change: 1 addition & 0 deletions ui/src/shared/locales/fr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,7 @@ export const fr: Record<string, string> = {

'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}',

Expand Down
17 changes: 16 additions & 1 deletion ui/src/shared/useWidgetBridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand Down Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions ui/src/shared/widgetMessages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
62 changes: 62 additions & 0 deletions ui/test/app-icon-host.test.ts
Original file line number Diff line number Diff line change
@@ -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()
})
})
12 changes: 11 additions & 1 deletion ui/test/bridge.test.ts
Original file line number Diff line number Diff line change
@@ -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', () => {
Expand Down Expand Up @@ -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()
}
})
})
Loading
Loading