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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ 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
- **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
read the list of installed applications itself, which the `connect-src 'none'` its frame is
served with has always refused, so anything the user had never docked fell back to the kind's
Expand Down
2 changes: 1 addition & 1 deletion server/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ export async function buildApp(opts: AppOptions): Promise<FastifyInstance> {

await app.register(configRoutes, { store, catalog })
await app.register(connectionRoutes, { store, catalog, types: connectionTypes, manager: connections, secrets, connCache })
await app.register(widgetRoutes, { catalog, store })
await app.register(widgetRoutes, { catalog, store, port: opts.port, dev: process.env.FREMKIT_DEV === '1' })
await app.register(themeRoutes, { catalog: themes })
await app.register(proxyRoutes, { catalog, store, secrets, cache: connCache })
const marketplaceRegistry = new Registry({
Expand Down
50 changes: 30 additions & 20 deletions server/src/widgets/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import { SDK_VERSION } from '../bridge/sdk.js'
import { tr } from '../i18n.js'

const BRIDGE_PATH = fileURLToPath(new URL('../bridge/fremkit.js', import.meta.url))
const BRIDGE_TAG = '<script src="/fremkit.js"></script>'

/**
* What a widget may do, said in a header rather than left to the iframe.
Expand All @@ -24,36 +23,47 @@ const BRIDGE_TAG = '<script src="/fremkit.js"></script>'
*
* `sandbox allow-scripts` without `allow-same-origin` puts the document in an opaque origin:
* scripts run, but nothing they do counts as coming from us. Everything else is an allow-list of
* what the widgets in this repository actually need — `'self'` for their own files and the
* bridge, `data:`/`blob:` for what they generate, `i.scdn.co` for the album art the local
* what the widgets in this repository actually need. WebKit does not resolve `'self'` for
* opaque frames, so the server's loopback origins are listed explicitly for packaged files.
* `data:`/`blob:` cover what widgets generate, `i.scdn.co` covers album art the local
* Spotify app hands us as an https URL. No `connect-src` at all: every network call goes through
* `Fremkit.fetch`, which asks the host, which asks the proxy, which checks the manifest.
*/
export const WIDGET_CSP = [
'sandbox allow-scripts',
"default-src 'none'",
"script-src 'self' 'unsafe-inline'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: blob: https://i.scdn.co",
"media-src 'self' data:",
"font-src 'self'",
"connect-src 'none'",
"frame-src 'none'",
"form-action 'none'",
"base-uri 'none'",
].join('; ')
export function widgetCsp(port = 4242, dev = false): string {
const ownOrigins = [`http://127.0.0.1:${port}`, `http://localhost:${port}`]
if (dev) ownOrigins.push('http://127.0.0.1:5173', 'http://localhost:5173')
const own = ownOrigins.join(' ')
return [
'sandbox allow-scripts',
"default-src 'none'",
`script-src 'self' ${own} 'unsafe-inline'`,
`style-src 'self' ${own} 'unsafe-inline'`,
`img-src 'self' ${own} data: blob: https://i.scdn.co`,
`media-src 'self' ${own} data:`,
`font-src 'self' ${own}`,
"connect-src 'none'",
"frame-src 'none'",
"form-action 'none'",
"base-uri 'none'",
].join('; ')
}

export const WIDGET_CSP = widgetCsp()

export function injectBridge(html: string): string {
const tag = '<script src="/fremkit.js"></script>'

const i = html.search(/<head[^>]*>/i)
if (i >= 0) {
const end = html.indexOf('>', i) + 1
return html.slice(0, end) + BRIDGE_TAG + html.slice(end)
return html.slice(0, end) + tag + html.slice(end)
}
return BRIDGE_TAG + html
return tag + html
}

export async function widgetRoutes(app: FastifyInstance, opts: { catalog: WidgetCatalog; store: ConfigStore }): Promise<void> {
export async function widgetRoutes(app: FastifyInstance, opts: { catalog: WidgetCatalog; store: ConfigStore; port?: number; dev?: boolean }): Promise<void> {
const bridge = await readFile(BRIDGE_PATH, 'utf8')
const csp = widgetCsp(opts.port, opts.dev)

app.get('/fremkit.js', async (_req, reply) => reply.type('application/javascript; charset=utf-8').send(bridge))

Expand Down Expand Up @@ -101,7 +111,7 @@ export async function widgetRoutes(app: FastifyInstance, opts: { catalog: Widget
const rel = req.params['*'] || 'index.html'
// On every answer, not just the entry point: a widget's second HTML file is the same
// untrusted code, and on a case-insensitive filesystem so is `Index.html`.
reply.header('content-security-policy', WIDGET_CSP)
reply.header('content-security-policy', csp)
// The folder rather than the root: a widget may be a built-in or one the user installed, and
// which of the two owns an id is the catalogue's answer, decided once at scan time.
const folder = opts.catalog.folderOf(id)
Expand Down
35 changes: 34 additions & 1 deletion server/test/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { mkdtemp, mkdir, writeFile, readFile, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { buildApp } from '../src/app.js'
import { WIDGET_CSP } from '../src/widgets/routes.js'
import { WIDGET_CSP, widgetCsp } from '../src/widgets/routes.js'
import { BYTE_ROUTES, isByteRoute } from '../src/http/headers.js'
import { degradedMessage } from '../src/config/routes.js'
import { defaultLocale } from '../src/config/schema.js'
Expand Down Expand Up @@ -161,6 +161,39 @@ describe('widget routes', () => {
expect(res.body).toContain('<head><script src="/fremkit.js"></script>')
expect(res.body).toContain('hi')
})
it('allows the bridge and a widget-owned relative script in an opaque frame', async () => {
await writeFile(join(dir, 'widgets', 'clock', 'index.html'),
'<html><head><script src="./app.js"></script></head><body>hi</body></html>')
await writeFile(join(dir, 'widgets', 'clock', 'app.js'), 'window.widgetLoaded = true')
const res = await app.inject({ url: '/widgets/clock/index.html' })
expect(res.body).toContain('<script src="/fremkit.js"></script>')
expect(res.body).toContain('<script src="./app.js"></script>')
expect(res.headers['content-security-policy']).toContain("script-src 'self' http://127.0.0.1:4242")
expect((await app.inject({ url: '/fremkit.js' })).statusCode).toBe(200)
expect((await app.inject({ url: '/widgets/clock/app.js' })).body).toBe('window.widgetLoaded = true')
})
it('scopes explicit subresource origins to the server port and development proxy', () => {
const csp = widgetCsp(4301, true)
for (const directive of ['script-src', 'style-src', 'img-src', 'font-src', 'media-src']) {
const line = csp.split('; ').find((part) => part.startsWith(directive))
expect(line).toContain('http://127.0.0.1:4301')
expect(line).toContain('http://localhost:5173')
expect(line).not.toContain('[::1]')
expect(line).not.toContain('http://127.0.0.1:4242')
}
expect(widgetCsp(4301)).not.toContain(':5173')
})
it('serves a second checkout with its own widget origin', async () => {
const other = await buildApp({ dataDir: join(dir, 'data'), widgetsDir: join(dir, 'widgets'), port: 4301 })
try {
const res = await other.inject({ url: '/widgets/clock/index.html', headers: { host: '127.0.0.1:4301' } })
expect(res.statusCode).toBe(200)
expect(res.headers['content-security-policy']).toBe(widgetCsp(4301))
expect(res.headers['content-security-policy']).not.toContain(':4242')
} finally {
await other.close()
}
})
it('sandboxes a widget however it is reached', async () => {
// Opening a widget top-level, or as a second HTML file, or as Index.html on a
// case-insensitive filesystem: all the same untrusted code, all the same header.
Expand Down
Loading