diff --git a/CLAUDE.md b/CLAUDE.md index 24ddb41f..35c1ef23 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -226,10 +226,10 @@ Loaded at runtime from a plugins directory via `packages/yourssh_script_engine`. - `PluginUiRegistry` — plugins can register Flutter widgets by calling the `ui.register(id, widgetSpec)` JS API; the app renders these in the plugin manager **Bridges (Dart APIs exposed to JS):** -- `SshBridge` — `ssh.exec(sessionId, cmd)`, `ssh.write(sessionId, data)` -- `SftpBridge` — `sftp.list(sessionId, path)`, `sftp.readFile`, `sftp.writeFile` -- `StorageBridge` — `storage.get/set/delete(key)` (namespaced per plugin) -- `UiBridge` — `ui.showNotification(msg)`, `ui.register(id, spec)`; panel `postMessage` types handled natively in Dart (`ssh-exec`, `ssh-sessions`, `sftp-list`, `sftp-read`) enforce the same permissions as the bridges (`ssh.exec`, `session.observe`|`ssh.exec`, `sftp.read`) — a panel is plugin-controlled HTML +- Plugin globals come from a JS prelude (`_kPrelude` in `script_engine_service.dart`) that wraps the raw `_x` host functions (JSON in/out); a wrapper throws `Permission denied` when the bridge did not register the function, so `PermissionGuard` stays the only gate. Raw `_x.*` functions keep working. Documented in `docs/plugin-authoring-guide.md` section 5. +- `SshBridge` — `ssh.sessions()` (`session.observe`|`ssh.exec`); `TerminalInjectBridge` — `ssh.inject(sessionId, text)` (`terminal.inject`). No JS `ssh.exec`/`sftp` (the raw `_ssh.exec` and `_sftp.*` are stubs; use the panel messages below) +- `StorageBridge` — `storage.get/set/delete(key)` (sync, string values, namespaced per plugin, no permission) +- `UiBridge` — `ui.notify(msg, {type})` (host `onNotify`), `ui.statusbar.add/update/remove`, `ui.panel.register({title, icon, webviewEntry, onMessage})`, `ui.clipboard.copy`, `ui.addCommand` (handler not invoked yet); panel `postMessage` types handled natively in Dart (`ssh-exec`, `ssh-sessions`, `sftp-list`, `sftp-read`) enforce the same permissions as the bridges (`ssh.exec`, `session.observe`|`ssh.exec`, `sftp.read`) — a panel is plugin-controlled HTML **UI screens:** - `plugin_consent_dialog.dart` — shown on first load; user must accept declared permissions diff --git a/app/lib/main.dart b/app/lib/main.dart index 89c334f4..29929f32 100644 --- a/app/lib/main.dart +++ b/app/lib/main.dart @@ -387,6 +387,9 @@ class _YourSSHAppState extends State with WindowListener { onLog: (pluginId, level, message) { _pluginEngineProvider.addLog(pluginId, '[$level] $message'); }, + onNotify: (pluginId, message, type) { + _pluginEngineProvider.addLog(pluginId, '[notify:$type] $message'); + }, ); // PluginEngineProvider must be created before PluginLoader because the // loader's onConsentRequired callback closes over _pluginEngineProvider. diff --git a/docs/plugin-authoring-guide.md b/docs/plugin-authoring-guide.md index 01dd470c..8a9911f3 100644 --- a/docs/plugin-authoring-guide.md +++ b/docs/plugin-authoring-guide.md @@ -35,8 +35,7 @@ App (Dart) Plugin (JavaScript) │ │──session opens──► plugin.on("session.connect", handler) │ │ - │──ssh.exec()────► ssh.exec(sessionId, "whoami") - │◄──result──────── Promise<{stdout, stderr, exitCode}> + │◄──ssh.inject()── ssh.inject(sessionId, "whoami\n") ``` --- @@ -275,25 +274,7 @@ ssh.inject(sessionId, "ls -la\n"); // \n submits the command ### `sftp` — File operations -> **Permission:** `sftp.read` (for list/read) or `sftp.write` (for write/delete/mkdir) - -```js -// List remote directory -const entries = await sftp.list(sessionId, "/var/log"); -// entries: [{ name, isDir, size, modified }] - -// Read remote file content -const content = await sftp.read(sessionId, "/etc/hostname"); - -// Write to remote file -await sftp.write(sessionId, "/tmp/test.txt", "hello world"); - -// Delete remote file -await sftp.delete(sessionId, "/tmp/test.txt"); - -// Create remote directory -await sftp.mkdir(sessionId, "/tmp/newdir"); -``` +> **Not available from plugin JavaScript.** The `sftp` global does not exist. Plugins with the `sftp.read` permission can list and read remote files from **panel HTML** through the [native panel messages](#6-api-native-panel-messages) `sftp-list` and `sftp-read`. Writing, deleting and creating remote files is not supported. --- @@ -302,15 +283,15 @@ await sftp.mkdir(sessionId, "/tmp/newdir"); > **Permission:** None — always available. Auto-namespaced by plugin id. ```js -// Save -await storage.set("mykey", "myvalue"); +// Save (values are stored as strings) +storage.set("mykey", "myvalue"); -// Load -const val = await storage.get("mykey"); +// Load: returns { value } or null when the key is missing +const val = storage.get("mykey"); if (val !== null) console.log(val.value); // Delete -await storage.delete("mykey"); +storage.delete("mykey"); ``` Keys are automatically namespaced as `plugin::::storage::` — no collision risk with other plugins. @@ -319,13 +300,14 @@ Keys are automatically namespaced as `plugin::::storage::` — no colli ### `ui` — User interface -#### `ui.notify(message, options)` — Desktop notification +#### `ui.notify(message, options)` — Notification > **Permission:** `ui.notify` ```js ui.notify("Upload complete!", { type: "info" }); // type: "info" | "warning" | "error" +// The app currently writes notifications to the plugin's Console. ``` #### `ui.statusbar.*` — Status bar items @@ -506,12 +488,12 @@ The app shows a consent dialog listing all requested permissions. The user appro | `terminal.intercept` | Cancel or modify user keystrokes before they reach SSH | | `session.observe` | Receive `session.connect` / `session.disconnect` events | | `session.control` | `session.connect.before` — can cancel a connection | -| `ssh.exec` | Call `ssh.exec()` to run commands on remote | +| `ssh.exec` | Run commands through the `ssh-exec` panel message; also allows `ssh.sessions()` | | `terminal.inject` | Send text directly into an active shell via `ssh.inject()` | -| `sftp.read` | `sftp.list()`, `sftp.read()` | -| `sftp.write` | `sftp.write()`, `sftp.delete()`, `sftp.mkdir()` | +| `sftp.read` | `sftp-list` / `sftp-read` panel messages | +| `sftp.write` | Reserved (no JS or panel API uses it yet) | | `command.intercept` | `command.before` / `command.after` hooks for SSH exec commands | -| `ui.notify` | Show desktop notifications | +| `ui.notify` | `ui.notify()` (shown in the plugin Console) | | `ui.statusbar` | Add items to the status bar | | `ui.clipboard` | Write to the system clipboard | | `ui.panel` | Register a sidebar panel with WebView UI | @@ -732,7 +714,7 @@ To re-enable: go to Plugin Manager and save the file (hot-reload resets the erro | Error | Cause | Fix | |-------|-------|-----| -| `Plugin "x" does not have permission: ssh.exec` | Missing permission in manifest | Add it to the `permissions` array | +| `Error: Permission denied: ui.panel not granted` | Missing permission in manifest | Add it to the `permissions` array | | `ManifestException: plugin.json missing required field: name` | Missing required field | Add the field to plugin.json | | `QuickJsException: SyntaxError` | JS syntax error | Fix index.js | | Plugin does not load | plugin.json cannot be parsed | Validate JSON at jsonlint.com | @@ -773,10 +755,11 @@ EOF | Limitation | Workaround | |-----------|------------| -| `ssh.exec()` does not work inside JS hook handlers (`session.connect`, `terminal.output`, etc.) — the JS runtime is synchronous | Use the **native panel message** `ssh-exec` from panel HTML instead | +| JS hook handlers (`session.connect`, `terminal.output`, etc.) are synchronous, so they cannot run SSH commands or await results | Use the **native panel message** `ssh-exec` from panel HTML instead | | `setInterval` / `setTimeout` are not available in the JS plugin context | Use `session.connect` hook to trigger logic; timer-based polling must run from panel HTML (the browser has native timers) | | `ui.addCommand` click handler is not invoked — commands appear in the palette but clicking them is a no-op | Known limitation — will be fixed in a future release | -| `sftp.write`, `sftp.delete`, `sftp.mkdir` in JS are not yet implemented | Use `ssh.inject(sessionId, "rm file\n")` to perform operations via the SSH shell | +| There is no `ssh.exec` or `sftp` global in plugin JS | Use the native panel messages `ssh-exec`, `sftp-list`, `sftp-read` from panel HTML, or `ssh.inject(sessionId, "rm file\n")` to run a command in the user's shell | +| `ui.notify` messages go to the plugin Console, not an on-screen toast | Use `ui.statusbar` for visible status | | Plugin panel WebView loads from `file://` — some browser security policies may block `fetch()` | Use native panel messages (`ssh-exec`, `sftp-read`) instead of `fetch()` in panel HTML | | Plugins cannot share state with each other | Use `storage.set/get` with a shared key prefix (there is no read-isolation between plugins) | diff --git a/packages/yourssh_script_engine/lib/src/script_engine_service.dart b/packages/yourssh_script_engine/lib/src/script_engine_service.dart index 90683ac1..9361247a 100644 --- a/packages/yourssh_script_engine/lib/src/script_engine_service.dart +++ b/packages/yourssh_script_engine/lib/src/script_engine_service.dart @@ -72,6 +72,79 @@ var console = { }; '''; +// JS prelude evaluated after the host bridges are registered and before the +// plugin entry. Defines the documented friendly globals (`ui`, `ssh`, +// `storage`) as thin wrappers over the raw `_x` host functions. A wrapper only +// forwards to a host function the PermissionGuard-gated bridge registered; when +// it is missing the call throws "Permission denied: ", so no wrapper can +// reach a capability the plugin was not granted. Raw `_x` stays available. +const _kPrelude = r''' +(function(g) { + function host(obj, fn, perm) { + return function(arg) { + if (typeof obj === 'undefined' || typeof obj[fn] !== 'function') { + throw new Error('Permission denied: ' + perm + ' not granted'); + } + var r = obj[fn](JSON.stringify(arg === undefined ? null : arg)); + return typeof r === 'string' ? JSON.parse(r) : null; + }; + } + var _u = typeof _ui === 'undefined' ? undefined : _ui; + var _us = typeof _ui_statusbar === 'undefined' ? undefined : _ui_statusbar; + var _s = typeof _ssh === 'undefined' ? undefined : _ssh; + var _st = typeof _storage === 'undefined' ? undefined : _storage; + var notify = host(_u, 'notify', 'ui.notify'); + var register = host(_u, 'registerPanel', 'ui.panel'); + var copy = host(_u, 'copyToClipboard', 'ui.clipboard'); + var addCommand = host(_u, 'addCommand', 'ui.statusbar or ui.panel'); + var sbAdd = host(_us, 'add', 'ui.statusbar'); + var sbUpdate = host(_us, 'update', 'ui.statusbar'); + var sbRemove = host(_us, 'remove', 'ui.statusbar'); + var sessions = host(_s, 'sessions', 'session.observe'); + var inject = host(_s, 'inject', 'terminal.inject'); + var sGet = host(_st, 'get', 'storage'); + var sSet = host(_st, 'set', 'storage'); + var sDel = host(_st, 'delete', 'storage'); + g.ui = { + notify: function(message, options) { + notify({message: String(message), type: (options && options.type) || 'info'}); + }, + statusbar: { + add: function(id, o) { + o = o || {}; + sbAdd({id: id, label: o.label, tooltip: o.tooltip}); + }, + update: function(id, o) { + o = o || {}; + sbUpdate({id: id, label: o.label, tooltip: o.tooltip}); + }, + remove: function(id) { sbRemove({id: id}); } + }, + panel: { + register: function(c) { + register({title: c.title, icon: c.icon, webviewEntry: c.webviewEntry}); + if (typeof c.onMessage === 'function') plugin._setPanelMessage(c.onMessage); + } + }, + clipboard: { copy: function(text) { copy({text: String(text)}); } }, + addCommand: function(c) { + addCommand({id: c.id, label: c.label, keybinding: c.keybinding}); + } + }; + g.ssh = { + sessions: function() { return sessions(null) || []; }, + inject: function(sessionId, text) { + inject({sessionId: sessionId, text: String(text)}); + } + }; + g.storage = { + get: function(key) { return sGet({key: key}); }, + set: function(key, value) { sSet({key: key, value: String(value)}); }, + delete: function(key) { sDel({key: key}); } + }; +})(this); +'''; + class _LoadedPlugin { final String id; final PluginManifest manifest; @@ -93,6 +166,10 @@ class ScriptEngineService { final SftpBridgeDelegate? sftpDelegate; final void Function(String pluginId, String level, String message)? onLog; + /// Receives `ui.notify(message, {type})` calls from plugins holding the + /// `ui.notify` permission. `type` is `info`, `warning` or `error`. + final void Function(String pluginId, String message, String type)? onNotify; + VoidCallback? onChange; List get loadedManifests => @@ -112,6 +189,7 @@ class ScriptEngineService { required this.sshDelegate, required this.sftpDelegate, this.onLog, + this.onNotify, }); Future loadPlugin( @@ -148,7 +226,9 @@ class ScriptEngineService { } if (sftpDelegate != null) SftpBridge(guard, sftpDelegate!).register(rt); if (uiRegistry != null) { - UiBridge(manifest.id, guard, uiRegistry!, null, (msg) async { + UiBridge(manifest.id, guard, uiRegistry!, + onNotify == null ? null : (m, t) => onNotify!(manifest.id, m, t), + (msg) async { final type = msg['type'] as String? ?? ''; // Native operations bypass the JS bridges, so they must enforce the @@ -232,6 +312,9 @@ class ScriptEngineService { }).register(rt); } + // Documented friendly globals (ui / ssh / storage) over the raw bridges. + rt.eval(_kPrelude, filename: '', timeout: kLoadTimeout); + // Execute plugin entry point final src = await entryFile.readAsString(); rt.eval(src, filename: manifest.entry, timeout: kLoadTimeout); diff --git a/packages/yourssh_script_engine/test/plugin_api_prelude_test.dart b/packages/yourssh_script_engine/test/plugin_api_prelude_test.dart new file mode 100644 index 00000000..7d06debf --- /dev/null +++ b/packages/yourssh_script_engine/test/plugin_api_prelude_test.dart @@ -0,0 +1,141 @@ +import 'dart:convert'; +import 'dart:io'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:yourssh_script_engine/src/bridge/ssh_bridge.dart'; +import 'package:yourssh_script_engine/src/bridge/storage_bridge.dart'; +import 'package:yourssh_script_engine/src/hook_bus.dart'; +import 'package:yourssh_script_engine/src/plugin_ui_registry.dart'; +import 'package:yourssh_script_engine/src/script_engine_service.dart'; + +class _FakeSsh implements SshBridgeDelegate { + final inputs = []; + @override + List> activeSessions() => [ + {'sessionId': 's1', 'host': 'h', 'username': 'u', 'port': 22, 'connected': true} + ]; + @override + Future> execCommand(String s, String c) async => + {'stdout': '', 'stderr': '', 'exitCode': 0}; + @override + void sendInput(String sessionId, String text) => inputs.add('$sessionId:$text'); +} + +void main() { + late Directory tmp; + late PluginUiRegistry registry; + late _FakeSsh ssh; + late List notes; + late List logs; + late ScriptEngineService svc; + + setUp(() async { + TestWidgetsFlutterBinding.ensureInitialized(); + SharedPreferences.setMockInitialValues({}); + await StorageBridge.warmup(); + tmp = Directory.systemTemp.createTempSync('plugin_prelude_'); + registry = PluginUiRegistry(); + ssh = _FakeSsh(); + notes = []; + logs = []; + svc = ScriptEngineService( + hookBus: HookBus(), + uiRegistry: registry, + sshDelegate: ssh, + sftpDelegate: null, + onLog: (id, level, msg) => logs.add('$level:$msg'), + onNotify: (id, msg, type) => notes.add('$type:$msg'), + ); + }); + + tearDown(() { + svc.dispose(); + tmp.deleteSync(recursive: true); + }); + + Future load(String js, Set perms) async { + final dir = Directory('${tmp.path}/p')..createSync(); + File('${dir.path}/plugin.json').writeAsStringSync(json.encode({ + 'id': 'test.prelude', + 'name': 'P', + 'version': '1.0.0', + 'entry': 'index.js', + 'minAppVersion': '1.0.0', + 'permissions': perms.toList(), + })); + File('${dir.path}/index.js').writeAsStringSync(js); + await svc.loadPlugin(dir.path, grantedPermissions: perms); + } + + test('ui.panel.register registers a panel and routes onMessage', () async { + await load(''' +ui.panel.register({title: "T", icon: "note", webviewEntry: "panel/index.html", + onMessage: function(m) { return {type: "echo", got: m.type}; }}); +''', {'ui.panel'}); + expect(registry.panels.single.title, 'T'); + final r = await registry.panels.single.onMessage({'type': 'ping'}); + expect(json.decode(r!)['got'], 'ping'); + }); + + test('storage.set/get/delete round trip', () async { + await load(''' +storage.set("k", "v"); +var a = storage.get("k"); +console.log("a=" + (a && a.value)); +storage.delete("k"); +console.log("b=" + storage.get("k")); +''', {}); + expect(logs, ['log:a=v', 'log:b=null']); + }); + + test('ui.notify reaches the host callback', () async { + await load('ui.notify("hi", {type: "warning"}); ui.notify("yo");', + {'ui.notify'}); + expect(notes, ['warning:hi', 'info:yo']); + }); + + test('ui.statusbar add/update/remove, clipboard and addCommand', () async { + await load(''' +ui.statusbar.add("a", {label: "L", tooltip: "t"}); +ui.statusbar.update("a", {label: "L2"}); +ui.statusbar.add("b", {label: "B"}); +ui.statusbar.remove("b"); +ui.addCommand({id: "c", label: "Cmd"}); +''', {'ui.statusbar'}); + expect(registry.statusBarItems.map((i) => i.label), ['L2']); + expect(registry.commands.single.label, 'Cmd'); + }); + + test('ssh.sessions and ssh.inject use the delegate', () async { + await load(''' +var s = ssh.sessions(); +console.log("n=" + s.length + " " + s[0].sessionId); +ssh.inject("s1", "ls\\n"); +''', {'session.observe', 'terminal.inject'}); + expect(logs, ['log:n=1 s1']); + expect(ssh.inputs, ['s1:ls\n']); + }); + + test('wrappers do not bypass permissions', () async { + await load(''' +try { ui.panel.register({title: "x", webviewEntry: "p"}); console.log("allowed"); } +catch (e) { console.log("denied:" + e.message); } +try { ssh.inject("s1", "x"); console.log("allowed"); } +catch (e) { console.log("denied:" + e.message); } +''', {'ui.notify'}); + expect(logs.length, 2); + expect(logs.every((l) => l.startsWith('log:denied:')), isTrue); + expect(logs[0], contains('ui.panel')); + expect(logs[1], contains('terminal.inject')); + expect(registry.panels, isEmpty); + expect(ssh.inputs, isEmpty); + }); + + test('plugin using only raw _x API still loads', () async { + await load(''' +_ui.registerPanel(JSON.stringify({title: "Raw", icon: "x", webviewEntry: "p"})); +_storage.set(JSON.stringify({key: "k", value: "v"})); +''', {'ui.panel'}); + expect(registry.panels.single.title, 'Raw'); + }); +}