feat: convert wake-on-lan into a plugin (B20)

This commit is contained in:
LukeGus committed 2026-09-24 15:49:55 -05:00
1 parent d4ec444558
commit 2ac7779eda
50 files changed
+17844 -199

No files matched your search

+27
View File
@@ -0,0 +1,27 @@
{
"hostAction": {
"title": "Wake",
"sent": "Wake-on-LAN packet sent",
"failed": "Failed to send Wake-on-LAN packet"
},
"permissions": {
"send": {
"title": "Send Wake-on-LAN packets",
"description": "Wake a host by sending a magic packet to its MAC address."
}
},
"settings": {
"host": {
"macAddress": {
"label": "MAC address",
"description": "The host's network MAC address, used to send Wake-on-LAN packets.",
"placeholder": "AA:BB:CC:DD:EE:FF"
},
"broadcastAddress": {
"label": "Broadcast address",
"description": "The subnet broadcast address to send the packet to. Leave blank for 255.255.255.255.",
"placeholder": "192.168.1.255"
}
}
}
}
+62
View File
@@ -0,0 +1,62 @@
{
"id": "wake-on-lan",
"name": "Wake-on-LAN",
"version": "1.0.0",
"description": "Wake a sleeping host by sending a Wake-on-LAN magic packet to its MAC address.",
"author": {
"name": "Termix"
},
"license": "MIT",
"repository": "https://github.com/Termix-SSH/Termix",
"category": "Networking",
"icon": "Zap",
"engine": {
"termix": ">=2.9.0",
"api": "1"
},
"capabilities": [
"hosts:read",
"network:broadcast",
"network:serve",
"ui:surface"
],
"provides": [
{
"service": "wake-on-lan.send",
"version": "1.0.0",
"permission": "wake-on-lan.send"
}
],
"contributes": {
"permissions": [
{
"name": "send",
"titleKey": "permissions.send.title",
"descriptionKey": "permissions.send.description",
"defaultRoles": ["admin", "user"]
}
],
"settings": {
"host": {
"fields": [
{
"key": "macAddress",
"type": "string",
"labelKey": "settings.host.macAddress.label",
"descriptionKey": "settings.host.macAddress.description",
"placeholderKey": "settings.host.macAddress.placeholder"
},
{
"key": "broadcastAddress",
"type": "string",
"labelKey": "settings.host.broadcastAddress.label",
"descriptionKey": "settings.host.broadcastAddress.description",
"placeholderKey": "settings.host.broadcastAddress.placeholder"
}
]
}
}
},
"locales": "locales",
"platforms": ["linux", "win32", "darwin"]
}
+15
View File
@@ -0,0 +1,15 @@
{
"name": "@termix-plugin/wake-on-lan",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"build": "termix-plugin build",
"test": "termix-plugin test",
"typecheck": "tsc -p tsconfig.json",
"validate": "termix-plugin validate"
},
"devDependencies": {
"@termix/plugin-sdk": "*"
}
}
+15
View File
@@ -0,0 +1,15 @@
import type { Router } from "express";
import type { PluginContext } from "@termix/plugin-sdk/backend";
import { createWakeOnLanService } from "./service.js";
import { registerWakeOnLanRoutes } from "./routes.js";
export async function activate(ctx: PluginContext) {
const service = createWakeOnLanService(ctx);
ctx.services.provide("wake-on-lan.send", service);
registerWakeOnLanRoutes(ctx.http.router<Router>(), ctx, service);
ctx.log.info("Wake-on-LAN routes mounted at /plugin-api/wake-on-lan");
}
export async function deactivate() {
// Everything above was registered through ctx and is disposed by core.
}
@@ -0,0 +1,49 @@
import dgram from "dgram";
const MAC_REGEX = /^([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}$/;
function parseMac(mac: string): Buffer {
return Buffer.from(mac.replace(/[:-]/g, ""), "hex");
}
export function buildMagicPacket(mac: string): Buffer {
const macBytes = parseMac(mac);
const packet = Buffer.alloc(102);
packet.fill(0xff, 0, 6);
for (let i = 0; i < 16; i++) {
macBytes.copy(packet, 6 + i * 6);
}
return packet;
}
export function isValidMac(mac: string): boolean {
return MAC_REGEX.test(mac);
}
export function sendMagicPacket(
mac: string,
broadcastAddress = "255.255.255.255",
): Promise<void> {
return new Promise((resolve, reject) => {
if (!isValidMac(mac)) {
return reject(new Error("Invalid MAC address"));
}
const packet = buildMagicPacket(mac);
const socket = dgram.createSocket("udp4");
socket.once("error", (err) => {
socket.close();
reject(err);
});
socket.bind(() => {
socket.setBroadcast(true);
socket.send(packet, 0, packet.length, 9, broadcastAddress, (err) => {
socket.close();
if (err) reject(err);
else resolve();
});
});
});
}
+47
View File
@@ -0,0 +1,47 @@
import type { Request, Response, Router } from "express";
import type { PluginContext } from "@termix/plugin-sdk/backend";
import type { WakeOnLanV1 } from "./service.js";
export function registerWakeOnLanRoutes(
router: Router,
ctx: PluginContext,
service: WakeOnLanV1,
): void {
router.use(ctx.rbac.require("send") as never);
/**
* @openapi
* /plugin-api/wake-on-lan/host/{id}/wake:
* post:
* summary: Send a Wake-on-LAN magic packet to a host
* tags:
* - Wake-on-LAN
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* responses:
* 200:
* description: Packet sent
* 400:
* description: No valid MAC address configured
* 404:
* description: Host not found
*/
router.post("/host/:id/wake", async (req: Request, res: Response) => {
const hostId = Number.parseInt(String(req.params.id), 10);
if (!Number.isInteger(hostId)) {
return res.status(400).json({ error: "Invalid host id" });
}
try {
await service.wake(hostId);
res.json({ success: true });
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
const status = message === "Host not found" ? 404 : 400;
res.status(status).json({ error: message });
}
});
}
@@ -0,0 +1,33 @@
import type { PluginContext } from "@termix/plugin-sdk/backend";
import { isValidMac, sendMagicPacket } from "./magic-packet.js";
export interface WakeOnLanV1 {
wake: (hostId: number) => Promise<void>;
}
export function createWakeOnLanService(ctx: PluginContext): WakeOnLanV1 {
return {
async wake(hostId: number): Promise<void> {
const host = await ctx.hosts.get(hostId);
if (!host) {
throw new Error("Host not found");
}
const macAddress = await ctx.settings.getHost<string>(
hostId,
"macAddress",
);
if (!macAddress || !isValidMac(macAddress)) {
throw new Error("No valid MAC address configured");
}
const broadcastAddress = await ctx.settings.getHost<string>(
hostId,
"broadcastAddress",
);
await ctx.capabilities.require("network:broadcast");
await sendMagicPacket(macAddress, broadcastAddress || undefined);
ctx.log.info(`Wake-on-LAN packet sent to host ${hostId}`);
},
};
}
@@ -0,0 +1,28 @@
import { toast } from "sonner";
import type { PluginApiClient, TermixApp } from "@termix/plugin-sdk/frontend";
export function hasMacAddress(host: Record<string, unknown>): boolean {
const settings = host.pluginSettings as
Record<string, Record<string, unknown>> | undefined;
const macAddress = settings?.["wake-on-lan"]?.macAddress;
return typeof macAddress === "string" && macAddress.trim().length > 0;
}
function errorMessage(error: unknown, fallback: string): string {
const message = (error as { response?: { data?: { error?: string } } })
?.response?.data?.error;
return message ?? fallback;
}
export function wakeHost(
api: PluginApiClient,
t: TermixApp["t"],
hostId: string,
): void {
void api
.post(`/host/${hostId}/wake`)
.then(() => toast.success(t("hostAction.sent")))
.catch((error: unknown) => {
toast.error(errorMessage(error, t("hostAction.failed")));
});
}
@@ -0,0 +1,15 @@
import { Zap } from "lucide-react";
import type { TermixApp } from "@termix/plugin-sdk/frontend";
import { hasMacAddress, wakeHost } from "./host-action.js";
export function activate(app: TermixApp): void {
app.registerHostAction({
id: "wake-on-lan",
titleKey: "hostAction.title",
icon: Zap,
kind: "open",
order: 50,
when: (host) => hasMacAddress(host as Record<string, unknown>),
run: (host) => wakeHost(app.api, app.t, String(host.id)),
});
}
@@ -0,0 +1,77 @@
import http from "node:http";
import type { AddressInfo } from "node:net";
import express, { type Router } from "express";
import {
createMockCtx,
type MockPluginContext,
} from "@termix/plugin-sdk/testing";
import type { PluginManifest } from "@termix/plugin-sdk/manifest";
import type { PluginHostSummary } from "@termix/plugin-sdk/backend";
import manifestJson from "../../manifest.json";
export const manifest = manifestJson as unknown as PluginManifest;
export interface TestServer {
mock: MockPluginContext;
request: (
method: string,
path: string,
options?: { user?: string; body?: unknown },
// eslint-disable-next-line @typescript-eslint/no-explicit-any
) => Promise<{ status: number; body: any }>;
close: () => Promise<void>;
}
export async function startServer(
options: {
permissions?: string[];
hosts?: PluginHostSummary[];
capabilities?: string[];
} = {},
): Promise<TestServer> {
let router: Router | null = null;
const mock = createMockCtx({
pluginId: manifest.id,
manifest,
capabilities: options.capabilities ?? manifest.capabilities,
router: () => (router = express.Router()),
permissions: options.permissions ?? ["wake-on-lan.send"],
hosts: options.hosts ?? [],
actor: "user-1",
});
const { activate } = await import("../../src/backend/index.js");
await activate(mock.ctx);
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
mock.setActor(req.header("x-test-user") ?? undefined);
next();
});
app.use((req, res, next) => router!(req, res, next));
const server = http.createServer(app);
await new Promise<void>((resolve) => server.listen(0, resolve));
const { port } = server.address() as AddressInfo;
return {
mock,
async request(method, path, { user = "user-1", body: given } = {}) {
const body = method === "GET" ? undefined : given;
const response = await fetch(`http://127.0.0.1:${port}${path}`, {
method,
headers: {
"x-test-user": user,
...(body !== undefined ? { "content-type": "application/json" } : {}),
},
body: body !== undefined ? JSON.stringify(body) : undefined,
});
const text = await response.text();
return { status: response.status, body: text ? JSON.parse(text) : null };
},
async close() {
await new Promise<void>((resolve) => server.close(() => resolve()));
},
};
}
@@ -0,0 +1,120 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("dgram", () => {
const socket = {
once: vi.fn(),
bind: vi.fn(),
setBroadcast: vi.fn(),
send: vi.fn(),
close: vi.fn(),
};
return { default: { createSocket: vi.fn(() => socket) } };
});
import dgram from "dgram";
import {
isValidMac,
buildMagicPacket,
sendMagicPacket,
} from "../../src/backend/magic-packet.js";
describe("isValidMac", () => {
it("accepts colon-separated MAC addresses", () => {
expect(isValidMac("01:23:45:67:89:AB")).toBe(true);
expect(isValidMac("aa:bb:cc:dd:ee:ff")).toBe(true);
});
it("accepts hyphen-separated MAC addresses", () => {
expect(isValidMac("01-23-45-67-89-AB")).toBe(true);
});
it("rejects malformed MAC addresses", () => {
expect(isValidMac("")).toBe(false);
expect(isValidMac("01:23:45:67:89")).toBe(false);
expect(isValidMac("01:23:45:67:89:AB:CD")).toBe(false);
expect(isValidMac("0123456789AB")).toBe(false);
expect(isValidMac("zz:23:45:67:89:ab")).toBe(false);
expect(isValidMac("01:23:45:67:89:AB ")).toBe(false);
});
});
describe("buildMagicPacket", () => {
it("produces a 102-byte packet", () => {
const packet = buildMagicPacket("01:23:45:67:89:AB");
expect(packet.length).toBe(102);
});
it("starts with six 0xFF bytes", () => {
const packet = buildMagicPacket("01:23:45:67:89:AB");
expect([...packet.subarray(0, 6)]).toEqual([
0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
]);
});
it("repeats the MAC bytes 16 times after the header", () => {
const packet = buildMagicPacket("01:23:45:67:89:AB");
const mac = Buffer.from([0x01, 0x23, 0x45, 0x67, 0x89, 0xab]);
for (let i = 0; i < 16; i++) {
const offset = 6 + i * 6;
expect([...packet.subarray(offset, offset + 6)]).toEqual([...mac]);
}
});
it("treats colon and hyphen separators identically", () => {
const colon = buildMagicPacket("aa:bb:cc:dd:ee:ff");
const hyphen = buildMagicPacket("aa-bb-cc-dd-ee-ff");
expect(colon.equals(hyphen)).toBe(true);
});
});
describe("sendMagicPacket", () => {
let mockSocket: ReturnType<typeof dgram.createSocket>;
beforeEach(() => {
vi.clearAllMocks();
mockSocket = (dgram.createSocket as ReturnType<typeof vi.fn>)();
(mockSocket.bind as ReturnType<typeof vi.fn>).mockImplementation(
(cb: () => void) => cb(),
);
(mockSocket.send as ReturnType<typeof vi.fn>).mockImplementation(
(
_buf: unknown,
_off: unknown,
_len: unknown,
_port: unknown,
_addr: unknown,
cb: (err: null) => void,
) => cb(null),
);
});
it("rejects on invalid MAC address", async () => {
await expect(sendMagicPacket("not-a-mac")).rejects.toThrow(
"Invalid MAC address",
);
});
it("sends to 255.255.255.255 by default", async () => {
await sendMagicPacket("aa:bb:cc:dd:ee:ff");
expect(mockSocket.send).toHaveBeenCalledWith(
expect.any(Buffer),
0,
102,
9,
"255.255.255.255",
expect.any(Function),
);
});
it("sends to a custom broadcast address when provided", async () => {
await sendMagicPacket("aa:bb:cc:dd:ee:ff", "192.168.1.255");
expect(mockSocket.send).toHaveBeenCalledWith(
expect.any(Buffer),
0,
102,
9,
"192.168.1.255",
expect.any(Function),
);
});
});
@@ -0,0 +1,65 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import type { PluginHostSummary } from "@termix/plugin-sdk/backend";
import { startServer, type TestServer } from "./helpers.js";
vi.mock("../../src/backend/magic-packet.js", async () => {
const actual = await vi.importActual<
typeof import("../../src/backend/magic-packet.js")
>("../../src/backend/magic-packet.js");
return { ...actual, sendMagicPacket: vi.fn().mockResolvedValue(undefined) };
});
const HOST: PluginHostSummary = {
id: 1,
userId: "user-1",
name: "server",
ip: "10.0.0.5",
port: 22,
username: "root",
tags: null,
folder: null,
authType: "password",
};
describe("POST /host/:id/wake", () => {
let server: TestServer;
beforeEach(() => {
vi.clearAllMocks();
});
afterEach(async () => {
await server?.close();
});
it("sends the packet for a configured host", async () => {
server = await startServer({ hosts: [HOST] });
await server.mock.ctx.settings.setHost(
1,
"macAddress",
"aa:bb:cc:dd:ee:ff",
);
const response = await server.request("POST", "/host/1/wake");
expect(response.status).toBe(200);
expect(response.body).toEqual({ success: true });
});
it("404s for an unknown host", async () => {
server = await startServer({ hosts: [] });
const response = await server.request("POST", "/host/999/wake");
expect(response.status).toBe(404);
});
it("400s when no MAC address is configured", async () => {
server = await startServer({ hosts: [HOST] });
const response = await server.request("POST", "/host/1/wake");
expect(response.status).toBe(400);
});
it("denies a caller without wake-on-lan.send", async () => {
server = await startServer({ hosts: [HOST], permissions: [] });
const response = await server.request("POST", "/host/1/wake");
expect(response.status).toBe(403);
});
});
@@ -0,0 +1,100 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { createMockCtx } from "@termix/plugin-sdk/testing";
import { createWakeOnLanService } from "../../src/backend/service.js";
vi.mock("../../src/backend/magic-packet.js", async () => {
const actual = await vi.importActual<
typeof import("../../src/backend/magic-packet.js")
>("../../src/backend/magic-packet.js");
return { ...actual, sendMagicPacket: vi.fn().mockResolvedValue(undefined) };
});
import { sendMagicPacket } from "../../src/backend/magic-packet.js";
const HOST = {
id: 1,
userId: "user-1",
name: "server",
ip: "10.0.0.5",
port: 22,
authType: "password",
};
describe("wake-on-lan service", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("sends a magic packet for a host with a valid MAC", async () => {
const mock = createMockCtx({
capabilities: ["hosts:read", "network:broadcast"],
hosts: [HOST],
actor: "user-1",
});
await mock.ctx.settings.setHost(1, "macAddress", "aa:bb:cc:dd:ee:ff");
const service = createWakeOnLanService(mock.ctx);
await service.wake(1);
expect(sendMagicPacket).toHaveBeenCalledWith(
"aa:bb:cc:dd:ee:ff",
undefined,
);
});
it("passes the configured broadcast address", async () => {
const mock = createMockCtx({
capabilities: ["hosts:read", "network:broadcast"],
hosts: [HOST],
actor: "user-1",
});
await mock.ctx.settings.setHost(1, "macAddress", "aa:bb:cc:dd:ee:ff");
await mock.ctx.settings.setHost(1, "broadcastAddress", "192.168.1.255");
const service = createWakeOnLanService(mock.ctx);
await service.wake(1);
expect(sendMagicPacket).toHaveBeenCalledWith(
"aa:bb:cc:dd:ee:ff",
"192.168.1.255",
);
});
it("rejects a host with no MAC address configured", async () => {
const mock = createMockCtx({
capabilities: ["hosts:read", "network:broadcast"],
hosts: [HOST],
actor: "user-1",
});
const service = createWakeOnLanService(mock.ctx);
await expect(service.wake(1)).rejects.toThrow(
"No valid MAC address configured",
);
expect(sendMagicPacket).not.toHaveBeenCalled();
});
it("rejects an unknown host", async () => {
const mock = createMockCtx({
capabilities: ["hosts:read", "network:broadcast"],
hosts: [],
actor: "user-1",
});
const service = createWakeOnLanService(mock.ctx);
await expect(service.wake(999)).rejects.toThrow("Host not found");
});
it("fails closed without network:broadcast", async () => {
const mock = createMockCtx({
capabilities: ["hosts:read"],
hosts: [HOST],
actor: "user-1",
});
await mock.ctx.settings.setHost(1, "macAddress", "aa:bb:cc:dd:ee:ff");
const service = createWakeOnLanService(mock.ctx);
await expect(service.wake(1)).rejects.toThrow();
expect(sendMagicPacket).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,33 @@
import { afterEach, describe, expect, it } from "vitest";
import {
renderWithApp,
type RenderedPluginApp,
} from "@termix/plugin-sdk/testing";
import type { PluginManifest } from "@termix/plugin-sdk/manifest";
import * as plugin from "../../src/frontend/index";
import manifestJson from "../../manifest.json";
import locales from "../../locales/en.json";
const manifest = manifestJson as unknown as PluginManifest;
let rendered: RenderedPluginApp | null = null;
afterEach(async () => {
await rendered?.deactivate();
rendered = null;
});
describe(`${manifest.id} activate`, () => {
it("registers the Wake host action", async () => {
rendered = await renderWithApp(plugin, { manifest, locales });
expect(rendered.registered.hostActions()).toEqual([
expect.objectContaining({ id: "wake-on-lan" }),
]);
});
it("removes the host action on deactivate", async () => {
const app = await renderWithApp(plugin, { manifest, locales });
await app.deactivate();
expect(app.registered.hostActions()).toEqual([]);
});
});
@@ -0,0 +1,74 @@
import { describe, it, expect, vi, afterEach } from "vitest";
import { toast } from "sonner";
import type { PluginApiClient } from "@termix/plugin-sdk/frontend";
import { hasMacAddress, wakeHost } from "../../src/frontend/host-action.js";
vi.mock("sonner", () => ({
toast: { success: vi.fn(), error: vi.fn() },
}));
afterEach(() => {
vi.clearAllMocks();
});
function stubApi(overrides: Partial<PluginApiClient> = {}): PluginApiClient {
return {
get: vi.fn(async () => ({ data: {} })),
post: vi.fn(async () => ({ data: {} })),
put: vi.fn(async () => ({ data: {} })),
patch: vi.fn(async () => ({ data: {} })),
delete: vi.fn(async () => ({ data: {} })),
...overrides,
} as PluginApiClient;
}
const t = (key: string) => key;
describe("hasMacAddress", () => {
it("is true when the host's wake-on-lan settings carry a MAC address", () => {
expect(
hasMacAddress({
pluginSettings: { "wake-on-lan": { macAddress: "aa:bb:cc:dd:ee:ff" } },
}),
).toBe(true);
});
it("is false with no plugin settings", () => {
expect(hasMacAddress({})).toBe(false);
});
it("is false with an empty MAC address", () => {
expect(
hasMacAddress({ pluginSettings: { "wake-on-lan": { macAddress: "" } } }),
).toBe(false);
});
});
describe("wakeHost", () => {
it("posts to the host's wake route and toasts success", async () => {
const api = stubApi();
wakeHost(api, t, "1");
await vi.waitFor(() =>
expect(api.post).toHaveBeenCalledWith("/host/1/wake"),
);
await vi.waitFor(() => expect(toast.success).toHaveBeenCalled());
});
it("toasts the server's error message on failure", async () => {
const api = stubApi({
post: vi
.fn()
.mockRejectedValue({ response: { data: { error: "no mac" } } }),
});
wakeHost(api, t, "1");
await vi.waitFor(() => expect(toast.error).toHaveBeenCalledWith("no mac"));
});
it("falls back to a generic message with no server error", async () => {
const api = stubApi({ post: vi.fn().mockRejectedValue(new Error("x")) });
wakeHost(api, t, "1");
await vi.waitFor(() =>
expect(toast.error).toHaveBeenCalledWith("hostAction.failed"),
);
});
});
+4
View File
@@ -0,0 +1,4 @@
{
"extends": "@termix/plugin-sdk/tsconfig.plugin.json",
"include": ["src/**/*.ts", "src/**/*.tsx", "tests/**/*.ts", "tests/**/*.tsx"]
}
+3
View File
@@ -0,0 +1,3 @@
import { pluginVitestConfig } from "@termix/plugin-sdk/vitest-preset";
export default pluginVitestConfig(import.meta.url);