The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(plugins): authenticate Desktop plugin sockets on a local gateway
unsupportedpastels38ceae226d28
diff --git a/apps/desktop/electron/local-gateway.ts b/apps/desktop/electron/local-gateway.tsindex 7e791136827..c6a074aceb7 100644--- a/apps/desktop/electron/local-gateway.ts+++ b/apps/desktop/electron/local-gateway.ts@@ -269,11 +269,34 @@ export async function redialLocalGateway<TEndpoint, TResult>(deps: {}}-function dialNonce(url: string): string | null {+/** A fresh one-use local dial: mint `purpose` for the routed profile's home and hand it to+ * `prepare`, re-ensuring once when the cached owner is gone (`redialLocalGateway`). */+export function localGatewayDial<T extends { baseUrl: string; gatewayEndpoint?: GatewayEndpoint }>(opts: {+ ensure: () => Promise<T>+ forget: () => Promise<void> | void+ launchHome: string+ mint?: typeof mintLocalGatewayTicket+ prepare: (baseUrl: string, ticket: string) => string+ profile: string+ purpose?: 'interactive' | 'native-http'+}): Promise<string> {+ const { mint = mintLocalGatewayTicket, purpose = 'interactive' } = opts++ return redialLocalGateway({+ ensure: opts.ensure,+ forget: opts.forget,+ // A shared-primary descriptor answers for a sibling profile too: the ticket must name+ // THAT profile's home or its sessions are another owner's.+ use: async current => opts.prepare(current.baseUrl, await mint(await routedTicketEndpoint(current.gatewayEndpoint!, opts.profile, opts.launchHome), purpose))+ })+}++function dialOf(url: string): { nonce: string; origin: string; pathname: string } | null {try {const parsed = new URL(url)+ const nonce = parsed.searchParams.get('native_dial')- return parsed.pathname === '/api/ws' ? parsed.searchParams.get('native_dial') : null+ return nonce ? { nonce, origin: parsed.origin, pathname: parsed.pathname } : null} catch {return null}@@ -281,35 +304,50 @@ function dialNonce(url: string): string | null {// A one-use ticket crosses private IPC, then leaves the URL before dialing.// Public descriptors and persisted connection state never contain credentials.+// A plugin socket's native-http grant never enters a URL at all: main attaches+// it as the header its REST twin sends, to that one dial only.export function createLocalGatewayDials() {- const pending = new Map<string, { ticket: string; webContentsId: number; expires: number }>()+ const pending = new Map<string, { ticket: string; webContentsId: number; expires: number; origin: string; pathname: string; header: boolean }>()- return {- prepare(origin: string, ticket: string, webContentsId: number) {- for (const [key, value] of pending) {if (value.expires <= Date.now()) {pending.delete(key)}}+ const reserve = (url: URL, ticket: string, webContentsId: number, header: boolean) => {+ for (const [key, value] of pending) {if (value.expires <= Date.now()) {pending.delete(key)}}- if (pending.size >= 100) {throw new Error('Too many pending gateway dials')}- // Keyed by the one-use nonce, not the full URL: a loopback proxy the app dials- // through (tests, tunnels) rewrites host:port but carries the query through.- const nonce = crypto.randomUUID()- const url = `${origin.replace(/^http/, 'ws')}/api/ws?native_dial=${nonce}`- pending.set(nonce, { ticket, webContentsId, expires: Date.now() + 25_000 })+ if (pending.size >= 100) {throw new Error('Too many pending gateway dials')}+ // Keyed by the one-use nonce, not the full URL: a loopback proxy the app dials+ // through (tests, tunnels) rewrites host:port but carries the query through.+ // A header grant is the exception: main attaches it, so it is bound to its origin.+ const nonce = crypto.randomUUID()+ url.searchParams.set('native_dial', nonce)+ pending.set(nonce, { ticket, webContentsId, expires: Date.now() + 25_000, origin: url.origin, pathname: url.pathname, header })- return `${url}&ticket=${encodeURIComponent(ticket)}`+ return url.toString()+ }++ return {+ prepare(origin: string, ticket: string, webContentsId: number) {+ return `${reserve(new URL(`${origin.replace(/^http/, 'ws')}/api/ws`), ticket, webContentsId, false)}&ticket=${encodeURIComponent(ticket)}`+ },+ /** `path`: an `/api/plugins/<id>/...` path (query allowed) the caller already validated. */+ preparePlugin(origin: string, path: string, ticket: string, webContentsId: number) {+ return reserve(new URL(path, origin.replace(/^http/, 'ws')), ticket, webContentsId, true)},headers(details: { url: string; webContentsId?: number; resourceType: string; requestHeaders?: Record<string, string> }) {- const nonce = dialNonce(details.url)- const grant = nonce ? pending.get(nonce) : undefined+ const dial = dialOf(details.url)+ const grant = dial ? pending.get(dial.nonce) : undefined++ if (!dial || !grant || grant.pathname !== dial.pathname || grant.webContentsId !== details.webContentsId+ || details.resourceType !== 'webSocket' || (grant.header && grant.origin !== dial.origin)) {return null}- if (!nonce || !grant || grant.webContentsId !== details.webContentsId || details.resourceType !== 'webSocket') {return null}- pending.delete(nonce)+ pending.delete(dial.nonce)if (grant.expires <= Date.now()) {return null}const headers = { ...details.requestHeaders }- for (const key of Object.keys(headers)) {if (key.toLowerCase() === 'origin') {delete headers[key]}}+ for (const key of Object.keys(headers)) {+ if (['origin', 'x-hermes-gateway-ticket'].includes(key.toLowerCase())) {delete headers[key]}+ }- return headers+ return grant.header ? { ...headers, 'X-Hermes-Gateway-Ticket': grant.ticket } : headers}}}diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 7736c8f476b..9bbd2585378 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -1,8 +1,9 @@import { type ChildProcess, execFileSync, spawn } from 'node:child_process'import type { GatewayEndpoint } from './local-gateway'-import { configurePythonGatewayTicketClient, createLocalGatewayDials, createStaleGatewayRestarter, ensureLocalGateway, gatewayOwnerProfile, mintLocalGatewayTicket, nativeGatewayHttpHeaders, redialLocalGateway, routedTicketEndpoint, runGatewayEnsure } from './local-gateway'+import { configurePythonGatewayTicketClient, createLocalGatewayDials, createStaleGatewayRestarter, ensureLocalGateway, gatewayOwnerProfile, localGatewayDial, nativeGatewayHttpHeaders, redialLocalGateway, runGatewayEnsure } from './local-gateway'import { closeGatewayTicketBridges, createGatewayTicketResolver } from './local-gateway-python'+import { createPluginWsUrlHandler } from './plugin-ws-url'const localGatewayDials = createLocalGatewayDials()configurePythonGatewayTicketClient(createGatewayTicketResolver(async () => ensureRuntime(await resolveHermesBackend([]), () => undefined), resolveHermesCwd))@@ -7898,17 +7899,8 @@ async function freshGatewayWsUrl(profile, webContentsId) {const connection = await ensureBackend(profile)if (connection.gatewayEndpoint) {- return redialLocalGateway({- ensure: () => ensureBackend(profile),- forget: () => forgetLocalGatewayDescriptor(profile),- use: async current => {- // A shared-primary descriptor answers for a sibling profile too: the socket's- // ticket must name THAT profile's home or its sessions are another owner's.- const ticket = await mintLocalGatewayTicket(await routedTicketEndpoint(current.gatewayEndpoint, String(profile ?? ''), HERMES_HOME))-- return localGatewayDials.prepare(current.baseUrl, ticket, webContentsId)- }- })+ return localGatewayDial({ ensure: () => ensureBackend(profile), forget: () => forgetLocalGatewayDescriptor(profile), launchHome: HERMES_HOME,+ prepare: (baseUrl, ticket) => localGatewayDials.prepare(baseUrl, ticket, webContentsId), profile: String(profile ?? '') })}if (connection.authMode === 'oauth') {@@ -15426,21 +15418,19 @@ ipcMain.handle('hermes:gateway:ws-url-for', async (_event, payload) => {const connection = await ensureRegistryBackend(payload?.connectionId, payload?.profile)if (connection.gatewayEndpoint) {- return redialLocalGateway({- ensure: () => ensureRegistryBackend(payload?.connectionId, payload?.profile),- forget: () => forgetRegistryLocalGatewayDescriptor(payload?.connectionId, payload?.profile),- use: async (current: typeof connection) => {- const ticket = await mintLocalGatewayTicket(await routedTicketEndpoint(current.gatewayEndpoint, String(payload?.profile ?? ''), HERMES_HOME))-- return localGatewayDials.prepare(current.baseUrl, ticket, _event.sender.id)- }- })+ return localGatewayDial({ ensure: () => ensureRegistryBackend(payload?.connectionId, payload?.profile), launchHome: HERMES_HOME,+ forget: () => forgetRegistryLocalGatewayDescriptor(payload?.connectionId, payload?.profile), profile: String(payload?.profile ?? ''),+ prepare: (baseUrl, ticket) => localGatewayDials.prepare(baseUrl, ticket, _event.sender.id) })}return registryGatewayWsUrlHandler(payload)})})+const pluginWsUrl = createPluginWsUrlHandler({ ensureBackend, ensureRegistryBackend, forgetLocalGatewayDescriptor,+ forgetRegistryLocalGatewayDescriptor, launchHome: HERMES_HOME, prepare: localGatewayDials.preparePlugin })+ipcMain.handle('hermes:plugin:ws-url', (event, payload) => pluginWsUrl(payload ?? {}, event.sender.id))+// Transactional update for a Desktop-managed SSH install. Unlike the generic// fleet fan-out below, this path owns the remote serve lifecycle: it gates new// dials, drains only exact Desktop-owned processes, runs the launcher outsidediff --git a/apps/desktop/electron/plugin-ws-url.test.ts b/apps/desktop/electron/plugin-ws-url.test.tsnew file mode 100644index 00000000000..4f6ede66e49--- /dev/null+++ b/apps/desktop/electron/plugin-ws-url.test.ts@@ -0,0 +1,91 @@+import { expect, test, vi } from 'vitest'++import { createLocalGatewayDials, type GatewayEndpoint } from './local-gateway'+import { createPluginWsUrlHandler, pluginWsPath } from './plugin-ws-url'++// PLG-1: a local gateway's plugin socket rides the native-http grant its REST twin uses. The grant+// is attached as a header to the one dial main prepared, never placed in the renderer's URL.++const endpoint = { api_origin: 'http://127.0.0.1:9', control_home: null, profile_id: '/home/u/.hermes' } as unknown as GatewayEndpoint++test('a plugin dial carries the grant header once and never in its URL', () => {+ const dials = createLocalGatewayDials()+ const url = dials.preparePlugin('http://127.0.0.1:9', '/api/plugins/kanban/events?board=b', 'grant-1', 7)+ const parsed = new URL(url)++ expect(url).not.toContain('grant-1')+ expect(parsed.pathname).toBe('/api/plugins/kanban/events')+ expect(parsed.searchParams.get('board')).toBe('b')+ const details = { url, webContentsId: 7, resourceType: 'webSocket', requestHeaders: { Origin: 'file://', 'x-hermes-gateway-ticket': 'forged' } }+ expect(dials.headers({ ...details, webContentsId: 8 })).toBeNull()+ // A different path carrying the same nonce gets nothing.+ expect(dials.headers({ ...details, url: url.replace('/kanban/events', '/other/events') })).toBeNull()+ // The same nonce and path aimed at another server, scheme or port gets nothing.+ for (const elsewhere of ['ws://evil.example:9', 'wss://127.0.0.1:9', 'ws://127.0.0.1:10', 'ws://localhost:9']) {+ expect(dials.headers({ ...details, url: url.replace('ws://127.0.0.1:9', elsewhere) })).toBeNull()+ }++ expect(dials.headers(details)).toEqual({ 'X-Hermes-Gateway-Ticket': 'grant-1' })+ expect(dials.headers(details)).toBeNull()+})++test('the gateway socket dial still carries no grant header', () => {+ const dials = createLocalGatewayDials()+ const dial = new URL(dials.prepare('http://127.0.0.1:9', 'interactive-1', 7))+ dial.searchParams.delete('ticket')++ expect(dials.headers({ url: dial.toString(), webContentsId: 7, resourceType: 'webSocket', requestHeaders: { Origin: 'file://' } })).toEqual({})+})++test('plugin socket paths stay inside the plugin namespace', () => {+ expect(pluginWsPath('kanban', '/events?board=a/../b')).toBe('/api/plugins/kanban/events?board=a/../b')++ for (const [id, path] of [['kanban', '/../../api/ws'], ['kanban', 'events'], ['..', '/x'], ['a/b', '/x'], ['kanban', '/a\\b'], ['kanban', '/./x'], [1, '/x'], ['kanban', null]]) {+ expect(() => pluginWsPath(id, path)).toThrow()+ }+})++test('encoded, dot-segment and backslash paths stay inside the plugin namespace through URL parsing', () => {+ for (const path of ['/%2e%2e/other/events', '/.%2e/other/events', '/%2E%2E/%2e%2e/api/ws', '/x/%2e%2e/%2e%2e/other/events',+ '/..%2fother/events', '/%2f..%2fother', '/a%2Fb', '/%5c..%5cother', '/%252e%252e/other', '/%2e/x', '/a/%2e%2e', '/%zz']) {+ expect(() => pluginWsPath('kanban', path), path).toThrow('Invalid plugin socket path')+ }++ // What the dial records and attaches the grant to is the path that was checked.+ const path = pluginWsPath('kanban', '/boards/b%20c/events?q=%2e%2e%2f')+ const dials = createLocalGatewayDials()+ const url = new URL(dials.preparePlugin('http://127.0.0.1:9', path, 'grant-3', 7))+ expect(url.pathname).toBe('/api/plugins/kanban/boards/b%20c/events')+ expect(path).toBe(`${url.pathname}?q=%2e%2e%2f`)+})++test('mints a native-http grant for a local gateway and null elsewhere', async () => {+ const mint = vi.fn(async () => 'grant-2')+ const prepare = vi.fn((origin: string, path: string, ticket: string, id: number) => `${origin}|${path}|${ticket}|${id}`)++ const handler = createPluginWsUrlHandler({+ ensureBackend: vi.fn(async () => ({ baseUrl: 'http://127.0.0.1:9', gatewayEndpoint: endpoint })),+ ensureRegistryBackend: vi.fn(async () => ({ baseUrl: 'https://remote.invalid' })),+ forgetLocalGatewayDescriptor: vi.fn(),+ forgetRegistryLocalGatewayDescriptor: vi.fn(),+ launchHome: '/home/u/.hermes',+ mint,+ prepare+ })++ await expect(handler({ path: '/events', pluginId: 'kanban', profile: 'default' }, 3)).resolves.toBe('http://127.0.0.1:9|/api/plugins/kanban/events|grant-2|3')+ expect(mint).toHaveBeenCalledWith(expect.objectContaining({ profile_id: '/home/u/.hermes' }), 'native-http')+ await expect(handler({ connectionId: 'homelab', path: '/events', pluginId: 'kanban' }, 3)).resolves.toBeNull()+ await expect(handler({ path: '/../ws', pluginId: 'kanban' }, 3)).rejects.toThrow('Invalid plugin socket path')+ await expect(handler({ path: '/%2e%2e/other/events', pluginId: 'kanban' }, 3)).rejects.toThrow('Invalid plugin socket path')+ expect(mint).toHaveBeenCalledTimes(1)+})++test('the shared local dial keeps the gateway socket on an interactive grant', async () => {+ const { localGatewayDial } = await import('./local-gateway')+ const mint = vi.fn(async () => 'interactive-2')+ const url = await localGatewayDial({ ensure: async () => ({ baseUrl: 'http://127.0.0.1:9', gatewayEndpoint: endpoint }), forget: vi.fn(), launchHome: '/home/u/.hermes', mint, prepare: (baseUrl, ticket) => `${baseUrl}|${ticket}`, profile: '' })++ expect(url).toBe('http://127.0.0.1:9|interactive-2')+ expect(mint).toHaveBeenCalledWith(expect.objectContaining({ profile_id: '/home/u/.hermes' }), 'interactive')+})diff --git a/apps/desktop/electron/plugin-ws-url.ts b/apps/desktop/electron/plugin-ws-url.tsnew file mode 100644index 00000000000..adfc108b946--- /dev/null+++ b/apps/desktop/electron/plugin-ws-url.ts@@ -0,0 +1,87 @@+import type { mintLocalGatewayTicket } from './local-gateway';+import { type GatewayEndpoint, localGatewayDial } from './local-gateway'++/** What the renderer's `pluginSocket` asks for: its plugin namespace, the path under it, and the+ * (connectionId, profile) route every other plugin call resolves through. */+export interface PluginWsUrlRequest {+ connectionId?: unknown+ path?: unknown+ pluginId?: unknown+ profile?: unknown+}++interface ResolvedBackend {+ baseUrl: string+ gatewayEndpoint?: GatewayEndpoint+}++/** A path segment as the server reads it (decoded once), or null when it is not valid encoding. */+function decodedSegment(segment: string): null | string {+ try {+ return decodeURIComponent(segment)+ } catch {+ return null+ }+}++/** `/api/plugins/<pluginId><path>` as the dial will carry it, or throw. The namespace is the+ * boundary: the renderer's own check is not trusted here, so a traversal or another core route can+ * never get a grant. Segments are checked decoded (`%2e%2e`, `%2f`, `%5c`, and `%25` double+ * encoding are refused), and the result is what the URL parser makes of it. */+export function pluginWsPath(pluginId: unknown, path: unknown): string {+ if (typeof pluginId !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(pluginId) || pluginId.includes('..')) {+ throw new Error('Invalid plugin id')+ }++ const prefix = `/api/plugins/${pluginId}/`++ const url = typeof path === 'string' && path.startsWith('/') && path.length <= 2048 && !/[#\\]/.test(path)+ && !path.split('?', 1)[0].split('/').some(segment => {+ const decoded = decodedSegment(segment)++ return decoded === null || decoded === '.' || decoded === '..' || /[/\\%]/.test(decoded)+ })+ ? new URL(`${prefix.slice(0, -1)}${path}`, 'ws://plugin.invalid')+ : null++ if (!url?.pathname.startsWith(prefix)) {+ throw new Error('Invalid plugin socket path')+ }++ return `${url.pathname}${url.search}`+}++/** A fresh one-use plugin socket URL for a local gateway, null for any other backend (those keep+ * the renderer's token path). The grant is the `native-http` one the plugin's REST calls already+ * carry, minted for the routed profile and attached by `prepare` to that one dial as a header.+ * The route resolves exactly as `hermes:gateway:ws-url(-for)` does: registry-scoped when the+ * renderer names a connection, else the profile-keyed local pool. */+export function createPluginWsUrlHandler(deps: {+ ensureBackend: (profile: unknown) => Promise<ResolvedBackend>+ ensureRegistryBackend: (connectionId: unknown, profile: unknown) => Promise<ResolvedBackend>+ forgetLocalGatewayDescriptor: (profile: unknown) => Promise<void> | void+ forgetRegistryLocalGatewayDescriptor: (connectionId: unknown, profile: unknown) => Promise<void> | void+ launchHome: string+ mint?: typeof mintLocalGatewayTicket+ prepare: (origin: string, path: string, ticket: string, webContentsId: number) => string+}) {+ return async (request: PluginWsUrlRequest, webContentsId: number): Promise<null | string> => {+ const path = pluginWsPath(request?.pluginId, request?.path)+ const { connectionId, profile } = request+ const ensure = () => (connectionId ? deps.ensureRegistryBackend(connectionId, profile) : deps.ensureBackend(profile))++ if (!(await ensure()).gatewayEndpoint) {+ return null+ }++ return localGatewayDial({+ ensure,+ forget: () => (connectionId ? deps.forgetRegistryLocalGatewayDescriptor(connectionId, profile) : deps.forgetLocalGatewayDescriptor(profile)),+ launchHome: deps.launchHome,+ mint: deps.mint,+ prepare: (baseUrl, ticket) => deps.prepare(baseUrl, path, ticket, webContentsId),+ profile: typeof profile === 'string' ? profile : '',+ purpose: 'native-http'+ })+ }+}diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.tsindex 53997ec7326..3fb2c6bc886 100644--- a/apps/desktop/electron/preload.ts+++ b/apps/desktop/electron/preload.ts@@ -46,6 +46,8 @@ contextBridge.exposeInMainWorld('hermesDesktop', {// Registry-scoped fresh WS URL: { connectionId, profile } → result shape of// getGatewayWsUrl, minted against that connection's backend.getGatewayWsUrlFor: payload => ipcRenderer.invoke('hermes:gateway:ws-url-for', payload),+ // { connectionId, profile, pluginId, path } → one-use local plugin socket URL, or null.+ getPluginWsUrl: payload => ipcRenderer.invoke('hermes:plugin:ws-url', payload),// Union agent roster across every registered connection.getAgentRoster: () => ipcRenderer.invoke('hermes:agents:roster'),openSessionWindow: (sessionId, opts) => ipcRenderer.invoke('hermes:window:openSession', sessionId, opts),diff --git a/apps/desktop/src/api/plugins.test.ts b/apps/desktop/src/api/plugins.test.tsindex 9a067521079..4e2573c18a4 100644--- a/apps/desktop/src/api/plugins.test.ts+++ b/apps/desktop/src/api/plugins.test.ts@@ -1,8 +1,10 @@+import { RECONNECT_STABLE_OPEN_MS } from '@hermes/shared'import { afterEach, describe, expect, it, vi } from 'vitest'import { setApiRequestConnection, setApiRequestProfile } from '@/hermes'+import { RECONNECT_ATTEMPT_TIMEOUT_MS } from '@/lib/with-timeout'-import { activeConnection } from './plugins'+import { activeConnection, pluginSocket } from './plugins'// desktop.getConnection/getConnectionFor are IPC round-trips into the main// process with no timeout of their own (#93454). A wedged main-process@@ -47,3 +49,153 @@ describe('activeConnection connection timeout (#93454)', () => {await pending})})++// PLG-1: a local gateway Desktop has no static token (authMode 'native'). Its plugin socket must+// dial the one-use URL main mints (the native grant rides a header, never the URL), and a socket+// that keeps being refused must stop instead of re-dialing an idle gateway forever.+describe('pluginSocket credentials and refusals (PLG-1)', () => {+ class FakeSocket {+ static all: FakeSocket[] = []+ readonly at = Date.now()+ onclose: (() => void) | null = null+ onmessage: ((event: { data: unknown }) => void) | null = null+ onopen: (() => void) | null = null+ constructor(readonly url: string) {+ FakeSocket.all.push(this)+ }+ close() {+ this.onclose?.()+ }+ }++ const desktop = (connection: Record<string, unknown>, minted: null | string = 'ws://127.0.0.1:9/api/plugins/kanban/events?native_dial=n') => {+ const getPluginWsUrl = vi.fn(async () => minted)+ Object.defineProperty(window, 'hermesDesktop', {+ configurable: true,+ value: { getConnection: vi.fn(async () => connection), getPluginWsUrl }+ })++ return getPluginWsUrl+ }++ const local = { authMode: 'native', baseUrl: 'http://127.0.0.1:9', token: '' }++ // Refuse the latest dial (closed before it ever opened) and let the backoff fire.+ const refuseLatest = async () => {+ FakeSocket.all.at(-1)?.onclose?.()+ await vi.advanceTimersByTimeAsync(31_000)+ }++ afterEach(() => {+ FakeSocket.all = []+ vi.restoreAllMocks()+ vi.unstubAllGlobals()+ setApiRequestProfile(null)+ Reflect.deleteProperty(window, 'hermesDesktop')+ vi.useRealTimers()+ })++ it('dials the minted local-gateway URL, never an empty ?token=', async () => {+ vi.useFakeTimers()+ vi.stubGlobal('WebSocket', FakeSocket)+ setApiRequestProfile('coder')+ const mint = desktop(local)++ const dispose = pluginSocket('kanban', '/events?board=b', () => undefined)+ await vi.advanceTimersByTimeAsync(0)++ expect(mint).toHaveBeenCalledWith({ connectionId: null, path: '/events?board=b', pluginId: 'kanban', profile: 'coder' })+ expect(FakeSocket.all.map(socket => socket.url)).toEqual(['ws://127.0.0.1:9/api/plugins/kanban/events?native_dial=n'])+ dispose()+ })++ it('stays on polling when main mints no local URL', async () => {+ vi.useFakeTimers()+ vi.stubGlobal('WebSocket', FakeSocket)+ desktop(local, null)++ const dispose = pluginSocket('kanban', '/events', () => undefined)+ await vi.advanceTimersByTimeAsync(120_000)++ expect(FakeSocket.all).toHaveLength(0)+ dispose()+ })++ it('stops re-dialing after repeated refusals', async () => {+ vi.useFakeTimers()+ vi.stubGlobal('WebSocket', FakeSocket)+ const mint = desktop(local)++ const dispose = pluginSocket('kanban', '/events', () => undefined)+ await vi.advanceTimersByTimeAsync(0)++ for (let i = 0; i < 20; i += 1) {+ await refuseLatest()+ }++ expect(FakeSocket.all).toHaveLength(5)+ expect(mint).toHaveBeenCalledTimes(5)+ dispose()+ })++ it('keeps reconnecting a socket that stayed open before it dropped', async () => {+ vi.useFakeTimers()+ vi.stubGlobal('WebSocket', FakeSocket)+ desktop({ authMode: 'token', baseUrl: 'http://remote.invalid', token: 'tok' })++ const dispose = pluginSocket('kanban', '/events', () => undefined)+ await vi.advanceTimersByTimeAsync(0)++ for (let i = 0; i < 10; i += 1) {+ FakeSocket.all.at(-1)?.onopen?.()+ await vi.advanceTimersByTimeAsync(RECONNECT_STABLE_OPEN_MS)+ await refuseLatest()+ }++ expect(FakeSocket.all).toHaveLength(11)+ expect(FakeSocket.all[0].url).toBe('ws://remote.invalid/api/plugins/kanban/events?token=tok')+ dispose()+ })++ // A server that accepts and then closes at once (Kanban on an archived board) must back off+ // and stop like a refusal, not re-dial at the first backoff step forever.+ it('backs off and stops on sockets that open and close at once', async () => {+ vi.useFakeTimers()+ vi.stubGlobal('WebSocket', FakeSocket)+ vi.spyOn(Math, 'random').mockReturnValue(0.5)+ desktop(local)++ const dispose = pluginSocket('kanban', '/events', () => undefined)+ await vi.advanceTimersByTimeAsync(0)+ const delays: number[] = []++ for (let i = 0; i < 20; i += 1) {+ const socket = FakeSocket.all.at(-1)!+ socket.onopen?.()+ const closedAt = Date.now()+ socket.onclose?.()+ await vi.advanceTimersByTimeAsync(31_000)++ if (FakeSocket.all.at(-1) !== socket) {delays.push(FakeSocket.all.at(-1)!.at - closedAt)}+ }++ expect(FakeSocket.all).toHaveLength(5)+ expect(delays).toEqual([250, 500, 1000, 2000])+ dispose()+ })++ // getPluginWsUrl is an IPC round-trip into main with no deadline of its own.+ it('re-dials when the local URL mint never answers', async () => {+ vi.useFakeTimers()+ vi.stubGlobal('WebSocket', FakeSocket)+ const mint = desktop(local)+ mint.mockImplementationOnce(() => new Promise(() => undefined))++ const dispose = pluginSocket('kanban', '/events', () => undefined)+ await vi.advanceTimersByTimeAsync(RECONNECT_ATTEMPT_TIMEOUT_MS + 31_000)++ expect(mint).toHaveBeenCalledTimes(2)+ expect(FakeSocket.all).toHaveLength(1)+ dispose()+ })+})diff --git a/apps/desktop/src/api/plugins.ts b/apps/desktop/src/api/plugins.tsindex d22d5e9d4ec..5b873e9d2c3 100644--- a/apps/desktop/src/api/plugins.ts+++ b/apps/desktop/src/api/plugins.ts@@ -1,4 +1,4 @@-import { reconnectBackoffDelayMs } from '@hermes/shared'+import { isStableOpen, reconnectBackoffDelayMs } from '@hermes/shared'import type { HermesConnection } from '@/global'import { RECONNECT_ATTEMPT_TIMEOUT_MS, withTimeout } from '@/lib/with-timeout'@@ -86,18 +86,63 @@ export async function pluginRest<T>(pluginId: string, path: string, opts: Plugin})}+/** Consecutive dials that never stayed open before the socket gives up for good.+ * Every attempt is gateway traffic that keeps an idle-exit gateway awake. */+const MAX_REFUSED_PLUGIN_DIALS = 5++/** The URL a plugin socket dials, or null to stay on polling. A local gateway+ * (`authMode: 'native'`, no static token) gets a fresh one-use URL from main:+ * its native grant rides a request header main attaches to that one dial. */+async function pluginSocketUrl(connection: HermesConnection, pluginId: string, suffix: string): Promise<null | string> {+ if (connection.authMode === 'native') {+ const mint = window.hermesDesktop.getPluginWsUrl++ // An IPC round-trip with no deadline of its own, bounded like activeConnection().+ return mint+ ? withTimeout(+ mint({ connectionId: getApiRequestConnection(), path: suffix, pluginId, profile: getApiRequestProfile() }),+ RECONNECT_ATTEMPT_TIMEOUT_MS,+ `Timed out preparing plugin socket "${pluginId}"`+ )+ : null+ }++ const base = connection.baseUrl.replace(/^http/, 'ws')+ const join = suffix.includes('?') ? '&' : '?'++ return `${base}/api/plugins/${pluginId}${suffix}${join}token=${encodeURIComponent(connection.token)}`+}+/** The plugin WebSocket door — the live twin of `pluginRest`, scoped the same* way: `path` is relative to `/api/plugins/<pluginId>` ('/events' → the* plugin's own event stream). Token-mode backends auth via the same query- * credential the app's own sockets use; OAuth remotes resolve null (callers- * keep their polling fallback — every consumer must have one anyway, since a- * socket can drop). Auto-reconnects with backoff until disposed. */+ * credential the app's own sockets use, a local gateway via the native grant+ * its REST twin uses; OAuth remotes resolve null (callers keep their polling+ * fallback — every consumer must have one anyway, since a socket can drop).+ * Auto-reconnects with backoff until disposed, and gives up after+ * MAX_REFUSED_PLUGIN_DIALS dials in a row that never stayed open. */export function pluginSocket(pluginId: string, path: string, onMessage: (data: unknown) => void): () => void {const suffix = pluginPathSuffix('pluginSocket', path)let socket: null | WebSocket = nulllet disposed = falselet attempt = 0+ let refused = 0++ const retry = () => {+ refused += 1++ if (disposed || refused >= MAX_REFUSED_PLUGIN_DIALS) {+ return+ }++ // Full-jitter exponential backoff: same rationale as the gateway+ // socket reconnect loops — an immediate-retry loop across many+ // desktop clients floods the gateway with connection attempts+ // during a restart.+ window.setTimeout(() => void connect(), reconnectBackoffDelayMs(attempt, { baseDelayMs: 500, capMs: 30_000 }))+ attempt += 1+ }const connect = async () => {const connection = await activeConnection().catch(() => null)@@ -108,11 +153,25 @@ export function pluginSocket(pluginId: string, path: string, onMessage: (data: ureturn}- const base = connection.baseUrl.replace(/^http/, 'ws')- const join = suffix.includes('?') ? '&' : '?'- socket = new WebSocket(- `${base}/api/plugins/${pluginId}${suffix}${join}token=${encodeURIComponent(connection.token)}`- )+ let url: null | string++ try {+ url = await pluginSocketUrl(connection, pluginId, suffix)+ } catch {+ // The local mint failed (gateway gone or refusing): a refused dial.+ return retry()+ }++ if (disposed || !url) {+ return+ }++ socket = new WebSocket(url)+ let openedAt: null | number = null++ socket.onopen = () => {+ openedAt = Date.now()+ }socket.onmessage = event => {attempt = 0@@ -127,14 +186,14 @@ export function pluginSocket(pluginId: string, path: string, onMessage: (data: usocket.onclose = () => {socket = null- if (!disposed) {- // Full-jitter exponential backoff: same rationale as the gateway- // socket reconnect loops — an immediate-retry loop across many- // desktop clients floods the gateway with connection attempts- // during a restart.- window.setTimeout(() => void connect(), reconnectBackoffDelayMs(attempt, { baseDelayMs: 500, capMs: 30_000 }))- attempt += 1+ // Only a socket that stayed up resets the ladder: an accept-then-close server+ // (Kanban on an archived board) counts as a refused dial.+ if (isStableOpen(openedAt)) {+ attempt = 0+ refused = 0}++ retry()}}diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex 33da11bd051..baef20e90be 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -48,6 +48,14 @@ declare global {connectionId?: null | stringprofile?: null | string}) => Promise<GatewayWsUrlResult>+ // One-use plugin socket URL for a local gateway (its native grant rides+ // a header main attaches to that dial); null for every other backend.+ getPluginWsUrl?: (payload: {+ connectionId?: null | string+ path: string+ pluginId: string+ profile?: null | string+ }) => Promise<null | string>// Union agent roster across every registered connection.getAgentRoster?: () => Promise<DesktopAgentRoster>// Credential-free routes across the union connection registry. The@@ -975,7 +983,8 @@ export interface HermesConnection {// 'cloud' saved-config entry resolves to a 'remote' connection under the hood// (cloud-auto-discovery Q3/Q6), so this never carries 'cloud'.mode?: 'local' | 'remote'- authMode?: 'oauth' | 'token'+ // 'native': this machine's gateway; no static token, per-call private grants.+ authMode?: 'native' | 'oauth' | 'token'remoteHost?: stringremoteIdentity?: stringremoteKind?: 'cloud' | 'ssh' | 'url'diff --git a/gateway/run_api.py b/gateway/run_api.pyindex b537805416a..a643120fdfc 100644--- a/gateway/run_api.py+++ b/gateway/run_api.py@@ -270,9 +270,8 @@ class GatewayRuntimeAPI:await JSONResponse({'error': 'gateway_not_ready', 'state': descriptor['state']},status_code=503)(scope, receive, send)return- if scope['type'] == 'http':- # Capture before Uvicorn's proxy middleware rewrites scope.client.- scope['hermes.gateway_socket_peer'] = scope.get('client')+ # Capture before Uvicorn's proxy middleware rewrites scope.client (native grants, both kinds).+ scope['hermes.gateway_socket_peer'] = scope.get('client')from gateway.run_idle_exit import attached_client, note_client_activityif scope['type'] != 'websocket' or scope['path'] != '/api/ws':note_client_activity(self.runner) # dashboard/API traffic keeps an idle-exit gateway updiff --git a/hermes_cli/dashboard_auth/native_http.py b/hermes_cli/dashboard_auth/native_http.pyindex bfedcfe6daa..92ebe530a7c 100644--- a/hermes_cli/dashboard_auth/native_http.py+++ b/hermes_cli/dashboard_auth/native_http.py@@ -121,23 +121,22 @@ def _redeem_http_ticket(store, ticket, request):return grant-async def authenticate_native_http(request):- """Return a rejection or stamp a one-request principal; absent header is inert."""- tickets = request.headers.getlist(HEADER)- if not tickets:- return None+def _native_store(conn, tickets):+ """The runner's ticket store when *conn* may redeem a private grant here, else None."""from gateway.drain_control import restart_wait_read- from gateway.session_authorities import all_authorities, authority_for_profile_id- runner = getattr(request.app.state, 'gateway_runner', None)+ from gateway.session_authorities import all_authorities+ runner = getattr(conn.app.state, 'gateway_runner', None)descriptor = getattr(runner, 'session_runtime_descriptor', {})authorities = all_authorities(runner)store = getattr(runner, 'session_ticket_store', None)- peer = request.scope.get('hermes.gateway_socket_peer')- if (len(tickets) != 1 or 'origin' in request.headers or not peer+ peer = conn.scope.get('hermes.gateway_socket_peer')+ if (len(tickets) != 1 or 'origin' in conn.headers or not peeror peer[0] not in {'127.0.0.1', '::1'}or descriptor.get('state') != 'ready'# A restart's after-turn wait still serves the reads that open a parked prompt (#139041).- or (getattr(runner, '_draining', True) and not restart_wait_read(runner, request.method, request.url.path))+ # A websocket scope has no method, so a socket upgrade never matches that GET allowlist.+ or (getattr(runner, '_draining', True)+ and not restart_wait_read(runner, conn.scope.get('method'), conn.url.path))or not authorities or store is Noneor store.instance_id != descriptor.get('instance_id')or any(a is not None and a.instance_id != store.instance_id for a in authorities)@@ -147,7 +146,59 @@ async def authenticate_native_http(request):or descriptor.get('served_profiles') != [{'profile_id': a.profile_id, 'home': a.profile_id} for a in authoritiesif a is not None and not getattr(a, 'retiring', False) and a.profile_id in store.profile_ids]):+ return None+ return runner, store+++def redeem_native_ws(conn):+ """Redeem the ``native-http`` grant a Desktop plugin socket upgrade presents; None when refused.++ Same issuer, header, peer/Origin and served-profile rules as HTTP: a plugin socket is the+ live twin of the plugin REST call that already rides this grant on a local gateway. The+ upgrade's ``profile`` selectors must name the grant's home. Plugin sockets only: ``/api/ws``+ and other core streams keep their own purpose-bound credentials. Called once per upgrade, by+ ``PluginApiWebSocketGate`` ahead of routing, so the grant's profile decides consent and scope+ before any route dependency or plugin code runs.+ """+ tickets = conn.headers.getlist(HEADER)+ gate = _native_store(conn, tickets) if conn.url.path.startswith('/api/plugins/') else None+ if gate is None:+ return None+ runner, store = gate+ from gateway.session_authorities import authority_for_profile_id+ try:+ grant = store.redeem(tickets[0], profile_id=None, purpose='native-http')+ if (grant['capabilities'] != frozenset({'http:owner'})+ or authority_for_profile_id(runner, grant['profile_id']) is None):+ return None+ for value in conn.query_params.getlist('profile'):+ _own_profile(value, grant['profile_id'])+ except PermissionError:+ return None+ return grant+++def authenticate_native_ws(ws):+ """The grant :func:`redeem_native_ws` admitted for this plugin socket, or None (refused).++ Never redeems: the gate already did, once, and bound the grant's home and secret scope for+ the whole connection.+ """+ if not ws.url.path.startswith('/api/plugins/'):+ return None+ return getattr(ws.state, 'native_http_principal', None)+++async def authenticate_native_http(request):+ """Return a rejection or stamp a one-request principal; absent header is inert."""+ tickets = request.headers.getlist(HEADER)+ if not tickets:+ return None+ from gateway.session_authorities import authority_for_profile_id+ gate = _native_store(request, tickets)+ if gate is None:return JSONResponse({'detail': 'Unauthorized'}, status_code=401)+ runner, store = gatetry:# The ticket names the served profile it was minted for; that home's authority owns it.grant = _redeem_http_ticket(store, tickets[0], request)diff --git a/hermes_cli/web_server_chat.py b/hermes_cli/web_server_chat.pyindex 640662e4692..b58e75af7c3 100644--- a/hermes_cli/web_server_chat.py+++ b/hermes_cli/web_server_chat.py@@ -213,8 +213,18 @@ def _ws_auth_reason(ws: WebSocket) -> tuple[Optional[str], str]:uses — e.g. a token-mode Remote desktop connection). The legacy in-process``_SESSION_TOKEN`` is rejected in gated mode: a leaked ``_SESSION_TOKEN``must not grant access.++ Either mode: a local Desktop (no static token) presents the private one-use+ ``X-Hermes-Gateway-Ticket`` grant its REST calls use (``authenticate_native_ws``)."""+ from hermes_cli.dashboard_auth.native_http import HEADER, authenticate_native_wsfrom hermes_cli.web_server import _SESSION_TOKEN, app+ if HEADER in ws.headers:+ grant = authenticate_native_ws(ws)+ if grant is None:+ return "native_invalid", "native"+ ws._hermes_auth_identity = {"user_id": grant["subject"], "provider": "local"}+ return None, "native"auth_required = bool(getattr(app.state, "auth_required", False))if auth_required:# Lazy import — keeps this function importable in test harnessesdiff --git a/hermes_cli/web_server_dashboard.py b/hermes_cli/web_server_dashboard.pyindex ba02f7ec515..3e4ed29e1f9 100644--- a/hermes_cli/web_server_dashboard.py+++ b/hermes_cli/web_server_dashboard.py@@ -881,18 +881,48 @@ class PluginApiWebSocketGate:cannot wait for auth (a gated-mode ticket is single-use: only the route may redeem it). That isno plugin-name oracle: a close before accept reaches the client as the same 403 handshakeanswer whether the plugin is disabled, unknown, or the credential was refused.++ A Desktop's native grant is the exception: it names the profile the socket acts for, so it is+ redeemed here, once (:func:`_native_ws_scope`), and consent is checked in that profile."""def __init__(self, app) -> None:self.app = appasync def __call__(self, scope, receive, send) -> None:- if scope["type"] == "websocket":- name = _plugin_api_name(scope)- if name and _plugin_api_request_refused(name):- await send({"type": "websocket.close", "code": status.WS_1008_POLICY_VIOLATION})+ name = _plugin_api_name(scope) if scope["type"] == "websocket" else ""+ if not name:+ await self.app(scope, receive, send)+ return+ with _native_ws_scope(scope) as admitted:+ if admitted and not _plugin_api_request_refused(name):+ await self.app(scope, receive, send)return- await self.app(scope, receive, send)+ await send({"type": "websocket.close", "code": status.WS_1008_POLICY_VIOLATION})+++@contextmanager+def _native_ws_scope(scope):+ """Yield whether a plugin socket's native grant (``X-Hermes-Gateway-Ticket``) was admitted,+ with that grant's home and secret scope bound for the rest of the connection; without the+ header, True and the ambient scope. The grant is redeemed here only: the route's credential+ check reads the principal stamped on the connection, and its scope dependency resolves the+ same profile, so consent, home and ``get_secret`` all follow the grant, as on HTTP+ (``native_profile_scope``).+ """+ from hermes_cli.dashboard_auth.native_http import HEADER, native_profile_scope, redeem_native_ws+ from hermes_cli.web_server_profiles import _config_profile_scope+ conn = HTTPConnection(scope)+ if HEADER not in conn.headers:+ yield True+ return+ grant = redeem_native_ws(conn)+ if grant is None:+ yield False+ return+ conn.state.native_http_principal = grant+ with native_profile_scope(conn), _config_profile_scope(None):+ yield True# Serializes plugin API mounts: concurrent first requests for a freshly enabled plugin must importdiff --git a/tests/gateway/test_native_plugin_ws_auth.py b/tests/gateway/test_native_plugin_ws_auth.pynew file mode 100644index 00000000000..a6f88014894--- /dev/null+++ b/tests/gateway/test_native_plugin_ws_auth.py@@ -0,0 +1,52 @@+"""Desktop plugin WebSockets on a local gateway ride the private native-HTTP grant (PLG-1).++A local Desktop has no static dashboard token (``authMode: native``), so the legacy ``?token=``+upgrade always failed and Kanban fell back to polling. The plugin socket presents the same+one-use ``native-http`` grant its REST twin sends, in the same header, under the same peer/Origin+rules; anything else stays refused.+"""+import asyncio+import json++import pytest+from websockets.asyncio.client import connect+from websockets.exceptions import InvalidStatus++from tests.gateway.test_native_http_auth import daemon, headers, ticket+++async def _upgrade(origin, path, extra=None):+ url = origin.replace('http:', 'ws:') + path+ try:+ async with connect(url, additional_headers=extra or {}, open_timeout=10):+ return 'open'+ except InvalidStatus as exc:+ return exc.response.status_code++[email protected]("linux")+def test_plugin_socket_accepts_native_grant_only(tmp_path):+ with daemon(tmp_path) as (home, descriptor):+ origin = descriptor['api_origin']+ events = '/api/plugins/kanban/events'++ def up(path=events, extra=None):+ return asyncio.run(_upgrade(origin, path, extra))++ assert up() != 'open'+ assert up(events + '?token=') != 'open'+ grant = ticket(home, descriptor)+ assert up(extra=headers(grant)) == 'open'+ assert up(extra=headers(grant)) != 'open' # one use+ assert up(extra=headers('invalid')) != 'open'+ for purpose in ('interactive', 'worker-adoption'):+ assert up(extra=headers(ticket(home, descriptor, purpose))) != 'open', purpose+ for browser_origin in ('https://evil.example', 'null'):+ assert up(extra={**headers(ticket(home, descriptor)), 'Origin': browser_origin}) != 'open'+ assert up(events + '?profile=other', headers(ticket(home, descriptor))) != 'open'+ assert up(events + '?profile=default', headers(ticket(home, descriptor))) == 'open'+ # The grant is not a query credential, and opens plugin sockets only.+ assert up(events + '?ticket=' + ticket(home, descriptor)) != 'open'+ for core in ('/api/ws', '/api/pty', '/api/audio/speak-stream'):+ assert up(core, headers(ticket(home, descriptor))) != 'open', core+ print(json.dumps({'plugin_ws_native_grant': 'accepted once; replay/purpose/origin/profile refused'}))diff --git a/tests/hermes_cli/test_plugin_native_ws_scope.py b/tests/hermes_cli/test_plugin_native_ws_scope.pynew file mode 100644index 00000000000..849643c8dc1--- /dev/null+++ b/tests/hermes_cli/test_plugin_native_ws_scope.py@@ -0,0 +1,244 @@+"""A Desktop plugin socket's native grant decides its consent and its scope before plugin code (PLG-1).++The one-use ``native-http`` grant names the profile the socket acts for. The handler used to+redeem it, after the runtime gate had checked consent in the launch profile's ambient scope and+the route dependency had bound the launch profile's secrets: a secondary profile's socket ran a+plugin that profile never enabled (or had disabled), with its home but the launch profile's+secrets. The grant is now redeemed once, ahead of routing; both profiles' consent holds before+accept, and the handler resolves home and secrets in the grant's profile.++Driven through the real app on the multiplexed daemon stand-in of the consent-gate tests.+"""+from __future__ import annotations++import asyncio+import json+from contextlib import ExitStack++import pytest+from starlette.status import WS_1008_POLICY_VIOLATION+from starlette.testclient import TestClient+from starlette.websockets import WebSocketDisconnect++from hermes_cli import web_server+from hermes_cli.web_server_dashboard import PluginApiWebSocketGate+from hermes_cli.web_server_profiles import _config_profile_scope+from tests.hermes_cli import test_plugin_api_consent_gate as consent_gate++daemon = consent_gate.daemon # the multiplexed daemon stand-in fixture+_plugins = consent_gate._plugins++_PROBE_API = '''+from pathlib import Path++from fastapi import APIRouter, WebSocket++router = APIRouter()++[email protected]("/ping")+async def ping():+ return {"pong": True}++[email protected]("/events")+async def events(ws: WebSocket):+ with Path(__file__).with_name("ENTERED").open("a") as entered:+ entered.write("x")+ from hermes_cli.web_server_chat import _ws_auth_ok+ if not _ws_auth_ok(ws):+ await ws.close(code=1008)+ return+ await ws.accept()+ from agent.secret_scope import get_secret+ from hermes_constants import get_hermes_home+ while True:+ await ws.send_json({"home": str(get_hermes_home()), "secret": get_secret("PLG_WS_SENTINEL")})+ if await ws.receive_text() == "bye":+ break+ await ws.close()+'''++NAME = "scope-probe"+EVENTS = f"/api/plugins/{NAME}/events"+++def _setup(daemon, *, beta_enabled=True, beta_disabled=False):+ dashboard = daemon.launch / "plugins" / NAME / "dashboard"+ dashboard.mkdir(parents=True)+ (dashboard / "manifest.json").write_text(json.dumps({"name": NAME, "api": "plugin_api.py"}))+ (dashboard / "plugin_api.py").write_text(_PROBE_API)+ (dashboard / "index.js").write_text("export {}\n")+ (daemon.launch / ".env").write_text("PLG_WS_SENTINEL=launch-sentinel\n")+ (daemon.beta / ".env").write_text("PLG_WS_SENTINEL=beta-sentinel\n")+ _plugins(daemon.launch, enabled=[NAME])+ _beta(daemon, enabled=beta_enabled, disabled=beta_disabled)+ assert daemon.client.get(f"/api/plugins/{NAME}/ping", headers=daemon.owner).status_code == 200 # mounts it+ return dashboard / "ENTERED"+++def _beta(daemon, *, enabled=True, disabled=False):+ _plugins(daemon.beta, enabled=[NAME] if enabled else [], disabled=[NAME] if disabled else [])+++def _store():+ return web_server.app.state.gateway_runner.session_ticket_store+++def _grant(home):+ return _store().mint(profile_id=str(home), subject="desktop", purpose="native-http")+++def _headers(grant):+ return {"X-Hermes-Gateway-Ticket": grant}+++def _refused(client, path, grant):+ """True when the upgrade closes with 1008 before accept, False when the socket opens and serves.+ Only entering ``websocket_connect`` may count as a refusal: a socket accepted and then closed+ fails the test."""+ with ExitStack() as stack:+ try:+ ws = stack.enter_context(client.websocket_connect(path, headers=_headers(grant)))+ except WebSocketDisconnect as refusal:+ assert refusal.code == WS_1008_POLICY_VIOLATION+ return True+ ws.receive_json()+ ws.send_text("bye")+ return False+++SELECTORS = ["", "?profile=current", "?profile=beta"]++[email protected]("selector", SELECTORS)[email protected]("beta_consent", ["absent", "disabled"])+def test_secondary_grant_needs_its_own_profiles_consent(daemon, selector, beta_consent):+ """Enabled in the launch profile only: the secondary profile's grant is refused before any+ plugin code runs, with the profile selector omitted (the Desktop's shape), current or explicit."""+ entered = _setup(daemon, beta_enabled=beta_consent == "disabled", beta_disabled=beta_consent == "disabled")++ assert _refused(daemon.client, EVENTS + selector, _grant(daemon.beta))+ assert not entered.exists()+ assert not _refused(daemon.client, EVENTS, _grant(daemon.launch)) # the launch profile's own socket opens+++def test_runtime_disable_in_either_profile_refuses_new_grant_sockets(daemon):+ _setup(daemon)+ assert not _refused(daemon.client, EVENTS, _grant(daemon.beta))++ _beta(daemon, disabled=True)+ assert _refused(daemon.client, EVENTS, _grant(daemon.beta))+ assert not _refused(daemon.client, EVENTS, _grant(daemon.launch))++ _beta(daemon)+ _plugins(daemon.launch, enabled=[NAME], disabled=[NAME])+ assert _refused(daemon.client, EVENTS, _grant(daemon.beta))+ assert _refused(daemon.client, EVENTS, _grant(daemon.launch))+++def test_grant_is_redeemed_once(daemon, monkeypatch):+ _setup(daemon)+ store, redeemed = _store(), []+ redeem = store.redeem++ def counting(ticket, **kwargs):+ redeemed.append(ticket)+ return redeem(ticket, **kwargs)++ monkeypatch.setattr(store, "redeem", counting)+ grant = _grant(daemon.beta)+ assert not _refused(daemon.client, EVENTS, grant)+ assert redeemed == [grant]+ assert _refused(daemon.client, EVENTS, grant) # a second dial with the same grant++[email protected]("selector", SELECTORS)+def test_handler_resolves_home_and_secrets_in_the_grants_profile(daemon, selector):+ _setup(daemon)+ with daemon.client.websocket_connect(EVENTS + selector, headers=_headers(_grant(daemon.beta))) as ws:+ assert ws.receive_json() == {"home": str(daemon.beta), "secret": "beta-sentinel"}+ ws.send_text("bye")+ with daemon.client.websocket_connect(EVENTS, headers=_headers(_grant(daemon.launch))) as ws:+ assert ws.receive_json() == {"home": str(daemon.launch), "secret": "launch-sentinel"}+ ws.send_text("bye")+++def test_concurrent_sockets_keep_their_own_profiles(daemon):+ """Two live sockets for different profiles on ONE event loop never see each other's home or+ secrets, before or after the other one opened."""+ _setup(daemon)++ async def app(scope, receive, send):+ if scope["type"] == "lifespan": # one shared loop for both sockets, without app startup+ for done in ("lifespan.startup.complete", "lifespan.shutdown.complete"):+ await receive()+ await send({"type": done})+ return+ scope["hermes.gateway_socket_peer"] = ("127.0.0.1", 50000)+ await web_server.app(scope, receive, send)++ beta = {"home": str(daemon.beta), "secret": "beta-sentinel"}+ launch = {"home": str(daemon.launch), "secret": "launch-sentinel"}+ with TestClient(app) as client, \+ client.websocket_connect(EVENTS, headers=_headers(_grant(daemon.beta))) as a:+ assert a.receive_json() == beta+ with client.websocket_connect(EVENTS, headers=_headers(_grant(daemon.launch))) as b:+ assert b.receive_json() == launch+ for ws, expected in ((a, beta), (b, launch), (a, beta)):+ ws.send_text("again")+ assert ws.receive_json() == expected+ b.send_text("bye")+ a.send_text("again")+ assert a.receive_json() == beta+ a.send_text("bye")+++def _ambient():+ from agent.secret_scope import get_secret+ from hermes_constants import get_hermes_home+ return str(get_hermes_home()), get_secret("PLG_WS_SENTINEL")++[email protected]("ending", ["raises", "cancelled"])+def test_grant_scope_is_restored_when_the_connection_ends_abnormally(daemon, ending):+ """The grant's home and secret scope last only as long as its connection: when the plugin+ handler raises, or the connection task is cancelled, the launch profile's are back."""+ _setup(daemon)+ seen = []++ async def handler(scope, receive, send):+ seen.append(_ambient())+ if ending == "raises":+ raise RuntimeError("plugin handler failed")+ await asyncio.Event().wait() # held open until cancelled++ async def receive():+ return {"type": "websocket.connect"}++ async def send(message):+ raise AssertionError(f"an admitted socket was answered by the gate: {message}")++ scope = {"type": "websocket", "path": EVENTS, "raw_path": EVENTS.encode(), "root_path": "",+ "query_string": b"", "app": web_server.app,+ "headers": [(b"x-hermes-gateway-ticket", _grant(daemon.beta).encode())],+ "hermes.gateway_socket_peer": ("127.0.0.1", 50000)}++ async def connection():+ with _config_profile_scope(None): # the launch profile's ambient scope+ before = _ambient()+ with pytest.raises(RuntimeError if ending == "raises" else asyncio.CancelledError):+ await PluginApiWebSocketGate(handler)(scope, receive, send)+ return before, _ambient()++ async def run():+ task = asyncio.create_task(connection())+ if ending == "cancelled":+ while not seen:+ await asyncio.sleep(0)+ task.cancel()+ return await task++ launch = (str(daemon.launch), "launch-sentinel")+ assert asyncio.run(run()) == (launch, launch)+ assert seen == [(str(daemon.beta), "beta-sentinel")]