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

@@ -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"),
);
});
});