sx-plugin-sdk 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Wittawas Nakkasem
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,140 @@
1
- # Temporary Holding Version
1
+ # sx-plugin-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Write a plugin for [sx](https://github.com/vittee/sx) in Node.js or TypeScript.
4
+ The package has the types of every message of the plugin protocol, and the code that runs a plugin over stdio or a WebSocket.
5
+ You write only the logic.
6
+ The guide for plugin authors is `docs/plugins.md` in the sx repository.
7
+
8
+ ## MessagePack
9
+
10
+ The messages are JSON, and that needs nothing more.
11
+ To send them as MessagePack, set `encoding: "msgpack"` and install one more package.
12
+ The SDK has no MessagePack code of its own.
13
+ Both packages below are optional peer dependencies, so a plugin that uses JSON installs neither.
14
+
15
+ - `@msgpack/msgpack`
16
+ - Pros: it is written in TypeScript, it has builds for ES modules and for CommonJS, and it supports MessagePack extensions and timestamps.
17
+ - Cons: it is bigger, about 900 KB on disk with both builds and the sources.
18
+ - `notepack.io`
19
+ - Pros: it is small, about 90 KB on disk, and it describes itself as fast.
20
+ This README did not measure that.
21
+ - Cons: it has a CommonJS build only. `import` still works, but a bundler or Node loads it as CommonJS.
22
+
23
+ Both have no dependencies, include their types, and work the same with the SDK.
24
+ The messages of sx need only maps, lists, text, numbers and booleans, so the extra features of `@msgpack/msgpack` are not needed.
25
+ Pick one by size and by what your project already uses.
26
+
27
+ ```sh
28
+ pnpm add @msgpack/msgpack
29
+ pnpm add notepack.io
30
+ ```
31
+
32
+ The SDK uses `@msgpack/msgpack` first, and `notepack.io` when it is not installed.
33
+ To choose one yourself, pass the module:
34
+
35
+ ```ts
36
+ import * as msgpack from "@msgpack/msgpack";
37
+
38
+ await runStdio(plugin, { msgpack });
39
+ ```
40
+
41
+ `msgpackCodec` wraps either package, so the plugin code is the same, and it leaves out the fields that are `undefined`, as JSON does.
42
+ If sx does not offer `msgpack`, the messages stay JSON.
43
+
44
+ ## A plugin
45
+
46
+ ```ts
47
+ import { definePlugin, runStdio } from "sx-plugin-sdk";
48
+
49
+ const plugin = definePlugin({
50
+ name: "acme.inventory",
51
+ version: "1.0.0",
52
+ provides: ["hosts", "snippets"],
53
+ async sync({ hosts, fresh }) {
54
+ // sx sends its host list. Answer with the list you want.
55
+ // With `fresh`, the user asked for new data: skip your own cache.
56
+ return {
57
+ hosts: [
58
+ ...hosts,
59
+ {
60
+ alias: "cloud1",
61
+ hostname: "10.1.2.3",
62
+ tags: ["cloud"],
63
+ },
64
+ ],
65
+ snippets: [
66
+ {
67
+ name: "cloud-hello",
68
+ content: "alias hello='echo hello'\n",
69
+ },
70
+ ],
71
+ };
72
+ },
73
+ beforeConnect({ host }) {
74
+ if (host === "frozen") {
75
+ return {
76
+ action: "block",
77
+ reason: "this host is frozen",
78
+ };
79
+ }
80
+ },
81
+ });
82
+
83
+ await runStdio(plugin);
84
+ ```
85
+
86
+ Add it to sx with `sx plugin add -- node /path/to/plugin.ts`.
87
+ Node 22.18 or later runs a TypeScript file as it is.
88
+
89
+ ## What you write
90
+
91
+ `definePlugin` takes these options:
92
+
93
+ | Option | What it does |
94
+ |---|---|
95
+ | `name` | The name, `namespace.name`. |
96
+ | `version` | Shown to the user when they approve the plugin. |
97
+ | `provides` | What `sync` gives: `hosts`, `snippets`, `profiles` or `envs`. The user approves each one. |
98
+ | `sync` | Gets the host list and `fresh`. Returns the parts that the plugin gives. |
99
+ | `beforeConnect` | Runs before ssh starts. Returns `block` to refuse, or `ssh_args` to add options. |
100
+ | `afterDisconnect` | Runs when a connection ends. |
101
+ | `persistent` | Keeps the process running between requests. |
102
+ | `encoding` | `json` (the default) or `msgpack`. |
103
+
104
+ - A part that `sync` leaves out is not given. sx keeps its host list as it was.
105
+ - A handler that throws gives an `error` reply, and the plugin keeps running. Throw a `PluginError` to choose the `code`.
106
+ - The field names are the ones on the wire, such as `ssh_args` and `exit_code`.
107
+ - `console.log` writes to stderr while `runStdio` runs, because stdout belongs to the protocol.
108
+
109
+ ## A WebSocket server
110
+
111
+ ```ts
112
+ import { serveWebSocket } from "sx-plugin-sdk";
113
+
114
+ await serveWebSocket(plugin, { port: 8765, token: process.env["PLUGIN_TOKEN"] });
115
+ ```
116
+
117
+ This needs the package `ws` (`pnpm add ws`).
118
+ The server listens on this machine only, unless you pass `host`.
119
+ Add it with `sx plugin add --url ws://127.0.0.1:8765`.
120
+
121
+ ## Test a plugin
122
+
123
+ `dispatch` answers one request without a process:
124
+
125
+ ```ts
126
+ import { dispatch } from "sx-plugin-sdk";
127
+
128
+ const reply = await dispatch(plugin, { v: 1, id: 2, type: "sync", fresh: false, hosts: [] });
129
+ ```
130
+
131
+ ## Develop the package
132
+
133
+ ```sh
134
+ pnpm install
135
+ pnpm run check
136
+ pnpm test
137
+ pnpm run build
138
+ ```
139
+
140
+ The tests run a plugin as a process, over stdio and over a WebSocket, in JSON and in MessagePack with both packages.
@@ -0,0 +1,31 @@
1
+ import { Buffer } from "node:buffer";
2
+ import type { Request } from "./types.ts";
3
+ /** The longest message, in bytes, that sx reads and that this package accepts. */
4
+ export declare const MAX_MESSAGE: number;
5
+ /** Turns a message into bytes and back. */
6
+ export interface Codec {
7
+ readonly name: "json" | "msgpack";
8
+ encode(message: object): Uint8Array;
9
+ decode(bytes: Uint8Array): unknown;
10
+ }
11
+ export declare const jsonCodec: Codec;
12
+ /**
13
+ * What a MessagePack package must have. `@msgpack/msgpack` and `notepack.io` both do:
14
+ * pass the module (or its default export) to `msgpackCodec`.
15
+ */
16
+ export interface MsgpackLibrary {
17
+ encode(value: unknown): Uint8Array;
18
+ decode(bytes: Buffer): unknown;
19
+ }
20
+ /** Wraps `@msgpack/msgpack` or `notepack.io`, so the plugin code is the same with both. */
21
+ export declare function msgpackCodec(library: MsgpackLibrary | {
22
+ default: MsgpackLibrary;
23
+ }): Codec;
24
+ /** Loads `@msgpack/msgpack`, or `notepack.io` when the first is not installed. */
25
+ export declare function loadMsgpack(library?: MsgpackLibrary | {
26
+ default: MsgpackLibrary;
27
+ }): Promise<Codec>;
28
+ /** A MessagePack message on stdio has its length before it: 4 bytes, big endian. */
29
+ export declare function withLength(bytes: Uint8Array): Buffer;
30
+ /** Checks that a decoded value has the header of a request. */
31
+ export declare function asRequest(value: unknown): Request | null;
package/dist/codec.js ADDED
@@ -0,0 +1,76 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { Buffer } from "node:buffer";
10
+ /** The longest message, in bytes, that sx reads and that this package accepts. */
11
+ export const MAX_MESSAGE = 4 * 1024 * 1024;
12
+ export const jsonCodec = {
13
+ name: "json",
14
+ encode: (message) => Buffer.from(JSON.stringify(message)),
15
+ decode: (bytes) => JSON.parse(Buffer.from(bytes).toString("utf8")),
16
+ };
17
+ // MessagePack has a value for `undefined`, and sx does not read it. JSON drops such a field, so do the same.
18
+ function withoutUndefined(value) {
19
+ // JSON writes null for an undefined item of an array.
20
+ if (Array.isArray(value))
21
+ return value.map((item) => (item === undefined ? null : withoutUndefined(item)));
22
+ if (value !== null && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
23
+ const out = {};
24
+ for (const [key, item] of Object.entries(value)) {
25
+ if (item !== undefined)
26
+ out[key] = withoutUndefined(item);
27
+ }
28
+ return out;
29
+ }
30
+ return value;
31
+ }
32
+ /** Wraps `@msgpack/msgpack` or `notepack.io`, so the plugin code is the same with both. */
33
+ export function msgpackCodec(library) {
34
+ // With `import()`, a CommonJS package such as `notepack.io` can have its functions under `default`.
35
+ const lib = "encode" in library ? library : library.default;
36
+ if (typeof lib?.encode !== "function" || typeof lib?.decode !== "function") {
37
+ throw new Error("the MessagePack package must have encode and decode functions");
38
+ }
39
+ return {
40
+ name: "msgpack",
41
+ encode: (message) => {
42
+ const bytes = lib.encode(withoutUndefined(message));
43
+ return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
44
+ },
45
+ decode: (bytes) => lib.decode(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)),
46
+ };
47
+ }
48
+ /** Loads `@msgpack/msgpack`, or `notepack.io` when the first is not installed. */
49
+ export async function loadMsgpack(library) {
50
+ if (library)
51
+ return msgpackCodec(library);
52
+ for (const name of ["@msgpack/msgpack", "notepack.io"]) {
53
+ try {
54
+ return msgpackCodec(await import(__rewriteRelativeImportExtension(name)));
55
+ }
56
+ catch (e) {
57
+ if (e.code !== "ERR_MODULE_NOT_FOUND")
58
+ throw e;
59
+ }
60
+ }
61
+ throw new Error('encoding "msgpack" needs a MessagePack package: install @msgpack/msgpack (or notepack.io)');
62
+ }
63
+ /** A MessagePack message on stdio has its length before it: 4 bytes, big endian. */
64
+ export function withLength(bytes) {
65
+ const out = Buffer.allocUnsafe(4 + bytes.length);
66
+ out.writeUInt32BE(bytes.length, 0);
67
+ out.set(bytes, 4);
68
+ return out;
69
+ }
70
+ /** Checks that a decoded value has the header of a request. */
71
+ export function asRequest(value) {
72
+ if (value === null || typeof value !== "object")
73
+ return null;
74
+ const { id, type } = value;
75
+ return typeof id === "number" && typeof type === "string" ? value : null;
76
+ }
@@ -0,0 +1,10 @@
1
+ export { PROTOCOL } from "./types.ts";
2
+ export type { AfterDisconnectReply, AfterDisconnectRequest, BeforeConnectReply, BeforeConnectRequest, Env, ErrorCode, ErrorReply, HelloReply, HelloRequest, HookDecision, Host, Message, Profile, Provides, Reply, ReplyFrame, Request, Snippet, SyncReply, SyncRequest, SyncResult, } from "./types.ts";
3
+ export { PluginError, definePlugin, dispatch } from "./plugin.ts";
4
+ export type { Plugin, PluginOptions } from "./plugin.ts";
5
+ export { jsonCodec, loadMsgpack, msgpackCodec } from "./codec.ts";
6
+ export type { Codec, MsgpackLibrary } from "./codec.ts";
7
+ export { runStdio } from "./stdio.ts";
8
+ export type { StdioOptions } from "./stdio.ts";
9
+ export { serveWebSocket } from "./websocket.ts";
10
+ export type { RunningServer, WebSocketOptions } from "./websocket.ts";
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { PROTOCOL } from "./types.js";
2
+ export { PluginError, definePlugin, dispatch } from "./plugin.js";
3
+ export { jsonCodec, loadMsgpack, msgpackCodec } from "./codec.js";
4
+ export { runStdio } from "./stdio.js";
5
+ export { serveWebSocket } from "./websocket.js";
@@ -0,0 +1,46 @@
1
+ import type { AfterDisconnectRequest, BeforeConnectRequest, ErrorCode, HookDecision, Provides, Reply, ReplyFrame, Request, SyncRequest, SyncResult } from "./types.ts";
2
+ /** What a plugin author writes. */
3
+ export interface PluginOptions {
4
+ /** The name, in the form `namespace.name`: `a-z`, `0-9` and `-` on each side of one dot. */
5
+ name: string;
6
+ version: string;
7
+ /**
8
+ * What `sync` gives. The user approves each one, so list only what you use.
9
+ * Leave it out for a plugin that only has hooks.
10
+ */
11
+ provides?: Provides[];
12
+ /** Keep the process running between requests. It has no use for a WebSocket server. */
13
+ persistent?: boolean;
14
+ /**
15
+ * The encoding of the messages after `hello`. `msgpack` needs `@msgpack/msgpack` or `notepack.io`.
16
+ * sx must offer it, or the plugin falls back to JSON.
17
+ */
18
+ encoding?: "json" | "msgpack";
19
+ /** Answers `sync`: gets the host list, returns what the plugin gives. */
20
+ sync?: (request: SyncRequest) => SyncResult | void | Promise<SyncResult | void>;
21
+ /** Runs before ssh starts. Return a `block` to refuse, or `ssh_args` to add options. */
22
+ beforeConnect?: (request: BeforeConnectRequest) => HookDecision | void | Promise<HookDecision | void>;
23
+ /** Runs when a connection ends. The answer is ignored. */
24
+ afterDisconnect?: (request: AfterDisconnectRequest) => void | Promise<void>;
25
+ }
26
+ /** A plugin, ready to run. */
27
+ export interface Plugin extends PluginOptions {
28
+ /** The capabilities for `hello`. */
29
+ readonly caps: string[];
30
+ }
31
+ /** Throw it from a handler to answer with an error that has this code. */
32
+ export declare class PluginError extends Error {
33
+ readonly code: ErrorCode;
34
+ constructor(message: string, code?: ErrorCode);
35
+ }
36
+ /** Checks the options and works out the capabilities. */
37
+ export declare function definePlugin(options: PluginOptions): Plugin;
38
+ /**
39
+ * Answers one request. A handler that throws gives an `error` reply, so the plugin does not stop.
40
+ * Use it to test a plugin without a process.
41
+ */
42
+ export declare function dispatch(plugin: Plugin, request: Request, transport?: string): Promise<Reply>;
43
+ /** The reply with the header of its request. */
44
+ export declare function frame(request: {
45
+ id: number;
46
+ }, reply: Reply): ReplyFrame;
package/dist/plugin.js ADDED
@@ -0,0 +1,109 @@
1
+ import { PROTOCOL } from "./types.js";
2
+ /** Throw it from a handler to answer with an error that has this code. */
3
+ export class PluginError extends Error {
4
+ code;
5
+ constructor(message, code = "internal") {
6
+ super(message);
7
+ this.name = "PluginError";
8
+ this.code = code;
9
+ }
10
+ }
11
+ const NAME = /^[a-z0-9-]+\.[a-z0-9-]+$/;
12
+ /** Checks the options and works out the capabilities. */
13
+ export function definePlugin(options) {
14
+ if (!NAME.test(options.name)) {
15
+ throw new Error(`the plugin name "${options.name}" must have the form namespace.name, with a-z, 0-9 and - only`);
16
+ }
17
+ if (options.sync && !options.provides?.length) {
18
+ throw new Error('a plugin with a sync handler must say what it provides, for example provides: ["hosts"]');
19
+ }
20
+ const caps = [...(options.sync ? (options.provides ?? []) : [])];
21
+ if (options.beforeConnect)
22
+ caps.push("hook.before_connect");
23
+ if (options.afterDisconnect)
24
+ caps.push("hook.after_disconnect");
25
+ if (options.persistent)
26
+ caps.push("session.persistent");
27
+ return {
28
+ ...options,
29
+ caps,
30
+ };
31
+ }
32
+ function error(code, message) {
33
+ return {
34
+ type: "error",
35
+ code,
36
+ message,
37
+ };
38
+ }
39
+ /**
40
+ * Answers one request. A handler that throws gives an `error` reply, so the plugin does not stop.
41
+ * Use it to test a plugin without a process.
42
+ */
43
+ export async function dispatch(plugin, request, transport = "stdio") {
44
+ try {
45
+ switch (request.type) {
46
+ case "hello": {
47
+ if (!request.protocols.includes(PROTOCOL)) {
48
+ return error("unsupported", `sx offers protocols ${request.protocols.join(", ")}, this plugin speaks ${PROTOCOL}`);
49
+ }
50
+ const hello = {
51
+ type: "hello",
52
+ protocol: PROTOCOL,
53
+ name: plugin.name,
54
+ version: plugin.version,
55
+ caps: plugin.caps,
56
+ transports: [transport],
57
+ };
58
+ // sx must offer the encoding. If it does not, the messages stay JSON.
59
+ if (plugin.encoding === "msgpack" && request.encodings?.includes("msgpack"))
60
+ hello.encoding = "msgpack";
61
+ return hello;
62
+ }
63
+ case "sync": {
64
+ if (!plugin.sync)
65
+ return error("unsupported", "this plugin does not answer sync");
66
+ const result = (await plugin.sync(request)) ?? {};
67
+ return {
68
+ type: "sync",
69
+ ...result,
70
+ };
71
+ }
72
+ case "before_connect": {
73
+ if (!plugin.beforeConnect)
74
+ return error("unsupported", "this plugin has no before_connect hook");
75
+ // A hook that returns nothing allows the connection.
76
+ const decision = await plugin.beforeConnect(request);
77
+ return {
78
+ type: "before_connect",
79
+ action: "allow",
80
+ ...decision,
81
+ };
82
+ }
83
+ case "after_disconnect": {
84
+ if (!plugin.afterDisconnect)
85
+ return error("unsupported", "this plugin has no after_disconnect hook");
86
+ await plugin.afterDisconnect(request);
87
+ return {
88
+ type: "after_disconnect",
89
+ };
90
+ }
91
+ default:
92
+ // A request type that a later sx adds. The guide says to refuse what you do not know.
93
+ return error("unsupported", `unknown request "${request.type}"`);
94
+ }
95
+ }
96
+ catch (e) {
97
+ if (e instanceof PluginError)
98
+ return error(e.code, e.message);
99
+ return error("internal", e instanceof Error ? e.message : String(e));
100
+ }
101
+ }
102
+ /** The reply with the header of its request. */
103
+ export function frame(request, reply) {
104
+ return {
105
+ v: PROTOCOL,
106
+ id: request.id,
107
+ ...reply,
108
+ };
109
+ }
@@ -0,0 +1,14 @@
1
+ import type { MsgpackLibrary } from "./codec.ts";
2
+ import type { Plugin } from "./plugin.ts";
3
+ export interface StdioOptions {
4
+ /** The MessagePack package. Without it, the SDK looks for `@msgpack/msgpack`, then `notepack.io`. */
5
+ msgpack?: MsgpackLibrary | {
6
+ default: MsgpackLibrary;
7
+ };
8
+ }
9
+ /**
10
+ * Runs the plugin on stdin and stdout, as sx starts it. It returns when stdin closes.
11
+ *
12
+ * Stdout belongs to the protocol, so `console.log` is sent to stderr from here on.
13
+ */
14
+ export declare function runStdio(plugin: Plugin, options?: StdioOptions): Promise<void>;
package/dist/stdio.js ADDED
@@ -0,0 +1,76 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { MAX_MESSAGE, asRequest, jsonCodec, loadMsgpack, withLength } from "./codec.js";
3
+ import { dispatch, frame } from "./plugin.js";
4
+ /**
5
+ * Runs the plugin on stdin and stdout, as sx starts it. It returns when stdin closes.
6
+ *
7
+ * Stdout belongs to the protocol, so `console.log` is sent to stderr from here on.
8
+ */
9
+ export async function runStdio(plugin, options = {}) {
10
+ const msgpack = plugin.encoding === "msgpack" ? await loadMsgpack(options.msgpack) : null;
11
+ console.log = console.info = console.debug = (...args) => console.error(...args);
12
+ let codec = jsonCodec;
13
+ let pending = Buffer.alloc(0);
14
+ let queue = Promise.resolve();
15
+ // JSON messages are lines. After `hello`, a plugin that chose MessagePack gets length-prefixed messages.
16
+ const next = () => {
17
+ if (codec === jsonCodec) {
18
+ const end = pending.indexOf(0x0a);
19
+ if (end < 0)
20
+ return pending.length > MAX_MESSAGE ? "too long" : null;
21
+ const line = pending.subarray(0, end);
22
+ pending = pending.subarray(end + 1);
23
+ return line;
24
+ }
25
+ if (pending.length < 4)
26
+ return null;
27
+ const size = pending.readUInt32BE(0);
28
+ if (size > MAX_MESSAGE)
29
+ return "too long";
30
+ if (pending.length < 4 + size)
31
+ return null;
32
+ const message = pending.subarray(4, 4 + size);
33
+ pending = pending.subarray(4 + size);
34
+ return message;
35
+ };
36
+ const write = (bytes) => {
37
+ process.stdout.write(codec === jsonCodec ? Buffer.concat([bytes, Buffer.from("\n")]) : withLength(bytes));
38
+ };
39
+ const drain = async () => {
40
+ for (;;) {
41
+ const bytes = next();
42
+ if (bytes === null)
43
+ return;
44
+ if (bytes === "too long") {
45
+ console.error(`a message is longer than ${MAX_MESSAGE} bytes`);
46
+ process.exit(1);
47
+ }
48
+ if (bytes.length === 0 || (codec === jsonCodec && Buffer.from(bytes).toString().trim() === ""))
49
+ continue;
50
+ let request;
51
+ try {
52
+ request = asRequest(codec.decode(bytes));
53
+ }
54
+ catch (e) {
55
+ console.error(`cannot read a message: ${e instanceof Error ? e.message : e}`);
56
+ continue;
57
+ }
58
+ if (!request) {
59
+ console.error("a message has no id or no type");
60
+ continue;
61
+ }
62
+ const reply = await dispatch(plugin, request, "stdio");
63
+ write(codec.encode(frame(request, reply)));
64
+ // The answer to `hello` is JSON. The messages after it use the encoding that it names.
65
+ if (reply.type === "hello" && reply.encoding === "msgpack" && msgpack)
66
+ codec = msgpack;
67
+ }
68
+ };
69
+ await new Promise((resolve) => {
70
+ process.stdin.on("data", (chunk) => {
71
+ pending = pending.length === 0 ? chunk : Buffer.concat([pending, chunk]);
72
+ queue = queue.then(drain);
73
+ });
74
+ process.stdin.on("end", () => void queue.then(resolve));
75
+ });
76
+ }
@@ -0,0 +1,127 @@
1
+ /** The version of the message format that this package speaks. */
2
+ export declare const PROTOCOL = 1;
3
+ /** One host. sx sends the list it has, and the plugin answers with the list it wants. */
4
+ export interface Host {
5
+ /** The name that ssh gets. sx tells hosts apart by it. */
6
+ alias: string;
7
+ hostname?: string;
8
+ user?: string;
9
+ port?: number;
10
+ tags?: string[];
11
+ meta?: Record<string, string>;
12
+ /** Where the host came from. sx sets it in what it sends, and ignores it in what comes back. */
13
+ source?: string;
14
+ }
15
+ /** A snippet. The name says which kind it is, as for a snippet of the user. */
16
+ export interface Snippet {
17
+ name: string;
18
+ content: string;
19
+ }
20
+ /** A prompt and the snippets that go together. */
21
+ export interface Profile {
22
+ name: string;
23
+ snippets?: string[];
24
+ prompt?: string;
25
+ themes?: string[];
26
+ title?: boolean;
27
+ marks?: boolean;
28
+ }
29
+ /** An environment, such as production. */
30
+ export interface Env {
31
+ name: string;
32
+ label?: string;
33
+ color?: string;
34
+ patterns?: string[];
35
+ features?: string[];
36
+ guard?: string[];
37
+ }
38
+ /** The header of every message. */
39
+ export interface Message {
40
+ v: number;
41
+ id: number;
42
+ }
43
+ export interface HelloRequest extends Message {
44
+ type: "hello";
45
+ sx_version: string;
46
+ protocols: number[];
47
+ transports: string[];
48
+ encodings?: string[];
49
+ }
50
+ export interface SyncRequest extends Message {
51
+ type: "sync";
52
+ /** The user asked for new data: do not answer from your own cache. */
53
+ fresh: boolean;
54
+ hosts: Host[];
55
+ }
56
+ export interface BeforeConnectRequest extends Message {
57
+ type: "before_connect";
58
+ host: string;
59
+ hostname?: string;
60
+ user?: string;
61
+ port?: number;
62
+ env?: string;
63
+ source?: string;
64
+ }
65
+ export interface AfterDisconnectRequest extends Message {
66
+ type: "after_disconnect";
67
+ host: string;
68
+ exit_code: number;
69
+ duration_ms: number;
70
+ }
71
+ /** Every request that sx sends. The `type` field tells them apart. */
72
+ export type Request = HelloRequest | SyncRequest | BeforeConnectRequest | AfterDisconnectRequest;
73
+ export type ErrorCode = "bad_request" | "unsupported" | "internal" | "denied";
74
+ export interface HelloReply {
75
+ type: "hello";
76
+ protocol: number;
77
+ name: string;
78
+ version: string;
79
+ caps: string[];
80
+ transports: string[];
81
+ encoding?: string;
82
+ }
83
+ export interface SyncReply {
84
+ type: "sync";
85
+ hosts?: Host[];
86
+ stop?: boolean;
87
+ snippets?: Snippet[];
88
+ profiles?: Profile[];
89
+ envs?: Env[];
90
+ }
91
+ export interface BeforeConnectReply {
92
+ type: "before_connect";
93
+ action: "allow" | "block";
94
+ reason?: string;
95
+ ssh_args?: string[];
96
+ }
97
+ export interface AfterDisconnectReply {
98
+ type: "after_disconnect";
99
+ }
100
+ export interface ErrorReply {
101
+ type: "error";
102
+ code: ErrorCode;
103
+ message: string;
104
+ }
105
+ /** Every answer that a plugin sends, without the header. */
106
+ export type Reply = HelloReply | SyncReply | BeforeConnectReply | AfterDisconnectReply | ErrorReply;
107
+ /** A reply with its header. */
108
+ export type ReplyFrame = Reply & Message;
109
+ /** What `sync` returns. A part that is left out is not given: sx keeps the host list as it was. */
110
+ export interface SyncResult {
111
+ hosts?: Host[];
112
+ /** End the chain: the plugins after this one are not asked for hosts. */
113
+ stop?: boolean;
114
+ snippets?: Snippet[];
115
+ profiles?: Profile[];
116
+ envs?: Env[];
117
+ }
118
+ /** What `beforeConnect` decides. Return nothing to allow the connection. */
119
+ export interface HookDecision {
120
+ action: "allow" | "block";
121
+ /** Why the connection is refused. Shown to the user. */
122
+ reason?: string;
123
+ /** Options for ssh. sx checks them, and refuses the list when one is not allowed. */
124
+ ssh_args?: string[];
125
+ }
126
+ /** What a plugin can provide. Each one is a capability that the user approves. */
127
+ export type Provides = "hosts" | "snippets" | "profiles" | "envs";
package/dist/types.js ADDED
@@ -0,0 +1,4 @@
1
+ // The messages of the sx plugin protocol, version 1. The names are the ones on the wire,
2
+ // so they match docs/plugins.md in the sx repository.
3
+ /** The version of the message format that this package speaks. */
4
+ export const PROTOCOL = 1;
@@ -0,0 +1,21 @@
1
+ import type { MsgpackLibrary } from "./codec.ts";
2
+ import type { Plugin } from "./plugin.ts";
3
+ export interface WebSocketOptions {
4
+ /** The port. The default is 8765. Use 0 to let the system pick one. */
5
+ port?: number;
6
+ /** The address to listen on. The default is this machine only: sx refuses `ws://` to another host. */
7
+ host?: string;
8
+ /** sx sends it as `Authorization: Bearer <token>`. A connection without it is refused. */
9
+ token?: string;
10
+ /** The MessagePack package. Without it, the SDK looks for `@msgpack/msgpack`, then `notepack.io`. */
11
+ msgpack?: MsgpackLibrary | {
12
+ default: MsgpackLibrary;
13
+ };
14
+ }
15
+ export interface RunningServer {
16
+ /** The port that the server listens on. */
17
+ port: number;
18
+ close(): Promise<void>;
19
+ }
20
+ /** Runs the plugin as a WebSocket server. It needs the package `ws`. */
21
+ export declare function serveWebSocket(plugin: Plugin, options?: WebSocketOptions): Promise<RunningServer>;
@@ -0,0 +1,73 @@
1
+ import { timingSafeEqual } from "node:crypto";
2
+ import { MAX_MESSAGE, asRequest, jsonCodec, loadMsgpack } from "./codec.js";
3
+ import { dispatch, frame } from "./plugin.js";
4
+ function sameToken(sent, token) {
5
+ const want = Buffer.from(`Bearer ${token}`);
6
+ const got = Buffer.from(sent ?? "");
7
+ return got.length === want.length && timingSafeEqual(got, want);
8
+ }
9
+ /** Runs the plugin as a WebSocket server. It needs the package `ws`. */
10
+ export async function serveWebSocket(plugin, options = {}) {
11
+ const msgpack = plugin.encoding === "msgpack" ? await loadMsgpack(options.msgpack) : null;
12
+ let ws;
13
+ try {
14
+ ws = await import("ws");
15
+ }
16
+ catch (e) {
17
+ if (e.code !== "ERR_MODULE_NOT_FOUND")
18
+ throw e;
19
+ throw new Error("a WebSocket plugin needs the package ws: install it");
20
+ }
21
+ const { token } = options;
22
+ const server = new ws.WebSocketServer({
23
+ host: options.host ?? "127.0.0.1",
24
+ port: options.port ?? 8765,
25
+ maxPayload: MAX_MESSAGE,
26
+ verifyClient: (info) => token === undefined || sameToken(info.req.headers.authorization, token),
27
+ });
28
+ server.on("connection", (socket) => {
29
+ // Each connection is one run. It starts with JSON, and `hello` can change that.
30
+ let codec = jsonCodec;
31
+ let queue = Promise.resolve();
32
+ socket.on("message", (data, isBinary) => {
33
+ queue = queue.then(async () => {
34
+ if (isBinary !== (codec !== jsonCodec)) {
35
+ socket.close(1003, `expected a ${codec === jsonCodec ? "text" : "binary"} frame`);
36
+ return;
37
+ }
38
+ let request;
39
+ try {
40
+ request = asRequest(codec.decode(data));
41
+ }
42
+ catch (e) {
43
+ console.error(`cannot read a message: ${e instanceof Error ? e.message : e}`);
44
+ return;
45
+ }
46
+ if (!request) {
47
+ console.error("a message has no id or no type");
48
+ return;
49
+ }
50
+ const reply = await dispatch(plugin, request, "websocket");
51
+ const bytes = codec.encode(frame(request, reply));
52
+ if (codec === jsonCodec)
53
+ socket.send(Buffer.from(bytes).toString("utf8"));
54
+ else
55
+ socket.send(bytes, { binary: true });
56
+ if (reply.type === "hello" && reply.encoding === "msgpack" && msgpack)
57
+ codec = msgpack;
58
+ });
59
+ });
60
+ });
61
+ await new Promise((resolve, reject) => {
62
+ server.once("listening", resolve);
63
+ server.once("error", reject);
64
+ });
65
+ return {
66
+ port: server.address().port,
67
+ close: () => new Promise((resolve) => {
68
+ for (const client of server.clients)
69
+ client.terminate();
70
+ server.close(() => resolve());
71
+ }),
72
+ };
73
+ }
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "sx-plugin-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Write a plugin for sx: the message types and the code that runs a plugin over stdio or a WebSocket",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/vittee/sx.git",
9
+ "directory": "sdk/node"
10
+ },
11
+ "keywords": ["sx", "ssh", "plugin"],
12
+ "type": "module",
13
+ "packageManager": "pnpm@11.9.0",
14
+ "engines": {
15
+ "node": ">=20"
16
+ },
17
+ "main": "dist/index.js",
18
+ "types": "dist/index.d.ts",
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "default": "./dist/index.js"
23
+ }
24
+ },
25
+ "files": ["dist", "README.md"],
26
+ "scripts": {
27
+ "build": "tsc -p tsconfig.build.json",
28
+ "check": "tsc",
29
+ "test": "node --test \"test/*.test.ts\"",
30
+ "prepublishOnly": "pnpm run check && pnpm test && pnpm run build"
31
+ },
32
+ "peerDependencies": {
33
+ "@msgpack/msgpack": "^3.0.0",
34
+ "notepack.io": "^3.0.0",
35
+ "ws": "^8.0.0"
36
+ },
37
+ "peerDependenciesMeta": {
38
+ "@msgpack/msgpack": { "optional": true },
39
+ "notepack.io": { "optional": true },
40
+ "ws": { "optional": true }
41
+ },
42
+ "devDependencies": {
43
+ "@msgpack/msgpack": "^3.0.0",
44
+ "@types/node": "^22.18.0",
45
+ "@types/ws": "^8.5.0",
46
+ "notepack.io": "^3.0.1",
47
+ "typescript": "^5.9.0",
48
+ "ws": "^8.18.0"
49
+ }
50
+ }