Skip to content

The agent that grows with you

fix(desktop): preview-script grants hold across windows and removals

Teknium55f3e384240e
diff --git a/apps/desktop/src/app/capabilities/plugins/plugin-page-access.test.tsx b/apps/desktop/src/app/capabilities/plugins/plugin-page-access.test.tsx
index 585dc69c187..4574f2f77df 100644
--- a/apps/desktop/src/app/capabilities/plugins/plugin-page-access.test.tsx
+++ b/apps/desktop/src/app/capabilities/plugins/plugin-page-access.test.tsx
@@ -6,7 +6,10 @@ import { $previewScriptGrants, ensurePreviewScriptConsent, grantPreviewScript }
import { PluginPageAccess } from './plugin-page-access'
-beforeEach(() => $previewScriptGrants.set({}))
+beforeEach(() => {
+ window.localStorage.clear()
+ $previewScriptGrants.set({})
+})
afterEach(cleanup)
describe('PluginPageAccess', () => {
diff --git a/apps/desktop/src/app/capabilities/plugins/plugin-page-access.tsx b/apps/desktop/src/app/capabilities/plugins/plugin-page-access.tsx
index 267222a827f..c40894de1f9 100644
--- a/apps/desktop/src/app/capabilities/plugins/plugin-page-access.tsx
+++ b/apps/desktop/src/app/capabilities/plugins/plugin-page-access.tsx
@@ -11,7 +11,7 @@ import { Pill } from '../../settings/primitives'
interface PluginPageAccessProps {
/** The Desktop half of the package; absent for agent-only packages. */
- plugin?: Pick<PluginRecord, 'capabilities' | 'id'>
+ plugin?: null | Pick<PluginRecord, 'capabilities' | 'id'>
pluginName: string
}
@@ -52,7 +52,6 @@ export function PluginPageAccess({ plugin, pluginName }: PluginPageAccessProps)
revokePreviewScript(pluginId, origin)
notify({ kind: 'info', message: copy.previewScriptRevoked(pluginName, origin) })
}}
- title={copy.previewScriptRevoke(origin)}
type="button"
>
<Codicon name="close" size="0.7rem" />
diff --git a/apps/desktop/src/app/contrib/plugin-preview-consent-dialog.test.tsx b/apps/desktop/src/app/contrib/plugin-preview-consent-dialog.test.tsx
index 1a9bdf995e5..8939747b0b8 100644
--- a/apps/desktop/src/app/contrib/plugin-preview-consent-dialog.test.tsx
+++ b/apps/desktop/src/app/contrib/plugin-preview-consent-dialog.test.tsx
@@ -11,6 +11,7 @@ import {
import { PluginPreviewConsentDialog } from './plugin-preview-consent-dialog'
beforeEach(() => {
+ window.localStorage.clear()
$previewScriptGrants.set({})
$previewScriptConsentQueue.set([])
})
diff --git a/apps/desktop/src/contrib/plugin-preview.test.ts b/apps/desktop/src/contrib/plugin-preview.test.ts
index 87583ff9138..8058fd7aeb1 100644
--- a/apps/desktop/src/contrib/plugin-preview.test.ts
+++ b/apps/desktop/src/contrib/plugin-preview.test.ts
@@ -6,6 +6,7 @@ import {
$previewScriptConsentQueue,
$previewScriptGrants,
answerPreviewScriptConsent,
+ forgetPluginPreviewAccess,
grantPreviewScript,
revokePreviewScript
} from '@/store/plugin-preview-grants'
@@ -15,6 +16,7 @@ import { createPluginContext } from './plugin'
import { dropPlugin, publishPlugin } from './plugins-store'
const CAPABILITY = 'preview.executeJavaScript'
+const GRANTS_KEY = 'hermes.desktop.pluginPreviewScriptGrants.v1'
// A stand-in guest page: evaluates the injected source the way the webview
// does (script completion value) against a page whose origin the test moves.
@@ -166,6 +168,59 @@ describe('ctx.preview.executeJavaScript', () => {
expect($previewScriptConsentQueue.get()).toEqual([])
})
+ it("honours a revoke made in another window instead of this window's cached list", async () => {
+ openPage()
+ const { ctx, id } = pluginWith([CAPABILITY])
+
+ grantPreviewScript(id, 'https://mail.example.com')
+ // Another window revoked it: same localStorage, this window's atom untouched.
+ window.localStorage.setItem(GRANTS_KEY, '{}')
+ void ctx.preview.executeJavaScript('document.title').catch(() => {})
+
+ await expect.poll(() => $previewScriptConsentQueue.get().length).toBe(1)
+ expect(userCodeRuns()).toBe(0)
+
+ window.dispatchEvent(new StorageEvent('storage', { key: GRANTS_KEY }))
+ expect($previewScriptGrants.get()).toEqual({})
+ })
+
+ it("a grant in this window does not resurrect another window's revoke", () => {
+ const { id } = pluginWith([CAPABILITY])
+
+ grantPreviewScript(id, 'https://mail.example.com')
+ window.localStorage.setItem(GRANTS_KEY, '{}')
+ grantPreviewScript(id, 'https://docs.example.com')
+
+ expect(JSON.parse(window.localStorage.getItem(GRANTS_KEY)!)).toEqual({ [id]: ['https://docs.example.com'] })
+ })
+
+ it('forgetting a removed plugin drops its grants and refuses its pending prompt', async () => {
+ openPage()
+ const { ctx, id } = pluginWith([CAPABILITY])
+
+ grantPreviewScript(id, 'https://docs.example.com')
+ const pending = ctx.preview.executeJavaScript('document.title')
+
+ await expect.poll(() => $previewScriptConsentQueue.get().length).toBe(1)
+ forgetPluginPreviewAccess(id)
+
+ await expect(pending).rejects.toThrow(/not allowed/)
+ expect($previewScriptConsentQueue.get()).toEqual([])
+ expect($previewScriptGrants.get()[id]).toBeUndefined()
+ expect(userCodeRuns()).toBe(0)
+ })
+
+ it("keeps a script's leading 'use strict' in effect behind the origin guard", async () => {
+ openPage()
+ const { ctx, id } = pluginWith([CAPABILITY])
+
+ grantPreviewScript(id, 'https://mail.example.com')
+
+ await expect(
+ ctx.preview.executeJavaScript("'use strict'; (function () { return this === undefined })()")
+ ).resolves.toBe(true)
+ })
+
it('rejects when no preview page is open', async () => {
const { ctx } = pluginWith([CAPABILITY])
diff --git a/apps/desktop/src/contrib/plugin-preview.ts b/apps/desktop/src/contrib/plugin-preview.ts
index 80446112053..bed8e635d39 100644
--- a/apps/desktop/src/contrib/plugin-preview.ts
+++ b/apps/desktop/src/contrib/plugin-preview.ts
@@ -41,11 +41,16 @@ export interface PluginPreview {
const ORIGIN_PROBE = 'window.location.origin'
-/** Prepends a statement, so the plugin's script keeps its completion value. */
+// A leading `'use strict'` directive must stay first or the script silently
+// leaves strict mode, so the guard goes right after it.
+const STRICT_PROLOGUE = /^\s*(['"])use strict\1[ \t]*(?:;|\r?\n|$)/
+
+/** Inserts a guard statement; the plugin's script keeps its completion value. */
function originGuarded(origin: string, code: string): string {
- const expected = JSON.stringify(origin)
+ const guard = `if (window.location.origin !== ${JSON.stringify(origin)}) { throw new Error('The preview page changed origin; script not run.') }\n`
+ const prologue = STRICT_PROLOGUE.exec(code)?.[0] ?? ''
- return `if (window.location.origin !== ${expected}) { throw new Error('The preview page changed origin; script not run.') }\n${code}`
+ return `${prologue}${prologue ? '\n' : ''}${guard}${code.slice(prologue.length)}`
}
async function runPreviewScript(pluginId: string, declared: boolean, code: unknown): Promise<unknown> {
diff --git a/apps/desktop/src/contrib/runtime-loader.ts b/apps/desktop/src/contrib/runtime-loader.ts
index 4946f0ab7d2..a872c9c7e66 100644
--- a/apps/desktop/src/contrib/runtime-loader.ts
+++ b/apps/desktop/src/contrib/runtime-loader.ts
@@ -37,7 +37,7 @@ import { atom } from 'nanostores'
import { isReadFileErrorResult } from '@/lib/desktop-fs'
import { installPluginSdk, sdkImportMap } from '@/sdk/runtime'
import { notifyError } from '@/store/notifications'
-import { revokePreviewScript } from '@/store/plugin-preview-grants'
+import { forgetPluginPreviewAccess } from '@/store/plugin-preview-grants'
import { trackGatewayEventDisposers } from './events'
import { createPluginContext, declaredCapabilities, type HermesPlugin } from './plugin'
@@ -965,11 +965,13 @@ async function scanDiskPlugins(reloadKnown = false): Promise<void> {
}
/** Forget a disk entry whose folder is gone: unload its registration, drop
- * its inventory rows, stop its file watch. */
+ * its inventory rows and its preview-script grants, stop its file watch. */
function retireDiskPlugin(file: string, record: DiskPlugin): void {
if (record.id) {
unloadRuntimePlugin(record.id)
dropPlugin(record.id)
+ // A later plugin reusing this id must ask the user again, never inherit.
+ forgetPluginPreviewAccess(record.id)
}
dropOriginRecord(record.origin, record)
@@ -1012,11 +1014,6 @@ export async function uninstallDiskPlugin(pluginId: string): Promise<{ ok: boole
retireDiskPlugin(file, record)
- // A later plugin reusing this id must ask the user again, never inherit.
- if (record.id) {
- revokePreviewScript(record.id)
- }
-
return { ok: true }
}
diff --git a/apps/desktop/src/store/plugin-preview-grants.ts b/apps/desktop/src/store/plugin-preview-grants.ts
index 101b7a1a140..fb559ba665b 100644
--- a/apps/desktop/src/store/plugin-preview-grants.ts
+++ b/apps/desktop/src/store/plugin-preview-grants.ts
@@ -1,6 +1,6 @@
import { atom } from 'nanostores'
-import { Codecs, persistentAtom } from '@/lib/persisted'
+import { readKey, writeKey } from '@/lib/storage'
/**
* USER GRANTS FOR `ctx.preview.executeJavaScript` — which plugin may run
@@ -42,11 +42,36 @@ function sanitizeGrants(value: unknown): PreviewScriptGrants {
return grants
}
-export const $previewScriptGrants = persistentAtom<PreviewScriptGrants>(
- 'hermes.desktop.pluginPreviewScriptGrants.v1',
- {},
- Codecs.json(sanitizeGrants)
-)
+const GRANTS_KEY = 'hermes.desktop.pluginPreviewScriptGrants.v1'
+
+// Every window that runs plugins shares this localStorage record, so it — not
+// a window's atom — is the source of truth: each check and each change reads
+// it fresh (a revoke in one window binds the others at once, and a grant in a
+// stale window cannot write a revoked origin back). The atom mirrors it for UI.
+function readStoredGrants(): PreviewScriptGrants {
+ const raw = readKey(GRANTS_KEY)
+
+ try {
+ return raw ? sanitizeGrants(JSON.parse(raw)) : {}
+ } catch {
+ return {}
+ }
+}
+
+export const $previewScriptGrants = atom<PreviewScriptGrants>(readStoredGrants())
+
+function commitGrants(next: PreviewScriptGrants): void {
+ writeKey(GRANTS_KEY, JSON.stringify(next))
+ $previewScriptGrants.set(next)
+}
+
+if (typeof window !== 'undefined') {
+ window.addEventListener('storage', event => {
+ if (event.key === GRANTS_KEY || event.key === null) {
+ $previewScriptGrants.set(readStoredGrants())
+ }
+ })
+}
/** "Don't allow" answers for this app run, as `${pluginId}\n${origin}`. */
const $sessionDenials = atom<ReadonlySet<string>>(new Set())
@@ -67,29 +92,22 @@ export function isGrantableOrigin(origin: string): boolean {
}
export function hasPreviewScriptGrant(pluginId: string, origin: string): boolean {
- return $previewScriptGrants.get()[pluginId]?.includes(origin) ?? false
+ return readStoredGrants()[pluginId]?.includes(origin) ?? false
}
export function grantPreviewScript(pluginId: string, origin: string): void {
- const grants = $previewScriptGrants.get()
+ const grants = readStoredGrants()
const current = grants[pluginId] ?? []
- if (!current.includes(origin)) {
- $previewScriptGrants.set({ ...grants, [pluginId]: [...current, origin] })
- }
+ commitGrants(current.includes(origin) ? grants : { ...grants, [pluginId]: [...current, origin] })
}
/** Revoke one origin, or every origin for the plugin when omitted. */
export function revokePreviewScript(pluginId: string, origin?: string): void {
- const { [pluginId]: current, ...rest } = $previewScriptGrants.get()
-
- if (!current) {
- return
- }
-
+ const { [pluginId]: current = [], ...rest } = readStoredGrants()
const kept = origin === undefined ? [] : current.filter(entry => entry !== origin)
- $previewScriptGrants.set(kept.length > 0 ? { ...rest, [pluginId]: kept } : rest)
+ commitGrants(kept.length > 0 ? { ...rest, [pluginId]: kept } : rest)
}
export interface PreviewScriptConsentRequest {
@@ -139,6 +157,28 @@ export function ensurePreviewScriptConsent(pluginId: string, pluginName: string,
return promise
}
+/**
+ * A plugin left (uninstalled, its folder retired): drop every grant it holds
+ * and refuse its open prompts, so a late "Allow" cannot re-grant a removed
+ * plugin and a later plugin reusing the id starts from nothing.
+ */
+export function forgetPluginPreviewAccess(pluginId: string): void {
+ revokePreviewScript(pluginId)
+
+ const queue = $previewScriptConsentQueue.get()
+
+ $previewScriptConsentQueue.set(queue.filter(entry => entry.pluginId !== pluginId))
+
+ for (const request of queue) {
+ if (request.pluginId === pluginId) {
+ const key = pairKey(request.pluginId, request.origin)
+
+ pending.get(key)?.resolve(false)
+ pending.delete(key)
+ }
+ }
+}
+
/** The dialog's answer for request `id`. Anything but an explicit allow —
* Esc, backdrop, the close button — arrives here as `false`. */
export function answerPreviewScriptConsent(id: number, allowed: boolean): void {