You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

467 lines
17 KiB

import { afterEach, describe, expect, it, vi } from 'vitest'
import type { BrowserWindow, IpcMainEvent } from 'electron'
import { createAppRouter } from '../../src/main/trpc/app-router'
import { router as composeRouter } from '../../src/main/trpc/runtime'
import type { RpcMeta } from '../../src/main/trpc/runtime'
import { createAppEvents } from '../../src/main/trpc/events'
import type { AppContext } from '../../src/main/context'
import { Scope } from '@template/core'
import { settingsSchema } from '@template/contracts/settings'
import { ELECTRON_TRPC_CHANNEL } from 'electron-trpc/shared'
const listeners = vi.hoisted(() => new Set<(event: IpcMainEvent, message: unknown) => void>())
vi.mock('electron', () => ({
ipcMain: {
on: vi.fn((_channel: string, listener: (event: IpcMainEvent, message: unknown) => void) =>
listeners.add(listener)
),
off: vi.fn((_channel: string, listener: (event: IpcMainEvent, message: unknown) => void) =>
listeners.delete(listener)
)
}
}))
import { RpcGateway } from '@template/desktop/rpc'
import { PublicError } from '@template/desktop/errors'
const fixtures: {
gateway: RpcGateway
scope: Scope
events: ReturnType<typeof createAppEvents>
}[] = []
afterEach(async () => {
for (const { gateway, scope, events } of fixtures.splice(0)) {
gateway.dispose()
await scope.dispose()
for (const stream of Object.values(events)) stream.dispose()
}
})
function fixture(role: 'main' | 'about' | 'settings' = 'main', minimal = false) {
const callbacks = new Map<string, (...args: unknown[]) => void>()
const mainFrame = { url: 'app://desktop/index.html' }
const contents = {
id: 1,
mainFrame,
on: vi.fn((name: string, callback: (...args: unknown[]) => void) =>
callbacks.set(name, callback)
),
once: vi.fn((name: string, callback: (...args: unknown[]) => void) =>
callbacks.set(name, callback)
),
off: vi.fn(),
isDestroyed: () => false,
getURL: () => mainFrame.url
}
const window = { webContents: contents, isDestroyed: () => false } as unknown as BrowserWindow
const log = vi.fn()
const gateway = new RpcGateway(log)
const scope = new Scope()
const events = createAppEvents()
fixtures.push({ gateway, scope, events })
const run = vi.fn()
const storage = {
kv: { get: vi.fn(() => ({ draft: 'saved' })), set: vi.fn() },
database: { prepare: vi.fn(() => ({ all: () => [], run })) }
}
const secrets = {
status: vi.fn(() => ({ available: true, stored: false })),
set: vi.fn(),
remove: vi.fn()
}
const files = {
read: vi.fn(() => 'text'),
choose: vi.fn(),
write: vi.fn(),
list: vi.fn(() => []),
watch: vi.fn(),
unwatch: vi.fn(),
release: vi.fn()
}
const settings = {
get: vi.fn(() => settingsSchema.parse({})),
set: vi.fn((value: unknown) => settingsSchema.parse(value))
}
const services = {
app: { getVersion: () => '0.1.0', isPackaged: false },
moduleIds: [],
storage,
secrets,
files,
events,
settings,
updates: {
get: () => ({ status: 'disabled' }),
check: vi.fn(),
download: vi.fn(),
install: vi.fn()
},
windows: { open: vi.fn() }
} as unknown as AppContext
if (minimal) {
services.files = undefined
services.storage = undefined
services.secrets = undefined
services.updates = undefined
}
const appRouter = createAppRouter(services, scope)
const revoke = vi.fn()
gateway.attach(window, role, mainFrame.url, revoke)
const reply = vi.fn()
const event = { sender: contents, senderFrame: mainFrame, reply } as unknown as IpcMainEvent
const send = (path: string, type = 'query', input?: unknown, id = 1): void => {
for (const listener of listeners)
listener(event, { method: 'request', operation: { id, path, type, input } })
}
const stop = (id = 1): void => {
for (const listener of listeners) listener(event, { method: 'subscription.stop', id })
}
const caller = (): ReturnType<typeof appRouter.createCaller> => {
const created = gateway.createContext(event)
created.release()
return appRouter.createCaller(created.context)
}
const start = (api = appRouter): void => gateway.start(api, (caller) => caller)
return {
gateway,
event,
contents,
callbacks,
revoke,
reply,
send,
stop,
caller,
log,
storage,
secrets,
files,
events,
run,
start,
appRouter
}
}
describe('tRPC authorization, validation and lifecycle', () => {
it('does not let an untrusted frame cancel a trusted subscription', async () => {
const { start, send, event, events, reply } = fixture()
start()
send('theme.changed', 'subscription')
await vi.waitFor(() => expect(reply).toHaveBeenCalled())
reply.mockClear()
for (const listener of listeners)
listener({ ...event, senderFrame: {} } as IpcMainEvent, { method: 'request.cancel', id: 1 })
events.theme.emit(true)
expect(reply).toHaveBeenCalledWith(ELECTRON_TRPC_CHANNEL, {
id: 1,
result: { type: 'data', data: true }
})
})
it('keeps core routes available and denies disabled capabilities in a minimal application', async () => {
const { caller } = fixture('main', true)
expect((await caller().app.info()).capabilities).toEqual({
files: false,
storage: false,
credentials: false,
updates: false
})
await expect(caller().settings.get()).resolves.toHaveProperty('theme')
for (const call of [
() => caller().files.list('00000000-0000-4000-8000-000000000000'),
() => caller().storage.get('draft'),
() => caller().notes.list(),
() => caller().secrets.status(),
() => caller().update.status()
])
await expect(call()).rejects.toMatchObject({
code: 'PRECONDITION_FAILED',
message: expect.stringContaining('DISABLED')
})
})
it('cancels pending response delivery without treating cancellation as mutation rollback', async () => {
const { start, send, event, files, reply } = fixture()
let resolve!: (value: object) => void
files.choose.mockReturnValue(
new Promise((yes) => {
resolve = yes
})
)
start()
send('files.choose', 'mutation', 'file')
await vi.waitFor(() => expect(files.choose).toHaveBeenCalled())
for (const listener of listeners) listener(event, { method: 'request.cancel', id: 1 })
resolve({ token: '00000000-0000-4000-8000-000000000000', name: 'text.txt', kind: 'file' })
await new Promise<void>((yes) => setImmediate(yes))
expect(reply).not.toHaveBeenCalled()
expect(files.choose).toHaveBeenCalledOnce()
})
it('rejects a different frame, unregistered sender or navigated page', () => {
const { gateway, event, contents } = fixture()
expect(() => gateway.createContext({ ...event, senderFrame: {} } as IpcMainEvent)).toThrow(
'Untrusted'
)
expect(() =>
gateway.createContext({
...event,
sender: { ...contents, id: 99 }
} as unknown as IpcMainEvent)
).toThrow('Untrusted')
contents.mainFrame.url = 'https://example.com/'
expect(() => gateway.createContext(event)).toThrow('Untrusted')
})
it('enforces roles before handlers and validates inputs', async () => {
const { caller, secrets } = fixture('about')
const write = secrets.set
await expect(caller().secrets.set('secret')).rejects.toMatchObject({ code: 'FORBIDDEN' })
expect(write).not.toHaveBeenCalled()
await expect(caller().shell.link('file:///secret' as 'electron')).rejects.toMatchObject({
code: 'BAD_REQUEST'
})
await expect(caller().app.info()).resolves.toMatchObject({ version: '0.1.0' })
})
it('sanitizes wire failures and maps only explicitly public service errors', async () => {
const { storage, caller, reply, send, start, log } = fixture()
storage.kv.get.mockImplementation(() => {
throw new Error('C:/private/secret-password')
})
start()
send('storage.get', 'query', 'draft')
await vi.waitFor(() => expect(reply).toHaveBeenCalled())
const response = reply.mock.calls[0]?.[1]
expect(JSON.stringify(response)).not.toContain('secret-password')
expect(response).toMatchObject({ error: { data: { code: 'INTERNAL_SERVER_ERROR' } } })
expect(response.error.data).not.toHaveProperty('stack')
expect(log).toHaveBeenCalledWith(
'RPC operation failed',
expect.objectContaining({
owner: 1,
path: 'storage.get',
incidentId: expect.any(String),
causes: expect.any(Array)
})
)
storage.kv.get.mockImplementation(() => {
throw new PublicError('BUSY', 'Try later')
})
await expect(caller().storage.get('draft')).rejects.toMatchObject({
code: 'PRECONDITION_FAILED',
message: 'BUSY: Try later'
})
})
it('removing a router disables its API without a second handler registry', async () => {
const { gateway, reply, send, storage } = fixture()
gateway.start(composeRouter({}), (caller) => caller)
send('storage.get', 'query', 'draft')
await vi.waitFor(() => expect(reply).toHaveBeenCalled())
expect(reply.mock.calls[0]?.[1]).toMatchObject({ error: { data: { code: 'NOT_FOUND' } } })
expect(storage.kv.get).not.toHaveBeenCalled()
})
it('rejects a procedure type mismatch without running a mutation', async () => {
const { start, send, reply, run: add } = fixture()
start()
send('notes.add', 'query', 'hello')
await vi.waitFor(() => expect(reply).toHaveBeenCalled())
expect(reply.mock.calls[0]?.[1]).toHaveProperty('error')
expect(add).not.toHaveBeenCalled()
})
it('rejects invalid handler output without leaking it', async () => {
const { storage, caller } = fixture()
storage.kv.get.mockReturnValue({ draft: { private: 'secret' } } as unknown as { draft: string })
await expect(caller().storage.get('draft')).rejects.toMatchObject({
code: 'INTERNAL_SERVER_ERROR'
})
})
it('delivers parsed inputs and validates the service result directly in the procedure', async () => {
const { caller, run } = fixture()
await expect(caller().notes.add(' hello ')).resolves.toMatchObject({ text: 'hello' })
expect(run).toHaveBeenCalledOnce()
expect(run.mock.calls[0]?.[0]).toMatchObject({ text: 'hello' })
})
it('subscribes through electron-trpc and releases on unsubscribe and reload', async () => {
const { start, events, send, stop, reply, callbacks, revoke } = fixture()
start()
send('theme.changed', 'subscription')
await vi.waitFor(() =>
expect(reply).toHaveBeenCalledWith(
ELECTRON_TRPC_CHANNEL,
expect.objectContaining({ result: { type: 'started' } })
)
)
events.theme.emit(true)
expect(reply).toHaveBeenLastCalledWith(ELECTRON_TRPC_CHANNEL, {
id: 1,
result: { type: 'data', data: true }
})
stop()
reply.mockClear()
events.theme.emit(false)
expect(reply).not.toHaveBeenCalled()
send('theme.changed', 'subscription', undefined, 2)
await vi.waitFor(() => expect(reply).toHaveBeenCalled())
callbacks.get('did-start-navigation')?.({ isMainFrame: true, isSameDocument: false })
reply.mockClear()
events.theme.emit(true)
expect(reply).not.toHaveBeenCalled()
expect(revoke).toHaveBeenCalledWith(1)
})
it('handles unsubscribe while a subscription request is still pending', async () => {
const { start, events, send, stop, reply } = fixture()
start()
send('theme.changed', 'subscription')
stop()
await new Promise<void>((resolve) => setImmediate(resolve))
events.theme.emit(true)
expect(reply).not.toHaveBeenCalled()
})
it('denies privileged subscriptions to about windows and ignores malformed envelopes', async () => {
const { start, event, send, reply } = fixture('about')
start()
for (const listener of listeners) listener(event, { method: 'request' })
send('files.changed', 'subscription')
await vi.waitFor(() => expect(reply).toHaveBeenCalledTimes(1))
expect(reply.mock.calls[0]?.[1]).toMatchObject({ error: { data: { code: 'FORBIDDEN' } } })
})
it('bounds request concurrency and releases capacity exactly once', () => {
const { gateway, event } = fixture()
const requests = Array.from({ length: 8 }, () => gateway.createContext(event))
expect(() => gateway.createContext(event)).toThrow('Too many requests')
requests[0]!.release()
requests[0]!.release()
const next = gateway.createContext(event)
expect(() => gateway.createContext(event)).toThrow('Too many requests')
next.release()
for (const request of requests) request.release()
})
it('bounds active subscriptions and returns capacity after unsubscribe', async () => {
const { start, send, stop, reply } = fixture()
start()
for (let id = 1; id <= 32; id++) {
send('theme.changed', 'subscription', undefined, id)
await vi.waitFor(() => expect(reply).toHaveBeenCalledTimes(id))
}
send('theme.changed', 'subscription', undefined, 33)
await vi.waitFor(() => expect(reply).toHaveBeenCalledTimes(33))
expect(reply.mock.calls.at(-1)?.[1]).toMatchObject({
error: { data: { code: 'TOO_MANY_REQUESTS' } }
})
stop(1)
send('theme.changed', 'subscription', undefined, 34)
await vi.waitFor(() => expect(reply).toHaveBeenCalledTimes(34))
expect(reply.mock.calls.at(-1)?.[1]).toMatchObject({ result: { type: 'started' } })
})
it('does not allow another frame to cancel an authorized subscription', async () => {
const { start, events, event, send, reply } = fixture()
start()
send('theme.changed', 'subscription')
await vi.waitFor(() => expect(reply).toHaveBeenCalled())
const foreignFrame = { ...event, senderFrame: {} } as IpcMainEvent
for (const listener of listeners) listener(foreignFrame, { method: 'subscription.stop', id: 1 })
reply.mockClear()
events.theme.emit(true)
expect(reply).toHaveBeenCalledWith(ELECTRON_TRPC_CHANNEL, {
id: 1,
result: { type: 'data', data: true }
})
})
it('revokes subscriptions and grants when the renderer process dies', async () => {
const { start, events, send, reply, callbacks, revoke } = fixture()
start()
send('theme.changed', 'subscription', undefined, 77)
await vi.waitFor(() => expect(reply).toHaveBeenCalled())
callbacks.get('render-process-gone')?.()
reply.mockClear()
events.theme.emit(true)
expect(reply).not.toHaveBeenCalled()
expect(revoke).toHaveBeenCalledWith(1)
})
it('revokes subscriptions on window destruction and removes the global transport listener', async () => {
const { gateway, start, events, send, reply, callbacks, revoke, contents } = fixture()
start()
send('theme.changed', 'subscription')
await vi.waitFor(() => expect(reply).toHaveBeenCalled())
callbacks.get('destroyed')?.()
expect(revoke).toHaveBeenCalledWith(1)
reply.mockClear()
events.theme.emit(true)
expect(reply).not.toHaveBeenCalled()
gateway.dispose()
expect(listeners.size).toBe(0)
expect(contents.off).toHaveBeenCalled()
})
})
describe('per-procedure window policies', () => {
it.each(['main', 'settings', 'about'] as const)('preserves the complete %s policy', (role) => {
const { appRouter } = fixture(role)
const procedures = appRouter._def.procedures as unknown as Record<
string,
{ _def: { meta?: RpcMeta } }
>
const allowed = Object.entries(procedures)
.filter(([, procedure]) => procedure._def.meta?.roles.includes(role))
.map(([path]) => path)
.sort()
const expected =
role === 'main'
? Object.keys(procedures)
: role === 'about'
? [
'app.info',
'window.close',
'diagnostics.report',
'shell.link',
'settings.get',
'settings.changed',
'theme.changed'
]
: [
'app.info',
'settings.get',
'settings.patch',
'window.close',
'window.minimize',
'window.maximize',
'secrets.status',
'secrets.set',
'secrets.remove',
'update.status',
'update.cancel',
'diagnostics.status',
'diagnostics.report',
'diagnostics.send',
'diagnostics.export',
'diagnostics.clear',
'update.check',
'update.download',
'update.install',
'settings.changed',
'theme.changed',
'update.changed'
]
expect(allowed).toEqual(expected.sort())
})
it.each(['about', 'settings'] as const)(
'keeps %s windows away from file operations',
async (role) => {
const { caller, files } = fixture(role)
await expect(
caller().files.read('00000000-0000-4000-8000-000000000000')
).rejects.toMatchObject({ code: 'FORBIDDEN' })
expect(files.read).not.toHaveBeenCalled()
}
)
})