Skip to main content

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.

MemberCapabilityWhat it does
pluginId, manifestnoneYour id and manifest.
lognoneLines in Termix's log, tagged with your plugin.
dbdb:ownYour own tables. See database.
kvkv:ownSmall key value state.
files.dataDir()files:ownA folder of your own under the data folder.
settingsnoneYour settings. See settings.
secretssecrets:ownEncrypted values per user, or sealed values for your own tables.
http, wsnetwork:serveRoutes and sockets. See HTTP and WebSockets.
rbacnoneCheck the actor's permissions. See permissions.
hostshosts:read, hosts:writeList, read, create, update and share hosts as the actor.
sshssh:connect, credentials:useConnect to hosts through Termix's own SSH pipeline.
credentialsvariesThe actor's saved SSH keys, and protocol logins.
servicesper serviceCall other plugins and offer your own. See services.
eventsevents:core for core topicsEmit and listen for events.
notifynotify:sendSend alerts to the Alerts inbox.
fetchnetwork:outboundOutbound HTTP, with SSRF protection.
processprocess:spawnRun programs on the server.
schedulenoneTimers that stop on disable and never overlap.
audit.recordnoneWrite your own audit line.
syncnoneSync your tables to a linked desktop.
authauth:provideLogin methods, second factors, SSH auth types. See auth.
systemsystem:tlsThe server's HTTPS certificate.
plugins.list()plugins:readWhich plugins are installed.
asUser(userId, fn)always auditedRun background work as a user.
currentActor()noneThe user the current call runs for.
disposables.add(fn)noneExtra 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 sandbox block. Termix refuses one that isn't listed.
  • Await services.get, registry.consume and 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_process and native addons need the capability that allows them. termix-plugin validate warns 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.

  1. Raise engine.api to ^2.0.0, engine.termix to >=26.11.2-0 and the SDK in package.json to ^2.0.0 or newer.
  2. List your schedules (with an id on each every), event topics and registry keys in sandbox.
  3. Await the reads listed in The plugin process, and every call on another plugin's service or registry value.
  4. Replace db.transaction() with ctx.db.batch().
  5. Move direct node:fs, net, http and child_process use to ctx, or declare the capability that allows it. termix-plugin validate warns about each import that would be refused.
  6. Run your tests with createMockCtx({ sandbox: true }) and check the frontend with checkFrameApp, see Frames.
  7. 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.