/** * Opening osTicket tickets for alerts: the decision (planTicketRun), the osTicket API client (against a fake osTicket), the runner * over several simulated checks, and the admin routes. * * Run with: npm test --workspace server */ import { test, describe, before, after, beforeEach } from "node:test"; import assert from "node:assert/strict"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import http from "node:http"; const dir = mkdtempSync(join(tmpdir(), "hm-alert-tickets-")); process.env.DATABASE_PATH = join(dir, "test.sqlite"); process.env.SESSION_DIR = join(dir, "sessions"); process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32); process.env.APP_BASE_URL = "https://hm.example.lan"; const svc = await import("../src/services/alertTickets.js"); const { qualifies, planTicketRun, buildTicket, buildSummaryTicket, runAlertTicketCheck, ticketsForAlerts, getAlertTicketStatus } = svc; const { createOsTicketTicketApi, hasTicketApi, ticketEndpoint, ticketUrl } = await import("../src/integrations/osticket/ticketApi.js"); const { getSettings, updateSettings, setInternalFlag } = await import("../src/services/settingsStore.js"); const { runMigrations } = await import("../src/db/migrate.js"); const { db } = await import("../src/db/client.js"); const tables = await import("../src/db/schema.js"); await runMigrations(); type Alert = import("../src/services/alertTypes.js").Alert; type Settings = import("../src/services/settingsStore.js").AlertTicketSettings; type Row = import("../src/services/alertTickets.js").TicketRow; type NewTicket = import("../src/integrations/osticket/ticketApi.js").NewTicket; const alert = (id: string, over: Partial = {}): Alert => ({ id, severity: "critical", category: "offline", source: "Server", message: `Problem ${id}`, link: "/servers/1", silenced: false, ...over }); const settings = (over: Partial = {}): Settings => ({ ...(structuredClone((require_defaults())) as Settings), enabled: true, integrationId: 1, requesterEmail: "hm@example.test", ...over }); function require_defaults(): Settings { return { enabled: false, integrationId: null, severities: ["critical", "warning"], categories: [], requesterName: "Homelab Manager", requesterEmail: "", topicId: null, priorityId: null, notifyStaff: true, existingProblems: "ignore", confirmChecks: 2, summaryAbove: 5, reopenAfterMinutes: 60 }; } const T0 = new Date("2026-10-07T10:00:00.000Z"); const at = (minutes: number) => new Date(T0.getTime() + minutes * 60_000); const row = (over: Partial): Row => ({ id: 1, alertKey: "a", status: "open", seenCount: 1, integrationId: 1, ticketNumber: "1001", grouped: false, severity: "critical", message: "m", firstSeenAt: T0.toISOString(), lastSeenAt: T0.toISOString(), ticketedAt: T0.toISOString(), clearedAt: null, ...over }); const plan = (over: Partial[0]> & { alerts: Alert[] }) => planTicketRun({ rows: [], settings: settings(), now: at(0), baseline: false, complete: true, ...over }); const kinds = (p: ReturnType) => p.ops.map((o) => o.kind); // ─── which alerts count ───────────────────────────────────────────────────── describe("which alerts open a ticket", () => { test("by severity and by kind", () => { const s = settings({ severities: ["critical"], categories: ["disk", "offline"] }); assert.equal(qualifies(alert("a", { severity: "critical", category: "disk" }), s), true); assert.equal(qualifies(alert("a", { severity: "warning", category: "disk" }), s), false, "warnings weren't asked for"); assert.equal(qualifies(alert("a", { severity: "critical", category: "backup" }), s), false, "backups weren't asked for"); assert.equal(qualifies(alert("a", { severity: "info", category: "disk" }), settings({ severities: ["critical", "warning", "info"] })), true); assert.equal(qualifies(alert("a", { category: "backup" }), settings({ categories: [] })), true, "no kinds chosen means every kind"); }); test("never one under a maintenance window", () => { assert.equal(qualifies(alert("a", { silenced: true }), settings()), false); }); test("never one about the ticketing system itself", () => { assert.equal(qualifies(alert("tickets:osticket:1", { category: "tickets" }), settings({ severities: ["critical", "warning", "info"] })), false, "overdue tickets"); assert.equal(qualifies(alert("integration:failing:osticket", { category: "integration" }), settings()), false, "osTicket failing: a ticket would go to the thing that is down"); assert.equal(qualifies(alert("integration:failing:proxmox", { category: "integration" }), settings()), true, "another integration failing is fair game"); }); }); // ─── the decision ─────────────────────────────────────────────────────────── describe("planTicketRun", () => { test("a new problem waits for a second check before it opens a ticket", () => { const p = plan({ alerts: [alert("a")] }); assert.deepEqual(kinds(p), ["insertPending"]); assert.equal(p.toTicket.length, 0); }); test("…and opens one at the second", () => { const p = plan({ alerts: [alert("a")], rows: [row({ alertKey: "a", status: "pending", ticketNumber: null, seenCount: 1 })] }); assert.equal(p.toTicket.length, 1); assert.equal(p.toTicket[0].row?.status, "pending"); }); test("a setting of 3 checks needs three", () => { const s = settings({ confirmChecks: 3 }); const second = plan({ alerts: [alert("a")], settings: s, rows: [row({ alertKey: "a", status: "pending", ticketNumber: null, seenCount: 1 })] }); assert.deepEqual(kinds(second), ["bump"]); const third = plan({ alerts: [alert("a")], settings: s, rows: [row({ alertKey: "a", status: "pending", ticketNumber: null, seenCount: 2 })] }); assert.equal(third.toTicket.length, 1); }); test("a setting of 1 opens at once", () => { const p = plan({ alerts: [alert("a")], settings: settings({ confirmChecks: 1 }) }); assert.equal(p.toTicket.length, 1); assert.equal(p.toTicket[0].row, null); assert.deepEqual(kinds(p), []); }); test("a blip that goes away before it lasted is forgotten, never ticketed", () => { const p = plan({ alerts: [], rows: [row({ alertKey: "a", status: "pending", ticketNumber: null })] }); assert.deepEqual(kinds(p), ["dropPending"]); assert.equal(p.toTicket.length, 0); }); test("a problem with a ticket that is still there is only noted", () => { const p = plan({ alerts: [alert("a")], rows: [row({ alertKey: "a" })] }); assert.deepEqual(kinds(p), ["touch"]); assert.equal(p.toTicket.length, 0, "a second ticket for the same problem"); }); test("a problem that is gone is marked cleared", () => { assert.deepEqual(kinds(plan({ alerts: [], rows: [row({ alertKey: "a" })] })), ["clear"]); }); test("when something couldn't be read, 'not in the list' is not taken to mean 'gone'", () => { const p = plan({ alerts: [], rows: [row({ alertKey: "a" }), row({ id: 2, alertKey: "b", status: "pending", ticketNumber: null })], complete: false }); assert.deepEqual(kinds(p), []); }); test("a problem that clears and comes straight back is the same problem", () => { const cleared = row({ alertKey: "a", clearedAt: at(-10).toISOString() }); const p = plan({ alerts: [alert("a")], rows: [cleared] }); assert.deepEqual(kinds(p), ["reactivate"]); assert.equal(p.toTicket.length, 0); }); test("one that comes back after the reopen window is a new occurrence", () => { const cleared = row({ alertKey: "a", clearedAt: at(-120).toISOString() }); assert.deepEqual(kinds(plan({ alerts: [alert("a")], rows: [cleared] })), ["insertPending"]); assert.equal(plan({ alerts: [alert("a")], rows: [cleared], settings: settings({ confirmChecks: 1 }) }).toTicket.length, 1); }); test("a reopen window of 0 makes every return a new occurrence", () => { const cleared = row({ alertKey: "a", clearedAt: at(-1).toISOString() }); assert.deepEqual(kinds(plan({ alerts: [alert("a")], rows: [cleared], settings: settings({ reopenAfterMinutes: 0 }) })), ["insertPending"]); }); test("a pending problem that is silenced for now waits without counting", () => { const p = plan({ alerts: [alert("a", { silenced: true })], rows: [row({ alertKey: "a", status: "pending", ticketNumber: null, seenCount: 1 })] }); assert.deepEqual(kinds(p), ["touch"]); assert.equal(p.toTicket.length, 0); }); test("the first check after switching on records what's already wrong and opens nothing", () => { const p = plan({ alerts: [alert("a"), alert("b", { severity: "info" })], baseline: true }); assert.deepEqual(kinds(p), ["insertBaseline"], "only what qualifies is recorded"); assert.equal(p.toTicket.length, 0); }); test("alerts that don't qualify leave no trace", () => { const p = plan({ alerts: [alert("a", { severity: "info" }), alert("b", { silenced: true })] }); assert.deepEqual(kinds(p), []); }); }); // ─── what the ticket says ─────────────────────────────────────────────────── describe("the ticket text", () => { test("a single ticket says what, where, since when and how to look further", () => { const t = buildTicket(alert("offline:server:3", { message: "Server nas has not reported for 3h", source: "Server", link: "/servers/3" }), "2026-10-07T10:05:00.000Z"); assert.equal(t.subject, "[Homelab] Critical: Server nas has not reported for 3h"); assert.match(t.message, /Severity: Critical/); assert.match(t.message, /Kind: Server down/); assert.match(t.message, /Source: Server/); assert.match(t.message, /First seen: 2026-10-07 10:05 UTC/); assert.match(t.message, /Details: https:\/\/hm\.example\.lan\/servers\/3/); assert.match(t.message, /https:\/\/hm\.example\.lan\/alerts/); assert.match(t.message, /alert offline:server:3/); assert.match(t.message, /not updated or closed automatically/); }); test("a very long message makes a subject osTicket will take", () => { assert.ok(buildTicket(alert("a", { message: "x ".repeat(500) }), T0.toISOString()).subject.length <= 200); }); test("a summary lists every alert", () => { const t = buildSummaryTicket([1, 2, 3].map((n) => ({ alert: alert(`a${n}`, { message: `Thing ${n} is down` }), firstSeenAt: T0.toISOString() }))); assert.equal(t.subject, "[Homelab] 3 problems detected"); for (const n of [1, 2, 3]) assert.match(t.message, new RegExp(`Thing ${n} is down`)); }); }); // ─── the osTicket API ─────────────────────────────────────────────────────── describe("osTicket API client", () => { type Seen = { method: string; url: string; headers: http.IncomingHttpHeaders; body: any }; let server: http.Server; let port = 0; let seen: Seen[] = []; let respond: (req: http.IncomingMessage, res: http.ServerResponse) => void = (_req, res) => res.writeHead(201).end("123456"); before(async () => { server = http.createServer((req, res) => { let raw = ""; req.on("data", (c) => (raw += c)); req.on("end", () => { let body: unknown = raw; try { body = JSON.parse(raw); } catch { // keep the text } seen.push({ method: req.method ?? "", url: req.url ?? "", headers: req.headers, body }); respond(req, res); }); }); await new Promise((r) => server.listen(0, "127.0.0.1", r)); port = (server.address() as { port: number }).port; }); after(() => server.close()); beforeEach(() => { seen = []; respond = (_req, res) => res.writeHead(201).end("123456"); }); const client = (over: Record = {}) => createOsTicketTicketApi({ apiUrl: `http://127.0.0.1:${port}/`, apiKey: "KEY-SECRET-123", ...over } as never); const ticket = (over: Partial = {}): NewTicket => ({ name: "Homelab Manager", email: "hm@example.test", subject: "S", message: "M", alertStaff: true, ...over }); test("posts JSON to api/tickets.json with the key in X-API-Key, and returns the ticket number", async () => { const r = await client().createTicket(ticket({ subject: "Disk full", message: "Line one\nLine two — åäö ✓" })); assert.equal(r.number, "123456"); const s = seen[0]; assert.equal(s.method, "POST"); assert.equal(s.url, "/api/tickets.json"); assert.equal(s.headers["x-api-key"], "KEY-SECRET-123"); assert.match(String(s.headers["content-type"]), /application\/json/); assert.equal(s.body.subject, "Disk full"); assert.equal(s.body.name, "Homelab Manager"); assert.equal(s.body.email, "hm@example.test"); assert.equal(s.body.source, "API"); assert.equal(s.body.alert, true); assert.equal(s.body.autorespond, false, "an acknowledgement to the app's own address would only bounce"); // osTicket reads a message's type from an RFC 2397 data URL. It must be base64: osTicket leaves percent-encoded text as it is, // which put "%20" in place of every space in a real ticket. assert.match(s.body.message, /^data:text\/plain;charset=utf-8;base64,[A-Za-z0-9+/=]+$/); assert.doesNotMatch(s.body.message, /%[0-9A-Fa-f]{2}/, "percent-encoding ends up in the ticket as literal text"); assert.equal(Buffer.from(s.body.message.replace(/^data:text\/plain;charset=utf-8;base64,/, ""), "base64").toString("utf8"), "Line one\nLine two — åäö ✓"); }); test("topic and priority are sent only when set; staff alerts can be switched off", async () => { await client().createTicket(ticket()); assert.equal("topicId" in seen[0].body, false); assert.equal("priority" in seen[0].body, false); await client().createTicket(ticket({ topicId: 12, priorityId: 3, alertStaff: false })); assert.equal(seen[1].body.topicId, 12); assert.equal(seen[1].body.priority, 3); assert.equal(seen[1].body.alert, false); }); test("works from an address with or without a trailing slash, or in a sub-folder", async () => { await client({ apiUrl: `http://127.0.0.1:${port}/support` }).createTicket(ticket()); await client({ apiUrl: `http://127.0.0.1:${port}/support/` }).createTicket(ticket()); assert.deepEqual(seen.map((s) => s.url), ["/support/api/tickets.json", "/support/api/tickets.json"]); assert.equal(ticketEndpoint("https://t.example.lan").href, "https://t.example.lan/api/tickets.json"); assert.throws(() => ticketEndpoint("ftp://t.example.lan"), /http/); }); test("understands the ways a ticket number can come back", async () => { for (const [body, expected] of [["123456", "123456"], ['"987654"', "987654"], [" 555\n", "555"], ["", null], ["{}", null]] as const) { respond = (_req, res) => res.writeHead(201).end(body); assert.equal((await client().createTicket(ticket())).number, expected, JSON.stringify(body)); } }); test("a refused key says what to check, and never repeats the key", async () => { respond = (_req, res) => res.writeHead(401).end("Valid API key required"); const err = await client().createTicket(ticket()).then(() => null, (e: Error) => e); assert.ok(err); assert.match(err.message, /refused the API key/); assert.match(err.message, /IP address/); assert.doesNotMatch(err.message, /KEY-SECRET-123/); respond = (_req, res) => res.writeHead(403).end(""); await assert.rejects(() => client().createTicket(ticket()), /refused the API key/); }); test("other failures are explained", async () => { respond = (_req, res) => res.writeHead(404).end("nope"); await assert.rejects(() => client().createTicket(ticket()), /no osTicket API at/i); respond = (_req, res) => res.writeHead(400).end("Unable to create new ticket: validation errors exist\n\u0000"); await assert.rejects(() => client().createTicket(ticket()), /rejected the ticket: Unable to create new ticket/); respond = (_req, res) => res.writeHead(500).end("boom"); await assert.rejects(() => client().createTicket(ticket()), /HTTP 500/); respond = (_req, res) => res.writeHead(301, { location: "https://tickets.example.lan/api/tickets.json" }).end(""); await assert.rejects(() => client().createTicket(ticket()), /redirected to https:\/\/tickets\.example\.lan/); }); test("missing setup is a clear error, and nothing is sent", async () => { await assert.rejects(() => createOsTicketTicketApi({ apiUrl: "", apiKey: "" } as never).createTicket(ticket()), /no ticket API address and key/); assert.equal(seen.length, 0); assert.equal(hasTicketApi({ apiUrl: "https://x", apiKey: "k" }), true); assert.equal(hasTicketApi({ apiUrl: "https://x" }), false); assert.equal(hasTicketApi({ apiKey: "k" }), false); assert.equal(hasTicketApi({ apiUrl: " ", apiKey: "k" }), false); }); test("an unreachable osTicket is an error, not a hang", async () => { await assert.rejects(() => createOsTicketTicketApi({ apiUrl: "http://127.0.0.1:1/", apiKey: "k" } as never).createTicket(ticket()), /ECONNREFUSED|connect/i); }); test("a link to the ticket in the staff panel", () => { assert.equal(ticketUrl("https://t.example.lan", "123456"), "https://t.example.lan/scp/tickets.php?number=123456"); assert.equal(ticketUrl("https://t.example.lan/support/", "98 7"), "https://t.example.lan/support/scp/tickets.php?number=98%207"); assert.equal(ticketUrl("not a url", "1"), null); }); }); // ─── the runner, over several checks ──────────────────────────────────────── describe("runAlertTicketCheck", () => { let sent: NewTicket[] = []; let failNext = 0; const create = async (t: NewTicket) => { if (failNext > 0) { failNext--; throw new Error("osTicket refused the API key."); } sent.push(t); return { number: String(1000 + sent.length) }; }; const report = (alerts: Alert[], incomplete = false) => ({ alerts, counts: { critical: 0, warning: 0, info: 0, silenced: 0 }, couldntCheck: incomplete ? [{ name: "Proxmox", error: "down", affects: ["backup"] }] : [], notes: [], generatedAt: T0.toISOString(), cached: false, }); const check = (minutes: number, alerts: Alert[], opts: { incomplete?: boolean } = {}) => runAlertTicketCheck({ deps: { getReport: async () => report(alerts, opts.incomplete), createTicket: create, now: () => at(minutes) } }); const rows = () => db.select().from(tables.alertTickets); let osTicketId = 0; const configure = (over: Partial = {}) => updateSettings({ alertTickets: { ...settings(), integrationId: osTicketId, existingProblems: "ticket", ...over } }); before(async () => { // The rows the runner writes point at an integration, so there has to be one. await db.delete(tables.integrations); osTicketId = (await db.insert(tables.integrations).values({ type: "osticket", name: "osT", baseUrl: "", config: "{}" }).returning())[0].id; }); beforeEach(async () => { sent = []; failNext = 0; await db.delete(tables.alertTickets); await db.delete(tables.auditLog); await setInternalFlag("alertTicketsBaselineDone", ""); await setInternalFlag("alertTicketsLastRun", ""); await configure(); }); test("does nothing while switched off", async () => { await configure({ enabled: false }); const r = await check(0, [alert("a")]); assert.equal(r.skipped, "disabled"); assert.equal(sent.length, 0); assert.equal((await rows()).length, 0); }); test("one ticket for a problem that lasts, however many checks see it", async () => { assert.equal((await check(0, [alert("a")])).ticketsOpened, 0); assert.equal((await rows())[0].status, "pending"); const second = await check(15, [alert("a")]); assert.equal(second.ticketsOpened, 1); for (const m of [30, 45, 60, 75]) assert.equal((await check(m, [alert("a")])).ticketsOpened, 0); assert.equal(sent.length, 1, "more than one ticket for one problem"); const [only] = await rows(); assert.equal(only.status, "open"); assert.equal(only.ticketNumber, "1001"); assert.equal(only.ticketedAt, at(15).toISOString()); }); test("the ticket carries the settings and the alert's text", async () => { await configure({ requesterName: "HM", requesterEmail: "alerts@example.test", topicId: 4, priorityId: 2, notifyStaff: false }); await check(0, [alert("a", { message: "Disk / on nas is 97% full" })]); await check(15, [alert("a", { message: "Disk / on nas is 97% full" })]); assert.equal(sent.length, 1); assert.equal(sent[0].name, "HM"); assert.equal(sent[0].email, "alerts@example.test"); assert.equal(sent[0].topicId, 4); assert.equal(sent[0].priorityId, 2); assert.equal(sent[0].alertStaff, false); assert.match(sent[0].subject, /Disk \/ on nas is 97% full/); assert.match(sent[0].message, /First seen: 2026-10-07 10:00 UTC/, "the time it was first seen, not the time of the second check"); }); test("a blip that fixes itself never opens one", async () => { await check(0, [alert("a")]); await check(15, []); await check(30, [alert("a")]); await check(45, []); assert.equal(sent.length, 0); assert.equal((await rows()).length, 0); }); test("a problem that clears and returns quickly is the same ticket; much later it is a new one", async () => { await check(0, [alert("a")]); await check(15, [alert("a")]); assert.equal(sent.length, 1); await check(30, []); assert.ok((await rows())[0].clearedAt, "should be marked cleared"); await check(45, [alert("a")]); // back within the hour assert.equal(sent.length, 1, "a flap opened a second ticket"); assert.equal((await rows())[0].clearedAt, null); await check(60, []); await check(200, [alert("a")]); // back much later: pending again… assert.equal(sent.length, 1); await check(215, [alert("a")]); // …and now a new ticket assert.equal(sent.length, 2); assert.equal((await rows()).length, 2, "one row per occurrence"); }); test("something under a maintenance window gets no ticket, and gets one if it is still there after", async () => { await check(0, [alert("a", { silenced: true })]); await check(15, [alert("a", { silenced: true })]); assert.equal(sent.length, 0); assert.equal((await rows()).length, 0); await check(30, [alert("a")]); await check(45, [alert("a")]); assert.equal(sent.length, 1); }); test("when something couldn't be read, an open problem isn't called cleared", async () => { await check(0, [alert("a")]); await check(15, [alert("a")]); await check(30, [], { incomplete: true }); assert.equal((await rows())[0].clearedAt, null); await check(45, [], {}); assert.ok((await rows())[0].clearedAt); }); test("many new problems at once become one summary ticket", async () => { const many = Array.from({ length: 8 }, (_, i) => alert(`a${i}`)); await check(0, many); const r = await check(15, many); assert.equal(sent.length, 1, "should be a single ticket"); assert.equal(r.ticketsOpened, 1); assert.equal(r.alertsCovered, 8); assert.match(sent[0].subject, /8 problems detected/); for (let i = 0; i < 8; i++) assert.match(sent[0].message, new RegExp(`Problem a${i}`)); const all = await rows(); assert.equal(all.length, 8); assert.ok(all.every((x) => x.status === "open" && x.grouped && x.ticketNumber === "1001")); assert.equal((await check(30, many)).ticketsOpened, 0, "the covered alerts open nothing more"); }); test("a few at once each get their own", async () => { const few = [alert("a"), alert("b"), alert("c")]; await check(0, few); await check(15, few); assert.equal(sent.length, 3); assert.ok((await rows()).every((x) => !x.grouped)); assert.deepEqual(new Set((await rows()).map((x) => x.ticketNumber)).size, 3); }); test("a ticket that couldn't be opened is tried again at the next check, and nothing is claimed meanwhile", async () => { await check(0, [alert("a")]); failNext = 1; const r = await check(15, [alert("a")]); assert.equal(r.failed, 1); assert.match(r.error ?? "", /refused the API key/); assert.equal((await rows())[0].status, "pending"); assert.equal(sent.length, 0); const again = await check(30, [alert("a")]); assert.equal(again.ticketsOpened, 1); assert.equal(sent.length, 1); }); test("problems already there when it is switched on get no ticket (unless asked), but a new one does", async () => { await configure({ existingProblems: "ignore" }); const first = await check(0, [alert("old")]); assert.equal(first.baseline, 1); assert.equal((await rows())[0].status, "baseline"); await check(15, [alert("old")]); await check(30, [alert("old"), alert("new")]); await check(45, [alert("old"), alert("new")]); assert.equal(sent.length, 1); assert.match(sent[0].subject, /Problem new/); assert.equal(sent.some((t) => /Problem old/.test(t.subject)), false); }); test("a baseline problem that clears and later returns is a new problem", async () => { await configure({ existingProblems: "ignore" }); await check(0, [alert("old")]); await check(15, []); await check(200, [alert("old")]); await check(215, [alert("old")]); assert.equal(sent.length, 1); }); test("switching it off and on again starts from a new baseline", async () => { await configure({ existingProblems: "ignore" }); await check(0, [alert("old")]); await configure({ enabled: false, existingProblems: "ignore" }); await check(15, [alert("old")]); await configure({ enabled: true, existingProblems: "ignore" }); await db.delete(tables.alertTickets); const r = await check(30, [alert("old")]); assert.equal(r.baseline, 1, "should record the baseline again"); assert.equal(sent.length, 0); }); test("the baseline isn't called complete while a source couldn't be read", async () => { await configure({ existingProblems: "ignore" }); await check(0, [alert("old")], { incomplete: true }); assert.equal((await getAlertTicketStatus()).baselinePending, true); await check(15, [alert("old")]); assert.equal((await getAlertTicketStatus()).baselinePending, false); }); test("it never opens a ticket about osTicket", async () => { const own = [alert("integration:failing:osticket", { category: "integration" }), alert("tickets:osticket:1", { category: "tickets" })]; await check(0, own); await check(15, own); assert.equal(sent.length, 0); }); test("each ticket is in the audit log, with the ticket number and no secrets", async () => { await check(0, [alert("a")]); await check(15, [alert("a")]); const entries = (await db.select().from(tables.auditLog)).filter((e) => e.category === "alert_ticket"); assert.equal(entries.length, 1); assert.equal(entries[0].action, "create"); assert.equal(entries[0].targetId, "a"); assert.equal(JSON.parse(entries[0].detail!).ticket, "1001"); assert.equal(entries[0].actorLabel, "system"); }); test("it reports missing setup instead of failing silently", async () => { await configure({ integrationId: null }); const r = await runAlertTicketCheck({ deps: { getReport: async () => report([alert("a")]), now: () => at(0) } }); assert.match(r.error ?? "", /No osTicket integration is chosen/); await configure({ integrationId: 999 }); assert.match((await runAlertTicketCheck({ deps: { getReport: async () => report([]), now: () => at(0) } })).error ?? "", /no longer exists/); }); test("the status says how many are open, waiting and baselined", async () => { await configure({ existingProblems: "ignore" }); await check(0, [alert("old")]); await check(15, [alert("old"), alert("a")]); await check(30, [alert("old"), alert("a")]); const s = await getAlertTicketStatus(); assert.equal(s.baseline, 1); assert.equal(s.open, 1); assert.equal(s.pending, 0); assert.equal(s.lastRun?.ticketsOpened, 1); }); test("old cleared records are removed, recent ones kept", async () => { const old = new Date(T0.getTime() - 200 * 86_400_000).toISOString(); await db.insert(tables.alertTickets).values({ alertKey: "ancient", status: "open", severity: "critical", message: "m", firstSeenAt: old, lastSeenAt: old, clearedAt: old }); await db.insert(tables.alertTickets).values({ alertKey: "recent", status: "open", severity: "critical", message: "m", firstSeenAt: T0.toISOString(), lastSeenAt: T0.toISOString(), clearedAt: T0.toISOString() }); await check(0, []); assert.deepEqual((await rows()).map((r) => r.alertKey), ["recent"]); }); test("ticketsForAlerts links an active ticket to osTicket's staff panel", async () => { await db.delete(tables.integrations); const [integration] = await db.insert(tables.integrations).values({ type: "osticket", name: "osT", baseUrl: "", config: JSON.stringify({ apiUrl: "https://tickets.example.lan/" }) }).returning(); await db.insert(tables.alertTickets).values([ { alertKey: "a", status: "open", ticketNumber: "4321", integrationId: integration.id, severity: "critical", message: "m", firstSeenAt: T0.toISOString(), lastSeenAt: T0.toISOString(), ticketedAt: T0.toISOString() }, { alertKey: "b", status: "pending", integrationId: integration.id, severity: "critical", message: "m", firstSeenAt: T0.toISOString(), lastSeenAt: T0.toISOString() }, { alertKey: "c", status: "open", ticketNumber: "1", integrationId: integration.id, severity: "critical", message: "m", firstSeenAt: T0.toISOString(), lastSeenAt: T0.toISOString(), clearedAt: T0.toISOString() }, ]); const found = await ticketsForAlerts(["a", "b", "c", "d"]); assert.deepEqual([...found.keys()], ["a"], "only a ticketed, still-active problem shows one"); assert.equal(found.get("a")!.number, "4321"); assert.equal(found.get("a")!.url, "https://tickets.example.lan/scp/tickets.php?number=4321"); assert.equal((await ticketsForAlerts([])).size, 0); }); }); // ─── the settings and routes ──────────────────────────────────────────────── describe("admin routes", () => { let appServer: http.Server; let appPort = 0; let fake: http.Server; let fakePort = 0; let fakeResponse: (res: http.ServerResponse) => void = (res) => res.writeHead(201).end("424242"); const fakeSeen: { key?: string; body: any }[] = []; let admin = ""; let operator = ""; let viewer = ""; let integrationId = 0; let plainIntegrationId = 0; let last = { status: 0, text: "" }; function send(cookie: string | undefined, method: string, path: string, body?: object): Promise { return new Promise((resolve, reject) => { const payload = body ? JSON.stringify(body) : undefined; const headers: Record = {}; if (cookie) headers.cookie = cookie; if (payload) { headers["content-type"] = "application/json"; headers["content-length"] = String(Buffer.byteLength(payload)); } const req = http.request({ host: "127.0.0.1", port: appPort, method, path, headers }, (res) => { let text = ""; res.on("data", (c) => (text += c)); res.on("end", () => { last = { status: res.statusCode ?? 0, text }; resolve(res.statusCode ?? 0); }); }); req.on("error", reject); if (payload) req.write(payload); req.end(); }); } const json = () => JSON.parse(last.text); before(async () => { const express = (await import("express")).default; const session = (await import("express-session")).default; const { alertTicketsRouter } = await import("../src/routes/alertTickets.js"); const { integrationsRouter } = await import("../src/routes/integrations.js"); fake = http.createServer((req, res) => { let raw = ""; req.on("data", (c) => (raw += c)); req.on("end", () => { fakeSeen.push({ key: req.headers["x-api-key"] as string | undefined, body: JSON.parse(raw || "{}") }); fakeResponse(res); }); }); await new Promise((r) => fake.listen(0, "127.0.0.1", r)); fakePort = (fake.address() as { port: number }).port; await db.delete(tables.integrations); await db.delete(tables.users); await db.insert(tables.users).values([ { oidcSub: "ad", email: "ad@x", name: "Admin", role: "admin" }, { oidcSub: "op", email: "op@x", name: "Operator", role: "operator" }, { oidcSub: "vw", email: "vw@x", name: "Viewer", role: "viewer" }, ]); const app = express(); app.use(express.json()); app.use(session({ secret: "t", resave: false, saveUninitialized: true })); app.post("/login/:sub", (req, res) => { req.session.user = { sub: req.params.sub } as never; res.json({}); }); app.use("/api/alert-tickets", alertTicketsRouter); app.use("/api/integrations", integrationsRouter); appServer = app.listen(0); appPort = (appServer.address() as { port: number }).port; const login = async (sub: string) => ((await fetch(`http://127.0.0.1:${appPort}/login/${sub}`, { method: "POST" })).headers.get("set-cookie") as string).split(";")[0]; admin = await login("ad"); operator = await login("op"); viewer = await login("vw"); // Two osTicket integrations, made through the real route: one with the ticket API filled in, one without. const db_ = { host: "db.example.lan", database: "osticket", username: "ro", password: "pw" }; assert.equal(await send(admin, "POST", "/api/integrations", { type: "osticket", name: "osTicket (API)", config: { ...db_, apiUrl: `http://127.0.0.1:${fakePort}/`, apiKey: "THE-API-KEY" } }), 201, last.text); integrationId = json().integration.id; assert.equal(await send(admin, "POST", "/api/integrations", { type: "osticket", name: "osTicket (read-only)", config: db_ }), 201, "the ticket API fields must stay optional"); plainIntegrationId = json().integration.id; }); after(() => { appServer?.close(); fake?.close(); try { rmSync(dir, { recursive: true, force: true }); } catch { // Windows keeps the SQLite file locked until the process exits. } }); beforeEach(async () => { fakeSeen.length = 0; fakeResponse = (res) => res.writeHead(201).end("424242"); await db.delete(tables.auditLog); await updateSettings({ alertTickets: require_defaults() }); }); test("only an administrator can read or change any of it", async () => { for (const [cookie, label] of [[undefined, "signed out"], [viewer, "viewer"], [operator, "operator"]] as const) { const want = cookie ? 403 : 401; assert.equal(await send(cookie, "GET", "/api/alert-tickets"), want, `GET as ${label}`); assert.equal(await send(cookie, "PUT", "/api/alert-tickets", { enabled: false }), want, `PUT as ${label}`); assert.equal(await send(cookie, "POST", "/api/alert-tickets/test"), want, `test as ${label}`); assert.equal(await send(cookie, "POST", "/api/alert-tickets/run"), want, `run as ${label}`); } assert.equal(fakeSeen.length, 0, "a ticket was opened for someone who may not"); }); test("the overview lists the osTicket integrations and whether each can open tickets", async () => { assert.equal(await send(admin, "GET", "/api/alert-tickets"), 200); const o = json(); assert.equal(o.settings.enabled, false); assert.deepEqual(o.integrations.map((i: { name: string; ticketApiReady: boolean }) => [i.name, i.ticketApiReady]).sort(), [["osTicket (API)", true], ["osTicket (read-only)", false]]); assert.ok(o.categories.length >= 8); assert.equal(o.categories.some((c: { value: string }) => c.value === "tickets"), false, "tickets about tickets aren't offered"); assert.doesNotMatch(last.text, /THE-API-KEY/, "the API key must never be sent to the browser"); }); test("it can't be switched on without what it needs", async () => { const complete = { enabled: true, integrationId, requesterEmail: "hm@example.test" }; assert.equal(await send(admin, "PUT", "/api/alert-tickets", { enabled: true }), 400); assert.match(json().message, /Choose which osTicket integration/); assert.equal(await send(admin, "PUT", "/api/alert-tickets", { ...complete, integrationId: plainIntegrationId }), 400); assert.match(json().message, /no ticket API address and key/); assert.equal(await send(admin, "PUT", "/api/alert-tickets", { ...complete, integrationId: 9999 }), 400); assert.equal(await send(admin, "PUT", "/api/alert-tickets", { ...complete, requesterEmail: "" }), 400); assert.match(json().message, /email/i); assert.equal(await send(admin, "PUT", "/api/alert-tickets", { ...complete, severities: [] }), 400); assert.match(json().message, /severity/i); assert.equal((await getSettings()).alertTickets.enabled, false, "a refused change must change nothing"); assert.equal(await send(admin, "PUT", "/api/alert-tickets", complete), 200, last.text); assert.equal((await getSettings()).alertTickets.enabled, true); }); test("values are checked", async () => { for (const bad of [{ requesterEmail: "not an email" }, { confirmChecks: 0 }, { confirmChecks: 11 }, { summaryAbove: 0 }, { reopenAfterMinutes: -1 }, { severities: ["urgent"] }, { categories: ["tickets"] }, { topicId: 0 }, { existingProblems: "maybe" }]) { assert.equal(await send(admin, "PUT", "/api/alert-tickets", bad), 400, JSON.stringify(bad)); } assert.equal(await send(admin, "PUT", "/api/alert-tickets", { confirmChecks: 1, summaryAbove: 3, reopenAfterMinutes: 0, topicId: 7, priorityId: null, categories: ["disk", "offline"], severities: ["critical"] }), 200, last.text); const s = (await getSettings()).alertTickets; assert.deepEqual([s.confirmChecks, s.summaryAbove, s.reopenAfterMinutes, s.topicId, s.priorityId, s.categories, s.severities], [1, 3, 0, 7, null, ["disk", "offline"], ["critical"]]); }); test("a change is in the audit log, with what changed", async () => { await send(admin, "PUT", "/api/alert-tickets", { enabled: true, integrationId, requesterEmail: "hm@example.test", confirmChecks: 3 }); const entry = (await db.select().from(tables.auditLog)).find((e) => e.action === "update_alert_tickets"); assert.ok(entry); const changes = JSON.parse(entry.detail!).changes; assert.deepEqual(changes.confirmChecks, { from: 2, to: 3 }); assert.deepEqual(changes.enabled, { from: false, to: true }); assert.doesNotMatch(entry.detail!, /THE-API-KEY/); }); test("the test ticket reaches osTicket with the key, and says it's a test", async () => { await send(admin, "PUT", "/api/alert-tickets", { enabled: true, integrationId, requesterEmail: "hm@example.test", requesterName: "HM", topicId: 5 }); assert.equal(await send(admin, "POST", "/api/alert-tickets/test"), 200, last.text); assert.equal(json().ticketNumber, "424242"); assert.equal(fakeSeen.length, 1); assert.equal(fakeSeen[0].key, "THE-API-KEY"); assert.match(fakeSeen[0].body.subject, /Test ticket/); assert.equal(fakeSeen[0].body.topicId, 5); assert.equal(fakeSeen[0].body.email, "hm@example.test"); assert.ok((await db.select().from(tables.auditLog)).some((e) => e.category === "alert_ticket" && e.action === "test")); }); test("a refused key shows up as a readable failure on the test ticket", async () => { await send(admin, "PUT", "/api/alert-tickets", { enabled: true, integrationId, requesterEmail: "hm@example.test" }); fakeResponse = (res) => res.writeHead(401).end("Valid API key required"); assert.equal(await send(admin, "POST", "/api/alert-tickets/test"), 502); assert.match(json().message, /refused the API key/); assert.doesNotMatch(last.text, /THE-API-KEY/); }); test("a test ticket needs the setup too", async () => { assert.equal(await send(admin, "POST", "/api/alert-tickets/test"), 502); assert.match(json().message, /No osTicket integration is chosen/); }); test("'check now' on a switched-off feature does nothing", async () => { assert.equal(await send(admin, "POST", "/api/alert-tickets/run"), 200); assert.equal(json().summary.skipped, "disabled"); assert.equal(fakeSeen.length, 0); }); }); describe("osTicket integration fields", () => { test("the ticket API settings are optional, the key is secret, and the certificate option is a checkbox", async () => { const { INTEGRATION_FIELDS, validateIntegrationConfig, splitIntegrationConfig } = await import("../src/integrations/fieldSchemas.js"); const fields = INTEGRATION_FIELDS.osticket!; const byKey = Object.fromEntries(fields.map((f) => [f.key, f])); assert.equal(byKey.apiUrl.optional, true); assert.equal(byKey.apiKey.optional, true); assert.equal(byKey.apiKey.secret, true); assert.equal(byKey.apiInsecure.type, "checkbox"); const db_ = { host: "h", database: "d", username: "u", password: "p" }; assert.deepEqual(validateIntegrationConfig("osticket", db_), [], "an integration with only the database fields is still valid"); const split = splitIntegrationConfig("osticket", { ...db_, apiUrl: "https://t", apiKey: "k", apiInsecure: true }); assert.deepEqual(Object.keys(split.secretFields).sort(), ["apiKey", "password"]); assert.ok("apiUrl" in split.nonSecretFields && !("apiKey" in split.nonSecretFields)); }); });