Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions app/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,9 @@ class _YourSSHAppState extends State<YourSSHApp> 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.
Expand Down
51 changes: 17 additions & 34 deletions docs/plugin-authoring-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -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")
```

---
Expand Down Expand Up @@ -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.

---

Expand All @@ -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::<id>::storage::<key>` — no collision risk with other plugins.
Expand All @@ -319,13 +300,14 @@ Keys are automatically namespaced as `plugin::<id>::storage::<key>` — 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
Expand Down Expand Up @@ -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 |
Expand Down Expand Up @@ -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 |
Expand Down Expand Up @@ -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) |

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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: <perm>", 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;
Expand All @@ -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<PluginManifest> get loadedManifests =>
Expand All @@ -112,6 +189,7 @@ class ScriptEngineService {
required this.sshDelegate,
required this.sftpDelegate,
this.onLog,
this.onNotify,
});

Future<void> loadPlugin(
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -232,6 +312,9 @@ class ScriptEngineService {
}).register(rt);
}

// Documented friendly globals (ui / ssh / storage) over the raw bridges.
rt.eval(_kPrelude, filename: '<prelude>', timeout: kLoadTimeout);

// Execute plugin entry point
final src = await entryFile.readAsString();
rt.eval(src, filename: manifest.entry, timeout: kLoadTimeout);
Expand Down
Loading
Loading