feat: move totp and passkeys into plugins (C1)

This commit is contained in:
LukeGus committed 2026-09-24 16:57:24 -05:00
1 parent f4f26a9b8b
commit 5c18435105
235 files changed
+22545 -5610

No files matched your search

+95
View File
@@ -0,0 +1,95 @@
import http from "node:http";
import type { AddressInfo } from "node:net";
import { fileURLToPath } from "node:url";
import express, { type Router } from "express";
import {
createMockCtx,
createTestDb,
type MockPluginContext,
type TestDb,
} from "@termix/plugin-sdk/testing";
import type { PluginManifest } from "@termix/plugin-sdk/manifest";
import manifestJson from "../../manifest.json";
export const pluginDir = fileURLToPath(new URL("../..", import.meta.url));
export const manifest = manifestJson as unknown as PluginManifest;
export interface TestServer {
db: TestDb;
mock: MockPluginContext;
request: (
method: string,
path: string,
options?: { user?: string; body?: unknown },
// Route bodies vary per test; asserting on them is the point.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
) => Promise<{ status: number; body: any }>;
close: () => Promise<void>;
}
/**
* The plugin activated against a real in-memory database, its router mounted
* on an express app the way core mounts it: JSON parsed, the acting user set
* from the request, everything else left to the plugin.
*/
export async function startServer(
options: {
users?: string[];
capabilities?: string[];
refuseEnrollment?: string;
} = {},
): Promise<TestServer> {
const db = await createTestDb(pluginDir);
for (const user of options.users ?? ["user-1", "user-2"]) {
db.sqlite
.prepare("INSERT INTO users (id, username) VALUES (?, ?)")
.run(user, user);
}
let router: Router | null = null;
const mock = createMockCtx({
pluginId: manifest.id,
manifest,
capabilities: options.capabilities ?? manifest.capabilities,
db: db.database,
router: () => (router = express.Router()),
refuseEnrollment: options.refuseEnrollment,
});
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 {
db,
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()));
db.close();
},
};
}
+258
View File
@@ -0,0 +1,258 @@
import { afterEach, describe, expect, it } from "vitest";
import speakeasy from "speakeasy";
import { startServer, type TestServer } from "./helpers";
import { generateBackupCode, normalizeCode } from "../../src/backend/totp.js";
let server: TestServer | null = null;
afterEach(async () => {
await server?.close();
server = null;
});
const codeFor = (secret: string) =>
speakeasy.totp({ secret, encoding: "base32" });
async function enrol(target: TestServer, user = "user-1") {
const setup = await target.request("POST", "/setup", { user, body: {} });
expect(setup.status).toBe(200);
const secret: string = setup.body.secret;
const enable = await target.request("POST", "/enable", {
user,
body: { totp_code: codeFor(secret) },
});
expect(enable.status).toBe(200);
return { secret, backupCodes: enable.body.backup_codes as string[] };
}
function factor(target: TestServer) {
const registered = target.mock.auth.secondFactors.find(
(entry) => entry.id === "totp",
);
if (!registered) throw new Error("totp factor not registered");
return registered;
}
describe("enrolment", () => {
it("sets up, enables, records the enrolment and reports status", async () => {
server = await startServer();
expect((await server.request("GET", "/status")).body).toEqual({
enabled: false,
});
const setup = await server.request("POST", "/setup", { body: {} });
expect(setup.body.qr_code).toMatch(/^data:image\/png;base64,/);
expect(setup.body.secret).toMatch(/^[A-Z2-7]+$/);
const wrong = await server.request("POST", "/enable", {
body: { totp_code: "000000" },
});
expect(wrong.status).toBe(401);
expect(await factor(server).isEnrolled("user-1")).toBe(false);
const enable = await server.request("POST", "/enable", {
body: { totp_code: codeFor(setup.body.secret) },
});
expect(enable.status).toBe(200);
expect(enable.body.backup_codes).toHaveLength(8);
expect(server.mock.auth.enrollments.has("user-1:totp")).toBe(true);
expect((await server.request("GET", "/status")).body).toEqual({
enabled: true,
});
});
it("stores the secret sealed, never in the clear", async () => {
server = await startServer();
const { secret } = await enrol(server);
const row = server.db.sqlite
.prepare("SELECT * FROM p_totp_enrollments WHERE user_id = 'user-1'")
.get() as Record<string, string | null>;
expect(row.secret).not.toContain(secret);
expect(row.secret).toMatch(/^sealed:/);
expect(row.pending_secret).toBeNull();
});
it("refuses enable before setup and when already on", async () => {
server = await startServer();
expect(
(
await server.request("POST", "/enable", {
body: { totp_code: "123456" },
})
).status,
).toBe(400);
const { secret } = await enrol(server);
expect(
(
await server.request("POST", "/enable", {
body: { totp_code: codeFor(secret) },
})
).status,
).toBe(400);
});
it("leaves nothing enabled when core refuses the enrolment", async () => {
server = await startServer({
refuseEnrollment: "Cannot enable 2FA while password login is disabled.",
});
const setup = await server.request("POST", "/setup", { body: {} });
const enable = await server.request("POST", "/enable", {
body: { totp_code: codeFor(setup.body.secret) },
});
expect(enable.status).toBe(409);
expect(enable.body.error).toMatch(/password login/);
expect(await factor(server).isEnrolled("user-1")).toBe(false);
});
it("adds another authenticator only with a valid code", async () => {
server = await startServer();
const { secret } = await enrol(server);
expect((await server.request("POST", "/setup", { body: {} })).status).toBe(
400,
);
expect(
(
await server.request("POST", "/setup", {
body: { credential: "000000" },
})
).status,
).toBe(401);
const again = await server.request("POST", "/setup", {
body: { credential: codeFor(secret) },
});
expect(again.body).toMatchObject({ secret, additional: true });
});
it("disables with a code and removes the enrolment", async () => {
server = await startServer();
const { secret } = await enrol(server);
expect(
(
await server.request("POST", "/disable", {
body: { totp_code: "000000" },
})
).status,
).toBe(401);
const off = await server.request("POST", "/disable", {
body: { totp_code: codeFor(secret) },
});
expect(off.status).toBe(200);
expect(server.mock.auth.enrollments.has("user-1:totp")).toBe(false);
expect(await factor(server).isEnrolled("user-1")).toBe(false);
});
it("replaces backup codes", async () => {
server = await startServer();
const { secret, backupCodes } = await enrol(server);
const fresh = await server.request("POST", "/backup-codes", {
body: { totp_code: codeFor(secret) },
});
expect(fresh.body.backup_codes).toHaveLength(8);
expect(
await factor(server).verify("user-1", { totp_code: backupCodes[0] }),
).toBe(false);
expect(
await factor(server).verify("user-1", {
totp_code: fresh.body.backup_codes[0],
}),
).toBe(true);
});
it("keeps users apart", async () => {
server = await startServer();
await enrol(server, "user-1");
expect(
(await server.request("GET", "/status", { user: "user-2" })).body,
).toEqual({ enabled: false });
});
});
describe("login", () => {
it("verifies a current code and refuses a wrong one", async () => {
server = await startServer();
const { secret } = await enrol(server);
expect(await factor(server).verify("user-1", { totp_code: "000000" })).toBe(
false,
);
expect(
await factor(server).verify("user-1", { totp_code: codeFor(secret) }),
).toBe(true);
});
it("accepts each backup code once, typed in any case", async () => {
server = await startServer();
const { backupCodes } = await enrol(server);
const [first] = backupCodes;
expect(
await factor(server).verify("user-1", {
totp_code: first.toLowerCase(),
}),
).toBe(true);
expect(await factor(server).verify("user-1", { totp_code: first })).toBe(
false,
);
expect(
await factor(server).verify("user-1", { totp_code: backupCodes[1] }),
).toBe(true);
});
it("refuses with a message when the user has no readable secret", async () => {
server = await startServer();
expect(
await factor(server).verify("user-1", { totp_code: "123456" }),
).toMatchObject({ ok: false });
});
it("reset removes the enrolment, as the admin reset calls it", async () => {
server = await startServer();
const { secret } = await enrol(server);
await factor(server).reset!("user-1");
expect(await factor(server).isEnrolled("user-1")).toBe(false);
expect(
await factor(server).verify("user-1", { totp_code: codeFor(secret) }),
).toMatchObject({ ok: false });
});
it("drops the enrolment with the user", async () => {
server = await startServer();
await enrol(server);
server.db.sqlite.exec("DELETE FROM users WHERE id = 'user-1'");
expect(await factor(server).isEnrolled("user-1")).toBe(false);
});
});
describe("capabilities", () => {
it("fails closed without auth:provide", async () => {
await expect(
startServer({
capabilities: ["db:own", "secrets:own", "network:serve", "ui:surface"],
}),
).rejects.toThrow(/auth:provide/);
});
it("fails closed without db:own", async () => {
await expect(
startServer({
capabilities: [
"secrets:own",
"network:serve",
"auth:provide",
"ui:surface",
],
}),
).rejects.toThrow(/db:own/);
});
});
describe("helpers", () => {
it("makes backup codes from the unambiguous alphabet", () => {
for (let i = 0; i < 50; i++) {
expect(generateBackupCode()).toMatch(/^[A-HJ-NP-Z2-9]{8}$/);
}
});
it("normalises codes", () => {
expect(normalizeCode(" abcd1234 ")).toBe("ABCD1234");
expect(normalizeCode(42)).toBe("");
});
});
@@ -0,0 +1,90 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { fireEvent, screen, waitFor } from "@testing-library/react";
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 {
isValidTotpInput,
normalizeTotpInput,
} from "../../src/frontend/totp-input";
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 second factor with an enrolment section", async () => {
rendered = await renderWithApp(plugin, { manifest, locales });
expect(rendered.registered.secondFactors()).toEqual(["totp"]);
});
it("sends the typed code, backup codes included", async () => {
rendered = await renderWithApp(plugin, { manifest, locales });
const verify = vi.fn(async () => {});
rendered.renderSecondFactor("totp", { verify });
fireEvent.change(document.getElementById("totp-code")!, {
target: { value: "ab-cd 12 34" },
});
fireEvent.submit(document.getElementById("totp-code")!.closest("form")!);
await waitFor(() =>
expect(verify).toHaveBeenCalledWith({ totp_code: "ABCD1234" }),
);
});
it("shows the enrolment state from the plugin API", async () => {
rendered = await renderWithApp(plugin, {
manifest,
locales,
api: {
get: vi.fn(async () => ({ data: { enabled: true } })),
} as never,
});
rendered.renderEnrollment("totp");
expect(await screen.findByText(locales.enrollment.on)).toBeTruthy();
expect(screen.getByText(locales.enrollment.addDevice)).toBeTruthy();
});
it("starts setup and shows the QR code", async () => {
const post = vi.fn(async () => ({
data: { secret: "JBSWY3DPEHPK3PXP", qr_code: "data:image/png;base64,x" },
}));
rendered = await renderWithApp(plugin, {
manifest,
locales,
api: {
get: vi.fn(async () => ({ data: { enabled: false } })),
post,
} as never,
});
rendered.renderEnrollment("totp");
fireEvent.click(await screen.findByText(locales.enrollment.enable));
expect(await screen.findByText("JBSWY3DPEHPK3PXP")).toBeTruthy();
expect(post).toHaveBeenCalledWith("setup", {});
});
it("removes the factor on deactivate", async () => {
const app = await renderWithApp(plugin, { manifest, locales });
await app.deactivate();
expect(app.registered.secondFactors()).toEqual([]);
});
});
describe("totp input", () => {
it("normalises and validates codes", () => {
expect(normalizeTotpInput("12 34-56")).toBe("123456");
expect(normalizeTotpInput("abcd1234ef")).toBe("ABCD1234");
expect(isValidTotpInput("123456")).toBe(true);
expect(isValidTotpInput("ABCD1234")).toBe(true);
expect(isValidTotpInput("12345")).toBe(false);
});
});