Backend
Your backend exports activate(ctx). Termix calls it when the plugin starts and hands it ctx, which is everything your backend can use.
import type { PluginContext } from "@termix-ssh/plugin-sdk/backend";
export async function activate(ctx: PluginContext) {
ctx.log.info("hello is starting");
const router = ctx.http.router();
router.get("/ping", (_req, res) => res.json({ ok: true }));
}
export async function deactivate() {
// Optional. Anything made through ctx is cleaned up for you.
}
src/backend/index.ts is bundled to dist/backend.js as ESM for Node 22 and up.
What ctx has
The types in @termix-ssh/plugin-sdk/backend are the full reference. This is the map.
| Member | Capability | What it does |
|---|---|---|
pluginId, manifest | none | Your id and manifest. |
log | none | Lines in Termix's log, tagged with your plugin. |
db | db:own | Your own tables. See database. |
kv | kv:own | Small key value state. |
files.dataDir() | files:own | A folder of your own under the data folder. |
settings | none | Your settings. See settings. |
secrets | secrets:own | Encrypted values per user, or sealed values for your own tables. |
http, ws | network:serve | Routes and sockets. See HTTP and WebSockets. |
rbac | none | Check the actor's permissions. See permissions. |
hosts | hosts:read, hosts:write | List, read, create, update and share hosts as the actor. |
ssh | ssh:connect, credentials:use | Connect to hosts through Termix's own SSH pipeline. |
credentials | varies | The actor's saved SSH keys, and protocol logins. |
services | per service | Call other plugins and offer your own. See services. |
events | events:core for core topics | Emit and listen for events. |
notify | notify:send | Send alerts to the Alerts inbox. |
fetch | network:outbound | Outbound HTTP, with SSRF protection. |
process | process:spawn | Run programs on the server. |
schedule | none | Timers that stop on disable and never overlap. |
audit.record | none | Write your own audit line. |
sync | none | Sync your tables to a linked desktop. |
auth | auth:provide | Login methods, second factors, SSH auth types. See auth. |
system | system:tls | The server's HTTPS certificate. |
plugins.list() | plugins:read | Which plugins are installed. |
asUser(userId, fn) | always audited | Run background work as a user. |
currentActor() | none | The user the current call runs for. |
disposables.add(fn) | none | Extra cleanup on disable. |
Connecting to hosts
Never open your own SSH connection. Use ctx.ssh, so jump hosts, proxies, port knocking, host key checks, every auth type and sharing all work the way the user set them up.
const { client, dispose } = await ctx.ssh.connect(hostId, {
purpose: "hello",
profile: "background",
});
try {
// use the ssh2 client
} finally {
dispose();
}
withConnection(hostId, { pool, purpose }, fn) borrows a pooled connection, which is better for frequent short commands. @termix-ssh/plugin-sdk/host-commands has helpers to detect the OS and run package manager and sudo commands over a client. Its sudo helper sends the password on stdin. Never put a password or token in a command line, where other users on the host can read it.
Hosts you get from ctx.hosts never carry passwords or keys. Only a plugin with credentials:read sees them, and most don't need to: pass the host or its id back to ctx.ssh and Termix connects with the real secrets.
The plugin process
Your backend runs in its own Node process (plugin API 2). ctx works the same, but every call goes to Termix and back, so:
- List every timer id, event topic and registry key in the manifest's
sandboxblock. Termix refuses one that isn't listed. - Await
services.get,registry.consumeand the other reads the guide lists. Every method on another plugin's service returns a Promise. - Pass plain data to
ctx: objects, arrays, strings, numbers, Buffers, Dates, Maps and Sets. Class instances don't cross. - Use
ctx.db.batch()for writes that must land together.db.transaction()is not available. - Node modules like
node:net,node:child_processand native addons need the capability that allows them.termix-plugin validatewarns about each one. - Your process gets the variables you list in the manifest's
env, nothing else from the server.
"sandbox": {
"schedules": [{ "id": "refresh", "every": 60000 }],
"events": ["host.deleted"],
"registry": ["hello.variables"]
}
A plugin with nothing in that block, no services and no listeners starts on its first request and stops after 10 idle minutes. Test with createMockCtx({ sandbox: true }), which applies the same rules.
A job shorter than the idle time keeps the process running. If your short jobs often have nothing to do (watches nobody set up), call ctx.schedule.keepAwake?.(reason, awake) (plugin API 2.8) with true while there is work and false when there is none. Once you call it, your short jobs run only while the process runs, and Termix starts it at boot again if it had work when Termix last stopped.
Moving from API 1
Plugin API 1 ran inside the server. From Termix 26.11.2 nothing runs that way, so a plugin made for API 1 stays off until it has a version made for API 2. The plugins page names each one, and before an update it also names the plugins the new version won't run.
- Raise
engine.apito^2.0.0,engine.termixto>=26.11.2-0and the SDK inpackage.jsonto^2.0.0or newer. - List your schedules (with an
idon eachevery), event topics and registry keys insandbox. - Await the reads listed in The plugin process, and every call on another plugin's service or registry value.
- Replace
db.transaction()withctx.db.batch(). - Move direct
node:fs,net,httpandchild_processuse toctx, or declare the capability that allows it.termix-plugin validatewarns about each import that would be refused. - Run your tests with
createMockCtx({ sandbox: true })and check the frontend withcheckFrameApp, see Frames. - Drop capabilities you no longer use, bump the version and add a CHANGELOG entry.
Events
ctx.events.on("host.deleted", ({ hostId }) => cleanUp(hostId));
ctx.events.emit("plugin.hello.greeted", { name });
Your own events are plugin.<id>.<name>. Listening to other plugins' events needs nothing. Core events, like user.deleted and host changes, need events:core.
Timers
ctx.schedule.every(60_000, () => refresh(), { id: "refresh", jitterMs: 5_000 });
They stop when the plugin is disabled, and a run that is still going skips the next tick.
Outbound HTTP
const res = await ctx.fetch("https://api.example.com/v1/thing", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(payload),
});
ctx.fetch refuses private and loopback addresses unless you list the exact host in allowPrivateHosts. It doesn't follow redirects.
Fill allowPrivateHosts from an admin setting or a device an admin saved, never from the request itself.
Your own sockets
If you open a socket yourself (net, tls, dgram or http.request) to an address a user typed, check it first with @termix-ssh/plugin-sdk/net-guard (Termix 26.11.2 or newer). resolveTarget looks the name up once, refuses private addresses unless the host is in allowPrivateHosts, and returns the address to connect to:
import { resolveTarget } from "@termix-ssh/plugin-sdk/net-guard";
const { address } = await resolveTarget(host, { allowPrivateHosts });
const socket = net.connect({ host: address, port });
Connect to the returned address, not the name, so a second lookup can't send you somewhere else. For TLS pass the name as servername.
Dependencies
You can use any npm package. It is bundled into dist/backend.js. A few come from Termix instead and are never bundled, so you share one copy:
@termix-ssh/plugin-sdk, express, ssh2, ws, multer, cookie-parser, axios, drizzle-orm, sharp, and every Node builtin.
Workers and WebAssembly
Heavy work like decoding or encoding belongs in a worker thread, so it never blocks the server. Name each worker entry in package.json:
"termix": { "workers": { "engine": "src/backend/engine/worker.ts" } }
termix-plugin build (SDK 1.0.9 and later) bundles it on its own into dist/workers/engine.js. Start it with new Worker(new URL("./workers/engine.js", import.meta.url)). A worker bundles everything it imports, so it must not import @termix-ssh/plugin-sdk.
Importing a .wasm, .ttf or .otf file gives its bytes as a Uint8Array, in builds and in tests. Compile a module once on the main thread with WebAssembly.compile and pass it to each worker. The Remote Desktop plugin does this for its engine.
Packages with native .node bindings can't be bundled. List them in nativeDependencies. A community plugin can't rely on them being on the server yet, so avoid them if you can.