diff --git a/README.md b/README.md index 1968c1bd..9fb50e9b 100644 --- a/README.md +++ b/README.md @@ -43,14 +43,14 @@ Add the plugin to your [OpenCode config](https://opencode.ai/docs/config/): ### OpenCode V2 -OpenCode V2 uses the new plugin API. You can load `opencode-pty/v2` and optionally configure options (such as a fixed web UI port): +OpenCode V2 uses the new plugin API. Load the package by its bare npm ref — the `.` entrypoint is a dual-mode export that serves both runtimes — and optionally configure options (such as a fixed web UI port): ```json { "$schema": "https://opencode.ai/config.json", - "plugin": [ + "plugins": [ { - "package": "opencode-pty/v2", + "package": "opencode-pty", "options": { "port": 4200, "hostname": "127.0.0.1", @@ -61,6 +61,34 @@ OpenCode V2 uses the new plugin API. You can load `opencode-pty/v2` and optional } ``` +Notes for V2: + +- V2 reads the `plugins` array (object form). The V1 `plugin` field is silently ignored — a V1-shaped array produces zero plugin loads. +- The previous `opencode-pty/v2` subpath ref does not install: the V2 loader parses subpath refs as npm install specs ([#67](https://github.com/shekohex/opencode-pty/issues/67)). The bare ref works via the dual-mode default export; the `./v2` subpath remains valid for direct-import consumers. +- A plugin must export a default definition with an `id` and a `setup` (or `effect`) function. The `.` entrypoint now exports exactly that alongside the V1 `server` entrypoint. +- If the npm ref fails to install through OpenCode's bundled npm with ``, use a local clone (below). That failure happens for any package with dependencies, not just this one. + +#### Install from a local clone + +```bash +git clone https://github.com/shekohex/opencode-pty.git +cd opencode-pty +npm install --legacy-peer-deps # plain npm fails on react@18 vs @opentui/keymap peer +``` + +Then point a directory entry at the clone: + +```json +{ + "$schema": "https://opencode.ai/config.json", + "plugins": ["/absolute/path/to/opencode-pty"] +} +``` + +A directory entry resolves a root `server` file, else `index`, with a `.ts`, `.tsx`, or `.js` +extension; `package.json` `main` and `exports` are not followed for a path entry. This +repository's root `index.ts` is that entrypoint, so the clone loads without a build step. + | Option | Type | Default | Description | | --- | --- | --- | --- | | `port` | `number` | `0` (ephemeral) | Fixed port for the PTY Web UI observer server | @@ -297,7 +325,27 @@ This eliminates the need for polling—perfect for long-running processes like b ### Permissions -This plugin respects OpenCode's [permission settings](https://opencode.ai/docs/permissions/) for the `bash` tool. Commands spawned via `pty_spawn` are checked against your `permission.bash` configuration. +This plugin respects OpenCode's [permission settings](https://opencode.ai/docs/permissions/). Commands spawned via `pty_spawn`, and command lines sent with `pty_write`, are checked with the same permission surface the host's own shell tool uses. + +On **V2** that surface is `ctx.permission.assert`: the plugin asks the host to evaluate the session's rules and only spawns once the check resolves. A `deny` rule blocks the spawn, and an `ask` rule raises OpenCode's normal permission prompt — the answer is honoured, including saved approvals. V2 names the shell action `shell`: + +```json +{ + "$schema": "https://opencode.ai/config.json", + "permissions": [ + { "action": "shell", "resource": "npm *", "effect": "allow" }, + { "action": "shell", "resource": "git push", "effect": "deny" }, + { "action": "shell", "resource": "terraform *", "effect": "deny" } + ] +} +``` + +Two V2 edge cases are deliberate: + +- A check that cannot be attributed to a session is **denied** rather than allowed. Every PTY tool call carries its session, so this only affects calls made outside a tool invocation, and denying keeps a configured `deny` rule from being bypassed. +- A host that exposes no `ctx.permission` domain gets a startup warning and no checks, matching the pre-2.0 fallback below. This plugin cannot read `permissions` itself on V2 — the plugin context has no config reader — so the host is the only authority. + +On **V1** the plugin reads `permission.bash` from the host config: ```json { @@ -313,12 +361,12 @@ This plugin respects OpenCode's [permission settings](https://opencode.ai/docs/p ``` > [!IMPORTANT] -> **Limitations compared to built-in bash tool:** +> **V1 limitations compared to the built-in bash tool:** > -> - **"ask" permissions are treated as "deny"**: Since plugins cannot trigger OpenCode's permission prompt UI, commands matching an "ask" pattern will be denied. A toast notification will inform you when this happens. Configure explicit "allow" or "deny" for commands you want to use with PTY. -> - **"external_directory" with "ask" is treated as "allow"**: When the working directory is outside the project and `permission.external_directory` is set to "ask", this plugin allows it (with a log message). Set to "deny" explicitly if you want to block external directories. +> - **"ask" permissions are treated as "deny"**: Since the V1 plugin API cannot trigger OpenCode's permission prompt UI, commands matching an "ask" pattern will be denied. A toast notification will inform you when this happens. Configure explicit "allow" or "deny" for commands you want to use with PTY. (V2 does not have this limitation — `ctx.permission.assert` prompts.) +> - **"external_directory" with "ask" is treated as "allow"**: When the working directory is outside the project and `permission.external_directory` is set to "ask", the V1 path allows it (with a log message). Set to "deny" explicitly if you want to block external directories. -#### Example: Allow specific commands for PTY +#### Example: Allow specific commands for PTY (V1) ```json { diff --git a/index.ts b/index.ts index 8799a0a1..84aece80 100644 --- a/index.ts +++ b/index.ts @@ -1,2 +1,17 @@ +import { Plugin } from './src/v2/index.ts' +import { PTYPlugin } from './src/plugin.ts' + export { PTYPlugin } from './src/plugin.ts' export { PTYPlugin as server } from './src/plugin.ts' +export { Plugin } from './src/v2/index.ts' + +// Dual-mode default export: opencode V1 (>= 1.18.29) resolves the object entrypoint and +// calls `server()`; V2 validates `{ id, setup }` and calls `setup()`. The bare npm ref +// therefore loads on both runtimes — necessary because the V2 loader parses the +// documented `opencode-pty/v2` subpath ref as an npm install spec and cannot install it +// (#67), and the previous `.` entrypoint carried no default export at all. +export default { + id: Plugin.id, + server: PTYPlugin, + setup: Plugin.setup, +} diff --git a/src/adapters/index.ts b/src/adapters/index.ts index d2fca41a..5f34f391 100644 --- a/src/adapters/index.ts +++ b/src/adapters/index.ts @@ -4,6 +4,7 @@ import type { HostAdapter } from './types.ts' export * from './types.ts' export * from './v1/index.ts' +export * from './v2/index.ts' /** * Installs a host adapter by connecting its notifier and permission authorizer diff --git a/src/adapters/types.ts b/src/adapters/types.ts index 393ef48d..58d37565 100644 --- a/src/adapters/types.ts +++ b/src/adapters/types.ts @@ -8,12 +8,27 @@ export interface SessionNotifier { sendExitNotification(session: PTYSession, exitCode: number): Promise | void } +/** + * The tool invocation a permission check belongs to. + * + * Hosts that evaluate permissions per session need this to attribute the check + * to a session, an agent and a tool call. It is optional because a check can be + * made outside a tool call; hosts that require it decide what an absent value + * means (the V2 adapter denies, see `V2PermissionAuthorizer`). + */ +export interface PermissionRequestContext { + sessionID?: string + agent?: string + messageID?: string + callID?: string +} + /** * Host-agnostic authorizer for validating command and workdir execution permissions. */ export interface PermissionAuthorizer { - checkCommand(command: string, args: string[]): Promise - checkWorkdir(workdir: string): Promise + checkCommand(command: string, args: string[], context?: PermissionRequestContext): Promise + checkWorkdir(workdir: string, context?: PermissionRequestContext): Promise } /** diff --git a/src/adapters/v2/permissions.ts b/src/adapters/v2/permissions.ts new file mode 100644 index 00000000..3ae8cc67 --- /dev/null +++ b/src/adapters/v2/permissions.ts @@ -0,0 +1,153 @@ +import type { PermissionAuthorizer, PermissionRequestContext } from '../types.ts' + +/** + * The subset of opencode V2's `ctx.permission` the authorizer needs. + * + * Typed structurally rather than imported so the adapter stays decoupled from + * the `@opencode/plugin` package version pinned by the host, and so tests can + * supply a recording double without a whole V2 server context. + */ +export interface V2PermissionDomain { + assert(input: V2PermissionAssertInput): Promise +} + +export interface V2PermissionAssertInput { + sessionID: string + agent?: string + /** Permission action: V2 names the shell action `shell` (V1 called it `bash`). */ + action: string + resources: string[] + /** Patterns saved when the user answers "always allow". */ + save?: string[] + source?: { type: 'tool'; messageID: string; id: string } +} + +export interface V2PermissionAuthorizerOptions { + permission: V2PermissionDomain + /** The location directory; a workdir outside it is an external directory. */ + directory?: string +} + +/** + * V2 permission authorizer built on `ctx.permission.assert`. + * + * opencode V2 has no `config.get()` on the plugin context, so the configured + * `permissions` rules cannot be read and re-implemented here: `assert` is the + * only documented surface that evaluates them (including saved approvals and + * agent rules) and prompts when a rule resolves to `ask`. Delegating keeps the + * plugin's answer identical to the host's own shell tool. + * + * Safe default: when `assert` is present but the check cannot be attributed to + * a session, the check **denies**. Allowing instead would reintroduce #80 — + * a `deny` rule silently bypassed — while denying only affects calls made + * outside a tool invocation, which the plugin does not make. + */ +export class V2PermissionAuthorizer implements PermissionAuthorizer { + private readonly permission: V2PermissionDomain + private readonly directory?: string + + constructor(options: V2PermissionAuthorizerOptions) { + this.permission = options.permission + this.directory = options.directory + } + + async checkCommand( + command: string, + args: string[], + context?: PermissionRequestContext + ): Promise { + const commandLine = [command, ...args].join(' ').trim() + if (!commandLine) { + return + } + + // `save` proposes the exact command so "always allow" cannot widen a rule + // to a prefix the user never approved. The host decides whether to store it. + await this.assert(context, 'shell', [commandLine], [commandLine]) + } + + async checkWorkdir(workdir: string, context?: PermissionRequestContext): Promise { + if (!this.directory || isInside(workdir, this.directory)) { + return + } + + const normalized = normalizeSegments(workdir) + await this.assert(context, 'external_directory', [normalized, `${normalized}/*`]) + } + + private async assert( + context: PermissionRequestContext | undefined, + action: string, + resources: string[], + save?: string[] + ): Promise { + const sessionID = context?.sessionID + if (!sessionID) { + throw new Error( + `PTY: ${action} permission for "${resources.join(', ')}" cannot be evaluated without a session, so it is denied.` + ) + } + + const source = + context.messageID && context.callID + ? { type: 'tool' as const, messageID: context.messageID, id: context.callID } + : undefined + + await this.permission.assert({ + sessionID, + ...(context.agent ? { agent: context.agent } : {}), + action, + resources, + ...(save ? { save } : {}), + ...(source ? { source } : {}), + }) + } +} + +/** + * True when `path` is the same as, or below, `root`. + * + * Both sides are resolved lexically first, so `/workspace/app/../etc` is not + * mistaken for a path inside `/workspace/app`, and the comparison is + * segment-wise so `/workspace/app-evil` is not inside `/workspace/app` either. + */ +function isInside(path: string, root: string): boolean { + const normalizedRoot = normalizeSegments(root) + const normalizedPath = normalizeSegments(path) + return normalizedPath === normalizedRoot || normalizedPath.startsWith(`${normalizedRoot}/`) +} + +/** + * Collapses `.` and `..` segments without touching the filesystem. + * + * `..` never climbs above the first segment: a path that escapes its own root + * then simply fails the prefix comparison above. + */ +function normalizeSegments(path: string): string { + const absolute = path.startsWith('/') + const segments: string[] = [] + for (const segment of path.split('/')) { + if (!segment || segment === '.') { + continue + } + if (segment === '..') { + if (segments.length > 0) { + segments.pop() + } + continue + } + segments.push(segment) + } + const joined = segments.join('/') + return absolute ? `/${joined}` : joined || '.' +} + +export function createV2PermissionAuthorizer( + permission: V2PermissionDomain | undefined, + directory?: string +): V2PermissionAuthorizer | undefined { + if (!permission || typeof permission.assert !== 'function') { + return undefined + } + return new V2PermissionAuthorizer({ permission, directory }) +} diff --git a/src/plugin/pty/permissions.ts b/src/plugin/pty/permissions.ts index e727af14..a6455945 100644 --- a/src/plugin/pty/permissions.ts +++ b/src/plugin/pty/permissions.ts @@ -1,8 +1,8 @@ import type { PluginClient } from '../types.ts' -import type { PermissionAuthorizer } from '../../adapters/types.ts' +import type { PermissionAuthorizer, PermissionRequestContext } from '../../adapters/types.ts' import { V1PermissionAuthorizer } from '../../adapters/v1/permissions.ts' -export type { PermissionAuthorizer } +export type { PermissionAuthorizer, PermissionRequestContext } let _authorizer: PermissionAuthorizer | null = null @@ -27,22 +27,59 @@ export function initPermissions(client: PluginClient, directory: string): void { _authorizer = new V1PermissionAuthorizer(client, directory) } +/** + * Extracts what a host needs to attribute a permission check to a tool call. + * + * The V1 tool context and the V2 tool context carry overlapping but different + * fields (`id` only exists on V2), and a tool may be invoked without a context + * in tests, so every field is read defensively instead of being trusted. + */ +export function permissionRequestContext(toolContext: unknown): PermissionRequestContext { + const source = (toolContext ?? {}) as Record + const context: PermissionRequestContext = {} + for (const key of ['sessionID', 'agent', 'messageID'] as const) { + const value = source[key] + if (typeof value === 'string') context[key] = value + } + if (typeof source.id === 'string') context.callID = source.id + return context +} + /** * Checks command execution permission against the active authorizer. * Defaults to allowing if no authorizer is set. */ -export async function checkCommandPermission(command: string, args: string[]): Promise { - if (_authorizer) { - await _authorizer.checkCommand(command, args) +export async function checkCommandPermission( + command: string, + args: string[], + context?: PermissionRequestContext +): Promise { + if (!_authorizer) { + return + } + // Pass the context only when there is one: a context-less check keeps the + // two-argument call shape existing authorizers and tests already observe. + if (context) { + await _authorizer.checkCommand(command, args, context) + return } + await _authorizer.checkCommand(command, args) } /** * Checks working directory access permission against the active authorizer. * Defaults to allowing if no authorizer is set. */ -export async function checkWorkdirPermission(workdir: string): Promise { - if (_authorizer) { - await _authorizer.checkWorkdir(workdir) +export async function checkWorkdirPermission( + workdir: string, + context?: PermissionRequestContext +): Promise { + if (!_authorizer) { + return + } + if (context) { + await _authorizer.checkWorkdir(workdir, context) + return } + await _authorizer.checkWorkdir(workdir) } diff --git a/src/plugin/pty/tools/spawn.ts b/src/plugin/pty/tools/spawn.ts index f912be4e..504ce036 100644 --- a/src/plugin/pty/tools/spawn.ts +++ b/src/plugin/pty/tools/spawn.ts @@ -1,6 +1,10 @@ import { tool } from '@opencode-ai/plugin' import { manager } from '../manager.ts' -import { checkCommandPermission, checkWorkdirPermission } from '../permissions.ts' +import { + checkCommandPermission, + checkWorkdirPermission, + permissionRequestContext, +} from '../permissions.ts' import DESCRIPTION from './spawn.txt' const NOTIFY_ON_EXIT_INSTRUCTIONS = [ @@ -40,10 +44,11 @@ export const ptySpawn = tool({ ), }, async execute(args, ctx) { - await checkCommandPermission(args.command, args.args ?? []) + const permissionContext = permissionRequestContext(ctx) + await checkCommandPermission(args.command, args.args ?? [], permissionContext) if (args.workdir) { - await checkWorkdirPermission(args.workdir) + await checkWorkdirPermission(args.workdir, permissionContext) } const sessionId = ctx.sessionID diff --git a/src/plugin/pty/tools/write.ts b/src/plugin/pty/tools/write.ts index 6a320f76..66cc4065 100644 --- a/src/plugin/pty/tools/write.ts +++ b/src/plugin/pty/tools/write.ts @@ -1,6 +1,6 @@ import { tool } from '@opencode-ai/plugin' import { manager } from '../manager.ts' -import { checkCommandPermission } from '../permissions.ts' +import { checkCommandPermission, permissionRequestContext } from '../permissions.ts' import { buildSessionNotFoundError } from '../utils.ts' import DESCRIPTION from './write.txt' @@ -59,7 +59,7 @@ export const ptyWrite = tool({ id: tool.schema.string().describe('The PTY session ID (e.g., pty_a1b2c3d4)'), data: tool.schema.string().describe('The input data to send to the PTY'), }, - async execute(args) { + async execute(args, ctx) { const session = manager.get(args.id) if (!session) { throw buildSessionNotFoundError(args.id) @@ -73,10 +73,11 @@ export const ptyWrite = tool({ const parsedData = parseEscapeSequences(args.data) const commands = extractCommands(parsedData) + const permissionContext = permissionRequestContext(ctx) for (const commandLine of commands) { const { command, args: cmdArgs } = parseCommand(commandLine) if (command) { - await checkCommandPermission(command, cmdArgs) + await checkCommandPermission(command, cmdArgs, permissionContext) } } diff --git a/src/v2/index.ts b/src/v2/index.ts index ad044831..6888c78d 100644 --- a/src/v2/index.ts +++ b/src/v2/index.ts @@ -1,4 +1,5 @@ import { createV2Adapter } from '../adapters/v2/index.ts' +import { createV2PermissionAuthorizer } from '../adapters/v2/permissions.ts' import { installHostAdapter } from '../adapters/index.ts' import type { ServerOptions } from '../web/server/server.ts' import { getOrCreateServer, registerV2Commands } from './commands.ts' @@ -31,7 +32,25 @@ export const Plugin: PluginV2 = define({ ) } - const adapter = createV2Adapter({ notifier }) + // The project directory lives on `location`. `ctx.worktree` is deliberately + // NOT used: it is a domain object on the V2 API, not a path, and passing it + // through reached createHash and threw. Absent paths only mean no record is + // published — the sidebar then falls back to the instance-scoped URL scrape. + const location = (ctx as unknown as { location?: { directory?: unknown } }).location + const directory = typeof location?.directory === 'string' ? location.directory : undefined + + // opencode V2 exposes no `config.get()`, so `permission.bash` cannot be + // re-read and re-implemented here: `ctx.permission.assert` is the only + // documented surface that evaluates the session's rules and prompts on + // `ask`. Without it PTY spawns would bypass `permissions` deny rules (#80). + const permissions = createV2PermissionAuthorizer(ctx.permission, directory) + if (!permissions) { + console.warn( + '[opencode-pty] host does not expose ctx.permission.assert — PTY commands are not checked against permissions' + ) + } + + const adapter = createV2Adapter({ notifier, permissions }) installHostAdapter(adapter) if (ctx.tool && typeof ctx.tool.transform === 'function') { @@ -39,13 +58,6 @@ export const Plugin: PluginV2 = define({ registerV2Tools(draft) }) } - - // The project directory lives on `location`. `ctx.worktree` is deliberately - // NOT used: it is a domain object on the V2 API, not a path, and passing it - // through reached createHash and threw. Absent paths only mean no record is - // published — the sidebar then falls back to the instance-scoped URL scrape. - const location = (ctx as unknown as { location?: { directory?: unknown } }).location - const directory = typeof location?.directory === 'string' ? location.directory : undefined const serverOptions: ServerOptions = { port: ctx.options?.port, hostname: ctx.options?.hostname, diff --git a/src/v2/types.ts b/src/v2/types.ts index 0ea72205..4e67c265 100644 --- a/src/v2/types.ts +++ b/src/v2/types.ts @@ -1,4 +1,5 @@ import type { Plugin } from '@opencode/plugin' +import type { V2PermissionDomain } from '../adapters/v2/permissions.ts' export interface OpencodePtyOptions { /** @@ -60,6 +61,12 @@ export interface ToolDraft { export interface PluginContextV2 { readonly options?: OpencodePtyOptions & Record + /** + * opencode v2's permission domain. `assert` evaluates the session's rules + * (`allow`/`deny`/`ask`, including saved approvals and agent rules) and + * prompts when a rule resolves to `ask`. Optional for hosts pre-2.0.x. + */ + readonly permission?: V2PermissionDomain readonly command?: { transform( callback: (commands: CommandDraft) => Promise | void diff --git a/src/web/server/server.ts b/src/web/server/server.ts index 78123fd9..3ed8f878 100644 --- a/src/web/server/server.ts +++ b/src/web/server/server.ts @@ -106,7 +106,12 @@ export class PTYServer implements Disposable { websocket: { data: undefined as undefined, perMessageDeflate: true, - open: (ws) => ws.subscribe('sessions:update'), + // Bun's `subscribe` returns a boolean; the websocket `open` handler is + // typed `void | Promise`, so the call is wrapped to keep the + // build green instead of relying on emit-on-error. + open: (ws) => { + ws.subscribe('sessions:update') + }, message: handleWebSocketMessage, close: (ws) => { ws.subscriptions.forEach((topic) => { diff --git a/test/dual-mode-default.test.ts b/test/dual-mode-default.test.ts new file mode 100644 index 00000000..2f9c34fc --- /dev/null +++ b/test/dual-mode-default.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from 'bun:test' +import defaults, { PTYPlugin } from '../index.ts' +import { Plugin } from '../src/v2/index.ts' + +// The bare npm ref resolves the `.` entrypoint's default export on both runtimes: +// V1 (>= 1.18.29) calls `server()`, V2 validates `{ id, setup }` and calls `setup()`. +// Before the dual-mode export the `.` entrypoint had no default at all, so the bare +// ref schema-failed on V2 (#67) and the only working path was the `./v2` subpath — +// which the V2 loader cannot install (it parses subpath refs as npm install specs). +describe('dual-mode default export', () => { + it('carries the V2 id and setup', () => { + expect(defaults.id).toBe('opencode-pty') + expect(defaults.setup).toBe(Plugin.setup) + expect(typeof defaults.setup).toBe('function') + }) + + it('carries the V1 server entrypoint', () => { + expect(defaults.server).toBe(PTYPlugin) + expect(typeof defaults.server).toBe('function') + }) + + it('re-exports the V2 plugin by name', () => { + expect(Plugin.id).toBe('opencode-pty') + }) +}) diff --git a/test/v2-built-artifact.test.ts b/test/v2-built-artifact.test.ts new file mode 100644 index 00000000..277a6145 --- /dev/null +++ b/test/v2-built-artifact.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, it } from 'bun:test' +import { existsSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import type { ToolDraft } from '../src/v2/types.ts' + +// #86: the published 0.4.0 tarball loaded `active` but registered no tools, +// because the V2 adapter shipped without calling `registerV2Tools`. Loading is +// not registration — only a real `setup()` against a recording `ctx.tool` +// proves it. These tests run the *built* artifacts, so a stale or incomplete +// `dist` cannot ship again. +const DIST_ROOT = fileURLToPath(new URL('../dist/index.js', import.meta.url)) +const DIST_V2 = fileURLToPath(new URL('../dist/src/v2/index.js', import.meta.url)) + +const EXPECTED_TOOLS = ['pty_kill', 'pty_list', 'pty_read', 'pty_spawn', 'pty_write'] + +interface RecordedTool { + name: string + description?: string + input?: unknown + execute?: unknown +} + +interface RecordingContext { + options: Record + location: { directory: string } + tool: { transform: (callback: (draft: ToolDraft) => void) => Promise } + command: { transform: (callback: () => void) => Promise } +} + +function recordingContext(): { context: RecordingContext; tools: Map } { + const tools = new Map() + const context: RecordingContext = { + options: {}, + location: { directory: '/tmp/opencode-pty-built-artifact' }, + tool: { + transform: async (callback) => { + await callback({ + add: (tool) => { + tools.set(tool.name, tool as RecordedTool) + }, + } as ToolDraft) + }, + }, + command: { + transform: async () => {}, + }, + } + return { context, tools } +} + +describe('built V2 entrypoints register the PTY tools (#86)', () => { + it('builds dist before this test can pass', () => { + expect(existsSync(DIST_V2)).toBe(true) + expect(existsSync(DIST_ROOT)).toBe(true) + }) + + for (const [label, entry] of [ + ['package root (`.` entrypoint, dual-mode default)', DIST_ROOT], + ['the ./v2 subpath entrypoint', DIST_V2], + ] as const) { + it(`${label} registers all five tools when setup runs`, async () => { + const module = await import(entry) + const plugin = module.default + + expect(plugin).toBeDefined() + expect(plugin.id).toBe('opencode-pty') + expect(typeof plugin.setup).toBe('function') + + const { context, tools } = recordingContext() + await plugin.setup(context) + + expect([...tools.keys()].sort()).toEqual(EXPECTED_TOOLS) + + for (const tool of tools.values()) { + expect(typeof tool.description).toBe('string') + expect((tool.description ?? '').length).toBeGreaterThan(0) + expect(tool.input).toBeDefined() + expect(typeof tool.execute).toBe('function') + } + }) + } +}) diff --git a/test/v2-permissions.test.ts b/test/v2-permissions.test.ts new file mode 100644 index 00000000..d8660e51 --- /dev/null +++ b/test/v2-permissions.test.ts @@ -0,0 +1,200 @@ +import { afterEach, describe, expect, it, mock, spyOn } from 'bun:test' +import { createV2Adapter, installHostAdapter } from '../src/adapters/index.ts' +import { + V2PermissionAuthorizer, + type V2PermissionAssertInput, + createV2PermissionAuthorizer, +} from '../src/adapters/v2/permissions.ts' +import { manager } from '../src/plugin/pty/manager.ts' +import { + checkCommandPermission, + getPermissionAuthorizer, + permissionRequestContext, + setPermissionAuthorizer, +} from '../src/plugin/pty/permissions.ts' +import { ptySpawn } from '../src/plugin/pty/tools/spawn.ts' +import { ptyWrite } from '../src/plugin/pty/tools/write.ts' +import { Plugin } from '../src/v2/index.ts' + +// A tool invocation as opencode V2 hands it to `execute(input, context)`. +const toolContext = { + sessionID: 'ses_test', + messageID: 'msg_test', + agent: 'build', + id: 'call_test', + progress: async () => {}, + signal: new AbortController().signal, +} + +// What the tools hand the authorizer: the tool context narrowed to the fields a +// permission check needs, with V2's `id` mapped onto `callID`. +const permissionContext = permissionRequestContext(toolContext) + +const LOCATION = '/workspace/app' + +/** `ctx.permission` double that records every assertion it is asked to make. */ +function recordingPermission(reject = false) { + const calls: V2PermissionAssertInput[] = [] + const permission = { + assert: async (input: V2PermissionAssertInput) => { + calls.push(input) + if (reject) { + throw new Error(`Permission denied: ${input.action} ${input.resources.join(' ')}`) + } + }, + } + return { calls, permission } +} + +describe('OpenCode V2 permission authorizer (#80)', () => { + afterEach(() => { + setPermissionAuthorizer(null) + manager.clearAllSessions() + mock.restore() + }) + + describe('command checks', () => { + it('delegates the command line to ctx.permission.assert as the V2 shell action', async () => { + const { calls, permission } = recordingPermission() + const authorizer = new V2PermissionAuthorizer({ permission, directory: LOCATION }) + + await authorizer.checkCommand('git', ['push', 'origin', 'main'], permissionContext) + + expect(calls).toHaveLength(1) + expect(calls[0]).toEqual({ + sessionID: 'ses_test', + agent: 'build', + action: 'shell', + resources: ['git push origin main'], + save: ['git push origin main'], + source: { type: 'tool', messageID: 'msg_test', id: 'call_test' }, + }) + }) + + it('propagates a host rejection instead of swallowing it', async () => { + const { permission } = recordingPermission(true) + const authorizer = new V2PermissionAuthorizer({ permission, directory: LOCATION }) + + expect(authorizer.checkCommand('rm', ['-rf', '/'], permissionContext)).rejects.toThrow( + 'Permission denied: shell rm -rf /' + ) + }) + + it('denies when the check cannot be attributed to a session', async () => { + const { calls, permission } = recordingPermission() + const authorizer = new V2PermissionAuthorizer({ permission, directory: LOCATION }) + + // Denying keeps a deny rule from being bypassed; allowing here would be + // exactly the hole this authorizer closes. + expect(authorizer.checkCommand('echo', ['hi'])).rejects.toThrow(/without a session/) + expect(calls).toHaveLength(0) + }) + }) + + describe('workdir checks', () => { + it('does not consult the host for a workdir inside the location', async () => { + const { calls, permission } = recordingPermission() + const authorizer = new V2PermissionAuthorizer({ permission, directory: LOCATION }) + + await authorizer.checkWorkdir(`${LOCATION}/packages/web`, permissionContext) + await authorizer.checkWorkdir(LOCATION, permissionContext) + + expect(calls).toHaveLength(0) + }) + + it('checks external_directory for a sibling directory that merely shares a prefix', async () => { + const { calls, permission } = recordingPermission() + const authorizer = new V2PermissionAuthorizer({ permission, directory: LOCATION }) + + await authorizer.checkWorkdir('/workspace/app-evil', permissionContext) + + expect(calls).toHaveLength(1) + expect(calls[0]?.action).toBe('external_directory') + expect(calls[0]?.resources).toEqual(['/workspace/app-evil', '/workspace/app-evil/*']) + }) + + it('does not treat a traversing path as inside the location', async () => { + const { calls, permission } = recordingPermission() + const authorizer = new V2PermissionAuthorizer({ permission, directory: LOCATION }) + + await authorizer.checkWorkdir(`${LOCATION}/../../etc`, permissionContext) + + expect(calls).toHaveLength(1) + expect(calls[0]?.action).toBe('external_directory') + // Resolved lexically, so a rule is matched against the real boundary. + expect(calls[0]?.resources).toEqual(['/etc', '/etc/*']) + }) + }) + + describe('adapter wiring', () => { + it('reaches ctx.permission.assert through createV2Adapter and the core dispatcher', async () => { + const { calls, permission } = recordingPermission() + installHostAdapter( + createV2Adapter({ + permissions: createV2PermissionAuthorizer(permission, LOCATION), + }) + ) + + await checkCommandPermission('git', ['push'], permissionContext) + + expect(calls).toHaveLength(1) + expect(calls[0]?.action).toBe('shell') + expect(calls[0]?.resources).toEqual(['git push']) + }) + + it('installs the authorizer from ctx.permission during Plugin.setup', async () => { + const { calls, permission } = recordingPermission() + + await Plugin.setup({ options: {}, permission }) + + expect(getPermissionAuthorizer()).toBeInstanceOf(V2PermissionAuthorizer) + await checkCommandPermission('git', ['push'], permissionContext) + expect(calls).toHaveLength(1) + }) + + it('creates no authorizer when the host exposes no permission domain', () => { + expect(createV2PermissionAuthorizer(undefined, LOCATION)).toBeUndefined() + }) + }) + + describe('tool enforcement', () => { + it('a denied command does not spawn', async () => { + const { calls, permission } = recordingPermission(true) + installHostAdapter( + createV2Adapter({ + permissions: createV2PermissionAuthorizer(permission, LOCATION), + }) + ) + const spawnSpy = spyOn(manager, 'spawn') + + await expect( + ptySpawn.execute( + { command: 'rm', args: ['-rf', '/'], description: 'denied spawn attempt' }, + toolContext as never + ) + ).rejects.toThrow('Permission denied: shell rm -rf /') + + expect(calls[0]?.resources).toEqual(['rm -rf /']) + expect(spawnSpy).not.toHaveBeenCalled() + expect(manager.list()).toHaveLength(0) + }) + + it('pty_write checks the command it types before writing it', async () => { + const { calls, permission } = recordingPermission(true) + installHostAdapter( + createV2Adapter({ + permissions: createV2PermissionAuthorizer(permission, LOCATION), + }) + ) + spyOn(manager, 'get').mockReturnValue({ status: 'running' } as never) + const writeSpy = spyOn(manager, 'write') + + await expect( + ptyWrite.execute({ id: 'pty_denied', data: 'rm -rf /\n' }, toolContext as never) + ).rejects.toThrow('Permission denied: shell rm -rf /') + + expect(calls.map((call) => call.resources[0])).toEqual(['rm -rf /']) + expect(writeSpy).not.toHaveBeenCalled() + }) + }) +})