From 9af123e5d7bdb15771d69fb427faacf32c46dfb3 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E9=99=88=E5=A5=87?=
<16399091+binaricat@users.noreply.github.com>
Date: Mon, 26 Oct 2026 07:03:14 +0000
Subject: [PATCH] feat(plugins): inspect and revoke grants and align network
lease contracts
---
application/i18n/locales/en/core.ts | 11 ++
application/i18n/locales/es/core.ts | 11 ++
application/i18n/locales/ru/core.ts | 11 ++
application/i18n/locales/zh-CN/core.ts | 11 ++
application/i18n/locales/zh-TW/core.ts | 11 ++
application/state/usePluginManager.ts | 2 +-
.../settings/tabs/PluginPackageManager.tsx | 2 +
.../tabs/PluginPermissionPanel.test.tsx | 69 ++++++++++
.../settings/tabs/PluginPermissionPanel.tsx | 75 +++++++++++
docs/plugin-platform/capability-coverage.md | 81 ++++++++++++
.../security-and-permissions.md | 27 ++++
electron/main/registerBridges.cjs | 2 +
.../generated/plugin-contract.schema.json | 125 ++++++++++++++++++
electron/plugins/hostService.cjs | 6 +-
electron/plugins/leaseHttpExample.test.cjs | 47 +++++++
electron/plugins/networkBroker.cjs | 16 +--
electron/plugins/networkBroker.test.cjs | 11 ++
electron/plugins/pluginBridge.cjs | 35 +++++
electron/plugins/pluginBridge.test.cjs | 32 +++++
electron/plugins/pluginManager.cjs | 16 +++
electron/plugins/pluginManager.test.cjs | 45 +++++++
electron/plugins/secureCapabilities.test.cjs | 2 +-
electron/preload/api.cjs | 2 +
examples/plugins/lease-http/README.md | 25 ++++
examples/plugins/lease-http/browser.js | 24 ++++
.../plugins/lease-http/netcatty.plugin.json | 25 ++++
global.d.ts | 10 ++
.../schema/plugin-contract.schema.json | 125 ++++++++++++++++++
.../src/generated/plugin-contract.ts | 30 +++++
packages/plugin-contract/src/index.ts | 2 +
packages/plugin-sdk/src/index.test.ts | 18 +++
packages/plugin-sdk/src/index.ts | 19 +--
32 files changed, 900 insertions(+), 28 deletions(-)
create mode 100644 components/settings/tabs/PluginPermissionPanel.test.tsx
create mode 100644 components/settings/tabs/PluginPermissionPanel.tsx
create mode 100644 docs/plugin-platform/capability-coverage.md
create mode 100644 electron/plugins/leaseHttpExample.test.cjs
create mode 100644 examples/plugins/lease-http/README.md
create mode 100644 examples/plugins/lease-http/browser.js
create mode 100644 examples/plugins/lease-http/netcatty.plugin.json
diff --git a/application/i18n/locales/en/core.ts b/application/i18n/locales/en/core.ts
index 5653e8d31..5bdef9a35 100644
--- a/application/i18n/locales/en/core.ts
+++ b/application/i18n/locales/en/core.ts
@@ -1245,6 +1245,17 @@ Highlight the focused split pane:
"settings.plugins.manager.disable": "Disable",
"settings.plugins.manager.remove": "Uninstall",
"settings.plugins.manager.removeNote": "Uninstall removes package code and local KV data. User-owned settings, secrets and sync sidecars are retained.",
+ "settings.plugins.permissions.title": "Active grants",
+ "settings.plugins.permissions.refresh": "Refresh",
+ "settings.plugins.permissions.loading": "Loading grants...",
+ "settings.plugins.permissions.empty": "No active grants. One-use decisions are not retained.",
+ "settings.plugins.permissions.always": "Until revoked",
+ "settings.plugins.permissions.application": "Until Netcatty exits",
+ "settings.plugins.permissions.session": "Until the session closes",
+ "settings.plugins.permissions.audit": "Recent security events (up to 100)",
+ "settings.plugins.permissions.revoke": "Disable and revoke all grants",
+ "settings.plugins.permissions.revokeNote": "This disables the plugin, cancels its work, and removes saved grants. Enable it again to request new access.",
+ "settings.plugins.permissions.unavailable": "Plugin permission management is unavailable",
"settings.plugins.manager.permissions": "Declared permissions",
"settings.plugins.manager.permissionNote": "From the manifest, not a grant. Enabled allows lazy activation; required permissions are requested before first activation and optional permissions when used. Sensitive operations still pass host checks.",
"settings.plugins.manager.noPermissions": "No privileged permissions declared.",
diff --git a/application/i18n/locales/es/core.ts b/application/i18n/locales/es/core.ts
index e0e395161..27abdaebe 100644
--- a/application/i18n/locales/es/core.ts
+++ b/application/i18n/locales/es/core.ts
@@ -1245,6 +1245,17 @@ Resalta el panel dividido enfocado:
"settings.plugins.manager.disable": "Desactivar",
"settings.plugins.manager.remove": "Desinstalar",
"settings.plugins.manager.removeNote": "La desinstalación elimina el código y los datos KV locales. Se conservan los ajustes del usuario, los secretos y los datos auxiliares de sincronización.",
+ "settings.plugins.permissions.title": "Autorizaciones activas",
+ "settings.plugins.permissions.refresh": "Actualizar",
+ "settings.plugins.permissions.loading": "Cargando autorizaciones...",
+ "settings.plugins.permissions.empty": "No hay autorizaciones activas. Las decisiones de un solo uso no se conservan.",
+ "settings.plugins.permissions.always": "Hasta su revocación",
+ "settings.plugins.permissions.application": "Hasta cerrar Netcatty",
+ "settings.plugins.permissions.session": "Hasta cerrar la sesión",
+ "settings.plugins.permissions.audit": "Eventos de seguridad recientes (hasta 100)",
+ "settings.plugins.permissions.revoke": "Desactivar y revocar todas las autorizaciones",
+ "settings.plugins.permissions.revokeNote": "Desactiva el complemento, cancela su trabajo y elimina las autorizaciones guardadas. Actívelo para solicitar acceso de nuevo.",
+ "settings.plugins.permissions.unavailable": "La gestión de permisos no está disponible",
"settings.plugins.manager.permissions": "Permisos declarados",
"settings.plugins.manager.permissionNote": "Del manifiesto, no es una autorización. Activado permite la activación diferida; los permisos obligatorios se solicitan antes del primer uso y los opcionales cuando se necesitan. Las operaciones sensibles siguen verificándose.",
"settings.plugins.manager.noPermissions": "No se han declarado permisos privilegiados.",
diff --git a/application/i18n/locales/ru/core.ts b/application/i18n/locales/ru/core.ts
index c8ec349d5..cbc84b719 100644
--- a/application/i18n/locales/ru/core.ts
+++ b/application/i18n/locales/ru/core.ts
@@ -1140,6 +1140,17 @@ export const ruCoreMessages: Messages = {
"settings.plugins.manager.disable": "Отключить",
"settings.plugins.manager.remove": "Удалить",
"settings.plugins.manager.removeNote": "Удаление очищает код пакета и локальные данные KV. Настройки пользователя, секреты и данные синхронизации сохраняются.",
+ "settings.plugins.permissions.title": "Действующие разрешения",
+ "settings.plugins.permissions.refresh": "Обновить",
+ "settings.plugins.permissions.loading": "Загрузка разрешений...",
+ "settings.plugins.permissions.empty": "Действующих разрешений нет. Одноразовые решения не сохраняются.",
+ "settings.plugins.permissions.always": "До отзыва",
+ "settings.plugins.permissions.application": "До выхода из Netcatty",
+ "settings.plugins.permissions.session": "До закрытия сеанса",
+ "settings.plugins.permissions.audit": "Последние события безопасности (до 100)",
+ "settings.plugins.permissions.revoke": "Отключить и отозвать все разрешения",
+ "settings.plugins.permissions.revokeNote": "Плагин будет отключён, его задачи отменены, а сохранённые разрешения удалены. Включите его для нового запроса доступа.",
+ "settings.plugins.permissions.unavailable": "Управление разрешениями недоступно",
"settings.plugins.manager.permissions": "Заявленные разрешения",
"settings.plugins.manager.permissionNote": "Из манифеста, а не предоставленные права. Включение допускает отложенную активацию; обязательные разрешения запрашиваются перед ней, необязательные — при использовании. Чувствительные операции проверяются приложением.",
"settings.plugins.manager.noPermissions": "Привилегированные разрешения не заявлены.",
diff --git a/application/i18n/locales/zh-CN/core.ts b/application/i18n/locales/zh-CN/core.ts
index 1ab702c7b..3e949a8d8 100644
--- a/application/i18n/locales/zh-CN/core.ts
+++ b/application/i18n/locales/zh-CN/core.ts
@@ -1160,6 +1160,17 @@ Vaults 标签保持扁平,不使用这块背景。
"settings.plugins.manager.disable": "停用",
"settings.plugins.manager.remove": "卸载",
"settings.plugins.manager.removeNote": "卸载会移除插件代码和本地 KV 数据,保留用户设置、秘密存储和同步 sidecar。",
+ "settings.plugins.permissions.title": "实际授权",
+ "settings.plugins.permissions.refresh": "刷新",
+ "settings.plugins.permissions.loading": "正在读取授权...",
+ "settings.plugins.permissions.empty": "没有有效授权。单次决定不会保留。",
+ "settings.plugins.permissions.always": "直到撤销",
+ "settings.plugins.permissions.application": "直到退出 Netcatty",
+ "settings.plugins.permissions.session": "直到会话关闭",
+ "settings.plugins.permissions.audit": "最近的安全事件(最多 100 条)",
+ "settings.plugins.permissions.revoke": "停用并撤销全部授权",
+ "settings.plugins.permissions.revokeNote": "此操作会停用插件、取消其工作并删除已保存的授权。重新启用后可申请新授权。",
+ "settings.plugins.permissions.unavailable": "插件授权管理不可用",
"settings.plugins.manager.permissions": "声明的权限",
"settings.plugins.manager.permissionNote": "来自 manifest,不代表已授权。启用表示允许按需激活;必需权限在首次激活前申请,可选权限在用到时申请。敏感操作仍受宿主检查。",
"settings.plugins.manager.noPermissions": "未声明特权权限。",
diff --git a/application/i18n/locales/zh-TW/core.ts b/application/i18n/locales/zh-TW/core.ts
index eb7869555..4bdca2ccb 100644
--- a/application/i18n/locales/zh-TW/core.ts
+++ b/application/i18n/locales/zh-TW/core.ts
@@ -1163,6 +1163,17 @@ Vaults 分頁維持扁平,不使用這塊背景。
"settings.plugins.manager.disable": "停用",
"settings.plugins.manager.remove": "卸載",
"settings.plugins.manager.removeNote": "卸載會移除插件代碼和本地 KV 數據,保留用戶設置、秘密存儲和同步 sidecar。",
+ "settings.plugins.permissions.title": "實際授權",
+ "settings.plugins.permissions.refresh": "重新整理",
+ "settings.plugins.permissions.loading": "正在讀取授權...",
+ "settings.plugins.permissions.empty": "沒有有效授權。單次決定不會保留。",
+ "settings.plugins.permissions.always": "直到撤銷",
+ "settings.plugins.permissions.application": "直到退出 Netcatty",
+ "settings.plugins.permissions.session": "直到工作階段關閉",
+ "settings.plugins.permissions.audit": "最近的安全事件(最多 100 筆)",
+ "settings.plugins.permissions.revoke": "停用並撤銷全部授權",
+ "settings.plugins.permissions.revokeNote": "此操作會停用外掛、取消其工作並刪除已儲存的授權。重新啟用後可申請新授權。",
+ "settings.plugins.permissions.unavailable": "外掛授權管理無法使用",
"settings.plugins.manager.permissions": "聲明的權限",
"settings.plugins.manager.permissionNote": "來自 manifest,不代表已授權。啟用表示允許按需激活;必需權限在首次激活前申請,可選權限在用到時申請。敏感操作仍受宿主檢查。",
"settings.plugins.manager.noPermissions": "未聲明特權權限。",
diff --git a/application/state/usePluginManager.ts b/application/state/usePluginManager.ts
index c2dffbbf0..f8cd692ba 100644
--- a/application/state/usePluginManager.ts
+++ b/application/state/usePluginManager.ts
@@ -41,7 +41,7 @@ export function usePluginManager() {
}
}, [refresh]);
return {
- plugins, available, busy, error, credentialStorageAvailable,
+ plugins, available, busy, error, credentialStorageAvailable, refresh,
importPackage: () => run(async (bridge) => {
if (!bridge.selectFile || !bridge.installPluginPackage) throw new Error('Plugin import unavailable');
const path = await bridge.selectFile('Import plugin package', undefined, [{ name: 'Netcatty plugin', extensions: ['ncpkg'] }]);
diff --git a/components/settings/tabs/PluginPackageManager.tsx b/components/settings/tabs/PluginPackageManager.tsx
index 338b8aa0e..68b6581eb 100644
--- a/components/settings/tabs/PluginPackageManager.tsx
+++ b/components/settings/tabs/PluginPackageManager.tsx
@@ -1,6 +1,7 @@
import { describePluginPermission } from '@/domain/pluginPermissionDescriptions.cjs';
import { describePluginRuntime } from '@/domain/pluginRuntimePolicy.cjs';
import React, { useRef, useState } from 'react';
+import { PluginPermissionPanel } from './PluginPermissionPanel';
import { PluginBrandIcon } from '../../plugins/PluginBrandIcon';
import { ArrowLeft } from 'lucide-react';
import { usePluginManager } from '../../../application/state/usePluginManager';
@@ -108,6 +109,7 @@ export function PluginPackageManager({ manager, onSelectionChange }: { manager:
{plugin.runtime.lastError &&
{t('settings.plugins.manager.lastError')}: {plugin.runtime.lastError}
}
{selected === plugin.id && <>
+ { await manager.refresh(); }} />
{removing === plugin.id ?
{t('settings.plugins.manager.removeNote')}
diff --git a/components/settings/tabs/PluginPermissionPanel.test.tsx b/components/settings/tabs/PluginPermissionPanel.test.tsx
new file mode 100644
index 000000000..44879c2dd
--- /dev/null
+++ b/components/settings/tabs/PluginPermissionPanel.test.tsx
@@ -0,0 +1,69 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { JSDOM } from 'jsdom';
+
+test('permission panel refreshes real grants, revokes once, and keeps stale reads from replacing new results', async () => {
+ const dom = new JSDOM('
', { pretendToBeVisual: true, url: 'http://localhost' });
+ const previous = new Map
();
+ const install = (key: string, value: unknown) => {
+ previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
+ Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
+ };
+ for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent']) {
+ install(key, key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window]);
+ }
+ install('IS_REACT_ACT_ENVIRONMENT', true);
+ const { default: React, act } = await import('react');
+ const { createRoot } = await import('react-dom/client');
+ const { I18nProvider } = await import('../../../application/i18n/I18nProvider');
+ const { PluginPermissionPanel } = await import('./PluginPermissionPanel');
+ const root = createRoot(document.getElementById('root')!);
+ const initial = {
+ grants: [{ permission: 'network', resource: 'https://synthetic.invalid/', resourceKind: 'exact', scope: 'always' as const, sessionId: null, grantedAt: 1 }],
+ audit: [{ event: 'permission.used', createdAt: 2, permission: 'network' }],
+ };
+ let reads = 0;
+ let revokes = 0;
+ let changed = 0;
+ let staleRead: (value: typeof initial) => void = () => {};
+ let releaseRevoke: () => void = () => {};
+ const revokePending = new Promise((resolve) => { releaseRevoke = resolve; });
+ Object.assign(dom.window, { netcatty: {
+ async getPluginPermissions(id: string) {
+ assert.equal(id, 'com.example.synthetic');
+ reads++;
+ if (reads === 2) return new Promise((resolve) => { staleRead = resolve; });
+ return reads > 2 ? { grants: [], audit: [] } : initial;
+ },
+ async revokePluginPermissions(id: string) { assert.equal(id, 'com.example.synthetic'); revokes++; await revokePending; },
+ } });
+ const button = (text: string) => Array.from(document.querySelectorAll('button')).find((item) => item.textContent === text)!;
+ try {
+ await act(async () => root.render( { changed++; }} />));
+ assert.match(document.body.textContent!, /synthetic.invalid/);
+ assert.equal(document.querySelector('text'), null, 'resource is rendered as plain text');
+ assert.match(document.body.textContent!, /Until revoked/);
+ await act(async () => { button('Refresh').click(); });
+ await act(async () => {
+ button('Disable and revoke all grants').click();
+ button('Disable and revoke all grants').click();
+ });
+ assert.equal(revokes, 1);
+ assert.equal(button('Refresh').disabled, true);
+ await act(async () => { releaseRevoke(); });
+ assert.equal(changed, 1);
+ assert.match(document.body.textContent!, /No active grants/);
+ await act(async () => { staleRead(initial); });
+ assert.doesNotMatch(document.body.textContent!, /synthetic.invalid/);
+ Object.assign(dom.window, { netcatty: { async getPluginPermissions() { throw new Error('synthetic read failed'); } } });
+ await act(async () => { button('Refresh').click(); });
+ assert.match(document.querySelector('[role="alert"]')?.textContent ?? '', /synthetic read failed/);
+ } finally {
+ await act(async () => root.unmount());
+ dom.window.close();
+ for (const [key, descriptor] of previous) {
+ if (descriptor) Object.defineProperty(globalThis, key, descriptor);
+ else Reflect.deleteProperty(globalThis, key);
+ }
+ }
+});
diff --git a/components/settings/tabs/PluginPermissionPanel.tsx b/components/settings/tabs/PluginPermissionPanel.tsx
new file mode 100644
index 000000000..c4246c6ff
--- /dev/null
+++ b/components/settings/tabs/PluginPermissionPanel.tsx
@@ -0,0 +1,75 @@
+import React, { useCallback, useEffect, useRef, useState } from 'react';
+import { netcattyBridge } from '../../../infrastructure/services/netcattyBridge';
+import { useI18n } from '../../../application/i18n/I18nProvider';
+import { describePluginPermission } from '../../../domain/pluginPermissionDescriptions.cjs';
+import { Button } from '../../ui/button';
+
+/** Host UI only. Plugin views cannot query or mutate this security state. */
+export function PluginPermissionPanel({ pluginId, onChanged }: {
+ pluginId: string;
+ onChanged: () => Promise;
+}) {
+ const { t, resolvedLocale } = useI18n();
+ const [snapshot, setSnapshot] = useState(null);
+ const [error, setError] = useState(null);
+ const [busy, setBusy] = useState(false);
+ const generation = useRef(0);
+ const pending = useRef(false);
+ const refresh = useCallback(async () => {
+ const current = ++generation.current;
+ setError(null);
+ try {
+ const bridge = netcattyBridge.require();
+ if (!bridge.getPluginPermissions) throw new Error(t('settings.plugins.permissions.unavailable'));
+ const result = await bridge.getPluginPermissions(pluginId);
+ if (current === generation.current) setSnapshot(result);
+ } catch (cause) {
+ if (current === generation.current) setError(cause instanceof Error ? cause.message : String(cause));
+ }
+ }, [pluginId, t]);
+ useEffect(() => {
+ const requestGeneration = generation;
+ void refresh();
+ return () => { requestGeneration.current++; };
+ }, [refresh]);
+ const revoke = async () => {
+ if (pending.current) return;
+ pending.current = true;
+ setBusy(true);
+ setError(null);
+ try {
+ const bridge = netcattyBridge.require();
+ if (!bridge.revokePluginPermissions) throw new Error(t('settings.plugins.permissions.unavailable'));
+ await bridge.revokePluginPermissions(pluginId);
+ await onChanged();
+ await refresh();
+ } catch (cause) { setError(cause instanceof Error ? cause.message : String(cause)); }
+ finally { pending.current = false; setBusy(false); }
+ };
+ return
+
+
{t('settings.plugins.permissions.title')}
+
+
+ {error && {error}
}
+ {!snapshot && !error && {t('settings.plugins.permissions.loading')}
}
+ {snapshot && <>
+ {snapshot.grants.length === 0 && {t('settings.plugins.permissions.empty')}
}
+ {snapshot.grants.map((grant, index) =>
+
{describePluginPermission(grant.permission, resolvedLocale).label}
+
{grant.resource}
+
{t(`settings.plugins.permissions.${grant.scope}`)}{grant.sessionId ? ` · ${grant.sessionId}` : ''}
+
+
)}
+
+ {t('settings.plugins.permissions.audit')}
+ {snapshot.audit.map((entry, index) => -
+ {' · '}
+ {entry.event}{entry.permission ? ` · ${entry.permission}` : ''}{entry.scope ? ` · ${entry.scope}` : ''}
+
)}
+
+ {t('settings.plugins.permissions.revokeNote')}
+
+ >}
+ ;
+}
diff --git a/docs/plugin-platform/capability-coverage.md b/docs/plugin-platform/capability-coverage.md
new file mode 100644
index 000000000..c13a27632
--- /dev/null
+++ b/docs/plugin-platform/capability-coverage.md
@@ -0,0 +1,81 @@
+# Sandbox capability coverage
+
+This matrix tracks expansion from Draft #3951 at
+`e5bd294cddbf58dfe04c646b6291933d980498fd`. Each accepted item requires a
+canonical schema, generated SDK, broker, permission policy, quota and audit,
+host adapter, lifecycle cleanup, synthetic boundary tests, review, and exact-SHA
+CI. Enumeration in a manifest is not a working API. Status `planned` does not
+mean complete. Existing APIs remain available.
+
+## Coverage matrix
+
+| Subsystem | Working API at baseline | Enumeration or missing adapter | Accepted bounded entry | Data and action risk | Authorization resource | Revocation, audit, quota | Verification and disposition |
+| --- | --- | --- | --- | --- | --- | --- | --- |
+| Authorization management | Engine `listGrants`, `revokeAll`, database audit | Manager shows declarations only | Host-only grant list, bounded audit summary, disable and revoke | Paths, session IDs, grant metadata are sensitive | Exact plugin ID, trusted app sender | Serialized manager mutation, disable before revoke, runtime teardown, retained audit | Batch 1 implemented: host/manager/UI tests. Native acceptance pending. No plugin RPC for managing grants |
+| Network and credential leases | `network.request`, `credentials.createLease`, single-use host redemption | SDK request omits lease and authorization fields | Canonical request types matching broker | Network mutation and credentials | Exact origin plus secret reference and operation | Existing timeout, redirects, byte quotas, runtime checks, lease TTL | Batch 1 implemented: canonical schema and SDK, synthetic fixture and lease tests, feature negotiation. Native acceptance pending. No plaintext secret API |
+| Commands, menus, toolbar, status bar, views | `commands.execute`, settings, context keys, view state and messages, UI contributions | No editor or SFTP menu slots | Existing contribution system | Plugin text and arguments may be sensitive | Namespaced contributions and permissions | Existing lifecycle, rate and message limits | Existing tests. New context menu slots planned with bounded context DTOs |
+| Terminal providers | Decorations, links, completion, snapshots through provider requests | Session change delivery follows prior provider request and non-once grant | Preserve providers. Standalone selected-session watch planned | Hostnames, session state, endpoint identity | Host-selected session, runtime identity | Session-close and revoke cleanup, bounded event rate | Existing provider tests. Ordinary views cannot independently subscribe today |
+| Current context and host picker | Host context keys are boolean state | `vault.metadata` enumeration is not generic SDK | Selected host/session DTO from an explicit whitelist | Labels and endpoint metadata are sensitive | Host-owned user-action context, selected host/session | TTL, runtime and session invalidation, redacted audit | Planned. Never reuse agent `sanitizeHostForAgent` as plugin DTO |
+| Terminal selection and input draft | Provider-supplied snapshots, completion suggestions | No explicit selection-share or draft API | User shares selection, plugin proposes a visible editable draft | Terminal plaintext, accidental execution | Host action token plus exact live session/endpoint | Single-use token, size cap, no plaintext audit, active identity before commit | Planned. Reject Enter/control characters for draft insertion. No full history or direct shell |
+| Native interactions and clipboard | Native permission dialogs | Clipboard enum only. No quick-pick/input/progress/toast SDK | Host-owned prompts, explicit copy/paste with preview | Clipboard and input may contain secrets, prompt spam | Host action context plus clipboard direction | Cancellation, request count and byte caps, runtime cleanup | Planned. No background reads or trusted plugin `userGesture` boolean |
+| Local filesystem | Read file, stat, overwrite existing regular file | Directory listing lacks same-handle native adapter | Keep current boundary, evaluate file picker handles | Arbitrary local file content and writes | Canonical exact path or selected file handle | Inode checks, no symlink alias, bounded bytes, active runtime | Existing filesystem tests. Directory enumeration and new arbitrary-path creation deferred until portable safe native adapter exists |
+| SFTP and remote files | No generic plugin API | `sftp.read` and `sftp.write` enumerated only | Host-selected session/path/mode/TTL handles, read and explicit save/upload | Remote secrets and destructive overwrite | Live endpoint identity, exact path, read/write split | Cancel streams, byte quota, overwrite confirmation, close/revoke cleanup | Batch 2 planned. Never forward arbitrary MCP catalog or session ID alone |
+| Editor and Notes | No plugin document API | No versioned snapshot or edit preview | Explicit snapshot and versioned proposed edit | Document secrets, lost updates, executable files | Selected document plus revision and action token | Version conflict check, preview, bounded bytes, revocation | Planned evaluation after shared action context. No unattended edits |
+| Snippets and scripts | Provider import drafts only | No generic read/run API | Explicit selection and create draft | Script contents may contain secrets. Running executes commands | Selected item, read versus draft write | Preview, byte cap, no automatic execution | Planned evaluation. Script `run` and onConnect modification deferred |
+| Connections and authentication | Connection/authentication providers, opaque credentials, streams | Generic host open/connect absent | Existing providers remain | Connect can execute saved onConnect scripts | Provider operation plus live endpoint and credential lease | Existing provider lifecycle, streams and quotas | Existing tests. Generic connect is a write/execution capability, deferred pending explicit execution design |
+| Sync and storage | Local namespaced KV, encrypted-object sync providers, opt-in setting sidecars | No general KV cloud sync | Existing opt-in provider protocol | Conflicts, deletes, credential access | Provider/account/object, settings scope | Existing limits and lifecycle, non-cascade metadata | Existing sync tests. General KV sync deferred until conflict/delete/quota/migration policy is defined |
+| Vault and keychain | Credential references and import preview/commit | Metadata/write enums do not grant a generic Vault SDK | Only user-selected whitelist DTOs and drafts | Notes, environmentVariables, startupCommand, keys and credentials | Selected object plus field/direction | Explicit preview, identity checks, redacted audit | Full Vault export and secret reads deferred indefinitely. No agent field-exclusion DTO reuse |
+| System manager and Docker | No plugin system API | Agent/MCP adapters are separate authority | Typed read-only summaries excluding args/env/inspect | Process command lines and Docker inspect can expose secrets | Selected live session and summary kind | Bounded result, endpoint identity, cancellation | Planned evaluation. Arbitrary process/inspect forwarding deferred |
+| Port forwarding | No generic plugin API | Existing agent start is write-sensitive | Selected rule status and open host form | Rule endpoints and local exposure | Selected rule plus host action | Bounded DTO, session close and revoke | Planned evaluation. Direct start deferred until binding/listener approval design |
+| Themes, settings, appearance, i18n | Contributions, scoped setting API, environment updates | No arbitrary application settings write | Existing namespaced contributions. Candidate: declarative global ThemePack using the 19 semantic tokens in `uiThemes.ts`, with preview/apply/reset and uninstall fallback | Settings can contain sensitive plugin values. A theme must preserve contrast and security UI | Plugin namespace, declared scope | Existing persistence and lifecycle, explicit sync flag | Existing tests. ThemePack design pending parent review of allowed tokens, accessibility and fallback. No arbitrary host DOM/CSS, remote CSS/fonts or security UI hiding. Arbitrary host settings mutation deferred |
+| Transfer center | Host transfer queue exists, no plugin entry | No ownership-bound task API | Observe and cancel only plugin-created tasks | Paths and host endpoints reveal user data. Cancel may leave partial files | Own transfer handle plus source/destination authority | Shared backpressure, cancel/close cleanup, honest partial status | Planned with batch 2. Do not broadcast or cancel other tasks |
+| AI, MCP, automation | Host agent catalog and harness exist separately | No generic plugin AI or tool forwarding | Selection-to-proposal workflow through the same controlled primitives | Content disclosure, account authority and model cost | Explicit content sharing plus service origin/budget | No inherited history, tools, account, or hidden cron | Controlled workflow planned. Generic host AI and visible schedules deferred to distinct product decision |
+| Known hosts, app lock and global security | Host security management UI | No plugin management API | Future allowlisted security-page navigation | Host-key trust, unlock, keys and security policy affect all sessions | Host navigation action only | No mutation or sensitive DTO | Security policy mutation, private-key reads, auto-trust and unlocking deferred indefinitely |
+| Plugin blob/cache | Local KV exists | No exclusive blob cache | Evaluate bounded plugin-owned cache when a real workflow needs it | Disk growth and lifecycle ambiguity | Plugin namespace, no arbitrary path | Size quota, eviction and uninstall policy required | Deferred until a concrete larger-than-KV workflow establishes value and retention policy |
+| Distribution and runtimes | Browser-only public catalog, immutable packages, advanced developer gate | Signing/trust and release remain separate phase | Retain existing boundary | Package execution and publisher trust | Pinned catalog selection, hash, engine/features | Existing install transaction, quarantine and cleanup | No merge/release. Do not extend to arbitrary Node, IPC, shell, or global capabilities |
+
+## Delivery order and stopping rule
+
+1. Batch 1: actual authorization management plus network contract consistency.
+ Keep the existing manager layout. Add one independent permission panel.
+2. Batch 1b: host action context, native interactions, selected context and terminal
+ sharing/drafts. A plugin-supplied gesture is never authority.
+3. Batch 2: SFTP selected-file handles and explicit transfer destinations.
+4. Reassess editor, Notes, snippets, menus, system summaries, and port forwarding
+ using the tested host-action and resource primitives.
+
+Stop only when every row is implemented and tested, reasonably deferred with a
+specific boundary and rationale, or awaiting a concrete user decision. A
+planned row remains unfinished. Native screenshots and recordings belong to
+the parent thread. Real credentials, hosts, or transfers require approval for a
+specific target there. Synthetic checks do not establish native acceptance.
+
+## Batch 1 evidence and next workflow
+
+The independent permission panel adds only an import and a detail mount to
+`components/settings/tabs/PluginPackageManager.tsx`. It uses the manager hook's
+new `refresh()` after host revocation. Marketplace layout remains owned by the
+parallel UI layer. Five locale files contain the panel strings.
+
+The next usable workflow is a browser plugin that asks a host quick-pick/input
+question, then explicitly copies its result or asks the user to share clipboard
+text. The host displays the plugin source and action before reading or writing.
+A canonical `HostInteractionRequest` and bounded result carry only text/choice
+IDs. The host owns request IDs, requester webContents, runtime/version, TTL,
+cancellation, and the consent result. The renderer cannot reply for another
+window. Plugin `userGesture` values are ignored. Runtime/revoke shutdown aborts
+all outstanding prompts and ignores late replies. A shared prompt primitive
+then supports selected host/session context, selection share, and input drafts.
+
+Before proceeding to the sensitive context/terminal and SFTP entries, the
+native path must prove consent, cancellation, quota, and identity binding with
+synthetic data. UI screenshots and real-resource approval remain parent-owned.
+
+Baseline code references: `electron/plugins/hostService.cjs`,
+`secureCapabilities.cjs`, `permissionEngine.cjs`, `terminalProviderService.cjs`,
+`filesystemBroker.cjs`, `extensionProviderService.cjs`,
+`packages/plugin-sdk/src/index.ts`, and
+`packages/plugin-contract/schema/plugin-contract.schema.json`. Host business
+implementations under `electron/capabilities/catalog/` are reference material,
+not plugin authority. `infrastructure/ai/vaultAgentBridgeClient.ts` is not a
+plugin DTO sanitizer.
diff --git a/docs/plugin-platform/security-and-permissions.md b/docs/plugin-platform/security-and-permissions.md
index cf1bfe352..f5ff5922c 100644
--- a/docs/plugin-platform/security-and-permissions.md
+++ b/docs/plugin-platform/security-and-permissions.md
@@ -226,3 +226,30 @@ after durable user data can exist.
- PR 9 supplies signed publisher principals and trust policy through placement;
signed identity changes force a fresh grant instead of widening an unsigned
grant silently.
+
+## Inspect and revoke actual grants
+
+The installed package detail separates declared permissions from **Active
+grants**. The host-only panel lists resource, scope, session (when applicable),
+and grant time. One-use decisions do not appear as retained grants. Refresh
+reads the engine again. Recent security events include at most 100 entries and
+project only event, time, permission, and scope. Arbitrary database details,
+operation IDs, terminal content, and credential material never cross this UI
+boundary.
+
+**Disable and revoke all grants** runs through the manager mutation queue. It
+persists disabled state before revoking grants, invalidates contributions, and
+waits for runtime shutdown. Existing runtime teardown cancels RPC, streams,
+leases, providers, and companions. A containment failure is reported as a
+failure and leaves the plugin disabled. Explicit enable requests fresh access.
+This management bridge is available only to the trusted app renderer. It is
+not a plugin RPC method and grants no plugin authority over another package.
+
+`PluginNetworkRequest` and `PluginNetworkResponse` now derive from the canonical
+schema. `credentialLease` and `authorization` describe the existing host lease
+injection path. Hosts advertise `network.credential-lease` for discovery without
+changing existing API versions or disabling legacy requests. Plugins may
+require that feature or handle its absence. Optional authorization defaults to
+Bearer. Basic authorization accepts a bounded username. Plaintext is redeemed
+only inside the host after origin permission and operation binding checks.
+See the [synthetic fixture](../../examples/plugins/lease-http/README.md).
diff --git a/electron/main/registerBridges.cjs b/electron/main/registerBridges.cjs
index 379675229..5c19847cd 100644
--- a/electron/main/registerBridges.cjs
+++ b/electron/main/registerBridges.cjs
@@ -217,6 +217,8 @@ function createBridgeRegistrar(context) {
});
registerPluginBridge(ipcMain, {
manager: pluginHostService?.manager,
+ permissionEngine: pluginHostService?.permissionEngine,
+ database: pluginHostService?.database,
catalogService: pluginHostService?.catalogService,
contributionService: pluginHostService?.contributionService,
terminalProviderService: pluginHostService?.terminalProviderService,
diff --git a/electron/plugins/generated/plugin-contract.schema.json b/electron/plugins/generated/plugin-contract.schema.json
index b7d5586bc..927317ccf 100644
--- a/electron/plugins/generated/plugin-contract.schema.json
+++ b/electron/plugins/generated/plugin-contract.schema.json
@@ -231,6 +231,131 @@
},
"additionalProperties": false
},
+ "NetworkCredentialLeaseFeature": {
+ "const": "network.credential-lease"
+ },
+ "PluginNetworkAuthorization": {
+ "type": "object",
+ "properties": {
+ "scheme": {
+ "type": "string",
+ "enum": [
+ "Basic",
+ "Bearer"
+ ]
+ },
+ "username": {
+ "type": "string",
+ "maxLength": 8192,
+ "pattern": "^[^\\u0000-\\u001f\\u007f]*$"
+ }
+ },
+ "additionalProperties": false
+ },
+ "PluginNetworkRequest": {
+ "description": "Origin-authorized HTTP request. The host consumes a one-use credentialLease for network:; plaintext credentials never return to the plugin.",
+ "type": "object",
+ "required": [
+ "url"
+ ],
+ "properties": {
+ "url": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 8192
+ },
+ "method": {
+ "type": "string",
+ "enum": [
+ "GET",
+ "POST",
+ "PUT",
+ "PATCH",
+ "DELETE",
+ "HEAD"
+ ]
+ },
+ "headers": {
+ "type": "object",
+ "maxProperties": 64,
+ "additionalProperties": {
+ "type": "string",
+ "maxLength": 8192
+ }
+ },
+ "body": {
+ "type": "object",
+ "required": [
+ "encoding",
+ "data"
+ ],
+ "properties": {
+ "encoding": {
+ "enum": [
+ "utf8",
+ "base64"
+ ]
+ },
+ "data": {
+ "type": "string"
+ }
+ },
+ "additionalProperties": false
+ },
+ "timeoutMs": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 300000
+ },
+ "credentialLease": {
+ "$ref": "#/$defs/SecretLeaseRef"
+ },
+ "authorization": {
+ "$ref": "#/$defs/PluginNetworkAuthorization"
+ }
+ },
+ "additionalProperties": false
+ },
+ "PluginNetworkResponse": {
+ "type": "object",
+ "required": [
+ "url",
+ "status",
+ "headers",
+ "body"
+ ],
+ "properties": {
+ "url": {
+ "type": "string"
+ },
+ "status": {
+ "type": "integer"
+ },
+ "headers": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ }
+ },
+ "body": {
+ "type": "object",
+ "required": [
+ "encoding",
+ "data"
+ ],
+ "properties": {
+ "encoding": {
+ "const": "base64"
+ },
+ "data": {
+ "type": "string"
+ }
+ },
+ "additionalProperties": false
+ }
+ },
+ "additionalProperties": false
+ },
"SemanticVersion": {
"type": "string",
"pattern": "^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-(?:0|[1-9]\\d*|\\d*[A-Za-z-][0-9A-Za-z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"
diff --git a/electron/plugins/hostService.cjs b/electron/plugins/hostService.cjs
index 46d76335b..ca04cad4f 100644
--- a/electron/plugins/hostService.cjs
+++ b/electron/plugins/hostService.cjs
@@ -1,6 +1,7 @@
"use strict";
const path = require("node:path");
+const NETWORK_CREDENTIAL_LEASE_FEATURE = require("./generated/plugin-contract.schema.json").$defs.NetworkCredentialLeaseFeature.const;
const { assertBrowserOnlyPlugin } = require("../../domain/pluginRuntimePolicy.cjs");
const { isPluginDevelopmentEnabled, PLUGIN_API_VERSION } = require("./constants.cjs");
@@ -92,7 +93,7 @@ function createPluginHostService(options) {
database,
netcattyVersion: options.app.getVersion(),
apiVersion: PLUGIN_API_VERSION,
- supportedFeatures: [...new Set(["metadata.brand-icon", ...(options.supportedFeatures ?? [])])],
+ supportedFeatures: [...new Set(["metadata.brand-icon", NETWORK_CREDENTIAL_LEASE_FEATURE, ...(options.supportedFeatures ?? [])])],
});
const contributionIconService = new PluginContributionIconService({
database,
@@ -223,7 +224,7 @@ function createPluginHostService(options) {
paths,
netcattyVersion: options.app.getVersion(),
apiVersion: PLUGIN_API_VERSION,
- supportedFeatures: [...new Set(["metadata.brand-icon", ...(options.supportedFeatures ?? [])])],
+ supportedFeatures: [...new Set(["metadata.brand-icon", NETWORK_CREDENTIAL_LEASE_FEATURE, ...(options.supportedFeatures ?? [])])],
runtimeDirectory,
appRoot,
rpcRegistry,
@@ -353,6 +354,7 @@ function createPluginHostService(options) {
})
: null;
const manager = new PluginManager({
+ permissionEngine,
database,
packageStore,
runtimeSupervisor,
diff --git a/electron/plugins/leaseHttpExample.test.cjs b/electron/plugins/leaseHttpExample.test.cjs
new file mode 100644
index 000000000..28ab0c201
--- /dev/null
+++ b/electron/plugins/leaseHttpExample.test.cjs
@@ -0,0 +1,47 @@
+"use strict";
+const assert = require("node:assert/strict");
+const test = require("node:test");
+const { MessageChannel } = require("node:worker_threads");
+const { PluginRpcRouter } = require("./rpcRouter.cjs");
+
+test("browser lease example negotiates its feature and forwards only an opaque lease", async () => {
+ const { startPluginRuntime } = await import("./runtime/runtimePeer.mjs");
+ const fixture = await import("../../examples/plugins/lease-http/browser.js");
+ const calls = [];
+ const secret = { kind: "secret", id: "s".repeat(32), key: "synthetic-token" };
+ const lease = { kind: "secret-lease", id: "l".repeat(32), operationId: "network:https://example.invalid", expiresAt: Date.now() + 30_000 };
+ const { port1, port2 } = new MessageChannel();
+ const host = new PluginRpcRouter({
+ pluginId: "com.netcatty.lease-http",
+ send: (message) => port1.postMessage(message),
+ handlers: {
+ "secrets.set": async (params) => { calls.push("secret"); assert.equal(params.key, secret.key); return { secret }; },
+ "credentials.createLease": async (params) => {
+ calls.push("lease"); assert.deepEqual(params.secret, secret); assert.equal(params.operationId, lease.operationId); return lease;
+ },
+ "network.request": async (params) => {
+ calls.push("network");
+ assert.deepEqual(params, { url: "https://example.invalid/synthetic", credentialLease: lease, authorization: { scheme: "Bearer" } });
+ assert.equal(JSON.stringify(params).includes("synthetic-acceptance-token"), false);
+ return { status: 200, url: params.url, headers: {}, body: { encoding: "base64", data: "" } };
+ },
+ },
+ });
+ port1.on("message", (message) => { void host.accept(message); });
+ const peer = await startPluginRuntime({
+ port: port2,
+ config: { pluginId: "com.netcatty.lease-http", pluginVersion: "0.1.0", netcattyVersion: "0.0.0", apiVersion: "0.1.0-internal.1", enabledFeatures: ["network.credential-lease"] },
+ loadPlugin: async () => fixture,
+ });
+ try {
+ const initialized = await host.request("plugin.initialize", { netcattyVersion: "0.0.0", apiVersion: "0.1.0-internal.1", supportedFeatures: ["network.credential-lease"] });
+ assert.deepEqual(initialized.enabledFeatures, ["network.credential-lease"]);
+ await host.request("plugin.activate", {});
+ assert.deepEqual(await host.request("plugin.command.execute", { command: "com.netcatty.lease-http.request", invocation: { source: "palette" } }), { status: 200 });
+ assert.deepEqual(calls, ["secret", "lease", "network"]);
+ } finally {
+ await peer.dispose();
+ host.close();
+ port1.close();
+ }
+});
diff --git a/electron/plugins/networkBroker.cjs b/electron/plugins/networkBroker.cjs
index 37e4f71fa..0491e5c11 100644
--- a/electron/plugins/networkBroker.cjs
+++ b/electron/plugins/networkBroker.cjs
@@ -1,5 +1,9 @@
"use strict";
+const { createDefinitionValidator } = require("./contractValidator.cjs");
+const validateLease = createDefinitionValidator("SecretLeaseRef");
+const validateAuthorization = createDefinitionValidator("PluginNetworkAuthorization");
+
const { PluginRpcError, RPC_ERRORS } = require("./rpcRouter.cjs");
const { PLUGIN_RPC_MAX_RAW_BYTES } = require("./constants.cjs");
const { canonicalizeNetworkOrigin } = require("./permissionResources.cjs");
@@ -180,15 +184,7 @@ class PluginNetworkBroker {
// network.request lease injection would become dead code.
if (params?.credentialLease !== undefined) {
const lease = params.credentialLease;
- if (
- !lease
- || typeof lease !== "object"
- || Array.isArray(lease)
- || lease.kind !== "secret-lease"
- || typeof lease.id !== "string"
- || typeof lease.operationId !== "string"
- || !Number.isFinite(lease.expiresAt)
- ) {
+ if (!validateLease(lease)) {
throw invalidArgument("Plugin network credential lease is invalid");
}
validated.credentialLease = Object.freeze({
@@ -200,7 +196,7 @@ class PluginNetworkBroker {
}
if (params?.authorization !== undefined) {
const authorization = params.authorization;
- if (!authorization || typeof authorization !== "object" || Array.isArray(authorization)) {
+ if (!validateAuthorization(authorization)) {
throw invalidArgument("Plugin network authorization is invalid");
}
const scheme = authorization.scheme === "Basic" ? "Basic" : "Bearer";
diff --git a/electron/plugins/networkBroker.test.cjs b/electron/plugins/networkBroker.test.cjs
index 6e044fb84..ffaa46b1c 100644
--- a/electron/plugins/networkBroker.test.cjs
+++ b/electron/plugins/networkBroker.test.cjs
@@ -172,3 +172,14 @@ test("network broker reports its own timeout as a stable deadline error", async
(error) => error.code === RPC_ERRORS.deadlineExceeded,
);
});
+
+test("credential field validation follows the canonical contract and keeps Bearer default", () => {
+ const broker = new PluginNetworkBroker({ permissionEngine: {} });
+ const lease = { kind: "secret-lease", id: "l".repeat(32), operationId: "network:https://example.invalid", expiresAt: 1000 };
+ const request = { url: "https://example.invalid", credentialLease: lease, authorization: {} };
+ assert.deepEqual(broker.validate(request).authorization, { scheme: "Bearer" });
+ for (const authorization of [{ scheme: "Digest" }, { scheme: "Basic", username: "name\n" }, { password: "synthetic" }]) {
+ assert.throws(() => broker.validate({ ...request, authorization }), /authorization is invalid/);
+ }
+ assert.throws(() => broker.validate({ ...request, credentialLease: { ...lease, id: "short" } }), /lease is invalid/);
+});
diff --git a/electron/plugins/pluginBridge.cjs b/electron/plugins/pluginBridge.cjs
index 09d5437d0..e0990cf84 100644
--- a/electron/plugins/pluginBridge.cjs
+++ b/electron/plugins/pluginBridge.cjs
@@ -3,6 +3,9 @@
const fs = require("node:fs/promises");
const { randomUUID } = require("node:crypto");
+const { createDefinitionValidator } = require("./contractValidator.cjs");
+const validateManagedPluginId = createDefinitionValidator("PluginId");
+
const { raceWithAbort } = require("./rpcRouter.cjs");
const {
INLINE_SYNC_OBJECT_SAFE_BYTES,
@@ -14,6 +17,8 @@ const { assertSecretKey } = require("./secretStore.cjs");
const CHANNELS = Object.freeze({
status: "netcatty:plugins:status",
list: "netcatty:plugins:list",
+ permissions: "netcatty:plugins:permissions",
+ revokePermissions: "netcatty:plugins:revoke-permissions",
catalog: "netcatty:plugins:catalog",
catalogReadme: "netcatty:plugins:catalog-readme",
catalogInstall: "netcatty:plugins:catalog-install",
@@ -657,6 +662,36 @@ function registerPluginBridge(ipcMain, options) {
return options.catalogService.install(payload?.id, payload?.selectionToken);
});
handle(CHANNELS.list, async (activeManager) => activeManager.list());
+ const assertManagedPluginId = (payload) => {
+ const id = payload?.pluginId;
+ if (!validateManagedPluginId(id)) {
+ throw new TypeError("Plugin ID is invalid");
+ }
+ return id;
+ };
+ handle(CHANNELS.permissions, async (_manager, payload) => {
+ const pluginId = assertManagedPluginId(payload);
+ if (!options.permissionEngine || !options.database) throw new Error("Plugin permissions are unavailable");
+ const groups = options.permissionEngine.listGrants(pluginId);
+ // Host-only summaries: never return arbitrary audit details, reasons,
+ // operation IDs, credentials, terminal content or future database columns.
+ const grants = ["always", "application", "session"].flatMap((scope) => (
+ (groups[scope] ?? []).map((grant) => ({
+ permission: grant.permission, resource: grant.resource,
+ resourceKind: grant.resourceKind, scope,
+ sessionId: grant.sessionId ?? null, grantedAt: grant.grantedAt,
+ }))
+ ));
+ const audit = options.database.listSecurityAudit(pluginId, 100).map((entry) => ({
+ event: entry.event, createdAt: entry.createdAt,
+ ...(typeof entry.details?.permission === "string" ? { permission: entry.details.permission } : {}),
+ ...(typeof entry.details?.scope === "string" ? { scope: entry.details.scope } : {}),
+ }));
+ return { grants, audit };
+ });
+ handle(CHANNELS.revokePermissions, async (activeManager, payload) => (
+ activeManager.revokePermissions(assertManagedPluginId(payload))
+ ));
handle(CHANNELS.install, async (activeManager, payload) => activeManager.install(
payload?.archivePath,
{ enable: typeof payload?.enable === "boolean" ? payload.enable : undefined },
diff --git a/electron/plugins/pluginBridge.test.cjs b/electron/plugins/pluginBridge.test.cjs
index 0901abd9d..a02080d09 100644
--- a/electron/plugins/pluginBridge.test.cjs
+++ b/electron/plugins/pluginBridge.test.cjs
@@ -1635,3 +1635,35 @@ test('brand metadata bridge accepts only trusted UI and forwards only the plugin
await ipcMain.handlers.get(CHANNELS.brandIcon)({ trusted: true }, { pluginId: 'com.test.brand', path: '/secret', url: 'https://attacker.invalid/' });
assert.deepEqual(seen, [['com.test.brand']]);
});
+
+test("permission management is trusted-host-only and projects bounded audit summaries", async () => {
+ const ipcMain = createIpcMain();
+ let reads = 0;
+ const revoked = [];
+ registerPluginBridge(ipcMain, {
+ manager: { async initialize() {}, async revokePermissions(id) { revoked.push(id); return { enabled: false }; } },
+ isTrustedSender: (event) => event?.trusted === true,
+ permissionEngine: { listGrants(id) {
+ reads++;
+ assert.equal(id, "com.example.synthetic");
+ return { always: [{ permission: "network", resource: "https://example.invalid", resourceKind: "exact", grantedAt: 12, declarationHash: "private" }], application: [], session: [] };
+ } },
+ database: { listSecurityAudit(id, limit) {
+ assert.equal(id, "com.example.synthetic");
+ assert.equal(limit, 100);
+ return [{ event: "permission.used", createdAt: 13, details: { permission: "network", scope: "always", operationId: "hidden", secret: "synthetic-private" } }];
+ } },
+ });
+ const payload = { pluginId: "com.example.synthetic" };
+ for (const channel of [CHANNELS.permissions, CHANNELS.revokePermissions]) {
+ await assert.rejects(ipcMain.handlers.get(channel)({}, payload), /Untrusted/);
+ await assert.rejects(ipcMain.handlers.get(channel)({ trusted: true }, { pluginId: "../invalid" }), /Plugin ID/);
+ }
+ assert.equal(reads, 0);
+ assert.deepEqual(await ipcMain.handlers.get(CHANNELS.permissions)({ trusted: true }, payload), {
+ grants: [{ permission: "network", resource: "https://example.invalid", resourceKind: "exact", scope: "always", sessionId: null, grantedAt: 12 }],
+ audit: [{ event: "permission.used", createdAt: 13, permission: "network", scope: "always" }],
+ });
+ assert.deepEqual(await ipcMain.handlers.get(CHANNELS.revokePermissions)({ trusted: true }, payload), { enabled: false });
+ assert.deepEqual(revoked, [payload.pluginId]);
+});
diff --git a/electron/plugins/pluginManager.cjs b/electron/plugins/pluginManager.cjs
index 5c2173369..62a7935b3 100644
--- a/electron/plugins/pluginManager.cjs
+++ b/electron/plugins/pluginManager.cjs
@@ -11,6 +11,7 @@ class PluginManager {
onPluginEnabled: (pluginId) => this.runtimeSupervisor.start(pluginId),
};
this.beforeClose = options.beforeClose ?? null;
+ this.permissionEngine = options.permissionEngine ?? null;
this.initialized = false;
this.initializePromise = null;
this.mutationTail = Promise.resolve();
@@ -128,6 +129,21 @@ class PluginManager {
});
}
+ revokePermissions(pluginId) {
+ return this.#mutate(async () => {
+ await this.#ready();
+ if (!this.permissionEngine) throw new Error("Plugin permissions are unavailable");
+ if (!this.database.getActivePlugin(pluginId)) throw new Error("Plugin is not installed");
+ // Disable before revoking. Lazy activation cannot re-create authority while
+ // runtime shutdown cancels pending RPC, streams, leases and provider work.
+ this.database.setEnabled(pluginId, false);
+ this.permissionEngine.revokeAll(pluginId);
+ this.contributionService.onPluginDisabled(pluginId);
+ await this.runtimeSupervisor.stop(pluginId);
+ return this.database.getActivePlugin(pluginId);
+ });
+ }
+
restart(pluginId) {
return this.#mutate(async () => {
await this.#ready();
diff --git a/electron/plugins/pluginManager.test.cjs b/electron/plugins/pluginManager.test.cjs
index 7c7e19ffa..93319a266 100644
--- a/electron/plugins/pluginManager.test.cjs
+++ b/electron/plugins/pluginManager.test.cjs
@@ -511,3 +511,48 @@ test("explicit enable checks compatibility before clearing quarantine or exposin
await assert.rejects(manager.setEnabled(plugin.id, true), /incompatible/);
assert.deepEqual(calls, []);
});
+
+test("permission revocation disables before clearing grants and waits for runtime cleanup", async () => {
+ const calls = [];
+ let releaseStop;
+ const stopped = new Promise((resolve) => { releaseStop = resolve; });
+ let enabled = true;
+ const manager = new PluginManager({
+ database: {
+ getActivePlugin: (id) => ({ id, enabled }),
+ setEnabled(_id, value) { enabled = value; calls.push("disable"); },
+ },
+ packageStore: { async initialize() {} },
+ contributionService: {
+ async initialize() {},
+ onPluginDisabled() { calls.push("contributions"); },
+ },
+ permissionEngine: { revokeAll() { assert.equal(enabled, false); calls.push("revoke"); } },
+ runtimeSupervisor: { async stop() { calls.push("stop"); await stopped; calls.push("clean"); } },
+ });
+ let complete = false;
+ const revoke = manager.revokePermissions("com.example.revoke").then((value) => { complete = true; return value; });
+ const enable = manager.setEnabled("com.example.revoke", false);
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.deepEqual(calls, ["disable", "revoke", "contributions", "stop"]);
+ assert.equal(complete, false);
+ releaseStop();
+ assert.equal((await revoke).enabled, false);
+ await enable;
+ assert.deepEqual(calls.slice(4), ["clean", "disable", "contributions", "stop", "clean"]);
+});
+
+test("failed runtime containment leaves the revoked plugin disabled and reports failure", async () => {
+ let enabled = true;
+ let revoked = false;
+ const manager = new PluginManager({
+ database: { getActivePlugin: () => ({ enabled }), setEnabled(_id, value) { enabled = value; } },
+ packageStore: { async initialize() {} },
+ contributionService: { async initialize() {}, onPluginDisabled() {} },
+ permissionEngine: { revokeAll() { revoked = true; } },
+ runtimeSupervisor: { async stop() { throw new Error("containment failed"); } },
+ });
+ await assert.rejects(manager.revokePermissions("com.example.revoke"), /containment failed/);
+ assert.equal(enabled, false);
+ assert.equal(revoked, true);
+});
diff --git a/electron/plugins/secureCapabilities.test.cjs b/electron/plugins/secureCapabilities.test.cjs
index 7c84cf53f..5a02d44df 100644
--- a/electron/plugins/secureCapabilities.test.cjs
+++ b/electron/plugins/secureCapabilities.test.cjs
@@ -324,7 +324,7 @@ test("networkBroker.validate preserves credentialLease for registry dispatch", (
url: "https://example.com/vault",
credentialLease: {
kind: "secret-lease",
- id: "lease-1",
+ id: "l".repeat(32),
operationId: "network:https://example.com",
expiresAt: Date.now() + 60_000,
},
diff --git a/electron/preload/api.cjs b/electron/preload/api.cjs
index 4a5a179a1..034634b5f 100644
--- a/electron/preload/api.cjs
+++ b/electron/preload/api.cjs
@@ -103,6 +103,8 @@ function createPreloadApi(ctx) {
getPluginCatalogReadme: (id, selectionToken) => ipcRenderer.invoke("netcatty:plugins:catalog-readme", { id, selectionToken }),
installCatalogPlugin: (id, selectionToken) => ipcRenderer.invoke("netcatty:plugins:catalog-install", { id, selectionToken }),
listPlugins: () => ipcRenderer.invoke("netcatty:plugins:list"),
+ getPluginPermissions: (pluginId) => ipcRenderer.invoke("netcatty:plugins:permissions", { pluginId }),
+ revokePluginPermissions: (pluginId) => ipcRenderer.invoke("netcatty:plugins:revoke-permissions", { pluginId }),
installPluginPackage: (archivePath, options) => ipcRenderer.invoke("netcatty:plugins:install", {
archivePath,
enable: options?.enable === true,
diff --git a/examples/plugins/lease-http/README.md b/examples/plugins/lease-http/README.md
new file mode 100644
index 000000000..d47ba5afb
--- /dev/null
+++ b/examples/plugins/lease-http/README.md
@@ -0,0 +1,25 @@
+# Synthetic credential lease fixture
+
+This browser-only package exercises feature negotiation, plugin-owned secret
+references, a one-use host-consumed network lease, and the host grant panel.
+It contains only synthetic data and targets `https://example.invalid`.
+A synthetic host test supplies the HTTP response. The normal app reports a
+network failure at that deliberately non-routable address after permission.
+This fixture does not prove a live third-party integration.
+
+Pack the source after building the plugin packages:
+
+```sh
+node packages/plugin-cli/dist/cli.js pack examples/plugins/lease-http --out /tmp/lease-http.ncpkg
+```
+
+In the normal plugin manager, import the package disabled, inspect its declared
+permissions, and enable it. The command palette contains **Synthetic credential
+lease request**. Reject a permission prompt to verify that the request stops.
+OS secret storage must be available to proceed past `secrets.set`.
+
+The package detail's **Active grants** panel shows retained decisions. One-use
+decisions are not retained. **Disable and revoke all grants** disables the
+plugin and waits for its runtime cleanup. Re-enable it to request access again.
+Recent events show event type and permission without terminal or secret data.
+Do not change the destination or substitute real credentials for this check.
diff --git a/examples/plugins/lease-http/browser.js b/examples/plugins/lease-http/browser.js
new file mode 100644
index 000000000..f6aaf1734
--- /dev/null
+++ b/examples/plugins/lease-http/browser.js
@@ -0,0 +1,24 @@
+import { definePlugin, PLUGIN_NETWORK_CREDENTIAL_LEASE_FEATURE } from '@netcatty/plugin-sdk';
+
+// Isolated acceptance fixture: the target is deliberately non-routable.
+// Tests provide a synthetic HTTP transport. Never substitute a real credential.
+export default definePlugin({
+ activate(context) {
+ context.subscriptions.add(context.commands.registerCommand('com.netcatty.lease-http.request', async () => {
+ if (!context.enabledFeatures.has(PLUGIN_NETWORK_CREDENTIAL_LEASE_FEATURE)) {
+ throw new Error('Host does not advertise network credential leases');
+ }
+ const secret = await context.secrets.set('synthetic-token', 'synthetic-acceptance-token');
+ const credentialLease = await context.credentials.createLease(secret, {
+ operationId: 'network:https://example.invalid',
+ purpose: 'Authenticate an isolated synthetic request',
+ });
+ const response = await context.network.request({
+ url: 'https://example.invalid/synthetic',
+ credentialLease,
+ authorization: { scheme: 'Bearer' },
+ });
+ return { status: response.status };
+ }));
+ },
+});
diff --git a/examples/plugins/lease-http/netcatty.plugin.json b/examples/plugins/lease-http/netcatty.plugin.json
new file mode 100644
index 000000000..005a16f89
--- /dev/null
+++ b/examples/plugins/lease-http/netcatty.plugin.json
@@ -0,0 +1,25 @@
+{
+ "manifestVersion": 1,
+ "id": "com.netcatty.lease-http",
+ "name": "lease-http",
+ "displayName": "Synthetic credential lease",
+ "description": "Isolated credential lease and grant revocation acceptance fixture.",
+ "version": "0.1.0",
+ "publisher": "netcatty",
+ "license": "GPL-3.0-or-later",
+ "engines": { "netcatty": ">=0.0.0", "api": ">=0.1.0-internal <0.2.0" },
+ "features": { "required": ["network.credential-lease"] },
+ "main": { "browser": "browser.js" },
+ "activationEvents": ["onCommand:com.netcatty.lease-http.request"],
+ "permissions": {
+ "required": ["commands", "menus"],
+ "optional": [
+ { "permission": "secrets", "resources": ["secret:synthetic-token"] },
+ { "permission": "network", "resources": ["https://example.invalid"] }
+ ]
+ },
+ "contributes": {
+ "commands": [{ "id": "com.netcatty.lease-http.request", "title": "Synthetic credential lease request" }],
+ "menus": [{ "command": "com.netcatty.lease-http.request", "location": "commandPalette" }]
+ }
+}
diff --git a/global.d.ts b/global.d.ts
index 54c9febcb..dbdee3a38 100644
--- a/global.d.ts
+++ b/global.d.ts
@@ -355,6 +355,14 @@ declare global {
artifact?: { url: string; sha256: string };
}
+ interface NetcattyPluginPermissionSnapshot {
+ grants: Array<{
+ permission: string; resource: string; resourceKind: string;
+ scope: 'always' | 'application' | 'session'; sessionId: string | null; grantedAt: number;
+ }>;
+ audit: Array<{ event: string; createdAt: number; permission?: string; scope?: string }>;
+ }
+
interface NetcattyInstalledPlugin {
id: string;
enabled: boolean;
@@ -436,6 +444,8 @@ declare global {
getPluginCatalogReadme?(id: string, selectionToken?: string): Promise;
installCatalogPlugin?(id: string, selectionToken?: string): Promise;
listPlugins?(): Promise;
+ getPluginPermissions?(pluginId: string): Promise;
+ revokePluginPermissions?(pluginId: string): Promise;
installPluginPackage?(archivePath: string, options?: { enable?: boolean }): Promise;
setPluginEnabled?(pluginId: string, enabled: boolean): Promise;
restartPlugin?(pluginId: string): Promise;
diff --git a/packages/plugin-contract/schema/plugin-contract.schema.json b/packages/plugin-contract/schema/plugin-contract.schema.json
index 9c5e8980e..cf635ff91 100644
--- a/packages/plugin-contract/schema/plugin-contract.schema.json
+++ b/packages/plugin-contract/schema/plugin-contract.schema.json
@@ -178,6 +178,131 @@
},
"additionalProperties": false
},
+ "NetworkCredentialLeaseFeature": {
+ "const": "network.credential-lease"
+ },
+ "PluginNetworkAuthorization": {
+ "type": "object",
+ "properties": {
+ "scheme": {
+ "type": "string",
+ "enum": [
+ "Basic",
+ "Bearer"
+ ]
+ },
+ "username": {
+ "type": "string",
+ "maxLength": 8192,
+ "pattern": "^[^\\u0000-\\u001f\\u007f]*$"
+ }
+ },
+ "additionalProperties": false
+ },
+ "PluginNetworkRequest": {
+ "description": "Origin-authorized HTTP request. The host consumes a one-use credentialLease for network:; plaintext credentials never return to the plugin.",
+ "type": "object",
+ "required": [
+ "url"
+ ],
+ "properties": {
+ "url": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 8192
+ },
+ "method": {
+ "type": "string",
+ "enum": [
+ "GET",
+ "POST",
+ "PUT",
+ "PATCH",
+ "DELETE",
+ "HEAD"
+ ]
+ },
+ "headers": {
+ "type": "object",
+ "maxProperties": 64,
+ "additionalProperties": {
+ "type": "string",
+ "maxLength": 8192
+ }
+ },
+ "body": {
+ "type": "object",
+ "required": [
+ "encoding",
+ "data"
+ ],
+ "properties": {
+ "encoding": {
+ "enum": [
+ "utf8",
+ "base64"
+ ]
+ },
+ "data": {
+ "type": "string"
+ }
+ },
+ "additionalProperties": false
+ },
+ "timeoutMs": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 300000
+ },
+ "credentialLease": {
+ "$ref": "#/$defs/SecretLeaseRef"
+ },
+ "authorization": {
+ "$ref": "#/$defs/PluginNetworkAuthorization"
+ }
+ },
+ "additionalProperties": false
+ },
+ "PluginNetworkResponse": {
+ "type": "object",
+ "required": [
+ "url",
+ "status",
+ "headers",
+ "body"
+ ],
+ "properties": {
+ "url": {
+ "type": "string"
+ },
+ "status": {
+ "type": "integer"
+ },
+ "headers": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ }
+ },
+ "body": {
+ "type": "object",
+ "required": [
+ "encoding",
+ "data"
+ ],
+ "properties": {
+ "encoding": {
+ "const": "base64"
+ },
+ "data": {
+ "type": "string"
+ }
+ },
+ "additionalProperties": false
+ }
+ },
+ "additionalProperties": false
+ },
"SemanticVersion": {
"type": "string",
"pattern": "^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-(?:0|[1-9]\\d*|\\d*[A-Za-z-][0-9A-Za-z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"
diff --git a/packages/plugin-contract/src/generated/plugin-contract.ts b/packages/plugin-contract/src/generated/plugin-contract.ts
index bab11b5f1..f7f03598e 100644
--- a/packages/plugin-contract/src/generated/plugin-contract.ts
+++ b/packages/plugin-contract/src/generated/plugin-contract.ts
@@ -355,6 +355,8 @@ export type MenuContribution = {
export type MenuLocation = "commandPalette" | "application" | "host/context" | "terminal/context" | "terminal/toolbar" | "statusBar";
+export type NetworkCredentialLeaseFeature = "network.credential-lease";
+
export type NonResourceScopedPermission = "storage" | "runtime.advanced" | "settings.read" | "settings.write" | "commands" | "menus" | "views" | "clipboard.read" | "clipboard.write" | "terminal.metadata" | "terminal.output" | "terminal.input" | "terminal.decorate" | "terminal.complete" | "terminal.intercept.input" | "terminal.intercept.output" | "vault.metadata" | "vault.write" | "vault.credentials" | "sftp.read" | "sftp.write" | "secrets" | "provider.terminal" | "provider.connection" | "provider.authentication" | "provider.sync" | "provider.importer";
export type NullableRpcId = (RpcId) | (null);
@@ -481,6 +483,34 @@ export type PluginManifestHeader = ({
engines: PluginEngineHeader;
} & Record);
+export type PluginNetworkAuthorization = {
+ scheme?: "Basic" | "Bearer";
+ username?: string;
+};
+
+export type PluginNetworkRequest = {
+ url: string;
+ method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD";
+ headers?: { [key: string]: string };
+ body?: {
+ encoding: "utf8" | "base64";
+ data: string;
+ };
+ timeoutMs?: number;
+ credentialLease?: SecretLeaseRef;
+ authorization?: PluginNetworkAuthorization;
+};
+
+export type PluginNetworkResponse = {
+ url: string;
+ status: number;
+ headers: { [key: string]: string };
+ body: {
+ encoding: "base64";
+ data: string;
+ };
+};
+
export type PluginPermission = "storage" | "runtime.advanced" | "settings.read" | "settings.write" | "commands" | "menus" | "views" | "clipboard.read" | "clipboard.write" | "terminal.metadata" | "terminal.output" | "terminal.input" | "terminal.decorate" | "terminal.complete" | "terminal.intercept.input" | "terminal.intercept.output" | "vault.metadata" | "vault.write" | "vault.credentials" | "sftp.read" | "sftp.write" | "network" | "filesystem.read" | "filesystem.write" | "secrets" | "companion.execute" | "provider.terminal" | "provider.connection" | "provider.authentication" | "provider.sync" | "provider.importer";
export type PluginWireErrorCode = -32001 | -32002 | -32003 | -32004 | -32005 | -32006 | -32007 | -32008 | -32009 | -32010 | -32011 | -32012 | -32013 | -32014 | -32015 | -32016;
diff --git a/packages/plugin-contract/src/index.ts b/packages/plugin-contract/src/index.ts
index ee2a692e9..f268deba3 100644
--- a/packages/plugin-contract/src/index.ts
+++ b/packages/plugin-contract/src/index.ts
@@ -49,3 +49,5 @@ export {
} from "./streamTransport.js";
export { inspectPluginBrandIcon, PLUGIN_BRAND_ICON_FEATURE, PLUGIN_BRAND_ICON_MAX_BYTES, PLUGIN_BRAND_ICON_MAX_EDGE } from './brandIcon.js';
+
+export const PLUGIN_NETWORK_CREDENTIAL_LEASE_FEATURE = "network.credential-lease" as const satisfies import("./generated/plugin-contract.js").NetworkCredentialLeaseFeature;
diff --git a/packages/plugin-sdk/src/index.test.ts b/packages/plugin-sdk/src/index.test.ts
index 0bec25ebc..68a8fa314 100644
--- a/packages/plugin-sdk/src/index.test.ts
+++ b/packages/plugin-sdk/src/index.test.ts
@@ -395,3 +395,21 @@ test("CancellationTokenSource finishes disposal when a cancellation listener fai
assert.throws(() => source.dispose(true), AggregateError);
assert.doesNotThrow(() => source.dispose(true));
});
+
+test("network requests expose canonical host-consumed credential leases without plaintext fields", () => {
+ assertSdkTypeChecks(`
+ import type { PluginNetworkRequest, PluginNetworkClient, SecretLeaseRef } from './index.ts';
+ declare const network: PluginNetworkClient;
+ declare const lease: SecretLeaseRef;
+ const request: PluginNetworkRequest = {
+ url: 'https://example.invalid', credentialLease: lease,
+ authorization: { scheme: 'Basic', username: 'synthetic' },
+ };
+ void network.request(request);
+ void network.request({ url: 'https://example.invalid' });
+ // @ts-expect-error Plaintext credential handoff is not supported.
+ void network.request({ url: 'https://example.invalid', authorization: { scheme: 'Bearer', password: 'secret' } });
+ // @ts-expect-error Unsupported authentication schemes fail at compile time.
+ void network.request({ url: 'https://example.invalid', authorization: { scheme: 'Digest' } });
+ `);
+});
diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.ts
index 85f77d69a..d5ba07dac 100644
--- a/packages/plugin-sdk/src/index.ts
+++ b/packages/plugin-sdk/src/index.ts
@@ -13,6 +13,8 @@ import type {
ConnectionStatusResult,
ConnectionValidateResult,
CredentialRef,
+ PluginNetworkRequest,
+ PluginNetworkResponse,
FeatureId,
ImporterDetectPayload,
ImporterDetectResult,
@@ -636,20 +638,7 @@ export interface PluginCredentialBroker {
createLease(credential: SecretRef | CredentialRef, options: PluginCredentialLeaseOptions): Promise;
}
-export interface PluginNetworkRequest {
- readonly url: string;
- readonly method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD";
- readonly headers?: Readonly>;
- readonly body?: Readonly<{ encoding: "utf8" | "base64"; data: string }>;
- readonly timeoutMs?: number;
-}
-
-export interface PluginNetworkResponse {
- readonly url: string;
- readonly status: number;
- readonly headers: Readonly>;
- readonly body: Readonly<{ encoding: "base64"; data: string }>;
-}
+export type { PluginNetworkAuthorization, PluginNetworkRequest, PluginNetworkResponse } from "@netcatty/plugin-contract";
export interface PluginNetworkClient {
request(request: PluginNetworkRequest): Promise;
@@ -922,3 +911,5 @@ export function definePlugin(plugin: T): T {
export function throwIfCancellationRequested(token: CancellationToken): void {
if (token.isCancellationRequested) throw new CancellationError();
}
+
+export { PLUGIN_NETWORK_CREDENTIAL_LEASE_FEATURE } from "@netcatty/plugin-contract";